Release 6.23a
[org-mode.git] / lisp / org.el
blobc6daa35adcada400a46fc85dba0c005893fc9f87
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, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.23a
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-footnote)
93 ;;;; Customization variables
95 ;;; Version
97 (defconst org-version "6.23a"
98 "The version number of the file org.el.")
100 (defun org-version (&optional here)
101 "Show the org-mode version in the echo area.
102 With prefix arg HERE, insert it at point."
103 (interactive "P")
104 (let ((version (format "Org-mode version %s" org-version)))
105 (message version)
106 (if here
107 (insert version))))
109 ;;; Compatibility constants
111 ;;; The custom variables
113 (defgroup org nil
114 "Outline-based notes management and organizer."
115 :tag "Org"
116 :group 'outlines
117 :group 'hypermedia
118 :group 'calendar)
120 (defcustom org-load-hook nil
121 "Hook that is run after org.el has been loaded."
122 :group 'org
123 :type 'hook)
125 (defvar org-modules) ; defined below
126 (defvar org-modules-loaded nil
127 "Have the modules been loaded already?")
129 (defun org-load-modules-maybe (&optional force)
130 "Load all extensions listed in `org-modules'."
131 (when (or force (not org-modules-loaded))
132 (mapc (lambda (ext)
133 (condition-case nil (require ext)
134 (error (message "Problems while trying to load feature `%s'" ext))))
135 org-modules)
136 (setq org-modules-loaded t)))
138 (defun org-set-modules (var value)
139 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
140 (set var value)
141 (when (featurep 'org)
142 (org-load-modules-maybe 'force)))
144 (when (org-bound-and-true-p org-modules)
145 (let ((a (member 'org-infojs org-modules)))
146 (and a (setcar a 'org-jsinfo))))
148 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
149 "Modules that should always be loaded together with org.el.
150 If a description starts with <C>, the file is not part of Emacs
151 and loading it will require that you have downloaded and properly installed
152 the org-mode distribution.
154 You can also use this system to load external packages (i.e. neither Org
155 core modules, not modules from the CONTRIB directory). Just add symbols
156 to the end of the list. If the package is called org-xyz.el, then you need
157 to add the symbol `xyz', and the package must have a call to
159 (provide 'org-xyz)"
160 :group 'org
161 :set 'org-set-modules
162 :type
163 '(set :greedy t
164 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
165 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
166 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
167 (const :tag " id: Global IDs for identifying entries" org-id)
168 (const :tag " info: Links to Info nodes" org-info)
169 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
170 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
171 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
172 (const :tag " mew Links to Mew folders/messages" org-mew)
173 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
174 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
175 (const :tag " vm: Links to VM folders/messages" org-vm)
176 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
177 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
178 (const :tag " mouse: Additional mouse support" org-mouse)
180 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
181 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
182 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
183 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
184 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
185 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
186 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
187 (const :tag "C eval: Include command output as text" org-eval)
188 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
189 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
190 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
191 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
192 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
193 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
194 (const :tag "C mtags: Support for muse-like tags" org-mtags)
195 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
196 (const :tag "C R: Computation using the R language" org-R)
197 (const :tag "C registry: A registry for Org links" org-registry)
198 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
199 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
200 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
201 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
202 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
204 (defcustom org-support-shift-select nil
205 "Non-nil means, make shift-cursor commands select text when possible.
207 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
208 selecting a region, or enlarge thusly regions started in this way.
209 In Org-mode, in special contexts, these same keys are used for other
210 purposes, important enough to compete with shift selection. Org tries
211 to balance these needs by supporting `shift-select-mode' outside these
212 special contexts, under control of this variable.
214 The default of this variable is nil, to avoid confusing behavior. Shifted
215 cursor keys will then execute Org commands in the following contexts:
216 - on a headline, changing TODO state (left/right) and priority (up/down)
217 - on a time stamp, changing the time
218 - in a plain list item, changing the bullet type
219 - in a property definition line, switching between allowed values
220 - in the BEGIN line of a clock table (changing the time block).
221 Outside these contexts, the commands will throw an error.
223 When this variable is t and the cursor is not in a special context,
224 Org-mode will support shift-selection for making and enlarging regions.
225 To make this more effective, the bullet cycling will no longer happen
226 anywhere in an item line, but only if the cursor is exactly on the bullet.
228 If you set this variable to the symbol `always', then the keys
229 will not be special in headlines, property lines, and item lines, to make
230 shift selection work there as well. If this is what you want, you can
231 use the following alternative commands: `C-c C-t' and `C-c ,' to
232 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
233 TODO sets, `C-c -' to cycle item bullet types, and properties can be
234 edited by hand or in column view.
236 However, when the cursor is on a timestamp, shift-cursor commands
237 will still edit the time stamp - this is just too good to give up.
239 XEmacs user should have this variable set to nil, because shift-select-mode
240 is Emacs 23 only."
241 :group 'org
242 :type '(choice
243 (const :tag "Never" nil)
244 (const :tag "When outside special context" t)
245 (const :tag "Everywhere except timestamps" always)))
247 (defgroup org-startup nil
248 "Options concerning startup of Org-mode."
249 :tag "Org Startup"
250 :group 'org)
252 (defcustom org-startup-folded t
253 "Non-nil means, entering Org-mode will switch to OVERVIEW.
254 This can also be configured on a per-file basis by adding one of
255 the following lines anywhere in the buffer:
257 #+STARTUP: fold
258 #+STARTUP: nofold
259 #+STARTUP: content"
260 :group 'org-startup
261 :type '(choice
262 (const :tag "nofold: show all" nil)
263 (const :tag "fold: overview" t)
264 (const :tag "content: all headlines" content)))
266 (defcustom org-startup-truncated t
267 "Non-nil means, entering Org-mode will set `truncate-lines'.
268 This is useful since some lines containing links can be very long and
269 uninteresting. Also tables look terrible when wrapped."
270 :group 'org-startup
271 :type 'boolean)
273 (defcustom org-startup-align-all-tables nil
274 "Non-nil means, align all tables when visiting a file.
275 This is useful when the column width in tables is forced with <N> cookies
276 in table fields. Such tables will look correct only after the first re-align.
277 This can also be configured on a per-file basis by adding one of
278 the following lines anywhere in the buffer:
279 #+STARTUP: align
280 #+STARTUP: noalign"
281 :group 'org-startup
282 :type 'boolean)
284 (defcustom org-insert-mode-line-in-empty-file nil
285 "Non-nil means insert the first line setting Org-mode in empty files.
286 When the function `org-mode' is called interactively in an empty file, this
287 normally means that the file name does not automatically trigger Org-mode.
288 To ensure that the file will always be in Org-mode in the future, a
289 line enforcing Org-mode will be inserted into the buffer, if this option
290 has been set."
291 :group 'org-startup
292 :type 'boolean)
294 (defcustom org-replace-disputed-keys nil
295 "Non-nil means use alternative key bindings for some keys.
296 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
297 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
298 If you want to use Org-mode together with one of these other modes,
299 or more generally if you would like to move some Org-mode commands to
300 other keys, set this variable and configure the keys with the variable
301 `org-disputed-keys'.
303 This option is only relevant at load-time of Org-mode, and must be set
304 *before* org.el is loaded. Changing it requires a restart of Emacs to
305 become effective."
306 :group 'org-startup
307 :type 'boolean)
309 (defcustom org-use-extra-keys nil
310 "Non-nil means use extra key sequence definitions for certain
311 commands. This happens automatically if you run XEmacs or if
312 window-system is nil. This variable lets you do the same
313 manually. You must set it before loading org.
315 Example: on Carbon Emacs 22 running graphically, with an external
316 keyboard on a Powerbook, the default way of setting M-left might
317 not work for either Alt or ESC. Setting this variable will make
318 it work for ESC."
319 :group 'org-startup
320 :type 'boolean)
322 (if (fboundp 'defvaralias)
323 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
325 (defcustom org-disputed-keys
326 '(([(shift up)] . [(meta p)])
327 ([(shift down)] . [(meta n)])
328 ([(shift left)] . [(meta -)])
329 ([(shift right)] . [(meta +)])
330 ([(control shift right)] . [(meta shift +)])
331 ([(control shift left)] . [(meta shift -)]))
332 "Keys for which Org-mode and other modes compete.
333 This is an alist, cars are the default keys, second element specifies
334 the alternative to use when `org-replace-disputed-keys' is t.
336 Keys can be specified in any syntax supported by `define-key'.
337 The value of this option takes effect only at Org-mode's startup,
338 therefore you'll have to restart Emacs to apply it after changing."
339 :group 'org-startup
340 :type 'alist)
342 (defun org-key (key)
343 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
344 Or return the original if not disputed."
345 (if org-replace-disputed-keys
346 (let* ((nkey (key-description key))
347 (x (org-find-if (lambda (x)
348 (equal (key-description (car x)) nkey))
349 org-disputed-keys)))
350 (if x (cdr x) key))
351 key))
353 (defun org-find-if (predicate seq)
354 (catch 'exit
355 (while seq
356 (if (funcall predicate (car seq))
357 (throw 'exit (car seq))
358 (pop seq)))))
360 (defun org-defkey (keymap key def)
361 "Define a key, possibly translated, as returned by `org-key'."
362 (define-key keymap (org-key key) def))
364 (defcustom org-ellipsis nil
365 "The ellipsis to use in the Org-mode outline.
366 When nil, just use the standard three dots. When a string, use that instead,
367 When a face, use the standard 3 dots, but with the specified face.
368 The change affects only Org-mode (which will then use its own display table).
369 Changing this requires executing `M-x org-mode' in a buffer to become
370 effective."
371 :group 'org-startup
372 :type '(choice (const :tag "Default" nil)
373 (face :tag "Face" :value org-warning)
374 (string :tag "String" :value "...#")))
376 (defvar org-display-table nil
377 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
379 (defgroup org-keywords nil
380 "Keywords in Org-mode."
381 :tag "Org Keywords"
382 :group 'org)
384 (defcustom org-deadline-string "DEADLINE:"
385 "String to mark deadline entries.
386 A deadline is this string, followed by a time stamp. Should be a word,
387 terminated by a colon. You can insert a schedule keyword and
388 a timestamp with \\[org-deadline].
389 Changes become only effective after restarting Emacs."
390 :group 'org-keywords
391 :type 'string)
393 (defcustom org-scheduled-string "SCHEDULED:"
394 "String to mark scheduled TODO entries.
395 A schedule is this string, followed by a time stamp. Should be a word,
396 terminated by a colon. You can insert a schedule keyword and
397 a timestamp with \\[org-schedule].
398 Changes become only effective after restarting Emacs."
399 :group 'org-keywords
400 :type 'string)
402 (defcustom org-closed-string "CLOSED:"
403 "String used as the prefix for timestamps logging closing a TODO entry."
404 :group 'org-keywords
405 :type 'string)
407 (defcustom org-clock-string "CLOCK:"
408 "String used as prefix for timestamps clocking work hours on an item."
409 :group 'org-keywords
410 :type 'string)
412 (defcustom org-comment-string "COMMENT"
413 "Entries starting with this keyword will never be exported.
414 An entry can be toggled between COMMENT and normal with
415 \\[org-toggle-comment].
416 Changes become only effective after restarting Emacs."
417 :group 'org-keywords
418 :type 'string)
420 (defcustom org-quote-string "QUOTE"
421 "Entries starting with this keyword will be exported in fixed-width font.
422 Quoting applies only to the text in the entry following the headline, and does
423 not extend beyond the next headline, even if that is lower level.
424 An entry can be toggled between QUOTE and normal with
425 \\[org-toggle-fixed-width-section]."
426 :group 'org-keywords
427 :type 'string)
429 (defconst org-repeat-re
430 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
431 "Regular expression for specifying repeated events.
432 After a match, group 1 contains the repeat expression.")
434 (defgroup org-structure nil
435 "Options concerning the general structure of Org-mode files."
436 :tag "Org Structure"
437 :group 'org)
439 (defgroup org-reveal-location nil
440 "Options about how to make context of a location visible."
441 :tag "Org Reveal Location"
442 :group 'org-structure)
444 (defconst org-context-choice
445 '(choice
446 (const :tag "Always" t)
447 (const :tag "Never" nil)
448 (repeat :greedy t :tag "Individual contexts"
449 (cons
450 (choice :tag "Context"
451 (const agenda)
452 (const org-goto)
453 (const occur-tree)
454 (const tags-tree)
455 (const link-search)
456 (const mark-goto)
457 (const bookmark-jump)
458 (const isearch)
459 (const default))
460 (boolean))))
461 "Contexts for the reveal options.")
463 (defcustom org-show-hierarchy-above '((default . t))
464 "Non-nil means, show full hierarchy 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 hierarchy of headings
467 above the exposed location is shown.
468 Turning this off for example for sparse trees makes them very compact.
469 Instead of t, this can also be an alist specifying this option for different
470 contexts. Valid contexts are
471 agenda when exposing an entry from the agenda
472 org-goto when using the command `org-goto' on key C-c C-j
473 occur-tree when using the command `org-occur' on key C-c /
474 tags-tree when constructing a sparse tree based on tags matches
475 link-search when exposing search matches associated with a link
476 mark-goto when exposing the jump goal of a mark
477 bookmark-jump when exposing a bookmark location
478 isearch when exiting from an incremental search
479 default default for all contexts not set explicitly"
480 :group 'org-reveal-location
481 :type org-context-choice)
483 (defcustom org-show-following-heading '((default . nil))
484 "Non-nil means, show following heading when revealing a location.
485 Org-mode often shows locations in an org-mode file which might have
486 been invisible before. When this is set, the heading following the
487 match is shown.
488 Turning this off for example for sparse trees makes them very compact,
489 but makes it harder to edit the location of the match. In such a case,
490 use the command \\[org-reveal] to show more context.
491 Instead of t, this can also be an alist specifying this option for different
492 contexts. See `org-show-hierarchy-above' for valid contexts."
493 :group 'org-reveal-location
494 :type org-context-choice)
496 (defcustom org-show-siblings '((default . nil) (isearch t))
497 "Non-nil means, show all sibling heading when revealing a location.
498 Org-mode often shows locations in an org-mode file which might have
499 been invisible before. When this is set, the sibling of the current entry
500 heading are all made visible. If `org-show-hierarchy-above' is t,
501 the same happens on each level of the hierarchy above the current entry.
503 By default this is on for the isearch context, off for all other contexts.
504 Turning this off for example for sparse trees makes them very compact,
505 but makes it harder to edit the location of the match. In such a case,
506 use the command \\[org-reveal] to show more context.
507 Instead of t, this can also be an alist specifying this option for different
508 contexts. See `org-show-hierarchy-above' for valid contexts."
509 :group 'org-reveal-location
510 :type org-context-choice)
512 (defcustom org-show-entry-below '((default . nil))
513 "Non-nil means, show the entry below a headline when revealing a location.
514 Org-mode often shows locations in an org-mode file which might have
515 been invisible before. When this is set, the text below the headline that is
516 exposed is also shown.
518 By default this is off for all contexts.
519 Instead of t, this can also be an alist specifying this option for different
520 contexts. See `org-show-hierarchy-above' for valid contexts."
521 :group 'org-reveal-location
522 :type org-context-choice)
524 (defcustom org-indirect-buffer-display 'other-window
525 "How should indirect tree buffers be displayed?
526 This applies to indirect buffers created with the commands
527 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
528 Valid values are:
529 current-window Display in the current window
530 other-window Just display in another window.
531 dedicated-frame Create one new frame, and re-use it each time.
532 new-frame Make a new frame each time. Note that in this case
533 previously-made indirect buffers are kept, and you need to
534 kill these buffers yourself."
535 :group 'org-structure
536 :group 'org-agenda-windows
537 :type '(choice
538 (const :tag "In current window" current-window)
539 (const :tag "In current frame, other window" other-window)
540 (const :tag "Each time a new frame" new-frame)
541 (const :tag "One dedicated frame" dedicated-frame)))
543 (defgroup org-cycle nil
544 "Options concerning visibility cycling in Org-mode."
545 :tag "Org Cycle"
546 :group 'org-structure)
548 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
549 "Names of drawers. Drawers are not opened by cycling on the headline above.
550 Drawers only open with a TAB on the drawer line itself. A drawer looks like
551 this:
552 :DRAWERNAME:
553 .....
554 :END:
555 The drawer \"PROPERTIES\" is special for capturing properties through
556 the property API.
558 Drawers can be defined on the per-file basis with a line like:
560 #+DRAWERS: HIDDEN STATE PROPERTIES"
561 :group 'org-structure
562 :type '(repeat (string :tag "Drawer Name")))
564 (defcustom org-cycle-global-at-bob nil
565 "Cycle globally if cursor is at beginning of buffer and not at a headline.
566 This makes it possible to do global cycling without having to use S-TAB or
567 C-u TAB. For this special case to work, the first line of the buffer
568 must not be a headline - it may be empty or some other text. When used in
569 this way, `org-cycle-hook' is disables temporarily, to make sure the
570 cursor stays at the beginning of the buffer.
571 When this option is nil, don't do anything special at the beginning
572 of the buffer."
573 :group 'org-cycle
574 :type 'boolean)
576 (defcustom org-cycle-emulate-tab t
577 "Where should `org-cycle' emulate TAB.
578 nil Never
579 white Only in completely white lines
580 whitestart Only at the beginning of lines, before the first non-white char
581 t Everywhere except in headlines
582 exc-hl-bol Everywhere except at the start of a headline
583 If TAB is used in a place where it does not emulate TAB, the current subtree
584 visibility is cycled."
585 :group 'org-cycle
586 :type '(choice (const :tag "Never" nil)
587 (const :tag "Only in completely white lines" white)
588 (const :tag "Before first char in a line" whitestart)
589 (const :tag "Everywhere except in headlines" t)
590 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
593 (defcustom org-cycle-separator-lines 2
594 "Number of empty lines needed to keep an empty line between collapsed trees.
595 If you leave an empty line between the end of a subtree and the following
596 headline, this empty line is hidden when the subtree is folded.
597 Org-mode will leave (exactly) one empty line visible if the number of
598 empty lines is equal or larger to the number given in this variable.
599 So the default 2 means, at least 2 empty lines after the end of a subtree
600 are needed to produce free space between a collapsed subtree and the
601 following headline.
603 Special case: when 0, never leave empty lines in collapsed view."
604 :group 'org-cycle
605 :type 'integer)
606 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
608 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
609 org-cycle-hide-drawers
610 org-cycle-show-empty-lines
611 org-optimize-window-after-visibility-change)
612 "Hook that is run after `org-cycle' has changed the buffer visibility.
613 The function(s) in this hook must accept a single argument which indicates
614 the new state that was set by the most recent `org-cycle' command. The
615 argument is a symbol. After a global state change, it can have the values
616 `overview', `content', or `all'. After a local state change, it can have
617 the values `folded', `children', or `subtree'."
618 :group 'org-cycle
619 :type 'hook)
621 (defgroup org-edit-structure nil
622 "Options concerning structure editing in Org-mode."
623 :tag "Org Edit Structure"
624 :group 'org-structure)
626 (defcustom org-odd-levels-only nil
627 "Non-nil means, skip even levels and only use odd levels for the outline.
628 This has the effect that two stars are being added/taken away in
629 promotion/demotion commands. It also influences how levels are
630 handled by the exporters.
631 Changing it requires restart of `font-lock-mode' to become effective
632 for fontification also in regions already fontified.
633 You may also set this on a per-file basis by adding one of the following
634 lines to the buffer:
636 #+STARTUP: odd
637 #+STARTUP: oddeven"
638 :group 'org-edit-structure
639 :group 'org-font-lock
640 :type 'boolean)
642 (defcustom org-adapt-indentation t
643 "Non-nil means, adapt indentation when promoting and demoting.
644 When this is set and the *entire* text in an entry is indented, the
645 indentation is increased by one space in a demotion command, and
646 decreased by one in a promotion command. If any line in the entry
647 body starts at column 0, indentation is not changed at all."
648 :group 'org-edit-structure
649 :type 'boolean)
651 (defcustom org-special-ctrl-a/e nil
652 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
653 When t, `C-a' will bring back the cursor to the beginning of the
654 headline text, i.e. after the stars and after a possible TODO keyword.
655 In an item, this will be the position after the bullet.
656 When the cursor is already at that position, another `C-a' will bring
657 it to the beginning of the line.
658 `C-e' will jump to the end of the headline, ignoring the presence of tags
659 in the headline. A second `C-e' will then jump to the true end of the
660 line, after any tags.
661 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
662 and only a directly following, identical keypress will bring the cursor
663 to the special positions."
664 :group 'org-edit-structure
665 :type '(choice
666 (const :tag "off" nil)
667 (const :tag "after bullet first" t)
668 (const :tag "border first" reversed)))
670 (if (fboundp 'defvaralias)
671 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
673 (defcustom org-special-ctrl-k nil
674 "Non-nil means `C-k' will behave specially in headlines.
675 When nil, `C-k' will call the default `kill-line' command.
676 When t, the following will happen while the cursor is in the headline:
678 - When the cursor is at the beginning of a headline, kill the entire
679 line and possible the folded subtree below the line.
680 - When in the middle of the headline text, kill the headline up to the tags.
681 - When after the headline text, kill the tags."
682 :group 'org-edit-structure
683 :type 'boolean)
685 (defcustom org-yank-folded-subtrees t
686 "Non-nil means, when yanking subtrees, fold them.
687 If the kill is a single subtree, or a sequence of subtrees, i.e. if
688 it starts with a heading and all other headings in it are either children
689 or siblings, then fold all the subtrees. However, do this only if no
690 text after the yank would be swallowed into a folded tree by this action."
691 :group 'org-edit-structure
692 :type 'boolean)
694 (defcustom org-yank-adjusted-subtrees nil
695 "Non-nil means, when yanking subtrees, adjust the level.
696 With this setting, `org-paste-subtree' is used to insert the subtree, see
697 this function for details."
698 :group 'org-edit-structure
699 :type 'boolean)
701 (defcustom org-M-RET-may-split-line '((default . t))
702 "Non-nil means, M-RET will split the line at the cursor position.
703 When nil, it will go to the end of the line before making a
704 new line.
705 You may also set this option in a different way for different
706 contexts. Valid contexts are:
708 headline when creating a new headline
709 item when creating a new item
710 table in a table field
711 default the value to be used for all contexts not explicitly
712 customized"
713 :group 'org-structure
714 :group 'org-table
715 :type '(choice
716 (const :tag "Always" t)
717 (const :tag "Never" nil)
718 (repeat :greedy t :tag "Individual contexts"
719 (cons
720 (choice :tag "Context"
721 (const headline)
722 (const item)
723 (const table)
724 (const default))
725 (boolean)))))
728 (defcustom org-insert-heading-respect-content nil
729 "Non-nil means, insert new headings after the current subtree.
730 When nil, the new heading is created directly after the current line.
731 The commands \\[org-insert-heading-respect-content] and
732 \\[org-insert-todo-heading-respect-content] turn this variable on
733 for the duration of the command."
734 :group 'org-structure
735 :type 'boolean)
737 (defcustom org-blank-before-new-entry '((heading . auto)
738 (plain-list-item . auto))
739 "Should `org-insert-heading' leave a blank line before new heading/item?
740 The value is an alist, with `heading' and `plain-list-item' as car,
741 and a boolean flag as cdr."
742 :group 'org-edit-structure
743 :type '(list
744 (cons (const heading)
745 (choice (const :tag "Never" nil)
746 (const :tag "Always" t)
747 (const :tag "Auto" auto)))
748 (cons (const plain-list-item)
749 (choice (const :tag "Never" nil)
750 (const :tag "Always" t)
751 (const :tag "Auto" auto)))))
753 (defcustom org-insert-heading-hook nil
754 "Hook being run after inserting a new heading."
755 :group 'org-edit-structure
756 :type 'hook)
758 (defcustom org-enable-fixed-width-editor t
759 "Non-nil means, lines starting with \":\" are treated as fixed-width.
760 This currently only means, they are never auto-wrapped.
761 When nil, such lines will be treated like ordinary lines.
762 See also the QUOTE keyword."
763 :group 'org-edit-structure
764 :type 'boolean)
766 (defcustom org-edit-src-region-extra nil
767 "Additional regexps to identify regions for editing with `org-edit-src-code'.
768 For examples see the function `org-edit-src-find-region-and-lang'.
769 The regular expression identifying the begin marker should end with a newline,
770 and the regexp marking the end line should start with a newline, to make sure
771 there are kept outside the narrowed region."
772 :group 'org-edit-structure
773 :type '(repeat
774 (list
775 (regexp :tag "begin regexp")
776 (regexp :tag "end regexp")
777 (choice :tag "language"
778 (string :tag "specify")
779 (integer :tag "from match group")
780 (const :tag "from `lang' element")
781 (const :tag "from `style' element")))))
783 (defcustom org-coderef-label-format "(ref:%s)"
784 "The default coderef format.
785 This format string will be used to search for coderef labels in literal
786 examples (EXAMPLE and SRC blocks). The format can be overwritten
787 an individual literal example with the -f option, like
789 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
791 #+END_SRC
793 If you want to use this for HTML export, make sure that the format does
794 not introduce special font-locking, and avoid the HTML special
795 characters `<', `>', and `&'. The reason for this restriction is that
796 the labels are searched for only after htmlize has done its job."
797 :group 'org-edit-structure ; FIXME this is not in the right group
798 :type 'string)
800 (defcustom org-edit-fixed-width-region-mode 'artist-mode
801 "The mode that should be used to edit fixed-width regions.
802 These are the regions where each line starts with a colon."
803 :group 'org-edit-structure
804 :type '(choice
805 (const artist-mode)
806 (const picture-mode)
807 (const fundamental-mode)
808 (function :tag "Other (specify)")))
810 (defcustom org-goto-auto-isearch t
811 "Non-nil means, typing characters in org-goto starts incremental search."
812 :group 'org-edit-structure
813 :type 'boolean)
815 (defgroup org-sparse-trees nil
816 "Options concerning sparse trees in Org-mode."
817 :tag "Org Sparse Trees"
818 :group 'org-structure)
820 (defcustom org-highlight-sparse-tree-matches t
821 "Non-nil means, highlight all matches that define a sparse tree.
822 The highlights will automatically disappear the next time the buffer is
823 changed by an edit command."
824 :group 'org-sparse-trees
825 :type 'boolean)
827 (defcustom org-remove-highlights-with-change t
828 "Non-nil means, any change to the buffer will remove temporary highlights.
829 Such highlights are created by `org-occur' and `org-clock-display'.
830 When nil, `C-c C-c needs to be used to get rid of the highlights.
831 The highlights created by `org-preview-latex-fragment' always need
832 `C-c C-c' to be removed."
833 :group 'org-sparse-trees
834 :group 'org-time
835 :type 'boolean)
838 (defcustom org-occur-hook '(org-first-headline-recenter)
839 "Hook that is run after `org-occur' has constructed a sparse tree.
840 This can be used to recenter the window to show as much of the structure
841 as possible."
842 :group 'org-sparse-trees
843 :type 'hook)
845 (defgroup org-imenu-and-speedbar nil
846 "Options concerning imenu and speedbar in Org-mode."
847 :tag "Org Imenu and Speedbar"
848 :group 'org-structure)
850 (defcustom org-imenu-depth 2
851 "The maximum level for Imenu access to Org-mode headlines.
852 This also applied for speedbar access."
853 :group 'org-imenu-and-speedbar
854 :type 'number)
856 (defgroup org-table nil
857 "Options concerning tables in Org-mode."
858 :tag "Org Table"
859 :group 'org)
861 (defcustom org-enable-table-editor 'optimized
862 "Non-nil means, lines starting with \"|\" are handled by the table editor.
863 When nil, such lines will be treated like ordinary lines.
865 When equal to the symbol `optimized', the table editor will be optimized to
866 do the following:
867 - Automatic overwrite mode in front of whitespace in table fields.
868 This makes the structure of the table stay in tact as long as the edited
869 field does not exceed the column width.
870 - Minimize the number of realigns. Normally, the table is aligned each time
871 TAB or RET are pressed to move to another field. With optimization this
872 happens only if changes to a field might have changed the column width.
873 Optimization requires replacing the functions `self-insert-command',
874 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
875 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
876 very good at guessing when a re-align will be necessary, but you can always
877 force one with \\[org-ctrl-c-ctrl-c].
879 If you would like to use the optimized version in Org-mode, but the
880 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
882 This variable can be used to turn on and off the table editor during a session,
883 but in order to toggle optimization, a restart is required.
885 See also the variable `org-table-auto-blank-field'."
886 :group 'org-table
887 :type '(choice
888 (const :tag "off" nil)
889 (const :tag "on" t)
890 (const :tag "on, optimized" optimized)))
892 (defcustom org-table-tab-recognizes-table.el t
893 "Non-nil means, TAB will automatically notice a table.el table.
894 When it sees such a table, it moves point into it and - if necessary -
895 calls `table-recognize-table'."
896 :group 'org-table-editing
897 :type 'boolean)
899 (defgroup org-link nil
900 "Options concerning links in Org-mode."
901 :tag "Org Link"
902 :group 'org)
904 (defvar org-link-abbrev-alist-local nil
905 "Buffer-local version of `org-link-abbrev-alist', which see.
906 The value of this is taken from the #+LINK lines.")
907 (make-variable-buffer-local 'org-link-abbrev-alist-local)
909 (defcustom org-link-abbrev-alist nil
910 "Alist of link abbreviations.
911 The car of each element is a string, to be replaced at the start of a link.
912 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
913 links in Org-mode buffers can have an optional tag after a double colon, e.g.
915 [[linkkey:tag][description]]
917 If REPLACE is a string, the tag will simply be appended to create the link.
918 If the string contains \"%s\", the tag will be inserted there. Alternatively,
919 the placeholder \"%h\" will cause a url-encoded version of the tag to
920 be inserted at that point (see the function `url-hexify-string').
922 REPLACE may also be a function that will be called with the tag as the
923 only argument to create the link, which should be returned as a string.
925 See the manual for examples."
926 :group 'org-link
927 :type '(repeat
928 (cons
929 (string :tag "Protocol")
930 (choice
931 (string :tag "Format")
932 (function)))))
934 (defcustom org-descriptive-links t
935 "Non-nil means, hide link part and only show description of bracket links.
936 Bracket links are like [[link][description]]. This variable sets the initial
937 state in new org-mode buffers. The setting can then be toggled on a
938 per-buffer basis from the Org->Hyperlinks menu."
939 :group 'org-link
940 :type 'boolean)
942 (defcustom org-link-file-path-type 'adaptive
943 "How the path name in file links should be stored.
944 Valid values are:
946 relative Relative to the current directory, i.e. the directory of the file
947 into which the link is being inserted.
948 absolute Absolute path, if possible with ~ for home directory.
949 noabbrev Absolute path, no abbreviation of home directory.
950 adaptive Use relative path for files in the current directory and sub-
951 directories of it. For other files, use an absolute path."
952 :group 'org-link
953 :type '(choice
954 (const relative)
955 (const absolute)
956 (const noabbrev)
957 (const adaptive)))
959 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
960 "Types of links that should be activated in Org-mode files.
961 This is a list of symbols, each leading to the activation of a certain link
962 type. In principle, it does not hurt to turn on most link types - there may
963 be a small gain when turning off unused link types. The types are:
965 bracket The recommended [[link][description]] or [[link]] links with hiding.
966 angular Links in angular brackets that may contain whitespace like
967 <bbdb:Carsten Dominik>.
968 plain Plain links in normal text, no whitespace, like http://google.com.
969 radio Text that is matched by a radio target, see manual for details.
970 tag Tag settings in a headline (link to tag search).
971 date Time stamps (link to calendar).
972 footnote Footnote labels.
974 Changing this variable requires a restart of Emacs to become effective."
975 :group 'org-link
976 :type '(set :greedy t
977 (const :tag "Double bracket links (new style)" bracket)
978 (const :tag "Angular bracket links (old style)" angular)
979 (const :tag "Plain text links" plain)
980 (const :tag "Radio target matches" radio)
981 (const :tag "Tags" tag)
982 (const :tag "Timestamps" date)
983 (const :tag "Footnotes" footnote)))
985 (defcustom org-make-link-description-function nil
986 "Function to use to generate link descriptions from links. If
987 nil the link location will be used. This function must take two
988 parameters; the first is the link and the second the description
989 org-insert-link has generated, and should return the description
990 to use."
991 :group 'org-link
992 :type 'function)
994 (defgroup org-link-store nil
995 "Options concerning storing links in Org-mode."
996 :tag "Org Store Link"
997 :group 'org-link)
999 (defcustom org-email-link-description-format "Email %c: %.30s"
1000 "Format of the description part of a link to an email or usenet message.
1001 The following %-escapes will be replaced by corresponding information:
1003 %F full \"From\" field
1004 %f name, taken from \"From\" field, address if no name
1005 %T full \"To\" field
1006 %t first name in \"To\" field, address if no name
1007 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1008 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1009 %s subject
1010 %m message-id.
1012 You may use normal field width specification between the % and the letter.
1013 This is for example useful to limit the length of the subject.
1015 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1016 :group 'org-link-store
1017 :type 'string)
1019 (defcustom org-from-is-user-regexp
1020 (let (r1 r2)
1021 (when (and user-mail-address (not (string= user-mail-address "")))
1022 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1023 (when (and user-full-name (not (string= user-full-name "")))
1024 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1025 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1026 "Regexp matched against the \"From:\" header of an email or usenet message.
1027 It should match if the message is from the user him/herself."
1028 :group 'org-link-store
1029 :type 'regexp)
1031 (defcustom org-link-to-org-use-id 'create-if-interactive
1032 "Non-nil means, storing a link to an Org file will use entry IDs.
1034 Note that before this variable is even considered, org-id must be loaded,
1035 to please customize `org-modules' and turn it on.
1037 The variable can have the following values:
1039 t Create an ID if needed to make a link to the current entry.
1041 create-if-interactive
1042 If `org-store-link' is called directly (interactively, as a user
1043 command), do create an ID to support the link. But when doing the
1044 job for remember, only use the ID if it already exists. The
1045 purpose of this setting is to avoid proliferation of unwanted
1046 IDs, just because you happen to be in an Org file when you
1047 call `org-remember' that automatically and preemptively
1048 creates a link. If you do want to get an ID link in a remember
1049 template to an entry not having an ID, create it first by
1050 explicitly creating a link to it, using `C-c C-l' first.
1052 use-existing
1053 Use existing ID, do not create one.
1055 nil Never use an ID to make a link, instead link using a text search for
1056 the headline text."
1057 :group 'org-link-store
1058 :type '(choice
1059 (const :tag "Create ID to make link" t)
1060 (const :tag "Create if string link interactively"
1061 'create-if-interactive)
1062 (const :tag "Only use existing" 'use-existing)
1063 (const :tag "Do not use ID to create link" nil)))
1065 (defcustom org-context-in-file-links t
1066 "Non-nil means, file links from `org-store-link' contain context.
1067 A search string will be added to the file name with :: as separator and
1068 used to find the context when the link is activated by the command
1069 `org-open-at-point'.
1070 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1071 negates this setting for the duration of the command."
1072 :group 'org-link-store
1073 :type 'boolean)
1075 (defcustom org-keep-stored-link-after-insertion nil
1076 "Non-nil means, keep link in list for entire session.
1078 The command `org-store-link' adds a link pointing to the current
1079 location to an internal list. These links accumulate during a session.
1080 The command `org-insert-link' can be used to insert links into any
1081 Org-mode file (offering completion for all stored links). When this
1082 option is nil, every link which has been inserted once using \\[org-insert-link]
1083 will be removed from the list, to make completing the unused links
1084 more efficient."
1085 :group 'org-link-store
1086 :type 'boolean)
1088 (defgroup org-link-follow nil
1089 "Options concerning following links in Org-mode."
1090 :tag "Org Follow Link"
1091 :group 'org-link)
1093 (defcustom org-link-translation-function nil
1094 "Function to translate links with different syntax to Org syntax.
1095 This can be used to translate links created for example by the Planner
1096 or emacs-wiki packages to Org syntax.
1097 The function must accept two parameters, a TYPE containing the link
1098 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1099 which is everything after the link protocol. It should return a cons
1100 with possibly modified values of type and path.
1101 Org contains a function for this, so if you set this variable to
1102 `org-translate-link-from-planner', you should be able follow many
1103 links created by planner."
1104 :group 'org-link-follow
1105 :type 'function)
1107 (defcustom org-follow-link-hook nil
1108 "Hook that is run after a link has been followed."
1109 :group 'org-link-follow
1110 :type 'hook)
1112 (defcustom org-tab-follows-link nil
1113 "Non-nil means, on links TAB will follow the link.
1114 Needs to be set before org.el is loaded.
1115 This really should not be used, it does not make sense, and the
1116 implementation is bad."
1117 :group 'org-link-follow
1118 :type 'boolean)
1120 (defcustom org-return-follows-link nil
1121 "Non-nil means, on links RET will follow the link.
1122 Needs to be set before org.el is loaded."
1123 :group 'org-link-follow
1124 :type 'boolean)
1126 (defcustom org-mouse-1-follows-link
1127 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1128 "Non-nil means, mouse-1 on a link will follow the link.
1129 A longer mouse click will still set point. Does not work on XEmacs.
1130 Needs to be set before org.el is loaded."
1131 :group 'org-link-follow
1132 :type 'boolean)
1134 (defcustom org-mark-ring-length 4
1135 "Number of different positions to be recorded in the ring
1136 Changing this requires a restart of Emacs to work correctly."
1137 :group 'org-link-follow
1138 :type 'integer)
1140 (defcustom org-link-frame-setup
1141 '((vm . vm-visit-folder-other-frame)
1142 (gnus . gnus-other-frame)
1143 (file . find-file-other-window))
1144 "Setup the frame configuration for following links.
1145 When following a link with Emacs, it may often be useful to display
1146 this link in another window or frame. This variable can be used to
1147 set this up for the different types of links.
1148 For VM, use any of
1149 `vm-visit-folder'
1150 `vm-visit-folder-other-frame'
1151 For Gnus, use any of
1152 `gnus'
1153 `gnus-other-frame'
1154 `org-gnus-no-new-news'
1155 For FILE, use any of
1156 `find-file'
1157 `find-file-other-window'
1158 `find-file-other-frame'
1159 For the calendar, use the variable `calendar-setup'.
1160 For BBDB, it is currently only possible to display the matches in
1161 another window."
1162 :group 'org-link-follow
1163 :type '(list
1164 (cons (const vm)
1165 (choice
1166 (const vm-visit-folder)
1167 (const vm-visit-folder-other-window)
1168 (const vm-visit-folder-other-frame)))
1169 (cons (const gnus)
1170 (choice
1171 (const gnus)
1172 (const gnus-other-frame)
1173 (const org-gnus-no-new-news)))
1174 (cons (const file)
1175 (choice
1176 (const find-file)
1177 (const find-file-other-window)
1178 (const find-file-other-frame)))))
1180 (defcustom org-display-internal-link-with-indirect-buffer nil
1181 "Non-nil means, use indirect buffer to display infile links.
1182 Activating internal links (from one location in a file to another location
1183 in the same file) normally just jumps to the location. When the link is
1184 activated with a C-u prefix (or with mouse-3), the link is displayed in
1185 another window. When this option is set, the other window actually displays
1186 an indirect buffer clone of the current buffer, to avoid any visibility
1187 changes to the current buffer."
1188 :group 'org-link-follow
1189 :type 'boolean)
1191 (defcustom org-open-non-existing-files nil
1192 "Non-nil means, `org-open-file' will open non-existing files.
1193 When nil, an error will be generated."
1194 :group 'org-link-follow
1195 :type 'boolean)
1197 (defcustom org-open-directory-means-index-dot-org nil
1198 "Non-nil means, a link to a directory really means to index.org.
1199 When nil, following a directory link will run dired or open a finder/explorer
1200 window on that directory."
1201 :group 'org-link-follow
1202 :type 'boolean)
1204 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1205 "Function and arguments to call for following mailto links.
1206 This is a list with the first element being a lisp function, and the
1207 remaining elements being arguments to the function. In string arguments,
1208 %a will be replaced by the address, and %s will be replaced by the subject
1209 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1210 :group 'org-link-follow
1211 :type '(choice
1212 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1213 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1214 (const :tag "message-mail" (message-mail "%a" "%s"))
1215 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1217 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1218 "Non-nil means, ask for confirmation before executing shell links.
1219 Shell links can be dangerous: just think about a link
1221 [[shell:rm -rf ~/*][Google Search]]
1223 This link would show up in your Org-mode document as \"Google Search\",
1224 but really it would remove your entire home directory.
1225 Therefore we advise against setting this variable to nil.
1226 Just change it to `y-or-n-p' of you want to confirm with a
1227 single keystroke rather than having to type \"yes\"."
1228 :group 'org-link-follow
1229 :type '(choice
1230 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1231 (const :tag "with y-or-n (faster)" y-or-n-p)
1232 (const :tag "no confirmation (dangerous)" nil)))
1234 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1235 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1236 Elisp links can be dangerous: just think about a link
1238 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1240 This link would show up in your Org-mode document as \"Google Search\",
1241 but really it would remove your entire home directory.
1242 Therefore we advise against setting this variable to nil.
1243 Just change it to `y-or-n-p' of you want to confirm with a
1244 single keystroke rather than having to type \"yes\"."
1245 :group 'org-link-follow
1246 :type '(choice
1247 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1248 (const :tag "with y-or-n (faster)" y-or-n-p)
1249 (const :tag "no confirmation (dangerous)" nil)))
1251 (defconst org-file-apps-defaults-gnu
1252 '((remote . emacs)
1253 (system . mailcap)
1254 (t . mailcap))
1255 "Default file applications on a UNIX or GNU/Linux system.
1256 See `org-file-apps'.")
1258 (defconst org-file-apps-defaults-macosx
1259 '((remote . emacs)
1260 (t . "open %s")
1261 (system . "open %s")
1262 ("ps.gz" . "gv %s")
1263 ("eps.gz" . "gv %s")
1264 ("dvi" . "xdvi %s")
1265 ("fig" . "xfig %s"))
1266 "Default file applications on a MacOS X system.
1267 The system \"open\" is known as a default, but we use X11 applications
1268 for some files for which the OS does not have a good default.
1269 See `org-file-apps'.")
1271 (defconst org-file-apps-defaults-windowsnt
1272 (list
1273 '(remote . emacs)
1274 (cons t
1275 (list (if (featurep 'xemacs)
1276 'mswindows-shell-execute
1277 'w32-shell-execute)
1278 "open" 'file))
1279 (cons 'system
1280 (list (if (featurep 'xemacs)
1281 'mswindows-shell-execute
1282 'w32-shell-execute)
1283 "open" 'file)))
1284 "Default file applications on a Windows NT system.
1285 The system \"open\" is used for most files.
1286 See `org-file-apps'.")
1288 (defcustom org-file-apps
1290 (auto-mode . emacs)
1291 ("\\.x?html?\\'" . default)
1292 ("\\.pdf\\'" . default)
1294 "External applications for opening `file:path' items in a document.
1295 Org-mode uses system defaults for different file types, but
1296 you can use this variable to set the application for a given file
1297 extension. The entries in this list are cons cells where the car identifies
1298 files and the cdr the corresponding command. Possible values for the
1299 file identifier are
1300 \"regex\" Regular expression matched against the file name. For backward
1301 compatibility, this can also be a string with only alphanumeric
1302 characters, which is then interpreted as an extension.
1303 `directory' Matches a directory
1304 `remote' Matches a remote file, accessible through tramp or efs.
1305 Remote files most likely should be visited through Emacs
1306 because external applications cannot handle such paths.
1307 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1308 so all files Emacs knows how to handle. Using this with
1309 command `emacs' will open most files in Emacs. Beware that this
1310 will also open html files inside Emacs, unless you add
1311 (\"html\" . default) to the list as well.
1312 t Default for files not matched by any of the other options.
1313 `system' The system command to open files, like `open' on Windows
1314 and Mac OS X, and mailcap under GNU/Linux. This is the command
1315 that will be selected if you call `C-c C-o' with a double
1316 `C-u C-u' prefix.
1318 Possible values for the command are:
1319 `emacs' The file will be visited by the current Emacs process.
1320 `default' Use the default application for this file type, which is the
1321 association for t in the list, most likely in the system-specific
1322 part.
1323 This can be used to overrule an unwanted setting in the
1324 system-specific variable.
1325 `system' Use the system command for opening files, like \"open\".
1326 This command is specified by the entry whose car is `system'.
1327 Most likely, the system-specific version of this variable
1328 does define this command, but you can overrule/replace it
1329 here.
1330 string A command to be executed by a shell; %s will be replaced
1331 by the path to the file.
1332 sexp A Lisp form which will be evaluated. The file path will
1333 be available in the Lisp variable `file'.
1334 For more examples, see the system specific constants
1335 `org-file-apps-defaults-macosx'
1336 `org-file-apps-defaults-windowsnt'
1337 `org-file-apps-defaults-gnu'."
1338 :group 'org-link-follow
1339 :type '(repeat
1340 (cons (choice :value ""
1341 (string :tag "Extension")
1342 (const :tag "System command to open files" system)
1343 (const :tag "Default for unrecognized files" t)
1344 (const :tag "Remote file" remote)
1345 (const :tag "Links to a directory" directory)
1346 (const :tag "Any files that have Emacs modes"
1347 auto-mode))
1348 (choice :value ""
1349 (const :tag "Visit with Emacs" emacs)
1350 (const :tag "Use default" default)
1351 (const :tag "Use the system command" system)
1352 (string :tag "Command")
1353 (sexp :tag "Lisp form")))))
1355 (defgroup org-refile nil
1356 "Options concerning refiling entries in Org-mode."
1357 :tag "Org Refile"
1358 :group 'org)
1360 (defcustom org-directory "~/org"
1361 "Directory with org files.
1362 This is just a default location to look for Org files. There is no need
1363 at all to put your files into this directory. It is only used in the
1364 following situations:
1366 1. When a remember template specifies a target file that is not an
1367 absolute path. The path will then be interpreted relative to
1368 `org-directory'
1369 2. When a remember note is filed away in an interactive way (when exiting the
1370 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1371 with `org-directory' as the default path."
1372 :group 'org-refile
1373 :group 'org-remember
1374 :type 'directory)
1376 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1377 "Default target for storing notes.
1378 Used by the hooks for remember.el. This can be a string, or nil to mean
1379 the value of `remember-data-file'.
1380 You can set this on a per-template basis with the variable
1381 `org-remember-templates'."
1382 :group 'org-refile
1383 :group 'org-remember
1384 :type '(choice
1385 (const :tag "Default from remember-data-file" nil)
1386 file))
1388 (defcustom org-goto-interface 'outline
1389 "The default interface to be used for `org-goto'.
1390 Allowed values are:
1391 outline The interface shows an outline of the relevant file
1392 and the correct heading is found by moving through
1393 the outline or by searching with incremental search.
1394 outline-path-completion Headlines in the current buffer are offered via
1395 completion. This is the interface also used by
1396 the refile command."
1397 :group 'org-refile
1398 :type '(choice
1399 (const :tag "Outline" outline)
1400 (const :tag "Outline-path-completion" outline-path-completion)))
1402 (defcustom org-goto-max-level 5
1403 "Maximum level to be considered when running org-goto with refile interface."
1404 :group 'org-refile
1405 :type 'number)
1407 (defcustom org-reverse-note-order nil
1408 "Non-nil means, store new notes at the beginning of a file or entry.
1409 When nil, new notes will be filed to the end of a file or entry.
1410 This can also be a list with cons cells of regular expressions that
1411 are matched against file names, and values."
1412 :group 'org-remember
1413 :group 'org-refile
1414 :type '(choice
1415 (const :tag "Reverse always" t)
1416 (const :tag "Reverse never" nil)
1417 (repeat :tag "By file name regexp"
1418 (cons regexp boolean))))
1420 (defcustom org-refile-targets nil
1421 "Targets for refiling entries with \\[org-refile].
1422 This is list of cons cells. Each cell contains:
1423 - a specification of the files to be considered, either a list of files,
1424 or a symbol whose function or variable value will be used to retrieve
1425 a file name or a list of file names. If you use `org-agenda-files' for
1426 that, all agenda files will be scanned for targets. Nil means, consider
1427 headings in the current buffer.
1428 - A specification of how to find candidate refile targets. This may be
1429 any of:
1430 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1431 This tag has to be present in all target headlines, inheritance will
1432 not be considered.
1433 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1434 todo keyword.
1435 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1436 headlines that are refiling targets.
1437 - a cons cell (:level . N). Any headline of level N is considered a target.
1438 Note that, when `org-odd-levels-only' is set, level corresponds to
1439 order in hierarchy, not to the number of stars.
1440 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1441 Note that, when `org-odd-levels-only' is set, level corresponds to
1442 order in hierarchy, not to the number of stars.
1444 When this variable is nil, all top-level headlines in the current buffer
1445 are used, equivalent to the value `((nil . (:level . 1))'."
1446 :group 'org-refile
1447 :type '(repeat
1448 (cons
1449 (choice :value org-agenda-files
1450 (const :tag "All agenda files" org-agenda-files)
1451 (const :tag "Current buffer" nil)
1452 (function) (variable) (file))
1453 (choice :tag "Identify target headline by"
1454 (cons :tag "Specific tag" (const :value :tag) (string))
1455 (cons :tag "TODO keyword" (const :value :todo) (string))
1456 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1457 (cons :tag "Level number" (const :value :level) (integer))
1458 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1460 (defcustom org-refile-use-outline-path nil
1461 "Non-nil means, provide refile targets as paths.
1462 So a level 3 headline will be available as level1/level2/level3.
1463 When the value is `file', also include the file name (without directory)
1464 into the path. When `full-file-path', include the full file path."
1465 :group 'org-refile
1466 :type '(choice
1467 (const :tag "Not" nil)
1468 (const :tag "Yes" t)
1469 (const :tag "Start with file name" file)
1470 (const :tag "Start with full file path" full-file-path)))
1472 (defcustom org-outline-path-complete-in-steps t
1473 "Non-nil means, complete the outline path in hierarchical steps.
1474 When Org-mode uses the refile interface to select an outline path
1475 \(see variable `org-refile-use-outline-path'), the completion of
1476 the path can be done is a single go, or if can be done in steps down
1477 the headline hierarchy. Going in steps is probably the best if you
1478 do not use a special completion package like `ido' or `icicles'.
1479 However, when using these packages, going in one step can be very
1480 fast, while still showing the whole path to the entry."
1481 :group 'org-refile
1482 :type 'boolean)
1484 (defgroup org-todo nil
1485 "Options concerning TODO items in Org-mode."
1486 :tag "Org TODO"
1487 :group 'org)
1489 (defgroup org-progress nil
1490 "Options concerning Progress logging in Org-mode."
1491 :tag "Org Progress"
1492 :group 'org-time)
1494 (defvar org-todo-interpretation-widgets
1496 (:tag "Sequence (cycling hits every state)" sequence)
1497 (:tag "Type (cycling directly to DONE)" type))
1498 "The available interpretation symbols for customizing
1499 `org-todo-keywords'.
1500 Interested libraries should add to this list.")
1502 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1503 "List of TODO entry keyword sequences and their interpretation.
1504 \\<org-mode-map>This is a list of sequences.
1506 Each sequence starts with a symbol, either `sequence' or `type',
1507 indicating if the keywords should be interpreted as a sequence of
1508 action steps, or as different types of TODO items. The first
1509 keywords are states requiring action - these states will select a headline
1510 for inclusion into the global TODO list Org-mode produces. If one of
1511 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1512 signify that no further action is necessary. If \"|\" is not found,
1513 the last keyword is treated as the only DONE state of the sequence.
1515 The command \\[org-todo] cycles an entry through these states, and one
1516 additional state where no keyword is present. For details about this
1517 cycling, see the manual.
1519 TODO keywords and interpretation can also be set on a per-file basis with
1520 the special #+SEQ_TODO and #+TYP_TODO lines.
1522 Each keyword can optionally specify a character for fast state selection
1523 \(in combination with the variable `org-use-fast-todo-selection')
1524 and specifiers for state change logging, using the same syntax
1525 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1526 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1527 indicates to record a time stamp each time this state is selected.
1529 Each keyword may also specify if a timestamp or a note should be
1530 recorded when entering or leaving the state, by adding additional
1531 characters in the parenthesis after the keyword. This looks like this:
1532 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1533 record only the time of the state change. With X and Y being either
1534 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1535 Y when leaving the state if and only if the *target* state does not
1536 define X. You may omit any of the fast-selection key or X or /Y,
1537 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1539 For backward compatibility, this variable may also be just a list
1540 of keywords - in this case the interpretation (sequence or type) will be
1541 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1542 :group 'org-todo
1543 :group 'org-keywords
1544 :type '(choice
1545 (repeat :tag "Old syntax, just keywords"
1546 (string :tag "Keyword"))
1547 (repeat :tag "New syntax"
1548 (cons
1549 (choice
1550 :tag "Interpretation"
1551 ;;Quick and dirty way to see
1552 ;;`org-todo-interpretations'. This takes the
1553 ;;place of item arguments
1554 :convert-widget
1555 (lambda (widget)
1556 (widget-put widget
1557 :args (mapcar
1558 #'(lambda (x)
1559 (widget-convert
1560 (cons 'const x)))
1561 org-todo-interpretation-widgets))
1562 widget))
1563 (repeat
1564 (string :tag "Keyword"))))))
1566 (defvar org-todo-keywords-1 nil
1567 "All TODO and DONE keywords active in a buffer.")
1568 (make-variable-buffer-local 'org-todo-keywords-1)
1569 (defvar org-todo-keywords-for-agenda nil)
1570 (defvar org-done-keywords-for-agenda nil)
1571 (defvar org-todo-keyword-alist-for-agenda nil)
1572 (defvar org-tag-alist-for-agenda nil)
1573 (defvar org-agenda-contributing-files nil)
1574 (defvar org-not-done-keywords nil)
1575 (make-variable-buffer-local 'org-not-done-keywords)
1576 (defvar org-done-keywords nil)
1577 (make-variable-buffer-local 'org-done-keywords)
1578 (defvar org-todo-heads nil)
1579 (make-variable-buffer-local 'org-todo-heads)
1580 (defvar org-todo-sets nil)
1581 (make-variable-buffer-local 'org-todo-sets)
1582 (defvar org-todo-log-states nil)
1583 (make-variable-buffer-local 'org-todo-log-states)
1584 (defvar org-todo-kwd-alist nil)
1585 (make-variable-buffer-local 'org-todo-kwd-alist)
1586 (defvar org-todo-key-alist nil)
1587 (make-variable-buffer-local 'org-todo-key-alist)
1588 (defvar org-todo-key-trigger nil)
1589 (make-variable-buffer-local 'org-todo-key-trigger)
1591 (defcustom org-todo-interpretation 'sequence
1592 "Controls how TODO keywords are interpreted.
1593 This variable is in principle obsolete and is only used for
1594 backward compatibility, if the interpretation of todo keywords is
1595 not given already in `org-todo-keywords'. See that variable for
1596 more information."
1597 :group 'org-todo
1598 :group 'org-keywords
1599 :type '(choice (const sequence)
1600 (const type)))
1602 (defcustom org-use-fast-todo-selection t
1603 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1604 This variable describes if and under what circumstances the cycling
1605 mechanism for TODO keywords will be replaced by a single-key, direct
1606 selection scheme.
1608 When nil, fast selection is never used.
1610 When the symbol `prefix', it will be used when `org-todo' is called with
1611 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1612 in an agenda buffer.
1614 When t, fast selection is used by default. In this case, the prefix
1615 argument forces cycling instead.
1617 In all cases, the special interface is only used if access keys have actually
1618 been assigned by the user, i.e. if keywords in the configuration are followed
1619 by a letter in parenthesis, like TODO(t)."
1620 :group 'org-todo
1621 :type '(choice
1622 (const :tag "Never" nil)
1623 (const :tag "By default" t)
1624 (const :tag "Only with C-u C-c C-t" prefix)))
1626 (defcustom org-provide-todo-statistics t
1627 "Non-nil means, update todo statistics after insert and toggle.
1628 When this is set, todo statistics is updated in the parent of the current
1629 entry each time a todo state is changed."
1630 :group 'org-todo
1631 :type 'boolean)
1633 (defcustom org-after-todo-state-change-hook nil
1634 "Hook which is run after the state of a TODO item was changed.
1635 The new state (a string with a TODO keyword, or nil) is available in the
1636 Lisp variable `state'."
1637 :group 'org-todo
1638 :type 'hook)
1640 (defvar org-blocker-hook nil
1641 "Hook for functions that are allowed to block a state change.
1643 Each function gets as its single argument a property list, see
1644 `org-trigger-hook' for more information about this list.
1646 If any of the functions in this hook returns nil, the state change
1647 is blocked.")
1649 (defvar org-trigger-hook nil
1650 "Hook for functions that are triggered by a state change.
1652 Each function gets as its single argument a property list with at least
1653 the following elements:
1655 (:type type-of-change :position pos-at-entry-start
1656 :from old-state :to new-state)
1658 Depending on the type, more properties may be present.
1660 This mechanism is currently implemented for:
1662 TODO state changes
1663 ------------------
1664 :type todo-state-change
1665 :from previous state (keyword as a string), or nil, or a symbol
1666 'todo' or 'done', to indicate the general type of state.
1667 :to new state, like in :from")
1669 (defcustom org-enforce-todo-dependencies nil
1670 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1671 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1672 be blocked if any prior sibling is not yet done.
1673 This variable needs to be set before org.el is loaded, and you need to
1674 restart Emacs after a change to make the change effective. The only way
1675 to change is while Emacs is running is through the customize interface."
1676 :set (lambda (var val)
1677 (set var val)
1678 (if val
1679 (add-hook 'org-blocker-hook
1680 'org-block-todo-from-children-or-siblings)
1681 (remove-hook 'org-blocker-hook
1682 'org-block-todo-from-children-or-siblings)))
1683 :group 'org-todo
1684 :type 'boolean)
1686 (defcustom org-enforce-todo-checkbox-dependencies nil
1687 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1688 When this is nil, checkboxes have no influence on switching TODO states.
1689 When non-nil, you first need to check off all check boxes before the TODO
1690 entry can be switched to DONE.
1691 This variable needs to be set before org.el is loaded, and you need to
1692 restart Emacs after a change to make the change effective. The only way
1693 to change is while Emacs is running is through the customize interface."
1694 :set (lambda (var val)
1695 (set var val)
1696 (if val
1697 (add-hook 'org-blocker-hook
1698 'org-block-todo-from-checkboxes)
1699 (remove-hook 'org-blocker-hook
1700 'org-block-todo-from-checkboxes)))
1701 :group 'org-todo
1702 :type 'boolean)
1704 (defcustom org-todo-state-tags-triggers nil
1705 "Tag changes that should be triggered by TODO state changes.
1706 This is a list. Each entry is
1708 (state-change (tag . flag) .......)
1710 State-change can be a string with a state, and empty string to indicate the
1711 state that has no TODO keyword, or it can be one of the symbols `todo'
1712 or `done', meaning any not-done or done state, respectively."
1713 :group 'org-todo
1714 :group 'org-tags
1715 :type '(repeat
1716 (cons (choice :tag "When changing to"
1717 (const :tag "Not-done state" todo)
1718 (const :tag "Done state" done)
1719 (string :tag "State"))
1720 (repeat
1721 (cons :tag "Tag action"
1722 (string :tag "Tag")
1723 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1725 (defcustom org-log-done nil
1726 "Information to record when a task moves to the DONE state.
1728 Possible values are:
1730 nil Don't add anything, just change the keyword
1731 time Add a time stamp to the task
1732 note Prompt a closing note and add it with template `org-log-note-headings'
1734 This option can also be set with on a per-file-basis with
1736 #+STARTUP: nologdone
1737 #+STARTUP: logdone
1738 #+STARTUP: lognotedone
1740 You can have local logging settings for a subtree by setting the LOGGING
1741 property to one or more of these keywords."
1742 :group 'org-todo
1743 :group 'org-progress
1744 :type '(choice
1745 (const :tag "No logging" nil)
1746 (const :tag "Record CLOSED timestamp" time)
1747 (const :tag "Record CLOSED timestamp with closing note." note)))
1749 ;; Normalize old uses of org-log-done.
1750 (cond
1751 ((eq org-log-done t) (setq org-log-done 'time))
1752 ((and (listp org-log-done) (memq 'done org-log-done))
1753 (setq org-log-done 'note)))
1755 (defcustom org-log-note-clock-out nil
1756 "Non-nil means, record a note when clocking out of an item.
1757 This can also be configured on a per-file basis by adding one of
1758 the following lines anywhere in the buffer:
1760 #+STARTUP: lognoteclock-out
1761 #+STARTUP: nolognoteclock-out"
1762 :group 'org-todo
1763 :group 'org-progress
1764 :type 'boolean)
1766 (defcustom org-log-done-with-time t
1767 "Non-nil means, the CLOSED time stamp will contain date and time.
1768 When nil, only the date will be recorded."
1769 :group 'org-progress
1770 :type 'boolean)
1772 (defcustom org-log-note-headings
1773 '((done . "CLOSING NOTE %t")
1774 (state . "State %-12s from %-12S %t")
1775 (note . "Note taken on %t")
1776 (clock-out . ""))
1777 "Headings for notes added to entries.
1778 The value is an alist, with the car being a symbol indicating the note
1779 context, and the cdr is the heading to be used. The heading may also be the
1780 empty string.
1781 %t in the heading will be replaced by a time stamp.
1782 %s will be replaced by the new TODO state, in double quotes.
1783 %S will be replaced by the old TODO state, in double quotes.
1784 %u will be replaced by the user name.
1785 %U will be replaced by the full user name."
1786 :group 'org-todo
1787 :group 'org-progress
1788 :type '(list :greedy t
1789 (cons (const :tag "Heading when closing an item" done) string)
1790 (cons (const :tag
1791 "Heading when changing todo state (todo sequence only)"
1792 state) string)
1793 (cons (const :tag "Heading when just taking a note" note) string)
1794 (cons (const :tag "Heading when clocking out" clock-out) string)))
1796 (unless (assq 'note org-log-note-headings)
1797 (push '(note . "%t") org-log-note-headings))
1799 (defcustom org-log-into-drawer nil
1800 "Non-nil means, insert state change notes and time stamps into a drawer.
1801 When nil, state changes notes will be inserted after the headline and
1802 any scheduling and clock lines, but not inside a drawer.
1804 The value of this variable should be the name of the drawer to use.
1805 LOGBOOK is proposed at the default drawer for this purpose, you can
1806 also set this to a string to define the drawer of your choice.
1808 A value of t is also allowed, representing \"LOGBOOK\".
1810 If this variable is set, `org-log-state-notes-insert-after-drawers'
1811 will be ognored."
1812 :group 'org-todo
1813 :group 'org-progress
1814 :type '(choice
1815 (const :tag "Not into a drawer" nil)
1816 (const :tag "LOGBOOK" t)
1817 (string :tag "Other")))
1819 (if (fboundp 'defvaralias)
1820 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1822 (defcustom org-log-state-notes-insert-after-drawers nil
1823 "Non-nil means, insert state change notes after any drawers in entry.
1824 Only the drawers that *immediately* follow the headline and the
1825 deadline/scheduled line are skipped.
1826 When nil, insert notes right after the heading and perhaps the line
1827 with deadline/scheduling if present.
1829 This variable will have no effect if `org-log-into-drawer' is
1830 set."
1831 :group 'org-todo
1832 :group 'org-progress
1833 :type 'boolean)
1835 (defcustom org-log-states-order-reversed t
1836 "Non-nil means, the latest state change note will be directly after heading.
1837 When nil, the notes will be orderer according to time."
1838 :group 'org-todo
1839 :group 'org-progress
1840 :type 'boolean)
1842 (defcustom org-log-repeat 'time
1843 "Non-nil means, record moving through the DONE state when triggering repeat.
1844 An auto-repeating tasks is immediately switched back to TODO when marked
1845 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1846 the TODO keyword definition, or recording a closing note by setting
1847 `org-log-done', there will be no record of the task moving through DONE.
1848 This variable forces taking a note anyway. Possible values are:
1850 nil Don't force a record
1851 time Record a time stamp
1852 note Record a note
1854 This option can also be set with on a per-file-basis with
1856 #+STARTUP: logrepeat
1857 #+STARTUP: lognoterepeat
1858 #+STARTUP: nologrepeat
1860 You can have local logging settings for a subtree by setting the LOGGING
1861 property to one or more of these keywords."
1862 :group 'org-todo
1863 :group 'org-progress
1864 :type '(choice
1865 (const :tag "Don't force a record" nil)
1866 (const :tag "Force recording the DONE state" time)
1867 (const :tag "Force recording a note with the DONE state" note)))
1870 (defgroup org-priorities nil
1871 "Priorities in Org-mode."
1872 :tag "Org Priorities"
1873 :group 'org-todo)
1875 (defcustom org-highest-priority ?A
1876 "The highest priority of TODO items. A character like ?A, ?B etc.
1877 Must have a smaller ASCII number than `org-lowest-priority'."
1878 :group 'org-priorities
1879 :type 'character)
1881 (defcustom org-lowest-priority ?C
1882 "The lowest priority of TODO items. A character like ?A, ?B etc.
1883 Must have a larger ASCII number than `org-highest-priority'."
1884 :group 'org-priorities
1885 :type 'character)
1887 (defcustom org-default-priority ?B
1888 "The default priority of TODO items.
1889 This is the priority an item get if no explicit priority is given."
1890 :group 'org-priorities
1891 :type 'character)
1893 (defcustom org-priority-start-cycle-with-default t
1894 "Non-nil means, start with default priority when starting to cycle.
1895 When this is nil, the first step in the cycle will be (depending on the
1896 command used) one higher or lower that the default priority."
1897 :group 'org-priorities
1898 :type 'boolean)
1900 (defgroup org-time nil
1901 "Options concerning time stamps and deadlines in Org-mode."
1902 :tag "Org Time"
1903 :group 'org)
1905 (defcustom org-insert-labeled-timestamps-at-point nil
1906 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1907 When nil, these labeled time stamps are forces into the second line of an
1908 entry, just after the headline. When scheduling from the global TODO list,
1909 the time stamp will always be forced into the second line."
1910 :group 'org-time
1911 :type 'boolean)
1913 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1914 "Formats for `format-time-string' which are used for time stamps.
1915 It is not recommended to change this constant.")
1917 (defcustom org-time-stamp-rounding-minutes '(0 5)
1918 "Number of minutes to round time stamps to.
1919 These are two values, the first applies when first creating a time stamp.
1920 The second applies when changing it with the commands `S-up' and `S-down'.
1921 When changing the time stamp, this means that it will change in steps
1922 of N minutes, as given by the second value.
1924 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1925 numbers should be factors of 60, so for example 5, 10, 15.
1927 When this is larger than 1, you can still force an exact time-stamp by using
1928 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1929 and by using a prefix arg to `S-up/down' to specify the exact number
1930 of minutes to shift."
1931 :group 'org-time
1932 :get '(lambda (var) ; Make sure all entries have 5 elements
1933 (if (integerp (default-value var))
1934 (list (default-value var) 5)
1935 (default-value var)))
1936 :type '(list
1937 (integer :tag "when inserting times")
1938 (integer :tag "when modifying times")))
1940 ;; Normalize old customizations of this variable.
1941 (when (integerp org-time-stamp-rounding-minutes)
1942 (setq org-time-stamp-rounding-minutes
1943 (list org-time-stamp-rounding-minutes
1944 org-time-stamp-rounding-minutes)))
1946 (defcustom org-display-custom-times nil
1947 "Non-nil means, overlay custom formats over all time stamps.
1948 The formats are defined through the variable `org-time-stamp-custom-formats'.
1949 To turn this on on a per-file basis, insert anywhere in the file:
1950 #+STARTUP: customtime"
1951 :group 'org-time
1952 :set 'set-default
1953 :type 'sexp)
1954 (make-variable-buffer-local 'org-display-custom-times)
1956 (defcustom org-time-stamp-custom-formats
1957 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1958 "Custom formats for time stamps. See `format-time-string' for the syntax.
1959 These are overlayed over the default ISO format if the variable
1960 `org-display-custom-times' is set. Time like %H:%M should be at the
1961 end of the second format."
1962 :group 'org-time
1963 :type 'sexp)
1965 (defun org-time-stamp-format (&optional long inactive)
1966 "Get the right format for a time string."
1967 (let ((f (if long (cdr org-time-stamp-formats)
1968 (car org-time-stamp-formats))))
1969 (if inactive
1970 (concat "[" (substring f 1 -1) "]")
1971 f)))
1973 (defcustom org-time-clocksum-format "%d:%02d"
1974 "The format string used when creating CLOCKSUM lines, or when
1975 org-mode generates a time duration."
1976 :group 'org-time
1977 :type 'string)
1979 (defcustom org-deadline-warning-days 14
1980 "No. of days before expiration during which a deadline becomes active.
1981 This variable governs the display in sparse trees and in the agenda.
1982 When 0 or negative, it means use this number (the absolute value of it)
1983 even if a deadline has a different individual lead time specified."
1984 :group 'org-time
1985 :group 'org-agenda-daily/weekly
1986 :type 'number)
1988 (defcustom org-read-date-prefer-future t
1989 "Non-nil means, assume future for incomplete date input from user.
1990 This affects the following situations:
1991 1. The user gives a day, but no month.
1992 For example, if today is the 15th, and you enter \"3\", Org-mode will
1993 read this as the third of *next* month. However, if you enter \"17\",
1994 it will be considered as *this* month.
1995 2. The user gives a month but not a year.
1996 For example, if it is april and you enter \"feb 2\", this will be read
1997 as feb 2, *next* year. \"May 5\", however, will be this year.
1999 Currently this does not work for ISO week specifications.
2001 When this option is nil, the current month and year will always be used
2002 as defaults."
2003 :group 'org-time
2004 :type 'boolean)
2006 (defcustom org-read-date-display-live t
2007 "Non-nil means, display current interpretation of date prompt live.
2008 This display will be in an overlay, in the minibuffer."
2009 :group 'org-time
2010 :type 'boolean)
2012 (defcustom org-read-date-popup-calendar t
2013 "Non-nil means, pop up a calendar when prompting for a date.
2014 In the calendar, the date can be selected with mouse-1. However, the
2015 minibuffer will also be active, and you can simply enter the date as well.
2016 When nil, only the minibuffer will be available."
2017 :group 'org-time
2018 :type 'boolean)
2019 (if (fboundp 'defvaralias)
2020 (defvaralias 'org-popup-calendar-for-date-prompt
2021 'org-read-date-popup-calendar))
2023 (defcustom org-extend-today-until 0
2024 "The hour when your day really ends. Must be an integer.
2025 This has influence for the following applications:
2026 - When switching the agenda to \"today\". It it is still earlier than
2027 the time given here, the day recognized as TODAY is actually yesterday.
2028 - When a date is read from the user and it is still before the time given
2029 here, the current date and time will be assumed to be yesterday, 23:59.
2030 Also, timestamps inserted in remember templates follow this rule.
2032 IMPORTANT: This is a feature whose implementation is and likely will
2033 remain incomplete. Really, it is only here because past midnight seems to
2034 be the favorite working time of John Wiegley :-)"
2035 :group 'org-time
2036 :type 'number)
2038 (defcustom org-edit-timestamp-down-means-later nil
2039 "Non-nil means, S-down will increase the time in a time stamp.
2040 When nil, S-up will increase."
2041 :group 'org-time
2042 :type 'boolean)
2044 (defcustom org-calendar-follow-timestamp-change t
2045 "Non-nil means, make the calendar window follow timestamp changes.
2046 When a timestamp is modified and the calendar window is visible, it will be
2047 moved to the new date."
2048 :group 'org-time
2049 :type 'boolean)
2051 (defgroup org-tags nil
2052 "Options concerning tags in Org-mode."
2053 :tag "Org Tags"
2054 :group 'org)
2056 (defcustom org-tag-alist nil
2057 "List of tags allowed in Org-mode files.
2058 When this list is nil, Org-mode will base TAG input on what is already in the
2059 buffer.
2060 The value of this variable is an alist, the car of each entry must be a
2061 keyword as a string, the cdr may be a character that is used to select
2062 that tag through the fast-tag-selection interface.
2063 See the manual for details."
2064 :group 'org-tags
2065 :type '(repeat
2066 (choice
2067 (cons (string :tag "Tag name")
2068 (character :tag "Access char"))
2069 (const :tag "Start radio group" (:startgroup))
2070 (const :tag "End radio group" (:endgroup))
2071 (const :tag "New line" (:newline)))))
2073 (defvar org-file-tags nil
2074 "List of tags that can be inherited by all entries in the file.
2075 The tags will be inherited if the variable `org-use-tag-inheritance'
2076 says they should be.
2077 This variable is populated from #+TAG lines.")
2079 (defcustom org-use-fast-tag-selection 'auto
2080 "Non-nil means, use fast tag selection scheme.
2081 This is a special interface to select and deselect tags with single keys.
2082 When nil, fast selection is never used.
2083 When the symbol `auto', fast selection is used if and only if selection
2084 characters for tags have been configured, either through the variable
2085 `org-tag-alist' or through a #+TAGS line in the buffer.
2086 When t, fast selection is always used and selection keys are assigned
2087 automatically if necessary."
2088 :group 'org-tags
2089 :type '(choice
2090 (const :tag "Always" t)
2091 (const :tag "Never" nil)
2092 (const :tag "When selection characters are configured" 'auto)))
2094 (defcustom org-fast-tag-selection-single-key nil
2095 "Non-nil means, fast tag selection exits after first change.
2096 When nil, you have to press RET to exit it.
2097 During fast tag selection, you can toggle this flag with `C-c'.
2098 This variable can also have the value `expert'. In this case, the window
2099 displaying the tags menu is not even shown, until you press C-c again."
2100 :group 'org-tags
2101 :type '(choice
2102 (const :tag "No" nil)
2103 (const :tag "Yes" t)
2104 (const :tag "Expert" expert)))
2106 (defvar org-fast-tag-selection-include-todo nil
2107 "Non-nil means, fast tags selection interface will also offer TODO states.
2108 This is an undocumented feature, you should not rely on it.")
2110 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2111 "The column to which tags should be indented in a headline.
2112 If this number is positive, it specifies the column. If it is negative,
2113 it means that the tags should be flushright to that column. For example,
2114 -80 works well for a normal 80 character screen."
2115 :group 'org-tags
2116 :type 'integer)
2118 (defcustom org-auto-align-tags t
2119 "Non-nil means, realign tags after pro/demotion of TODO state change.
2120 These operations change the length of a headline and therefore shift
2121 the tags around. With this options turned on, after each such operation
2122 the tags are again aligned to `org-tags-column'."
2123 :group 'org-tags
2124 :type 'boolean)
2126 (defcustom org-use-tag-inheritance t
2127 "Non-nil means, tags in levels apply also for sublevels.
2128 When nil, only the tags directly given in a specific line apply there.
2129 This may also be a list of tags that should be inherited, or a regexp that
2130 matches tags that should be inherited. Additional control is possible
2131 with the variable `org-tags-exclude-from-inheritance' which gives an
2132 explicit list of tags to be excluded from inheritance., even if the value of
2133 `org-use-tag-inheritance' would select it for inheritance.
2135 If this option is t, a match early-on in a tree can lead to a large
2136 number of matches in the subtree when constructing the agenda or creating
2137 a sparse tree. If you only want to see the first match in a tree during
2138 a search, check out the variable `org-tags-match-list-sublevels'."
2139 :group 'org-tags
2140 :type '(choice
2141 (const :tag "Not" nil)
2142 (const :tag "Always" t)
2143 (repeat :tag "Specific tags" (string :tag "Tag"))
2144 (regexp :tag "Tags matched by regexp")))
2146 (defcustom org-tags-exclude-from-inheritance nil
2147 "List of tags that should never be inherited.
2148 This is a way to exclude a few tags from inheritance. For way to do
2149 the opposite, to actively allow inheritance for selected tags,
2150 see the variable `org-use-tag-inheritance'."
2151 :group 'org-tags
2152 :type '(repeat (string :tag "Tag")))
2154 (defun org-tag-inherit-p (tag)
2155 "Check if TAG is one that should be inherited."
2156 (cond
2157 ((member tag org-tags-exclude-from-inheritance) nil)
2158 ((eq org-use-tag-inheritance t) t)
2159 ((not org-use-tag-inheritance) nil)
2160 ((stringp org-use-tag-inheritance)
2161 (string-match org-use-tag-inheritance tag))
2162 ((listp org-use-tag-inheritance)
2163 (member tag org-use-tag-inheritance))
2164 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2166 (defcustom org-tags-match-list-sublevels t
2167 "Non-nil means list also sublevels of headlines matching tag search.
2168 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2169 the sublevels of a headline matching a tag search often also match
2170 the same search. Listing all of them can create very long lists.
2171 Setting this variable to nil causes subtrees of a match to be skipped.
2172 This option is off by default, because inheritance in on. If you turn
2173 inheritance off, you very likely want to turn this option on.
2175 As a special case, if the tag search is restricted to TODO items, the
2176 value of this variable is ignored and sublevels are always checked, to
2177 make sure all corresponding TODO items find their way into the list.
2179 This variable is semi-obsolete and probably should always be true. It
2180 is better to limit inheritance to certain tags using the variables
2181 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2182 :group 'org-tags
2183 :type 'boolean)
2185 (defvar org-tags-history nil
2186 "History of minibuffer reads for tags.")
2187 (defvar org-last-tags-completion-table nil
2188 "The last used completion table for tags.")
2189 (defvar org-after-tags-change-hook nil
2190 "Hook that is run after the tags in a line have changed.")
2192 (defgroup org-properties nil
2193 "Options concerning properties in Org-mode."
2194 :tag "Org Properties"
2195 :group 'org)
2197 (defcustom org-property-format "%-10s %s"
2198 "How property key/value pairs should be formatted by `indent-line'.
2199 When `indent-line' hits a property definition, it will format the line
2200 according to this format, mainly to make sure that the values are
2201 lined-up with respect to each other."
2202 :group 'org-properties
2203 :type 'string)
2205 (defcustom org-use-property-inheritance nil
2206 "Non-nil means, properties apply also for sublevels.
2208 This setting is chiefly used during property searches. Turning it on can
2209 cause significant overhead when doing a search, which is why it is not
2210 on by default.
2212 When nil, only the properties directly given in the current entry count.
2213 When t, every property is inherited. The value may also be a list of
2214 properties that should have inheritance, or a regular expression matching
2215 properties that should be inherited.
2217 However, note that some special properties use inheritance under special
2218 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2219 and the properties ending in \"_ALL\" when they are used as descriptor
2220 for valid values of a property.
2222 Note for programmers:
2223 When querying an entry with `org-entry-get', you can control if inheritance
2224 should be used. By default, `org-entry-get' looks only at the local
2225 properties. You can request inheritance by setting the inherit argument
2226 to t (to force inheritance) or to `selective' (to respect the setting
2227 in this variable)."
2228 :group 'org-properties
2229 :type '(choice
2230 (const :tag "Not" nil)
2231 (const :tag "Always" t)
2232 (repeat :tag "Specific properties" (string :tag "Property"))
2233 (regexp :tag "Properties matched by regexp")))
2235 (defun org-property-inherit-p (property)
2236 "Check if PROPERTY is one that should be inherited."
2237 (cond
2238 ((eq org-use-property-inheritance t) t)
2239 ((not org-use-property-inheritance) nil)
2240 ((stringp org-use-property-inheritance)
2241 (string-match org-use-property-inheritance property))
2242 ((listp org-use-property-inheritance)
2243 (member property org-use-property-inheritance))
2244 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2246 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2247 "The default column format, if no other format has been defined.
2248 This variable can be set on the per-file basis by inserting a line
2250 #+COLUMNS: %25ITEM ....."
2251 :group 'org-properties
2252 :type 'string)
2254 (defcustom org-columns-ellipses ".."
2255 "The ellipses to be used when a field in column view is truncated.
2256 When this is the empty string, as many characters as possible are shown,
2257 but then there will be no visual indication that the field has been truncated.
2258 When this is a string of length N, the last N characters of a truncated
2259 field are replaced by this string. If the column is narrower than the
2260 ellipses string, only part of the ellipses string will be shown."
2261 :group 'org-properties
2262 :type 'string)
2264 (defcustom org-columns-modify-value-for-display-function nil
2265 "Function that modifies values for display in column view.
2266 For example, it can be used to cut out a certain part from a time stamp.
2267 The function must take 2 arguments:
2269 column-title The title of the column (*not* the property name)
2270 value The value that should be modified.
2272 The function should return the value that should be displayed,
2273 or nil if the normal value should be used."
2274 :group 'org-properties
2275 :type 'function)
2277 (defcustom org-effort-property "Effort"
2278 "The property that is being used to keep track of effort estimates.
2279 Effort estimates given in this property need to have the format H:MM."
2280 :group 'org-properties
2281 :group 'org-progress
2282 :type '(string :tag "Property"))
2284 (defconst org-global-properties-fixed
2285 '(("VISIBILITY_ALL" . "folded children content all"))
2286 "List of property/value pairs that can be inherited by any entry.
2287 These are fixed values, for the preset properties.")
2290 (defcustom org-global-properties nil
2291 "List of property/value pairs that can be inherited by any entry.
2292 You can set buffer-local values for the same purpose in the variable
2293 `org-file-properties' this by adding lines like
2295 #+PROPERTY: NAME VALUE"
2296 :group 'org-properties
2297 :type '(repeat
2298 (cons (string :tag "Property")
2299 (string :tag "Value"))))
2301 (defvar org-file-properties nil
2302 "List of property/value pairs that can be inherited by any entry.
2303 Valid for the current buffer.
2304 This variable is populated from #+PROPERTY lines.")
2305 (make-variable-buffer-local 'org-file-properties)
2307 (defgroup org-agenda nil
2308 "Options concerning agenda views in Org-mode."
2309 :tag "Org Agenda"
2310 :group 'org)
2312 (defvar org-category nil
2313 "Variable used by org files to set a category for agenda display.
2314 Such files should use a file variable to set it, for example
2316 # -*- mode: org; org-category: \"ELisp\"
2318 or contain a special line
2320 #+CATEGORY: ELisp
2322 If the file does not specify a category, then file's base name
2323 is used instead.")
2324 (make-variable-buffer-local 'org-category)
2325 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2327 (defcustom org-agenda-files nil
2328 "The files to be used for agenda display.
2329 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2330 \\[org-remove-file]. You can also use customize to edit the list.
2332 If an entry is a directory, all files in that directory that are matched by
2333 `org-agenda-file-regexp' will be part of the file list.
2335 If the value of the variable is not a list but a single file name, then
2336 the list of agenda files is actually stored and maintained in that file, one
2337 agenda file per line."
2338 :group 'org-agenda
2339 :type '(choice
2340 (repeat :tag "List of files and directories" file)
2341 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2343 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2344 "Regular expression to match files for `org-agenda-files'.
2345 If any element in the list in that variable contains a directory instead
2346 of a normal file, all files in that directory that are matched by this
2347 regular expression will be included."
2348 :group 'org-agenda
2349 :type 'regexp)
2351 (defcustom org-agenda-text-search-extra-files nil
2352 "List of extra files to be searched by text search commands.
2353 These files will be search in addition to the agenda files by the
2354 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2355 Note that these files will only be searched for text search commands,
2356 not for the other agenda views like todo lists, tag searches or the weekly
2357 agenda. This variable is intended to list notes and possibly archive files
2358 that should also be searched by these two commands.
2359 In fact, if the first element in the list is the symbol `agenda-archives',
2360 than all archive files of all agenda files will be added to the search
2361 scope."
2362 :group 'org-agenda
2363 :type '(set :greedy t
2364 (const :tag "Agenda Archives" agenda-archives)
2365 (repeat :inline t (file))))
2367 (if (fboundp 'defvaralias)
2368 (defvaralias 'org-agenda-multi-occur-extra-files
2369 'org-agenda-text-search-extra-files))
2371 (defcustom org-agenda-skip-unavailable-files nil
2372 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2373 A nil value means to remove them, after a query, from the list."
2374 :group 'org-agenda
2375 :type 'boolean)
2377 (defcustom org-calendar-to-agenda-key [?c]
2378 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2379 The command `org-calendar-goto-agenda' will be bound to this key. The
2380 default is the character `c' because then `c' can be used to switch back and
2381 forth between agenda and calendar."
2382 :group 'org-agenda
2383 :type 'sexp)
2385 (defcustom org-calendar-agenda-action-key [?k]
2386 "The key to be installed in `calendar-mode-map' for agenda-action.
2387 The command `org-agenda-action' will be bound to this key. The
2388 default is the character `k' because we use the same key in the agenda."
2389 :group 'org-agenda
2390 :type 'sexp)
2392 (eval-after-load "calendar"
2393 '(progn
2394 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2395 'org-calendar-goto-agenda)
2396 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2397 'org-agenda-action)))
2399 (defgroup org-latex nil
2400 "Options for embedding LaTeX code into Org-mode."
2401 :tag "Org LaTeX"
2402 :group 'org)
2404 (defcustom org-format-latex-options
2405 '(:foreground default :background default :scale 1.0
2406 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2407 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2408 "Options for creating images from LaTeX fragments.
2409 This is a property list with the following properties:
2410 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2411 `default' means use the foreground of the default face.
2412 :background the background color, or \"Transparent\".
2413 `default' means use the background of the default face.
2414 :scale a scaling factor for the size of the images.
2415 :html-foreground, :html-background, :html-scale
2416 the same numbers for HTML export.
2417 :matchers a list indicating which matchers should be used to
2418 find LaTeX fragments. Valid members of this list are:
2419 \"begin\" find environments
2420 \"$1\" find single characters surrounded by $.$
2421 \"$\" find math expressions surrounded by $...$
2422 \"$$\" find math expressions surrounded by $$....$$
2423 \"\\(\" find math expressions surrounded by \\(...\\)
2424 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2425 :group 'org-latex
2426 :type 'plist)
2428 (defcustom org-format-latex-header "\\documentclass{article}
2429 \\usepackage{fullpage} % do not remove
2430 \\usepackage{amssymb}
2431 \\usepackage[usenames]{color}
2432 \\usepackage{amsmath}
2433 \\usepackage{latexsym}
2434 \\usepackage[mathscr]{eucal}
2435 \\pagestyle{empty} % do not remove"
2436 "The document header used for processing LaTeX fragments."
2437 :group 'org-latex
2438 :type 'string)
2441 (defgroup org-font-lock nil
2442 "Font-lock settings for highlighting in Org-mode."
2443 :tag "Org Font Lock"
2444 :group 'org)
2446 (defcustom org-level-color-stars-only nil
2447 "Non-nil means fontify only the stars in each headline.
2448 When nil, the entire headline is fontified.
2449 Changing it requires restart of `font-lock-mode' to become effective
2450 also in regions already fontified."
2451 :group 'org-font-lock
2452 :type 'boolean)
2454 (defcustom org-hide-leading-stars nil
2455 "Non-nil means, hide the first N-1 stars in a headline.
2456 This works by using the face `org-hide' for these stars. This
2457 face is white for a light background, and black for a dark
2458 background. You may have to customize the face `org-hide' to
2459 make this work.
2460 Changing it requires restart of `font-lock-mode' to become effective
2461 also in regions already fontified.
2462 You may also set this on a per-file basis by adding one of the following
2463 lines to the buffer:
2465 #+STARTUP: hidestars
2466 #+STARTUP: showstars"
2467 :group 'org-font-lock
2468 :type 'boolean)
2470 (defcustom org-fontify-done-headline nil
2471 "Non-nil means, change the face of a headline if it is marked DONE.
2472 Normally, only the TODO/DONE keyword indicates the state of a headline.
2473 When this is non-nil, the headline after the keyword is set to the
2474 `org-headline-done' as an additional indication."
2475 :group 'org-font-lock
2476 :type 'boolean)
2478 (defcustom org-fontify-emphasized-text t
2479 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2480 Changing this variable requires a restart of Emacs to take effect."
2481 :group 'org-font-lock
2482 :type 'boolean)
2484 (defcustom org-highlight-latex-fragments-and-specials nil
2485 "Non-nil means, fontify what is treated specially by the exporters."
2486 :group 'org-font-lock
2487 :type 'boolean)
2489 (defcustom org-hide-emphasis-markers nil
2490 "Non-nil mean font-lock should hide the emphasis marker characters."
2491 :group 'org-font-lock
2492 :type 'boolean)
2494 (defvar org-emph-re nil
2495 "Regular expression for matching emphasis.")
2496 (defvar org-verbatim-re nil
2497 "Regular expression for matching verbatim text.")
2498 (defvar org-emphasis-regexp-components) ; defined just below
2499 (defvar org-emphasis-alist) ; defined just below
2500 (defun org-set-emph-re (var val)
2501 "Set variable and compute the emphasis regular expression."
2502 (set var val)
2503 (when (and (boundp 'org-emphasis-alist)
2504 (boundp 'org-emphasis-regexp-components)
2505 org-emphasis-alist org-emphasis-regexp-components)
2506 (let* ((e org-emphasis-regexp-components)
2507 (pre (car e))
2508 (post (nth 1 e))
2509 (border (nth 2 e))
2510 (body (nth 3 e))
2511 (nl (nth 4 e))
2512 (body1 (concat body "*?"))
2513 (markers (mapconcat 'car org-emphasis-alist ""))
2514 (vmarkers (mapconcat
2515 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2516 org-emphasis-alist "")))
2517 ;; make sure special characters appear at the right position in the class
2518 (if (string-match "\\^" markers)
2519 (setq markers (concat (replace-match "" t t markers) "^")))
2520 (if (string-match "-" markers)
2521 (setq markers (concat (replace-match "" t t markers) "-")))
2522 (if (string-match "\\^" vmarkers)
2523 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2524 (if (string-match "-" vmarkers)
2525 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2526 (if (> nl 0)
2527 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2528 (int-to-string nl) "\\}")))
2529 ;; Make the regexp
2530 (setq org-emph-re
2531 (concat "\\([" pre "]\\|^\\)"
2532 "\\("
2533 "\\([" markers "]\\)"
2534 "\\("
2535 "[^" border "]\\|"
2536 "[^" border "]"
2537 body1
2538 "[^" border "]"
2539 "\\)"
2540 "\\3\\)"
2541 "\\([" post "]\\|$\\)"))
2542 (setq org-verbatim-re
2543 (concat "\\([" pre "]\\|^\\)"
2544 "\\("
2545 "\\([" vmarkers "]\\)"
2546 "\\("
2547 "[^" border "]\\|"
2548 "[^" border "]"
2549 body1
2550 "[^" border "]"
2551 "\\)"
2552 "\\3\\)"
2553 "\\([" post "]\\|$\\)")))))
2555 (defcustom org-emphasis-regexp-components
2556 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2557 "Components used to build the regular expression for emphasis.
2558 This is a list with 6 entries. Terminology: In an emphasis string
2559 like \" *strong word* \", we call the initial space PREMATCH, the final
2560 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2561 and \"trong wor\" is the body. The different components in this variable
2562 specify what is allowed/forbidden in each part:
2564 pre Chars allowed as prematch. Beginning of line will be allowed too.
2565 post Chars allowed as postmatch. End of line will be allowed too.
2566 border The chars *forbidden* as border characters.
2567 body-regexp A regexp like \".\" to match a body character. Don't use
2568 non-shy groups here, and don't allow newline here.
2569 newline The maximum number of newlines allowed in an emphasis exp.
2571 Use customize to modify this, or restart Emacs after changing it."
2572 :group 'org-font-lock
2573 :set 'org-set-emph-re
2574 :type '(list
2575 (sexp :tag "Allowed chars in pre ")
2576 (sexp :tag "Allowed chars in post ")
2577 (sexp :tag "Forbidden chars in border ")
2578 (sexp :tag "Regexp for body ")
2579 (integer :tag "number of newlines allowed")
2580 (option (boolean :tag "Please ignore this button"))))
2582 (defcustom org-emphasis-alist
2583 `(("*" bold "<b>" "</b>")
2584 ("/" italic "<i>" "</i>")
2585 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2586 ("=" org-code "<code>" "</code>" verbatim)
2587 ("~" org-verbatim "<code>" "</code>" verbatim)
2588 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2589 "<del>" "</del>")
2591 "Special syntax for emphasized text.
2592 Text starting and ending with a special character will be emphasized, for
2593 example *bold*, _underlined_ and /italic/. This variable sets the marker
2594 characters, the face to be used by font-lock for highlighting in Org-mode
2595 Emacs buffers, and the HTML tags to be used for this.
2596 Use customize to modify this, or restart Emacs after changing it."
2597 :group 'org-font-lock
2598 :set 'org-set-emph-re
2599 :type '(repeat
2600 (list
2601 (string :tag "Marker character")
2602 (choice
2603 (face :tag "Font-lock-face")
2604 (plist :tag "Face property list"))
2605 (string :tag "HTML start tag")
2606 (string :tag "HTML end tag")
2607 (option (const verbatim)))))
2609 ;;; Miscellaneous options
2611 (defgroup org-completion nil
2612 "Completion in Org-mode."
2613 :tag "Org Completion"
2614 :group 'org)
2616 (defcustom org-completion-use-ido nil
2617 "Non-nil means, use ido completion wherever possible.
2618 Note that `ido-mode' must be active for this variable to be relevant.
2619 If you decide to turn this variable on, you might well want to turn off
2620 `org-outline-path-complete-in-steps'."
2621 :group 'org-completion
2622 :type 'boolean)
2624 (defcustom org-completion-fallback-command 'hippie-expand
2625 "The expansion command called by \\[org-complete] in normal context.
2626 Normal means, no org-mode-specific context."
2627 :group 'org-completion
2628 :type 'function)
2630 ;;; Functions and variables from ther packages
2631 ;; Declared here to avoid compiler warnings
2633 ;; XEmacs only
2634 (defvar outline-mode-menu-heading)
2635 (defvar outline-mode-menu-show)
2636 (defvar outline-mode-menu-hide)
2637 (defvar zmacs-regions) ; XEmacs regions
2639 ;; Emacs only
2640 (defvar mark-active)
2642 ;; Various packages
2643 (declare-function find-library-name "find-func" (library))
2644 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2645 (declare-function calendar-forward-day "cal-move" (arg))
2646 (declare-function calendar-goto-date "cal-move" (date))
2647 (declare-function calendar-goto-today "cal-move" ())
2648 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2649 (defvar calc-embedded-close-formula)
2650 (defvar calc-embedded-open-formula)
2651 (declare-function cdlatex-tab "ext:cdlatex" ())
2652 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2653 (defvar font-lock-unfontify-region-function)
2654 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2655 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2656 (defvar iswitchb-temp-buflist)
2657 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2658 (defvar org-agenda-tags-todo-honor-ignore-options)
2659 (declare-function org-agenda-skip "org-agenda" ())
2660 (declare-function org-format-agenda-item "org-agenda"
2661 (extra txt &optional category tags dotime noprefix remove-re))
2662 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2663 (declare-function org-agenda-change-all-lines "org-agenda"
2664 (newhead hdmarker &optional fixface just-this))
2665 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2666 (declare-function org-agenda-maybe-redo "org-agenda" ())
2667 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2668 (beg end))
2669 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2670 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2671 "org-agenda" (&optional end))
2673 (declare-function parse-time-string "parse-time" (string))
2674 (declare-function remember "remember" (&optional initial))
2675 (declare-function remember-buffer-desc "remember" ())
2676 (declare-function remember-finalize "remember" ())
2677 (defvar remember-save-after-remembering)
2678 (defvar remember-data-file)
2679 (defvar remember-register)
2680 (defvar remember-buffer)
2681 (defvar remember-handler-functions)
2682 (defvar remember-annotation-functions)
2683 (defvar texmathp-why)
2684 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2685 (declare-function table--at-cell-p "table" (position &optional object at-column))
2687 (defvar w3m-current-url)
2688 (defvar w3m-current-title)
2690 (defvar org-latex-regexps)
2692 ;;; Autoload and prepare some org modules
2694 ;; Some table stuff that needs to be defined here, because it is used
2695 ;; by the functions setting up org-mode or checking for table context.
2697 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2698 "Detects an org-type or table-type table.")
2699 (defconst org-table-line-regexp "^[ \t]*|"
2700 "Detects an org-type table line.")
2701 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2702 "Detects an org-type table line.")
2703 (defconst org-table-hline-regexp "^[ \t]*|-"
2704 "Detects an org-type table hline.")
2705 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2706 "Detects a table-type table hline.")
2707 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2708 "Searching from within a table (any type) this finds the first line
2709 outside the table.")
2711 ;; Autoload the functions in org-table.el that are needed by functions here.
2713 (eval-and-compile
2714 (org-autoload "org-table"
2715 '(org-table-align org-table-begin org-table-blank-field
2716 org-table-convert org-table-convert-region org-table-copy-down
2717 org-table-copy-region org-table-create
2718 org-table-create-or-convert-from-region
2719 org-table-create-with-table.el org-table-current-dline
2720 org-table-cut-region org-table-delete-column org-table-edit-field
2721 org-table-edit-formulas org-table-end org-table-eval-formula
2722 org-table-export org-table-field-info
2723 org-table-get-stored-formulas org-table-goto-column
2724 org-table-hline-and-move org-table-import org-table-insert-column
2725 org-table-insert-hline org-table-insert-row org-table-iterate
2726 org-table-justify-field-maybe org-table-kill-row
2727 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2728 org-table-move-column org-table-move-column-left
2729 org-table-move-column-right org-table-move-row
2730 org-table-move-row-down org-table-move-row-up
2731 org-table-next-field org-table-next-row org-table-paste-rectangle
2732 org-table-previous-field org-table-recalculate
2733 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2734 org-table-toggle-coordinate-overlays
2735 org-table-toggle-formula-debugger org-table-wrap-region
2736 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2738 (defun org-at-table-p (&optional table-type)
2739 "Return t if the cursor is inside an org-type table.
2740 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2741 (if org-enable-table-editor
2742 (save-excursion
2743 (beginning-of-line 1)
2744 (looking-at (if table-type org-table-any-line-regexp
2745 org-table-line-regexp)))
2746 nil))
2747 (defsubst org-table-p () (org-at-table-p))
2749 (defun org-at-table.el-p ()
2750 "Return t if and only if we are at a table.el table."
2751 (and (org-at-table-p 'any)
2752 (save-excursion
2753 (goto-char (org-table-begin 'any))
2754 (looking-at org-table1-hline-regexp))))
2755 (defun org-table-recognize-table.el ()
2756 "If there is a table.el table nearby, recognize it and move into it."
2757 (if org-table-tab-recognizes-table.el
2758 (if (org-at-table.el-p)
2759 (progn
2760 (beginning-of-line 1)
2761 (if (looking-at org-table-dataline-regexp)
2763 (if (looking-at org-table1-hline-regexp)
2764 (progn
2765 (beginning-of-line 2)
2766 (if (looking-at org-table-any-border-regexp)
2767 (beginning-of-line -1)))))
2768 (if (re-search-forward "|" (org-table-end t) t)
2769 (progn
2770 (require 'table)
2771 (if (table--at-cell-p (point))
2773 (message "recognizing table.el table...")
2774 (table-recognize-table)
2775 (message "recognizing table.el table...done")))
2776 (error "This should not happen..."))
2778 nil)
2779 nil))
2781 (defun org-at-table-hline-p ()
2782 "Return t if the cursor is inside a hline in a table."
2783 (if org-enable-table-editor
2784 (save-excursion
2785 (beginning-of-line 1)
2786 (looking-at org-table-hline-regexp))
2787 nil))
2789 (defvar org-table-clean-did-remove-column nil)
2791 (defun org-table-map-tables (function)
2792 "Apply FUNCTION to the start of all tables in the buffer."
2793 (save-excursion
2794 (save-restriction
2795 (widen)
2796 (goto-char (point-min))
2797 (while (re-search-forward org-table-any-line-regexp nil t)
2798 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2799 (beginning-of-line 1)
2800 (if (looking-at org-table-line-regexp)
2801 (save-excursion (funcall function)))
2802 (re-search-forward org-table-any-border-regexp nil 1))))
2803 (message "Mapping tables: done"))
2805 ;; Declare and autoload functions from org-exp.el
2807 (declare-function org-default-export-plist "org-exp")
2808 (declare-function org-infile-export-plist "org-exp")
2809 (declare-function org-get-current-options "org-exp")
2810 (eval-and-compile
2811 (org-autoload "org-exp"
2812 '(org-export org-export-as-ascii org-export-visible
2813 org-insert-export-options-template org-export-as-html-and-open
2814 org-export-as-html-batch org-export-as-html-to-buffer
2815 org-replace-region-by-html org-export-region-as-html
2816 org-export-as-html org-export-icalendar-this-file
2817 org-export-icalendar-all-agenda-files
2818 org-table-clean-before-export
2819 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2821 ;; Declare and autoload functions from org-agenda.el
2823 (eval-and-compile
2824 (org-autoload "org-agenda"
2825 '(org-agenda org-agenda-list org-search-view
2826 org-todo-list org-tags-view org-agenda-list-stuck-projects
2827 org-diary org-agenda-to-appt
2828 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2830 ;; Autoload org-remember
2832 (eval-and-compile
2833 (org-autoload "org-remember"
2834 '(org-remember-insinuate org-remember-annotation
2835 org-remember-apply-template org-remember org-remember-handler)))
2837 ;; Autoload org-clock.el
2840 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2841 (beg end))
2842 (declare-function org-clock-update-mode-line "org-clock" ())
2843 (defvar org-clock-start-time)
2844 (defvar org-clock-marker (make-marker)
2845 "Marker recording the last clock-in.")
2847 (eval-and-compile
2848 (org-autoload
2849 "org-clock"
2850 '(org-clock-in org-clock-out org-clock-cancel
2851 org-clock-goto org-clock-sum org-clock-display
2852 org-clock-remove-overlays org-clock-report
2853 org-clocktable-shift org-dblock-write:clocktable
2854 org-get-clocktable)))
2856 (defun org-clock-update-time-maybe ()
2857 "If this is a CLOCK line, update it and return t.
2858 Otherwise, return nil."
2859 (interactive)
2860 (save-excursion
2861 (beginning-of-line 1)
2862 (skip-chars-forward " \t")
2863 (when (looking-at org-clock-string)
2864 (let ((re (concat "[ \t]*" org-clock-string
2865 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2866 "\\([ \t]*=>.*\\)?\\)?"))
2867 ts te h m s neg)
2868 (cond
2869 ((not (looking-at re))
2870 nil)
2871 ((not (match-end 2))
2872 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2873 (> org-clock-marker (point))
2874 (<= org-clock-marker (point-at-eol)))
2875 ;; The clock is running here
2876 (setq org-clock-start-time
2877 (apply 'encode-time
2878 (org-parse-time-string (match-string 1))))
2879 (org-clock-update-mode-line)))
2881 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2882 (end-of-line 1)
2883 (setq ts (match-string 1)
2884 te (match-string 3))
2885 (setq s (- (time-to-seconds
2886 (apply 'encode-time (org-parse-time-string te)))
2887 (time-to-seconds
2888 (apply 'encode-time (org-parse-time-string ts))))
2889 neg (< s 0)
2890 s (abs s)
2891 h (floor (/ s 3600))
2892 s (- s (* 3600 h))
2893 m (floor (/ s 60))
2894 s (- s (* 60 s)))
2895 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2896 t))))))
2898 (defun org-check-running-clock ()
2899 "Check if the current buffer contains the running clock.
2900 If yes, offer to stop it and to save the buffer with the changes."
2901 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2902 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2903 (buffer-name))))
2904 (org-clock-out)
2905 (when (y-or-n-p "Save changed buffer?")
2906 (save-buffer))))
2908 (defun org-clocktable-try-shift (dir n)
2909 "Check if this line starts a clock table, if yes, shift the time block."
2910 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2911 (org-clocktable-shift dir n)))
2913 ;; Autoload org-timer.el
2915 ;(declare-function org-timer "org-timer")
2917 (eval-and-compile
2918 (org-autoload
2919 "org-timer"
2920 '(org-timer-start org-timer org-timer-item
2921 org-timer-change-times-in-region)))
2924 ;; Autoload archiving code
2925 ;; The stuff that is needed for cycling and tags has to be defined here.
2927 (defgroup org-archive nil
2928 "Options concerning archiving in Org-mode."
2929 :tag "Org Archive"
2930 :group 'org-structure)
2932 (defcustom org-archive-location "%s_archive::"
2933 "The location where subtrees should be archived.
2935 The value of this variable is a string, consisting of two parts,
2936 separated by a double-colon. The first part is a filename and
2937 the second part is a headline.
2939 When the filename is omitted, archiving happens in the same file.
2940 %s in the filename will be replaced by the current file
2941 name (without the directory part). Archiving to a different file
2942 is useful to keep archived entries from contributing to the
2943 Org-mode Agenda.
2945 The archived entries will be filed as subtrees of the specified
2946 headline. When the headline is omitted, the subtrees are simply
2947 filed away at the end of the file, as top-level entries. Also in
2948 the heading you can use %s to represent the file name, this can be
2949 useful when using the same archive for a number of different files.
2951 Here are a few examples:
2952 \"%s_archive::\"
2953 If the current file is Projects.org, archive in file
2954 Projects.org_archive, as top-level trees. This is the default.
2956 \"::* Archived Tasks\"
2957 Archive in the current file, under the top-level headline
2958 \"* Archived Tasks\".
2960 \"~/org/archive.org::\"
2961 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2963 \"~/org/archive.org::From %s\"
2964 Archive in file ~/org/archive.org (absolute path), und headlines
2965 \"From FILENAME\" where file name is the current file name.
2967 \"basement::** Finished Tasks\"
2968 Archive in file ./basement (relative path), as level 3 trees
2969 below the level 2 heading \"** Finished Tasks\".
2971 You may set this option on a per-file basis by adding to the buffer a
2972 line like
2974 #+ARCHIVE: basement::** Finished Tasks
2976 You may also define it locally for a subtree by setting an ARCHIVE property
2977 in the entry. If such a property is found in an entry, or anywhere up
2978 the hierarchy, it will be used."
2979 :group 'org-archive
2980 :type 'string)
2982 (defcustom org-archive-tag "ARCHIVE"
2983 "The tag that marks a subtree as archived.
2984 An archived subtree does not open during visibility cycling, and does
2985 not contribute to the agenda listings.
2986 After changing this, font-lock must be restarted in the relevant buffers to
2987 get the proper fontification."
2988 :group 'org-archive
2989 :group 'org-keywords
2990 :type 'string)
2992 (defcustom org-agenda-skip-archived-trees t
2993 "Non-nil means, the agenda will skip any items located in archived trees.
2994 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2995 variable is no longer recommended, you should leave it at the value t.
2996 Instead, use the key `v' to cycle the archives-mode in the agenda."
2997 :group 'org-archive
2998 :group 'org-agenda-skip
2999 :type 'boolean)
3001 (defcustom org-cycle-open-archived-trees nil
3002 "Non-nil means, `org-cycle' will open archived trees.
3003 An archived tree is a tree marked with the tag ARCHIVE.
3004 When nil, archived trees will stay folded. You can still open them with
3005 normal outline commands like `show-all', but not with the cycling commands."
3006 :group 'org-archive
3007 :group 'org-cycle
3008 :type 'boolean)
3010 (defcustom org-sparse-tree-open-archived-trees nil
3011 "Non-nil means sparse tree construction shows matches in archived trees.
3012 When nil, matches in these trees are highlighted, but the trees are kept in
3013 collapsed state."
3014 :group 'org-archive
3015 :group 'org-sparse-trees
3016 :type 'boolean)
3018 (defun org-cycle-hide-archived-subtrees (state)
3019 "Re-hide all archived subtrees after a visibility state change."
3020 (when (and (not org-cycle-open-archived-trees)
3021 (not (memq state '(overview folded))))
3022 (save-excursion
3023 (let* ((globalp (memq state '(contents all)))
3024 (beg (if globalp (point-min) (point)))
3025 (end (if globalp (point-max) (org-end-of-subtree t))))
3026 (org-hide-archived-subtrees beg end)
3027 (goto-char beg)
3028 (if (looking-at (concat ".*:" org-archive-tag ":"))
3029 (message "%s" (substitute-command-keys
3030 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3032 (defun org-force-cycle-archived ()
3033 "Cycle subtree even if it is archived."
3034 (interactive)
3035 (setq this-command 'org-cycle)
3036 (let ((org-cycle-open-archived-trees t))
3037 (call-interactively 'org-cycle)))
3039 (defun org-hide-archived-subtrees (beg end)
3040 "Re-hide all archived subtrees after a visibility state change."
3041 (save-excursion
3042 (let* ((re (concat ":" org-archive-tag ":")))
3043 (goto-char beg)
3044 (while (re-search-forward re end t)
3045 (and (org-on-heading-p) (hide-subtree))
3046 (org-end-of-subtree t)))))
3048 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3050 (eval-and-compile
3051 (org-autoload "org-archive"
3052 '(org-add-archive-files org-archive-subtree
3053 org-archive-to-archive-sibling org-toggle-archive-tag)))
3055 ;; Autoload Column View Code
3057 (declare-function org-columns-number-to-string "org-colview")
3058 (declare-function org-columns-get-format-and-top-level "org-colview")
3059 (declare-function org-columns-compute "org-colview")
3061 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3062 '(org-columns-number-to-string org-columns-get-format-and-top-level
3063 org-columns-compute org-agenda-columns org-columns-remove-overlays
3064 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3066 ;; Autoload ID code
3068 (declare-function org-id-store-link "org-id")
3069 (declare-function org-id-locations-load "org-id")
3070 (declare-function org-id-locations-save "org-id")
3071 (defvar org-id-track-globally)
3072 (org-autoload "org-id"
3073 '(org-id-get-create org-id-new org-id-copy org-id-get
3074 org-id-get-with-outline-path-completion
3075 org-id-get-with-outline-drilling
3076 org-id-goto org-id-find org-id-store-link))
3078 ;; Autoload Plotting Code
3080 (org-autoload "org-plot"
3081 '(org-plot/gnuplot))
3083 ;;; Variables for pre-computed regular expressions, all buffer local
3085 (defvar org-drawer-regexp nil
3086 "Matches first line of a hidden block.")
3087 (make-variable-buffer-local 'org-drawer-regexp)
3088 (defvar org-todo-regexp nil
3089 "Matches any of the TODO state keywords.")
3090 (make-variable-buffer-local 'org-todo-regexp)
3091 (defvar org-not-done-regexp nil
3092 "Matches any of the TODO state keywords except the last one.")
3093 (make-variable-buffer-local 'org-not-done-regexp)
3094 (defvar org-todo-line-regexp nil
3095 "Matches a headline and puts TODO state into group 2 if present.")
3096 (make-variable-buffer-local 'org-todo-line-regexp)
3097 (defvar org-complex-heading-regexp nil
3098 "Matches a headline and puts everything into groups:
3099 group 1: the stars
3100 group 2: The todo keyword, maybe
3101 group 3: Priority cookie
3102 group 4: True headline
3103 group 5: Tags")
3104 (make-variable-buffer-local 'org-complex-heading-regexp)
3105 (defvar org-todo-line-tags-regexp nil
3106 "Matches a headline and puts TODO state into group 2 if present.
3107 Also put tags into group 4 if tags are present.")
3108 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3109 (defvar org-nl-done-regexp nil
3110 "Matches newline followed by a headline with the DONE keyword.")
3111 (make-variable-buffer-local 'org-nl-done-regexp)
3112 (defvar org-looking-at-done-regexp nil
3113 "Matches the DONE keyword a point.")
3114 (make-variable-buffer-local 'org-looking-at-done-regexp)
3115 (defvar org-ds-keyword-length 12
3116 "Maximum length of the Deadline and SCHEDULED keywords.")
3117 (make-variable-buffer-local 'org-ds-keyword-length)
3118 (defvar org-deadline-regexp nil
3119 "Matches the DEADLINE keyword.")
3120 (make-variable-buffer-local 'org-deadline-regexp)
3121 (defvar org-deadline-time-regexp nil
3122 "Matches the DEADLINE keyword together with a time stamp.")
3123 (make-variable-buffer-local 'org-deadline-time-regexp)
3124 (defvar org-deadline-line-regexp nil
3125 "Matches the DEADLINE keyword and the rest of the line.")
3126 (make-variable-buffer-local 'org-deadline-line-regexp)
3127 (defvar org-scheduled-regexp nil
3128 "Matches the SCHEDULED keyword.")
3129 (make-variable-buffer-local 'org-scheduled-regexp)
3130 (defvar org-scheduled-time-regexp nil
3131 "Matches the SCHEDULED keyword together with a time stamp.")
3132 (make-variable-buffer-local 'org-scheduled-time-regexp)
3133 (defvar org-closed-time-regexp nil
3134 "Matches the CLOSED keyword together with a time stamp.")
3135 (make-variable-buffer-local 'org-closed-time-regexp)
3137 (defvar org-keyword-time-regexp nil
3138 "Matches any of the 4 keywords, together with the time stamp.")
3139 (make-variable-buffer-local 'org-keyword-time-regexp)
3140 (defvar org-keyword-time-not-clock-regexp nil
3141 "Matches any of the 3 keywords, together with the time stamp.")
3142 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3143 (defvar org-maybe-keyword-time-regexp nil
3144 "Matches a timestamp, possibly preceeded by a keyword.")
3145 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3146 (defvar org-planning-or-clock-line-re nil
3147 "Matches a line with planning or clock info.")
3148 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3150 (defconst org-plain-time-of-day-regexp
3151 (concat
3152 "\\(\\<[012]?[0-9]"
3153 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3154 "\\(--?"
3155 "\\(\\<[012]?[0-9]"
3156 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3157 "\\)?")
3158 "Regular expression to match a plain time or time range.
3159 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3160 groups carry important information:
3161 0 the full match
3162 1 the first time, range or not
3163 8 the second time, if it is a range.")
3165 (defconst org-plain-time-extension-regexp
3166 (concat
3167 "\\(\\<[012]?[0-9]"
3168 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3169 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3170 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3171 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3172 groups carry important information:
3173 0 the full match
3174 7 hours of duration
3175 9 minutes of duration")
3177 (defconst org-stamp-time-of-day-regexp
3178 (concat
3179 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3180 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3181 "\\(--?"
3182 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3183 "Regular expression to match a timestamp time or time range.
3184 After a match, the following groups carry important information:
3185 0 the full match
3186 1 date plus weekday, for backreferencing to make sure both times on same day
3187 2 the first time, range or not
3188 4 the second time, if it is a range.")
3190 (defconst org-startup-options
3191 '(("fold" org-startup-folded t)
3192 ("overview" org-startup-folded t)
3193 ("nofold" org-startup-folded nil)
3194 ("showall" org-startup-folded nil)
3195 ("content" org-startup-folded content)
3196 ("hidestars" org-hide-leading-stars t)
3197 ("showstars" org-hide-leading-stars nil)
3198 ("odd" org-odd-levels-only t)
3199 ("oddeven" org-odd-levels-only nil)
3200 ("align" org-startup-align-all-tables t)
3201 ("noalign" org-startup-align-all-tables nil)
3202 ("customtime" org-display-custom-times t)
3203 ("logdone" org-log-done time)
3204 ("lognotedone" org-log-done note)
3205 ("nologdone" org-log-done nil)
3206 ("lognoteclock-out" org-log-note-clock-out t)
3207 ("nolognoteclock-out" org-log-note-clock-out nil)
3208 ("logrepeat" org-log-repeat state)
3209 ("lognoterepeat" org-log-repeat note)
3210 ("nologrepeat" org-log-repeat nil)
3211 ("fninline" org-footnote-define-inline t)
3212 ("nofninline" org-footnote-define-inline nil)
3213 ("fnlocal" org-footnote-section nil)
3214 ("fnauto" org-footnote-auto-label t)
3215 ("fnprompt" org-footnote-auto-label nil)
3216 ("fnconfirm" org-footnote-auto-label confirm)
3217 ("fnplain" org-footnote-auto-label plain)
3218 ("constcgs" constants-unit-system cgs)
3219 ("constSI" constants-unit-system SI))
3220 "Variable associated with STARTUP options for org-mode.
3221 Each element is a list of three items: The startup options as written
3222 in the #+STARTUP line, the corresponding variable, and the value to
3223 set this variable to if the option is found. An optional forth element PUSH
3224 means to push this value onto the list in the variable.")
3226 (defun org-set-regexps-and-options ()
3227 "Precompute regular expressions for current buffer."
3228 (when (org-mode-p)
3229 (org-set-local 'org-todo-kwd-alist nil)
3230 (org-set-local 'org-todo-key-alist nil)
3231 (org-set-local 'org-todo-key-trigger nil)
3232 (org-set-local 'org-todo-keywords-1 nil)
3233 (org-set-local 'org-done-keywords nil)
3234 (org-set-local 'org-todo-heads nil)
3235 (org-set-local 'org-todo-sets nil)
3236 (org-set-local 'org-todo-log-states nil)
3237 (org-set-local 'org-file-properties nil)
3238 (org-set-local 'org-file-tags nil)
3239 (let ((re (org-make-options-regexp
3240 '("CATEGORY" "TODO" "COLUMNS"
3241 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3242 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3243 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3244 (splitre "[ \t]+")
3245 kwds kws0 kwsa key log value cat arch tags const links hw dws
3246 tail sep kws1 prio props ftags drawers
3247 ext-setup-or-nil setup-contents (start 0))
3248 (save-excursion
3249 (save-restriction
3250 (widen)
3251 (goto-char (point-min))
3252 (while (or (and ext-setup-or-nil
3253 (string-match re ext-setup-or-nil start)
3254 (setq start (match-end 0)))
3255 (and (setq ext-setup-or-nil nil start 0)
3256 (re-search-forward re nil t)))
3257 (setq key (upcase (match-string 1 ext-setup-or-nil))
3258 value (org-match-string-no-properties 2 ext-setup-or-nil))
3259 (cond
3260 ((equal key "CATEGORY")
3261 (if (string-match "[ \t]+$" value)
3262 (setq value (replace-match "" t t value)))
3263 (setq cat value))
3264 ((member key '("SEQ_TODO" "TODO"))
3265 (push (cons 'sequence (org-split-string value splitre)) kwds))
3266 ((equal key "TYP_TODO")
3267 (push (cons 'type (org-split-string value splitre)) kwds))
3268 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3269 ;; general TODO-like setup
3270 (push (cons (intern (downcase (match-string 1 key)))
3271 (org-split-string value splitre)) kwds))
3272 ((equal key "TAGS")
3273 (setq tags (append tags (if tags '("\\n") nil)
3274 (org-split-string value splitre))))
3275 ((equal key "COLUMNS")
3276 (org-set-local 'org-columns-default-format value))
3277 ((equal key "LINK")
3278 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3279 (push (cons (match-string 1 value)
3280 (org-trim (match-string 2 value)))
3281 links)))
3282 ((equal key "PRIORITIES")
3283 (setq prio (org-split-string value " +")))
3284 ((equal key "PROPERTY")
3285 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3286 (push (cons (match-string 1 value) (match-string 2 value))
3287 props)))
3288 ((equal key "FILETAGS")
3289 (when (string-match "\\S-" value)
3290 (setq ftags
3291 (append
3292 ftags
3293 (apply 'append
3294 (mapcar (lambda (x) (org-split-string x ":"))
3295 (org-split-string value)))))))
3296 ((equal key "DRAWERS")
3297 (setq drawers (org-split-string value splitre)))
3298 ((equal key "CONSTANTS")
3299 (setq const (append const (org-split-string value splitre))))
3300 ((equal key "STARTUP")
3301 (let ((opts (org-split-string value splitre))
3302 l var val)
3303 (while (setq l (pop opts))
3304 (when (setq l (assoc l org-startup-options))
3305 (setq var (nth 1 l) val (nth 2 l))
3306 (if (not (nth 3 l))
3307 (set (make-local-variable var) val)
3308 (if (not (listp (symbol-value var)))
3309 (set (make-local-variable var) nil))
3310 (set (make-local-variable var) (symbol-value var))
3311 (add-to-list var val))))))
3312 ((equal key "ARCHIVE")
3313 (string-match " *$" value)
3314 (setq arch (replace-match "" t t value))
3315 (remove-text-properties 0 (length arch)
3316 '(face t fontified t) arch))
3317 ((equal key "SETUPFILE")
3318 (setq setup-contents (org-file-contents
3319 (expand-file-name
3320 (org-remove-double-quotes value))
3321 'noerror))
3322 (if (not ext-setup-or-nil)
3323 (setq ext-setup-or-nil setup-contents start 0)
3324 (setq ext-setup-or-nil
3325 (concat (substring ext-setup-or-nil 0 start)
3326 "\n" setup-contents "\n"
3327 (substring ext-setup-or-nil start)))))
3328 ))))
3329 (when cat
3330 (org-set-local 'org-category (intern cat))
3331 (push (cons "CATEGORY" cat) props))
3332 (when prio
3333 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3334 (setq prio (mapcar 'string-to-char prio))
3335 (org-set-local 'org-highest-priority (nth 0 prio))
3336 (org-set-local 'org-lowest-priority (nth 1 prio))
3337 (org-set-local 'org-default-priority (nth 2 prio)))
3338 (and props (org-set-local 'org-file-properties (nreverse props)))
3339 (and ftags (org-set-local 'org-file-tags ftags))
3340 (and drawers (org-set-local 'org-drawers drawers))
3341 (and arch (org-set-local 'org-archive-location arch))
3342 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3343 ;; Process the TODO keywords
3344 (unless kwds
3345 ;; Use the global values as if they had been given locally.
3346 (setq kwds (default-value 'org-todo-keywords))
3347 (if (stringp (car kwds))
3348 (setq kwds (list (cons org-todo-interpretation
3349 (default-value 'org-todo-keywords)))))
3350 (setq kwds (reverse kwds)))
3351 (setq kwds (nreverse kwds))
3352 (let (inter kws kw)
3353 (while (setq kws (pop kwds))
3354 (let ((kws (or
3355 (run-hook-with-args-until-success
3356 'org-todo-setup-filter-hook kws)
3357 kws)))
3358 (setq inter (pop kws) sep (member "|" kws)
3359 kws0 (delete "|" (copy-sequence kws))
3360 kwsa nil
3361 kws1 (mapcar
3362 (lambda (x)
3363 ;; 1 2
3364 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3365 (progn
3366 (setq kw (match-string 1 x)
3367 key (and (match-end 2) (match-string 2 x))
3368 log (org-extract-log-state-settings x))
3369 (push (cons kw (and key (string-to-char key))) kwsa)
3370 (and log (push log org-todo-log-states))
3372 (error "Invalid TODO keyword %s" x)))
3373 kws0)
3374 kwsa (if kwsa (append '((:startgroup))
3375 (nreverse kwsa)
3376 '((:endgroup))))
3377 hw (car kws1)
3378 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3379 tail (list inter hw (car dws) (org-last dws))))
3380 (add-to-list 'org-todo-heads hw 'append)
3381 (push kws1 org-todo-sets)
3382 (setq org-done-keywords (append org-done-keywords dws nil))
3383 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3384 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3385 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3386 (setq org-todo-sets (nreverse org-todo-sets)
3387 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3388 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3389 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3390 ;; Process the constants
3391 (when const
3392 (let (e cst)
3393 (while (setq e (pop const))
3394 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3395 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3396 (setq org-table-formula-constants-local cst)))
3398 ;; Process the tags.
3399 (when tags
3400 (let (e tgs)
3401 (while (setq e (pop tags))
3402 (cond
3403 ((equal e "{") (push '(:startgroup) tgs))
3404 ((equal e "}") (push '(:endgroup) tgs))
3405 ((equal e "\\n") (push '(:newline) tgs))
3406 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3407 (push (cons (match-string 1 e)
3408 (string-to-char (match-string 2 e)))
3409 tgs))
3410 (t (push (list e) tgs))))
3411 (org-set-local 'org-tag-alist nil)
3412 (while (setq e (pop tgs))
3413 (or (and (stringp (car e))
3414 (assoc (car e) org-tag-alist))
3415 (push e org-tag-alist)))))
3417 ;; Compute the regular expressions and other local variables
3418 (if (not org-done-keywords)
3419 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3420 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3421 (length org-scheduled-string)
3422 (length org-clock-string)
3423 (length org-closed-string)))
3424 org-drawer-regexp
3425 (concat "^[ \t]*:\\("
3426 (mapconcat 'regexp-quote org-drawers "\\|")
3427 "\\):[ \t]*$")
3428 org-not-done-keywords
3429 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3430 org-todo-regexp
3431 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3432 "\\|") "\\)\\>")
3433 org-not-done-regexp
3434 (concat "\\<\\("
3435 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3436 "\\)\\>")
3437 org-todo-line-regexp
3438 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3439 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3440 "\\)\\>\\)?[ \t]*\\(.*\\)")
3441 org-complex-heading-regexp
3442 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3443 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3444 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3445 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3446 org-nl-done-regexp
3447 (concat "\n\\*+[ \t]+"
3448 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3449 "\\)" "\\>")
3450 org-todo-line-tags-regexp
3451 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3452 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3453 (org-re
3454 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3455 org-looking-at-done-regexp
3456 (concat "^" "\\(?:"
3457 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3458 "\\>")
3459 org-deadline-regexp (concat "\\<" org-deadline-string)
3460 org-deadline-time-regexp
3461 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3462 org-deadline-line-regexp
3463 (concat "\\<\\(" org-deadline-string "\\).*")
3464 org-scheduled-regexp
3465 (concat "\\<" org-scheduled-string)
3466 org-scheduled-time-regexp
3467 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3468 org-closed-time-regexp
3469 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3470 org-keyword-time-regexp
3471 (concat "\\<\\(" org-scheduled-string
3472 "\\|" org-deadline-string
3473 "\\|" org-closed-string
3474 "\\|" org-clock-string "\\)"
3475 " *[[<]\\([^]>]+\\)[]>]")
3476 org-keyword-time-not-clock-regexp
3477 (concat "\\<\\(" org-scheduled-string
3478 "\\|" org-deadline-string
3479 "\\|" org-closed-string
3480 "\\)"
3481 " *[[<]\\([^]>]+\\)[]>]")
3482 org-maybe-keyword-time-regexp
3483 (concat "\\(\\<\\(" org-scheduled-string
3484 "\\|" org-deadline-string
3485 "\\|" org-closed-string
3486 "\\|" org-clock-string "\\)\\)?"
3487 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3488 org-planning-or-clock-line-re
3489 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3490 "\\|" org-deadline-string
3491 "\\|" org-closed-string "\\|" org-clock-string
3492 "\\)\\>\\)")
3494 (org-compute-latex-and-specials-regexp)
3495 (org-set-font-lock-defaults))))
3497 (defun org-file-contents (file &optional noerror)
3498 "Return the contents of FILE, as a string."
3499 (if (or (not file)
3500 (not (file-readable-p file)))
3501 (if noerror
3502 (progn
3503 (message "Cannot read file %s" file)
3504 (ding) (sit-for 2)
3506 (error "Cannot read file %s" file))
3507 (with-temp-buffer
3508 (insert-file-contents file)
3509 (buffer-string))))
3511 (defun org-extract-log-state-settings (x)
3512 "Extract the log state setting from a TODO keyword string.
3513 This will extract info from a string like \"WAIT(w@/!)\"."
3514 (let (kw key log1 log2)
3515 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3516 (setq kw (match-string 1 x)
3517 key (and (match-end 2) (match-string 2 x))
3518 log1 (and (match-end 3) (match-string 3 x))
3519 log2 (and (match-end 4) (match-string 4 x)))
3520 (and (or log1 log2)
3521 (list kw
3522 (and log1 (if (equal log1 "!") 'time 'note))
3523 (and log2 (if (equal log2 "!") 'time 'note)))))))
3525 (defun org-remove-keyword-keys (list)
3526 "Remove a pair of parenthesis at the end of each string in LIST."
3527 (mapcar (lambda (x)
3528 (if (string-match "(.*)$" x)
3529 (substring x 0 (match-beginning 0))
3531 list))
3533 ;; FIXME: this could be done much better, using second characters etc.
3534 (defun org-assign-fast-keys (alist)
3535 "Assign fast keys to a keyword-key alist.
3536 Respect keys that are already there."
3537 (let (new e k c c1 c2 (char ?a))
3538 (while (setq e (pop alist))
3539 (cond
3540 ((equal e '(:startgroup)) (push e new))
3541 ((equal e '(:endgroup)) (push e new))
3542 ((equal e '(:newline)) (push e new))
3544 (setq k (car e) c2 nil)
3545 (if (cdr e)
3546 (setq c (cdr e))
3547 ;; automatically assign a character.
3548 (setq c1 (string-to-char
3549 (downcase (substring
3550 k (if (= (string-to-char k) ?@) 1 0)))))
3551 (if (or (rassoc c1 new) (rassoc c1 alist))
3552 (while (or (rassoc char new) (rassoc char alist))
3553 (setq char (1+ char)))
3554 (setq c2 c1))
3555 (setq c (or c2 char)))
3556 (push (cons k c) new))))
3557 (nreverse new)))
3559 ;;; Some variables used in various places
3561 (defvar org-window-configuration nil
3562 "Used in various places to store a window configuration.")
3563 (defvar org-finish-function nil
3564 "Function to be called when `C-c C-c' is used.
3565 This is for getting out of special buffers like remember.")
3568 ;; FIXME: Occasionally check by commenting these, to make sure
3569 ;; no other functions uses these, forgetting to let-bind them.
3570 (defvar entry)
3571 (defvar state)
3572 (defvar last-state)
3573 (defvar date)
3574 (defvar description)
3576 ;; Defined somewhere in this file, but used before definition.
3577 (defvar org-html-entities)
3578 (defvar org-struct-menu)
3579 (defvar org-org-menu)
3580 (defvar org-tbl-menu)
3581 (defvar org-agenda-keymap)
3583 ;;;; Define the Org-mode
3585 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3586 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22."))
3589 ;; We use a before-change function to check if a table might need
3590 ;; an update.
3591 (defvar org-table-may-need-update t
3592 "Indicates that a table might need an update.
3593 This variable is set by `org-before-change-function'.
3594 `org-table-align' sets it back to nil.")
3595 (defun org-before-change-function (beg end)
3596 "Every change indicates that a table might need an update."
3597 (setq org-table-may-need-update t))
3598 (defvar org-mode-map)
3599 (defvar org-mode-hook nil
3600 "Mode hook for Org-mode, run after the mode was turned on.")
3601 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3602 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3603 (defvar org-table-buffer-is-an nil)
3604 (defconst org-outline-regexp "\\*+ ")
3606 ;;;###autoload
3607 (define-derived-mode org-mode outline-mode "Org"
3608 "Outline-based notes management and organizer, alias
3609 \"Carsten's outline-mode for keeping track of everything.\"
3611 Org-mode develops organizational tasks around a NOTES file which
3612 contains information about projects as plain text. Org-mode is
3613 implemented on top of outline-mode, which is ideal to keep the content
3614 of large files well structured. It supports ToDo items, deadlines and
3615 time stamps, which magically appear in the diary listing of the Emacs
3616 calendar. Tables are easily created with a built-in table editor.
3617 Plain text URL-like links connect to websites, emails (VM), Usenet
3618 messages (Gnus), BBDB entries, and any files related to the project.
3619 For printing and sharing of notes, an Org-mode file (or a part of it)
3620 can be exported as a structured ASCII or HTML file.
3622 The following commands are available:
3624 \\{org-mode-map}"
3626 ;; Get rid of Outline menus, they are not needed
3627 ;; Need to do this here because define-derived-mode sets up
3628 ;; the keymap so late. Still, it is a waste to call this each time
3629 ;; we switch another buffer into org-mode.
3630 (if (featurep 'xemacs)
3631 (when (boundp 'outline-mode-menu-heading)
3632 ;; Assume this is Greg's port, it used easymenu
3633 (easy-menu-remove outline-mode-menu-heading)
3634 (easy-menu-remove outline-mode-menu-show)
3635 (easy-menu-remove outline-mode-menu-hide))
3636 (define-key org-mode-map [menu-bar headings] 'undefined)
3637 (define-key org-mode-map [menu-bar hide] 'undefined)
3638 (define-key org-mode-map [menu-bar show] 'undefined))
3640 (org-load-modules-maybe)
3641 (easy-menu-add org-org-menu)
3642 (easy-menu-add org-tbl-menu)
3643 (org-install-agenda-files-menu)
3644 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3645 (org-add-to-invisibility-spec '(org-cwidth))
3646 (when (featurep 'xemacs)
3647 (org-set-local 'line-move-ignore-invisible t))
3648 (org-set-local 'outline-regexp org-outline-regexp)
3649 (org-set-local 'outline-level 'org-outline-level)
3650 (when (and org-ellipsis
3651 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3652 (fboundp 'make-glyph-code))
3653 (unless org-display-table
3654 (setq org-display-table (make-display-table)))
3655 (set-display-table-slot
3656 org-display-table 4
3657 (vconcat (mapcar
3658 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3659 org-ellipsis)))
3660 (if (stringp org-ellipsis) org-ellipsis "..."))))
3661 (setq buffer-display-table org-display-table))
3662 (org-set-regexps-and-options)
3663 (when (and org-tag-faces (not org-tags-special-faces-re))
3664 ;; tag faces set outside customize.... force initialization.
3665 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3666 ;; Calc embedded
3667 (org-set-local 'calc-embedded-open-mode "# ")
3668 (modify-syntax-entry ?# "<")
3669 (modify-syntax-entry ?@ "w")
3670 (if org-startup-truncated (setq truncate-lines t))
3671 (org-set-local 'font-lock-unfontify-region-function
3672 'org-unfontify-region)
3673 ;; Activate before-change-function
3674 (org-set-local 'org-table-may-need-update t)
3675 (org-add-hook 'before-change-functions 'org-before-change-function nil
3676 'local)
3677 ;; Check for running clock before killing a buffer
3678 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3679 ;; Paragraphs and auto-filling
3680 (org-set-autofill-regexps)
3681 (setq indent-line-function 'org-indent-line-function)
3682 (org-update-radio-target-regexp)
3683 ;; Make sure dependence stuff works reliably, even for users who set it
3684 ;; too late :-(
3685 (if org-enforce-todo-dependencies
3686 (add-hook 'org-blocker-hook
3687 'org-block-todo-from-children-or-siblings)
3688 (remove-hook 'org-blocker-hook
3689 'org-block-todo-from-children-or-siblings))
3690 (if org-enforce-todo-checkbox-dependencies
3691 (add-hook 'org-blocker-hook
3692 'org-block-todo-from-checkboxes)
3693 (remove-hook 'org-blocker-hook
3694 'org-block-todo-from-checkboxes))
3696 ;; Comment characters
3697 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3698 (org-set-local 'comment-padding " ")
3700 ;; Align options lines
3701 (org-set-local
3702 'align-mode-rules-list
3703 '((org-in-buffer-settings
3704 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3705 (modes . '(org-mode)))))
3707 ;; Imenu
3708 (org-set-local 'imenu-create-index-function
3709 'org-imenu-get-tree)
3711 ;; Make isearch reveal context
3712 (if (or (featurep 'xemacs)
3713 (not (boundp 'outline-isearch-open-invisible-function)))
3714 ;; Emacs 21 and XEmacs make use of the hook
3715 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3716 ;; Emacs 22 deals with this through a special variable
3717 (org-set-local 'outline-isearch-open-invisible-function
3718 (lambda (&rest ignore) (org-show-context 'isearch))))
3720 ;; If empty file that did not turn on org-mode automatically, make it to.
3721 (if (and org-insert-mode-line-in-empty-file
3722 (interactive-p)
3723 (= (point-min) (point-max)))
3724 (insert "# -*- mode: org -*-\n\n"))
3726 (unless org-inhibit-startup
3727 (when org-startup-align-all-tables
3728 (let ((bmp (buffer-modified-p)))
3729 (org-table-map-tables 'org-table-align)
3730 (set-buffer-modified-p bmp)))
3731 (org-set-startup-visibility)))
3733 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3735 (defun org-current-time ()
3736 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3737 (if (> (car org-time-stamp-rounding-minutes) 1)
3738 (let ((r (car org-time-stamp-rounding-minutes))
3739 (time (decode-time)))
3740 (apply 'encode-time
3741 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3742 (nthcdr 2 time))))
3743 (current-time)))
3745 ;;;; Font-Lock stuff, including the activators
3747 (defvar org-mouse-map (make-sparse-keymap))
3748 (org-defkey org-mouse-map
3749 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3750 (org-defkey org-mouse-map
3751 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3752 (when org-mouse-1-follows-link
3753 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3754 (when org-tab-follows-link
3755 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3756 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3758 (require 'font-lock)
3760 (defconst org-non-link-chars "]\t\n\r<>")
3761 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3762 "shell" "elisp"))
3763 (defvar org-link-types-re nil
3764 "Matches a link that has a url-like prefix like \"http:\"")
3765 (defvar org-link-re-with-space nil
3766 "Matches a link with spaces, optional angular brackets around it.")
3767 (defvar org-link-re-with-space2 nil
3768 "Matches a link with spaces, optional angular brackets around it.")
3769 (defvar org-link-re-with-space3 nil
3770 "Matches a link with spaces, only for internal part in bracket links.")
3771 (defvar org-angle-link-re nil
3772 "Matches link with angular brackets, spaces are allowed.")
3773 (defvar org-plain-link-re nil
3774 "Matches plain link, without spaces.")
3775 (defvar org-bracket-link-regexp nil
3776 "Matches a link in double brackets.")
3777 (defvar org-bracket-link-analytic-regexp nil
3778 "Regular expression used to analyze links.
3779 Here is what the match groups contain after a match:
3780 1: http:
3781 2: http
3782 3: path
3783 4: [desc]
3784 5: desc")
3785 (defvar org-bracket-link-analytic-regexp++ nil
3786 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3787 (defvar org-any-link-re nil
3788 "Regular expression matching any link.")
3790 (defun org-make-link-regexps ()
3791 "Update the link regular expressions.
3792 This should be called after the variable `org-link-types' has changed."
3793 (setq org-link-types-re
3794 (concat
3795 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3796 org-link-re-with-space
3797 (concat
3798 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3799 "\\([^" org-non-link-chars " ]"
3800 "[^" org-non-link-chars "]*"
3801 "[^" org-non-link-chars " ]\\)>?")
3802 org-link-re-with-space2
3803 (concat
3804 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3805 "\\([^" org-non-link-chars " ]"
3806 "[^\t\n\r]*"
3807 "[^" org-non-link-chars " ]\\)>?")
3808 org-link-re-with-space3
3809 (concat
3810 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3811 "\\([^" org-non-link-chars " ]"
3812 "[^\t\n\r]*\\)")
3813 org-angle-link-re
3814 (concat
3815 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3816 "\\([^" org-non-link-chars " ]"
3817 "[^" org-non-link-chars "]*"
3818 "\\)>")
3819 org-plain-link-re
3820 (concat
3821 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3822 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3823 org-bracket-link-regexp
3824 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3825 org-bracket-link-analytic-regexp
3826 (concat
3827 "\\[\\["
3828 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3829 "\\([^]]+\\)"
3830 "\\]"
3831 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3832 "\\]")
3833 org-bracket-link-analytic-regexp++
3834 (concat
3835 "\\[\\["
3836 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3837 "\\([^]]+\\)"
3838 "\\]"
3839 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3840 "\\]")
3841 org-any-link-re
3842 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3843 org-angle-link-re "\\)\\|\\("
3844 org-plain-link-re "\\)")))
3846 (org-make-link-regexps)
3848 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3849 "Regular expression for fast time stamp matching.")
3850 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3851 "Regular expression for fast time stamp matching.")
3852 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3853 "Regular expression matching time strings for analysis.
3854 This one does not require the space after the date, so it can be used
3855 on a string that terminates immediately after the date.")
3856 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3857 "Regular expression matching time strings for analysis.")
3858 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3859 "Regular expression matching time stamps, with groups.")
3860 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3861 "Regular expression matching time stamps (also [..]), with groups.")
3862 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3863 "Regular expression matching a time stamp range.")
3864 (defconst org-tr-regexp-both
3865 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3866 "Regular expression matching a time stamp range.")
3867 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3868 org-ts-regexp "\\)?")
3869 "Regular expression matching a time stamp or time stamp range.")
3870 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3871 org-ts-regexp-both "\\)?")
3872 "Regular expression matching a time stamp or time stamp range.
3873 The time stamps may be either active or inactive.")
3875 (defvar org-emph-face nil)
3877 (defun org-do-emphasis-faces (limit)
3878 "Run through the buffer and add overlays to links."
3879 (let (rtn)
3880 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3881 (if (not (= (char-after (match-beginning 3))
3882 (char-after (match-beginning 4))))
3883 (progn
3884 (setq rtn t)
3885 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3886 'face
3887 (nth 1 (assoc (match-string 3)
3888 org-emphasis-alist)))
3889 (add-text-properties (match-beginning 2) (match-end 2)
3890 '(font-lock-multiline t))
3891 (when org-hide-emphasis-markers
3892 (add-text-properties (match-end 4) (match-beginning 5)
3893 '(invisible org-link))
3894 (add-text-properties (match-beginning 3) (match-end 3)
3895 '(invisible org-link)))))
3896 (backward-char 1))
3897 rtn))
3899 (defun org-emphasize (&optional char)
3900 "Insert or change an emphasis, i.e. a font like bold or italic.
3901 If there is an active region, change that region to a new emphasis.
3902 If there is no region, just insert the marker characters and position
3903 the cursor between them.
3904 CHAR should be either the marker character, or the first character of the
3905 HTML tag associated with that emphasis. If CHAR is a space, the means
3906 to remove the emphasis of the selected region.
3907 If char is not given (for example in an interactive call) it
3908 will be prompted for."
3909 (interactive)
3910 (let ((eal org-emphasis-alist) e det
3911 (erc org-emphasis-regexp-components)
3912 (prompt "")
3913 (string "") beg end move tag c s)
3914 (if (org-region-active-p)
3915 (setq beg (region-beginning) end (region-end)
3916 string (buffer-substring beg end))
3917 (setq move t))
3919 (while (setq e (pop eal))
3920 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3921 c (aref tag 0))
3922 (push (cons c (string-to-char (car e))) det)
3923 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3924 (substring tag 1)))))
3925 (setq det (nreverse det))
3926 (unless char
3927 (message "%s" (concat "Emphasis marker or tag:" prompt))
3928 (setq char (read-char-exclusive)))
3929 (setq char (or (cdr (assoc char det)) char))
3930 (if (equal char ?\ )
3931 (setq s "" move nil)
3932 (unless (assoc (char-to-string char) org-emphasis-alist)
3933 (error "No such emphasis marker: \"%c\"" char))
3934 (setq s (char-to-string char)))
3935 (while (and (> (length string) 1)
3936 (equal (substring string 0 1) (substring string -1))
3937 (assoc (substring string 0 1) org-emphasis-alist))
3938 (setq string (substring string 1 -1)))
3939 (setq string (concat s string s))
3940 (if beg (delete-region beg end))
3941 (unless (or (bolp)
3942 (string-match (concat "[" (nth 0 erc) "\n]")
3943 (char-to-string (char-before (point)))))
3944 (insert " "))
3945 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3946 (char-to-string (char-after (point))))
3947 (insert " ") (backward-char 1))
3948 (insert string)
3949 (and move (backward-char 1))))
3951 (defconst org-nonsticky-props
3952 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3955 (defun org-activate-plain-links (limit)
3956 "Run through the buffer and add overlays to links."
3957 (catch 'exit
3958 (let (f)
3959 (while (re-search-forward org-plain-link-re limit t)
3960 (setq f (get-text-property (match-beginning 0) 'face))
3961 (if (or (eq f 'org-tag)
3962 (and (listp f) (memq 'org-tag f)))
3964 (add-text-properties (match-beginning 0) (match-end 0)
3965 (list 'mouse-face 'highlight
3966 'rear-nonsticky org-nonsticky-props
3967 'keymap org-mouse-map
3969 (throw 'exit t))))))
3971 (defun org-activate-code (limit)
3972 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3973 (progn
3974 (remove-text-properties (match-beginning 0) (match-end 0)
3975 '(display t invisible t intangible t))
3976 t)))
3978 (defun org-activate-angle-links (limit)
3979 "Run through the buffer and add overlays to links."
3980 (if (re-search-forward org-angle-link-re limit t)
3981 (progn
3982 (add-text-properties (match-beginning 0) (match-end 0)
3983 (list 'mouse-face 'highlight
3984 'rear-nonsticky org-nonsticky-props
3985 'keymap org-mouse-map
3987 t)))
3989 (defun org-activate-footnote-links (limit)
3990 "Run through the buffer and add overlays to links."
3991 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3992 limit t)
3993 (progn
3994 (add-text-properties (match-beginning 2) (match-end 2)
3995 (list 'mouse-face 'highlight
3996 'rear-nonsticky org-nonsticky-props
3997 'keymap org-mouse-map
3998 'help-echo
3999 (if (= (point-at-bol) (match-beginning 2))
4000 "Footnote definition"
4001 "Footnote reference")
4003 t)))
4005 (defun org-activate-bracket-links (limit)
4006 "Run through the buffer and add overlays to bracketed links."
4007 (if (re-search-forward org-bracket-link-regexp limit t)
4008 (let* ((help (concat "LINK: "
4009 (org-match-string-no-properties 1)))
4010 ;; FIXME: above we should remove the escapes.
4011 ;; but that requires another match, protecting match data,
4012 ;; a lot of overhead for font-lock.
4013 (ip (org-maybe-intangible
4014 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4015 'keymap org-mouse-map 'mouse-face 'highlight
4016 'font-lock-multiline t 'help-echo help)))
4017 (vp (list 'rear-nonsticky org-nonsticky-props
4018 'keymap org-mouse-map 'mouse-face 'highlight
4019 ' font-lock-multiline t 'help-echo help)))
4020 ;; We need to remove the invisible property here. Table narrowing
4021 ;; may have made some of this invisible.
4022 (remove-text-properties (match-beginning 0) (match-end 0)
4023 '(invisible nil))
4024 (if (match-end 3)
4025 (progn
4026 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4027 (add-text-properties (match-beginning 3) (match-end 3) vp)
4028 (add-text-properties (match-end 3) (match-end 0) ip))
4029 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4030 (add-text-properties (match-beginning 1) (match-end 1) vp)
4031 (add-text-properties (match-end 1) (match-end 0) ip))
4032 t)))
4034 (defun org-activate-dates (limit)
4035 "Run through the buffer and add overlays to dates."
4036 (if (re-search-forward org-tsr-regexp-both limit t)
4037 (progn
4038 (add-text-properties (match-beginning 0) (match-end 0)
4039 (list 'mouse-face 'highlight
4040 'rear-nonsticky org-nonsticky-props
4041 'keymap org-mouse-map))
4042 (when org-display-custom-times
4043 (if (match-end 3)
4044 (org-display-custom-time (match-beginning 3) (match-end 3)))
4045 (org-display-custom-time (match-beginning 1) (match-end 1)))
4046 t)))
4048 (defvar org-target-link-regexp nil
4049 "Regular expression matching radio targets in plain text.")
4050 (make-variable-buffer-local 'org-target-link-regexp)
4051 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4052 "Regular expression matching a link target.")
4053 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4054 "Regular expression matching a radio target.")
4055 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4056 "Regular expression matching any target.")
4058 (defun org-activate-target-links (limit)
4059 "Run through the buffer and add overlays to target matches."
4060 (when org-target-link-regexp
4061 (let ((case-fold-search t))
4062 (if (re-search-forward org-target-link-regexp limit t)
4063 (progn
4064 (add-text-properties (match-beginning 0) (match-end 0)
4065 (list 'mouse-face 'highlight
4066 'rear-nonsticky org-nonsticky-props
4067 'keymap org-mouse-map
4068 'help-echo "Radio target link"
4069 'org-linked-text t))
4070 t)))))
4072 (defun org-update-radio-target-regexp ()
4073 "Find all radio targets in this file and update the regular expression."
4074 (interactive)
4075 (when (memq 'radio org-activate-links)
4076 (setq org-target-link-regexp
4077 (org-make-target-link-regexp (org-all-targets 'radio)))
4078 (org-restart-font-lock)))
4080 (defun org-hide-wide-columns (limit)
4081 (let (s e)
4082 (setq s (text-property-any (point) (or limit (point-max))
4083 'org-cwidth t))
4084 (when s
4085 (setq e (next-single-property-change s 'org-cwidth))
4086 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4087 (goto-char e)
4088 t)))
4090 (defvar org-latex-and-specials-regexp nil
4091 "Regular expression for highlighting export special stuff.")
4092 (defvar org-match-substring-regexp)
4093 (defvar org-match-substring-with-braces-regexp)
4094 (defvar org-export-html-special-string-regexps)
4096 (defun org-compute-latex-and-specials-regexp ()
4097 "Compute regular expression for stuff treated specially by exporters."
4098 (if (not org-highlight-latex-fragments-and-specials)
4099 (org-set-local 'org-latex-and-specials-regexp nil)
4100 (require 'org-exp)
4101 (let*
4102 ((matchers (plist-get org-format-latex-options :matchers))
4103 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4104 org-latex-regexps)))
4105 (options (org-combine-plists (org-default-export-plist)
4106 (org-infile-export-plist)))
4107 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4108 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4109 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4110 (org-export-html-expand (plist-get options :expand-quoted-html))
4111 (org-export-with-special-strings (plist-get options :special-strings))
4112 (re-sub
4113 (cond
4114 ((equal org-export-with-sub-superscripts '{})
4115 (list org-match-substring-with-braces-regexp))
4116 (org-export-with-sub-superscripts
4117 (list org-match-substring-regexp))
4118 (t nil)))
4119 (re-latex
4120 (if org-export-with-LaTeX-fragments
4121 (mapcar (lambda (x) (nth 1 x)) latexs)))
4122 (re-macros
4123 (if org-export-with-TeX-macros
4124 (list (concat "\\\\"
4125 (regexp-opt
4126 (append (mapcar 'car org-html-entities)
4127 (if (boundp 'org-latex-entities)
4128 org-latex-entities nil))
4129 'words))) ; FIXME
4131 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4132 (re-special (if org-export-with-special-strings
4133 (mapcar (lambda (x) (car x))
4134 org-export-html-special-string-regexps)))
4135 (re-rest
4136 (delq nil
4137 (list
4138 (if org-export-html-expand "@<[^>\n]+>")
4139 ))))
4140 (org-set-local
4141 'org-latex-and-specials-regexp
4142 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4143 re-rest) "\\|")))))
4145 (defun org-do-latex-and-special-faces (limit)
4146 "Run through the buffer and add overlays to links."
4147 (when org-latex-and-specials-regexp
4148 (let (rtn d)
4149 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4150 limit t))
4151 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4152 'face))
4153 '(org-code org-verbatim underline)))
4154 (progn
4155 (setq rtn t
4156 d (cond ((member (char-after (1+ (match-beginning 0)))
4157 '(?_ ?^)) 1)
4158 (t 0)))
4159 (font-lock-prepend-text-property
4160 (+ d (match-beginning 0)) (match-end 0)
4161 'face 'org-latex-and-export-specials)
4162 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4163 '(font-lock-multiline t)))))
4164 rtn)))
4166 (defun org-restart-font-lock ()
4167 "Restart font-lock-mode, to force refontification."
4168 (when (and (boundp 'font-lock-mode) font-lock-mode)
4169 (font-lock-mode -1)
4170 (font-lock-mode 1)))
4172 (defun org-all-targets (&optional radio)
4173 "Return a list of all targets in this file.
4174 With optional argument RADIO, only find radio targets."
4175 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4176 rtn)
4177 (save-excursion
4178 (goto-char (point-min))
4179 (while (re-search-forward re nil t)
4180 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4181 rtn)))
4183 (defun org-make-target-link-regexp (targets)
4184 "Make regular expression matching all strings in TARGETS.
4185 The regular expression finds the targets also if there is a line break
4186 between words."
4187 (and targets
4188 (concat
4189 "\\<\\("
4190 (mapconcat
4191 (lambda (x)
4192 (while (string-match " +" x)
4193 (setq x (replace-match "\\s-+" t t x)))
4195 targets
4196 "\\|")
4197 "\\)\\>")))
4199 (defun org-activate-tags (limit)
4200 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4201 (progn
4202 (add-text-properties (match-beginning 1) (match-end 1)
4203 (list 'mouse-face 'highlight
4204 'rear-nonsticky org-nonsticky-props
4205 'keymap org-mouse-map))
4206 t)))
4208 (defun org-outline-level ()
4209 (save-excursion
4210 (looking-at outline-regexp)
4211 (if (match-beginning 1)
4212 (+ (org-get-string-indentation (match-string 1)) 1000)
4213 (1- (- (match-end 0) (match-beginning 0))))))
4215 (defvar org-font-lock-keywords nil)
4217 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4218 "Regular expression matching a property line.")
4220 (defvar org-font-lock-hook nil
4221 "Functions to be called for special font lock stuff.")
4223 (defun org-font-lock-hook (limit)
4224 (run-hook-with-args 'org-font-lock-hook limit))
4226 (defun org-set-font-lock-defaults ()
4227 (let* ((em org-fontify-emphasized-text)
4228 (lk org-activate-links)
4229 (org-font-lock-extra-keywords
4230 (list
4231 ;; Call the hook
4232 '(org-font-lock-hook)
4233 ;; Headlines
4234 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4235 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4236 ;; Table lines
4237 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4238 (1 'org-table t))
4239 ;; Table internals
4240 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4241 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4242 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4243 ;; Drawers
4244 (list org-drawer-regexp '(0 'org-special-keyword t))
4245 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4246 ;; Properties
4247 (list org-property-re
4248 '(1 'org-special-keyword t)
4249 '(3 'org-property-value t))
4250 (if org-format-transports-properties-p
4251 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4252 ;; Links
4253 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4254 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4255 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4256 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4257 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4258 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4259 (if (memq 'footnote lk) '(org-activate-footnote-links
4260 (2 'org-footnote t)))
4261 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4262 '(org-hide-wide-columns (0 nil append))
4263 ;; TODO lines
4264 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4265 '(1 (org-get-todo-face 1) t))
4266 ;; DONE
4267 (if org-fontify-done-headline
4268 (list (concat "^[*]+ +\\<\\("
4269 (mapconcat 'regexp-quote org-done-keywords "\\|")
4270 "\\)\\(.*\\)")
4271 '(2 'org-headline-done t))
4272 nil)
4273 ;; Priorities
4274 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4275 ;; Tags
4276 '(org-font-lock-add-tag-faces)
4277 ;; Special keywords
4278 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4279 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4280 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4281 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4282 ;; Emphasis
4283 (if em
4284 (if (featurep 'xemacs)
4285 '(org-do-emphasis-faces (0 nil append))
4286 '(org-do-emphasis-faces)))
4287 ;; Checkboxes
4288 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4289 2 'bold prepend)
4290 (if org-provide-checkbox-statistics
4291 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4292 (0 (org-get-checkbox-statistics-face) t)))
4293 ;; Description list items
4294 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4295 2 'bold prepend)
4296 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4297 '(1 'org-archived prepend))
4298 ;; Specials
4299 '(org-do-latex-and-special-faces)
4300 ;; Code
4301 '(org-activate-code (1 'org-code t))
4302 ;; COMMENT
4303 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4304 "\\|" org-quote-string "\\)\\>")
4305 '(1 'org-special-keyword t))
4306 '("^#.*" (0 'font-lock-comment-face t))
4308 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4309 ;; Now set the full font-lock-keywords
4310 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4311 (org-set-local 'font-lock-defaults
4312 '(org-font-lock-keywords t nil nil backward-paragraph))
4313 (kill-local-variable 'font-lock-keywords) nil))
4315 (defvar org-m nil)
4316 (defvar org-l nil)
4317 (defvar org-f nil)
4318 (defun org-get-level-face (n)
4319 "Get the right face for match N in font-lock matching of headlines."
4320 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4321 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4322 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4323 (cond
4324 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4325 ((eq n 2) org-f)
4326 (t (if org-level-color-stars-only nil org-f))))
4328 (defun org-get-todo-face (kwd)
4329 "Get the right face for a TODO keyword KWD.
4330 If KWD is a number, get the corresponding match group."
4331 (if (numberp kwd) (setq kwd (match-string kwd)))
4332 (or (cdr (assoc kwd org-todo-keyword-faces))
4333 (and (member kwd org-done-keywords) 'org-done)
4334 'org-todo))
4336 (defun org-font-lock-add-tag-faces (limit)
4337 "Add the special tag faces."
4338 (when (and org-tag-faces org-tags-special-faces-re)
4339 (while (re-search-forward org-tags-special-faces-re limit t)
4340 (add-text-properties (match-beginning 1) (match-end 1)
4341 (list 'face (org-get-tag-face 1)
4342 'font-lock-fontified t))
4343 (backward-char 1))))
4345 (defun org-get-tag-face (kwd)
4346 "Get the right face for a TODO keyword KWD.
4347 If KWD is a number, get the corresponding match group."
4348 (if (numberp kwd) (setq kwd (match-string kwd)))
4349 (or (cdr (assoc kwd org-tag-faces))
4350 'org-tag))
4352 (defun org-unfontify-region (beg end &optional maybe_loudly)
4353 "Remove fontification and activation overlays from links."
4354 (font-lock-default-unfontify-region beg end)
4355 (let* ((buffer-undo-list t)
4356 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4357 (inhibit-modification-hooks t)
4358 deactivate-mark buffer-file-name buffer-file-truename)
4359 (remove-text-properties beg end
4360 '(mouse-face t keymap t org-linked-text t
4361 invisible t intangible t))))
4363 ;;;; Visibility cycling, including org-goto and indirect buffer
4365 ;;; Cycling
4367 (defvar org-cycle-global-status nil)
4368 (make-variable-buffer-local 'org-cycle-global-status)
4369 (defvar org-cycle-subtree-status nil)
4370 (make-variable-buffer-local 'org-cycle-subtree-status)
4372 ;;;###autoload
4373 (defun org-cycle (&optional arg)
4374 "Visibility cycling for Org-mode.
4376 - When this function is called with a prefix argument, rotate the entire
4377 buffer through 3 states (global cycling)
4378 1. OVERVIEW: Show only top-level headlines.
4379 2. CONTENTS: Show all headlines of all levels, but no body text.
4380 3. SHOW ALL: Show everything.
4381 When called with two C-u C-u prefixes, switch to the startup visibility,
4382 determined by the variable `org-startup-folded', and by any VISIBILITY
4383 properties in the buffer.
4384 When called with three C-u C-u C-u prefixed, show the entire buffer,
4385 including drawers.
4387 - When point is at the beginning of a headline, rotate the subtree started
4388 by this line through 3 different states (local cycling)
4389 1. FOLDED: Only the main headline is shown.
4390 2. CHILDREN: The main headline and the direct children are shown.
4391 From this state, you can move to one of the children
4392 and zoom in further.
4393 3. SUBTREE: Show the entire subtree, including body text.
4395 - When there is a numeric prefix, go up to a heading with level ARG, do
4396 a `show-subtree' and return to the previous cursor position. If ARG
4397 is negative, go up that many levels.
4399 - When point is not at the beginning of a headline, execute the global
4400 binding for TAB, which is re-indenting the line. See the option
4401 `org-cycle-emulate-tab' for details.
4403 - Special case: if point is at the beginning of the buffer and there is
4404 no headline in line 1, this function will act as if called with prefix arg.
4405 But only if also the variable `org-cycle-global-at-bob' is t."
4406 (interactive "P")
4407 (org-load-modules-maybe)
4408 (let* ((outline-regexp
4409 (if (and (org-mode-p) org-cycle-include-plain-lists)
4410 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4411 outline-regexp))
4412 (bob-special (and org-cycle-global-at-bob (bobp)
4413 (not (looking-at outline-regexp))))
4414 (org-cycle-hook
4415 (if bob-special
4416 (delq 'org-optimize-window-after-visibility-change
4417 (copy-sequence org-cycle-hook))
4418 org-cycle-hook))
4419 (pos (point)))
4421 (if (or bob-special (equal arg '(4)))
4422 ;; special case: use global cycling
4423 (setq arg t))
4425 (cond
4427 ((equal arg '(16))
4428 (org-set-startup-visibility)
4429 (message "Startup visibility, plus VISIBILITY properties"))
4431 ((equal arg '(64))
4432 (show-all)
4433 (message "Entire buffer visible, including drawers"))
4435 ((org-at-table-p 'any)
4436 ;; Enter the table or move to the next field in the table
4437 (or (org-table-recognize-table.el)
4438 (progn
4439 (if arg (org-table-edit-field t)
4440 (org-table-justify-field-maybe)
4441 (call-interactively 'org-table-next-field)))))
4443 ((eq arg t) ;; Global cycling
4445 (cond
4446 ((and (eq last-command this-command)
4447 (eq org-cycle-global-status 'overview))
4448 ;; We just created the overview - now do table of contents
4449 ;; This can be slow in very large buffers, so indicate action
4450 (message "CONTENTS...")
4451 (org-content)
4452 (message "CONTENTS...done")
4453 (setq org-cycle-global-status 'contents)
4454 (run-hook-with-args 'org-cycle-hook 'contents))
4456 ((and (eq last-command this-command)
4457 (eq org-cycle-global-status 'contents))
4458 ;; We just showed the table of contents - now show everything
4459 (show-all)
4460 (message "SHOW ALL")
4461 (setq org-cycle-global-status 'all)
4462 (run-hook-with-args 'org-cycle-hook 'all))
4465 ;; Default action: go to overview
4466 (org-overview)
4467 (message "OVERVIEW")
4468 (setq org-cycle-global-status 'overview)
4469 (run-hook-with-args 'org-cycle-hook 'overview))))
4471 ((and org-drawers org-drawer-regexp
4472 (save-excursion
4473 (beginning-of-line 1)
4474 (looking-at org-drawer-regexp)))
4475 ;; Toggle block visibility
4476 (org-flag-drawer
4477 (not (get-char-property (match-end 0) 'invisible))))
4479 ((integerp arg)
4480 ;; Show-subtree, ARG levels up from here.
4481 (save-excursion
4482 (org-back-to-heading)
4483 (outline-up-heading (if (< arg 0) (- arg)
4484 (- (funcall outline-level) arg)))
4485 (org-show-subtree)))
4487 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4488 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4489 ;; At a heading: rotate between three different views
4490 (org-back-to-heading)
4491 (let ((goal-column 0) eoh eol eos)
4492 ;; First, some boundaries
4493 (save-excursion
4494 (org-back-to-heading)
4495 (save-excursion
4496 (beginning-of-line 2)
4497 (while (and (not (eobp)) ;; this is like `next-line'
4498 (get-char-property (1- (point)) 'invisible))
4499 (beginning-of-line 2)) (setq eol (point)))
4500 (outline-end-of-heading) (setq eoh (point))
4501 (org-end-of-subtree t)
4502 (unless (eobp)
4503 (skip-chars-forward " \t\n")
4504 (beginning-of-line 1) ; in case this is an item
4506 (setq eos (1- (point))))
4507 ;; Find out what to do next and set `this-command'
4508 (cond
4509 ((= eos eoh)
4510 ;; Nothing is hidden behind this heading
4511 (message "EMPTY ENTRY")
4512 (setq org-cycle-subtree-status nil)
4513 (save-excursion
4514 (goto-char eos)
4515 (outline-next-heading)
4516 (if (org-invisible-p) (org-flag-heading nil))))
4517 ((or (>= eol eos)
4518 (not (string-match "\\S-" (buffer-substring eol eos))))
4519 ;; Entire subtree is hidden in one line: open it
4520 (org-show-entry)
4521 (show-children)
4522 (message "CHILDREN")
4523 (save-excursion
4524 (goto-char eos)
4525 (outline-next-heading)
4526 (if (org-invisible-p) (org-flag-heading nil)))
4527 (setq org-cycle-subtree-status 'children)
4528 (run-hook-with-args 'org-cycle-hook 'children))
4529 ((and (eq last-command this-command)
4530 (eq org-cycle-subtree-status 'children))
4531 ;; We just showed the children, now show everything.
4532 (org-show-subtree)
4533 (message "SUBTREE")
4534 (setq org-cycle-subtree-status 'subtree)
4535 (run-hook-with-args 'org-cycle-hook 'subtree))
4537 ;; Default action: hide the subtree.
4538 (hide-subtree)
4539 (message "FOLDED")
4540 (setq org-cycle-subtree-status 'folded)
4541 (run-hook-with-args 'org-cycle-hook 'folded)))))
4543 ;; TAB emulation and template completion
4544 (buffer-read-only (org-back-to-heading))
4546 ((org-try-structure-completion))
4548 ((org-try-cdlatex-tab))
4550 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4551 (or (not (bolp))
4552 (not (looking-at outline-regexp))))
4553 (call-interactively (global-key-binding "\t")))
4555 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4556 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4557 (or (and (eq org-cycle-emulate-tab 'white)
4558 (= (match-end 0) (point-at-eol)))
4559 (and (eq org-cycle-emulate-tab 'whitestart)
4560 (>= (match-end 0) pos))))
4562 (eq org-cycle-emulate-tab t))
4563 (call-interactively (global-key-binding "\t")))
4565 (t (save-excursion
4566 (org-back-to-heading)
4567 (org-cycle))))))
4569 ;;;###autoload
4570 (defun org-global-cycle (&optional arg)
4571 "Cycle the global visibility. For details see `org-cycle'.
4572 With C-u prefix arg, switch to startup visibility.
4573 With a numeric prefix, show all headlines up to that level."
4574 (interactive "P")
4575 (let ((org-cycle-include-plain-lists
4576 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4577 (cond
4578 ((integerp arg)
4579 (show-all)
4580 (hide-sublevels arg)
4581 (setq org-cycle-global-status 'contents))
4582 ((equal arg '(4))
4583 (org-set-startup-visibility)
4584 (message "Startup visibility, plus VISIBILITY properties."))
4586 (org-cycle '(4))))))
4588 (defun org-set-startup-visibility ()
4589 "Set the visibility required by startup options and properties."
4590 (cond
4591 ((eq org-startup-folded t)
4592 (org-cycle '(4)))
4593 ((eq org-startup-folded 'content)
4594 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4595 (org-cycle '(4)) (org-cycle '(4)))))
4596 (org-set-visibility-according-to-property 'no-cleanup)
4597 (org-cycle-hide-archived-subtrees 'all)
4598 (org-cycle-hide-drawers 'all)
4599 (org-cycle-show-empty-lines 'all))
4601 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4602 "Switch subtree visibilities according to :VISIBILITY: property."
4603 (interactive)
4604 (let (org-show-entry-below state)
4605 (save-excursion
4606 (goto-char (point-min))
4607 (while (re-search-forward
4608 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4609 nil t)
4610 (setq state (match-string 1))
4611 (save-excursion
4612 (org-back-to-heading t)
4613 (hide-subtree)
4614 (org-reveal)
4615 (cond
4616 ((equal state '("fold" "folded"))
4617 (hide-subtree))
4618 ((equal state "children")
4619 (org-show-hidden-entry)
4620 (show-children))
4621 ((equal state "content")
4622 (save-excursion
4623 (save-restriction
4624 (org-narrow-to-subtree)
4625 (org-content))))
4626 ((member state '("all" "showall"))
4627 (show-subtree)))))
4628 (unless no-cleanup
4629 (org-cycle-hide-archived-subtrees 'all)
4630 (org-cycle-hide-drawers 'all)
4631 (org-cycle-show-empty-lines 'all)))))
4633 (defun org-overview ()
4634 "Switch to overview mode, showing only top-level headlines.
4635 Really, this shows all headlines with level equal or greater than the level
4636 of the first headline in the buffer. This is important, because if the
4637 first headline is not level one, then (hide-sublevels 1) gives confusing
4638 results."
4639 (interactive)
4640 (let ((level (save-excursion
4641 (goto-char (point-min))
4642 (if (re-search-forward (concat "^" outline-regexp) nil t)
4643 (progn
4644 (goto-char (match-beginning 0))
4645 (funcall outline-level))))))
4646 (and level (hide-sublevels level))))
4648 (defun org-content (&optional arg)
4649 "Show all headlines in the buffer, like a table of contents.
4650 With numerical argument N, show content up to level N."
4651 (interactive "P")
4652 (save-excursion
4653 ;; Visit all headings and show their offspring
4654 (and (integerp arg) (org-overview))
4655 (goto-char (point-max))
4656 (catch 'exit
4657 (while (and (progn (condition-case nil
4658 (outline-previous-visible-heading 1)
4659 (error (goto-char (point-min))))
4661 (looking-at outline-regexp))
4662 (if (integerp arg)
4663 (show-children (1- arg))
4664 (show-branches))
4665 (if (bobp) (throw 'exit nil))))))
4668 (defun org-optimize-window-after-visibility-change (state)
4669 "Adjust the window after a change in outline visibility.
4670 This function is the default value of the hook `org-cycle-hook'."
4671 (when (get-buffer-window (current-buffer))
4672 (cond
4673 ((eq state 'content) nil)
4674 ((eq state 'all) nil)
4675 ((eq state 'folded) nil)
4676 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4677 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4679 (defun org-compact-display-after-subtree-move ()
4680 "Show a compacter version of the tree of the entry's parent."
4681 (save-excursion
4682 (if (org-up-heading-safe)
4683 (progn
4684 (hide-subtree)
4685 (show-entry)
4686 (show-children)
4687 (org-cycle-show-empty-lines 'children)
4688 (org-cycle-hide-drawers 'children))
4689 (org-overview))))
4691 (defun org-cycle-show-empty-lines (state)
4692 "Show empty lines above all visible headlines.
4693 The region to be covered depends on STATE when called through
4694 `org-cycle-hook'. Lisp program can use t for STATE to get the
4695 entire buffer covered. Note that an empty line is only shown if there
4696 are at least `org-cycle-separator-lines' empty lines before the headline."
4697 (when (> org-cycle-separator-lines 0)
4698 (save-excursion
4699 (let* ((n org-cycle-separator-lines)
4700 (re (cond
4701 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4702 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4703 (t (let ((ns (number-to-string (- n 2))))
4704 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4705 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4706 beg end)
4707 (cond
4708 ((memq state '(overview contents t))
4709 (setq beg (point-min) end (point-max)))
4710 ((memq state '(children folded))
4711 (setq beg (point) end (progn (org-end-of-subtree t t)
4712 (beginning-of-line 2)
4713 (point)))))
4714 (when beg
4715 (goto-char beg)
4716 (while (re-search-forward re end t)
4717 (if (not (get-char-property (match-end 1) 'invisible))
4718 (outline-flag-region
4719 (match-beginning 1) (match-end 1) nil)))))))
4720 ;; Never hide empty lines at the end of the file.
4721 (save-excursion
4722 (goto-char (point-max))
4723 (outline-previous-heading)
4724 (outline-end-of-heading)
4725 (if (and (looking-at "[ \t\n]+")
4726 (= (match-end 0) (point-max)))
4727 (outline-flag-region (point) (match-end 0) nil))))
4729 (defun org-show-empty-lines-in-parent ()
4730 "Move to the parent and re-show empty lines before visible headlines."
4731 (save-excursion
4732 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4733 (org-cycle-show-empty-lines context))))
4735 (defun org-cycle-hide-drawers (state)
4736 "Re-hide all drawers after a visibility state change."
4737 (when (and (org-mode-p)
4738 (not (memq state '(overview folded))))
4739 (save-excursion
4740 (let* ((globalp (memq state '(contents all)))
4741 (beg (if globalp (point-min) (point)))
4742 (end (if globalp (point-max) (org-end-of-subtree t))))
4743 (goto-char beg)
4744 (while (re-search-forward org-drawer-regexp end t)
4745 (org-flag-drawer t))))))
4747 (defun org-flag-drawer (flag)
4748 (save-excursion
4749 (beginning-of-line 1)
4750 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4751 (let ((b (match-end 0))
4752 (outline-regexp org-outline-regexp))
4753 (if (re-search-forward
4754 "^[ \t]*:END:"
4755 (save-excursion (outline-next-heading) (point)) t)
4756 (outline-flag-region b (point-at-eol) flag)
4757 (error ":END: line missing"))))))
4759 (defun org-subtree-end-visible-p ()
4760 "Is the end of the current subtree visible?"
4761 (pos-visible-in-window-p
4762 (save-excursion (org-end-of-subtree t) (point))))
4764 (defun org-first-headline-recenter (&optional N)
4765 "Move cursor to the first headline and recenter the headline.
4766 Optional argument N means, put the headline into the Nth line of the window."
4767 (goto-char (point-min))
4768 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4769 (beginning-of-line)
4770 (recenter (prefix-numeric-value N))))
4772 ;;; Org-goto
4774 (defvar org-goto-window-configuration nil)
4775 (defvar org-goto-marker nil)
4776 (defvar org-goto-map
4777 (let ((map (make-sparse-keymap)))
4778 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4779 (while (setq cmd (pop cmds))
4780 (substitute-key-definition cmd cmd map global-map)))
4781 (suppress-keymap map)
4782 (org-defkey map "\C-m" 'org-goto-ret)
4783 (org-defkey map [(return)] 'org-goto-ret)
4784 (org-defkey map [(left)] 'org-goto-left)
4785 (org-defkey map [(right)] 'org-goto-right)
4786 (org-defkey map [(control ?g)] 'org-goto-quit)
4787 (org-defkey map "\C-i" 'org-cycle)
4788 (org-defkey map [(tab)] 'org-cycle)
4789 (org-defkey map [(down)] 'outline-next-visible-heading)
4790 (org-defkey map [(up)] 'outline-previous-visible-heading)
4791 (if org-goto-auto-isearch
4792 (if (fboundp 'define-key-after)
4793 (define-key-after map [t] 'org-goto-local-auto-isearch)
4794 nil)
4795 (org-defkey map "q" 'org-goto-quit)
4796 (org-defkey map "n" 'outline-next-visible-heading)
4797 (org-defkey map "p" 'outline-previous-visible-heading)
4798 (org-defkey map "f" 'outline-forward-same-level)
4799 (org-defkey map "b" 'outline-backward-same-level)
4800 (org-defkey map "u" 'outline-up-heading))
4801 (org-defkey map "/" 'org-occur)
4802 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4803 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4804 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4805 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4806 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4807 map))
4809 (defconst org-goto-help
4810 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4811 RET=jump to location [Q]uit and return to previous location
4812 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4814 (defvar org-goto-start-pos) ; dynamically scoped parameter
4816 ;; FIXME: Docstring doe not mention both interfaces
4817 (defun org-goto (&optional alternative-interface)
4818 "Look up a different location in the current file, keeping current visibility.
4820 When you want look-up or go to a different location in a document, the
4821 fastest way is often to fold the entire buffer and then dive into the tree.
4822 This method has the disadvantage, that the previous location will be folded,
4823 which may not be what you want.
4825 This command works around this by showing a copy of the current buffer
4826 in an indirect buffer, in overview mode. You can dive into the tree in
4827 that copy, use org-occur and incremental search to find a location.
4828 When pressing RET or `Q', the command returns to the original buffer in
4829 which the visibility is still unchanged. After RET is will also jump to
4830 the location selected in the indirect buffer and expose the
4831 the headline hierarchy above."
4832 (interactive "P")
4833 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4834 (org-refile-use-outline-path t)
4835 (interface
4836 (if (not alternative-interface)
4837 org-goto-interface
4838 (if (eq org-goto-interface 'outline)
4839 'outline-path-completion
4840 'outline)))
4841 (org-goto-start-pos (point))
4842 (selected-point
4843 (if (eq interface 'outline)
4844 (car (org-get-location (current-buffer) org-goto-help))
4845 (nth 3 (org-refile-get-location "Goto: ")))))
4846 (if selected-point
4847 (progn
4848 (org-mark-ring-push org-goto-start-pos)
4849 (goto-char selected-point)
4850 (if (or (org-invisible-p) (org-invisible-p2))
4851 (org-show-context 'org-goto)))
4852 (message "Quit"))))
4854 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4855 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4856 (defvar org-goto-local-auto-isearch-map) ; defined below
4858 (defun org-get-location (buf help)
4859 "Let the user select a location in the Org-mode buffer BUF.
4860 This function uses a recursive edit. It returns the selected position
4861 or nil."
4862 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4863 (isearch-hide-immediately nil)
4864 (isearch-search-fun-function
4865 (lambda () 'org-goto-local-search-headings))
4866 (org-goto-selected-point org-goto-exit-command))
4867 (save-excursion
4868 (save-window-excursion
4869 (delete-other-windows)
4870 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4871 (switch-to-buffer
4872 (condition-case nil
4873 (make-indirect-buffer (current-buffer) "*org-goto*")
4874 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4875 (with-output-to-temp-buffer "*Help*"
4876 (princ help))
4877 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4878 (setq buffer-read-only nil)
4879 (let ((org-startup-truncated t)
4880 (org-startup-folded nil)
4881 (org-startup-align-all-tables nil))
4882 (org-mode)
4883 (org-overview))
4884 (setq buffer-read-only t)
4885 (if (and (boundp 'org-goto-start-pos)
4886 (integer-or-marker-p org-goto-start-pos))
4887 (let ((org-show-hierarchy-above t)
4888 (org-show-siblings t)
4889 (org-show-following-heading t))
4890 (goto-char org-goto-start-pos)
4891 (and (org-invisible-p) (org-show-context)))
4892 (goto-char (point-min)))
4893 (let (org-special-ctrl-a/e) (org-beginning-of-line))
4894 (message "Select location and press RET")
4895 (use-local-map org-goto-map)
4896 (recursive-edit)
4898 (kill-buffer "*org-goto*")
4899 (cons org-goto-selected-point org-goto-exit-command)))
4901 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4902 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4903 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4904 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4906 (defun org-goto-local-search-headings (string bound noerror)
4907 "Search and make sure that any matches are in headlines."
4908 (catch 'return
4909 (while (if isearch-forward
4910 (search-forward string bound noerror)
4911 (search-backward string bound noerror))
4912 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4913 (and (member :headline context)
4914 (not (member :tags context))))
4915 (throw 'return (point))))))
4917 (defun org-goto-local-auto-isearch ()
4918 "Start isearch."
4919 (interactive)
4920 (goto-char (point-min))
4921 (let ((keys (this-command-keys)))
4922 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4923 (isearch-mode t)
4924 (isearch-process-search-char (string-to-char keys)))))
4926 (defun org-goto-ret (&optional arg)
4927 "Finish `org-goto' by going to the new location."
4928 (interactive "P")
4929 (setq org-goto-selected-point (point)
4930 org-goto-exit-command 'return)
4931 (throw 'exit nil))
4933 (defun org-goto-left ()
4934 "Finish `org-goto' by going to the new location."
4935 (interactive)
4936 (if (org-on-heading-p)
4937 (progn
4938 (beginning-of-line 1)
4939 (setq org-goto-selected-point (point)
4940 org-goto-exit-command 'left)
4941 (throw 'exit nil))
4942 (error "Not on a heading")))
4944 (defun org-goto-right ()
4945 "Finish `org-goto' by going to the new location."
4946 (interactive)
4947 (if (org-on-heading-p)
4948 (progn
4949 (setq org-goto-selected-point (point)
4950 org-goto-exit-command 'right)
4951 (throw 'exit nil))
4952 (error "Not on a heading")))
4954 (defun org-goto-quit ()
4955 "Finish `org-goto' without cursor motion."
4956 (interactive)
4957 (setq org-goto-selected-point nil)
4958 (setq org-goto-exit-command 'quit)
4959 (throw 'exit nil))
4961 ;;; Indirect buffer display of subtrees
4963 (defvar org-indirect-dedicated-frame nil
4964 "This is the frame being used for indirect tree display.")
4965 (defvar org-last-indirect-buffer nil)
4967 (defun org-tree-to-indirect-buffer (&optional arg)
4968 "Create indirect buffer and narrow it to current subtree.
4969 With numerical prefix ARG, go up to this level and then take that tree.
4970 If ARG is negative, go up that many levels.
4971 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4972 indirect buffer previously made with this command, to avoid proliferation of
4973 indirect buffers. However, when you call the command with a `C-u' prefix, or
4974 when `org-indirect-buffer-display' is `new-frame', the last buffer
4975 is kept so that you can work with several indirect buffers at the same time.
4976 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4977 requests that a new frame be made for the new buffer, so that the dedicated
4978 frame is not changed."
4979 (interactive "P")
4980 (let ((cbuf (current-buffer))
4981 (cwin (selected-window))
4982 (pos (point))
4983 beg end level heading ibuf)
4984 (save-excursion
4985 (org-back-to-heading t)
4986 (when (numberp arg)
4987 (setq level (org-outline-level))
4988 (if (< arg 0) (setq arg (+ level arg)))
4989 (while (> (setq level (org-outline-level)) arg)
4990 (outline-up-heading 1 t)))
4991 (setq beg (point)
4992 heading (org-get-heading))
4993 (org-end-of-subtree t) (setq end (point)))
4994 (if (and (buffer-live-p org-last-indirect-buffer)
4995 (not (eq org-indirect-buffer-display 'new-frame))
4996 (not arg))
4997 (kill-buffer org-last-indirect-buffer))
4998 (setq ibuf (org-get-indirect-buffer cbuf)
4999 org-last-indirect-buffer ibuf)
5000 (cond
5001 ((or (eq org-indirect-buffer-display 'new-frame)
5002 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5003 (select-frame (make-frame))
5004 (delete-other-windows)
5005 (switch-to-buffer ibuf)
5006 (org-set-frame-title heading))
5007 ((eq org-indirect-buffer-display 'dedicated-frame)
5008 (raise-frame
5009 (select-frame (or (and org-indirect-dedicated-frame
5010 (frame-live-p org-indirect-dedicated-frame)
5011 org-indirect-dedicated-frame)
5012 (setq org-indirect-dedicated-frame (make-frame)))))
5013 (delete-other-windows)
5014 (switch-to-buffer ibuf)
5015 (org-set-frame-title (concat "Indirect: " heading)))
5016 ((eq org-indirect-buffer-display 'current-window)
5017 (switch-to-buffer ibuf))
5018 ((eq org-indirect-buffer-display 'other-window)
5019 (pop-to-buffer ibuf))
5020 (t (error "Invalid value.")))
5021 (if (featurep 'xemacs)
5022 (save-excursion (org-mode) (turn-on-font-lock)))
5023 (narrow-to-region beg end)
5024 (show-all)
5025 (goto-char pos)
5026 (and (window-live-p cwin) (select-window cwin))))
5028 (defun org-get-indirect-buffer (&optional buffer)
5029 (setq buffer (or buffer (current-buffer)))
5030 (let ((n 1) (base (buffer-name buffer)) bname)
5031 (while (buffer-live-p
5032 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5033 (setq n (1+ n)))
5034 (condition-case nil
5035 (make-indirect-buffer buffer bname 'clone)
5036 (error (make-indirect-buffer buffer bname)))))
5038 (defun org-set-frame-title (title)
5039 "Set the title of the current frame to the string TITLE."
5040 ;; FIXME: how to name a single frame in XEmacs???
5041 (unless (featurep 'xemacs)
5042 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5044 ;;;; Structure editing
5046 ;;; Inserting headlines
5048 (defun org-previous-line-empty-p ()
5049 (save-excursion
5050 (and (not (bobp))
5051 (or (beginning-of-line 0) t)
5052 (save-match-data
5053 (looking-at "[ \t]*$")))))
5055 (defun org-insert-heading (&optional force-heading)
5056 "Insert a new heading or item with same depth at point.
5057 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5058 If point is at the beginning of a headline, insert a sibling before the
5059 current headline. If point is not at the beginning, do not split the line,
5060 but create the new headline after the current line."
5061 (interactive "P")
5062 (if (= (buffer-size) 0)
5063 (insert "\n* ")
5064 (when (or force-heading (not (org-insert-item)))
5065 (let* ((empty-line-p nil)
5066 (head (save-excursion
5067 (condition-case nil
5068 (progn
5069 (org-back-to-heading)
5070 (setq empty-line-p (org-previous-line-empty-p))
5071 (match-string 0))
5072 (error "*"))))
5073 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5074 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5075 pos hide-previous previous-pos)
5076 (cond
5077 ((and (org-on-heading-p) (bolp)
5078 (or (bobp)
5079 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5080 ;; insert before the current line
5081 (open-line (if blank 2 1)))
5082 ((and (bolp)
5083 (or (bobp)
5084 (save-excursion
5085 (backward-char 1) (not (org-invisible-p)))))
5086 ;; insert right here
5087 nil)
5089 ;; somewhere in the line
5090 (save-excursion
5091 (setq previous-pos (point-at-bol))
5092 (end-of-line)
5093 (setq hide-previous (org-invisible-p)))
5094 (and org-insert-heading-respect-content (org-show-subtree))
5095 (let ((split
5096 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5097 (save-excursion
5098 (let ((p (point)))
5099 (goto-char (point-at-bol))
5100 (and (looking-at org-complex-heading-regexp)
5101 (> p (match-beginning 4)))))))
5102 tags pos)
5103 (cond
5104 (org-insert-heading-respect-content
5105 (org-end-of-subtree nil t)
5106 (or (bolp) (newline))
5107 (or (org-previous-line-empty-p)
5108 (and blank (newline)))
5109 (open-line 1))
5110 ((org-on-heading-p)
5111 (when hide-previous
5112 (show-children)
5113 (org-show-entry))
5114 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5115 (setq tags (and (match-end 2) (match-string 2)))
5116 (and (match-end 1)
5117 (delete-region (match-beginning 1) (match-end 1)))
5118 (setq pos (point-at-bol))
5119 (or split (end-of-line 1))
5120 (delete-horizontal-space)
5121 (newline (if blank 2 1))
5122 (when tags
5123 (save-excursion
5124 (goto-char pos)
5125 (end-of-line 1)
5126 (insert " " tags)
5127 (org-set-tags nil 'align))))
5129 (or split (end-of-line 1))
5130 (newline (if blank 2 1)))))))
5131 (insert head) (just-one-space)
5132 (setq pos (point))
5133 (end-of-line 1)
5134 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5135 (when (and org-insert-heading-respect-content hide-previous)
5136 (save-excursion
5137 (goto-char previous-pos)
5138 (hide-subtree)))
5139 (run-hooks 'org-insert-heading-hook)))))
5141 (defun org-get-heading (&optional no-tags)
5142 "Return the heading of the current entry, without the stars."
5143 (save-excursion
5144 (org-back-to-heading t)
5145 (if (looking-at
5146 (if no-tags
5147 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5148 "\\*+[ \t]+\\([^\r\n]*\\)"))
5149 (match-string 1) "")))
5151 (defun org-heading-components ()
5152 "Return the components of the current heading.
5153 This is a list with the following elements:
5154 - the level as an integer
5155 - the reduced level, different if `org-odd-levels-only' is set.
5156 - the TODO keyword, or nil
5157 - the priority character, like ?A, or nil if no priority is given
5158 - the headline text itself, or the tags string if no headline text
5159 - the tags string, or nil."
5160 (save-excursion
5161 (org-back-to-heading t)
5162 (if (looking-at org-complex-heading-regexp)
5163 (list (length (match-string 1))
5164 (org-reduced-level (length (match-string 1)))
5165 (org-match-string-no-properties 2)
5166 (and (match-end 3) (aref (match-string 3) 2))
5167 (org-match-string-no-properties 4)
5168 (org-match-string-no-properties 5)))))
5170 (defun org-insert-heading-after-current ()
5171 "Insert a new heading with same level as current, after current subtree."
5172 (interactive)
5173 (org-back-to-heading)
5174 (org-insert-heading)
5175 (org-move-subtree-down)
5176 (end-of-line 1))
5178 (defun org-insert-heading-respect-content ()
5179 (interactive)
5180 (let ((org-insert-heading-respect-content t))
5181 (org-insert-heading t)))
5183 (defun org-insert-todo-heading-respect-content (&optional force-state)
5184 (interactive "P")
5185 (let ((org-insert-heading-respect-content t))
5186 (org-insert-todo-heading force-state t)))
5188 (defun org-insert-todo-heading (arg &optional force-heading)
5189 "Insert a new heading with the same level and TODO state as current heading.
5190 If the heading has no TODO state, or if the state is DONE, use the first
5191 state (TODO by default). Also with prefix arg, force first state."
5192 (interactive "P")
5193 (when (or force-heading (not (org-insert-item 'checkbox)))
5194 (org-insert-heading force-heading)
5195 (save-excursion
5196 (org-back-to-heading)
5197 (outline-previous-heading)
5198 (looking-at org-todo-line-regexp))
5199 (let*
5200 ((new-mark-x
5201 (if (or arg
5202 (not (match-beginning 2))
5203 (member (match-string 2) org-done-keywords))
5204 (car org-todo-keywords-1)
5205 (match-string 2)))
5206 (new-mark
5208 (run-hook-with-args-until-success
5209 'org-todo-get-default-hook new-mark-x nil)
5210 new-mark-x)))
5211 (insert new-mark " "))
5212 (when org-provide-todo-statistics
5213 (org-update-parent-todo-statistics))))
5215 (defun org-insert-subheading (arg)
5216 "Insert a new subheading and demote it.
5217 Works for outline headings and for plain lists alike."
5218 (interactive "P")
5219 (org-insert-heading arg)
5220 (cond
5221 ((org-on-heading-p) (org-do-demote))
5222 ((org-at-item-p) (org-indent-item 1))))
5224 (defun org-insert-todo-subheading (arg)
5225 "Insert a new subheading with TODO keyword or checkbox and demote it.
5226 Works for outline headings and for plain lists alike."
5227 (interactive "P")
5228 (org-insert-todo-heading arg)
5229 (cond
5230 ((org-on-heading-p) (org-do-demote))
5231 ((org-at-item-p) (org-indent-item 1))))
5233 ;;; Promotion and Demotion
5235 (defun org-promote-subtree ()
5236 "Promote the entire subtree.
5237 See also `org-promote'."
5238 (interactive)
5239 (save-excursion
5240 (org-map-tree 'org-promote))
5241 (org-fix-position-after-promote))
5243 (defun org-demote-subtree ()
5244 "Demote the entire subtree. See `org-demote'.
5245 See also `org-promote'."
5246 (interactive)
5247 (save-excursion
5248 (org-map-tree 'org-demote))
5249 (org-fix-position-after-promote))
5252 (defun org-do-promote ()
5253 "Promote the current heading higher up the tree.
5254 If the region is active in `transient-mark-mode', promote all headings
5255 in the region."
5256 (interactive)
5257 (save-excursion
5258 (if (org-region-active-p)
5259 (org-map-region 'org-promote (region-beginning) (region-end))
5260 (org-promote)))
5261 (org-fix-position-after-promote))
5263 (defun org-do-demote ()
5264 "Demote the current heading lower down the tree.
5265 If the region is active in `transient-mark-mode', demote all headings
5266 in the region."
5267 (interactive)
5268 (save-excursion
5269 (if (org-region-active-p)
5270 (org-map-region 'org-demote (region-beginning) (region-end))
5271 (org-demote)))
5272 (org-fix-position-after-promote))
5274 (defun org-fix-position-after-promote ()
5275 "Make sure that after pro/demotion cursor position is right."
5276 (let ((pos (point)))
5277 (when (save-excursion
5278 (beginning-of-line 1)
5279 (looking-at org-todo-line-regexp)
5280 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5281 (cond ((eobp) (insert " "))
5282 ((eolp) (insert " "))
5283 ((equal (char-after) ?\ ) (forward-char 1))))))
5285 (defun org-reduced-level (l)
5286 "Compute the effective level of a heading.
5287 This takes into account the setting of `org-odd-levels-only'."
5288 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5290 (defun org-get-valid-level (level &optional change)
5291 "Rectify a level change under the influence of `org-odd-levels-only'
5292 LEVEL is a current level, CHANGE is by how much the level should be
5293 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5294 even level numbers will become the next higher odd number."
5295 (if org-odd-levels-only
5296 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5297 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5298 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5299 (max 1 (+ level change))))
5301 (if (boundp 'define-obsolete-function-alias)
5302 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5303 (define-obsolete-function-alias 'org-get-legal-level
5304 'org-get-valid-level)
5305 (define-obsolete-function-alias 'org-get-legal-level
5306 'org-get-valid-level "23.1")))
5308 (defun org-promote ()
5309 "Promote the current heading higher up the tree.
5310 If the region is active in `transient-mark-mode', promote all headings
5311 in the region."
5312 (org-back-to-heading t)
5313 (let* ((level (save-match-data (funcall outline-level)))
5314 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5315 (diff (abs (- level (length up-head) -1))))
5316 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5317 (replace-match up-head nil t)
5318 ;; Fixup tag positioning
5319 (and org-auto-align-tags (org-set-tags nil t))
5320 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5322 (defun org-demote ()
5323 "Demote the current heading lower down the tree.
5324 If the region is active in `transient-mark-mode', demote all headings
5325 in the region."
5326 (org-back-to-heading t)
5327 (let* ((level (save-match-data (funcall outline-level)))
5328 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5329 (diff (abs (- level (length down-head) -1))))
5330 (replace-match down-head nil t)
5331 ;; Fixup tag positioning
5332 (and org-auto-align-tags (org-set-tags nil t))
5333 (if org-adapt-indentation (org-fixup-indentation diff))))
5335 (defun org-map-tree (fun)
5336 "Call FUN for every heading underneath the current one."
5337 (org-back-to-heading)
5338 (let ((level (funcall outline-level)))
5339 (save-excursion
5340 (funcall fun)
5341 (while (and (progn
5342 (outline-next-heading)
5343 (> (funcall outline-level) level))
5344 (not (eobp)))
5345 (funcall fun)))))
5347 (defun org-map-region (fun beg end)
5348 "Call FUN for every heading between BEG and END."
5349 (let ((org-ignore-region t))
5350 (save-excursion
5351 (setq end (copy-marker end))
5352 (goto-char beg)
5353 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5354 (< (point) end))
5355 (funcall fun))
5356 (while (and (progn
5357 (outline-next-heading)
5358 (< (point) end))
5359 (not (eobp)))
5360 (funcall fun)))))
5362 (defun org-fixup-indentation (diff)
5363 "Change the indentation in the current entry by DIFF
5364 However, if any line in the current entry has no indentation, or if it
5365 would end up with no indentation after the change, nothing at all is done."
5366 (save-excursion
5367 (let ((end (save-excursion (outline-next-heading)
5368 (point-marker)))
5369 (prohibit (if (> diff 0)
5370 "^\\S-"
5371 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5372 col)
5373 (unless (save-excursion (end-of-line 1)
5374 (re-search-forward prohibit end t))
5375 (while (and (< (point) end)
5376 (re-search-forward "^[ \t]+" end t))
5377 (goto-char (match-end 0))
5378 (setq col (current-column))
5379 (if (< diff 0) (replace-match ""))
5380 (org-indent-to-column (+ diff col))))
5381 (move-marker end nil))))
5383 (defun org-convert-to-odd-levels ()
5384 "Convert an org-mode file with all levels allowed to one with odd levels.
5385 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5386 level 5 etc."
5387 (interactive)
5388 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5389 (let ((org-odd-levels-only nil) n)
5390 (save-excursion
5391 (goto-char (point-min))
5392 (while (re-search-forward "^\\*\\*+ " nil t)
5393 (setq n (- (length (match-string 0)) 2))
5394 (while (>= (setq n (1- n)) 0)
5395 (org-demote))
5396 (end-of-line 1))))))
5399 (defun org-convert-to-oddeven-levels ()
5400 "Convert an org-mode file with only odd levels to one with odd and even levels.
5401 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5402 section with an even level, conversion would destroy the structure of the file. An error
5403 is signaled in this case."
5404 (interactive)
5405 (goto-char (point-min))
5406 ;; First check if there are no even levels
5407 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5408 (org-show-context t)
5409 (error "Not all levels are odd in this file. Conversion not possible."))
5410 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5411 (let ((org-odd-levels-only nil) n)
5412 (save-excursion
5413 (goto-char (point-min))
5414 (while (re-search-forward "^\\*\\*+ " nil t)
5415 (setq n (/ (1- (length (match-string 0))) 2))
5416 (while (>= (setq n (1- n)) 0)
5417 (org-promote))
5418 (end-of-line 1))))))
5420 (defun org-tr-level (n)
5421 "Make N odd if required."
5422 (if org-odd-levels-only (1+ (/ n 2)) n))
5424 ;;; Vertical tree motion, cutting and pasting of subtrees
5426 (defun org-move-subtree-up (&optional arg)
5427 "Move the current subtree up past ARG headlines of the same level."
5428 (interactive "p")
5429 (org-move-subtree-down (- (prefix-numeric-value arg))))
5431 (defun org-move-subtree-down (&optional arg)
5432 "Move the current subtree down past ARG headlines of the same level."
5433 (interactive "p")
5434 (setq arg (prefix-numeric-value arg))
5435 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5436 'outline-get-last-sibling))
5437 (ins-point (make-marker))
5438 (cnt (abs arg))
5439 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5440 ;; Select the tree
5441 (org-back-to-heading)
5442 (setq beg0 (point))
5443 (save-excursion
5444 (setq ne-beg (org-back-over-empty-lines))
5445 (setq beg (point)))
5446 (save-match-data
5447 (save-excursion (outline-end-of-heading)
5448 (setq folded (org-invisible-p)))
5449 (outline-end-of-subtree))
5450 (outline-next-heading)
5451 (setq ne-end (org-back-over-empty-lines))
5452 (setq end (point))
5453 (goto-char beg0)
5454 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5455 ;; include less whitespace
5456 (save-excursion
5457 (goto-char beg)
5458 (forward-line (- ne-beg ne-end))
5459 (setq beg (point))))
5460 ;; Find insertion point, with error handling
5461 (while (> cnt 0)
5462 (or (and (funcall movfunc) (looking-at outline-regexp))
5463 (progn (goto-char beg0)
5464 (error "Cannot move past superior level or buffer limit")))
5465 (setq cnt (1- cnt)))
5466 (if (> arg 0)
5467 ;; Moving forward - still need to move over subtree
5468 (progn (org-end-of-subtree t t)
5469 (save-excursion
5470 (org-back-over-empty-lines)
5471 (or (bolp) (newline)))))
5472 (setq ne-ins (org-back-over-empty-lines))
5473 (move-marker ins-point (point))
5474 (setq txt (buffer-substring beg end))
5475 (org-save-markers-in-region beg end)
5476 (delete-region beg end)
5477 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5478 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5479 (let ((bbb (point)))
5480 (insert-before-markers txt)
5481 (org-reinstall-markers-in-region bbb)
5482 (move-marker ins-point bbb))
5483 (or (bolp) (insert "\n"))
5484 (setq ins-end (point))
5485 (goto-char ins-point)
5486 (org-skip-whitespace)
5487 (when (and (< arg 0)
5488 (org-first-sibling-p)
5489 (> ne-ins ne-beg))
5490 ;; Move whitespace back to beginning
5491 (save-excursion
5492 (goto-char ins-end)
5493 (let ((kill-whole-line t))
5494 (kill-line (- ne-ins ne-beg)) (point)))
5495 (insert (make-string (- ne-ins ne-beg) ?\n)))
5496 (move-marker ins-point nil)
5497 (org-compact-display-after-subtree-move)
5498 (org-show-empty-lines-in-parent)
5499 (unless folded
5500 (org-show-entry)
5501 (show-children)
5502 (org-cycle-hide-drawers 'children))))
5504 (defvar org-subtree-clip ""
5505 "Clipboard for cut and paste of subtrees.
5506 This is actually only a copy of the kill, because we use the normal kill
5507 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5509 (defvar org-subtree-clip-folded nil
5510 "Was the last copied subtree folded?
5511 This is used to fold the tree back after pasting.")
5513 (defun org-cut-subtree (&optional n)
5514 "Cut the current subtree into the clipboard.
5515 With prefix arg N, cut this many sequential subtrees.
5516 This is a short-hand for marking the subtree and then cutting it."
5517 (interactive "p")
5518 (org-copy-subtree n 'cut))
5520 (defun org-copy-subtree (&optional n cut force-store-markers)
5521 "Cut the current subtree into the clipboard.
5522 With prefix arg N, cut this many sequential subtrees.
5523 This is a short-hand for marking the subtree and then copying it.
5524 If CUT is non-nil, actually cut the subtree.
5525 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5526 of some markers in the region, even if CUT is non-nil. This is
5527 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5528 (interactive "p")
5529 (let (beg end folded (beg0 (point)))
5530 (if (interactive-p)
5531 (org-back-to-heading nil) ; take what looks like a subtree
5532 (org-back-to-heading t)) ; take what is really there
5533 (org-back-over-empty-lines)
5534 (setq beg (point))
5535 (skip-chars-forward " \t\r\n")
5536 (save-match-data
5537 (save-excursion (outline-end-of-heading)
5538 (setq folded (org-invisible-p)))
5539 (condition-case nil
5540 (outline-forward-same-level (1- n))
5541 (error nil))
5542 (org-end-of-subtree t t))
5543 (org-back-over-empty-lines)
5544 (setq end (point))
5545 (goto-char beg0)
5546 (when (> end beg)
5547 (setq org-subtree-clip-folded folded)
5548 (when (or cut force-store-markers)
5549 (org-save-markers-in-region beg end))
5550 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5551 (setq org-subtree-clip (current-kill 0))
5552 (message "%s: Subtree(s) with %d characters"
5553 (if cut "Cut" "Copied")
5554 (length org-subtree-clip)))))
5556 (defun org-paste-subtree (&optional level tree for-yank)
5557 "Paste the clipboard as a subtree, with modification of headline level.
5558 The entire subtree is promoted or demoted in order to match a new headline
5559 level.
5561 If the cursor is at the beginning of a headline, the same level as
5562 that headline is used to paste the tree
5564 If not, the new level is derived from the *visible* headings
5565 before and after the insertion point, and taken to be the inferior headline
5566 level of the two. So if the previous visible heading is level 3 and the
5567 next is level 4 (or vice versa), level 4 will be used for insertion.
5568 This makes sure that the subtree remains an independent subtree and does
5569 not swallow low level entries.
5571 You can also force a different level, either by using a numeric prefix
5572 argument, or by inserting the heading marker by hand. For example, if the
5573 cursor is after \"*****\", then the tree will be shifted to level 5.
5575 If optional TREE is given, use this text instead of the kill ring.
5577 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5578 move back over whitespace before inserting, and move point to the end of
5579 the inserted text when done."
5580 (interactive "P")
5581 (unless (org-kill-is-subtree-p tree)
5582 (error "%s"
5583 (substitute-command-keys
5584 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5585 (let* ((visp (not (org-invisible-p)))
5586 (txt (or tree (and kill-ring (current-kill 0))))
5587 (^re (concat "^\\(" outline-regexp "\\)"))
5588 (re (concat "\\(" outline-regexp "\\)"))
5589 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5591 (old-level (if (string-match ^re txt)
5592 (- (match-end 0) (match-beginning 0) 1)
5593 -1))
5594 (force-level (cond (level (prefix-numeric-value level))
5595 ((and (looking-at "[ \t]*$")
5596 (string-match
5597 ^re_ (buffer-substring
5598 (point-at-bol) (point))))
5599 (- (match-end 1) (match-beginning 1)))
5600 ((and (bolp)
5601 (looking-at org-outline-regexp))
5602 (- (match-end 0) (point) 1))
5603 (t nil)))
5604 (previous-level (save-excursion
5605 (condition-case nil
5606 (progn
5607 (outline-previous-visible-heading 1)
5608 (if (looking-at re)
5609 (- (match-end 0) (match-beginning 0) 1)
5611 (error 1))))
5612 (next-level (save-excursion
5613 (condition-case nil
5614 (progn
5615 (or (looking-at outline-regexp)
5616 (outline-next-visible-heading 1))
5617 (if (looking-at re)
5618 (- (match-end 0) (match-beginning 0) 1)
5620 (error 1))))
5621 (new-level (or force-level (max previous-level next-level)))
5622 (shift (if (or (= old-level -1)
5623 (= new-level -1)
5624 (= old-level new-level))
5626 (- new-level old-level)))
5627 (delta (if (> shift 0) -1 1))
5628 (func (if (> shift 0) 'org-demote 'org-promote))
5629 (org-odd-levels-only nil)
5630 beg end newend)
5631 ;; Remove the forced level indicator
5632 (if force-level
5633 (delete-region (point-at-bol) (point)))
5634 ;; Paste
5635 (beginning-of-line 1)
5636 (unless for-yank (org-back-over-empty-lines))
5637 (setq beg (point))
5638 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5639 (insert-before-markers txt)
5640 (unless (string-match "\n\\'" txt) (insert "\n"))
5641 (setq newend (point))
5642 (org-reinstall-markers-in-region beg)
5643 (setq end (point))
5644 (goto-char beg)
5645 (skip-chars-forward " \t\n\r")
5646 (setq beg (point))
5647 (if (and (org-invisible-p) visp)
5648 (save-excursion (outline-show-heading)))
5649 ;; Shift if necessary
5650 (unless (= shift 0)
5651 (save-restriction
5652 (narrow-to-region beg end)
5653 (while (not (= shift 0))
5654 (org-map-region func (point-min) (point-max))
5655 (setq shift (+ delta shift)))
5656 (goto-char (point-min))
5657 (setq newend (point-max))))
5658 (when (or (interactive-p) for-yank)
5659 (message "Clipboard pasted as level %d subtree" new-level))
5660 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5661 kill-ring
5662 (eq org-subtree-clip (current-kill 0))
5663 org-subtree-clip-folded)
5664 ;; The tree was folded before it was killed/copied
5665 (hide-subtree))
5666 (and for-yank (goto-char newend))))
5668 (defun org-kill-is-subtree-p (&optional txt)
5669 "Check if the current kill is an outline subtree, or a set of trees.
5670 Returns nil if kill does not start with a headline, or if the first
5671 headline level is not the largest headline level in the tree.
5672 So this will actually accept several entries of equal levels as well,
5673 which is OK for `org-paste-subtree'.
5674 If optional TXT is given, check this string instead of the current kill."
5675 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5676 (start-level (and kill
5677 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5678 org-outline-regexp "\\)")
5679 kill)
5680 (- (match-end 2) (match-beginning 2) 1)))
5681 (re (concat "^" org-outline-regexp))
5682 (start (1+ (or (match-beginning 2) -1))))
5683 (if (not start-level)
5684 (progn
5685 nil) ;; does not even start with a heading
5686 (catch 'exit
5687 (while (setq start (string-match re kill (1+ start)))
5688 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5689 (throw 'exit nil)))
5690 t))))
5692 (defvar org-markers-to-move nil
5693 "Markers that should be moved with a cut-and-paste operation.
5694 Those markers are stored together with their positions relative to
5695 the start of the region.")
5697 (defun org-save-markers-in-region (beg end)
5698 "Check markers in region.
5699 If these markers are between BEG and END, record their position relative
5700 to BEG, so that after moving the block of text, we can put the markers back
5701 into place.
5702 This function gets called just before an entry or tree gets cut from the
5703 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5704 called immediately, to move the markers with the entries."
5705 (setq org-markers-to-move nil)
5706 (when (featurep 'org-clock)
5707 (org-clock-save-markers-for-cut-and-paste beg end))
5708 (when (featurep 'org-agenda)
5709 (org-agenda-save-markers-for-cut-and-paste beg end)))
5711 (defun org-check-and-save-marker (marker beg end)
5712 "Check if MARKER is between BEG and END.
5713 If yes, remember the marker and the distance to BEG."
5714 (when (and (marker-buffer marker)
5715 (equal (marker-buffer marker) (current-buffer)))
5716 (if (and (>= marker beg) (< marker end))
5717 (push (cons marker (- marker beg)) org-markers-to-move))))
5719 (defun org-reinstall-markers-in-region (beg)
5720 "Move all remembered markers to their position relative to BEG."
5721 (mapc (lambda (x)
5722 (move-marker (car x) (+ beg (cdr x))))
5723 org-markers-to-move)
5724 (setq org-markers-to-move nil))
5726 (defun org-narrow-to-subtree ()
5727 "Narrow buffer to the current subtree."
5728 (interactive)
5729 (save-excursion
5730 (save-match-data
5731 (narrow-to-region
5732 (progn (org-back-to-heading) (point))
5733 (progn (org-end-of-subtree t) (point))))))
5736 ;;; Outline Sorting
5738 (defun org-sort (with-case)
5739 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5740 Optional argument WITH-CASE means sort case-sensitively.
5741 With a double prefix argument, also remove duplicate entries."
5742 (interactive "P")
5743 (if (org-at-table-p)
5744 (org-call-with-arg 'org-table-sort-lines with-case)
5745 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5747 (defun org-sort-remove-invisible (s)
5748 (remove-text-properties 0 (length s) org-rm-props s)
5749 (while (string-match org-bracket-link-regexp s)
5750 (setq s (replace-match (if (match-end 2)
5751 (match-string 3 s)
5752 (match-string 1 s)) t t s)))
5755 (defvar org-priority-regexp) ; defined later in the file
5757 (defun org-sort-entries-or-items
5758 (&optional with-case sorting-type getkey-func compare-func property)
5759 "Sort entries on a certain level of an outline tree.
5760 If there is an active region, the entries in the region are sorted.
5761 Else, if the cursor is before the first entry, sort the top-level items.
5762 Else, the children of the entry at point are sorted.
5764 Sorting can be alphabetically, numerically, and by date/time as given by
5765 the first time stamp in the entry. The command prompts for the sorting
5766 type unless it has been given to the function through the SORTING-TYPE
5767 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5768 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5769 called with point at the beginning of the record. It must return either
5770 a string or a number that should serve as the sorting key for that record.
5772 Comparing entries ignores case by default. However, with an optional argument
5773 WITH-CASE, the sorting considers case as well."
5774 (interactive "P")
5775 (let ((case-func (if with-case 'identity 'downcase))
5776 start beg end stars re re2
5777 txt what tmp plain-list-p)
5778 ;; Find beginning and end of region to sort
5779 (cond
5780 ((org-region-active-p)
5781 ;; we will sort the region
5782 (setq end (region-end)
5783 what "region")
5784 (goto-char (region-beginning))
5785 (if (not (org-on-heading-p)) (outline-next-heading))
5786 (setq start (point)))
5787 ((org-at-item-p)
5788 ;; we will sort this plain list
5789 (org-beginning-of-item-list) (setq start (point))
5790 (org-end-of-item-list) (setq end (point))
5791 (goto-char start)
5792 (setq plain-list-p t
5793 what "plain list"))
5794 ((or (org-on-heading-p)
5795 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5796 ;; we will sort the children of the current headline
5797 (org-back-to-heading)
5798 (setq start (point)
5799 end (progn (org-end-of-subtree t t)
5800 (org-back-over-empty-lines)
5801 (point))
5802 what "children")
5803 (goto-char start)
5804 (show-subtree)
5805 (outline-next-heading))
5807 ;; we will sort the top-level entries in this file
5808 (goto-char (point-min))
5809 (or (org-on-heading-p) (outline-next-heading))
5810 (setq start (point) end (point-max) what "top-level")
5811 (goto-char start)
5812 (show-all)))
5814 (setq beg (point))
5815 (if (>= beg end) (error "Nothing to sort"))
5817 (unless plain-list-p
5818 (looking-at "\\(\\*+\\)")
5819 (setq stars (match-string 1)
5820 re (concat "^" (regexp-quote stars) " +")
5821 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5822 txt (buffer-substring beg end))
5823 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5824 (if (and (not (equal stars "*")) (string-match re2 txt))
5825 (error "Region to sort contains a level above the first entry")))
5827 (unless sorting-type
5828 (message
5829 (if plain-list-p
5830 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5831 "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:")
5832 what)
5833 (setq sorting-type (read-char-exclusive))
5835 (and (= (downcase sorting-type) ?f)
5836 (setq getkey-func
5837 (org-ido-completing-read "Sort using function: "
5838 obarray 'fboundp t nil nil))
5839 (setq getkey-func (intern getkey-func)))
5841 (and (= (downcase sorting-type) ?r)
5842 (setq property
5843 (org-ido-completing-read "Property: "
5844 (mapcar 'list (org-buffer-property-keys t))
5845 nil t))))
5847 (message "Sorting entries...")
5849 (save-restriction
5850 (narrow-to-region start end)
5852 (let ((dcst (downcase sorting-type))
5853 (now (current-time)))
5854 (sort-subr
5855 (/= dcst sorting-type)
5856 ;; This function moves to the beginning character of the "record" to
5857 ;; be sorted.
5858 (if plain-list-p
5859 (lambda nil
5860 (if (org-at-item-p) t (goto-char (point-max))))
5861 (lambda nil
5862 (if (re-search-forward re nil t)
5863 (goto-char (match-beginning 0))
5864 (goto-char (point-max)))))
5865 ;; This function moves to the last character of the "record" being
5866 ;; sorted.
5867 (if plain-list-p
5868 'org-end-of-item
5869 (lambda nil
5870 (save-match-data
5871 (condition-case nil
5872 (outline-forward-same-level 1)
5873 (error
5874 (goto-char (point-max)))))))
5876 ;; This function returns the value that gets sorted against.
5877 (if plain-list-p
5878 (lambda nil
5879 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5880 (cond
5881 ((= dcst ?n)
5882 (string-to-number (buffer-substring (match-end 0)
5883 (point-at-eol))))
5884 ((= dcst ?a)
5885 (buffer-substring (match-end 0) (point-at-eol)))
5886 ((= dcst ?t)
5887 (if (re-search-forward org-ts-regexp
5888 (point-at-eol) t)
5889 (org-time-string-to-time (match-string 0))
5890 now))
5891 ((= dcst ?f)
5892 (if getkey-func
5893 (progn
5894 (setq tmp (funcall getkey-func))
5895 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5896 tmp)
5897 (error "Invalid key function `%s'" getkey-func)))
5898 (t (error "Invalid sorting type `%c'" sorting-type)))))
5899 (lambda nil
5900 (cond
5901 ((= dcst ?n)
5902 (if (looking-at org-complex-heading-regexp)
5903 (string-to-number (match-string 4))
5904 nil))
5905 ((= dcst ?a)
5906 (if (looking-at org-complex-heading-regexp)
5907 (funcall case-func (match-string 4))
5908 nil))
5909 ((= dcst ?t)
5910 (if (re-search-forward org-ts-regexp
5911 (save-excursion
5912 (forward-line 2)
5913 (point)) t)
5914 (org-time-string-to-time (match-string 0))
5915 now))
5916 ((= dcst ?p)
5917 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5918 (string-to-char (match-string 2))
5919 org-default-priority))
5920 ((= dcst ?r)
5921 (or (org-entry-get nil property) ""))
5922 ((= dcst ?o)
5923 (if (looking-at org-complex-heading-regexp)
5924 (- 9999 (length (member (match-string 2)
5925 org-todo-keywords-1)))))
5926 ((= dcst ?f)
5927 (if getkey-func
5928 (progn
5929 (setq tmp (funcall getkey-func))
5930 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5931 tmp)
5932 (error "Invalid key function `%s'" getkey-func)))
5933 (t (error "Invalid sorting type `%c'" sorting-type)))))
5935 (cond
5936 ((= dcst ?a) 'string<)
5937 ((= dcst ?t) 'time-less-p)
5938 ((= dcst ?f) compare-func)
5939 (t nil)))))
5940 (message "Sorting entries...done")))
5942 (defun org-do-sort (table what &optional with-case sorting-type)
5943 "Sort TABLE of WHAT according to SORTING-TYPE.
5944 The user will be prompted for the SORTING-TYPE if the call to this
5945 function does not specify it. WHAT is only for the prompt, to indicate
5946 what is being sorted. The sorting key will be extracted from
5947 the car of the elements of the table.
5948 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5949 (unless sorting-type
5950 (message
5951 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5952 what)
5953 (setq sorting-type (read-char-exclusive)))
5954 (let ((dcst (downcase sorting-type))
5955 extractfun comparefun)
5956 ;; Define the appropriate functions
5957 (cond
5958 ((= dcst ?n)
5959 (setq extractfun 'string-to-number
5960 comparefun (if (= dcst sorting-type) '< '>)))
5961 ((= dcst ?a)
5962 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5963 (lambda(x) (downcase (org-sort-remove-invisible x))))
5964 comparefun (if (= dcst sorting-type)
5965 'string<
5966 (lambda (a b) (and (not (string< a b))
5967 (not (string= a b)))))))
5968 ((= dcst ?t)
5969 (setq extractfun
5970 (lambda (x)
5971 (if (or (string-match org-ts-regexp x)
5972 (string-match org-ts-regexp-both x))
5973 (time-to-seconds
5974 (org-time-string-to-time (match-string 0 x)))
5976 comparefun (if (= dcst sorting-type) '< '>)))
5977 (t (error "Invalid sorting type `%c'" sorting-type)))
5979 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5980 table)
5981 (lambda (a b) (funcall comparefun (car a) (car b))))))
5983 ;;; Editing source examples
5985 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5986 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5987 (defvar org-edit-src-force-single-line nil)
5988 (defvar org-edit-src-from-org-mode nil)
5989 (defvar org-edit-src-picture nil)
5991 (define-minor-mode org-exit-edit-mode
5992 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5994 (defun org-edit-src-code ()
5995 "Edit the source code example at point.
5996 An indirect buffer is created, and that buffer is then narrowed to the
5997 example at point and switched to the correct language mode. When done,
5998 exit by killing the buffer with \\[org-edit-src-exit]."
5999 (interactive)
6000 (let ((line (org-current-line))
6001 (case-fold-search t)
6002 (msg (substitute-command-keys
6003 "Edit, then exit with C-c ' (C-c and single quote)"))
6004 (info (org-edit-src-find-region-and-lang))
6005 (org-mode-p (eq major-mode 'org-mode))
6006 beg end lang lang-f single lfmt)
6007 (if (not info)
6009 (setq beg (nth 0 info)
6010 end (nth 1 info)
6011 lang (nth 2 info)
6012 single (nth 3 info)
6013 lfmt (nth 4 info)
6014 lang-f (intern (concat lang "-mode")))
6015 (unless (functionp lang-f)
6016 (error "No such language mode: %s" lang-f))
6017 (goto-line line)
6018 (if (get-buffer "*Org Edit Src Example*")
6019 (kill-buffer "*Org Edit Src Example*"))
6020 (switch-to-buffer (make-indirect-buffer (current-buffer)
6021 "*Org Edit Src Example*"))
6022 (narrow-to-region beg end)
6023 (remove-text-properties beg end '(display nil invisible nil
6024 intangible nil))
6025 (let ((org-inhibit-startup t))
6026 (funcall lang-f))
6027 (set (make-local-variable 'org-edit-src-force-single-line) single)
6028 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6029 (when lfmt
6030 (set (make-local-variable 'org-coderef-label-format) lfmt))
6031 (when org-mode-p
6032 (goto-char (point-min))
6033 (while (re-search-forward "^," nil t)
6034 (replace-match "")))
6035 (goto-line line)
6036 (org-exit-edit-mode)
6037 (org-set-local 'header-line-format msg)
6038 (message "%s" msg)
6039 t)))
6041 (defun org-edit-fixed-width-region ()
6042 "Edit the fixed-width ascii drawing at point.
6043 This must be a region where each line starts with a colon followed by
6044 a space character.
6045 An indirect buffer is created, and that buffer is then narrowed to the
6046 example at point and switched to artist-mode. When done,
6047 exit by killing the buffer with \\[org-edit-src-exit]."
6048 (interactive)
6049 (let ((line (org-current-line))
6050 (case-fold-search t)
6051 (msg (substitute-command-keys
6052 "Edit, then exit with C-c ' (C-c and single quote)"))
6053 (org-mode-p (eq major-mode 'org-mode))
6054 beg end)
6055 (beginning-of-line 1)
6056 (if (looking-at "[ \t]*[^:\n \t]")
6058 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6059 (setq beg (point) end beg)
6060 (save-excursion
6061 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6062 (setq beg (point-at-bol 2))
6063 (setq beg (point))))
6064 (save-excursion
6065 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6066 (setq end (1- (match-beginning 0)))
6067 (setq end (point))))
6068 (goto-line line))
6069 (if (get-buffer "*Org Edit Picture*")
6070 (kill-buffer "*Org Edit Picture*"))
6071 (switch-to-buffer (make-indirect-buffer (current-buffer)
6072 "*Org Edit Picture*"))
6073 (narrow-to-region beg end)
6074 (remove-text-properties beg end '(display nil invisible nil
6075 intangible nil))
6076 (when (fboundp 'font-lock-unfontify-region)
6077 (font-lock-unfontify-region (point-min) (point-max)))
6078 (cond
6079 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6080 (fundamental-mode)
6081 (artist-mode 1))
6082 (t (funcall org-edit-fixed-width-region-mode)))
6083 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6084 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6085 (set (make-local-variable 'org-edit-src-picture) t)
6086 (goto-char (point-min))
6087 (while (re-search-forward "^[ \t]*: ?" nil t)
6088 (replace-match ""))
6089 (goto-line line)
6090 (org-exit-edit-mode)
6091 (org-set-local 'header-line-format msg)
6092 (message "%s" msg)
6093 t)))
6096 (defun org-edit-src-find-region-and-lang ()
6097 "Find the region and language for a local edit.
6098 Return a list with beginning and end of the region, a string representing
6099 the language, a switch telling of the content should be in a single line."
6100 (let ((re-list
6101 (append
6102 org-edit-src-region-extra
6104 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6105 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6106 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6107 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6108 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6109 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6110 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6111 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6112 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6113 ("^#\\+html:" "\n" "html" single-line)
6114 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6115 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6116 ("^#\\+latex:" "\n" "latex" single-line)
6117 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6118 ("^#\\+ascii:" "\n" "ascii" single-line)
6120 (pos (point))
6121 re1 re2 single beg end lang lfmt match-re1)
6122 (catch 'exit
6123 (while (setq entry (pop re-list))
6124 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6125 single (nth 3 entry))
6126 (save-excursion
6127 (if (or (looking-at re1)
6128 (re-search-backward re1 nil t))
6129 (progn
6130 (setq match-re1 (match-string 0))
6131 (setq beg (match-end 0)
6132 lang (org-edit-src-get-lang lang)
6133 lfmt (org-edit-src-get-label-format match-re1))
6134 (if (and (re-search-forward re2 nil t)
6135 (>= (match-end 0) pos))
6136 (throw 'exit (list beg (match-beginning 0)
6137 lang single lfmt))))
6138 (if (or (looking-at re2)
6139 (re-search-forward re2 nil t))
6140 (progn
6141 (setq end (match-beginning 0))
6142 (if (and (re-search-backward re1 nil t)
6143 (<= (match-beginning 0) pos))
6144 (progn
6145 (setq lfmt (org-edit-src-get-label-format
6146 (match-string 0)))
6147 (throw 'exit
6148 (list (match-end 0) end
6149 (org-edit-src-get-lang lang)
6150 single lfmt))))))))))))
6152 (defun org-edit-src-get-lang (lang)
6153 "Extract the src language."
6154 (let ((m (match-string 0)))
6155 (cond
6156 ((stringp lang) lang)
6157 ((integerp lang) (match-string lang))
6158 ((and (eq lang 'lang)
6159 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6160 (match-string 1 m))
6161 ((and (eq lang 'style)
6162 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6163 (match-string 1 m))
6164 (t "fundamental"))))
6166 (defun org-edit-src-get-label-format (s)
6167 "Extract the label format."
6168 (save-match-data
6169 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6170 (match-string 1 s))))
6172 (defun org-edit-src-exit ()
6173 "Exit special edit and protect problematic lines."
6174 (interactive)
6175 (unless (buffer-base-buffer (current-buffer))
6176 (error "This is not an indirect buffer, something is wrong..."))
6177 (unless (> (point-min) 1)
6178 (error "This buffer is not narrowed, something is wrong..."))
6179 (goto-char (point-min))
6180 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6181 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6182 (when (org-bound-and-true-p org-edit-src-force-single-line)
6183 (goto-char (point-min))
6184 (while (re-search-forward "\n" nil t)
6185 (replace-match " "))
6186 (goto-char (point-min))
6187 (if (looking-at "\\s-*") (replace-match " "))
6188 (if (re-search-forward "\\s-+\\'" nil t)
6189 (replace-match "")))
6190 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6191 (goto-char (point-min))
6192 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6193 (replace-match ",\\1"))
6194 (when font-lock-mode
6195 (font-lock-unfontify-region (point-min) (point-max)))
6196 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6197 (when (org-bound-and-true-p org-edit-src-picture)
6198 (untabify (point-min) (point-max))
6199 (goto-char (point-min))
6200 (while (re-search-forward "^" nil t)
6201 (replace-match ": "))
6202 (when font-lock-mode
6203 (font-lock-unfontify-region (point-min) (point-max)))
6204 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6205 (kill-buffer (current-buffer))
6206 (and (org-mode-p) (org-restart-font-lock)))
6209 ;;; The orgstruct minor mode
6211 ;; Define a minor mode which can be used in other modes in order to
6212 ;; integrate the org-mode structure editing commands.
6214 ;; This is really a hack, because the org-mode structure commands use
6215 ;; keys which normally belong to the major mode. Here is how it
6216 ;; works: The minor mode defines all the keys necessary to operate the
6217 ;; structure commands, but wraps the commands into a function which
6218 ;; tests if the cursor is currently at a headline or a plain list
6219 ;; item. If that is the case, the structure command is used,
6220 ;; temporarily setting many Org-mode variables like regular
6221 ;; expressions for filling etc. However, when any of those keys is
6222 ;; used at a different location, function uses `key-binding' to look
6223 ;; up if the key has an associated command in another currently active
6224 ;; keymap (minor modes, major mode, global), and executes that
6225 ;; command. There might be problems if any of the keys is otherwise
6226 ;; used as a prefix key.
6228 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6229 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6230 ;; addresses this by checking explicitly for both bindings.
6232 (defvar orgstruct-mode-map (make-sparse-keymap)
6233 "Keymap for the minor `orgstruct-mode'.")
6235 (defvar org-local-vars nil
6236 "List of local variables, for use by `orgstruct-mode'")
6238 ;;;###autoload
6239 (define-minor-mode orgstruct-mode
6240 "Toggle the minor more `orgstruct-mode'.
6241 This mode is for using Org-mode structure commands in other modes.
6242 The following key behave as if Org-mode was active, if the cursor
6243 is on a headline, or on a plain list item (both in the definition
6244 of Org-mode).
6246 M-up Move entry/item up
6247 M-down Move entry/item down
6248 M-left Promote
6249 M-right Demote
6250 M-S-up Move entry/item up
6251 M-S-down Move entry/item down
6252 M-S-left Promote subtree
6253 M-S-right Demote subtree
6254 M-q Fill paragraph and items like in Org-mode
6255 C-c ^ Sort entries
6256 C-c - Cycle list bullet
6257 TAB Cycle item visibility
6258 M-RET Insert new heading/item
6259 S-M-RET Insert new TODO heading / Checkbox item
6260 C-c C-c Set tags / toggle checkbox"
6261 nil " OrgStruct" nil
6262 (org-load-modules-maybe)
6263 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6265 ;;;###autoload
6266 (defun turn-on-orgstruct ()
6267 "Unconditionally turn on `orgstruct-mode'."
6268 (orgstruct-mode 1))
6270 ;;;###autoload
6271 (defun turn-on-orgstruct++ ()
6272 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6273 In addition to setting orgstruct-mode, this also exports all indentation and
6274 autofilling variables from org-mode into the buffer. Note that turning
6275 off orgstruct-mode will *not* remove these additional settings."
6276 (orgstruct-mode 1)
6277 (let (var val)
6278 (mapc
6279 (lambda (x)
6280 (when (string-match
6281 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6282 (symbol-name (car x)))
6283 (setq var (car x) val (nth 1 x))
6284 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6285 org-local-vars)))
6287 (defun orgstruct-error ()
6288 "Error when there is no default binding for a structure key."
6289 (interactive)
6290 (error "This key has no function outside structure elements"))
6292 (defun orgstruct-setup ()
6293 "Setup orgstruct keymaps."
6294 (let ((nfunc 0)
6295 (bindings
6296 (list
6297 '([(meta up)] org-metaup)
6298 '([(meta down)] org-metadown)
6299 '([(meta left)] org-metaleft)
6300 '([(meta right)] org-metaright)
6301 '([(meta shift up)] org-shiftmetaup)
6302 '([(meta shift down)] org-shiftmetadown)
6303 '([(meta shift left)] org-shiftmetaleft)
6304 '([(meta shift right)] org-shiftmetaright)
6305 '([(shift up)] org-shiftup)
6306 '([(shift down)] org-shiftdown)
6307 '([(shift left)] org-shiftleft)
6308 '([(shift right)] org-shiftright)
6309 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6310 '("\M-q" fill-paragraph)
6311 '("\C-c^" org-sort)
6312 '("\C-c-" org-cycle-list-bullet)))
6313 elt key fun cmd)
6314 (while (setq elt (pop bindings))
6315 (setq nfunc (1+ nfunc))
6316 (setq key (org-key (car elt))
6317 fun (nth 1 elt)
6318 cmd (orgstruct-make-binding fun nfunc key))
6319 (org-defkey orgstruct-mode-map key cmd))
6321 ;; Special treatment needed for TAB and RET
6322 (org-defkey orgstruct-mode-map [(tab)]
6323 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6324 (org-defkey orgstruct-mode-map "\C-i"
6325 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6327 (org-defkey orgstruct-mode-map "\M-\C-m"
6328 (orgstruct-make-binding 'org-insert-heading 105
6329 "\M-\C-m" [(meta return)]))
6330 (org-defkey orgstruct-mode-map [(meta return)]
6331 (orgstruct-make-binding 'org-insert-heading 106
6332 [(meta return)] "\M-\C-m"))
6334 (org-defkey orgstruct-mode-map [(shift meta return)]
6335 (orgstruct-make-binding 'org-insert-todo-heading 107
6336 [(meta return)] "\M-\C-m"))
6338 (unless org-local-vars
6339 (setq org-local-vars (org-get-local-variables)))
6343 (defun orgstruct-make-binding (fun n &rest keys)
6344 "Create a function for binding in the structure minor mode.
6345 FUN is the command to call inside a table. N is used to create a unique
6346 command name. KEYS are keys that should be checked in for a command
6347 to execute outside of tables."
6348 (eval
6349 (list 'defun
6350 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6351 '(arg)
6352 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6353 "Outside of structure, run the binding of `"
6354 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6355 "'.")
6356 '(interactive "p")
6357 (list 'if
6358 '(org-context-p 'headline 'item)
6359 (list 'org-run-like-in-org-mode (list 'quote fun))
6360 (list 'let '(orgstruct-mode)
6361 (list 'call-interactively
6362 (append '(or)
6363 (mapcar (lambda (k)
6364 (list 'key-binding k))
6365 keys)
6366 '('orgstruct-error))))))))
6368 (defun org-context-p (&rest contexts)
6369 "Check if local context is any of CONTEXTS.
6370 Possible values in the list of contexts are `table', `headline', and `item'."
6371 (let ((pos (point)))
6372 (goto-char (point-at-bol))
6373 (prog1 (or (and (memq 'table contexts)
6374 (looking-at "[ \t]*|"))
6375 (and (memq 'headline contexts)
6376 ;;????????? (looking-at "\\*+"))
6377 (looking-at outline-regexp))
6378 (and (memq 'item contexts)
6379 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6380 (goto-char pos))))
6382 (defun org-get-local-variables ()
6383 "Return a list of all local variables in an org-mode buffer."
6384 (let (varlist)
6385 (with-current-buffer (get-buffer-create "*Org tmp*")
6386 (erase-buffer)
6387 (org-mode)
6388 (setq varlist (buffer-local-variables)))
6389 (kill-buffer "*Org tmp*")
6390 (delq nil
6391 (mapcar
6392 (lambda (x)
6393 (setq x
6394 (if (symbolp x)
6395 (list x)
6396 (list (car x) (list 'quote (cdr x)))))
6397 (if (string-match
6398 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6399 (symbol-name (car x)))
6400 x nil))
6401 varlist))))
6403 ;;;###autoload
6404 (defun org-run-like-in-org-mode (cmd)
6405 (org-load-modules-maybe)
6406 (unless org-local-vars
6407 (setq org-local-vars (org-get-local-variables)))
6408 (eval (list 'let org-local-vars
6409 (list 'call-interactively (list 'quote cmd)))))
6411 ;;;; Archiving
6413 (defun org-get-category (&optional pos)
6414 "Get the category applying to position POS."
6415 (get-text-property (or pos (point)) 'org-category))
6417 (defun org-refresh-category-properties ()
6418 "Refresh category text properties in the buffer."
6419 (let ((def-cat (cond
6420 ((null org-category)
6421 (if buffer-file-name
6422 (file-name-sans-extension
6423 (file-name-nondirectory buffer-file-name))
6424 "???"))
6425 ((symbolp org-category) (symbol-name org-category))
6426 (t org-category)))
6427 beg end cat pos optionp)
6428 (org-unmodified
6429 (save-excursion
6430 (save-restriction
6431 (widen)
6432 (goto-char (point-min))
6433 (put-text-property (point) (point-max) 'org-category def-cat)
6434 (while (re-search-forward
6435 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6436 (setq pos (match-end 0)
6437 optionp (equal (char-after (match-beginning 0)) ?#)
6438 cat (org-trim (match-string 2)))
6439 (if optionp
6440 (setq beg (point-at-bol) end (point-max))
6441 (org-back-to-heading t)
6442 (setq beg (point) end (org-end-of-subtree t t)))
6443 (put-text-property beg end 'org-category cat)
6444 (goto-char pos)))))))
6447 ;;;; Link Stuff
6449 ;;; Link abbreviations
6451 (defun org-link-expand-abbrev (link)
6452 "Apply replacements as defined in `org-link-abbrev-alist."
6453 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6454 (let* ((key (match-string 1 link))
6455 (as (or (assoc key org-link-abbrev-alist-local)
6456 (assoc key org-link-abbrev-alist)))
6457 (tag (and (match-end 2) (match-string 3 link)))
6458 rpl)
6459 (if (not as)
6460 link
6461 (setq rpl (cdr as))
6462 (cond
6463 ((symbolp rpl) (funcall rpl tag))
6464 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6465 ((string-match "%h" rpl)
6466 (replace-match (url-hexify-string (or tag "")) t t rpl))
6467 (t (concat rpl tag)))))
6468 link))
6470 ;;; Storing and inserting links
6472 (defvar org-insert-link-history nil
6473 "Minibuffer history for links inserted with `org-insert-link'.")
6475 (defvar org-stored-links nil
6476 "Contains the links stored with `org-store-link'.")
6478 (defvar org-store-link-plist nil
6479 "Plist with info about the most recently link created with `org-store-link'.")
6481 (defvar org-link-protocols nil
6482 "Link protocols added to Org-mode using `org-add-link-type'.")
6484 (defvar org-store-link-functions nil
6485 "List of functions that are called to create and store a link.
6486 Each function will be called in turn until one returns a non-nil
6487 value. Each function should check if it is responsible for creating
6488 this link (for example by looking at the major mode).
6489 If not, it must exit and return nil.
6490 If yes, it should return a non-nil value after a calling
6491 `org-store-link-props' with a list of properties and values.
6492 Special properties are:
6494 :type The link prefix. like \"http\". This must be given.
6495 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6496 This is obligatory as well.
6497 :description Optional default description for the second pair
6498 of brackets in an Org-mode link. The user can still change
6499 this when inserting this link into an Org-mode buffer.
6501 In addition to these, any additional properties can be specified
6502 and then used in remember templates.")
6504 (defun org-add-link-type (type &optional follow export)
6505 "Add TYPE to the list of `org-link-types'.
6506 Re-compute all regular expressions depending on `org-link-types'
6508 FOLLOW and EXPORT are two functions.
6510 FOLLOW should take the link path as the single argument and do whatever
6511 is necessary to follow the link, for example find a file or display
6512 a mail message.
6514 EXPORT should format the link path for export to one of the export formats.
6515 It should be a function accepting three arguments:
6517 path the path of the link, the text after the prefix (like \"http:\")
6518 desc the description of the link, if any, nil if there was no description
6519 format the export format, a symbol like `html' or `latex'.
6521 The function may use the FORMAT information to return different values
6522 depending on the format. The return value will be put literally into
6523 the exported file.
6524 Org-mode has a built-in default for exporting links. If you are happy with
6525 this default, there is no need to define an export function for the link
6526 type. For a simple example of an export function, see `org-bbdb.el'."
6527 (add-to-list 'org-link-types type t)
6528 (org-make-link-regexps)
6529 (if (assoc type org-link-protocols)
6530 (setcdr (assoc type org-link-protocols) (list follow export))
6531 (push (list type follow export) org-link-protocols)))
6533 ;;;###autoload
6534 (defun org-store-link (arg)
6535 "\\<org-mode-map>Store an org-link to the current location.
6536 This link is added to `org-stored-links' and can later be inserted
6537 into an org-buffer with \\[org-insert-link].
6539 For some link types, a prefix arg is interpreted:
6540 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6541 For file links, arg negates `org-context-in-file-links'."
6542 (interactive "P")
6543 (org-load-modules-maybe)
6544 (setq org-store-link-plist nil) ; reset
6545 (let (link cpltxt desc description search txt)
6546 (cond
6548 ((run-hook-with-args-until-success 'org-store-link-functions)
6549 (setq link (plist-get org-store-link-plist :link)
6550 desc (or (plist-get org-store-link-plist :description) link)))
6552 ((equal (buffer-name) "*Org Edit Src Example*")
6553 (let (label gc)
6554 (while (or (not label)
6555 (save-excursion
6556 (save-restriction
6557 (widen)
6558 (goto-char (point-min))
6559 (re-search-forward
6560 (regexp-quote (format org-coderef-label-format label))
6561 nil t))))
6562 (when label (message "Label exists already") (sit-for 2))
6563 (setq label (read-string "Code line label: " label)))
6564 (end-of-line 1)
6565 (setq link (format org-coderef-label-format label))
6566 (setq gc (- 79 (length link)))
6567 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6568 (insert link)
6569 (setq link (concat "(" label ")") desc nil)))
6571 ((eq major-mode 'calendar-mode)
6572 (let ((cd (calendar-cursor-to-date)))
6573 (setq link
6574 (format-time-string
6575 (car org-time-stamp-formats)
6576 (apply 'encode-time
6577 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6578 nil nil nil))))
6579 (org-store-link-props :type "calendar" :date cd)))
6581 ((eq major-mode 'w3-mode)
6582 (setq cpltxt (url-view-url t)
6583 link (org-make-link cpltxt))
6584 (org-store-link-props :type "w3" :url (url-view-url t)))
6586 ((eq major-mode 'w3m-mode)
6587 (setq cpltxt (or w3m-current-title w3m-current-url)
6588 link (org-make-link w3m-current-url))
6589 (org-store-link-props :type "w3m" :url (url-view-url t)))
6591 ((setq search (run-hook-with-args-until-success
6592 'org-create-file-search-functions))
6593 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6594 "::" search))
6595 (setq cpltxt (or description link)))
6597 ((eq major-mode 'image-mode)
6598 (setq cpltxt (concat "file:"
6599 (abbreviate-file-name buffer-file-name))
6600 link (org-make-link cpltxt))
6601 (org-store-link-props :type "image" :file buffer-file-name))
6603 ((eq major-mode 'dired-mode)
6604 ;; link to the file in the current line
6605 (setq cpltxt (concat "file:"
6606 (abbreviate-file-name
6607 (expand-file-name
6608 (dired-get-filename nil t))))
6609 link (org-make-link cpltxt)))
6611 ((and buffer-file-name (org-mode-p))
6612 (cond
6613 ((org-in-regexp "<<\\(.*?\\)>>")
6614 (setq cpltxt
6615 (concat "file:"
6616 (abbreviate-file-name buffer-file-name)
6617 "::" (match-string 1))
6618 link (org-make-link cpltxt)))
6619 ((and (featurep 'org-id)
6620 (or (eq org-link-to-org-use-id t)
6621 (and (eq org-link-to-org-use-id 'create-if-interactive)
6622 (interactive-p))
6623 (and org-link-to-org-use-id
6624 (condition-case nil
6625 (org-entry-get nil "ID")
6626 (error nil)))))
6627 ;; We can make a link using the ID.
6628 (setq link (condition-case nil
6629 (prog1 (org-id-store-link)
6630 (setq desc (plist-get org-store-link-plist
6631 :description)))
6632 (error
6633 ;; probably before first headline, link to file only
6634 (concat "file:"
6635 (abbreviate-file-name buffer-file-name))))))
6637 ;; Just link to current headline
6638 (setq cpltxt (concat "file:"
6639 (abbreviate-file-name buffer-file-name)))
6640 ;; Add a context search string
6641 (when (org-xor org-context-in-file-links arg)
6642 (setq txt (cond
6643 ((org-on-heading-p) nil)
6644 ((org-region-active-p)
6645 (buffer-substring (region-beginning) (region-end)))
6646 (t nil)))
6647 (when (or (null txt) (string-match "\\S-" txt))
6648 (setq cpltxt
6649 (concat cpltxt "::"
6650 (condition-case nil
6651 (org-make-org-heading-search-string txt)
6652 (error "")))
6653 desc "NONE")))
6654 (if (string-match "::\\'" cpltxt)
6655 (setq cpltxt (substring cpltxt 0 -2)))
6656 (setq link (org-make-link cpltxt)))))
6658 ((buffer-file-name (buffer-base-buffer))
6659 ;; Just link to this file here.
6660 (setq cpltxt (concat "file:"
6661 (abbreviate-file-name
6662 (buffer-file-name (buffer-base-buffer)))))
6663 ;; Add a context string
6664 (when (org-xor org-context-in-file-links arg)
6665 (setq txt (if (org-region-active-p)
6666 (buffer-substring (region-beginning) (region-end))
6667 (buffer-substring (point-at-bol) (point-at-eol))))
6668 ;; Only use search option if there is some text.
6669 (when (string-match "\\S-" txt)
6670 (setq cpltxt
6671 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6672 desc "NONE")))
6673 (setq link (org-make-link cpltxt)))
6675 ((interactive-p)
6676 (error "Cannot link to a buffer which is not visiting a file"))
6678 (t (setq link nil)))
6680 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6681 (setq link (or link cpltxt)
6682 desc (or desc cpltxt))
6683 (if (equal desc "NONE") (setq desc nil))
6685 (if (and (interactive-p) link)
6686 (progn
6687 (setq org-stored-links
6688 (cons (list link desc) org-stored-links))
6689 (message "Stored: %s" (or desc link)))
6690 (and link (org-make-link-string link desc)))))
6692 (defun org-store-link-props (&rest plist)
6693 "Store link properties, extract names and addresses."
6694 (let (x adr)
6695 (when (setq x (plist-get plist :from))
6696 (setq adr (mail-extract-address-components x))
6697 (setq plist (plist-put plist :fromname (car adr)))
6698 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6699 (when (setq x (plist-get plist :to))
6700 (setq adr (mail-extract-address-components x))
6701 (setq plist (plist-put plist :toname (car adr)))
6702 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6703 (let ((from (plist-get plist :from))
6704 (to (plist-get plist :to)))
6705 (when (and from to org-from-is-user-regexp)
6706 (setq plist
6707 (plist-put plist :fromto
6708 (if (string-match org-from-is-user-regexp from)
6709 (concat "to %t")
6710 (concat "from %f"))))))
6711 (setq org-store-link-plist plist))
6713 (defun org-add-link-props (&rest plist)
6714 "Add these properties to the link property list."
6715 (let (key value)
6716 (while plist
6717 (setq key (pop plist) value (pop plist))
6718 (setq org-store-link-plist
6719 (plist-put org-store-link-plist key value)))))
6721 (defun org-email-link-description (&optional fmt)
6722 "Return the description part of an email link.
6723 This takes information from `org-store-link-plist' and formats it
6724 according to FMT (default from `org-email-link-description-format')."
6725 (setq fmt (or fmt org-email-link-description-format))
6726 (let* ((p org-store-link-plist)
6727 (to (plist-get p :toaddress))
6728 (from (plist-get p :fromaddress))
6729 (table
6730 (list
6731 (cons "%c" (plist-get p :fromto))
6732 (cons "%F" (plist-get p :from))
6733 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6734 (cons "%T" (plist-get p :to))
6735 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6736 (cons "%s" (plist-get p :subject))
6737 (cons "%m" (plist-get p :message-id)))))
6738 (when (string-match "%c" fmt)
6739 ;; Check if the user wrote this message
6740 (if (and org-from-is-user-regexp from to
6741 (save-match-data (string-match org-from-is-user-regexp from)))
6742 (setq fmt (replace-match "to %t" t t fmt))
6743 (setq fmt (replace-match "from %f" t t fmt))))
6744 (org-replace-escapes fmt table)))
6746 (defun org-make-org-heading-search-string (&optional string heading)
6747 "Make search string for STRING or current headline."
6748 (interactive)
6749 (let ((s (or string (org-get-heading))))
6750 (unless (and string (not heading))
6751 ;; We are using a headline, clean up garbage in there.
6752 (if (string-match org-todo-regexp s)
6753 (setq s (replace-match "" t t s)))
6754 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6755 (setq s (replace-match "" t t s)))
6756 (setq s (org-trim s))
6757 (if (string-match (concat "^\\(" org-quote-string "\\|"
6758 org-comment-string "\\)") s)
6759 (setq s (replace-match "" t t s)))
6760 (while (string-match org-ts-regexp s)
6761 (setq s (replace-match "" t t s))))
6762 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6763 (setq s (replace-match " " t t s)))
6764 (or string (setq s (concat "*" s))) ; Add * for headlines
6765 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6767 (defun org-make-link (&rest strings)
6768 "Concatenate STRINGS."
6769 (apply 'concat strings))
6771 (defun org-make-link-string (link &optional description)
6772 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6773 (unless (string-match "\\S-" link)
6774 (error "Empty link"))
6775 (when (stringp description)
6776 ;; Remove brackets from the description, they are fatal.
6777 (while (string-match "\\[" description)
6778 (setq description (replace-match "{" t t description)))
6779 (while (string-match "\\]" description)
6780 (setq description (replace-match "}" t t description))))
6781 (when (equal (org-link-escape link) description)
6782 ;; No description needed, it is identical
6783 (setq description nil))
6784 (when (and (not description)
6785 (not (equal link (org-link-escape link))))
6786 (setq description (org-extract-attributes link)))
6787 (concat "[[" (org-link-escape link) "]"
6788 (if description (concat "[" description "]") "")
6789 "]"))
6791 (defconst org-link-escape-chars
6792 '((?\ . "%20")
6793 (?\[ . "%5B")
6794 (?\] . "%5D")
6795 (?\340 . "%E0") ; `a
6796 (?\342 . "%E2") ; ^a
6797 (?\347 . "%E7") ; ,c
6798 (?\350 . "%E8") ; `e
6799 (?\351 . "%E9") ; 'e
6800 (?\352 . "%EA") ; ^e
6801 (?\356 . "%EE") ; ^i
6802 (?\364 . "%F4") ; ^o
6803 (?\371 . "%F9") ; `u
6804 (?\373 . "%FB") ; ^u
6805 (?\; . "%3B")
6806 (?? . "%3F")
6807 (?= . "%3D")
6808 (?+ . "%2B")
6810 "Association list of escapes for some characters problematic in links.
6811 This is the list that is used for internal purposes.")
6813 (defconst org-link-escape-chars-browser
6814 '((?\ . "%20")) ; 32 for the SPC char
6815 "Association list of escapes for some characters problematic in links.
6816 This is the list that is used before handing over to the browser.")
6818 (defun org-link-escape (text &optional table)
6819 "Escape characters in TEXT that are problematic for links."
6820 (setq table (or table org-link-escape-chars))
6821 (when text
6822 (let ((re (mapconcat (lambda (x) (regexp-quote
6823 (char-to-string (car x))))
6824 table "\\|")))
6825 (while (string-match re text)
6826 (setq text
6827 (replace-match
6828 (cdr (assoc (string-to-char (match-string 0 text))
6829 table))
6830 t t text)))
6831 text)))
6833 (defun org-link-unescape (text &optional table)
6834 "Reverse the action of `org-link-escape'."
6835 (setq table (or table org-link-escape-chars))
6836 (when text
6837 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6838 table "\\|")))
6839 (while (string-match re text)
6840 (setq text
6841 (replace-match
6842 (char-to-string (car (rassoc (match-string 0 text) table)))
6843 t t text)))
6844 text)))
6846 (defun org-xor (a b)
6847 "Exclusive or."
6848 (if a (not b) b))
6850 (defun org-fixup-message-id-for-http (s)
6851 "Replace special characters in a message id, so it can be used in an http query."
6852 (while (string-match "<" s)
6853 (setq s (replace-match "%3C" t t s)))
6854 (while (string-match ">" s)
6855 (setq s (replace-match "%3E" t t s)))
6856 (while (string-match "@" s)
6857 (setq s (replace-match "%40" t t s)))
6860 ;;;###autoload
6861 (defun org-insert-link-global ()
6862 "Insert a link like Org-mode does.
6863 This command can be called in any mode to insert a link in Org-mode syntax."
6864 (interactive)
6865 (org-load-modules-maybe)
6866 (org-run-like-in-org-mode 'org-insert-link))
6868 (defun org-insert-link (&optional complete-file link-location)
6869 "Insert a link. At the prompt, enter the link.
6871 Completion can be used to insert any of the link protocol prefixes like
6872 http or ftp in use.
6874 The history can be used to select a link previously stored with
6875 `org-store-link'. When the empty string is entered (i.e. if you just
6876 press RET at the prompt), the link defaults to the most recently
6877 stored link. As SPC triggers completion in the minibuffer, you need to
6878 use M-SPC or C-q SPC to force the insertion of a space character.
6880 You will also be prompted for a description, and if one is given, it will
6881 be displayed in the buffer instead of the link.
6883 If there is already a link at point, this command will allow you to edit link
6884 and description parts.
6886 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6887 be selected using completion. The path to the file will be relative to the
6888 current directory if the file is in the current directory or a subdirectory.
6889 Otherwise, the link will be the absolute path as completed in the minibuffer
6890 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6891 option `org-link-file-path-type'.
6893 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6894 the current directory or below.
6896 With three \\[universal-argument] prefixes, negate the meaning of
6897 `org-keep-stored-link-after-insertion'.
6899 If `org-make-link-description-function' is non-nil, this function will be
6900 called with the link target, and the result will be the default
6901 link description.
6903 If the LINK-LOCATION parameter is non-nil, this value will be
6904 used as the link location instead of reading one interactively."
6905 (interactive "P")
6906 (let* ((wcf (current-window-configuration))
6907 (region (if (org-region-active-p)
6908 (buffer-substring (region-beginning) (region-end))))
6909 (remove (and region (list (region-beginning) (region-end))))
6910 (desc region)
6911 tmphist ; byte-compile incorrectly complains about this
6912 (link link-location)
6913 entry file)
6914 (cond
6915 (link-location) ; specified by arg, just use it.
6916 ((org-in-regexp org-bracket-link-regexp 1)
6917 ;; We do have a link at point, and we are going to edit it.
6918 (setq remove (list (match-beginning 0) (match-end 0)))
6919 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6920 (setq link (read-string "Link: "
6921 (org-link-unescape
6922 (org-match-string-no-properties 1)))))
6923 ((or (org-in-regexp org-angle-link-re)
6924 (org-in-regexp org-plain-link-re))
6925 ;; Convert to bracket link
6926 (setq remove (list (match-beginning 0) (match-end 0))
6927 link (read-string "Link: "
6928 (org-remove-angle-brackets (match-string 0)))))
6929 ((member complete-file '((4) (16)))
6930 ;; Completing read for file names.
6931 (setq file (read-file-name "File: "))
6932 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6933 (pwd1 (file-name-as-directory (abbreviate-file-name
6934 (expand-file-name ".")))))
6935 (cond
6936 ((equal complete-file '(16))
6937 (setq link (org-make-link
6938 "file:"
6939 (abbreviate-file-name (expand-file-name file)))))
6940 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6941 (setq link (org-make-link "file:" (match-string 1 file))))
6942 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6943 (expand-file-name file))
6944 (setq link (org-make-link
6945 "file:" (match-string 1 (expand-file-name file)))))
6946 (t (setq link (org-make-link "file:" file))))))
6948 ;; Read link, with completion for stored links.
6949 (with-output-to-temp-buffer "*Org Links*"
6950 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6951 (when org-stored-links
6952 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6953 (princ (mapconcat
6954 (lambda (x)
6955 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6956 (reverse org-stored-links) "\n"))))
6957 (let ((cw (selected-window)))
6958 (select-window (get-buffer-window "*Org Links*"))
6959 (setq truncate-lines t)
6960 (org-fit-window-to-buffer)
6961 (select-window cw))
6962 ;; Fake a link history, containing the stored links.
6963 (setq tmphist (append (mapcar 'car org-stored-links)
6964 org-insert-link-history))
6965 (unwind-protect
6966 (setq link
6967 (let ((org-completion-use-ido nil))
6968 (org-completing-read
6969 "Link: "
6970 (append
6971 (mapcar (lambda (x) (list (concat (car x) ":")))
6972 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6973 (mapcar (lambda (x) (list (concat x ":")))
6974 org-link-types))
6975 nil nil nil
6976 'tmphist
6977 (or (car (car org-stored-links))))))
6978 (set-window-configuration wcf)
6979 (kill-buffer "*Org Links*"))
6980 (setq entry (assoc link org-stored-links))
6981 (or entry (push link org-insert-link-history))
6982 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6983 (not org-keep-stored-link-after-insertion))
6984 (setq org-stored-links (delq (assoc link org-stored-links)
6985 org-stored-links)))
6986 (setq desc (or desc (nth 1 entry)))))
6988 (if (string-match org-plain-link-re link)
6989 ;; URL-like link, normalize the use of angular brackets.
6990 (setq link (org-make-link (org-remove-angle-brackets link))))
6992 ;; Check if we are linking to the current file with a search option
6993 ;; If yes, simplify the link by using only the search option.
6994 (when (and buffer-file-name
6995 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6996 (let* ((path (match-string 1 link))
6997 (case-fold-search nil)
6998 (search (match-string 2 link)))
6999 (save-match-data
7000 (if (equal (file-truename buffer-file-name) (file-truename path))
7001 ;; We are linking to this same file, with a search option
7002 (setq link search)))))
7004 ;; Check if we can/should use a relative path. If yes, simplify the link
7005 (when (string-match "^file:\\(.*\\)" link)
7006 (let* ((path (match-string 1 link))
7007 (origpath path)
7008 (case-fold-search nil))
7009 (cond
7010 ((or (eq org-link-file-path-type 'absolute)
7011 (equal complete-file '(16)))
7012 (setq path (abbreviate-file-name (expand-file-name path))))
7013 ((eq org-link-file-path-type 'noabbrev)
7014 (setq path (expand-file-name path)))
7015 ((eq org-link-file-path-type 'relative)
7016 (setq path (file-relative-name path)))
7018 (save-match-data
7019 (if (string-match (concat "^" (regexp-quote
7020 (file-name-as-directory
7021 (expand-file-name "."))))
7022 (expand-file-name path))
7023 ;; We are linking a file with relative path name.
7024 (setq path (substring (expand-file-name path)
7025 (match-end 0)))
7026 (setq path (abbreviate-file-name (expand-file-name path)))))))
7027 (setq link (concat "file:" path))
7028 (if (equal desc origpath)
7029 (setq desc path))))
7031 (if org-make-link-description-function
7032 (setq desc (funcall org-make-link-description-function link desc)))
7034 (setq desc (read-string "Description: " desc))
7035 (unless (string-match "\\S-" desc) (setq desc nil))
7036 (if remove (apply 'delete-region remove))
7037 (insert (org-make-link-string link desc))))
7039 (defun org-completing-read (&rest args)
7040 "Completing-read with SPACE being a normal character."
7041 (let ((minibuffer-local-completion-map
7042 (copy-keymap minibuffer-local-completion-map)))
7043 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7044 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7045 (apply 'org-ido-completing-read args)))
7047 (defun org-completing-read-no-ido (&rest args)
7048 (let (org-completion-use-ido)
7049 (apply 'org-completing-read args)))
7051 (defun org-ido-completing-read (&rest args)
7052 "Completing-read using `ido-mode' speedups if available"
7053 (if (and org-completion-use-ido
7054 (fboundp 'ido-completing-read)
7055 (boundp 'ido-mode) ido-mode
7056 (listp (second args)))
7057 (let ((ido-enter-matching-directory nil))
7058 (apply 'ido-completing-read (concat (car args))
7059 (mapcar (lambda (x) (car x)) (nth 1 args))
7060 (cddr args)))
7061 (apply 'completing-read args)))
7064 (defun org-extract-attributes (s)
7065 "Extract the attributes cookie from a string and set as text property."
7066 (let (a attr (start 0) key value)
7067 (save-match-data
7068 (when (string-match "{{\\([^}]+\\)}}$" s)
7069 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7070 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7071 (setq key (match-string 1 a) value (match-string 2 a)
7072 start (match-end 0)
7073 attr (plist-put attr (intern key) value))))
7074 (org-add-props s nil 'org-attr attr))
7077 (defun org-attributes-to-string (plist)
7078 "Format a property list into an HTML attribute list."
7079 (let ((s "") key value)
7080 (while plist
7081 (setq key (pop plist) value (pop plist))
7082 (and value
7083 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7086 ;;; Opening/following a link
7088 (defvar org-link-search-failed nil)
7090 (defun org-next-link ()
7091 "Move forward to the next link.
7092 If the link is in hidden text, expose it."
7093 (interactive)
7094 (when (and org-link-search-failed (eq this-command last-command))
7095 (goto-char (point-min))
7096 (message "Link search wrapped back to beginning of buffer"))
7097 (setq org-link-search-failed nil)
7098 (let* ((pos (point))
7099 (ct (org-context))
7100 (a (assoc :link ct)))
7101 (if a (goto-char (nth 2 a)))
7102 (if (re-search-forward org-any-link-re nil t)
7103 (progn
7104 (goto-char (match-beginning 0))
7105 (if (org-invisible-p) (org-show-context)))
7106 (goto-char pos)
7107 (setq org-link-search-failed t)
7108 (error "No further link found"))))
7110 (defun org-previous-link ()
7111 "Move backward to the previous link.
7112 If the link is in hidden text, expose it."
7113 (interactive)
7114 (when (and org-link-search-failed (eq this-command last-command))
7115 (goto-char (point-max))
7116 (message "Link search wrapped back to end of buffer"))
7117 (setq org-link-search-failed nil)
7118 (let* ((pos (point))
7119 (ct (org-context))
7120 (a (assoc :link ct)))
7121 (if a (goto-char (nth 1 a)))
7122 (if (re-search-backward org-any-link-re nil t)
7123 (progn
7124 (goto-char (match-beginning 0))
7125 (if (org-invisible-p) (org-show-context)))
7126 (goto-char pos)
7127 (setq org-link-search-failed t)
7128 (error "No further link found"))))
7130 (defun org-translate-link (s)
7131 "Translate a link string if a translation function has been defined."
7132 (if (and org-link-translation-function
7133 (fboundp org-link-translation-function)
7134 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7135 (progn
7136 (setq s (funcall org-link-translation-function
7137 (match-string 1) (match-string 2)))
7138 (concat (car s) ":" (cdr s)))
7141 (defun org-translate-link-from-planner (type path)
7142 "Translate a link from Emacs Planner syntax so that Org can follow it.
7143 This is still an experimental function, your mileage may vary."
7144 (cond
7145 ((member type '("http" "https" "news" "ftp"))
7146 ;; standard Internet links are the same.
7147 nil)
7148 ((and (equal type "irc") (string-match "^//" path))
7149 ;; Planner has two / at the beginning of an irc link, we have 1.
7150 ;; We should have zero, actually....
7151 (setq path (substring path 1)))
7152 ((and (equal type "lisp") (string-match "^/" path))
7153 ;; Planner has a slash, we do not.
7154 (setq type "elisp" path (substring path 1)))
7155 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7156 ;; A typical message link. Planner has the id after the fina slash,
7157 ;; we separate it with a hash mark
7158 (setq path (concat (match-string 1 path) "#"
7159 (org-remove-angle-brackets (match-string 2 path)))))
7161 (cons type path))
7163 (defun org-find-file-at-mouse (ev)
7164 "Open file link or URL at mouse."
7165 (interactive "e")
7166 (mouse-set-point ev)
7167 (org-open-at-point 'in-emacs))
7169 (defun org-open-at-mouse (ev)
7170 "Open file link or URL at mouse."
7171 (interactive "e")
7172 (mouse-set-point ev)
7173 (if (eq major-mode 'org-agenda-mode)
7174 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7175 (org-open-at-point))
7177 (defvar org-window-config-before-follow-link nil
7178 "The window configuration before following a link.
7179 This is saved in case the need arises to restore it.")
7181 (defvar org-open-link-marker (make-marker)
7182 "Marker pointing to the location where `org-open-at-point; was called.")
7184 ;;;###autoload
7185 (defun org-open-at-point-global ()
7186 "Follow a link like Org-mode does.
7187 This command can be called in any mode to follow a link that has
7188 Org-mode syntax."
7189 (interactive)
7190 (org-run-like-in-org-mode 'org-open-at-point))
7192 ;;;###autoload
7193 (defun org-open-link-from-string (s &optional arg)
7194 "Open a link in the string S, as if it was in Org-mode."
7195 (interactive "sLink: \nP")
7196 (with-temp-buffer
7197 (let ((org-inhibit-startup t))
7198 (org-mode)
7199 (insert s)
7200 (goto-char (point-min))
7201 (org-open-at-point arg))))
7203 (defun org-open-at-point (&optional in-emacs)
7204 "Open link at or after point.
7205 If there is no link at point, this function will search forward up to
7206 the end of the current subtree.
7207 Normally, files will be opened by an appropriate application. If the
7208 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7209 With a double prefix argument, try to open outside of Emacs, in the
7210 application the system uses for this file type."
7211 (interactive "P")
7212 (org-load-modules-maybe)
7213 (move-marker org-open-link-marker (point))
7214 (setq org-window-config-before-follow-link (current-window-configuration))
7215 (org-remove-occur-highlights nil nil t)
7216 (cond
7217 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7218 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7219 (org-footnote-action))
7221 (let (type path link line search (pos (point)))
7222 (catch 'match
7223 (save-excursion
7224 (skip-chars-forward "^]\n\r")
7225 (when (org-in-regexp org-bracket-link-regexp)
7226 (setq link (org-extract-attributes
7227 (org-link-unescape (org-match-string-no-properties 1))))
7228 (while (string-match " *\n *" link)
7229 (setq link (replace-match " " t t link)))
7230 (setq link (org-link-expand-abbrev link))
7231 (cond
7232 ((or (file-name-absolute-p link)
7233 (string-match "^\\.\\.?/" link))
7234 (setq type "file" path link))
7235 ((string-match org-link-re-with-space3 link)
7236 (setq type (match-string 1 link) path (match-string 2 link)))
7237 (t (setq type "thisfile" path link)))
7238 (throw 'match t)))
7240 (when (get-text-property (point) 'org-linked-text)
7241 (setq type "thisfile"
7242 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7243 (1+ (point)) (point))
7244 path (buffer-substring
7245 (previous-single-property-change pos 'org-linked-text)
7246 (next-single-property-change pos 'org-linked-text)))
7247 (throw 'match t))
7249 (save-excursion
7250 (when (or (org-in-regexp org-angle-link-re)
7251 (org-in-regexp org-plain-link-re))
7252 (setq type (match-string 1) path (match-string 2))
7253 (throw 'match t)))
7254 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7255 (setq type "tree-match"
7256 path (match-string 1))
7257 (throw 'match t))
7258 (save-excursion
7259 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7260 (setq type "tags"
7261 path (match-string 1))
7262 (while (string-match ":" path)
7263 (setq path (replace-match "+" t t path)))
7264 (throw 'match t))))
7265 (unless path
7266 (error "No link found"))
7267 ;; Remove any trailing spaces in path
7268 (if (string-match " +\\'" path)
7269 (setq path (replace-match "" t t path)))
7270 (if (and org-link-translation-function
7271 (fboundp org-link-translation-function))
7272 ;; Check if we need to translate the link
7273 (let ((tmp (funcall org-link-translation-function type path)))
7274 (setq type (car tmp) path (cdr tmp))))
7276 (cond
7278 ((assoc type org-link-protocols)
7279 (funcall (nth 1 (assoc type org-link-protocols)) path))
7281 ((equal type "mailto")
7282 (let ((cmd (car org-link-mailto-program))
7283 (args (cdr org-link-mailto-program)) args1
7284 (address path) (subject "") a)
7285 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7286 (setq address (match-string 1 path)
7287 subject (org-link-escape (match-string 2 path))))
7288 (while args
7289 (cond
7290 ((not (stringp (car args))) (push (pop args) args1))
7291 (t (setq a (pop args))
7292 (if (string-match "%a" a)
7293 (setq a (replace-match address t t a)))
7294 (if (string-match "%s" a)
7295 (setq a (replace-match subject t t a)))
7296 (push a args1))))
7297 (apply cmd (nreverse args1))))
7299 ((member type '("http" "https" "ftp" "news"))
7300 (browse-url (concat type ":" (org-link-escape
7301 path org-link-escape-chars-browser))))
7303 ((member type '("message"))
7304 (browse-url (concat type ":" path)))
7306 ((string= type "tags")
7307 (org-tags-view in-emacs path))
7308 ((string= type "thisfile")
7309 (if in-emacs
7310 (switch-to-buffer-other-window
7311 (org-get-buffer-for-internal-link (current-buffer)))
7312 (org-mark-ring-push))
7313 (let ((cmd `(org-link-search
7314 ,path
7315 ,(cond ((equal in-emacs '(4)) 'occur)
7316 ((equal in-emacs '(16)) 'org-occur)
7317 (t nil))
7318 ,pos)))
7319 (condition-case nil (eval cmd)
7320 (error (progn (widen) (eval cmd))))))
7322 ((string= type "tree-match")
7323 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7325 ((string= type "file")
7326 (if (string-match "::\\([0-9]+\\)\\'" path)
7327 (setq line (string-to-number (match-string 1 path))
7328 path (substring path 0 (match-beginning 0)))
7329 (if (string-match "::\\(.+\\)\\'" path)
7330 (setq search (match-string 1 path)
7331 path (substring path 0 (match-beginning 0)))))
7332 (if (string-match "[*?{]" (file-name-nondirectory path))
7333 (dired path)
7334 (org-open-file path in-emacs line search)))
7336 ((string= type "news")
7337 (require 'org-gnus)
7338 (org-gnus-follow-link path))
7340 ((string= type "shell")
7341 (let ((cmd path))
7342 (if (or (not org-confirm-shell-link-function)
7343 (funcall org-confirm-shell-link-function
7344 (format "Execute \"%s\" in shell? "
7345 (org-add-props cmd nil
7346 'face 'org-warning))))
7347 (progn
7348 (message "Executing %s" cmd)
7349 (shell-command cmd))
7350 (error "Abort"))))
7352 ((string= type "elisp")
7353 (let ((cmd path))
7354 (if (or (not org-confirm-elisp-link-function)
7355 (funcall org-confirm-elisp-link-function
7356 (format "Execute \"%s\" as elisp? "
7357 (org-add-props cmd nil
7358 'face 'org-warning))))
7359 (message "%s => %s" cmd
7360 (if (equal (string-to-char cmd) ?\()
7361 (eval (read cmd))
7362 (call-interactively (read cmd))))
7363 (error "Abort"))))
7366 (browse-url-at-point))))))
7367 (move-marker org-open-link-marker nil)
7368 (run-hook-with-args 'org-follow-link-hook))
7370 ;;;; Time estimates
7372 (defun org-get-effort (&optional pom)
7373 "Get the effort estimate for the current entry."
7374 (org-entry-get pom org-effort-property))
7376 ;;; File search
7378 (defvar org-create-file-search-functions nil
7379 "List of functions to construct the right search string for a file link.
7380 These functions are called in turn with point at the location to
7381 which the link should point.
7383 A function in the hook should first test if it would like to
7384 handle this file type, for example by checking the major-mode or
7385 the file extension. If it decides not to handle this file, it
7386 should just return nil to give other functions a chance. If it
7387 does handle the file, it must return the search string to be used
7388 when following the link. The search string will be part of the
7389 file link, given after a double colon, and `org-open-at-point'
7390 will automatically search for it. If special measures must be
7391 taken to make the search successful, another function should be
7392 added to the companion hook `org-execute-file-search-functions',
7393 which see.
7395 A function in this hook may also use `setq' to set the variable
7396 `description' to provide a suggestion for the descriptive text to
7397 be used for this link when it gets inserted into an Org-mode
7398 buffer with \\[org-insert-link].")
7400 (defvar org-execute-file-search-functions nil
7401 "List of functions to execute a file search triggered by a link.
7403 Functions added to this hook must accept a single argument, the
7404 search string that was part of the file link, the part after the
7405 double colon. The function must first check if it would like to
7406 handle this search, for example by checking the major-mode or the
7407 file extension. If it decides not to handle this search, it
7408 should just return nil to give other functions a chance. If it
7409 does handle the search, it must return a non-nil value to keep
7410 other functions from trying.
7412 Each function can access the current prefix argument through the
7413 variable `current-prefix-argument'. Note that a single prefix is
7414 used to force opening a link in Emacs, so it may be good to only
7415 use a numeric or double prefix to guide the search function.
7417 In case this is needed, a function in this hook can also restore
7418 the window configuration before `org-open-at-point' was called using:
7420 (set-window-configuration org-window-config-before-follow-link)")
7422 (defun org-link-search (s &optional type avoid-pos)
7423 "Search for a link search option.
7424 If S is surrounded by forward slashes, it is interpreted as a
7425 regular expression. In org-mode files, this will create an `org-occur'
7426 sparse tree. In ordinary files, `occur' will be used to list matches.
7427 If the current buffer is in `dired-mode', grep will be used to search
7428 in all files. If AVOID-POS is given, ignore matches near that position."
7429 (let ((case-fold-search t)
7430 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7431 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7432 (append '(("") (" ") ("\t") ("\n"))
7433 org-emphasis-alist)
7434 "\\|") "\\)"))
7435 (pos (point))
7436 (pre nil) (post nil)
7437 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7438 (cond
7439 ;; First check if there are any special
7440 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7441 ;; Now try the builtin stuff
7442 ((save-excursion
7443 (goto-char (point-min))
7444 (and
7445 (re-search-forward
7446 (concat "<<" (regexp-quote s0) ">>") nil t)
7447 (setq type 'dedicated
7448 pos (match-beginning 0))))
7449 ;; There is an exact target for this
7450 (goto-char pos))
7451 ((and (string-match "^(\\(.*\\))$" s0)
7452 (save-excursion
7453 (goto-char (point-min))
7454 (and
7455 (re-search-forward
7456 (concat "[^[]" (regexp-quote
7457 (format org-coderef-label-format
7458 (match-string 1 s0))))
7459 nil t)
7460 (setq type 'dedicated
7461 pos (1+ (match-beginning 0))))))
7462 ;; There is a coderef target for this
7463 (goto-char pos))
7464 ((string-match "^/\\(.*\\)/$" s)
7465 ;; A regular expression
7466 (cond
7467 ((org-mode-p)
7468 (org-occur (match-string 1 s)))
7469 ;;((eq major-mode 'dired-mode)
7470 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7471 (t (org-do-occur (match-string 1 s)))))
7473 ;; A normal search strings
7474 (when (equal (string-to-char s) ?*)
7475 ;; Anchor on headlines, post may include tags.
7476 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7477 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7478 s (substring s 1)))
7479 (remove-text-properties
7480 0 (length s)
7481 '(face nil mouse-face nil keymap nil fontified nil) s)
7482 ;; Make a series of regular expressions to find a match
7483 (setq words (org-split-string s "[ \n\r\t]+")
7485 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7486 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7487 "\\)" markers)
7488 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7489 re2a (concat "[ \t\r\n]" re2a_)
7490 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7491 re4 (concat "[^a-zA-Z_]" re4_)
7493 re1 (concat pre re2 post)
7494 re3 (concat pre (if pre re4_ re4) post)
7495 re5 (concat pre ".*" re4)
7496 re2 (concat pre re2)
7497 re2a (concat pre (if pre re2a_ re2a))
7498 re4 (concat pre (if pre re4_ re4))
7499 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7500 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7501 re5 "\\)"
7503 (cond
7504 ((eq type 'org-occur) (org-occur reall))
7505 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7506 (t (goto-char (point-min))
7507 (setq type 'fuzzy)
7508 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7509 (org-search-not-self 1 re1 nil t)
7510 (org-search-not-self 1 re2 nil t)
7511 (org-search-not-self 1 re2a nil t)
7512 (org-search-not-self 1 re3 nil t)
7513 (org-search-not-self 1 re4 nil t)
7514 (org-search-not-self 1 re5 nil t)
7516 (goto-char (match-beginning 1))
7517 (goto-char pos)
7518 (error "No match")))))
7520 ;; Normal string-search
7521 (goto-char (point-min))
7522 (if (search-forward s nil t)
7523 (goto-char (match-beginning 0))
7524 (error "No match"))))
7525 (and (org-mode-p) (org-show-context 'link-search))
7526 type))
7528 (defun org-search-not-self (group &rest args)
7529 "Execute `re-search-forward', but only accept matches that do not
7530 enclose the position of `org-open-link-marker'."
7531 (let ((m org-open-link-marker))
7532 (catch 'exit
7533 (while (apply 're-search-forward args)
7534 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7535 (goto-char (match-end group))
7536 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7537 (> (match-beginning 0) (marker-position m))
7538 (< (match-end 0) (marker-position m)))
7539 (save-match-data
7540 (or (not (org-in-regexp
7541 org-bracket-link-analytic-regexp 1))
7542 (not (match-end 4)) ; no description
7543 (and (<= (match-beginning 4) (point))
7544 (>= (match-end 4) (point))))))
7545 (throw 'exit (point))))))))
7547 (defun org-get-buffer-for-internal-link (buffer)
7548 "Return a buffer to be used for displaying the link target of internal links."
7549 (cond
7550 ((not org-display-internal-link-with-indirect-buffer)
7551 buffer)
7552 ((string-match "(Clone)$" (buffer-name buffer))
7553 (message "Buffer is already a clone, not making another one")
7554 ;; we also do not modify visibility in this case
7555 buffer)
7556 (t ; make a new indirect buffer for displaying the link
7557 (let* ((bn (buffer-name buffer))
7558 (ibn (concat bn "(Clone)"))
7559 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7560 (with-current-buffer ib (org-overview))
7561 ib))))
7563 (defun org-do-occur (regexp &optional cleanup)
7564 "Call the Emacs command `occur'.
7565 If CLEANUP is non-nil, remove the printout of the regular expression
7566 in the *Occur* buffer. This is useful if the regex is long and not useful
7567 to read."
7568 (occur regexp)
7569 (when cleanup
7570 (let ((cwin (selected-window)) win beg end)
7571 (when (setq win (get-buffer-window "*Occur*"))
7572 (select-window win))
7573 (goto-char (point-min))
7574 (when (re-search-forward "match[a-z]+" nil t)
7575 (setq beg (match-end 0))
7576 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7577 (setq end (1- (match-beginning 0)))))
7578 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7579 (goto-char (point-min))
7580 (select-window cwin))))
7582 ;;; The mark ring for links jumps
7584 (defvar org-mark-ring nil
7585 "Mark ring for positions before jumps in Org-mode.")
7586 (defvar org-mark-ring-last-goto nil
7587 "Last position in the mark ring used to go back.")
7588 ;; Fill and close the ring
7589 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7590 (loop for i from 1 to org-mark-ring-length do
7591 (push (make-marker) org-mark-ring))
7592 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7593 org-mark-ring)
7595 (defun org-mark-ring-push (&optional pos buffer)
7596 "Put the current position or POS into the mark ring and rotate it."
7597 (interactive)
7598 (setq pos (or pos (point)))
7599 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7600 (move-marker (car org-mark-ring)
7601 (or pos (point))
7602 (or buffer (current-buffer)))
7603 (message "%s"
7604 (substitute-command-keys
7605 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7607 (defun org-mark-ring-goto (&optional n)
7608 "Jump to the previous position in the mark ring.
7609 With prefix arg N, jump back that many stored positions. When
7610 called several times in succession, walk through the entire ring.
7611 Org-mode commands jumping to a different position in the current file,
7612 or to another Org-mode file, automatically push the old position
7613 onto the ring."
7614 (interactive "p")
7615 (let (p m)
7616 (if (eq last-command this-command)
7617 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7618 (setq p org-mark-ring))
7619 (setq org-mark-ring-last-goto p)
7620 (setq m (car p))
7621 (switch-to-buffer (marker-buffer m))
7622 (goto-char m)
7623 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7625 (defun org-remove-angle-brackets (s)
7626 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7627 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7629 (defun org-add-angle-brackets (s)
7630 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7631 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7633 (defun org-remove-double-quotes (s)
7634 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7635 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7638 ;;; Following specific links
7640 (defun org-follow-timestamp-link ()
7641 (cond
7642 ((org-at-date-range-p t)
7643 (let ((org-agenda-start-on-weekday)
7644 (t1 (match-string 1))
7645 (t2 (match-string 2)))
7646 (setq t1 (time-to-days (org-time-string-to-time t1))
7647 t2 (time-to-days (org-time-string-to-time t2)))
7648 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7649 ((org-at-timestamp-p t)
7650 (org-agenda-list nil (time-to-days (org-time-string-to-time
7651 (substring (match-string 1) 0 10)))
7653 (t (error "This should not happen"))))
7656 ;;; Following file links
7657 (defvar org-wait nil)
7658 (defun org-open-file (path &optional in-emacs line search)
7659 "Open the file at PATH.
7660 First, this expands any special file name abbreviations. Then the
7661 configuration variable `org-file-apps' is checked if it contains an
7662 entry for this file type, and if yes, the corresponding command is launched.
7664 If no application is found, Emacs simply visits the file.
7666 With optional prefix argument IN-EMACS, Emacs will visit the file.
7667 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7668 and o use an external application to visit the file.
7670 Optional LINE specifies a line to go to, optional SEARCH a string to
7671 search for. If LINE or SEARCH is given, the file will always be
7672 opened in Emacs.
7673 If the file does not exist, an error is thrown."
7674 (setq in-emacs (or in-emacs line search))
7675 (let* ((file (if (equal path "")
7676 buffer-file-name
7677 (substitute-in-file-name (expand-file-name path))))
7678 (apps (append org-file-apps (org-default-apps)))
7679 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7680 (dirp (if remp nil (file-directory-p file)))
7681 (file (if (and dirp org-open-directory-means-index-dot-org)
7682 (concat (file-name-as-directory file) "index.org")
7683 file))
7684 (a-m-a-p (assq 'auto-mode apps))
7685 (dfile (downcase file))
7686 (old-buffer (current-buffer))
7687 (old-pos (point))
7688 (old-mode major-mode)
7689 ext cmd)
7690 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7691 (setq ext (match-string 1 dfile))
7692 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7693 (setq ext (match-string 1 dfile))))
7694 (cond
7695 ((equal in-emacs '(16))
7696 (setq cmd (cdr (assoc 'system apps))))
7697 (in-emacs (setq cmd 'emacs))
7699 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7700 (and dirp (cdr (assoc 'directory apps)))
7701 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7702 'string-match)
7703 (cdr (assoc ext apps))
7704 (cdr (assoc t apps))))))
7705 (when (eq cmd 'system)
7706 (setq cmd (cdr (assoc 'system apps))))
7707 (when (eq cmd 'default)
7708 (setq cmd (cdr (assoc t apps))))
7709 (when (eq cmd 'mailcap)
7710 (require 'mailcap)
7711 (mailcap-parse-mailcaps)
7712 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7713 (command (mailcap-mime-info mime-type)))
7714 (if (stringp command)
7715 (setq cmd command)
7716 (setq cmd 'emacs))))
7717 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7718 (not (file-exists-p file))
7719 (not org-open-non-existing-files))
7720 (error "No such file: %s" file))
7721 (cond
7722 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7723 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7724 (while (string-match "['\"]%s['\"]" cmd)
7725 (setq cmd (replace-match "%s" t t cmd)))
7726 (while (string-match "%s" cmd)
7727 (setq cmd (replace-match
7728 (save-match-data
7729 (shell-quote-argument
7730 (convert-standard-filename file)))
7731 t t cmd)))
7732 (save-window-excursion
7733 (start-process-shell-command cmd nil cmd)
7734 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7736 ((or (stringp cmd)
7737 (eq cmd 'emacs))
7738 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7739 (widen)
7740 (if line (goto-line line)
7741 (if search (org-link-search search))))
7742 ((consp cmd)
7743 (let ((file (convert-standard-filename file)))
7744 (eval cmd)))
7745 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7746 (and (org-mode-p) (eq old-mode 'org-mode)
7747 (or (not (equal old-buffer (current-buffer)))
7748 (not (equal old-pos (point))))
7749 (org-mark-ring-push old-pos old-buffer))))
7751 (defun org-default-apps ()
7752 "Return the default applications for this operating system."
7753 (cond
7754 ((eq system-type 'darwin)
7755 org-file-apps-defaults-macosx)
7756 ((eq system-type 'windows-nt)
7757 org-file-apps-defaults-windowsnt)
7758 (t org-file-apps-defaults-gnu)))
7760 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7761 "Convert extensions to regular expressions in the cars of LIST.
7762 Also, weed out any non-string entries, because the return value is used
7763 only for regexp matching.
7764 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7765 point to the symbol `emacs', indicating that the file should
7766 be opened in Emacs."
7767 (append
7768 (delq nil
7769 (mapcar (lambda (x)
7770 (if (not (stringp (car x)))
7772 (if (string-match "\\W" (car x))
7774 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7775 list))
7776 (if add-auto-mode
7777 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7779 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7780 (defun org-file-remote-p (file)
7781 "Test whether FILE specifies a location on a remote system.
7782 Return non-nil if the location is indeed remote.
7784 For example, the filename \"/user@host:/foo\" specifies a location
7785 on the system \"/user@host:\"."
7786 (cond ((fboundp 'file-remote-p)
7787 (file-remote-p file))
7788 ((fboundp 'tramp-handle-file-remote-p)
7789 (tramp-handle-file-remote-p file))
7790 ((and (boundp 'ange-ftp-name-format)
7791 (string-match (car ange-ftp-name-format) file))
7793 (t nil)))
7796 ;;;; Refiling
7798 (defun org-get-org-file ()
7799 "Read a filename, with default directory `org-directory'."
7800 (let ((default (or org-default-notes-file remember-data-file)))
7801 (read-file-name (format "File name [%s]: " default)
7802 (file-name-as-directory org-directory)
7803 default)))
7805 (defun org-notes-order-reversed-p ()
7806 "Check if the current file should receive notes in reversed order."
7807 (cond
7808 ((not org-reverse-note-order) nil)
7809 ((eq t org-reverse-note-order) t)
7810 ((not (listp org-reverse-note-order)) nil)
7811 (t (catch 'exit
7812 (let ((all org-reverse-note-order)
7813 entry)
7814 (while (setq entry (pop all))
7815 (if (string-match (car entry) buffer-file-name)
7816 (throw 'exit (cdr entry))))
7817 nil)))))
7819 (defvar org-refile-target-table nil
7820 "The list of refile targets, created by `org-refile'.")
7822 (defvar org-agenda-new-buffers nil
7823 "Buffers created to visit agenda files.")
7825 (defun org-get-refile-targets (&optional default-buffer)
7826 "Produce a table with refile targets."
7827 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7828 targets txt re files f desc descre fast-path-p level)
7829 (message "Getting targets...")
7830 (with-current-buffer (or default-buffer (current-buffer))
7831 (while (setq entry (pop entries))
7832 (setq files (car entry) desc (cdr entry))
7833 (setq fast-path-p nil)
7834 (cond
7835 ((null files) (setq files (list (current-buffer))))
7836 ((eq files 'org-agenda-files)
7837 (setq files (org-agenda-files 'unrestricted)))
7838 ((and (symbolp files) (fboundp files))
7839 (setq files (funcall files)))
7840 ((and (symbolp files) (boundp files))
7841 (setq files (symbol-value files))))
7842 (if (stringp files) (setq files (list files)))
7843 (cond
7844 ((eq (car desc) :tag)
7845 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7846 ((eq (car desc) :todo)
7847 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7848 ((eq (car desc) :regexp)
7849 (setq descre (cdr desc)))
7850 ((eq (car desc) :level)
7851 (setq descre (concat "^\\*\\{" (number-to-string
7852 (if org-odd-levels-only
7853 (1- (* 2 (cdr desc)))
7854 (cdr desc)))
7855 "\\}[ \t]")))
7856 ((eq (car desc) :maxlevel)
7857 (setq fast-path-p t)
7858 (setq descre (concat "^\\*\\{1," (number-to-string
7859 (if org-odd-levels-only
7860 (1- (* 2 (cdr desc)))
7861 (cdr desc)))
7862 "\\}[ \t]")))
7863 (t (error "Bad refiling target description %s" desc)))
7864 (while (setq f (pop files))
7865 (save-excursion
7866 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7867 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7868 (setq f (expand-file-name f))
7869 (save-excursion
7870 (save-restriction
7871 (widen)
7872 (goto-char (point-min))
7873 (while (re-search-forward descre nil t)
7874 (goto-char (point-at-bol))
7875 (when (looking-at org-complex-heading-regexp)
7876 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7877 txt (org-link-display-format (match-string 4))
7878 re (concat "^" (regexp-quote
7879 (buffer-substring (match-beginning 1)
7880 (match-end 4)))))
7881 (if (match-end 5) (setq re (concat re "[ \t]+"
7882 (regexp-quote
7883 (match-string 5)))))
7884 (setq re (concat re "[ \t]*$"))
7885 (when org-refile-use-outline-path
7886 (setq txt (mapconcat 'org-protect-slash
7887 (append
7888 (if (eq org-refile-use-outline-path 'file)
7889 (list (file-name-nondirectory
7890 (buffer-file-name (buffer-base-buffer))))
7891 (if (eq org-refile-use-outline-path 'full-file-path)
7892 (list (buffer-file-name (buffer-base-buffer)))))
7893 (org-get-outline-path fast-path-p level txt)
7894 (list txt))
7895 "/")))
7896 (push (list txt f re (point)) targets))
7897 (goto-char (point-at-eol))))))))
7898 (message "Getting targets...done")
7899 (nreverse targets))))
7901 (defun org-protect-slash (s)
7902 (while (string-match "/" s)
7903 (setq s (replace-match "\\" t t s)))
7906 (defvar org-olpa (make-vector 20 nil))
7908 (defun org-get-outline-path (&optional fastp level heading)
7909 "Return the outline path to the current entry, as a list."
7910 (if fastp
7911 (progn
7912 (if (> level 19)
7913 (error "Outline path failure, more than 19 levels."))
7914 (loop for i from level upto 19 do
7915 (aset org-olpa i nil))
7916 (prog1
7917 (delq nil (append org-olpa nil))
7918 (aset org-olpa level heading)))
7919 (let (rtn)
7920 (save-excursion
7921 (while (org-up-heading-safe)
7922 (when (looking-at org-complex-heading-regexp)
7923 (push (org-match-string-no-properties 4) rtn)))
7924 rtn))))
7926 (defvar org-refile-history nil
7927 "History for refiling operations.")
7929 (defun org-refile (&optional goto default-buffer)
7930 "Move the entry at point to another heading.
7931 The list of target headings is compiled using the information in
7932 `org-refile-targets', which see. This list is created before each use
7933 and will therefore always be up-to-date.
7935 At the target location, the entry is filed as a subitem of the target heading.
7936 Depending on `org-reverse-note-order', the new subitem will either be the
7937 first or the last subitem.
7939 If there is an active region, all entries in that region will be moved.
7940 However, the region must fulfil the requirement that the first heading
7941 is the first one sets the top-level of the moved text - at most siblings
7942 below it are allowed.
7944 With prefix arg GOTO, the command will only visit the target location,
7945 not actually move anything.
7946 With a double prefix `C-u C-u', go to the location where the last refiling
7947 operation has put the subtree."
7948 (interactive "P")
7949 (let* ((cbuf (current-buffer))
7950 (regionp (org-region-active-p))
7951 (region-start (and regionp (region-beginning)))
7952 (region-end (and regionp (region-end)))
7953 (region-length (and regionp (- region-end region-start)))
7954 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7955 pos it nbuf file re level reversed)
7956 (when regionp (goto-char region-start)
7957 (unless (org-kill-is-subtree-p
7958 (buffer-substring region-start region-end))
7959 (error "The region is not a (sequence of) subtree(s)")))
7960 (if (equal goto '(16))
7961 (org-refile-goto-last-stored)
7962 (when (setq it (org-refile-get-location
7963 (if goto "Goto: " "Refile to: ") default-buffer))
7964 (setq file (nth 1 it)
7965 re (nth 2 it)
7966 pos (nth 3 it))
7967 (if (and (equal (buffer-file-name) file)
7968 (if regionp
7969 (and (>= pos region-start)
7970 (<= pos region-end))
7971 (and (>= pos (point))
7972 (< pos (save-excursion
7973 (org-end-of-subtree t t))))))
7974 (error "Cannot refile to position inside the tree or region"))
7976 (setq nbuf (or (find-buffer-visiting file)
7977 (find-file-noselect file)))
7978 (if goto
7979 (progn
7980 (switch-to-buffer nbuf)
7981 (goto-char pos)
7982 (org-show-context 'org-goto))
7983 (if regionp
7984 (progn
7985 (kill-new (buffer-substring region-start region-end))
7986 (org-save-markers-in-region region-start region-end))
7987 (org-copy-subtree 1 nil t))
7988 (save-excursion
7989 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7990 (find-file-noselect file))))
7991 (setq reversed (org-notes-order-reversed-p))
7992 (save-excursion
7993 (save-restriction
7994 (widen)
7995 (goto-char pos)
7996 (looking-at outline-regexp)
7997 (setq level (org-get-valid-level (funcall outline-level) 1))
7998 (goto-char
7999 (if reversed
8000 (or (outline-next-heading) (point-max))
8001 (or (save-excursion (outline-get-next-sibling))
8002 (org-end-of-subtree t t)
8003 (point-max))))
8004 (if (not (bolp)) (newline))
8005 (bookmark-set "org-refile-last-stored")
8006 (org-paste-subtree level))))
8007 (if regionp
8008 (delete-region (point) (+ (point) region-length))
8009 (org-cut-subtree))
8010 (setq org-markers-to-move nil)
8011 (message "Refiled to \"%s\"" (car it)))))))
8013 (defun org-refile-goto-last-stored ()
8014 "Go to the location where the last refile was stored."
8015 (interactive)
8016 (bookmark-jump "org-refile-last-stored")
8017 (message "This is the location of the last refile"))
8019 (defun org-refile-get-location (&optional prompt default-buffer)
8020 "Prompt the user for a refile location, using PROMPT."
8021 (let ((org-refile-targets org-refile-targets)
8022 (org-refile-use-outline-path org-refile-use-outline-path))
8023 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8024 (unless org-refile-target-table
8025 (error "No refile targets"))
8026 (let* ((cbuf (current-buffer))
8027 (partial-completion-mode nil)
8028 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8029 (cfunc (if (and org-refile-use-outline-path
8030 org-outline-path-complete-in-steps)
8031 'org-olpath-completing-read
8032 'org-ido-completing-read))
8033 (extra (if org-refile-use-outline-path "/" ""))
8034 (filename (and cfn (expand-file-name cfn)))
8035 (tbl (mapcar
8036 (lambda (x)
8037 (if (not (equal filename (nth 1 x)))
8038 (cons (concat (car x) extra " ("
8039 (file-name-nondirectory (nth 1 x)) ")")
8040 (cdr x))
8041 (cons (concat (car x) extra) (cdr x))))
8042 org-refile-target-table))
8043 (completion-ignore-case t))
8044 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8045 tbl)))
8047 (defun org-olpath-completing-read (prompt collection &rest args)
8048 "Read an outline path like a file name."
8049 (let ((thetable collection)
8050 (org-completion-use-ido nil)) ; does not work with ido.
8051 (apply
8052 'org-ido-completing-read prompt
8053 (lambda (string predicate &optional flag)
8054 (let (rtn r f (l (length string)))
8055 (cond
8056 ((eq flag nil)
8057 ;; try completion
8058 (try-completion string thetable))
8059 ((eq flag t)
8060 ;; all-completions
8061 (setq rtn (all-completions string thetable predicate))
8062 (mapcar
8063 (lambda (x)
8064 (setq r (substring x l))
8065 (if (string-match " ([^)]*)$" x)
8066 (setq f (match-string 0 x))
8067 (setq f ""))
8068 (if (string-match "/" r)
8069 (concat string (substring r 0 (match-end 0)) f)
8071 rtn))
8072 ((eq flag 'lambda)
8073 ;; exact match?
8074 (assoc string thetable)))
8076 args)))
8078 ;;;; Dynamic blocks
8080 (defun org-find-dblock (name)
8081 "Find the first dynamic block with name NAME in the buffer.
8082 If not found, stay at current position and return nil."
8083 (let (pos)
8084 (save-excursion
8085 (goto-char (point-min))
8086 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8087 nil t)
8088 (match-beginning 0))))
8089 (if pos (goto-char pos))
8090 pos))
8092 (defconst org-dblock-start-re
8093 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8094 "Matches the startline of a dynamic block, with parameters.")
8096 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8097 "Matches the end of a dynamic block.")
8099 (defun org-create-dblock (plist)
8100 "Create a dynamic block section, with parameters taken from PLIST.
8101 PLIST must contain a :name entry which is used as name of the block."
8102 (unless (bolp) (newline))
8103 (let ((name (plist-get plist :name)))
8104 (insert "#+BEGIN: " name)
8105 (while plist
8106 (if (eq (car plist) :name)
8107 (setq plist (cddr plist))
8108 (insert " " (prin1-to-string (pop plist)))))
8109 (insert "\n\n#+END:\n")
8110 (beginning-of-line -2)))
8112 (defun org-prepare-dblock ()
8113 "Prepare dynamic block for refresh.
8114 This empties the block, puts the cursor at the insert position and returns
8115 the property list including an extra property :name with the block name."
8116 (unless (looking-at org-dblock-start-re)
8117 (error "Not at a dynamic block"))
8118 (let* ((begdel (1+ (match-end 0)))
8119 (name (org-no-properties (match-string 1)))
8120 (params (append (list :name name)
8121 (read (concat "(" (match-string 3) ")")))))
8122 (unless (re-search-forward org-dblock-end-re nil t)
8123 (error "Dynamic block not terminated"))
8124 (setq params
8125 (append params
8126 (list :content (buffer-substring
8127 begdel (match-beginning 0)))))
8128 (delete-region begdel (match-beginning 0))
8129 (goto-char begdel)
8130 (open-line 1)
8131 params))
8133 (defun org-map-dblocks (&optional command)
8134 "Apply COMMAND to all dynamic blocks in the current buffer.
8135 If COMMAND is not given, use `org-update-dblock'."
8136 (let ((cmd (or command 'org-update-dblock))
8137 pos)
8138 (save-excursion
8139 (goto-char (point-min))
8140 (while (re-search-forward org-dblock-start-re nil t)
8141 (goto-char (setq pos (match-beginning 0)))
8142 (condition-case nil
8143 (funcall cmd)
8144 (error (message "Error during update of dynamic block")))
8145 (goto-char pos)
8146 (unless (re-search-forward org-dblock-end-re nil t)
8147 (error "Dynamic block not terminated"))))))
8149 (defun org-dblock-update (&optional arg)
8150 "User command for updating dynamic blocks.
8151 Update the dynamic block at point. With prefix ARG, update all dynamic
8152 blocks in the buffer."
8153 (interactive "P")
8154 (if arg
8155 (org-update-all-dblocks)
8156 (or (looking-at org-dblock-start-re)
8157 (org-beginning-of-dblock))
8158 (org-update-dblock)))
8160 (defun org-update-dblock ()
8161 "Update the dynamic block at point
8162 This means to empty the block, parse for parameters and then call
8163 the correct writing function."
8164 (save-window-excursion
8165 (let* ((pos (point))
8166 (line (org-current-line))
8167 (params (org-prepare-dblock))
8168 (name (plist-get params :name))
8169 (cmd (intern (concat "org-dblock-write:" name))))
8170 (message "Updating dynamic block `%s' at line %d..." name line)
8171 (funcall cmd params)
8172 (message "Updating dynamic block `%s' at line %d...done" name line)
8173 (goto-char pos))))
8175 (defun org-beginning-of-dblock ()
8176 "Find the beginning of the dynamic block at point.
8177 Error if there is no such block at point."
8178 (let ((pos (point))
8179 beg)
8180 (end-of-line 1)
8181 (if (and (re-search-backward org-dblock-start-re nil t)
8182 (setq beg (match-beginning 0))
8183 (re-search-forward org-dblock-end-re nil t)
8184 (> (match-end 0) pos))
8185 (goto-char beg)
8186 (goto-char pos)
8187 (error "Not in a dynamic block"))))
8189 (defun org-update-all-dblocks ()
8190 "Update all dynamic blocks in the buffer.
8191 This function can be used in a hook."
8192 (when (org-mode-p)
8193 (org-map-dblocks 'org-update-dblock)))
8196 ;;;; Completion
8198 (defconst org-additional-option-like-keywords
8199 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8200 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8201 "BEGIN_EXAMPLE" "END_EXAMPLE"
8202 "BEGIN_QUOTE" "END_QUOTE"
8203 "BEGIN_VERSE" "END_VERSE"
8204 "BEGIN_SRC" "END_SRC"
8205 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8207 (defcustom org-structure-template-alist
8209 ("s" "#+begin_src ?\n\n#+end_src"
8210 "<src lang=\"?\">\n\n</src>")
8211 ("e" "#+begin_example\n?\n#+end_example"
8212 "<example>\n?\n</example>")
8213 ("q" "#+begin_quote\n?\n#+end_quote"
8214 "<quote>\n?\n</quote>")
8215 ("v" "#+begin_verse\n?\n#+end_verse"
8216 "<verse>\n?\n/verse>")
8217 ("l" "#+begin_latex\n?\n#+end_latex"
8218 "<literal style=\"latex\">\n?\n</literal>")
8219 ("L" "#+latex: "
8220 "<literal style=\"latex\">?</literal>")
8221 ("h" "#+begin_html\n?\n#+end_html"
8222 "<literal style=\"html\">\n?\n</literal>")
8223 ("H" "#+html: "
8224 "<literal style=\"html\">?</literal>")
8225 ("a" "#+begin_ascii\n?\n#+end_ascii")
8226 ("A" "#+ascii: ")
8227 ("i" "#+include %file ?"
8228 "<include file=%file markup=\"?\">")
8230 "Structure completion elements.
8231 This is a list of abbreviation keys and values. The value gets inserted
8232 it you type @samp{.} followed by the key and then the completion key,
8233 usually `M-TAB'. %file will be replaced by a file name after prompting
8234 for the file using completion.
8235 There are two templates for each key, the first uses the original Org syntax,
8236 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8237 the default when the /org-mtags.el/ module has been loaded. See also the
8238 variable `org-mtags-prefer-muse-templates'.
8239 This is an experimental feature, it is undecided if it is going to stay in."
8240 :group 'org-completion
8241 :type '(repeat
8242 (string :tag "Key")
8243 (string :tag "Template")
8244 (string :tag "Muse Template")))
8246 (defun org-try-structure-completion ()
8247 "Try to complete a structure template before point.
8248 This looks for strings like \"<e\" on an otherwise empty line and
8249 expands them."
8250 (let ((l (buffer-substring (point-at-bol) (point)))
8252 (when (and (looking-at "[ \t]*$")
8253 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8254 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8255 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8256 (match-beginning 1)) a)
8257 t)))
8259 (defun org-complete-expand-structure-template (start cell)
8260 "Expand a structure template."
8261 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8262 (rpl (nth (if musep 2 1) cell)))
8263 (delete-region start (point))
8264 (when (string-match "\\`#\\+" rpl)
8265 (cond
8266 ((bolp))
8267 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8268 (delete-region (point-at-bol) (point)))
8269 (t (newline))))
8270 (setq start (point))
8271 (if (string-match "%file" rpl)
8272 (setq rpl (replace-match
8273 (concat
8274 "\""
8275 (save-match-data
8276 (abbreviate-file-name (read-file-name "Include file: ")))
8277 "\"")
8278 t t rpl)))
8279 (insert rpl)
8280 (if (re-search-backward "\\?" start t) (delete-char 1))))
8283 (defun org-complete (&optional arg)
8284 "Perform completion on word at point.
8285 At the beginning of a headline, this completes TODO keywords as given in
8286 `org-todo-keywords'.
8287 If the current word is preceded by a backslash, completes the TeX symbols
8288 that are supported for HTML support.
8289 If the current word is preceded by \"#+\", completes special words for
8290 setting file options.
8291 In the line after \"#+STARTUP:, complete valid keywords.\"
8292 At all other locations, this simply calls the value of
8293 `org-completion-fallback-command'."
8294 (interactive "P")
8295 (org-without-partial-completion
8296 (catch 'exit
8297 (let* ((a nil)
8298 (end (point))
8299 (beg1 (save-excursion
8300 (skip-chars-backward (org-re "[:alnum:]_@"))
8301 (point)))
8302 (beg (save-excursion
8303 (skip-chars-backward "a-zA-Z0-9_:$")
8304 (point)))
8305 (confirm (lambda (x) (stringp (car x))))
8306 (searchhead (equal (char-before beg) ?*))
8307 (struct
8308 (when (and (member (char-before beg1) '(?. ?<))
8309 (setq a (assoc (buffer-substring beg1 (point))
8310 org-structure-template-alist)))
8311 (org-complete-expand-structure-template (1- beg1) a)
8312 (throw 'exit t)))
8313 (tag (and (equal (char-before beg1) ?:)
8314 (equal (char-after (point-at-bol)) ?*)))
8315 (prop (and (equal (char-before beg1) ?:)
8316 (not (equal (char-after (point-at-bol)) ?*))))
8317 (texp (equal (char-before beg) ?\\))
8318 (link (equal (char-before beg) ?\[))
8319 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8320 beg)
8321 "#+"))
8322 (startup (string-match "^#\\+STARTUP:.*"
8323 (buffer-substring (point-at-bol) (point))))
8324 (completion-ignore-case opt)
8325 (type nil)
8326 (tbl nil)
8327 (table (cond
8328 (opt
8329 (setq type :opt)
8330 (require 'org-exp)
8331 (append
8332 (mapcar
8333 (lambda (x)
8334 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8335 (cons (match-string 2 x) (match-string 1 x)))
8336 (org-split-string (org-get-current-options) "\n"))
8337 (mapcar 'list org-additional-option-like-keywords)))
8338 (startup
8339 (setq type :startup)
8340 org-startup-options)
8341 (link (append org-link-abbrev-alist-local
8342 org-link-abbrev-alist))
8343 (texp
8344 (setq type :tex)
8345 org-html-entities)
8346 ((string-match "\\`\\*+[ \t]+\\'"
8347 (buffer-substring (point-at-bol) beg))
8348 (setq type :todo)
8349 (mapcar 'list org-todo-keywords-1))
8350 (searchhead
8351 (setq type :searchhead)
8352 (save-excursion
8353 (goto-char (point-min))
8354 (while (re-search-forward org-todo-line-regexp nil t)
8355 (push (list
8356 (org-make-org-heading-search-string
8357 (match-string 3) t))
8358 tbl)))
8359 tbl)
8360 (tag (setq type :tag beg beg1)
8361 (or org-tag-alist (org-get-buffer-tags)))
8362 (prop (setq type :prop beg beg1)
8363 (mapcar 'list (org-buffer-property-keys nil t t)))
8364 (t (progn
8365 (call-interactively org-completion-fallback-command)
8366 (throw 'exit nil)))))
8367 (pattern (buffer-substring-no-properties beg end))
8368 (completion (try-completion pattern table confirm)))
8369 (cond ((eq completion t)
8370 (if (not (assoc (upcase pattern) table))
8371 (message "Already complete")
8372 (if (and (equal type :opt)
8373 (not (member (car (assoc (upcase pattern) table))
8374 org-additional-option-like-keywords)))
8375 (insert (substring (cdr (assoc (upcase pattern) table))
8376 (length pattern)))
8377 (if (memq type '(:tag :prop)) (insert ":")))))
8378 ((null completion)
8379 (message "Can't find completion for \"%s\"" pattern)
8380 (ding))
8381 ((not (string= pattern completion))
8382 (delete-region beg end)
8383 (if (string-match " +$" completion)
8384 (setq completion (replace-match "" t t completion)))
8385 (insert completion)
8386 (if (get-buffer-window "*Completions*")
8387 (delete-window (get-buffer-window "*Completions*")))
8388 (if (assoc completion table)
8389 (if (eq type :todo) (insert " ")
8390 (if (memq type '(:tag :prop)) (insert ":"))))
8391 (if (and (equal type :opt) (assoc completion table))
8392 (message "%s" (substitute-command-keys
8393 "Press \\[org-complete] again to insert example settings"))))
8395 (message "Making completion list...")
8396 (let ((list (sort (all-completions pattern table confirm)
8397 'string<)))
8398 (with-output-to-temp-buffer "*Completions*"
8399 (condition-case nil
8400 ;; Protection needed for XEmacs and emacs 21
8401 (display-completion-list list pattern)
8402 (error (display-completion-list list)))))
8403 (message "Making completion list...%s" "done")))))))
8405 ;;;; TODO, DEADLINE, Comments
8407 (defun org-toggle-comment ()
8408 "Change the COMMENT state of an entry."
8409 (interactive)
8410 (save-excursion
8411 (org-back-to-heading)
8412 (let (case-fold-search)
8413 (if (looking-at (concat outline-regexp
8414 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8415 (replace-match "" t t nil 1)
8416 (if (looking-at outline-regexp)
8417 (progn
8418 (goto-char (match-end 0))
8419 (insert org-comment-string " ")))))))
8421 (defvar org-last-todo-state-is-todo nil
8422 "This is non-nil when the last TODO state change led to a TODO state.
8423 If the last change removed the TODO tag or switched to DONE, then
8424 this is nil.")
8426 (defvar org-setting-tags nil) ; dynamically skipped
8428 (defun org-parse-local-options (string var)
8429 "Parse STRING for startup setting relevant for variable VAR."
8430 (let ((rtn (symbol-value var))
8431 e opts)
8432 (save-match-data
8433 (if (or (not string) (not (string-match "\\S-" string)))
8435 (setq opts (delq nil (mapcar (lambda (x)
8436 (setq e (assoc x org-startup-options))
8437 (if (eq (nth 1 e) var) e nil))
8438 (org-split-string string "[ \t]+"))))
8439 (if (not opts)
8441 (setq rtn nil)
8442 (while (setq e (pop opts))
8443 (if (not (nth 3 e))
8444 (setq rtn (nth 2 e))
8445 (if (not (listp rtn)) (setq rtn nil))
8446 (push (nth 2 e) rtn)))
8447 rtn)))))
8449 (defvar org-todo-setup-filter-hook nil
8450 "Hook for functions that pre-filter todo specs.
8452 Each function takes a todo spec and returns either `nil' or the spec
8453 transformed into canonical form." )
8455 (defvar org-todo-get-default-hook nil
8456 "Hook for functions that get a default item for todo.
8458 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8459 `nil' or a string to be used for the todo mark." )
8461 (defvar org-agenda-headline-snapshot-before-repeat)
8462 (defun org-todo (&optional arg)
8463 "Change the TODO state of an item.
8464 The state of an item is given by a keyword at the start of the heading,
8465 like
8466 *** TODO Write paper
8467 *** DONE Call mom
8469 The different keywords are specified in the variable `org-todo-keywords'.
8470 By default the available states are \"TODO\" and \"DONE\".
8471 So for this example: when the item starts with TODO, it is changed to DONE.
8472 When it starts with DONE, the DONE is removed. And when neither TODO nor
8473 DONE are present, add TODO at the beginning of the heading.
8475 With C-u prefix arg, use completion to determine the new state.
8476 With numeric prefix arg, switch to that state.
8477 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8478 With a tripple C-u prefix, circumvent any state blocking.
8480 For calling through lisp, arg is also interpreted in the following way:
8481 'none -> empty state
8482 \"\"(empty string) -> switch to empty state
8483 'done -> switch to DONE
8484 'nextset -> switch to the next set of keywords
8485 'previousset -> switch to the previous set of keywords
8486 \"WAITING\" -> switch to the specified keyword, but only if it
8487 really is a member of `org-todo-keywords'."
8488 (interactive "P")
8489 (if (equal arg '(16)) (setq arg 'nextset))
8490 (let ((org-blocker-hook org-blocker-hook))
8491 (when (equal arg '(64))
8492 (setq arg nil org-blocker-hook nil))
8493 (save-excursion
8494 (catch 'exit
8495 (org-back-to-heading)
8496 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8497 (or (looking-at (concat " +" org-todo-regexp " *"))
8498 (looking-at " *"))
8499 (let* ((match-data (match-data))
8500 (startpos (point-at-bol))
8501 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8502 (org-log-done org-log-done)
8503 (org-log-repeat org-log-repeat)
8504 (org-todo-log-states org-todo-log-states)
8505 (this (match-string 1))
8506 (hl-pos (match-beginning 0))
8507 (head (org-get-todo-sequence-head this))
8508 (ass (assoc head org-todo-kwd-alist))
8509 (interpret (nth 1 ass))
8510 (done-word (nth 3 ass))
8511 (final-done-word (nth 4 ass))
8512 (last-state (or this ""))
8513 (completion-ignore-case t)
8514 (member (member this org-todo-keywords-1))
8515 (tail (cdr member))
8516 (state (cond
8517 ((and org-todo-key-trigger
8518 (or (and (equal arg '(4))
8519 (eq org-use-fast-todo-selection 'prefix))
8520 (and (not arg) org-use-fast-todo-selection
8521 (not (eq org-use-fast-todo-selection
8522 'prefix)))))
8523 ;; Use fast selection
8524 (org-fast-todo-selection))
8525 ((and (equal arg '(4))
8526 (or (not org-use-fast-todo-selection)
8527 (not org-todo-key-trigger)))
8528 ;; Read a state with completion
8529 (org-ido-completing-read
8530 "State: " (mapcar (lambda(x) (list x))
8531 org-todo-keywords-1)
8532 nil t))
8533 ((eq arg 'right)
8534 (if this
8535 (if tail (car tail) nil)
8536 (car org-todo-keywords-1)))
8537 ((eq arg 'left)
8538 (if (equal member org-todo-keywords-1)
8540 (if this
8541 (nth (- (length org-todo-keywords-1)
8542 (length tail) 2)
8543 org-todo-keywords-1)
8544 (org-last org-todo-keywords-1))))
8545 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8546 (setq arg nil))) ; hack to fall back to cycling
8547 (arg
8548 ;; user or caller requests a specific state
8549 (cond
8550 ((equal arg "") nil)
8551 ((eq arg 'none) nil)
8552 ((eq arg 'done) (or done-word (car org-done-keywords)))
8553 ((eq arg 'nextset)
8554 (or (car (cdr (member head org-todo-heads)))
8555 (car org-todo-heads)))
8556 ((eq arg 'previousset)
8557 (let ((org-todo-heads (reverse org-todo-heads)))
8558 (or (car (cdr (member head org-todo-heads)))
8559 (car org-todo-heads))))
8560 ((car (member arg org-todo-keywords-1)))
8561 ((nth (1- (prefix-numeric-value arg))
8562 org-todo-keywords-1))))
8563 ((null member) (or head (car org-todo-keywords-1)))
8564 ((equal this final-done-word) nil) ;; -> make empty
8565 ((null tail) nil) ;; -> first entry
8566 ((memq interpret '(type priority))
8567 (if (eq this-command last-command)
8568 (car tail)
8569 (if (> (length tail) 0)
8570 (or done-word (car org-done-keywords))
8571 nil)))
8573 (car tail))))
8574 (state (or
8575 (run-hook-with-args-until-success
8576 'org-todo-get-default-hook state last-state)
8577 state))
8578 (next (if state (concat " " state " ") " "))
8579 (change-plist (list :type 'todo-state-change :from this :to state
8580 :position startpos))
8581 dolog now-done-p)
8582 (when org-blocker-hook
8583 (setq org-last-todo-state-is-todo
8584 (not (member this org-done-keywords)))
8585 (unless (save-excursion
8586 (save-match-data
8587 (run-hook-with-args-until-failure
8588 'org-blocker-hook change-plist)))
8589 (if (interactive-p)
8590 (error "TODO state change from %s to %s blocked" this state)
8591 ;; fail silently
8592 (message "TODO state change from %s to %s blocked" this state)
8593 (throw 'exit nil))))
8594 (store-match-data match-data)
8595 (replace-match next t t)
8596 (unless (pos-visible-in-window-p hl-pos)
8597 (message "TODO state changed to %s" (org-trim next)))
8598 (unless head
8599 (setq head (org-get-todo-sequence-head state)
8600 ass (assoc head org-todo-kwd-alist)
8601 interpret (nth 1 ass)
8602 done-word (nth 3 ass)
8603 final-done-word (nth 4 ass)))
8604 (when (memq arg '(nextset previousset))
8605 (message "Keyword-Set %d/%d: %s"
8606 (- (length org-todo-sets) -1
8607 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8608 (length org-todo-sets)
8609 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8610 (setq org-last-todo-state-is-todo
8611 (not (member state org-done-keywords)))
8612 (setq now-done-p (and (member state org-done-keywords)
8613 (not (member this org-done-keywords))))
8614 (and logging (org-local-logging logging))
8615 (when (and (or org-todo-log-states org-log-done)
8616 (not (memq arg '(nextset previousset))))
8617 ;; we need to look at recording a time and note
8618 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8619 (nth 2 (assoc this org-todo-log-states))))
8620 (when (and state
8621 (member state org-not-done-keywords)
8622 (not (member this org-not-done-keywords)))
8623 ;; This is now a todo state and was not one before
8624 ;; If there was a CLOSED time stamp, get rid of it.
8625 (org-add-planning-info nil nil 'closed))
8626 (when (and now-done-p org-log-done)
8627 ;; It is now done, and it was not done before
8628 (org-add-planning-info 'closed (org-current-time))
8629 (if (and (not dolog) (eq 'note org-log-done))
8630 (org-add-log-setup 'done state this 'findpos 'note)))
8631 (when (and state dolog)
8632 ;; This is a non-nil state, and we need to log it
8633 (org-add-log-setup 'state state this 'findpos dolog)))
8634 ;; Fixup tag positioning
8635 (org-todo-trigger-tag-changes state)
8636 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8637 (when org-provide-todo-statistics
8638 (org-update-parent-todo-statistics))
8639 (run-hooks 'org-after-todo-state-change-hook)
8640 (if (and arg (not (member state org-done-keywords)))
8641 (setq head (org-get-todo-sequence-head state)))
8642 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8643 ;; Do we need to trigger a repeat?
8644 (when now-done-p
8645 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8646 ;; This is for the agenda, take a snapshot of the headline.
8647 (save-match-data
8648 (setq org-agenda-headline-snapshot-before-repeat
8649 (org-get-heading))))
8650 (org-auto-repeat-maybe state))
8651 ;; Fixup cursor location if close to the keyword
8652 (if (and (outline-on-heading-p)
8653 (not (bolp))
8654 (save-excursion (beginning-of-line 1)
8655 (looking-at org-todo-line-regexp))
8656 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8657 (progn
8658 (goto-char (or (match-end 2) (match-end 1)))
8659 (just-one-space)))
8660 (when org-trigger-hook
8661 (save-excursion
8662 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8664 (defun org-block-todo-from-children-or-siblings (change-plist)
8665 "Block turning an entry into a TODO, using the hierarchy.
8666 This checks whether the current task should be blocked from state
8667 changes. Such blocking occurs when:
8669 1. The task has children which are not all in a completed state.
8671 2. A task has a parent with the property :ORDERED:, and there
8672 are siblings prior to the current task with incomplete
8673 status."
8674 (catch 'dont-block
8675 ;; If this is not a todo state change, or if this entry is already DONE,
8676 ;; do not block
8677 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8678 (member (plist-get change-plist :from)
8679 (cons 'done org-done-keywords))
8680 (member (plist-get change-plist :to)
8681 (cons 'todo org-not-done-keywords)))
8682 (throw 'dont-block t))
8683 ;; If this task has children, and any are undone, it's blocked
8684 (save-excursion
8685 (org-back-to-heading t)
8686 (let ((this-level (funcall outline-level)))
8687 (outline-next-heading)
8688 (let ((child-level (funcall outline-level)))
8689 (while (and (not (eobp))
8690 (> child-level this-level))
8691 ;; this todo has children, check whether they are all
8692 ;; completed
8693 (if (and (not (org-entry-is-done-p))
8694 (org-entry-is-todo-p))
8695 (throw 'dont-block nil))
8696 (outline-next-heading)
8697 (setq child-level (funcall outline-level))))))
8698 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8699 ;; any previous siblings are undone, it's blocked
8700 (save-excursion
8701 (org-back-to-heading t)
8702 (when (save-excursion
8703 (ignore-errors
8704 (org-up-heading-all 1)
8705 (org-entry-get (point) "ORDERED")))
8706 (let* ((this-level (funcall outline-level))
8707 (current-level this-level))
8708 (while (and (not (bobp))
8709 (= current-level this-level))
8710 (outline-previous-heading)
8711 (setq current-level (funcall outline-level))
8712 (if (= current-level this-level)
8713 ;; this todo has children, check whether they are all
8714 ;; completed
8715 (if (and (not (org-entry-is-done-p))
8716 (org-entry-is-todo-p))
8717 (throw 'dont-block nil)))))))
8718 t)) ; don't block
8720 (defcustom org-track-ordered-property-with-tag nil
8721 "Should the ORDERED property also be shown as a tag?
8722 The ORDERED property decides if an entry should require subtasks to be
8723 completed in sequence. Since a property is not very visible, setting
8724 this option means that toggling the ORDERED property with the command
8725 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
8726 not relevant for the behavior, but it makes things more visible.
8728 Note that toggling the tag with tags commands will not change the property
8729 and therefore not influence behavior!
8731 This can be t, meaning the tag ORDERED should be used, It can also be a
8732 string to select a different tag for this task."
8733 :group 'org-todo
8734 :type '(choice
8735 (const :tag "No tracking" nil)
8736 (const :tag "Track with ORDERED tag" t)
8737 (string :tag "Use other tag")))
8739 (defun org-toggle-ordered-property ()
8740 "Toggle the ORDERED property of the current entry.
8741 For better visibility, you can track the value of this property with a tag.
8742 See variable `org-track-ordered-property-with-tag'."
8743 (interactive)
8744 (let* ((t1 org-track-ordered-property-with-tag)
8745 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
8746 (save-excursion
8747 (org-back-to-heading)
8748 (if (org-entry-get nil "ORDERED")
8749 (progn
8750 (org-delete-property "ORDERED")
8751 (and tag (org-toggle-tag tag 'off))
8752 (message "Subtasks can be completed in arbitrary order"))
8753 (org-entry-put nil "ORDERED" "t")
8754 (and tag (org-toggle-tag tag 'on))
8755 (message "Subtasks must be completed in sequence")))))
8757 (defvar org-blocked-by-checkboxes) ; dynamically scoped
8758 (defun org-block-todo-from-checkboxes (change-plist)
8759 "Block turning an entry into a TODO, using checkboxes.
8760 This checks whether the current task should be blocked from state
8761 changes because there are uncheckd boxes in this entry."
8762 (catch 'dont-block
8763 ;; If this is not a todo state change, or if this entry is already DONE,
8764 ;; do not block
8765 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8766 (member (plist-get change-plist :from)
8767 (cons 'done org-done-keywords))
8768 (member (plist-get change-plist :to)
8769 (cons 'todo org-not-done-keywords)))
8770 (throw 'dont-block t))
8771 ;; If this task has checkboxes that are not checked, it's blocked
8772 (save-excursion
8773 (org-back-to-heading t)
8774 (let ((beg (point)) end)
8775 (outline-next-heading)
8776 (setq end (point))
8777 (goto-char beg)
8778 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8779 end t)
8780 (progn
8781 (if (boundp 'org-blocked-by-checkboxes)
8782 (setq org-blocked-by-checkboxes t))
8783 (throw 'dont-block nil)))))
8784 t)) ; do not block
8786 (defun org-update-parent-todo-statistics ()
8787 "Update any statistics cookie in the parent of the current headline."
8788 (interactive)
8789 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8790 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
8791 (catch 'exit
8792 (save-excursion
8793 (setq level (org-up-heading-safe))
8794 (unless level
8795 (throw 'exit nil))
8796 (while (re-search-forward box-re (point-at-eol) t)
8797 (setq cnt-all 0 cnt-done 0 cookie-present t)
8798 (setq is-percent (match-end 2))
8799 (save-match-data
8800 (unless (outline-next-heading) (throw 'exit nil))
8801 (while (looking-at org-todo-line-regexp)
8802 (setq kwd (match-string 2))
8803 (and kwd (setq cnt-all (1+ cnt-all)))
8804 (and (member kwd org-done-keywords)
8805 (setq cnt-done (1+ cnt-done)))
8806 (condition-case nil
8807 (org-forward-same-level 1)
8808 (error (end-of-line 1)))))
8809 (replace-match
8810 (if is-percent
8811 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8812 (format "[%d/%d]" cnt-done cnt-all))))
8813 (when cookie-present
8814 (run-hook-with-args 'org-after-todo-statistics-hook
8815 cnt-done (- cnt-all cnt-done)))))))
8817 (defvar org-after-todo-statistics-hook nil
8818 "Hook that is called after a TODO statistics cookie has been updated.
8819 Each function is called with two arguments: the number of not-done entries
8820 and the number of done entries.
8822 For example, the following function, when added to this hook, will switch
8823 an entry to DONE when all children are done, and back to TODO when new
8824 entries are set to a TODO status. Note that this hook is only called
8825 when there is a statistics cookie in the headline!
8827 (defun org-summary-todo (n-done n-not-done)
8828 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8829 (let (org-log-done org-log-states) ; turn off logging
8830 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8833 (defun org-todo-trigger-tag-changes (state)
8834 "Apply the changes defined in `org-todo-state-tags-triggers'."
8835 (let ((l org-todo-state-tags-triggers)
8836 changes)
8837 (when (or (not state) (equal state ""))
8838 (setq changes (append changes (cdr (assoc "" l)))))
8839 (when (and (stringp state) (> (length state) 0))
8840 (setq changes (append changes (cdr (assoc state l)))))
8841 (when (member state org-not-done-keywords)
8842 (setq changes (append changes (cdr (assoc 'todo l)))))
8843 (when (member state org-done-keywords)
8844 (setq changes (append changes (cdr (assoc 'done l)))))
8845 (dolist (c changes)
8846 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8848 (defun org-local-logging (value)
8849 "Get logging settings from a property VALUE."
8850 (let* (words w a)
8851 ;; directly set the variables, they are already local.
8852 (setq org-log-done nil
8853 org-log-repeat nil
8854 org-todo-log-states nil)
8855 (setq words (org-split-string value))
8856 (while (setq w (pop words))
8857 (cond
8858 ((setq a (assoc w org-startup-options))
8859 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8860 (set (nth 1 a) (nth 2 a))))
8861 ((setq a (org-extract-log-state-settings w))
8862 (and (member (car a) org-todo-keywords-1)
8863 (push a org-todo-log-states)))))))
8865 (defun org-get-todo-sequence-head (kwd)
8866 "Return the head of the TODO sequence to which KWD belongs.
8867 If KWD is not set, check if there is a text property remembering the
8868 right sequence."
8869 (let (p)
8870 (cond
8871 ((not kwd)
8872 (or (get-text-property (point-at-bol) 'org-todo-head)
8873 (progn
8874 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8875 nil (point-at-eol)))
8876 (get-text-property p 'org-todo-head))))
8877 ((not (member kwd org-todo-keywords-1))
8878 (car org-todo-keywords-1))
8879 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8881 (defun org-fast-todo-selection ()
8882 "Fast TODO keyword selection with single keys.
8883 Returns the new TODO keyword, or nil if no state change should occur."
8884 (let* ((fulltable org-todo-key-alist)
8885 (done-keywords org-done-keywords) ;; needed for the faces.
8886 (maxlen (apply 'max (mapcar
8887 (lambda (x)
8888 (if (stringp (car x)) (string-width (car x)) 0))
8889 fulltable)))
8890 (expert nil)
8891 (fwidth (+ maxlen 3 1 3))
8892 (ncol (/ (- (window-width) 4) fwidth))
8893 tg cnt e c tbl
8894 groups ingroup)
8895 (save-excursion
8896 (save-window-excursion
8897 (if expert
8898 (set-buffer (get-buffer-create " *Org todo*"))
8899 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8900 (erase-buffer)
8901 (org-set-local 'org-done-keywords done-keywords)
8902 (setq tbl fulltable cnt 0)
8903 (while (setq e (pop tbl))
8904 (cond
8905 ((equal e '(:startgroup))
8906 (push '() groups) (setq ingroup t)
8907 (when (not (= cnt 0))
8908 (setq cnt 0)
8909 (insert "\n"))
8910 (insert "{ "))
8911 ((equal e '(:endgroup))
8912 (setq ingroup nil cnt 0)
8913 (insert "}\n"))
8914 ((equal e '(:newline))
8915 (insert "\n "))
8917 (setq tg (car e) c (cdr e))
8918 (if ingroup (push tg (car groups)))
8919 (setq tg (org-add-props tg nil 'face
8920 (org-get-todo-face tg)))
8921 (if (and (= cnt 0) (not ingroup)) (insert " "))
8922 (insert "[" c "] " tg (make-string
8923 (- fwidth 4 (length tg)) ?\ ))
8924 (when (= (setq cnt (1+ cnt)) ncol)
8925 (insert "\n")
8926 (if ingroup (insert " "))
8927 (setq cnt 0)))))
8928 (insert "\n")
8929 (goto-char (point-min))
8930 (if (not expert) (org-fit-window-to-buffer))
8931 (message "[a-z..]:Set [SPC]:clear")
8932 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8933 (cond
8934 ((or (= c ?\C-g)
8935 (and (= c ?q) (not (rassoc c fulltable))))
8936 (setq quit-flag t))
8937 ((= c ?\ ) nil)
8938 ((setq e (rassoc c fulltable) tg (car e))
8940 (t (setq quit-flag t)))))))
8942 (defun org-entry-is-todo-p ()
8943 (member (org-get-todo-state) org-not-done-keywords))
8945 (defun org-entry-is-done-p ()
8946 (member (org-get-todo-state) org-done-keywords))
8948 (defun org-get-todo-state ()
8949 (save-excursion
8950 (org-back-to-heading t)
8951 (and (looking-at org-todo-line-regexp)
8952 (match-end 2)
8953 (match-string 2))))
8955 (defun org-at-date-range-p (&optional inactive-ok)
8956 "Is the cursor inside a date range?"
8957 (interactive)
8958 (save-excursion
8959 (catch 'exit
8960 (let ((pos (point)))
8961 (skip-chars-backward "^[<\r\n")
8962 (skip-chars-backward "<[")
8963 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8964 (>= (match-end 0) pos)
8965 (throw 'exit t))
8966 (skip-chars-backward "^<[\r\n")
8967 (skip-chars-backward "<[")
8968 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8969 (>= (match-end 0) pos)
8970 (throw 'exit t)))
8971 nil)))
8973 (defun org-get-repeat ()
8974 "Check if there is a deadline/schedule with repeater in this entry."
8975 (save-match-data
8976 (save-excursion
8977 (org-back-to-heading t)
8978 (if (re-search-forward
8979 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8980 (match-string 1)))))
8982 (defvar org-last-changed-timestamp)
8983 (defvar org-last-inserted-timestamp)
8984 (defvar org-log-post-message)
8985 (defvar org-log-note-purpose)
8986 (defvar org-log-note-how)
8987 (defvar org-log-note-extra)
8988 (defun org-auto-repeat-maybe (done-word)
8989 "Check if the current headline contains a repeated deadline/schedule.
8990 If yes, set TODO state back to what it was and change the base date
8991 of repeating deadline/scheduled time stamps to new date.
8992 This function is run automatically after each state change to a DONE state."
8993 ;; last-state is dynamically scoped into this function
8994 (let* ((repeat (org-get-repeat))
8995 (aa (assoc last-state org-todo-kwd-alist))
8996 (interpret (nth 1 aa))
8997 (head (nth 2 aa))
8998 (whata '(("d" . day) ("m" . month) ("y" . year)))
8999 (msg "Entry repeats: ")
9000 (org-log-done nil)
9001 (org-todo-log-states nil)
9002 (nshiftmax 10) (nshift 0)
9003 re type n what ts time)
9004 (when repeat
9005 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9006 (org-todo (if (eq interpret 'type) last-state head))
9007 (when org-log-repeat
9008 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9009 (memq 'org-add-log-note post-command-hook))
9010 ;; OK, we are already setup for some record
9011 (if (eq org-log-repeat 'note)
9012 ;; make sure we take a note, not only a time stamp
9013 (setq org-log-note-how 'note))
9014 ;; Set up for taking a record
9015 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9016 last-state
9017 'findpos org-log-repeat)))
9018 (org-back-to-heading t)
9019 (org-add-planning-info nil nil 'closed)
9020 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9021 org-deadline-time-regexp "\\)\\|\\("
9022 org-ts-regexp "\\)"))
9023 (while (re-search-forward
9024 re (save-excursion (outline-next-heading) (point)) t)
9025 (setq type (if (match-end 1) org-scheduled-string
9026 (if (match-end 3) org-deadline-string "Plain:"))
9027 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9028 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9029 (setq n (string-to-number (match-string 2 ts))
9030 what (match-string 3 ts))
9031 (if (equal what "w") (setq n (* n 7) what "d"))
9032 ;; Preparation, see if we need to modify the start date for the change
9033 (when (match-end 1)
9034 (setq time (save-match-data (org-time-string-to-time ts)))
9035 (cond
9036 ((equal (match-string 1 ts) ".")
9037 ;; Shift starting date to today
9038 (org-timestamp-change
9039 (- (time-to-days (current-time)) (time-to-days time))
9040 'day))
9041 ((equal (match-string 1 ts) "+")
9042 (while (or (= nshift 0)
9043 (<= (time-to-days time) (time-to-days (current-time))))
9044 (when (= (incf nshift) nshiftmax)
9045 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9046 (error "Abort")))
9047 (org-timestamp-change n (cdr (assoc what whata)))
9048 (org-at-timestamp-p t)
9049 (setq ts (match-string 1))
9050 (setq time (save-match-data (org-time-string-to-time ts))))
9051 (org-timestamp-change (- n) (cdr (assoc what whata)))
9052 ;; rematch, so that we have everything in place for the real shift
9053 (org-at-timestamp-p t)
9054 (setq ts (match-string 1))
9055 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9056 (org-timestamp-change n (cdr (assoc what whata)))
9057 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9058 (setq org-log-post-message msg)
9059 (message "%s" msg))))
9061 (defun org-show-todo-tree (arg)
9062 "Make a compact tree which shows all headlines marked with TODO.
9063 The tree will show the lines where the regexp matches, and all higher
9064 headlines above the match.
9065 With a \\[universal-argument] prefix, also show the DONE entries.
9066 With a numeric prefix N, construct a sparse tree for the Nth element
9067 of `org-todo-keywords-1'."
9068 (interactive "P")
9069 (let ((case-fold-search nil)
9070 (kwd-re
9071 (cond ((null arg) org-not-done-regexp)
9072 ((equal arg '(4))
9073 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9074 (mapcar 'list org-todo-keywords-1))))
9075 (concat "\\("
9076 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9077 "\\)\\>")))
9078 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9079 (regexp-quote (nth (1- (prefix-numeric-value arg))
9080 org-todo-keywords-1)))
9081 (t (error "Invalid prefix argument: %s" arg)))))
9082 (message "%d TODO entries found"
9083 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9085 (defun org-deadline (&optional remove time)
9086 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9087 With argument REMOVE, remove any deadline from the item.
9088 When TIME is set, it should be an internal time specification, and the
9089 scheduling will use the corresponding date."
9090 (interactive "P")
9091 (if remove
9092 (progn
9093 (org-remove-timestamp-with-keyword org-deadline-string)
9094 (message "Item no longer has a deadline."))
9095 (if (org-get-repeat)
9096 (error "Cannot change deadline on task with repeater, please do that by hand")
9097 (org-add-planning-info 'deadline time 'closed)
9098 (message "Deadline on %s" org-last-inserted-timestamp))))
9100 (defun org-schedule (&optional remove time)
9101 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9102 With argument REMOVE, remove any scheduling date from the item.
9103 When TIME is set, it should be an internal time specification, and the
9104 scheduling will use the corresponding date."
9105 (interactive "P")
9106 (if remove
9107 (progn
9108 (org-remove-timestamp-with-keyword org-scheduled-string)
9109 (message "Item is no longer scheduled."))
9110 (if (org-get-repeat)
9111 (error "Cannot reschedule task with repeater, please do that by hand")
9112 (org-add-planning-info 'scheduled time 'closed)
9113 (message "Scheduled to %s" org-last-inserted-timestamp))))
9115 (defun org-get-scheduled-time (pom &optional inherit)
9116 "Get the scheduled time as a time tuple, of a format suitable
9117 for calling org-schedule with, or if there is no scheduling,
9118 returns nil."
9119 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9120 (when time
9121 (apply 'encode-time (org-parse-time-string time)))))
9123 (defun org-get-deadline-time (pom &optional inherit)
9124 "Get the deadine as a time tuple, of a format suitable for
9125 calling org-deadlin with, or if there is no scheduling, returns
9126 nil."
9127 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9128 (when time
9129 (apply 'encode-time (org-parse-time-string time)))))
9131 (defun org-remove-timestamp-with-keyword (keyword)
9132 "Remove all time stamps with KEYWORD in the current entry."
9133 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9134 beg)
9135 (save-excursion
9136 (org-back-to-heading t)
9137 (setq beg (point))
9138 (org-end-of-subtree t t)
9139 (while (re-search-backward re beg t)
9140 (replace-match "")
9141 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9142 (equal (char-before) ?\ ))
9143 (backward-delete-char 1)
9144 (if (string-match "^[ \t]*$" (buffer-substring
9145 (point-at-bol) (point-at-eol)))
9146 (delete-region (point-at-bol)
9147 (min (point-max) (1+ (point-at-eol))))))))))
9149 (defun org-add-planning-info (what &optional time &rest remove)
9150 "Insert new timestamp with keyword in the line directly after the headline.
9151 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9152 If non is given, the user is prompted for a date.
9153 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9154 be removed."
9155 (interactive)
9156 (let (org-time-was-given org-end-time-was-given ts
9157 end default-time default-input)
9159 (when (and (not time) (memq what '(scheduled deadline)))
9160 ;; Try to get a default date/time from existing timestamp
9161 (save-excursion
9162 (org-back-to-heading t)
9163 (setq end (save-excursion (outline-next-heading) (point)))
9164 (when (re-search-forward (if (eq what 'scheduled)
9165 org-scheduled-time-regexp
9166 org-deadline-time-regexp)
9167 end t)
9168 (setq ts (match-string 1)
9169 default-time
9170 (apply 'encode-time (org-parse-time-string ts))
9171 default-input (and ts (org-get-compact-tod ts))))))
9172 (when what
9173 ;; If necessary, get the time from the user
9174 (setq time (or time (org-read-date nil 'to-time nil nil
9175 default-time default-input))))
9177 (when (and org-insert-labeled-timestamps-at-point
9178 (member what '(scheduled deadline)))
9179 (insert
9180 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9181 (org-insert-time-stamp time org-time-was-given
9182 nil nil nil (list org-end-time-was-given))
9183 (setq what nil))
9184 (save-excursion
9185 (save-restriction
9186 (let (col list elt ts buffer-invisibility-spec)
9187 (org-back-to-heading t)
9188 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9189 (goto-char (match-end 1))
9190 (setq col (current-column))
9191 (goto-char (match-end 0))
9192 (if (eobp) (insert "\n") (forward-char 1))
9193 (if (and (not (looking-at outline-regexp))
9194 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9195 "[^\r\n]*"))
9196 (not (equal (match-string 1) org-clock-string)))
9197 (narrow-to-region (match-beginning 0) (match-end 0))
9198 (insert-before-markers "\n")
9199 (backward-char 1)
9200 (narrow-to-region (point) (point))
9201 (and org-adapt-indentation (org-indent-to-column col)))
9202 ;; Check if we have to remove something.
9203 (setq list (cons what remove))
9204 (while list
9205 (setq elt (pop list))
9206 (goto-char (point-min))
9207 (when (or (and (eq elt 'scheduled)
9208 (re-search-forward org-scheduled-time-regexp nil t))
9209 (and (eq elt 'deadline)
9210 (re-search-forward org-deadline-time-regexp nil t))
9211 (and (eq elt 'closed)
9212 (re-search-forward org-closed-time-regexp nil t)))
9213 (replace-match "")
9214 (if (looking-at "--+<[^>]+>") (replace-match ""))
9215 (if (looking-at " +") (replace-match ""))))
9216 (goto-char (point-max))
9217 (when what
9218 (insert
9219 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9220 (cond ((eq what 'scheduled) org-scheduled-string)
9221 ((eq what 'deadline) org-deadline-string)
9222 ((eq what 'closed) org-closed-string))
9223 " ")
9224 (setq ts (org-insert-time-stamp
9225 time
9226 (or org-time-was-given
9227 (and (eq what 'closed) org-log-done-with-time))
9228 (eq what 'closed)
9229 nil nil (list org-end-time-was-given)))
9230 (end-of-line 1))
9231 (goto-char (point-min))
9232 (widen)
9233 (if (and (looking-at "[ \t]+\n")
9234 (equal (char-before) ?\n))
9235 (delete-region (1- (point)) (point-at-eol)))
9236 ts)))))
9238 (defvar org-log-note-marker (make-marker))
9239 (defvar org-log-note-purpose nil)
9240 (defvar org-log-note-state nil)
9241 (defvar org-log-note-previous-state nil)
9242 (defvar org-log-note-how nil)
9243 (defvar org-log-note-extra nil)
9244 (defvar org-log-note-window-configuration nil)
9245 (defvar org-log-note-return-to (make-marker))
9246 (defvar org-log-post-message nil
9247 "Message to be displayed after a log note has been stored.
9248 The auto-repeater uses this.")
9250 (defun org-add-note ()
9251 "Add a note to the current entry.
9252 This is done in the same way as adding a state change note."
9253 (interactive)
9254 (org-add-log-setup 'note nil nil 'findpos nil))
9256 (defvar org-property-end-re)
9257 (defun org-add-log-setup (&optional purpose state prev-state
9258 findpos how &optional extra)
9259 "Set up the post command hook to take a note.
9260 If this is about to TODO state change, the new state is expected in STATE.
9261 When FINDPOS is non-nil, find the correct position for the note in
9262 the current entry. If not, assume that it can be inserted at point.
9263 HOW is an indicator what kind of note should be created.
9264 EXTRA is additional text that will be inserted into the notes buffer."
9265 (let ((drawer (cond ((stringp org-log-into-drawer)
9266 org-log-into-drawer)
9267 (org-log-into-drawer "LOGBOOK")
9268 (t nil))))
9269 (save-restriction
9270 (save-excursion
9271 (when findpos
9272 (org-back-to-heading t)
9273 (narrow-to-region (point) (save-excursion
9274 (outline-next-heading) (point)))
9275 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9276 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9277 "[^\r\n]*\\)?"))
9278 (goto-char (match-end 0))
9279 (cond
9280 (drawer
9281 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9282 nil t)
9283 (progn
9284 (goto-char (match-end 0))
9285 (or org-log-states-order-reversed
9286 (and (re-search-forward org-property-end-re nil t)
9287 (goto-char (1- (match-beginning 0))))))
9288 (insert "\n:" drawer ":\n:END:")
9289 (beginning-of-line 0)
9290 (org-indent-line-function)
9291 (beginning-of-line 2)
9292 (org-indent-line-function)
9293 (end-of-line 0)))
9294 ((and org-log-state-notes-insert-after-drawers
9295 (save-excursion
9296 (forward-line) (looking-at org-drawer-regexp)))
9297 (forward-line)
9298 (while (looking-at org-drawer-regexp)
9299 (goto-char (match-end 0))
9300 (re-search-forward org-property-end-re (point-max) t)
9301 (forward-line))
9302 (forward-line -1)))
9303 (unless org-log-states-order-reversed
9304 (and (= (char-after) ?\n) (forward-char 1))
9305 (org-skip-over-state-notes)
9306 (skip-chars-backward " \t\n\r")))
9307 (move-marker org-log-note-marker (point))
9308 (setq org-log-note-purpose purpose
9309 org-log-note-state state
9310 org-log-note-previous-state prev-state
9311 org-log-note-how how
9312 org-log-note-extra extra)
9313 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9315 (defun org-skip-over-state-notes ()
9316 "Skip past the list of State notes in an entry."
9317 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9318 (while (looking-at "[ \t]*- State")
9319 (condition-case nil
9320 (org-next-item)
9321 (error (org-end-of-item)))))
9323 (defun org-add-log-note (&optional purpose)
9324 "Pop up a window for taking a note, and add this note later at point."
9325 (remove-hook 'post-command-hook 'org-add-log-note)
9326 (setq org-log-note-window-configuration (current-window-configuration))
9327 (delete-other-windows)
9328 (move-marker org-log-note-return-to (point))
9329 (switch-to-buffer (marker-buffer org-log-note-marker))
9330 (goto-char org-log-note-marker)
9331 (org-switch-to-buffer-other-window "*Org Note*")
9332 (erase-buffer)
9333 (if (memq org-log-note-how '(time state))
9334 (let (current-prefix-arg) (org-store-log-note))
9335 (let ((org-inhibit-startup t)) (org-mode))
9336 (insert (format "# Insert note for %s.
9337 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9338 (cond
9339 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9340 ((eq org-log-note-purpose 'done) "closed todo item")
9341 ((eq org-log-note-purpose 'state)
9342 (format "state change from \"%s\" to \"%s\""
9343 (or org-log-note-previous-state "")
9344 (or org-log-note-state "")))
9345 ((eq org-log-note-purpose 'note)
9346 "this entry")
9347 (t (error "This should not happen")))))
9348 (if org-log-note-extra (insert org-log-note-extra))
9349 (org-set-local 'org-finish-function 'org-store-log-note)))
9351 (defvar org-note-abort nil) ; dynamically scoped
9352 (defun org-store-log-note ()
9353 "Finish taking a log note, and insert it to where it belongs."
9354 (let ((txt (buffer-string))
9355 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9356 lines ind)
9357 (kill-buffer (current-buffer))
9358 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9359 (setq txt (replace-match "" t t txt)))
9360 (if (string-match "\\s-+\\'" txt)
9361 (setq txt (replace-match "" t t txt)))
9362 (setq lines (org-split-string txt "\n"))
9363 (when (and note (string-match "\\S-" note))
9364 (setq note
9365 (org-replace-escapes
9366 note
9367 (list (cons "%u" (user-login-name))
9368 (cons "%U" user-full-name)
9369 (cons "%t" (format-time-string
9370 (org-time-stamp-format 'long 'inactive)
9371 (current-time)))
9372 (cons "%s" (if org-log-note-state
9373 (concat "\"" org-log-note-state "\"")
9374 ""))
9375 (cons "%S" (if org-log-note-previous-state
9376 (concat "\"" org-log-note-previous-state "\"")
9377 "\"\"")))))
9378 (if lines (setq note (concat note " \\\\")))
9379 (push note lines))
9380 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9381 (when lines
9382 (save-excursion
9383 (set-buffer (marker-buffer org-log-note-marker))
9384 (save-excursion
9385 (goto-char org-log-note-marker)
9386 (move-marker org-log-note-marker nil)
9387 (end-of-line 1)
9388 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9389 (insert "- " (pop lines))
9390 (org-indent-line-function)
9391 (beginning-of-line 1)
9392 (looking-at "[ \t]*")
9393 (setq ind (concat (match-string 0) " "))
9394 (end-of-line 1)
9395 (while lines (insert "\n" ind (pop lines)))
9396 (message "Note stored")
9397 (org-back-to-heading t)
9398 (org-cycle-hide-drawers 'children)))))
9399 (set-window-configuration org-log-note-window-configuration)
9400 (with-current-buffer (marker-buffer org-log-note-return-to)
9401 (goto-char org-log-note-return-to))
9402 (move-marker org-log-note-return-to nil)
9403 (and org-log-post-message (message "%s" org-log-post-message)))
9405 (defun org-sparse-tree (&optional arg)
9406 "Create a sparse tree, prompt for the details.
9407 This command can create sparse trees. You first need to select the type
9408 of match used to create the tree:
9410 t Show entries with a specific TODO keyword.
9411 T Show entries selected by a tags match.
9412 p Enter a property name and its value (both with completion on existing
9413 names/values) and show entries with that property.
9414 r Show entries matching a regular expression
9415 d Show deadlines due within `org-deadline-warning-days'."
9416 (interactive "P")
9417 (let (ans kwd value)
9418 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9419 (setq ans (read-char-exclusive))
9420 (cond
9421 ((equal ans ?d)
9422 (call-interactively 'org-check-deadlines))
9423 ((equal ans ?b)
9424 (call-interactively 'org-check-before-date))
9425 ((equal ans ?t)
9426 (org-show-todo-tree '(4)))
9427 ((equal ans ?T)
9428 (call-interactively 'org-tags-sparse-tree))
9429 ((member ans '(?p ?P))
9430 (setq kwd (org-ido-completing-read "Property: "
9431 (mapcar 'list (org-buffer-property-keys))))
9432 (setq value (org-ido-completing-read "Value: "
9433 (mapcar 'list (org-property-values kwd))))
9434 (unless (string-match "\\`{.*}\\'" value)
9435 (setq value (concat "\"" value "\"")))
9436 (org-tags-sparse-tree arg (concat kwd "=" value)))
9437 ((member ans '(?r ?R ?/))
9438 (call-interactively 'org-occur))
9439 (t (error "No such sparse tree command \"%c\"" ans)))))
9441 (defvar org-occur-highlights nil
9442 "List of overlays used for occur matches.")
9443 (make-variable-buffer-local 'org-occur-highlights)
9444 (defvar org-occur-parameters nil
9445 "Parameters of the active org-occur calls.
9446 This is a list, each call to org-occur pushes as cons cell,
9447 containing the regular expression and the callback, onto the list.
9448 The list can contain several entries if `org-occur' has been called
9449 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9450 will only contain one set of parameters. When the highlights are
9451 removed (for example with `C-c C-c', or with the next edit (depending
9452 on `org-remove-highlights-with-change'), this variable is emptied
9453 as well.")
9454 (make-variable-buffer-local 'org-occur-parameters)
9456 (defun org-occur (regexp &optional keep-previous callback)
9457 "Make a compact tree which shows all matches of REGEXP.
9458 The tree will show the lines where the regexp matches, and all higher
9459 headlines above the match. It will also show the heading after the match,
9460 to make sure editing the matching entry is easy.
9461 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9462 call to `org-occur' will be kept, to allow stacking of calls to this
9463 command.
9464 If CALLBACK is non-nil, it is a function which is called to confirm
9465 that the match should indeed be shown."
9466 (interactive "sRegexp: \nP")
9467 (unless keep-previous
9468 (org-remove-occur-highlights nil nil t))
9469 (push (cons regexp callback) org-occur-parameters)
9470 (let ((cnt 0))
9471 (save-excursion
9472 (goto-char (point-min))
9473 (if (or (not keep-previous) ; do not want to keep
9474 (not org-occur-highlights)) ; no previous matches
9475 ;; hide everything
9476 (org-overview))
9477 (while (re-search-forward regexp nil t)
9478 (when (or (not callback)
9479 (save-match-data (funcall callback)))
9480 (setq cnt (1+ cnt))
9481 (when org-highlight-sparse-tree-matches
9482 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9483 (org-show-context 'occur-tree))))
9484 (when org-remove-highlights-with-change
9485 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9486 nil 'local))
9487 (unless org-sparse-tree-open-archived-trees
9488 (org-hide-archived-subtrees (point-min) (point-max)))
9489 (run-hooks 'org-occur-hook)
9490 (if (interactive-p)
9491 (message "%d match(es) for regexp %s" cnt regexp))
9492 cnt))
9494 (defun org-show-context (&optional key)
9495 "Make sure point and context and visible.
9496 How much context is shown depends upon the variables
9497 `org-show-hierarchy-above', `org-show-following-heading'. and
9498 `org-show-siblings'."
9499 (let ((heading-p (org-on-heading-p t))
9500 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9501 (following-p (org-get-alist-option org-show-following-heading key))
9502 (entry-p (org-get-alist-option org-show-entry-below key))
9503 (siblings-p (org-get-alist-option org-show-siblings key)))
9504 (catch 'exit
9505 ;; Show heading or entry text
9506 (if (and heading-p (not entry-p))
9507 (org-flag-heading nil) ; only show the heading
9508 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9509 (org-show-hidden-entry))) ; show entire entry
9510 (when following-p
9511 ;; Show next sibling, or heading below text
9512 (save-excursion
9513 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9514 (org-flag-heading nil))))
9515 (when siblings-p (org-show-siblings))
9516 (when hierarchy-p
9517 ;; show all higher headings, possibly with siblings
9518 (save-excursion
9519 (while (and (condition-case nil
9520 (progn (org-up-heading-all 1) t)
9521 (error nil))
9522 (not (bobp)))
9523 (org-flag-heading nil)
9524 (when siblings-p (org-show-siblings))))))))
9526 (defun org-reveal (&optional siblings)
9527 "Show current entry, hierarchy above it, and the following headline.
9528 This can be used to show a consistent set of context around locations
9529 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9530 not t for the search context.
9532 With optional argument SIBLINGS, on each level of the hierarchy all
9533 siblings are shown. This repairs the tree structure to what it would
9534 look like when opened with hierarchical calls to `org-cycle'."
9535 (interactive "P")
9536 (let ((org-show-hierarchy-above t)
9537 (org-show-following-heading t)
9538 (org-show-siblings (if siblings t org-show-siblings)))
9539 (org-show-context nil)))
9541 (defun org-highlight-new-match (beg end)
9542 "Highlight from BEG to END and mark the highlight is an occur headline."
9543 (let ((ov (org-make-overlay beg end)))
9544 (org-overlay-put ov 'face 'secondary-selection)
9545 (push ov org-occur-highlights)))
9547 (defun org-remove-occur-highlights (&optional beg end noremove)
9548 "Remove the occur highlights from the buffer.
9549 BEG and END are ignored. If NOREMOVE is nil, remove this function
9550 from the `before-change-functions' in the current buffer."
9551 (interactive)
9552 (unless org-inhibit-highlight-removal
9553 (mapc 'org-delete-overlay org-occur-highlights)
9554 (setq org-occur-highlights nil)
9555 (setq org-occur-parameters nil)
9556 (unless noremove
9557 (remove-hook 'before-change-functions
9558 'org-remove-occur-highlights 'local))))
9560 ;;;; Priorities
9562 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9563 "Regular expression matching the priority indicator.")
9565 (defvar org-remove-priority-next-time nil)
9567 (defun org-priority-up ()
9568 "Increase the priority of the current item."
9569 (interactive)
9570 (org-priority 'up))
9572 (defun org-priority-down ()
9573 "Decrease the priority of the current item."
9574 (interactive)
9575 (org-priority 'down))
9577 (defun org-priority (&optional action)
9578 "Change the priority of an item by ARG.
9579 ACTION can be `set', `up', `down', or a character."
9580 (interactive)
9581 (setq action (or action 'set))
9582 (let (current new news have remove)
9583 (save-excursion
9584 (org-back-to-heading t)
9585 (if (looking-at org-priority-regexp)
9586 (setq current (string-to-char (match-string 2))
9587 have t)
9588 (setq current org-default-priority))
9589 (cond
9590 ((or (eq action 'set)
9591 (if (featurep 'xemacs) (characterp action) (integerp action)))
9592 (if (not (eq action 'set))
9593 (setq new action)
9594 (message "Priority %c-%c, SPC to remove: "
9595 org-highest-priority org-lowest-priority)
9596 (setq new (read-char-exclusive)))
9597 (if (and (= (upcase org-highest-priority) org-highest-priority)
9598 (= (upcase org-lowest-priority) org-lowest-priority))
9599 (setq new (upcase new)))
9600 (cond ((equal new ?\ ) (setq remove t))
9601 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9602 (error "Priority must be between `%c' and `%c'"
9603 org-highest-priority org-lowest-priority))))
9604 ((eq action 'up)
9605 (if (and (not have) (eq last-command this-command))
9606 (setq new org-lowest-priority)
9607 (setq new (if (and org-priority-start-cycle-with-default (not have))
9608 org-default-priority (1- current)))))
9609 ((eq action 'down)
9610 (if (and (not have) (eq last-command this-command))
9611 (setq new org-highest-priority)
9612 (setq new (if (and org-priority-start-cycle-with-default (not have))
9613 org-default-priority (1+ current)))))
9614 (t (error "Invalid action")))
9615 (if (or (< (upcase new) org-highest-priority)
9616 (> (upcase new) org-lowest-priority))
9617 (setq remove t))
9618 (setq news (format "%c" new))
9619 (if have
9620 (if remove
9621 (replace-match "" t t nil 1)
9622 (replace-match news t t nil 2))
9623 (if remove
9624 (error "No priority cookie found in line")
9625 (looking-at org-todo-line-regexp)
9626 (if (match-end 2)
9627 (progn
9628 (goto-char (match-end 2))
9629 (insert " [#" news "]"))
9630 (goto-char (match-beginning 3))
9631 (insert "[#" news "] ")))))
9632 (org-preserve-lc (org-set-tags nil 'align))
9633 (if remove
9634 (message "Priority removed")
9635 (message "Priority of current item set to %s" news))))
9638 (defun org-get-priority (s)
9639 "Find priority cookie and return priority."
9640 (save-match-data
9641 (if (not (string-match org-priority-regexp s))
9642 (* 1000 (- org-lowest-priority org-default-priority))
9643 (* 1000 (- org-lowest-priority
9644 (string-to-char (match-string 2 s)))))))
9646 ;;;; Tags
9648 (defvar org-agenda-archives-mode)
9649 (defun org-scan-tags (action matcher &optional todo-only)
9650 "Scan headline tags with inheritance and produce output ACTION.
9652 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9653 or `agenda' to produce an entry list for an agenda view. It can also be
9654 a Lisp form or a function that should be called at each matched headline, in
9655 this case the return value is a list of all return values from these calls.
9657 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9658 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9659 only lines with a TODO keyword are included in the output."
9660 (require 'org-agenda)
9661 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9662 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9663 (org-re
9664 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9665 (props (list 'face 'default
9666 'done-face 'org-done
9667 'undone-face 'default
9668 'mouse-face 'highlight
9669 'org-not-done-regexp org-not-done-regexp
9670 'org-todo-regexp org-todo-regexp
9671 'keymap org-agenda-keymap
9672 'help-echo
9673 (format "mouse-2 or RET jump to org file %s"
9674 (abbreviate-file-name
9675 (or (buffer-file-name (buffer-base-buffer))
9676 (buffer-name (buffer-base-buffer)))))))
9677 (case-fold-search nil)
9678 lspos tags tags-list
9679 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9680 (llast 0) rtn rtn1 level category i txt
9681 todo marker entry priority)
9682 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9683 (setq action (list 'lambda nil action)))
9684 (save-excursion
9685 (goto-char (point-min))
9686 (when (eq action 'sparse-tree)
9687 (org-overview)
9688 (org-remove-occur-highlights))
9689 (while (re-search-forward re nil t)
9690 (catch :skip
9691 (setq todo (if (match-end 1) (match-string 2))
9692 tags (if (match-end 4) (match-string 4)))
9693 (goto-char (setq lspos (1+ (match-beginning 0))))
9694 (setq level (org-reduced-level (funcall outline-level))
9695 category (org-get-category))
9696 (setq i llast llast level)
9697 ;; remove tag lists from same and sublevels
9698 (while (>= i level)
9699 (when (setq entry (assoc i tags-alist))
9700 (setq tags-alist (delete entry tags-alist)))
9701 (setq i (1- i)))
9702 ;; add the next tags
9703 (when tags
9704 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9705 tags-alist
9706 (cons (cons level tags) tags-alist)))
9707 ;; compile tags for current headline
9708 (setq tags-list
9709 (if org-use-tag-inheritance
9710 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9711 tags))
9712 (when org-use-tag-inheritance
9713 (setcdr (car tags-alist)
9714 (mapcar (lambda (x)
9715 (setq x (copy-sequence x))
9716 (org-add-prop-inherited x))
9717 (cdar tags-alist))))
9718 (when (and tags org-use-tag-inheritance
9719 (not (eq t org-use-tag-inheritance)))
9720 ;; selective inheritance, remove uninherited ones
9721 (setcdr (car tags-alist)
9722 (org-remove-uniherited-tags (cdar tags-alist))))
9723 (when (and (or (not todo-only)
9724 (and (member todo org-not-done-keywords)
9725 (or (not org-agenda-tags-todo-honor-ignore-options)
9726 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9727 (let ((case-fold-search t)) (eval matcher))
9729 (not (member org-archive-tag tags-list))
9730 ;; we have an archive tag, should we use this anyway?
9731 (or (not org-agenda-skip-archived-trees)
9732 (and (eq action 'agenda) org-agenda-archives-mode))))
9733 (unless (eq action 'sparse-tree) (org-agenda-skip))
9735 ;; select this headline
9737 (cond
9738 ((eq action 'sparse-tree)
9739 (and org-highlight-sparse-tree-matches
9740 (org-get-heading) (match-end 0)
9741 (org-highlight-new-match
9742 (match-beginning 0) (match-beginning 1)))
9743 (org-show-context 'tags-tree))
9744 ((eq action 'agenda)
9745 (setq txt (org-format-agenda-item
9747 (concat
9748 (if org-tags-match-list-sublevels
9749 (make-string (1- level) ?.) "")
9750 (org-get-heading))
9751 category (org-get-tags-at))
9752 priority (org-get-priority txt))
9753 (goto-char lspos)
9754 (setq marker (org-agenda-new-marker))
9755 (org-add-props txt props
9756 'org-marker marker 'org-hd-marker marker 'org-category category
9757 'todo-state todo
9758 'priority priority 'type "tagsmatch")
9759 (push txt rtn))
9760 ((functionp action)
9761 (save-excursion
9762 (setq rtn1 (funcall action))
9763 (push rtn1 rtn))
9764 (goto-char (point-at-eol)))
9765 (t (error "Invalid action")))
9767 ;; if we are to skip sublevels, jump to end of subtree
9768 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9769 (when (and (eq action 'sparse-tree)
9770 (not org-sparse-tree-open-archived-trees))
9771 (org-hide-archived-subtrees (point-min) (point-max)))
9772 (nreverse rtn)))
9774 (defun org-remove-uniherited-tags (tags)
9775 "Remove all tags that are not inherited from the list TAGS."
9776 (cond
9777 ((eq org-use-tag-inheritance t)
9778 (if org-tags-exclude-from-inheritance
9779 (org-delete-all org-tags-exclude-from-inheritance tags)
9780 tags))
9781 ((not org-use-tag-inheritance) nil)
9782 ((stringp org-use-tag-inheritance)
9783 (delq nil (mapcar
9784 (lambda (x)
9785 (if (and (string-match org-use-tag-inheritance x)
9786 (not (member x org-tags-exclude-from-inheritance)))
9787 x nil))
9788 tags)))
9789 ((listp org-use-tag-inheritance)
9790 (delq nil (mapcar
9791 (lambda (x)
9792 (if (member x org-use-tag-inheritance) x nil))
9793 tags)))))
9795 (defvar todo-only) ;; dynamically scoped
9797 (defun org-tags-sparse-tree (&optional todo-only match)
9798 "Create a sparse tree according to tags string MATCH.
9799 MATCH can contain positive and negative selection of tags, like
9800 \"+WORK+URGENT-WITHBOSS\".
9801 If optional argument TODO-ONLY is non-nil, only select lines that are
9802 also TODO lines."
9803 (interactive "P")
9804 (org-prepare-agenda-buffers (list (current-buffer)))
9805 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9807 (defvar org-cached-props nil)
9808 (defun org-cached-entry-get (pom property)
9809 (if (or (eq t org-use-property-inheritance)
9810 (and (stringp org-use-property-inheritance)
9811 (string-match org-use-property-inheritance property))
9812 (and (listp org-use-property-inheritance)
9813 (member property org-use-property-inheritance)))
9814 ;; Caching is not possible, check it directly
9815 (org-entry-get pom property 'inherit)
9816 ;; Get all properties, so that we can do complicated checks easily
9817 (cdr (assoc property (or org-cached-props
9818 (setq org-cached-props
9819 (org-entry-properties pom)))))))
9821 (defun org-global-tags-completion-table (&optional files)
9822 "Return the list of all tags in all agenda buffer/files."
9823 (save-excursion
9824 (org-uniquify
9825 (delq nil
9826 (apply 'append
9827 (mapcar
9828 (lambda (file)
9829 (set-buffer (find-file-noselect file))
9830 (append (org-get-buffer-tags)
9831 (mapcar (lambda (x) (if (stringp (car-safe x))
9832 (list (car-safe x)) nil))
9833 org-tag-alist)))
9834 (if (and files (car files))
9835 files
9836 (org-agenda-files))))))))
9838 (defun org-make-tags-matcher (match)
9839 "Create the TAGS//TODO matcher form for the selection string MATCH."
9840 ;; todo-only is scoped dynamically into this function, and the function
9841 ;; may change it if the matcher asks for it.
9842 (unless match
9843 ;; Get a new match request, with completion
9844 (let ((org-last-tags-completion-table
9845 (org-global-tags-completion-table)))
9846 (setq match (org-completing-read-no-ido
9847 "Match: " 'org-tags-completion-function nil nil nil
9848 'org-tags-history))))
9850 ;; Parse the string and create a lisp form
9851 (let ((match0 match)
9852 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9853 minus tag mm
9854 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9855 orterms term orlist re-p str-p level-p level-op time-p
9856 prop-p pn pv po cat-p gv rest)
9857 (if (string-match "/+" match)
9858 ;; match contains also a todo-matching request
9859 (progn
9860 (setq tagsmatch (substring match 0 (match-beginning 0))
9861 todomatch (substring match (match-end 0)))
9862 (if (string-match "^!" todomatch)
9863 (setq todo-only t todomatch (substring todomatch 1)))
9864 (if (string-match "^\\s-*$" todomatch)
9865 (setq todomatch nil)))
9866 ;; only matching tags
9867 (setq tagsmatch match todomatch nil))
9869 ;; Make the tags matcher
9870 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9871 (setq tagsmatcher t)
9872 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9873 (while (setq term (pop orterms))
9874 (while (and (equal (substring term -1) "\\") orterms)
9875 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9876 (while (string-match re term)
9877 (setq rest (substring term (match-end 0))
9878 minus (and (match-end 1)
9879 (equal (match-string 1 term) "-"))
9880 tag (match-string 2 term)
9881 re-p (equal (string-to-char tag) ?{)
9882 level-p (match-end 4)
9883 prop-p (match-end 5)
9884 mm (cond
9885 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9886 (level-p
9887 (setq level-op (org-op-to-function (match-string 3 term)))
9888 `(,level-op level ,(string-to-number
9889 (match-string 4 term))))
9890 (prop-p
9891 (setq pn (match-string 5 term)
9892 po (match-string 6 term)
9893 pv (match-string 7 term)
9894 cat-p (equal pn "CATEGORY")
9895 re-p (equal (string-to-char pv) ?{)
9896 str-p (equal (string-to-char pv) ?\")
9897 time-p (save-match-data
9898 (string-match "^\"[[<].*[]>]\"$" pv))
9899 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9900 (if time-p (setq pv (org-matcher-time pv)))
9901 (setq po (org-op-to-function po (if time-p 'time str-p)))
9902 (cond
9903 ((equal pn "CATEGORY")
9904 (setq gv '(get-text-property (point) 'org-category)))
9905 ((equal pn "TODO")
9906 (setq gv 'todo))
9908 (setq gv `(org-cached-entry-get nil ,pn))))
9909 (if re-p
9910 (if (eq po 'org<>)
9911 `(not (string-match ,pv (or ,gv "")))
9912 `(string-match ,pv (or ,gv "")))
9913 (if str-p
9914 `(,po (or ,gv "") ,pv)
9915 `(,po (string-to-number (or ,gv ""))
9916 ,(string-to-number pv) ))))
9917 (t `(member ,(downcase tag) tags-list)))
9918 mm (if minus (list 'not mm) mm)
9919 term rest)
9920 (push mm tagsmatcher))
9921 (push (if (> (length tagsmatcher) 1)
9922 (cons 'and tagsmatcher)
9923 (car tagsmatcher))
9924 orlist)
9925 (setq tagsmatcher nil))
9926 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9927 (setq tagsmatcher
9928 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9929 ;; Make the todo matcher
9930 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9931 (setq todomatcher t)
9932 (setq orterms (org-split-string todomatch "|") orlist nil)
9933 (while (setq term (pop orterms))
9934 (while (string-match re term)
9935 (setq minus (and (match-end 1)
9936 (equal (match-string 1 term) "-"))
9937 kwd (match-string 2 term)
9938 re-p (equal (string-to-char kwd) ?{)
9939 term (substring term (match-end 0))
9940 mm (if re-p
9941 `(string-match ,(substring kwd 1 -1) todo)
9942 (list 'equal 'todo kwd))
9943 mm (if minus (list 'not mm) mm))
9944 (push mm todomatcher))
9945 (push (if (> (length todomatcher) 1)
9946 (cons 'and todomatcher)
9947 (car todomatcher))
9948 orlist)
9949 (setq todomatcher nil))
9950 (setq todomatcher (if (> (length orlist) 1)
9951 (cons 'or orlist) (car orlist))))
9953 ;; Return the string and lisp forms of the matcher
9954 (setq matcher (if todomatcher
9955 (list 'and tagsmatcher todomatcher)
9956 tagsmatcher))
9957 (cons match0 matcher)))
9959 (defun org-op-to-function (op &optional stringp)
9960 "Turn an operator into the appropriate function."
9961 (setq op
9962 (cond
9963 ((equal op "<" ) '(< string< org-time<))
9964 ((equal op ">" ) '(> org-string> org-time>))
9965 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9966 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9967 ((member op '("=" "==")) '(= string= org-time=))
9968 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9969 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9971 (defun org<> (a b) (not (= a b)))
9972 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9973 (defun org-string>= (a b) (not (string< a b)))
9974 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9975 (defun org-string<> (a b) (not (string= a b)))
9976 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9977 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9978 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9979 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9980 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9981 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9982 (defun org-2ft (s)
9983 "Convert S to a floating point time.
9984 If S is already a number, just return it. If it is a string, parse
9985 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9986 (cond
9987 ((numberp s) s)
9988 ((stringp s)
9989 (condition-case nil
9990 (float-time (apply 'encode-time (org-parse-time-string s)))
9991 (error 0.)))
9992 (t 0.)))
9994 (defun org-time-today ()
9995 "Time in seconds today at 0:00.
9996 Returns the float number of seconds since the beginning of the
9997 epoch to the beginning of today (00:00)."
9998 (float-time (apply 'encode-time
9999 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10001 (defun org-matcher-time (s)
10002 "Interpret a time comparison value."
10003 (save-match-data
10004 (cond
10005 ((string= s "<now>") (float-time))
10006 ((string= s "<today>") (org-time-today))
10007 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10008 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10009 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10010 (+ (org-time-today)
10011 (* (string-to-number (match-string 1 s))
10012 (cdr (assoc (match-string 2 s)
10013 '(("d" . 86400.0) ("w" . 604800.0)
10014 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10015 (t (org-2ft s)))))
10017 (defun org-match-any-p (re list)
10018 "Does re match any element of list?"
10019 (setq list (mapcar (lambda (x) (string-match re x)) list))
10020 (delq nil list))
10022 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10023 (defvar org-tags-overlay (org-make-overlay 1 1))
10024 (org-detach-overlay org-tags-overlay)
10026 (defun org-get-local-tags-at (&optional pos)
10027 "Get a list of tags defined in the current headline."
10028 (org-get-tags-at pos 'local))
10030 (defun org-get-local-tags ()
10031 "Get a list of tags defined in the current headline."
10032 (org-get-tags-at nil 'local))
10034 (defun org-get-tags-at (&optional pos local)
10035 "Get a list of all headline tags applicable at POS.
10036 POS defaults to point. If tags are inherited, the list contains
10037 the targets in the same sequence as the headlines appear, i.e.
10038 the tags of the current headline come last.
10039 When LOCAL is non-nil, only return tags from the current headline,
10040 ignore inherited ones."
10041 (interactive)
10042 (let (tags ltags lastpos parent)
10043 (save-excursion
10044 (save-restriction
10045 (widen)
10046 (goto-char (or pos (point)))
10047 (save-match-data
10048 (catch 'done
10049 (condition-case nil
10050 (progn
10051 (org-back-to-heading t)
10052 (while (not (equal lastpos (point)))
10053 (setq lastpos (point))
10054 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10055 (setq ltags (org-split-string
10056 (org-match-string-no-properties 1) ":"))
10057 (when parent
10058 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10059 (setq tags (append
10060 (if parent
10061 (org-remove-uniherited-tags ltags)
10062 ltags)
10063 tags)))
10064 (or org-use-tag-inheritance (throw 'done t))
10065 (if local (throw 'done t))
10066 (org-up-heading-all 1)
10067 (setq parent t)))
10068 (error nil)))))
10069 (append (org-remove-uniherited-tags org-file-tags) tags))))
10071 (defun org-add-prop-inherited (s)
10072 (add-text-properties 0 (length s) '(inherited t) s)
10075 (defun org-toggle-tag (tag &optional onoff)
10076 "Toggle the tag TAG for the current line.
10077 If ONOFF is `on' or `off', don't toggle but set to this state."
10078 (let (res current)
10079 (save-excursion
10080 (org-back-to-heading t)
10081 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10082 (point-at-eol) t)
10083 (progn
10084 (setq current (match-string 1))
10085 (replace-match ""))
10086 (setq current ""))
10087 (setq current (nreverse (org-split-string current ":")))
10088 (cond
10089 ((eq onoff 'on)
10090 (setq res t)
10091 (or (member tag current) (push tag current)))
10092 ((eq onoff 'off)
10093 (or (not (member tag current)) (setq current (delete tag current))))
10094 (t (if (member tag current)
10095 (setq current (delete tag current))
10096 (setq res t)
10097 (push tag current))))
10098 (end-of-line 1)
10099 (if current
10100 (progn
10101 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10102 (org-set-tags nil t))
10103 (delete-horizontal-space))
10104 (run-hooks 'org-after-tags-change-hook))
10105 res))
10107 (defun org-align-tags-here (to-col)
10108 ;; Assumes that this is a headline
10109 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10110 (beginning-of-line 1)
10111 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10112 (< pos (match-beginning 2)))
10113 (progn
10114 (setq tags-l (- (match-end 2) (match-beginning 2)))
10115 (goto-char (match-beginning 1))
10116 (insert " ")
10117 (delete-region (point) (1+ (match-beginning 2)))
10118 (setq ncol (max (1+ (current-column))
10119 (1+ col)
10120 (if (> to-col 0)
10121 to-col
10122 (- (abs to-col) tags-l))))
10123 (setq p (point))
10124 (insert (make-string (- ncol (current-column)) ?\ ))
10125 (setq ncol (current-column))
10126 (when indent-tabs-mode (tabify p (point-at-eol)))
10127 (org-move-to-column (min ncol col) t))
10128 (goto-char pos))))
10130 (defun org-set-tags-command (&optional arg just-align)
10131 "Call the set-tags command for the current entry."
10132 (interactive "P")
10133 (if (org-on-heading-p)
10134 (org-set-tags arg just-align)
10135 (save-excursion
10136 (org-back-to-heading t)
10137 (org-set-tags arg just-align))))
10139 (defun org-set-tags (&optional arg just-align)
10140 "Set the tags for the current headline.
10141 With prefix ARG, realign all tags in headings in the current buffer."
10142 (interactive "P")
10143 (let* ((re (concat "^" outline-regexp))
10144 (current (org-get-tags-string))
10145 (col (current-column))
10146 (org-setting-tags t)
10147 table current-tags inherited-tags ; computed below when needed
10148 tags p0 c0 c1 rpl)
10149 (if arg
10150 (save-excursion
10151 (goto-char (point-min))
10152 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10153 (while (re-search-forward re nil t)
10154 (org-set-tags nil t)
10155 (end-of-line 1)))
10156 (message "All tags realigned to column %d" org-tags-column))
10157 (if just-align
10158 (setq tags current)
10159 ;; Get a new set of tags from the user
10160 (save-excursion
10161 (setq table (or org-tag-alist (org-get-buffer-tags))
10162 org-last-tags-completion-table table
10163 current-tags (org-split-string current ":")
10164 inherited-tags (nreverse
10165 (nthcdr (length current-tags)
10166 (nreverse (org-get-tags-at))))
10167 tags
10168 (if (or (eq t org-use-fast-tag-selection)
10169 (and org-use-fast-tag-selection
10170 (delq nil (mapcar 'cdr table))))
10171 (org-fast-tag-selection
10172 current-tags inherited-tags table
10173 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10174 (let ((org-add-colon-after-tag-completion t))
10175 (org-trim
10176 (org-without-partial-completion
10177 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10178 nil nil current 'org-tags-history)))))))
10179 (while (string-match "[-+&]+" tags)
10180 ;; No boolean logic, just a list
10181 (setq tags (replace-match ":" t t tags))))
10183 (if (string-match "\\`[\t ]*\\'" tags)
10184 (setq tags "")
10185 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10186 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10188 ;; Insert new tags at the correct column
10189 (beginning-of-line 1)
10190 (cond
10191 ((and (equal current "") (equal tags "")))
10192 ((re-search-forward
10193 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10194 (point-at-eol) t)
10195 (if (equal tags "")
10196 (setq rpl "")
10197 (goto-char (match-beginning 0))
10198 (setq c0 (current-column) p0 (point)
10199 c1 (max (1+ c0) (if (> org-tags-column 0)
10200 org-tags-column
10201 (- (- org-tags-column) (length tags))))
10202 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10203 (replace-match rpl t t)
10204 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10205 tags)
10206 (t (error "Tags alignment failed")))
10207 (org-move-to-column col)
10208 (unless just-align
10209 (run-hooks 'org-after-tags-change-hook)))))
10211 (defun org-change-tag-in-region (beg end tag off)
10212 "Add or remove TAG for each entry in the region.
10213 This works in the agenda, and also in an org-mode buffer."
10214 (interactive
10215 (list (region-beginning) (region-end)
10216 (let ((org-last-tags-completion-table
10217 (if (org-mode-p)
10218 (org-get-buffer-tags)
10219 (org-global-tags-completion-table))))
10220 (org-ido-completing-read
10221 "Tag: " 'org-tags-completion-function nil nil nil
10222 'org-tags-history))
10223 (progn
10224 (message "[s]et or [r]emove? ")
10225 (equal (read-char-exclusive) ?r))))
10226 (if (fboundp 'deactivate-mark) (deactivate-mark))
10227 (let ((agendap (equal major-mode 'org-agenda-mode))
10228 l1 l2 m buf pos newhead (cnt 0))
10229 (goto-char end)
10230 (setq l2 (1- (org-current-line)))
10231 (goto-char beg)
10232 (setq l1 (org-current-line))
10233 (loop for l from l1 to l2 do
10234 (goto-line l)
10235 (setq m (get-text-property (point) 'org-hd-marker))
10236 (when (or (and (org-mode-p) (org-on-heading-p))
10237 (and agendap m))
10238 (setq buf (if agendap (marker-buffer m) (current-buffer))
10239 pos (if agendap m (point)))
10240 (with-current-buffer buf
10241 (save-excursion
10242 (save-restriction
10243 (goto-char pos)
10244 (setq cnt (1+ cnt))
10245 (org-toggle-tag tag (if off 'off 'on))
10246 (setq newhead (org-get-heading)))))
10247 (and agendap (org-agenda-change-all-lines newhead m))))
10248 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10250 (defun org-tags-completion-function (string predicate &optional flag)
10251 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10252 (confirm (lambda (x) (stringp (car x)))))
10253 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10254 (setq s1 (match-string 1 string)
10255 s2 (match-string 2 string))
10256 (setq s1 "" s2 string))
10257 (cond
10258 ((eq flag nil)
10259 ;; try completion
10260 (setq rtn (try-completion s2 ctable confirm))
10261 (if (stringp rtn)
10262 (setq rtn
10263 (concat s1 s2 (substring rtn (length s2))
10264 (if (and org-add-colon-after-tag-completion
10265 (assoc rtn ctable))
10266 ":" ""))))
10267 rtn)
10268 ((eq flag t)
10269 ;; all-completions
10270 (all-completions s2 ctable confirm)
10272 ((eq flag 'lambda)
10273 ;; exact match?
10274 (assoc s2 ctable)))
10277 (defun org-fast-tag-insert (kwd tags face &optional end)
10278 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10279 (insert (format "%-12s" (concat kwd ":"))
10280 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10281 (or end "")))
10283 (defun org-fast-tag-show-exit (flag)
10284 (save-excursion
10285 (goto-line 3)
10286 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10287 (replace-match ""))
10288 (when flag
10289 (end-of-line 1)
10290 (org-move-to-column (- (window-width) 19) t)
10291 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10293 (defun org-set-current-tags-overlay (current prefix)
10294 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10295 (if (featurep 'xemacs)
10296 (org-overlay-display org-tags-overlay (concat prefix s)
10297 'secondary-selection)
10298 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10299 (org-overlay-display org-tags-overlay (concat prefix s)))))
10301 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10302 "Fast tag selection with single keys.
10303 CURRENT is the current list of tags in the headline, INHERITED is the
10304 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10305 possibly with grouping information. TODO-TABLE is a similar table with
10306 TODO keywords, should these have keys assigned to them.
10307 If the keys are nil, a-z are automatically assigned.
10308 Returns the new tags string, or nil to not change the current settings."
10309 (let* ((fulltable (append table todo-table))
10310 (maxlen (apply 'max (mapcar
10311 (lambda (x)
10312 (if (stringp (car x)) (string-width (car x)) 0))
10313 fulltable)))
10314 (buf (current-buffer))
10315 (expert (eq org-fast-tag-selection-single-key 'expert))
10316 (buffer-tags nil)
10317 (fwidth (+ maxlen 3 1 3))
10318 (ncol (/ (- (window-width) 4) fwidth))
10319 (i-face 'org-done)
10320 (c-face 'org-todo)
10321 tg cnt e c char c1 c2 ntable tbl rtn
10322 ov-start ov-end ov-prefix
10323 (exit-after-next org-fast-tag-selection-single-key)
10324 (done-keywords org-done-keywords)
10325 groups ingroup)
10326 (save-excursion
10327 (beginning-of-line 1)
10328 (if (looking-at
10329 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10330 (setq ov-start (match-beginning 1)
10331 ov-end (match-end 1)
10332 ov-prefix "")
10333 (setq ov-start (1- (point-at-eol))
10334 ov-end (1+ ov-start))
10335 (skip-chars-forward "^\n\r")
10336 (setq ov-prefix
10337 (concat
10338 (buffer-substring (1- (point)) (point))
10339 (if (> (current-column) org-tags-column)
10341 (make-string (- org-tags-column (current-column)) ?\ ))))))
10342 (org-move-overlay org-tags-overlay ov-start ov-end)
10343 (save-window-excursion
10344 (if expert
10345 (set-buffer (get-buffer-create " *Org tags*"))
10346 (delete-other-windows)
10347 (split-window-vertically)
10348 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10349 (erase-buffer)
10350 (org-set-local 'org-done-keywords done-keywords)
10351 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10352 (org-fast-tag-insert "Current" current c-face "\n\n")
10353 (org-fast-tag-show-exit exit-after-next)
10354 (org-set-current-tags-overlay current ov-prefix)
10355 (setq tbl fulltable char ?a cnt 0)
10356 (while (setq e (pop tbl))
10357 (cond
10358 ((equal e '(:startgroup))
10359 (push '() groups) (setq ingroup t)
10360 (when (not (= cnt 0))
10361 (setq cnt 0)
10362 (insert "\n"))
10363 (insert "{ "))
10364 ((equal e '(:endgroup))
10365 (setq ingroup nil cnt 0)
10366 (insert "}\n"))
10367 ((equal e '(:newline))
10368 (insert "\n "))
10370 (setq tg (car e) c2 nil)
10371 (if (cdr e)
10372 (setq c (cdr e))
10373 ;; automatically assign a character.
10374 (setq c1 (string-to-char
10375 (downcase (substring
10376 tg (if (= (string-to-char tg) ?@) 1 0)))))
10377 (if (or (rassoc c1 ntable) (rassoc c1 table))
10378 (while (or (rassoc char ntable) (rassoc char table))
10379 (setq char (1+ char)))
10380 (setq c2 c1))
10381 (setq c (or c2 char)))
10382 (if ingroup (push tg (car groups)))
10383 (setq tg (org-add-props tg nil 'face
10384 (cond
10385 ((not (assoc tg table))
10386 (org-get-todo-face tg))
10387 ((member tg current) c-face)
10388 ((member tg inherited) i-face)
10389 (t nil))))
10390 (if (and (= cnt 0) (not ingroup)) (insert " "))
10391 (insert "[" c "] " tg (make-string
10392 (- fwidth 4 (length tg)) ?\ ))
10393 (push (cons tg c) ntable)
10394 (when (= (setq cnt (1+ cnt)) ncol)
10395 (insert "\n")
10396 (if ingroup (insert " "))
10397 (setq cnt 0)))))
10398 (setq ntable (nreverse ntable))
10399 (insert "\n")
10400 (goto-char (point-min))
10401 (if (not expert) (org-fit-window-to-buffer))
10402 (setq rtn
10403 (catch 'exit
10404 (while t
10405 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10406 (if groups " [!] no groups" " [!]groups")
10407 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10408 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10409 (cond
10410 ((= c ?\r) (throw 'exit t))
10411 ((= c ?!)
10412 (setq groups (not groups))
10413 (goto-char (point-min))
10414 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10415 ((= c ?\C-c)
10416 (if (not expert)
10417 (org-fast-tag-show-exit
10418 (setq exit-after-next (not exit-after-next)))
10419 (setq expert nil)
10420 (delete-other-windows)
10421 (split-window-vertically)
10422 (org-switch-to-buffer-other-window " *Org tags*")
10423 (org-fit-window-to-buffer)))
10424 ((or (= c ?\C-g)
10425 (and (= c ?q) (not (rassoc c ntable))))
10426 (org-detach-overlay org-tags-overlay)
10427 (setq quit-flag t))
10428 ((= c ?\ )
10429 (setq current nil)
10430 (if exit-after-next (setq exit-after-next 'now)))
10431 ((= c ?\t)
10432 (condition-case nil
10433 (setq tg (org-ido-completing-read
10434 "Tag: "
10435 (or buffer-tags
10436 (with-current-buffer buf
10437 (org-get-buffer-tags)))))
10438 (quit (setq tg "")))
10439 (when (string-match "\\S-" tg)
10440 (add-to-list 'buffer-tags (list tg))
10441 (if (member tg current)
10442 (setq current (delete tg current))
10443 (push tg current)))
10444 (if exit-after-next (setq exit-after-next 'now)))
10445 ((setq e (rassoc c todo-table) tg (car e))
10446 (with-current-buffer buf
10447 (save-excursion (org-todo tg)))
10448 (if exit-after-next (setq exit-after-next 'now)))
10449 ((setq e (rassoc c ntable) tg (car e))
10450 (if (member tg current)
10451 (setq current (delete tg current))
10452 (loop for g in groups do
10453 (if (member tg g)
10454 (mapc (lambda (x)
10455 (setq current (delete x current)))
10456 g)))
10457 (push tg current))
10458 (if exit-after-next (setq exit-after-next 'now))))
10460 ;; Create a sorted list
10461 (setq current
10462 (sort current
10463 (lambda (a b)
10464 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10465 (if (eq exit-after-next 'now) (throw 'exit t))
10466 (goto-char (point-min))
10467 (beginning-of-line 2)
10468 (delete-region (point) (point-at-eol))
10469 (org-fast-tag-insert "Current" current c-face)
10470 (org-set-current-tags-overlay current ov-prefix)
10471 (while (re-search-forward
10472 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10473 (setq tg (match-string 1))
10474 (add-text-properties
10475 (match-beginning 1) (match-end 1)
10476 (list 'face
10477 (cond
10478 ((member tg current) c-face)
10479 ((member tg inherited) i-face)
10480 (t (get-text-property (match-beginning 1) 'face))))))
10481 (goto-char (point-min)))))
10482 (org-detach-overlay org-tags-overlay)
10483 (if rtn
10484 (mapconcat 'identity current ":")
10485 nil))))
10487 (defun org-get-tags-string ()
10488 "Get the TAGS string in the current headline."
10489 (unless (org-on-heading-p t)
10490 (error "Not on a heading"))
10491 (save-excursion
10492 (beginning-of-line 1)
10493 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10494 (org-match-string-no-properties 1)
10495 "")))
10497 (defun org-get-tags ()
10498 "Get the list of tags specified in the current headline."
10499 (org-split-string (org-get-tags-string) ":"))
10501 (defun org-get-buffer-tags ()
10502 "Get a table of all tags used in the buffer, for completion."
10503 (let (tags)
10504 (save-excursion
10505 (goto-char (point-min))
10506 (while (re-search-forward
10507 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10508 (when (equal (char-after (point-at-bol 0)) ?*)
10509 (mapc (lambda (x) (add-to-list 'tags x))
10510 (org-split-string (org-match-string-no-properties 1) ":")))))
10511 (mapcar 'list tags)))
10513 ;;;; The mapping API
10515 ;;;###autoload
10516 (defun org-map-entries (func &optional match scope &rest skip)
10517 "Call FUNC at each headline selected by MATCH in SCOPE.
10519 FUNC is a function or a lisp form. The function will be called without
10520 arguments, with the cursor positioned at the beginning of the headline.
10521 The return values of all calls to the function will be collected and
10522 returned as a list.
10524 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10525 Only headlines that are matched by this query will be considered during
10526 the iteration. When MATCH is nil or t, all headlines will be
10527 visited by the iteration.
10529 SCOPE determines the scope of this command. It can be any of:
10531 nil The current buffer, respecting the restriction if any
10532 tree The subtree started with the entry at point
10533 file The current buffer, without restriction
10534 file-with-archives
10535 The current buffer, and any archives associated with it
10536 agenda All agenda files
10537 agenda-with-archives
10538 All agenda files with any archive files associated with them
10539 \(file1 file2 ...)
10540 If this is a list, all files in the list will be scanned
10542 The remaining args are treated as settings for the skipping facilities of
10543 the scanner. The following items can be given here:
10545 archive skip trees with the archive tag.
10546 comment skip trees with the COMMENT keyword
10547 function or Emacs Lisp form:
10548 will be used as value for `org-agenda-skip-function', so whenever
10549 the the function returns t, FUNC will not be called for that
10550 entry and search will continue from the point where the
10551 function leaves it."
10552 (let* ((org-agenda-archives-mode nil) ; just to make sure
10553 (org-agenda-skip-archived-trees (memq 'archive skip))
10554 (org-agenda-skip-comment-trees (memq 'comment skip))
10555 (org-agenda-skip-function
10556 (car (org-delete-all '(comment archive) skip)))
10557 (org-tags-match-list-sublevels t)
10558 matcher file res
10559 org-todo-keywords-for-agenda
10560 org-done-keywords-for-agenda
10561 org-todo-keyword-alist-for-agenda
10562 org-tag-alist-for-agenda)
10564 (cond
10565 ((eq match t) (setq matcher t))
10566 ((eq match nil) (setq matcher t))
10567 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10569 (save-excursion
10570 (save-restriction
10571 (when (eq scope 'tree)
10572 (org-back-to-heading t)
10573 (org-narrow-to-subtree)
10574 (setq scope nil))
10576 (if (not scope)
10577 (progn
10578 (org-prepare-agenda-buffers
10579 (list (buffer-file-name (current-buffer))))
10580 (setq res (org-scan-tags func matcher)))
10581 ;; Get the right scope
10582 (cond
10583 ((and scope (listp scope) (symbolp (car scope)))
10584 (setq scope (eval scope)))
10585 ((eq scope 'agenda)
10586 (setq scope (org-agenda-files t)))
10587 ((eq scope 'agenda-with-archives)
10588 (setq scope (org-agenda-files t))
10589 (setq scope (org-add-archive-files scope)))
10590 ((eq scope 'file)
10591 (setq scope (list (buffer-file-name))))
10592 ((eq scope 'file-with-archives)
10593 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10594 (org-prepare-agenda-buffers scope)
10595 (while (setq file (pop scope))
10596 (with-current-buffer (org-find-base-buffer-visiting file)
10597 (save-excursion
10598 (save-restriction
10599 (widen)
10600 (goto-char (point-min))
10601 (setq res (append res (org-scan-tags func matcher))))))))))
10602 res))
10604 ;;;; Properties
10606 ;;; Setting and retrieving properties
10608 (defconst org-special-properties
10609 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10610 "TIMESTAMP" "TIMESTAMP_IA")
10611 "The special properties valid in Org-mode.
10613 These are properties that are not defined in the property drawer,
10614 but in some other way.")
10616 (defconst org-default-properties
10617 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10618 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10619 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10620 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10621 "Some properties that are used by Org-mode for various purposes.
10622 Being in this list makes sure that they are offered for completion.")
10624 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10625 "Regular expression matching the first line of a property drawer.")
10627 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10628 "Regular expression matching the first line of a property drawer.")
10630 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10631 "Regular expression matching the first line of a property drawer.")
10633 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10634 "Regular expression matching the first line of a property drawer.")
10636 (defconst org-property-drawer-re
10637 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10638 org-property-end-re "\\)\n?")
10639 "Matches an entire property drawer.")
10641 (defconst org-clock-drawer-re
10642 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10643 org-property-end-re "\\)\n?")
10644 "Matches an entire clock drawer.")
10646 (defun org-property-action ()
10647 "Do an action on properties."
10648 (interactive)
10649 (let (c)
10650 (org-at-property-p)
10651 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10652 (setq c (read-char-exclusive))
10653 (cond
10654 ((equal c ?s)
10655 (call-interactively 'org-set-property))
10656 ((equal c ?d)
10657 (call-interactively 'org-delete-property))
10658 ((equal c ?D)
10659 (call-interactively 'org-delete-property-globally))
10660 ((equal c ?c)
10661 (call-interactively 'org-compute-property-at-point))
10662 (t (error "No such property action %c" c)))))
10664 (defun org-at-property-p ()
10665 "Is the cursor in a property line?"
10666 ;; FIXME: Does not check if we are actually in the drawer.
10667 ;; FIXME: also returns true on any drawers.....
10668 ;; This is used by C-c C-c for property action.
10669 (save-excursion
10670 (beginning-of-line 1)
10671 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10673 (defun org-get-property-block (&optional beg end force)
10674 "Return the (beg . end) range of the body of the property drawer.
10675 BEG and END can be beginning and end of subtree, if not given
10676 they will be found.
10677 If the drawer does not exist and FORCE is non-nil, create the drawer."
10678 (catch 'exit
10679 (save-excursion
10680 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10681 (end (or end (progn (outline-next-heading) (point)))))
10682 (goto-char beg)
10683 (if (re-search-forward org-property-start-re end t)
10684 (setq beg (1+ (match-end 0)))
10685 (if force
10686 (save-excursion
10687 (org-insert-property-drawer)
10688 (setq end (progn (outline-next-heading) (point))))
10689 (throw 'exit nil))
10690 (goto-char beg)
10691 (if (re-search-forward org-property-start-re end t)
10692 (setq beg (1+ (match-end 0)))))
10693 (if (re-search-forward org-property-end-re end t)
10694 (setq end (match-beginning 0))
10695 (or force (throw 'exit nil))
10696 (goto-char beg)
10697 (setq end beg)
10698 (org-indent-line-function)
10699 (insert ":END:\n"))
10700 (cons beg end)))))
10702 (defun org-entry-properties (&optional pom which)
10703 "Get all properties of the entry at point-or-marker POM.
10704 This includes the TODO keyword, the tags, time strings for deadline,
10705 scheduled, and clocking, and any additional properties defined in the
10706 entry. The return value is an alist, keys may occur multiple times
10707 if the property key was used several times.
10708 POM may also be nil, in which case the current entry is used.
10709 If WHICH is nil or `all', get all properties. If WHICH is
10710 `special' or `standard', only get that subclass."
10711 (setq which (or which 'all))
10712 (org-with-point-at pom
10713 (let ((clockstr (substring org-clock-string 0 -1))
10714 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10715 beg end range props sum-props key value string clocksum)
10716 (save-excursion
10717 (when (condition-case nil
10718 (and (org-mode-p) (org-back-to-heading t))
10719 (error nil))
10720 (setq beg (point))
10721 (setq sum-props (get-text-property (point) 'org-summaries))
10722 (setq clocksum (get-text-property (point) :org-clock-minutes))
10723 (outline-next-heading)
10724 (setq end (point))
10725 (when (memq which '(all special))
10726 ;; Get the special properties, like TODO and tags
10727 (goto-char beg)
10728 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10729 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10730 (when (looking-at org-priority-regexp)
10731 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10732 (when (and (setq value (org-get-tags-string))
10733 (string-match "\\S-" value))
10734 (push (cons "TAGS" value) props))
10735 (when (setq value (org-get-tags-at))
10736 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10737 props))
10738 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10739 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10740 string (if (equal key clockstr)
10741 (org-no-properties
10742 (org-trim
10743 (buffer-substring
10744 (match-beginning 3) (goto-char (point-at-eol)))))
10745 (substring (org-match-string-no-properties 3) 1 -1)))
10746 (unless key
10747 (if (= (char-after (match-beginning 3)) ?\[)
10748 (setq key "TIMESTAMP_IA")
10749 (setq key "TIMESTAMP")))
10750 (when (or (equal key clockstr) (not (assoc key props)))
10751 (push (cons key string) props)))
10755 (when (memq which '(all standard))
10756 ;; Get the standard properties, like :PORP: ...
10757 (setq range (org-get-property-block beg end))
10758 (when range
10759 (goto-char (car range))
10760 (while (re-search-forward
10761 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10762 (cdr range) t)
10763 (setq key (org-match-string-no-properties 1)
10764 value (org-trim (or (org-match-string-no-properties 2) "")))
10765 (unless (member key excluded)
10766 (push (cons key (or value "")) props)))))
10767 (if clocksum
10768 (push (cons "CLOCKSUM"
10769 (org-columns-number-to-string (/ (float clocksum) 60.)
10770 'add_times))
10771 props))
10772 (unless (assoc "CATEGORY" props)
10773 (setq value (or (org-get-category)
10774 (progn (org-refresh-category-properties)
10775 (org-get-category))))
10776 (push (cons "CATEGORY" value) props))
10777 (append sum-props (nreverse props)))))))
10779 (defun org-entry-get (pom property &optional inherit)
10780 "Get value of PROPERTY for entry at point-or-marker POM.
10781 If INHERIT is non-nil and the entry does not have the property,
10782 then also check higher levels of the hierarchy.
10783 If INHERIT is the symbol `selective', use inheritance only if the setting
10784 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10785 If the property is present but empty, the return value is the empty string.
10786 If the property is not present at all, nil is returned."
10787 (org-with-point-at pom
10788 (if (and inherit (if (eq inherit 'selective)
10789 (org-property-inherit-p property)
10791 (org-entry-get-with-inheritance property)
10792 (if (member property org-special-properties)
10793 ;; We need a special property. Use brute force, get all properties.
10794 (cdr (assoc property (org-entry-properties nil 'special)))
10795 (let ((range (org-get-property-block)))
10796 (if (and range
10797 (goto-char (car range))
10798 (re-search-forward
10799 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10800 (cdr range) t))
10801 ;; Found the property, return it.
10802 (if (match-end 1)
10803 (org-match-string-no-properties 1)
10804 "")))))))
10806 (defun org-property-or-variable-value (var &optional inherit)
10807 "Check if there is a property fixing the value of VAR.
10808 If yes, return this value. If not, return the current value of the variable."
10809 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10810 (if (and prop (stringp prop) (string-match "\\S-" prop))
10811 (read prop)
10812 (symbol-value var))))
10814 (defun org-entry-delete (pom property)
10815 "Delete the property PROPERTY from entry at point-or-marker POM."
10816 (org-with-point-at pom
10817 (if (member property org-special-properties)
10818 nil ; cannot delete these properties.
10819 (let ((range (org-get-property-block)))
10820 (if (and range
10821 (goto-char (car range))
10822 (re-search-forward
10823 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10824 (cdr range) t))
10825 (progn
10826 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10828 nil)))))
10830 ;; Multi-values properties are properties that contain multiple values
10831 ;; These values are assumed to be single words, separated by whitespace.
10832 (defun org-entry-add-to-multivalued-property (pom property value)
10833 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10834 (let* ((old (org-entry-get pom property))
10835 (values (and old (org-split-string old "[ \t]"))))
10836 (setq value (org-entry-protect-space value))
10837 (unless (member value values)
10838 (setq values (cons value values))
10839 (org-entry-put pom property
10840 (mapconcat 'identity values " ")))))
10842 (defun org-entry-remove-from-multivalued-property (pom property value)
10843 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10844 (let* ((old (org-entry-get pom property))
10845 (values (and old (org-split-string old "[ \t]"))))
10846 (setq value (org-entry-protect-space value))
10847 (when (member value values)
10848 (setq values (delete value values))
10849 (org-entry-put pom property
10850 (mapconcat 'identity values " ")))))
10852 (defun org-entry-member-in-multivalued-property (pom property value)
10853 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10854 (let* ((old (org-entry-get pom property))
10855 (values (and old (org-split-string old "[ \t]"))))
10856 (setq value (org-entry-protect-space value))
10857 (member value values)))
10859 (defun org-entry-get-multivalued-property (pom property)
10860 "Return a list of values in a multivalued property."
10861 (let* ((value (org-entry-get pom property))
10862 (values (and value (org-split-string value "[ \t]"))))
10863 (mapcar 'org-entry-restore-space values)))
10865 (defun org-entry-put-multivalued-property (pom property &rest values)
10866 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10867 VALUES should be a list of strings. Spaces will be protected."
10868 (org-entry-put pom property
10869 (mapconcat 'org-entry-protect-space values " "))
10870 (let* ((value (org-entry-get pom property))
10871 (values (and value (org-split-string value "[ \t]"))))
10872 (mapcar 'org-entry-restore-space values)))
10874 (defun org-entry-protect-space (s)
10875 "Protect spaces and newline in string S."
10876 (while (string-match " " s)
10877 (setq s (replace-match "%20" t t s)))
10878 (while (string-match "\n" s)
10879 (setq s (replace-match "%0A" t t s)))
10882 (defun org-entry-restore-space (s)
10883 "Restore spaces and newline in string S."
10884 (while (string-match "%20" s)
10885 (setq s (replace-match " " t t s)))
10886 (while (string-match "%0A" s)
10887 (setq s (replace-match "\n" t t s)))
10890 (defvar org-entry-property-inherited-from (make-marker)
10891 "Marker pointing to the entry from where a property was inherited.
10892 Each call to `org-entry-get-with-inheritance' will set this marker to the
10893 location of the entry where the inheritance search matched. If there was
10894 no match, the marker will point nowhere.
10895 Note that also `org-entry-get' calls this function, if the INHERIT flag
10896 is set.")
10898 (defun org-entry-get-with-inheritance (property)
10899 "Get entry property, and search higher levels if not present."
10900 (move-marker org-entry-property-inherited-from nil)
10901 (let (tmp)
10902 (save-excursion
10903 (save-restriction
10904 (widen)
10905 (catch 'ex
10906 (while t
10907 (when (setq tmp (org-entry-get nil property))
10908 (org-back-to-heading t)
10909 (move-marker org-entry-property-inherited-from (point))
10910 (throw 'ex tmp))
10911 (or (org-up-heading-safe) (throw 'ex nil)))))
10912 (or tmp
10913 (cdr (assoc property org-file-properties))
10914 (cdr (assoc property org-global-properties))
10915 (cdr (assoc property org-global-properties-fixed))))))
10917 (defun org-entry-put (pom property value)
10918 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10919 (org-with-point-at pom
10920 (org-back-to-heading t)
10921 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10922 range)
10923 (cond
10924 ((equal property "TODO")
10925 (when (and (stringp value) (string-match "\\S-" value)
10926 (not (member value org-todo-keywords-1)))
10927 (error "\"%s\" is not a valid TODO state" value))
10928 (if (or (not value)
10929 (not (string-match "\\S-" value)))
10930 (setq value 'none))
10931 (org-todo value)
10932 (org-set-tags nil 'align))
10933 ((equal property "PRIORITY")
10934 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10935 (string-to-char value) ?\ ))
10936 (org-set-tags nil 'align))
10937 ((equal property "SCHEDULED")
10938 (if (re-search-forward org-scheduled-time-regexp end t)
10939 (cond
10940 ((eq value 'earlier) (org-timestamp-change -1 'day))
10941 ((eq value 'later) (org-timestamp-change 1 'day))
10942 (t (call-interactively 'org-schedule)))
10943 (call-interactively 'org-schedule)))
10944 ((equal property "DEADLINE")
10945 (if (re-search-forward org-deadline-time-regexp end t)
10946 (cond
10947 ((eq value 'earlier) (org-timestamp-change -1 'day))
10948 ((eq value 'later) (org-timestamp-change 1 'day))
10949 (t (call-interactively 'org-deadline)))
10950 (call-interactively 'org-deadline)))
10951 ((member property org-special-properties)
10952 (error "The %s property can not yet be set with `org-entry-put'"
10953 property))
10954 (t ; a non-special property
10955 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10956 (setq range (org-get-property-block beg end 'force))
10957 (goto-char (car range))
10958 (if (re-search-forward
10959 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10960 (progn
10961 (delete-region (match-beginning 1) (match-end 1))
10962 (goto-char (match-beginning 1)))
10963 (goto-char (cdr range))
10964 (insert "\n")
10965 (backward-char 1)
10966 (org-indent-line-function)
10967 (insert ":" property ":"))
10968 (and value (insert " " value))
10969 (org-indent-line-function)))))))
10971 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10972 "Get all property keys in the current buffer.
10973 With INCLUDE-SPECIALS, also list the special properties that reflect things
10974 like tags and TODO state.
10975 With INCLUDE-DEFAULTS, also include properties that has special meaning
10976 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10977 With INCLUDE-COLUMNS, also include property names given in COLUMN
10978 formats in the current buffer."
10979 (let (rtn range cfmt s p)
10980 (save-excursion
10981 (save-restriction
10982 (widen)
10983 (goto-char (point-min))
10984 (while (re-search-forward org-property-start-re nil t)
10985 (setq range (org-get-property-block))
10986 (goto-char (car range))
10987 (while (re-search-forward
10988 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10989 (cdr range) t)
10990 (add-to-list 'rtn (org-match-string-no-properties 1)))
10991 (outline-next-heading))))
10993 (when include-specials
10994 (setq rtn (append org-special-properties rtn)))
10996 (when include-defaults
10997 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10999 (when include-columns
11000 (save-excursion
11001 (save-restriction
11002 (widen)
11003 (goto-char (point-min))
11004 (while (re-search-forward
11005 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11006 nil t)
11007 (setq cfmt (match-string 2) s 0)
11008 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11009 cfmt s)
11010 (setq s (match-end 0)
11011 p (match-string 1 cfmt))
11012 (unless (or (equal p "ITEM")
11013 (member p org-special-properties))
11014 (add-to-list 'rtn (match-string 1 cfmt))))))))
11016 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11018 (defun org-property-values (key)
11019 "Return a list of all values of property KEY."
11020 (save-excursion
11021 (save-restriction
11022 (widen)
11023 (goto-char (point-min))
11024 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11025 values)
11026 (while (re-search-forward re nil t)
11027 (add-to-list 'values (org-trim (match-string 1))))
11028 (delete "" values)))))
11030 (defun org-insert-property-drawer ()
11031 "Insert a property drawer into the current entry."
11032 (interactive)
11033 (org-back-to-heading t)
11034 (looking-at outline-regexp)
11035 (let ((indent (- (match-end 0)(match-beginning 0)))
11036 (beg (point))
11037 (re (concat "^[ \t]*" org-keyword-time-regexp))
11038 end hiddenp)
11039 (outline-next-heading)
11040 (setq end (point))
11041 (goto-char beg)
11042 (while (re-search-forward re end t))
11043 (setq hiddenp (org-invisible-p))
11044 (end-of-line 1)
11045 (and (equal (char-after) ?\n) (forward-char 1))
11046 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11047 (if (member (match-string 1) '("CLOCK:" ":END:"))
11048 ;; just skip this line
11049 (beginning-of-line 2)
11050 ;; Drawer start, find the end
11051 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11052 (beginning-of-line 1)))
11053 (org-skip-over-state-notes)
11054 (skip-chars-backward " \t\n\r")
11055 (if (eq (char-before) ?*) (forward-char 1))
11056 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11057 (beginning-of-line 0)
11058 (org-indent-to-column indent)
11059 (beginning-of-line 2)
11060 (org-indent-to-column indent)
11061 (beginning-of-line 0)
11062 (if hiddenp
11063 (save-excursion
11064 (org-back-to-heading t)
11065 (hide-entry))
11066 (org-flag-drawer t))))
11068 (defun org-set-property (property value)
11069 "In the current entry, set PROPERTY to VALUE.
11070 When called interactively, this will prompt for a property name, offering
11071 completion on existing and default properties. And then it will prompt
11072 for a value, offering completion either on allowed values (via an inherited
11073 xxx_ALL property) or on existing values in other instances of this property
11074 in the current file."
11075 (interactive
11076 (let* ((completion-ignore-case t)
11077 (keys (org-buffer-property-keys nil t t))
11078 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11079 (prop (if (member prop0 keys)
11080 prop0
11081 (or (cdr (assoc (downcase prop0)
11082 (mapcar (lambda (x) (cons (downcase x) x))
11083 keys)))
11084 prop0)))
11085 (cur (org-entry-get nil prop))
11086 (allowed (org-property-get-allowed-values nil prop 'table))
11087 (existing (mapcar 'list (org-property-values prop)))
11088 (val (if allowed
11089 (org-completing-read "Value: " allowed nil 'req-match)
11090 (let (org-completion-use-ido)
11091 (org-completing-read
11092 (concat "Value" (if (and cur (string-match "\\S-" cur))
11093 (concat "[" cur "]") "")
11094 ": ")
11095 existing nil nil "" nil cur)))))
11096 (list prop (if (equal val "") cur val))))
11097 (unless (equal (org-entry-get nil property) value)
11098 (org-entry-put nil property value)))
11100 (defun org-delete-property (property)
11101 "In the current entry, delete PROPERTY."
11102 (interactive
11103 (let* ((completion-ignore-case t)
11104 (prop (org-ido-completing-read
11105 "Property: " (org-entry-properties nil 'standard))))
11106 (list prop)))
11107 (message "Property %s %s" property
11108 (if (org-entry-delete nil property)
11109 "deleted"
11110 "was not present in the entry")))
11112 (defun org-delete-property-globally (property)
11113 "Remove PROPERTY globally, from all entries."
11114 (interactive
11115 (let* ((completion-ignore-case t)
11116 (prop (org-ido-completing-read
11117 "Globally remove property: "
11118 (mapcar 'list (org-buffer-property-keys)))))
11119 (list prop)))
11120 (save-excursion
11121 (save-restriction
11122 (widen)
11123 (goto-char (point-min))
11124 (let ((cnt 0))
11125 (while (re-search-forward
11126 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11127 nil t)
11128 (setq cnt (1+ cnt))
11129 (replace-match ""))
11130 (message "Property \"%s\" removed from %d entries" property cnt)))))
11132 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11134 (defun org-compute-property-at-point ()
11135 "Compute the property at point.
11136 This looks for an enclosing column format, extracts the operator and
11137 then applies it to the property in the column format's scope."
11138 (interactive)
11139 (unless (org-at-property-p)
11140 (error "Not at a property"))
11141 (let ((prop (org-match-string-no-properties 2)))
11142 (org-columns-get-format-and-top-level)
11143 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11144 (error "No operator defined for property %s" prop))
11145 (org-columns-compute prop)))
11147 (defun org-property-get-allowed-values (pom property &optional table)
11148 "Get allowed values for the property PROPERTY.
11149 When TABLE is non-nil, return an alist that can directly be used for
11150 completion."
11151 (let (vals)
11152 (cond
11153 ((equal property "TODO")
11154 (setq vals (org-with-point-at pom
11155 (append org-todo-keywords-1 '("")))))
11156 ((equal property "PRIORITY")
11157 (let ((n org-lowest-priority))
11158 (while (>= n org-highest-priority)
11159 (push (char-to-string n) vals)
11160 (setq n (1- n)))))
11161 ((member property org-special-properties))
11163 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11165 (when (and vals (string-match "\\S-" vals))
11166 (setq vals (car (read-from-string (concat "(" vals ")"))))
11167 (setq vals (mapcar (lambda (x)
11168 (cond ((stringp x) x)
11169 ((numberp x) (number-to-string x))
11170 ((symbolp x) (symbol-name x))
11171 (t "???")))
11172 vals)))))
11173 (if table (mapcar 'list vals) vals)))
11175 (defun org-property-previous-allowed-value (&optional previous)
11176 "Switch to the next allowed value for this property."
11177 (interactive)
11178 (org-property-next-allowed-value t))
11180 (defun org-property-next-allowed-value (&optional previous)
11181 "Switch to the next allowed value for this property."
11182 (interactive)
11183 (unless (org-at-property-p)
11184 (error "Not at a property"))
11185 (let* ((key (match-string 2))
11186 (value (match-string 3))
11187 (allowed (or (org-property-get-allowed-values (point) key)
11188 (and (member value '("[ ]" "[-]" "[X]"))
11189 '("[ ]" "[X]"))))
11190 nval)
11191 (unless allowed
11192 (error "Allowed values for this property have not been defined"))
11193 (if previous (setq allowed (reverse allowed)))
11194 (if (member value allowed)
11195 (setq nval (car (cdr (member value allowed)))))
11196 (setq nval (or nval (car allowed)))
11197 (if (equal nval value)
11198 (error "Only one allowed value for this property"))
11199 (org-at-property-p)
11200 (replace-match (concat " :" key ": " nval) t t)
11201 (org-indent-line-function)
11202 (beginning-of-line 1)
11203 (skip-chars-forward " \t")))
11205 (defun org-find-entry-with-id (ident)
11206 "Locate the entry that contains the ID property with exact value IDENT.
11207 IDENT can be a string, a symbol or a number, this function will search for
11208 the string representation of it.
11209 Return the position where this entry starts, or nil if there is no such entry."
11210 (interactive "sID: ")
11211 (let ((id (cond
11212 ((stringp ident) ident)
11213 ((symbol-name ident) (symbol-name ident))
11214 ((numberp ident) (number-to-string ident))
11215 (t (error "IDENT %s must be a string, symbol or number" ident))))
11216 (case-fold-search nil))
11217 (save-excursion
11218 (save-restriction
11219 (widen)
11220 (goto-char (point-min))
11221 (when (re-search-forward
11222 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11223 nil t)
11224 (org-back-to-heading)
11225 (point))))))
11227 ;;;; Timestamps
11229 (defvar org-last-changed-timestamp nil)
11230 (defvar org-last-inserted-timestamp nil
11231 "The last time stamp inserted with `org-insert-time-stamp'.")
11232 (defvar org-time-was-given) ; dynamically scoped parameter
11233 (defvar org-end-time-was-given) ; dynamically scoped parameter
11234 (defvar org-ts-what) ; dynamically scoped parameter
11236 (defun org-time-stamp (arg &optional inactive)
11237 "Prompt for a date/time and insert a time stamp.
11238 If the user specifies a time like HH:MM, or if this command is called
11239 with a prefix argument, the time stamp will contain date and time.
11240 Otherwise, only the date will be included. All parts of a date not
11241 specified by the user will be filled in from the current date/time.
11242 So if you press just return without typing anything, the time stamp
11243 will represent the current date/time. If there is already a timestamp
11244 at the cursor, it will be modified."
11245 (interactive "P")
11246 (let* ((ts nil)
11247 (default-time
11248 ;; Default time is either today, or, when entering a range,
11249 ;; the range start.
11250 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11251 (save-excursion
11252 (re-search-backward
11253 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11254 (- (point) 20) t)))
11255 (apply 'encode-time (org-parse-time-string (match-string 1)))
11256 (current-time)))
11257 (default-input (and ts (org-get-compact-tod ts)))
11258 org-time-was-given org-end-time-was-given time)
11259 (cond
11260 ((and (org-at-timestamp-p t)
11261 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11262 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11263 (insert "--")
11264 (setq time (let ((this-command this-command))
11265 (org-read-date arg 'totime nil nil
11266 default-time default-input)))
11267 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11268 ((org-at-timestamp-p t)
11269 (setq time (let ((this-command this-command))
11270 (org-read-date arg 'totime nil nil default-time default-input)))
11271 (when (org-at-timestamp-p t) ; just to get the match data
11272 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11273 (replace-match "")
11274 (setq org-last-changed-timestamp
11275 (org-insert-time-stamp
11276 time (or org-time-was-given arg)
11277 inactive nil nil (list org-end-time-was-given))))
11278 (message "Timestamp updated"))
11280 (setq time (let ((this-command this-command))
11281 (org-read-date arg 'totime nil nil default-time default-input)))
11282 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11283 nil nil (list org-end-time-was-given))))))
11285 ;; FIXME: can we use this for something else, like computing time differences?
11286 (defun org-get-compact-tod (s)
11287 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11288 (let* ((t1 (match-string 1 s))
11289 (h1 (string-to-number (match-string 2 s)))
11290 (m1 (string-to-number (match-string 3 s)))
11291 (t2 (and (match-end 4) (match-string 5 s)))
11292 (h2 (and t2 (string-to-number (match-string 6 s))))
11293 (m2 (and t2 (string-to-number (match-string 7 s))))
11294 dh dm)
11295 (if (not t2)
11297 (setq dh (- h2 h1) dm (- m2 m1))
11298 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11299 (concat t1 "+" (number-to-string dh)
11300 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11302 (defun org-time-stamp-inactive (&optional arg)
11303 "Insert an inactive time stamp.
11304 An inactive time stamp is enclosed in square brackets instead of angle
11305 brackets. It is inactive in the sense that it does not trigger agenda entries,
11306 does not link to the calendar and cannot be changed with the S-cursor keys.
11307 So these are more for recording a certain time/date."
11308 (interactive "P")
11309 (org-time-stamp arg 'inactive))
11311 (defvar org-date-ovl (org-make-overlay 1 1))
11312 (org-overlay-put org-date-ovl 'face 'org-warning)
11313 (org-detach-overlay org-date-ovl)
11315 (defvar org-ans1) ; dynamically scoped parameter
11316 (defvar org-ans2) ; dynamically scoped parameter
11318 (defvar org-plain-time-of-day-regexp) ; defined below
11320 (defvar org-overriding-default-time nil) ; dynamically scoped
11321 (defvar org-read-date-overlay nil)
11322 (defvar org-dcst nil) ; dynamically scoped
11324 (defun org-read-date (&optional with-time to-time from-string prompt
11325 default-time default-input)
11326 "Read a date, possibly a time, and make things smooth for the user.
11327 The prompt will suggest to enter an ISO date, but you can also enter anything
11328 which will at least partially be understood by `parse-time-string'.
11329 Unrecognized parts of the date will default to the current day, month, year,
11330 hour and minute. If this command is called to replace a timestamp at point,
11331 of to enter the second timestamp of a range, the default time is taken from the
11332 existing stamp. For example,
11333 3-2-5 --> 2003-02-05
11334 feb 15 --> currentyear-02-15
11335 sep 12 9 --> 2009-09-12
11336 12:45 --> today 12:45
11337 22 sept 0:34 --> currentyear-09-22 0:34
11338 12 --> currentyear-currentmonth-12
11339 Fri --> nearest Friday (today or later)
11340 etc.
11342 Furthermore you can specify a relative date by giving, as the *first* thing
11343 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11344 change in days weeks, months, years.
11345 With a single plus or minus, the date is relative to today. With a double
11346 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11347 +4d --> four days from today
11348 +4 --> same as above
11349 +2w --> two weeks from today
11350 ++5 --> five days from default date
11352 The function understands only English month and weekday abbreviations,
11353 but this can be configured with the variables `parse-time-months' and
11354 `parse-time-weekdays'.
11356 While prompting, a calendar is popped up - you can also select the
11357 date with the mouse (button 1). The calendar shows a period of three
11358 months. To scroll it to other months, use the keys `>' and `<'.
11359 If you don't like the calendar, turn it off with
11360 \(setq org-read-date-popup-calendar nil)
11362 With optional argument TO-TIME, the date will immediately be converted
11363 to an internal time.
11364 With an optional argument WITH-TIME, the prompt will suggest to also
11365 insert a time. Note that when WITH-TIME is not set, you can still
11366 enter a time, and this function will inform the calling routine about
11367 this change. The calling routine may then choose to change the format
11368 used to insert the time stamp into the buffer to include the time.
11369 With optional argument FROM-STRING, read from this string instead from
11370 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11371 the time/date that is used for everything that is not specified by the
11372 user."
11373 (require 'parse-time)
11374 (let* ((org-time-stamp-rounding-minutes
11375 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11376 (org-dcst org-display-custom-times)
11377 (ct (org-current-time))
11378 (def (or org-overriding-default-time default-time ct))
11379 (defdecode (decode-time def))
11380 (dummy (progn
11381 (when (< (nth 2 defdecode) org-extend-today-until)
11382 (setcar (nthcdr 2 defdecode) -1)
11383 (setcar (nthcdr 1 defdecode) 59)
11384 (setq def (apply 'encode-time defdecode)
11385 defdecode (decode-time def)))))
11386 (calendar-move-hook nil)
11387 (calendar-view-diary-initially-flag nil)
11388 (view-diary-entries-initially nil)
11389 (calendar-view-holidays-initially-flag nil)
11390 (view-calendar-holidays-initially nil)
11391 (timestr (format-time-string
11392 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11393 (prompt (concat (if prompt (concat prompt " ") "")
11394 (format "Date+time [%s]: " timestr)))
11395 ans (org-ans0 "") org-ans1 org-ans2 final)
11397 (cond
11398 (from-string (setq ans from-string))
11399 (org-read-date-popup-calendar
11400 (save-excursion
11401 (save-window-excursion
11402 (calendar)
11403 (calendar-forward-day (- (time-to-days def)
11404 (calendar-absolute-from-gregorian
11405 (calendar-current-date))))
11406 (org-eval-in-calendar nil t)
11407 (let* ((old-map (current-local-map))
11408 (map (copy-keymap calendar-mode-map))
11409 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11410 (org-defkey map (kbd "RET") 'org-calendar-select)
11411 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11412 'org-calendar-select-mouse)
11413 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11414 'org-calendar-select-mouse)
11415 (org-defkey minibuffer-local-map [(meta shift left)]
11416 (lambda () (interactive)
11417 (org-eval-in-calendar '(calendar-backward-month 1))))
11418 (org-defkey minibuffer-local-map [(meta shift right)]
11419 (lambda () (interactive)
11420 (org-eval-in-calendar '(calendar-forward-month 1))))
11421 (org-defkey minibuffer-local-map [(meta shift up)]
11422 (lambda () (interactive)
11423 (org-eval-in-calendar '(calendar-backward-year 1))))
11424 (org-defkey minibuffer-local-map [(meta shift down)]
11425 (lambda () (interactive)
11426 (org-eval-in-calendar '(calendar-forward-year 1))))
11427 (org-defkey minibuffer-local-map [(shift up)]
11428 (lambda () (interactive)
11429 (org-eval-in-calendar '(calendar-backward-week 1))))
11430 (org-defkey minibuffer-local-map [(shift down)]
11431 (lambda () (interactive)
11432 (org-eval-in-calendar '(calendar-forward-week 1))))
11433 (org-defkey minibuffer-local-map [(shift left)]
11434 (lambda () (interactive)
11435 (org-eval-in-calendar '(calendar-backward-day 1))))
11436 (org-defkey minibuffer-local-map [(shift right)]
11437 (lambda () (interactive)
11438 (org-eval-in-calendar '(calendar-forward-day 1))))
11439 (org-defkey minibuffer-local-map ">"
11440 (lambda () (interactive)
11441 (org-eval-in-calendar '(scroll-calendar-left 1))))
11442 (org-defkey minibuffer-local-map "<"
11443 (lambda () (interactive)
11444 (org-eval-in-calendar '(scroll-calendar-right 1))))
11445 (unwind-protect
11446 (progn
11447 (use-local-map map)
11448 (add-hook 'post-command-hook 'org-read-date-display)
11449 (setq org-ans0 (read-string prompt default-input nil nil))
11450 ;; org-ans0: from prompt
11451 ;; org-ans1: from mouse click
11452 ;; org-ans2: from calendar motion
11453 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11454 (remove-hook 'post-command-hook 'org-read-date-display)
11455 (use-local-map old-map)
11456 (when org-read-date-overlay
11457 (org-delete-overlay org-read-date-overlay)
11458 (setq org-read-date-overlay nil)))))))
11460 (t ; Naked prompt only
11461 (unwind-protect
11462 (setq ans (read-string prompt default-input nil timestr))
11463 (when org-read-date-overlay
11464 (org-delete-overlay org-read-date-overlay)
11465 (setq org-read-date-overlay nil)))))
11467 (setq final (org-read-date-analyze ans def defdecode))
11469 (if to-time
11470 (apply 'encode-time final)
11471 (if (and (boundp 'org-time-was-given) org-time-was-given)
11472 (format "%04d-%02d-%02d %02d:%02d"
11473 (nth 5 final) (nth 4 final) (nth 3 final)
11474 (nth 2 final) (nth 1 final))
11475 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11476 (defvar def)
11477 (defvar defdecode)
11478 (defvar with-time)
11479 (defun org-read-date-display ()
11480 "Display the current date prompt interpretation in the minibuffer."
11481 (when org-read-date-display-live
11482 (when org-read-date-overlay
11483 (org-delete-overlay org-read-date-overlay))
11484 (let ((p (point)))
11485 (end-of-line 1)
11486 (while (not (equal (buffer-substring
11487 (max (point-min) (- (point) 4)) (point))
11488 " "))
11489 (insert " "))
11490 (goto-char p))
11491 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11492 " " (or org-ans1 org-ans2)))
11493 (org-end-time-was-given nil)
11494 (f (org-read-date-analyze ans def defdecode))
11495 (fmts (if org-dcst
11496 org-time-stamp-custom-formats
11497 org-time-stamp-formats))
11498 (fmt (if (or with-time
11499 (and (boundp 'org-time-was-given) org-time-was-given))
11500 (cdr fmts)
11501 (car fmts)))
11502 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11503 (when (and org-end-time-was-given
11504 (string-match org-plain-time-of-day-regexp txt))
11505 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11506 org-end-time-was-given
11507 (substring txt (match-end 0)))))
11508 (setq org-read-date-overlay
11509 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11510 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11512 (defun org-read-date-analyze (ans def defdecode)
11513 "Analyse the combined answer of the date prompt."
11514 ;; FIXME: cleanup and comment
11515 (let (delta deltan deltaw deltadef year month day
11516 hour minute second wday pm h2 m2 tl wday1
11517 iso-year iso-weekday iso-week iso-year iso-date)
11519 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11520 (setq ans "+0"))
11522 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11523 (setq ans (replace-match "" t t ans)
11524 deltan (car delta)
11525 deltaw (nth 1 delta)
11526 deltadef (nth 2 delta)))
11528 ;; Check if there is an iso week date in there
11529 ;; If yes, sore the info and postpone interpreting it until the rest
11530 ;; of the parsing is done
11531 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11532 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11533 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11534 iso-week (string-to-number (match-string 2 ans)))
11535 (setq ans (replace-match "" t t ans)))
11537 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11538 (when (string-match
11539 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11540 (setq year (if (match-end 2)
11541 (string-to-number (match-string 2 ans))
11542 (string-to-number (format-time-string "%Y")))
11543 month (string-to-number (match-string 3 ans))
11544 day (string-to-number (match-string 4 ans)))
11545 (if (< year 100) (setq year (+ 2000 year)))
11546 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11547 t nil ans)))
11548 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11549 ;; If there is a time with am/pm, and *no* time without it, we convert
11550 ;; so that matching will be successful.
11551 (loop for i from 1 to 2 do ; twice, for end time as well
11552 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11553 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11554 (setq hour (string-to-number (match-string 1 ans))
11555 minute (if (match-end 3)
11556 (string-to-number (match-string 3 ans))
11558 pm (equal ?p
11559 (string-to-char (downcase (match-string 4 ans)))))
11560 (if (and (= hour 12) (not pm))
11561 (setq hour 0)
11562 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11563 (setq ans (replace-match (format "%02d:%02d" hour minute)
11564 t t ans))))
11566 ;; Check if a time range is given as a duration
11567 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11568 (setq hour (string-to-number (match-string 1 ans))
11569 h2 (+ hour (string-to-number (match-string 3 ans)))
11570 minute (string-to-number (match-string 2 ans))
11571 m2 (+ minute (if (match-end 5) (string-to-number
11572 (match-string 5 ans))0)))
11573 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11574 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11575 t t ans)))
11577 ;; Check if there is a time range
11578 (when (boundp 'org-end-time-was-given)
11579 (setq org-time-was-given nil)
11580 (when (and (string-match org-plain-time-of-day-regexp ans)
11581 (match-end 8))
11582 (setq org-end-time-was-given (match-string 8 ans))
11583 (setq ans (concat (substring ans 0 (match-beginning 7))
11584 (substring ans (match-end 7))))))
11586 (setq tl (parse-time-string ans)
11587 day (or (nth 3 tl) (nth 3 defdecode))
11588 month (or (nth 4 tl)
11589 (if (and org-read-date-prefer-future
11590 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11591 (1+ (nth 4 defdecode))
11592 (nth 4 defdecode)))
11593 year (or (nth 5 tl)
11594 (if (and org-read-date-prefer-future
11595 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11596 (1+ (nth 5 defdecode))
11597 (nth 5 defdecode)))
11598 hour (or (nth 2 tl) (nth 2 defdecode))
11599 minute (or (nth 1 tl) (nth 1 defdecode))
11600 second (or (nth 0 tl) 0)
11601 wday (nth 6 tl))
11603 ;; Special date definitions below
11604 (cond
11605 (iso-week
11606 ;; There was an iso week
11607 (setq year (or iso-year year)
11608 day (or iso-weekday wday 1)
11609 wday nil ; to make sure that the trigger below does not match
11610 iso-date (calendar-gregorian-from-absolute
11611 (calendar-absolute-from-iso
11612 (list iso-week day year))))
11613 ; FIXME: Should we also push ISO weeks into the future?
11614 ; (when (and org-read-date-prefer-future
11615 ; (not iso-year)
11616 ; (< (calendar-absolute-from-gregorian iso-date)
11617 ; (time-to-days (current-time))))
11618 ; (setq year (1+ year)
11619 ; iso-date (calendar-gregorian-from-absolute
11620 ; (calendar-absolute-from-iso
11621 ; (list iso-week day year)))))
11622 (setq month (car iso-date)
11623 year (nth 2 iso-date)
11624 day (nth 1 iso-date)))
11625 (deltan
11626 (unless deltadef
11627 (let ((now (decode-time (current-time))))
11628 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11629 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11630 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11631 ((equal deltaw "m") (setq month (+ month deltan)))
11632 ((equal deltaw "y") (setq year (+ year deltan)))))
11633 ((and wday (not (nth 3 tl)))
11634 ;; Weekday was given, but no day, so pick that day in the week
11635 ;; on or after the derived date.
11636 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11637 (unless (equal wday wday1)
11638 (setq day (+ day (% (- wday wday1 -7) 7))))))
11639 (if (and (boundp 'org-time-was-given)
11640 (nth 2 tl))
11641 (setq org-time-was-given t))
11642 (if (< year 100) (setq year (+ 2000 year)))
11643 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11644 (list second minute hour day month year)))
11646 (defvar parse-time-weekdays)
11648 (defun org-read-date-get-relative (s today default)
11649 "Check string S for special relative date string.
11650 TODAY and DEFAULT are internal times, for today and for a default.
11651 Return shift list (N what def-flag)
11652 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11653 N is the number of WHATs to shift.
11654 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11655 the DEFAULT date rather than TODAY."
11656 (when (and
11657 (string-match
11658 (concat
11659 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11660 "\\([0-9]+\\)?"
11661 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11662 "\\([ \t]\\|$\\)") s)
11663 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11664 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11665 (string-to-char (substring (match-string 1 s) -1))
11666 ?+))
11667 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11668 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11669 (what (if (match-end 3) (match-string 3 s) "d"))
11670 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11671 (date (if rel default today))
11672 (wday (nth 6 (decode-time date)))
11673 delta)
11674 (if wday1
11675 (progn
11676 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11677 (if (= dir ?-) (setq delta (- delta 7)))
11678 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11679 (list delta "d" rel))
11680 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11682 (defun org-eval-in-calendar (form &optional keepdate)
11683 "Eval FORM in the calendar window and return to current window.
11684 Also, store the cursor date in variable org-ans2."
11685 (let ((sw (selected-window)))
11686 (select-window (get-buffer-window "*Calendar*"))
11687 (eval form)
11688 (when (and (not keepdate) (calendar-cursor-to-date))
11689 (let* ((date (calendar-cursor-to-date))
11690 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11691 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11692 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11693 (select-window sw)))
11695 (defun org-calendar-select ()
11696 "Return to `org-read-date' with the date currently selected.
11697 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11698 (interactive)
11699 (when (calendar-cursor-to-date)
11700 (let* ((date (calendar-cursor-to-date))
11701 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11702 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11703 (if (active-minibuffer-window) (exit-minibuffer))))
11705 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11706 "Insert a date stamp for the date given by the internal TIME.
11707 WITH-HM means, use the stamp format that includes the time of the day.
11708 INACTIVE means use square brackets instead of angular ones, so that the
11709 stamp will not contribute to the agenda.
11710 PRE and POST are optional strings to be inserted before and after the
11711 stamp.
11712 The command returns the inserted time stamp."
11713 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11714 stamp)
11715 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11716 (insert-before-markers (or pre ""))
11717 (insert-before-markers (setq stamp (format-time-string fmt time)))
11718 (when (listp extra)
11719 (setq extra (car extra))
11720 (if (and (stringp extra)
11721 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11722 (setq extra (format "-%02d:%02d"
11723 (string-to-number (match-string 1 extra))
11724 (string-to-number (match-string 2 extra))))
11725 (setq extra nil)))
11726 (when extra
11727 (backward-char 1)
11728 (insert-before-markers extra)
11729 (forward-char 1))
11730 (insert-before-markers (or post ""))
11731 (setq org-last-inserted-timestamp stamp)))
11733 (defun org-toggle-time-stamp-overlays ()
11734 "Toggle the use of custom time stamp formats."
11735 (interactive)
11736 (setq org-display-custom-times (not org-display-custom-times))
11737 (unless org-display-custom-times
11738 (let ((p (point-min)) (bmp (buffer-modified-p)))
11739 (while (setq p (next-single-property-change p 'display))
11740 (if (and (get-text-property p 'display)
11741 (eq (get-text-property p 'face) 'org-date))
11742 (remove-text-properties
11743 p (setq p (next-single-property-change p 'display))
11744 '(display t))))
11745 (set-buffer-modified-p bmp)))
11746 (if (featurep 'xemacs)
11747 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11748 (org-restart-font-lock)
11749 (setq org-table-may-need-update t)
11750 (if org-display-custom-times
11751 (message "Time stamps are overlayed with custom format")
11752 (message "Time stamp overlays removed")))
11754 (defun org-display-custom-time (beg end)
11755 "Overlay modified time stamp format over timestamp between BEG and END."
11756 (let* ((ts (buffer-substring beg end))
11757 t1 w1 with-hm tf time str w2 (off 0))
11758 (save-match-data
11759 (setq t1 (org-parse-time-string ts t))
11760 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11761 (setq off (- (match-end 0) (match-beginning 0)))))
11762 (setq end (- end off))
11763 (setq w1 (- end beg)
11764 with-hm (and (nth 1 t1) (nth 2 t1))
11765 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11766 time (org-fix-decoded-time t1)
11767 str (org-add-props
11768 (format-time-string
11769 (substring tf 1 -1) (apply 'encode-time time))
11770 nil 'mouse-face 'highlight)
11771 w2 (length str))
11772 (if (not (= w2 w1))
11773 (add-text-properties (1+ beg) (+ 2 beg)
11774 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11775 (if (featurep 'xemacs)
11776 (progn
11777 (put-text-property beg end 'invisible t)
11778 (put-text-property beg end 'end-glyph (make-glyph str)))
11779 (put-text-property beg end 'display str))))
11781 (defun org-translate-time (string)
11782 "Translate all timestamps in STRING to custom format.
11783 But do this only if the variable `org-display-custom-times' is set."
11784 (when org-display-custom-times
11785 (save-match-data
11786 (let* ((start 0)
11787 (re org-ts-regexp-both)
11788 t1 with-hm inactive tf time str beg end)
11789 (while (setq start (string-match re string start))
11790 (setq beg (match-beginning 0)
11791 end (match-end 0)
11792 t1 (save-match-data
11793 (org-parse-time-string (substring string beg end) t))
11794 with-hm (and (nth 1 t1) (nth 2 t1))
11795 inactive (equal (substring string beg (1+ beg)) "[")
11796 tf (funcall (if with-hm 'cdr 'car)
11797 org-time-stamp-custom-formats)
11798 time (org-fix-decoded-time t1)
11799 str (format-time-string
11800 (concat
11801 (if inactive "[" "<") (substring tf 1 -1)
11802 (if inactive "]" ">"))
11803 (apply 'encode-time time))
11804 string (replace-match str t t string)
11805 start (+ start (length str)))))))
11806 string)
11808 (defun org-fix-decoded-time (time)
11809 "Set 0 instead of nil for the first 6 elements of time.
11810 Don't touch the rest."
11811 (let ((n 0))
11812 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11814 (defun org-days-to-time (timestamp-string)
11815 "Difference between TIMESTAMP-STRING and now in days."
11816 (- (time-to-days (org-time-string-to-time timestamp-string))
11817 (time-to-days (current-time))))
11819 (defun org-deadline-close (timestamp-string &optional ndays)
11820 "Is the time in TIMESTAMP-STRING close to the current date?"
11821 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11822 (and (< (org-days-to-time timestamp-string) ndays)
11823 (not (org-entry-is-done-p))))
11825 (defun org-get-wdays (ts)
11826 "Get the deadline lead time appropriate for timestring TS."
11827 (cond
11828 ((<= org-deadline-warning-days 0)
11829 ;; 0 or negative, enforce this value no matter what
11830 (- org-deadline-warning-days))
11831 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
11832 ;; lead time is specified.
11833 (floor (* (string-to-number (match-string 1 ts))
11834 (cdr (assoc (match-string 2 ts)
11835 '(("d" . 1) ("w" . 7)
11836 ("m" . 30.4) ("y" . 365.25)))))))
11837 ;; go for the default.
11838 (t org-deadline-warning-days)))
11840 (defun org-calendar-select-mouse (ev)
11841 "Return to `org-read-date' with the date currently selected.
11842 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11843 (interactive "e")
11844 (mouse-set-point ev)
11845 (when (calendar-cursor-to-date)
11846 (let* ((date (calendar-cursor-to-date))
11847 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11848 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11849 (if (active-minibuffer-window) (exit-minibuffer))))
11851 (defun org-check-deadlines (ndays)
11852 "Check if there are any deadlines due or past due.
11853 A deadline is considered due if it happens within `org-deadline-warning-days'
11854 days from today's date. If the deadline appears in an entry marked DONE,
11855 it is not shown. The prefix arg NDAYS can be used to test that many
11856 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11857 (interactive "P")
11858 (let* ((org-warn-days
11859 (cond
11860 ((equal ndays '(4)) 100000)
11861 (ndays (prefix-numeric-value ndays))
11862 (t (abs org-deadline-warning-days))))
11863 (case-fold-search nil)
11864 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11865 (callback
11866 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11868 (message "%d deadlines past-due or due within %d days"
11869 (org-occur regexp nil callback)
11870 org-warn-days)))
11872 (defun org-check-before-date (date)
11873 "Check if there are deadlines or scheduled entries before DATE."
11874 (interactive (list (org-read-date)))
11875 (let ((case-fold-search nil)
11876 (regexp (concat "\\<\\(" org-deadline-string
11877 "\\|" org-scheduled-string
11878 "\\) *<\\([^>]+\\)>"))
11879 (callback
11880 (lambda () (time-less-p
11881 (org-time-string-to-time (match-string 2))
11882 (org-time-string-to-time date)))))
11883 (message "%d entries before %s"
11884 (org-occur regexp nil callback) date)))
11886 (defun org-evaluate-time-range (&optional to-buffer)
11887 "Evaluate a time range by computing the difference between start and end.
11888 Normally the result is just printed in the echo area, but with prefix arg
11889 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11890 If the time range is actually in a table, the result is inserted into the
11891 next column.
11892 For time difference computation, a year is assumed to be exactly 365
11893 days in order to avoid rounding problems."
11894 (interactive "P")
11896 (org-clock-update-time-maybe)
11897 (save-excursion
11898 (unless (org-at-date-range-p t)
11899 (goto-char (point-at-bol))
11900 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11901 (if (not (org-at-date-range-p t))
11902 (error "Not at a time-stamp range, and none found in current line")))
11903 (let* ((ts1 (match-string 1))
11904 (ts2 (match-string 2))
11905 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11906 (match-end (match-end 0))
11907 (time1 (org-time-string-to-time ts1))
11908 (time2 (org-time-string-to-time ts2))
11909 (t1 (time-to-seconds time1))
11910 (t2 (time-to-seconds time2))
11911 (diff (abs (- t2 t1)))
11912 (negative (< (- t2 t1) 0))
11913 ;; (ys (floor (* 365 24 60 60)))
11914 (ds (* 24 60 60))
11915 (hs (* 60 60))
11916 (fy "%dy %dd %02d:%02d")
11917 (fy1 "%dy %dd")
11918 (fd "%dd %02d:%02d")
11919 (fd1 "%dd")
11920 (fh "%02d:%02d")
11921 y d h m align)
11922 (if havetime
11923 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11925 d (floor (/ diff ds)) diff (mod diff ds)
11926 h (floor (/ diff hs)) diff (mod diff hs)
11927 m (floor (/ diff 60)))
11928 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11930 d (floor (+ (/ diff ds) 0.5))
11931 h 0 m 0))
11932 (if (not to-buffer)
11933 (message "%s" (org-make-tdiff-string y d h m))
11934 (if (org-at-table-p)
11935 (progn
11936 (goto-char match-end)
11937 (setq align t)
11938 (and (looking-at " *|") (goto-char (match-end 0))))
11939 (goto-char match-end))
11940 (if (looking-at
11941 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11942 (replace-match ""))
11943 (if negative (insert " -"))
11944 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11945 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11946 (insert " " (format fh h m))))
11947 (if align (org-table-align))
11948 (message "Time difference inserted")))))
11950 (defun org-make-tdiff-string (y d h m)
11951 (let ((fmt "")
11952 (l nil))
11953 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11954 l (push y l)))
11955 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11956 l (push d l)))
11957 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11958 l (push h l)))
11959 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11960 l (push m l)))
11961 (apply 'format fmt (nreverse l))))
11963 (defun org-time-string-to-time (s)
11964 (apply 'encode-time (org-parse-time-string s)))
11966 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11967 "Convert a time stamp to an absolute day number.
11968 If there is a specifyer for a cyclic time stamp, get the closest date to
11969 DAYNR.
11970 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11971 (cond
11972 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11973 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11974 daynr
11975 (+ daynr 1000)))
11976 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11977 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11978 (time-to-days (current-time))) (match-string 0 s)
11979 prefer show-all))
11980 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11982 (defun org-days-to-iso-week (days)
11983 "Return the iso week number."
11984 (require 'cal-iso)
11985 (car (calendar-iso-from-absolute days)))
11987 (defun org-small-year-to-year (year)
11988 "Convert 2-digit years into 4-digit years.
11989 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11990 The year 2000 cannot be abbreviated. Any year larger than 99
11991 is returned unchanged."
11992 (if (< year 38)
11993 (setq year (+ 2000 year))
11994 (if (< year 100)
11995 (setq year (+ 1900 year))))
11996 year)
11998 (defun org-time-from-absolute (d)
11999 "Return the time corresponding to date D.
12000 D may be an absolute day number, or a calendar-type list (month day year)."
12001 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12002 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12004 (defun org-calendar-holiday ()
12005 "List of holidays, for Diary display in Org-mode."
12006 (require 'holidays)
12007 (let ((hl (funcall
12008 (if (fboundp 'calendar-check-holidays)
12009 'calendar-check-holidays 'check-calendar-holidays) date)))
12010 (if hl (mapconcat 'identity hl "; "))))
12012 (defun org-diary-sexp-entry (sexp entry date)
12013 "Process a SEXP diary ENTRY for DATE."
12014 (require 'diary-lib)
12015 (let ((result (if calendar-debug-sexp
12016 (let ((stack-trace-on-error t))
12017 (eval (car (read-from-string sexp))))
12018 (condition-case nil
12019 (eval (car (read-from-string sexp)))
12020 (error
12021 (beep)
12022 (message "Bad sexp at line %d in %s: %s"
12023 (org-current-line)
12024 (buffer-file-name) sexp)
12025 (sleep-for 2))))))
12026 (cond ((stringp result) result)
12027 ((and (consp result)
12028 (stringp (cdr result))) (cdr result))
12029 (result entry)
12030 (t nil))))
12032 (defun org-diary-to-ical-string (frombuf)
12033 "Get iCalendar entries from diary entries in buffer FROMBUF.
12034 This uses the icalendar.el library."
12035 (let* ((tmpdir (if (featurep 'xemacs)
12036 (temp-directory)
12037 temporary-file-directory))
12038 (tmpfile (make-temp-name
12039 (expand-file-name "orgics" tmpdir)))
12040 buf rtn b e)
12041 (save-excursion
12042 (set-buffer frombuf)
12043 (icalendar-export-region (point-min) (point-max) tmpfile)
12044 (setq buf (find-buffer-visiting tmpfile))
12045 (set-buffer buf)
12046 (goto-char (point-min))
12047 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12048 (setq b (match-beginning 0)))
12049 (goto-char (point-max))
12050 (if (re-search-backward "^END:VEVENT" nil t)
12051 (setq e (match-end 0)))
12052 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12053 (kill-buffer buf)
12054 (delete-file tmpfile)
12055 rtn))
12057 (defun org-closest-date (start current change prefer show-all)
12058 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12059 When PREFER is `past' return a date that is either CURRENT or past.
12060 When PREFER is `future', return a date that is either CURRENT or future.
12061 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12062 ;; Make the proper lists from the dates
12063 (catch 'exit
12064 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12065 dn dw sday cday n1 n2 n0
12066 d m y y1 y2 date1 date2 nmonths nm ny m2)
12068 (setq start (org-date-to-gregorian start)
12069 current (org-date-to-gregorian
12070 (if show-all
12071 current
12072 (time-to-days (current-time))))
12073 sday (calendar-absolute-from-gregorian start)
12074 cday (calendar-absolute-from-gregorian current))
12076 (if (<= cday sday) (throw 'exit sday))
12078 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12079 (setq dn (string-to-number (match-string 1 change))
12080 dw (cdr (assoc (match-string 2 change) a1)))
12081 (error "Invalid change specifyer: %s" change))
12082 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12083 (cond
12084 ((eq dw 'day)
12085 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12086 n2 (+ n1 dn)))
12087 ((eq dw 'year)
12088 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12089 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12090 (setq date1 (list m d y1)
12091 n1 (calendar-absolute-from-gregorian date1)
12092 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12093 n2 (calendar-absolute-from-gregorian date2)))
12094 ((eq dw 'month)
12095 ;; approx number of month between the two dates
12096 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12097 ;; How often does dn fit in there?
12098 (setq d (nth 1 start) m (car start) y (nth 2 start)
12099 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12100 m (+ m nm)
12101 ny (floor (/ m 12))
12102 y (+ y ny)
12103 m (- m (* ny 12)))
12104 (while (> m 12) (setq m (- m 12) y (1+ y)))
12105 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12106 (setq m2 (+ m dn) y2 y)
12107 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12108 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12109 (while (<= n2 cday)
12110 (setq n1 n2 m m2 y y2)
12111 (setq m2 (+ m dn) y2 y)
12112 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12113 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12114 ;; Make sure n1 is the earlier date
12115 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12116 (if show-all
12117 (cond
12118 ((eq prefer 'past) n1)
12119 ((eq prefer 'future) (if (= cday n1) n1 n2))
12120 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12121 (cond
12122 ((eq prefer 'past) n1)
12123 ((eq prefer 'future) (if (= cday n1) n1 n2))
12124 (t (if (= cday n1) n1 n2)))))))
12126 (defun org-date-to-gregorian (date)
12127 "Turn any specification of DATE into a gregorian date for the calendar."
12128 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12129 ((and (listp date) (= (length date) 3)) date)
12130 ((stringp date)
12131 (setq date (org-parse-time-string date))
12132 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12133 ((listp date)
12134 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12136 (defun org-parse-time-string (s &optional nodefault)
12137 "Parse the standard Org-mode time string.
12138 This should be a lot faster than the normal `parse-time-string'.
12139 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12140 hour and minute fields will be nil if not given."
12141 (if (string-match org-ts-regexp0 s)
12142 (list 0
12143 (if (or (match-beginning 8) (not nodefault))
12144 (string-to-number (or (match-string 8 s) "0")))
12145 (if (or (match-beginning 7) (not nodefault))
12146 (string-to-number (or (match-string 7 s) "0")))
12147 (string-to-number (match-string 4 s))
12148 (string-to-number (match-string 3 s))
12149 (string-to-number (match-string 2 s))
12150 nil nil nil)
12151 (make-list 9 0)))
12153 (defun org-timestamp-up (&optional arg)
12154 "Increase the date item at the cursor by one.
12155 If the cursor is on the year, change the year. If it is on the month or
12156 the day, change that.
12157 With prefix ARG, change by that many units."
12158 (interactive "p")
12159 (org-timestamp-change (prefix-numeric-value arg)))
12161 (defun org-timestamp-down (&optional arg)
12162 "Decrease the date item at the cursor by one.
12163 If the cursor is on the year, change the year. If it is on the month or
12164 the day, change that.
12165 With prefix ARG, change by that many units."
12166 (interactive "p")
12167 (org-timestamp-change (- (prefix-numeric-value arg))))
12169 (defun org-timestamp-up-day (&optional arg)
12170 "Increase the date in the time stamp by one day.
12171 With prefix ARG, change that many days."
12172 (interactive "p")
12173 (if (and (not (org-at-timestamp-p t))
12174 (org-on-heading-p))
12175 (org-todo 'up)
12176 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12178 (defun org-timestamp-down-day (&optional arg)
12179 "Decrease the date in the time stamp by one day.
12180 With prefix ARG, change that many days."
12181 (interactive "p")
12182 (if (and (not (org-at-timestamp-p t))
12183 (org-on-heading-p))
12184 (org-todo 'down)
12185 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12187 (defun org-at-timestamp-p (&optional inactive-ok)
12188 "Determine if the cursor is in or at a timestamp."
12189 (interactive)
12190 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12191 (pos (point))
12192 (ans (or (looking-at tsr)
12193 (save-excursion
12194 (skip-chars-backward "^[<\n\r\t")
12195 (if (> (point) (point-min)) (backward-char 1))
12196 (and (looking-at tsr)
12197 (> (- (match-end 0) pos) -1))))))
12198 (and ans
12199 (boundp 'org-ts-what)
12200 (setq org-ts-what
12201 (cond
12202 ((= pos (match-beginning 0)) 'bracket)
12203 ((= pos (1- (match-end 0))) 'bracket)
12204 ((org-pos-in-match-range pos 2) 'year)
12205 ((org-pos-in-match-range pos 3) 'month)
12206 ((org-pos-in-match-range pos 7) 'hour)
12207 ((org-pos-in-match-range pos 8) 'minute)
12208 ((or (org-pos-in-match-range pos 4)
12209 (org-pos-in-match-range pos 5)) 'day)
12210 ((and (> pos (or (match-end 8) (match-end 5)))
12211 (< pos (match-end 0)))
12212 (- pos (or (match-end 8) (match-end 5))))
12213 (t 'day))))
12214 ans))
12216 (defun org-toggle-timestamp-type ()
12217 "Toggle the type (<active> or [inactive]) of a time stamp."
12218 (interactive)
12219 (when (org-at-timestamp-p t)
12220 (let ((beg (match-beginning 0)) (end (match-end 0))
12221 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12222 (save-excursion
12223 (goto-char beg)
12224 (while (re-search-forward "[][<>]" end t)
12225 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12226 t t)))
12227 (message "Timestamp is now %sactive"
12228 (if (equal (char-after beg) ?<) "" "in")))))
12230 (defun org-timestamp-change (n &optional what)
12231 "Change the date in the time stamp at point.
12232 The date will be changed by N times WHAT. WHAT can be `day', `month',
12233 `year', `minute', `second'. If WHAT is not given, the cursor position
12234 in the timestamp determines what will be changed."
12235 (let ((pos (point))
12236 with-hm inactive
12237 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12238 org-ts-what
12239 extra rem
12240 ts time time0)
12241 (if (not (org-at-timestamp-p t))
12242 (error "Not at a timestamp"))
12243 (if (and (not what) (eq org-ts-what 'bracket))
12244 (org-toggle-timestamp-type)
12245 (if (and (not what) (not (eq org-ts-what 'day))
12246 org-display-custom-times
12247 (get-text-property (point) 'display)
12248 (not (get-text-property (1- (point)) 'display)))
12249 (setq org-ts-what 'day))
12250 (setq org-ts-what (or what org-ts-what)
12251 inactive (= (char-after (match-beginning 0)) ?\[)
12252 ts (match-string 0))
12253 (replace-match "")
12254 (if (string-match
12255 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12257 (setq extra (match-string 1 ts)))
12258 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12259 (setq with-hm t))
12260 (setq time0 (org-parse-time-string ts))
12261 (when (and (eq org-ts-what 'minute)
12262 (eq current-prefix-arg nil))
12263 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12264 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12265 (setcar (cdr time0) (+ (nth 1 time0)
12266 (if (> n 0) (- rem) (- dm rem))))))
12267 (setq time
12268 (encode-time (or (car time0) 0)
12269 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12270 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12271 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12272 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12273 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12274 (nthcdr 6 time0)))
12275 (when (integerp org-ts-what)
12276 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12277 (if (eq what 'calendar)
12278 (let ((cal-date (org-get-date-from-calendar)))
12279 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12280 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12281 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12282 (setcar time0 (or (car time0) 0))
12283 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12284 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12285 (setq time (apply 'encode-time time0))))
12286 (setq org-last-changed-timestamp
12287 (org-insert-time-stamp time with-hm inactive nil nil extra))
12288 (org-clock-update-time-maybe)
12289 (goto-char pos)
12290 ;; Try to recenter the calendar window, if any
12291 (if (and org-calendar-follow-timestamp-change
12292 (get-buffer-window "*Calendar*" t)
12293 (memq org-ts-what '(day month year)))
12294 (org-recenter-calendar (time-to-days time))))))
12296 (defun org-modify-ts-extra (s pos n dm)
12297 "Change the different parts of the lead-time and repeat fields in timestamp."
12298 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12299 ng h m new rem)
12300 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12301 (cond
12302 ((or (org-pos-in-match-range pos 2)
12303 (org-pos-in-match-range pos 3))
12304 (setq m (string-to-number (match-string 3 s))
12305 h (string-to-number (match-string 2 s)))
12306 (if (org-pos-in-match-range pos 2)
12307 (setq h (+ h n))
12308 (setq n (* dm (org-no-warnings (signum n))))
12309 (when (not (= 0 (setq rem (% m dm))))
12310 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12311 (setq m (+ m n)))
12312 (if (< m 0) (setq m (+ m 60) h (1- h)))
12313 (if (> m 59) (setq m (- m 60) h (1+ h)))
12314 (setq h (min 24 (max 0 h)))
12315 (setq ng 1 new (format "-%02d:%02d" h m)))
12316 ((org-pos-in-match-range pos 6)
12317 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12318 ((org-pos-in-match-range pos 5)
12319 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12321 ((org-pos-in-match-range pos 9)
12322 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12323 ((org-pos-in-match-range pos 8)
12324 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12326 (when ng
12327 (setq s (concat
12328 (substring s 0 (match-beginning ng))
12330 (substring s (match-end ng))))))
12333 (defun org-recenter-calendar (date)
12334 "If the calendar is visible, recenter it to DATE."
12335 (let* ((win (selected-window))
12336 (cwin (get-buffer-window "*Calendar*" t))
12337 (calendar-move-hook nil))
12338 (when cwin
12339 (select-window cwin)
12340 (calendar-goto-date (if (listp date) date
12341 (calendar-gregorian-from-absolute date)))
12342 (select-window win))))
12344 (defun org-goto-calendar (&optional arg)
12345 "Go to the Emacs calendar at the current date.
12346 If there is a time stamp in the current line, go to that date.
12347 A prefix ARG can be used to force the current date."
12348 (interactive "P")
12349 (let ((tsr org-ts-regexp) diff
12350 (calendar-move-hook nil)
12351 (calendar-view-holidays-initially-flag nil)
12352 (view-calendar-holidays-initially nil)
12353 (calendar-view-diary-initially-flag nil)
12354 (view-diary-entries-initially nil))
12355 (if (or (org-at-timestamp-p)
12356 (save-excursion
12357 (beginning-of-line 1)
12358 (looking-at (concat ".*" tsr))))
12359 (let ((d1 (time-to-days (current-time)))
12360 (d2 (time-to-days
12361 (org-time-string-to-time (match-string 1)))))
12362 (setq diff (- d2 d1))))
12363 (calendar)
12364 (calendar-goto-today)
12365 (if (and diff (not arg)) (calendar-forward-day diff))))
12367 (defun org-get-date-from-calendar ()
12368 "Return a list (month day year) of date at point in calendar."
12369 (with-current-buffer "*Calendar*"
12370 (save-match-data
12371 (calendar-cursor-to-date))))
12373 (defun org-date-from-calendar ()
12374 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12375 If there is already a time stamp at the cursor position, update it."
12376 (interactive)
12377 (if (org-at-timestamp-p t)
12378 (org-timestamp-change 0 'calendar)
12379 (let ((cal-date (org-get-date-from-calendar)))
12380 (org-insert-time-stamp
12381 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12383 (defun org-minutes-to-hh:mm-string (m)
12384 "Compute H:MM from a number of minutes."
12385 (let ((h (/ m 60)))
12386 (setq m (- m (* 60 h)))
12387 (format org-time-clocksum-format h m)))
12389 (defun org-hh:mm-string-to-minutes (s)
12390 "Convert a string H:MM to a number of minutes."
12391 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12392 (+ (* (string-to-number (match-string 1 s)) 60)
12393 (string-to-number (match-string 2 s)))
12396 ;;;; Files
12398 (defun org-save-all-org-buffers ()
12399 "Save all Org-mode buffers without user confirmation."
12400 (interactive)
12401 (message "Saving all Org-mode buffers...")
12402 (save-some-buffers t 'org-mode-p)
12403 (when (featurep 'org-id) (org-id-locations-save))
12404 (message "Saving all Org-mode buffers... done"))
12406 (defun org-revert-all-org-buffers ()
12407 "Revert all Org-mode buffers.
12408 Prompt for confirmation when there are unsaved changes.
12409 Be sure you know what you are doing before letting this function
12410 overwrite your changes.
12412 This function is useful in a setup where one tracks org files
12413 with a version control system, to revert on one machine after pulling
12414 changes from another. I believe the procedure must be like this:
12416 1. M-x org-save-all-org-buffers
12417 2. Pull changes from the other machine, resolve conflicts
12418 3. M-x org-revert-all-org-buffers"
12419 (interactive)
12420 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12421 (error "Abort"))
12422 (save-excursion
12423 (save-window-excursion
12424 (mapc
12425 (lambda (b)
12426 (when (and (with-current-buffer b (org-mode-p))
12427 (with-current-buffer b buffer-file-name))
12428 (switch-to-buffer b)
12429 (revert-buffer t 'no-confirm)))
12430 (buffer-list))
12431 (when (and (featurep 'org-id) org-id-track-globally)
12432 (org-id-locations-load)))))
12434 ;;;; Agenda files
12436 ;;;###autoload
12437 (defun org-iswitchb (&optional arg)
12438 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12439 With a prefix argument, restrict available to files.
12440 With two prefix arguments, restrict available buffers to agenda files.
12442 Due to some yet unresolved reason, the global function
12443 `iswitchb-mode' needs to be active for this function to work."
12444 (interactive "P")
12445 (require 'iswitchb)
12446 (let ((enabled iswitchb-mode) blist)
12447 (or enabled (iswitchb-mode 1))
12448 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12449 ((equal arg '(16)) (org-buffer-list 'agenda))
12450 (t (org-buffer-list))))
12451 (unwind-protect
12452 (let ((iswitchb-make-buflist-hook
12453 (lambda ()
12454 (setq iswitchb-temp-buflist
12455 (mapcar 'buffer-name blist)))))
12456 (switch-to-buffer
12457 (iswitchb-read-buffer
12458 "Switch-to: " nil t))
12459 (or enabled (iswitchb-mode -1))))))
12461 ;;;###autoload
12462 (defun org-ido-switchb (&optional arg)
12463 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12464 With a prefix argument, restrict available to files.
12465 With two prefix arguments, restrict available buffers to agenda files."
12466 (interactive "P")
12467 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12468 ((equal arg '(16)) (org-buffer-list 'agenda))
12469 (t (org-buffer-list)))))
12470 (switch-to-buffer
12471 (org-ido-completing-read "Org buffer: "
12472 (mapcar 'buffer-name blist)
12473 nil t))))
12475 (defun org-buffer-list (&optional predicate exclude-tmp)
12476 "Return a list of Org buffers.
12477 PREDICATE can be `export', `files' or `agenda'.
12479 export restrict the list to Export buffers.
12480 files restrict the list to buffers visiting Org files.
12481 agenda restrict the list to buffers visiting agenda files.
12483 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12484 (let* ((bfn nil)
12485 (agenda-files (and (eq predicate 'agenda)
12486 (mapcar 'file-truename (org-agenda-files t))))
12487 (filter
12488 (cond
12489 ((eq predicate 'files)
12490 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12491 ((eq predicate 'export)
12492 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12493 ((eq predicate 'agenda)
12494 (lambda (b)
12495 (with-current-buffer b
12496 (and (eq major-mode 'org-mode)
12497 (setq bfn (buffer-file-name b))
12498 (member (file-truename bfn) agenda-files)))))
12499 (t (lambda (b) (with-current-buffer b
12500 (or (eq major-mode 'org-mode)
12501 (string-match "\*Org .*Export"
12502 (buffer-name b)))))))))
12503 (delq nil
12504 (mapcar
12505 (lambda(b)
12506 (if (and (funcall filter b)
12507 (or (not exclude-tmp)
12508 (not (string-match "tmp" (buffer-name b)))))
12510 nil))
12511 (buffer-list)))))
12513 (defun org-agenda-files (&optional unrestricted archives)
12514 "Get the list of agenda files.
12515 Optional UNRESTRICTED means return the full list even if a restriction
12516 is currently in place.
12517 When ARCHIVES is t, include all archive files hat are really being
12518 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12519 `org-agenda-archives-mode' is t."
12520 (let ((files
12521 (cond
12522 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12523 ((stringp org-agenda-files) (org-read-agenda-file-list))
12524 ((listp org-agenda-files) org-agenda-files)
12525 (t (error "Invalid value of `org-agenda-files'")))))
12526 (setq files (apply 'append
12527 (mapcar (lambda (f)
12528 (if (file-directory-p f)
12529 (directory-files
12530 f t org-agenda-file-regexp)
12531 (list f)))
12532 files)))
12533 (when org-agenda-skip-unavailable-files
12534 (setq files (delq nil
12535 (mapcar (function
12536 (lambda (file)
12537 (and (file-readable-p file) file)))
12538 files))))
12539 (when (or (eq archives t)
12540 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12541 (setq files (org-add-archive-files files)))
12542 files))
12544 (defun org-edit-agenda-file-list ()
12545 "Edit the list of agenda files.
12546 Depending on setup, this either uses customize to edit the variable
12547 `org-agenda-files', or it visits the file that is holding the list. In the
12548 latter case, the buffer is set up in a way that saving it automatically kills
12549 the buffer and restores the previous window configuration."
12550 (interactive)
12551 (if (stringp org-agenda-files)
12552 (let ((cw (current-window-configuration)))
12553 (find-file org-agenda-files)
12554 (org-set-local 'org-window-configuration cw)
12555 (org-add-hook 'after-save-hook
12556 (lambda ()
12557 (set-window-configuration
12558 (prog1 org-window-configuration
12559 (kill-buffer (current-buffer))))
12560 (org-install-agenda-files-menu)
12561 (message "New agenda file list installed"))
12562 nil 'local)
12563 (message "%s" (substitute-command-keys
12564 "Edit list and finish with \\[save-buffer]")))
12565 (customize-variable 'org-agenda-files)))
12567 (defun org-store-new-agenda-file-list (list)
12568 "Set new value for the agenda file list and save it correctly."
12569 (if (stringp org-agenda-files)
12570 (let ((f org-agenda-files) b)
12571 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12572 (with-temp-file f
12573 (insert (mapconcat 'identity list "\n") "\n")))
12574 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12575 (setq org-agenda-files list)
12576 (customize-save-variable 'org-agenda-files org-agenda-files))))
12578 (defun org-read-agenda-file-list ()
12579 "Read the list of agenda files from a file."
12580 (when (file-directory-p org-agenda-files)
12581 (error "`org-agenda-files' cannot be a single directory"))
12582 (when (stringp org-agenda-files)
12583 (with-temp-buffer
12584 (insert-file-contents org-agenda-files)
12585 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12588 ;;;###autoload
12589 (defun org-cycle-agenda-files ()
12590 "Cycle through the files in `org-agenda-files'.
12591 If the current buffer visits an agenda file, find the next one in the list.
12592 If the current buffer does not, find the first agenda file."
12593 (interactive)
12594 (let* ((fs (org-agenda-files t))
12595 (files (append fs (list (car fs))))
12596 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12597 file)
12598 (unless files (error "No agenda files"))
12599 (catch 'exit
12600 (while (setq file (pop files))
12601 (if (equal (file-truename file) tcf)
12602 (when (car files)
12603 (find-file (car files))
12604 (throw 'exit t))))
12605 (find-file (car fs)))
12606 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12608 (defun org-agenda-file-to-front (&optional to-end)
12609 "Move/add the current file to the top of the agenda file list.
12610 If the file is not present in the list, it is added to the front. If it is
12611 present, it is moved there. With optional argument TO-END, add/move to the
12612 end of the list."
12613 (interactive "P")
12614 (let ((org-agenda-skip-unavailable-files nil)
12615 (file-alist (mapcar (lambda (x)
12616 (cons (file-truename x) x))
12617 (org-agenda-files t)))
12618 (ctf (file-truename buffer-file-name))
12619 x had)
12620 (setq x (assoc ctf file-alist) had x)
12622 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12623 (if to-end
12624 (setq file-alist (append (delq x file-alist) (list x)))
12625 (setq file-alist (cons x (delq x file-alist))))
12626 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12627 (org-install-agenda-files-menu)
12628 (message "File %s to %s of agenda file list"
12629 (if had "moved" "added") (if to-end "end" "front"))))
12631 (defun org-remove-file (&optional file)
12632 "Remove current file from the list of files in variable `org-agenda-files'.
12633 These are the files which are being checked for agenda entries.
12634 Optional argument FILE means, use this file instead of the current."
12635 (interactive)
12636 (let* ((org-agenda-skip-unavailable-files nil)
12637 (file (or file buffer-file-name))
12638 (true-file (file-truename file))
12639 (afile (abbreviate-file-name file))
12640 (files (delq nil (mapcar
12641 (lambda (x)
12642 (if (equal true-file
12643 (file-truename x))
12644 nil x))
12645 (org-agenda-files t)))))
12646 (if (not (= (length files) (length (org-agenda-files t))))
12647 (progn
12648 (org-store-new-agenda-file-list files)
12649 (org-install-agenda-files-menu)
12650 (message "Removed file: %s" afile))
12651 (message "File was not in list: %s (not removed)" afile))))
12653 (defun org-file-menu-entry (file)
12654 (vector file (list 'find-file file) t))
12656 (defun org-check-agenda-file (file)
12657 "Make sure FILE exists. If not, ask user what to do."
12658 (when (not (file-exists-p file))
12659 (message "non-existent file %s. [R]emove from list or [A]bort?"
12660 (abbreviate-file-name file))
12661 (let ((r (downcase (read-char-exclusive))))
12662 (cond
12663 ((equal r ?r)
12664 (org-remove-file file)
12665 (throw 'nextfile t))
12666 (t (error "Abort"))))))
12668 (defun org-get-agenda-file-buffer (file)
12669 "Get a buffer visiting FILE. If the buffer needs to be created, add
12670 it to the list of buffers which might be released later."
12671 (let ((buf (org-find-base-buffer-visiting file)))
12672 (if buf
12673 buf ; just return it
12674 ;; Make a new buffer and remember it
12675 (setq buf (find-file-noselect file))
12676 (if buf (push buf org-agenda-new-buffers))
12677 buf)))
12679 (defun org-release-buffers (blist)
12680 "Release all buffers in list, asking the user for confirmation when needed.
12681 When a buffer is unmodified, it is just killed. When modified, it is saved
12682 \(if the user agrees) and then killed."
12683 (let (buf file)
12684 (while (setq buf (pop blist))
12685 (setq file (buffer-file-name buf))
12686 (when (and (buffer-modified-p buf)
12687 file
12688 (y-or-n-p (format "Save file %s? " file)))
12689 (with-current-buffer buf (save-buffer)))
12690 (kill-buffer buf))))
12692 (defun org-prepare-agenda-buffers (files)
12693 "Create buffers for all agenda files, protect archived trees and comments."
12694 (interactive)
12695 (let ((pa '(:org-archived t))
12696 (pc '(:org-comment t))
12697 (pall '(:org-archived t :org-comment t))
12698 (inhibit-read-only t)
12699 (rea (concat ":" org-archive-tag ":"))
12700 bmp file re)
12701 (save-excursion
12702 (save-restriction
12703 (while (setq file (pop files))
12704 (if (bufferp file)
12705 (set-buffer file)
12706 (org-check-agenda-file file)
12707 (set-buffer (org-get-agenda-file-buffer file)))
12708 (widen)
12709 (setq bmp (buffer-modified-p))
12710 (org-refresh-category-properties)
12711 (setq org-todo-keywords-for-agenda
12712 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12713 (setq org-done-keywords-for-agenda
12714 (append org-done-keywords-for-agenda org-done-keywords))
12715 (setq org-todo-keyword-alist-for-agenda
12716 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12717 (setq org-tag-alist-for-agenda
12718 (append org-tag-alist-for-agenda org-tag-alist))
12720 (save-excursion
12721 (remove-text-properties (point-min) (point-max) pall)
12722 (when org-agenda-skip-archived-trees
12723 (goto-char (point-min))
12724 (while (re-search-forward rea nil t)
12725 (if (org-on-heading-p t)
12726 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12727 (goto-char (point-min))
12728 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12729 (while (re-search-forward re nil t)
12730 (add-text-properties
12731 (match-beginning 0) (org-end-of-subtree t) pc)))
12732 (set-buffer-modified-p bmp))))
12733 (setq org-todo-keyword-alist-for-agenda
12734 (org-uniquify org-todo-keyword-alist-for-agenda)
12735 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12737 ;;;; Embedded LaTeX
12739 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12740 "Keymap for the minor `org-cdlatex-mode'.")
12742 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12743 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12744 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12745 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12746 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12748 (defvar org-cdlatex-texmathp-advice-is-done nil
12749 "Flag remembering if we have applied the advice to texmathp already.")
12751 (define-minor-mode org-cdlatex-mode
12752 "Toggle the minor `org-cdlatex-mode'.
12753 This mode supports entering LaTeX environment and math in LaTeX fragments
12754 in Org-mode.
12755 \\{org-cdlatex-mode-map}"
12756 nil " OCDL" nil
12757 (when org-cdlatex-mode (require 'cdlatex))
12758 (unless org-cdlatex-texmathp-advice-is-done
12759 (setq org-cdlatex-texmathp-advice-is-done t)
12760 (defadvice texmathp (around org-math-always-on activate)
12761 "Always return t in org-mode buffers.
12762 This is because we want to insert math symbols without dollars even outside
12763 the LaTeX math segments. If Orgmode thinks that point is actually inside
12764 an embedded LaTeX fragment, let texmathp do its job.
12765 \\[org-cdlatex-mode-map]"
12766 (interactive)
12767 (let (p)
12768 (cond
12769 ((not (org-mode-p)) ad-do-it)
12770 ((eq this-command 'cdlatex-math-symbol)
12771 (setq ad-return-value t
12772 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12774 (let ((p (org-inside-LaTeX-fragment-p)))
12775 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12776 (setq ad-return-value t
12777 texmathp-why '("Org-mode embedded math" . 0))
12778 (if p ad-do-it)))))))))
12780 (defun turn-on-org-cdlatex ()
12781 "Unconditionally turn on `org-cdlatex-mode'."
12782 (org-cdlatex-mode 1))
12784 (defun org-inside-LaTeX-fragment-p ()
12785 "Test if point is inside a LaTeX fragment.
12786 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12787 sequence appearing also before point.
12788 Even though the matchers for math are configurable, this function assumes
12789 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12790 delimiters are skipped when they have been removed by customization.
12791 The return value is nil, or a cons cell with the delimiter and
12792 and the position of this delimiter.
12794 This function does a reasonably good job, but can locally be fooled by
12795 for example currency specifications. For example it will assume being in
12796 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12797 fragments that are properly closed, but during editing, we have to live
12798 with the uncertainty caused by missing closing delimiters. This function
12799 looks only before point, not after."
12800 (catch 'exit
12801 (let ((pos (point))
12802 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12803 (lim (progn
12804 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12805 (point)))
12806 dd-on str (start 0) m re)
12807 (goto-char pos)
12808 (when dodollar
12809 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12810 re (nth 1 (assoc "$" org-latex-regexps)))
12811 (while (string-match re str start)
12812 (cond
12813 ((= (match-end 0) (length str))
12814 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12815 ((= (match-end 0) (- (length str) 5))
12816 (throw 'exit nil))
12817 (t (setq start (match-end 0))))))
12818 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12819 (goto-char pos)
12820 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12821 (and (match-beginning 2) (throw 'exit nil))
12822 ;; count $$
12823 (while (re-search-backward "\\$\\$" lim t)
12824 (setq dd-on (not dd-on)))
12825 (goto-char pos)
12826 (if dd-on (cons "$$" m))))))
12829 (defun org-try-cdlatex-tab ()
12830 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12831 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12832 - inside a LaTeX fragment, or
12833 - after the first word in a line, where an abbreviation expansion could
12834 insert a LaTeX environment."
12835 (when org-cdlatex-mode
12836 (cond
12837 ((save-excursion
12838 (skip-chars-backward "a-zA-Z0-9*")
12839 (skip-chars-backward " \t")
12840 (bolp))
12841 (cdlatex-tab) t)
12842 ((org-inside-LaTeX-fragment-p)
12843 (cdlatex-tab) t)
12844 (t nil))))
12846 (defun org-cdlatex-underscore-caret (&optional arg)
12847 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12848 Revert to the normal definition outside of these fragments."
12849 (interactive "P")
12850 (if (org-inside-LaTeX-fragment-p)
12851 (call-interactively 'cdlatex-sub-superscript)
12852 (let (org-cdlatex-mode)
12853 (call-interactively (key-binding (vector last-input-event))))))
12855 (defun org-cdlatex-math-modify (&optional arg)
12856 "Execute `cdlatex-math-modify' in LaTeX fragments.
12857 Revert to the normal definition outside of these fragments."
12858 (interactive "P")
12859 (if (org-inside-LaTeX-fragment-p)
12860 (call-interactively 'cdlatex-math-modify)
12861 (let (org-cdlatex-mode)
12862 (call-interactively (key-binding (vector last-input-event))))))
12864 (defvar org-latex-fragment-image-overlays nil
12865 "List of overlays carrying the images of latex fragments.")
12866 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12868 (defun org-remove-latex-fragment-image-overlays ()
12869 "Remove all overlays with LaTeX fragment images in current buffer."
12870 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12871 (setq org-latex-fragment-image-overlays nil))
12873 (defun org-preview-latex-fragment (&optional subtree)
12874 "Preview the LaTeX fragment at point, or all locally or globally.
12875 If the cursor is in a LaTeX fragment, create the image and overlay
12876 it over the source code. If there is no fragment at point, display
12877 all fragments in the current text, from one headline to the next. With
12878 prefix SUBTREE, display all fragments in the current subtree. With a
12879 double prefix `C-u C-u', or when the cursor is before the first headline,
12880 display all fragments in the buffer.
12881 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12882 (interactive "P")
12883 (org-remove-latex-fragment-image-overlays)
12884 (save-excursion
12885 (save-restriction
12886 (let (beg end at msg)
12887 (cond
12888 ((or (equal subtree '(16))
12889 (not (save-excursion
12890 (re-search-backward (concat "^" outline-regexp) nil t))))
12891 (setq beg (point-min) end (point-max)
12892 msg "Creating images for buffer...%s"))
12893 ((equal subtree '(4))
12894 (org-back-to-heading)
12895 (setq beg (point) end (org-end-of-subtree t)
12896 msg "Creating images for subtree...%s"))
12898 (if (setq at (org-inside-LaTeX-fragment-p))
12899 (goto-char (max (point-min) (- (cdr at) 2)))
12900 (org-back-to-heading))
12901 (setq beg (point) end (progn (outline-next-heading) (point))
12902 msg (if at "Creating image...%s"
12903 "Creating images for entry...%s"))))
12904 (message msg "")
12905 (narrow-to-region beg end)
12906 (goto-char beg)
12907 (org-format-latex
12908 (concat "ltxpng/" (file-name-sans-extension
12909 (file-name-nondirectory
12910 buffer-file-name)))
12911 default-directory 'overlays msg at 'forbuffer)
12912 (message msg "done. Use `C-c C-c' to remove images.")))))
12914 (defvar org-latex-regexps
12915 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12916 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12917 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12918 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12919 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12920 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12921 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12922 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12923 "Regular expressions for matching embedded LaTeX.")
12925 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12926 "Replace LaTeX fragments with links to an image, and produce images."
12927 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12928 (let* ((prefixnodir (file-name-nondirectory prefix))
12929 (absprefix (expand-file-name prefix dir))
12930 (todir (file-name-directory absprefix))
12931 (opt org-format-latex-options)
12932 (matchers (plist-get opt :matchers))
12933 (re-list org-latex-regexps)
12934 (cnt 0) txt link beg end re e checkdir
12935 m n block linkfile movefile ov)
12936 ;; Check if there are old images files with this prefix, and remove them
12937 (when (file-directory-p todir)
12938 (mapc 'delete-file
12939 (directory-files
12940 todir 'full
12941 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12942 ;; Check the different regular expressions
12943 (while (setq e (pop re-list))
12944 (setq m (car e) re (nth 1 e) n (nth 2 e)
12945 block (if (nth 3 e) "\n\n" ""))
12946 (when (member m matchers)
12947 (goto-char (point-min))
12948 (while (re-search-forward re nil t)
12949 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
12950 (not (get-text-property (match-beginning n)
12951 'org-protected)))
12952 (setq txt (match-string n)
12953 beg (match-beginning n) end (match-end n)
12954 cnt (1+ cnt)
12955 linkfile (format "%s_%04d.png" prefix cnt)
12956 movefile (format "%s_%04d.png" absprefix cnt)
12957 link (concat block "[[file:" linkfile "]]" block))
12958 (if msg (message msg cnt))
12959 (goto-char beg)
12960 (unless checkdir ; make sure the directory exists
12961 (setq checkdir t)
12962 (or (file-directory-p todir) (make-directory todir)))
12963 (org-create-formula-image
12964 txt movefile opt forbuffer)
12965 (if overlays
12966 (progn
12967 (setq ov (org-make-overlay beg end))
12968 (if (featurep 'xemacs)
12969 (progn
12970 (org-overlay-put ov 'invisible t)
12971 (org-overlay-put
12972 ov 'end-glyph
12973 (make-glyph (vector 'png :file movefile))))
12974 (org-overlay-put
12975 ov 'display
12976 (list 'image :type 'png :file movefile :ascent 'center)))
12977 (push ov org-latex-fragment-image-overlays)
12978 (goto-char end))
12979 (delete-region beg end)
12980 (insert link))))))))
12982 ;; This function borrows from Ganesh Swami's latex2png.el
12983 (defun org-create-formula-image (string tofile options buffer)
12984 (let* ((tmpdir (if (featurep 'xemacs)
12985 (temp-directory)
12986 temporary-file-directory))
12987 (texfilebase (make-temp-name
12988 (expand-file-name "orgtex" tmpdir)))
12989 (texfile (concat texfilebase ".tex"))
12990 (dvifile (concat texfilebase ".dvi"))
12991 (pngfile (concat texfilebase ".png"))
12992 (fnh (if (featurep 'xemacs)
12993 (font-height (get-face-font 'default))
12994 (face-attribute 'default :height nil)))
12995 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12996 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12997 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12998 "Black"))
12999 (bg (or (plist-get options (if buffer :background :html-background))
13000 "Transparent")))
13001 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13002 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13003 (with-temp-file texfile
13004 (insert org-format-latex-header
13005 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13006 (let ((dir default-directory))
13007 (condition-case nil
13008 (progn
13009 (cd tmpdir)
13010 (call-process "latex" nil nil nil texfile))
13011 (error nil))
13012 (cd dir))
13013 (if (not (file-exists-p dvifile))
13014 (progn (message "Failed to create dvi file from %s" texfile) nil)
13015 (condition-case nil
13016 (call-process "dvipng" nil nil nil
13017 "-E" "-fg" fg "-bg" bg
13018 "-D" dpi
13019 ;;"-x" scale "-y" scale
13020 "-T" "tight"
13021 "-o" pngfile
13022 dvifile)
13023 (error nil))
13024 (if (not (file-exists-p pngfile))
13025 (progn (message "Failed to create png file from %s" texfile) nil)
13026 ;; Use the requested file name and clean up
13027 (copy-file pngfile tofile 'replace)
13028 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13029 (delete-file (concat texfilebase e)))
13030 pngfile))))
13032 (defun org-dvipng-color (attr)
13033 "Return an rgb color specification for dvipng."
13034 (apply 'format "rgb %s %s %s"
13035 (mapcar 'org-normalize-color
13036 (color-values (face-attribute 'default attr nil)))))
13038 (defun org-normalize-color (value)
13039 "Return string to be used as color value for an RGB component."
13040 (format "%g" (/ value 65535.0)))
13042 ;;;; Key bindings
13044 ;; Make `C-c C-x' a prefix key
13045 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13047 ;; TAB key with modifiers
13048 (org-defkey org-mode-map "\C-i" 'org-cycle)
13049 (org-defkey org-mode-map [(tab)] 'org-cycle)
13050 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13051 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13052 (org-defkey org-mode-map "\M-\t" 'org-complete)
13053 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13054 ;; The following line is necessary under Suse GNU/Linux
13055 (unless (featurep 'xemacs)
13056 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13057 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13058 (define-key org-mode-map [backtab] 'org-shifttab)
13060 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13061 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13062 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13064 ;; Cursor keys with modifiers
13065 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13066 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13067 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13068 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13070 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13071 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13072 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13073 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13075 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13076 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13077 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13078 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13080 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13081 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13083 ;;; Extra keys for tty access.
13084 ;; We only set them when really needed because otherwise the
13085 ;; menus don't show the simple keys
13087 (when (or org-use-extra-keys
13088 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13089 (not window-system))
13090 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13091 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13092 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13093 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13094 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13095 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13096 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13097 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13098 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13099 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13100 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13101 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13102 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13103 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13104 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13105 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13106 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13107 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13108 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13109 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13110 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13111 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13113 ;; All the other keys
13115 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13116 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13117 (if (boundp 'narrow-map)
13118 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13119 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13120 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13121 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13122 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13123 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13124 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13125 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13126 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13127 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13128 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13129 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13130 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13131 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13132 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13133 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13134 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13135 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
13136 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13137 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13138 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13139 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13140 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13141 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13142 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13143 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13144 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13145 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13146 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13147 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13148 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13149 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13150 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13151 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13152 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13153 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13154 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13155 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13156 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13157 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13158 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13159 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13160 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13161 (org-defkey org-mode-map "\C-c^" 'org-sort)
13162 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13163 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13164 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13165 (org-defkey org-mode-map "\C-m" 'org-return)
13166 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13167 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13168 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13169 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13170 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13171 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13172 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13173 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13174 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13175 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13176 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13177 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13178 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13179 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13180 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13181 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13182 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13184 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13185 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13186 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13187 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13189 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13190 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13191 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13192 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13193 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13194 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13195 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13196 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13197 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13198 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13199 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13200 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13201 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13203 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13204 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13205 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13206 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13208 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13210 (when (featurep 'xemacs)
13211 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13213 (defvar org-table-auto-blank-field) ; defined in org-table.el
13214 (defun org-self-insert-command (N)
13215 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13216 If the cursor is in a table looking at whitespace, the whitespace is
13217 overwritten, and the table is not marked as requiring realignment."
13218 (interactive "p")
13219 (if (and (org-table-p)
13220 (progn
13221 ;; check if we blank the field, and if that triggers align
13222 (and (featurep 'org-table) org-table-auto-blank-field
13223 (member last-command
13224 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13225 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13226 ;; got extra space, this field does not determine column width
13227 (let (org-table-may-need-update) (org-table-blank-field))
13228 ;; no extra space, this field may determine column width
13229 (org-table-blank-field)))
13231 (eq N 1)
13232 (looking-at "[^|\n]* |"))
13233 (let (org-table-may-need-update)
13234 (goto-char (1- (match-end 0)))
13235 (delete-backward-char 1)
13236 (goto-char (match-beginning 0))
13237 (self-insert-command N))
13238 (setq org-table-may-need-update t)
13239 (self-insert-command N)
13240 (org-fix-tags-on-the-fly)))
13242 (defun org-fix-tags-on-the-fly ()
13243 (when (and (equal (char-after (point-at-bol)) ?*)
13244 (org-on-heading-p))
13245 (org-align-tags-here org-tags-column)))
13247 (defun org-delete-backward-char (N)
13248 "Like `delete-backward-char', insert whitespace at field end in tables.
13249 When deleting backwards, in tables this function will insert whitespace in
13250 front of the next \"|\" separator, to keep the table aligned. The table will
13251 still be marked for re-alignment if the field did fill the entire column,
13252 because, in this case the deletion might narrow the column."
13253 (interactive "p")
13254 (if (and (org-table-p)
13255 (eq N 1)
13256 (string-match "|" (buffer-substring (point-at-bol) (point)))
13257 (looking-at ".*?|"))
13258 (let ((pos (point))
13259 (noalign (looking-at "[^|\n\r]* |"))
13260 (c org-table-may-need-update))
13261 (backward-delete-char N)
13262 (skip-chars-forward "^|")
13263 (insert " ")
13264 (goto-char (1- pos))
13265 ;; noalign: if there were two spaces at the end, this field
13266 ;; does not determine the width of the column.
13267 (if noalign (setq org-table-may-need-update c)))
13268 (backward-delete-char N)
13269 (org-fix-tags-on-the-fly)))
13271 (defun org-delete-char (N)
13272 "Like `delete-char', but insert whitespace at field end in tables.
13273 When deleting characters, in tables this function will insert whitespace in
13274 front of the next \"|\" separator, to keep the table aligned. The table will
13275 still be marked for re-alignment if the field did fill the entire column,
13276 because, in this case the deletion might narrow the column."
13277 (interactive "p")
13278 (if (and (org-table-p)
13279 (not (bolp))
13280 (not (= (char-after) ?|))
13281 (eq N 1))
13282 (if (looking-at ".*?|")
13283 (let ((pos (point))
13284 (noalign (looking-at "[^|\n\r]* |"))
13285 (c org-table-may-need-update))
13286 (replace-match (concat
13287 (substring (match-string 0) 1 -1)
13288 " |"))
13289 (goto-char pos)
13290 ;; noalign: if there were two spaces at the end, this field
13291 ;; does not determine the width of the column.
13292 (if noalign (setq org-table-may-need-update c)))
13293 (delete-char N))
13294 (delete-char N)
13295 (org-fix-tags-on-the-fly)))
13297 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13298 (put 'org-self-insert-command 'delete-selection t)
13299 (put 'orgtbl-self-insert-command 'delete-selection t)
13300 (put 'org-delete-char 'delete-selection 'supersede)
13301 (put 'org-delete-backward-char 'delete-selection 'supersede)
13302 (put 'org-yank 'delete-selection 'yank)
13304 ;; Make `flyspell-mode' delay after some commands
13305 (put 'org-self-insert-command 'flyspell-delayed t)
13306 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13307 (put 'org-delete-char 'flyspell-delayed t)
13308 (put 'org-delete-backward-char 'flyspell-delayed t)
13310 ;; Make pabbrev-mode expand after org-mode commands
13311 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13312 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13314 ;; How to do this: Measure non-white length of current string
13315 ;; If equal to column width, we should realign.
13317 (defun org-remap (map &rest commands)
13318 "In MAP, remap the functions given in COMMANDS.
13319 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13320 (let (new old)
13321 (while commands
13322 (setq old (pop commands) new (pop commands))
13323 (if (fboundp 'command-remapping)
13324 (org-defkey map (vector 'remap old) new)
13325 (substitute-key-definition old new map global-map)))))
13327 (when (eq org-enable-table-editor 'optimized)
13328 ;; If the user wants maximum table support, we need to hijack
13329 ;; some standard editing functions
13330 (org-remap org-mode-map
13331 'self-insert-command 'org-self-insert-command
13332 'delete-char 'org-delete-char
13333 'delete-backward-char 'org-delete-backward-char)
13334 (org-defkey org-mode-map "|" 'org-force-self-insert))
13336 (defvar org-ctrl-c-ctrl-c-hook nil
13337 "Hook for functions attaching themselves to `C-c C-c'.
13338 This can be used to add additional functionality to the C-c C-c key which
13339 executes context-dependent commands.
13340 Each function will be called with no arguments. The function must check
13341 if the context is appropriate for it to act. If yes, it should do its
13342 thing and then return a non-nil value. If the context is wrong,
13343 just do nothing.")
13345 (defvar org-metaleft-hook nil
13346 "Hook for functions attaching themselves to `M-left'.
13347 See `org-ctrl-c-ctrl-c-hook' for more information.")
13348 (defvar org-metaright-hook nil
13349 "Hook for functions attaching themselves to `M-right'.
13350 See `org-ctrl-c-ctrl-c-hook' for more information.")
13351 (defvar org-metaup-hook nil
13352 "Hook for functions attaching themselves to `M-up'.
13353 See `org-ctrl-c-ctrl-c-hook' for more information.")
13354 (defvar org-metadown-hook nil
13355 "Hook for functions attaching themselves to `M-down'.
13356 See `org-ctrl-c-ctrl-c-hook' for more information.")
13357 (defvar org-shiftmetaleft-hook nil
13358 "Hook for functions attaching themselves to `M-S-left'.
13359 See `org-ctrl-c-ctrl-c-hook' for more information.")
13360 (defvar org-shiftmetaright-hook nil
13361 "Hook for functions attaching themselves to `M-S-right'.
13362 See `org-ctrl-c-ctrl-c-hook' for more information.")
13363 (defvar org-shiftmetaup-hook nil
13364 "Hook for functions attaching themselves to `M-S-up'.
13365 See `org-ctrl-c-ctrl-c-hook' for more information.")
13366 (defvar org-shiftmetadown-hook nil
13367 "Hook for functions attaching themselves to `M-S-down'.
13368 See `org-ctrl-c-ctrl-c-hook' for more information.")
13369 (defvar org-metareturn-hook nil
13370 "Hook for functions attaching themselves to `M-RET'.
13371 See `org-ctrl-c-ctrl-c-hook' for more information.")
13373 (defun org-modifier-cursor-error ()
13374 "Throw an error, a modified cursor command was applied in wrong context."
13375 (error "This command is active in special context like tables, headlines or items"))
13377 (defun org-shiftselect-error ()
13378 "Throw an error because Shift-Cursor command was applied in wrong context."
13379 (if (and (boundp 'shift-select-mode) shift-select-mode)
13380 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13381 (error "This command works only in special context like headlines or timestamps.")))
13383 (defun org-call-for-shift-select (cmd)
13384 (let ((this-command-keys-shift-translated t))
13385 (call-interactively cmd)))
13387 (defun org-shifttab (&optional arg)
13388 "Global visibility cycling or move to previous table field.
13389 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13390 on context.
13391 See the individual commands for more information."
13392 (interactive "P")
13393 (cond
13394 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13395 ((integerp arg)
13396 (message "Content view to level: %d" arg)
13397 (org-content (prefix-numeric-value arg))
13398 (setq org-cycle-global-status 'overview))
13399 (t (call-interactively 'org-global-cycle))))
13401 (defun org-shiftmetaleft ()
13402 "Promote subtree or delete table column.
13403 Calls `org-promote-subtree', `org-outdent-item',
13404 or `org-table-delete-column', depending on context.
13405 See the individual commands for more information."
13406 (interactive)
13407 (cond
13408 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13409 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13410 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13411 ((org-at-item-p) (call-interactively 'org-outdent-item))
13412 (t (org-modifier-cursor-error))))
13414 (defun org-shiftmetaright ()
13415 "Demote subtree or insert table column.
13416 Calls `org-demote-subtree', `org-indent-item',
13417 or `org-table-insert-column', depending on context.
13418 See the individual commands for more information."
13419 (interactive)
13420 (cond
13421 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13422 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13423 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13424 ((org-at-item-p) (call-interactively 'org-indent-item))
13425 (t (org-modifier-cursor-error))))
13427 (defun org-shiftmetaup (&optional arg)
13428 "Move subtree up or kill table row.
13429 Calls `org-move-subtree-up' or `org-table-kill-row' or
13430 `org-move-item-up' depending on context. See the individual commands
13431 for more information."
13432 (interactive "P")
13433 (cond
13434 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13435 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13436 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13437 ((org-at-item-p) (call-interactively 'org-move-item-up))
13438 (t (org-modifier-cursor-error))))
13440 (defun org-shiftmetadown (&optional arg)
13441 "Move subtree down or insert table row.
13442 Calls `org-move-subtree-down' or `org-table-insert-row' or
13443 `org-move-item-down', depending on context. See the individual
13444 commands for more information."
13445 (interactive "P")
13446 (cond
13447 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13448 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13449 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13450 ((org-at-item-p) (call-interactively 'org-move-item-down))
13451 (t (org-modifier-cursor-error))))
13453 (defun org-metaleft (&optional arg)
13454 "Promote heading or move table column to left.
13455 Calls `org-do-promote' or `org-table-move-column', depending on context.
13456 With no specific context, calls the Emacs default `backward-word'.
13457 See the individual commands for more information."
13458 (interactive "P")
13459 (cond
13460 ((run-hook-with-args-until-success 'org-metaleft-hook))
13461 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13462 ((or (org-on-heading-p)
13463 (and (org-region-active-p)
13464 (save-excursion
13465 (goto-char (region-beginning))
13466 (org-on-heading-p))))
13467 (call-interactively 'org-do-promote))
13468 ((or (org-at-item-p)
13469 (and (org-region-active-p)
13470 (save-excursion
13471 (goto-char (region-beginning))
13472 (org-at-item-p))))
13473 (call-interactively 'org-outdent-item))
13474 (t (call-interactively 'backward-word))))
13476 (defun org-metaright (&optional arg)
13477 "Demote subtree or move table column to right.
13478 Calls `org-do-demote' or `org-table-move-column', depending on context.
13479 With no specific context, calls the Emacs default `forward-word'.
13480 See the individual commands for more information."
13481 (interactive "P")
13482 (cond
13483 ((run-hook-with-args-until-success 'org-metaright-hook))
13484 ((org-at-table-p) (call-interactively 'org-table-move-column))
13485 ((or (org-on-heading-p)
13486 (and (org-region-active-p)
13487 (save-excursion
13488 (goto-char (region-beginning))
13489 (org-on-heading-p))))
13490 (call-interactively 'org-do-demote))
13491 ((or (org-at-item-p)
13492 (and (org-region-active-p)
13493 (save-excursion
13494 (goto-char (region-beginning))
13495 (org-at-item-p))))
13496 (call-interactively 'org-indent-item))
13497 (t (call-interactively 'forward-word))))
13499 (defun org-metaup (&optional arg)
13500 "Move subtree up or move table row up.
13501 Calls `org-move-subtree-up' or `org-table-move-row' or
13502 `org-move-item-up', depending on context. See the individual commands
13503 for more information."
13504 (interactive "P")
13505 (cond
13506 ((run-hook-with-args-until-success 'org-metaup-hook))
13507 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13508 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13509 ((org-at-item-p) (call-interactively 'org-move-item-up))
13510 (t (transpose-lines 1) (beginning-of-line -1))))
13512 (defun org-metadown (&optional arg)
13513 "Move subtree down or move table row down.
13514 Calls `org-move-subtree-down' or `org-table-move-row' or
13515 `org-move-item-down', depending on context. See the individual
13516 commands for more information."
13517 (interactive "P")
13518 (cond
13519 ((run-hook-with-args-until-success 'org-metadown-hook))
13520 ((org-at-table-p) (call-interactively 'org-table-move-row))
13521 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13522 ((org-at-item-p) (call-interactively 'org-move-item-down))
13523 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13525 (defun org-shiftup (&optional arg)
13526 "Increase item in timestamp or increase priority of current headline.
13527 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13528 depending on context. See the individual commands for more information."
13529 (interactive "P")
13530 (cond
13531 ((and org-support-shift-select (org-region-active-p))
13532 (org-call-for-shift-select 'previous-line))
13533 ((org-at-timestamp-p t)
13534 (call-interactively (if org-edit-timestamp-down-means-later
13535 'org-timestamp-down 'org-timestamp-up)))
13536 ((and (not (eq org-support-shift-select 'always))
13537 (org-on-heading-p))
13538 (call-interactively 'org-priority-up))
13539 ((and (not org-support-shift-select) (org-at-item-p))
13540 (call-interactively 'org-previous-item))
13541 ((org-clocktable-try-shift 'up arg))
13542 (org-support-shift-select
13543 (org-call-for-shift-select 'previous-line))
13544 (t (org-shiftselect-error))))
13546 (defun org-shiftdown (&optional arg)
13547 "Decrease item in timestamp or decrease priority of current headline.
13548 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13549 depending on context. See the individual commands for more information."
13550 (interactive "P")
13551 (cond
13552 ((and org-support-shift-select (org-region-active-p))
13553 (org-call-for-shift-select 'next-line))
13554 ((org-at-timestamp-p t)
13555 (call-interactively (if org-edit-timestamp-down-means-later
13556 'org-timestamp-up 'org-timestamp-down)))
13557 ((and (not (eq org-support-shift-select 'always))
13558 (org-on-heading-p))
13559 (call-interactively 'org-priority-down))
13560 ((and (not org-support-shift-select) (org-at-item-p))
13561 (call-interactively 'org-next-item))
13562 ((org-clocktable-try-shift 'down arg))
13563 (org-support-shift-select
13564 (org-call-for-shift-select 'next-line))
13565 (t (org-shiftselect-error))))
13567 (defun org-shiftright (&optional arg)
13568 "Cycle the thing at point or in the current line, depending on context.
13569 Depending on context, this does one of the following:
13571 - switch a timestamp at point one day into the future
13572 - on a headline, switch to the next TODO keyword.
13573 - on an item, switch entire list to the next bullet type
13574 - on a property line, switch to the next allowed value
13575 - on a clocktable definition line, move time block into the future"
13576 (interactive "P")
13577 (cond
13578 ((and org-support-shift-select (org-region-active-p))
13579 (org-call-for-shift-select 'forward-char))
13580 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13581 ((and (not (eq org-support-shift-select 'always))
13582 (org-on-heading-p))
13583 (org-call-with-arg 'org-todo 'right))
13584 ((or (and org-support-shift-select
13585 (not (eq org-support-shift-select 'always))
13586 (org-at-item-bullet-p))
13587 (and (not org-support-shift-select) (org-at-item-p)))
13588 (org-call-with-arg 'org-cycle-list-bullet nil))
13589 ((and (not (eq org-support-shift-select 'always))
13590 (org-at-property-p))
13591 (call-interactively 'org-property-next-allowed-value))
13592 ((org-clocktable-try-shift 'right arg))
13593 (org-support-shift-select
13594 (org-call-for-shift-select 'forward-char))
13595 (t (org-shiftselect-error))))
13597 (defun org-shiftleft (&optional arg)
13598 "Cycle the thing at point or in the current line, depending on context.
13599 Depending on context, this does one of the following:
13601 - switch a timestamp at point one day into the past
13602 - on a headline, switch to the previous TODO keyword.
13603 - on an item, switch entire list to the previous bullet type
13604 - on a property line, switch to the previous allowed value
13605 - on a clocktable definition line, move time block into the past"
13606 (interactive "P")
13607 (cond
13608 ((and org-support-shift-select (org-region-active-p))
13609 (org-call-for-shift-select 'backward-char))
13610 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13611 ((and (not (eq org-support-shift-select 'always))
13612 (org-on-heading-p))
13613 (org-call-with-arg 'org-todo 'left))
13614 ((or (and org-support-shift-select
13615 (not (eq org-support-shift-select 'always))
13616 (org-at-item-bullet-p))
13617 (and (not org-support-shift-select) (org-at-item-p)))
13618 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13619 ((and (not (eq org-support-shift-select 'always))
13620 (org-at-property-p))
13621 (call-interactively 'org-property-previous-allowed-value))
13622 ((org-clocktable-try-shift 'left arg))
13623 (org-support-shift-select
13624 (org-call-for-shift-select 'backward-char))
13625 (t (org-shiftselect-error))))
13627 (defun org-shiftcontrolright ()
13628 "Switch to next TODO set."
13629 (interactive)
13630 (cond
13631 ((and org-support-shift-select (org-region-active-p))
13632 (org-call-for-shift-select 'forward-word))
13633 ((and (not (eq org-support-shift-select 'always))
13634 (org-on-heading-p))
13635 (org-call-with-arg 'org-todo 'nextset))
13636 (org-support-shift-select
13637 (org-call-for-shift-select 'forward-word))
13638 (t (org-shiftselect-error))))
13640 (defun org-shiftcontrolleft ()
13641 "Switch to previous TODO set."
13642 (interactive)
13643 (cond
13644 ((and org-support-shift-select (org-region-active-p))
13645 (org-call-for-shift-select 'backward-word))
13646 ((and (not (eq org-support-shift-select 'always))
13647 (org-on-heading-p))
13648 (org-call-with-arg 'org-todo 'previousset))
13649 (org-support-shift-select
13650 (org-call-for-shift-select 'backward-word))
13651 (t (org-shiftselect-error))))
13653 (defun org-ctrl-c-ret ()
13654 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13655 (interactive)
13656 (cond
13657 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13658 (t (call-interactively 'org-insert-heading))))
13660 (defun org-copy-special ()
13661 "Copy region in table or copy current subtree.
13662 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13663 See the individual commands for more information."
13664 (interactive)
13665 (call-interactively
13666 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13668 (defun org-cut-special ()
13669 "Cut region in table or cut current subtree.
13670 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13671 See the individual commands for more information."
13672 (interactive)
13673 (call-interactively
13674 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13676 (defun org-paste-special (arg)
13677 "Paste rectangular region into table, or past subtree relative to level.
13678 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13679 See the individual commands for more information."
13680 (interactive "P")
13681 (if (org-at-table-p)
13682 (org-table-paste-rectangle)
13683 (org-paste-subtree arg)))
13685 (defun org-edit-special ()
13686 "Call a special editor for the stuff at point.
13687 When at a table, call the formula editor with `org-table-edit-formulas'.
13688 When at the first line of an src example, call `org-edit-src-code'.
13689 When in an #+include line, visit the include file. Otherwise call
13690 `ffap' to visit the file at point."
13691 (interactive)
13692 (cond
13693 ((org-at-table-p)
13694 (call-interactively 'org-table-edit-formulas))
13695 ((save-excursion
13696 (beginning-of-line 1)
13697 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13698 (find-file (org-trim (match-string 1))))
13699 ((org-edit-src-code))
13700 ((org-edit-fixed-width-region))
13701 (t (call-interactively 'ffap))))
13704 (defun org-ctrl-c-ctrl-c (&optional arg)
13705 "Set tags in headline, or update according to changed information at point.
13707 This command does many different things, depending on context:
13709 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
13710 this is what we do.
13712 - If the cursor is in a headline, prompt for tags and insert them
13713 into the current line, aligned to `org-tags-column'. When called
13714 with prefix arg, realign all tags in the current buffer.
13716 - If the cursor is in one of the special #+KEYWORD lines, this
13717 triggers scanning the buffer for these lines and updating the
13718 information.
13720 - If the cursor is inside a table, realign the table. This command
13721 works even if the automatic table editor has been turned off.
13723 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13724 the entire table.
13726 - If the cursor is at a footnote reference or definition, jump to
13727 the corresponding definition or references, respectively.
13729 - If the cursor is a the beginning of a dynamic block, update it.
13731 - If the cursor is inside a table created by the table.el package,
13732 activate that table.
13734 - If the current buffer is a remember buffer, close note and file
13735 it. A prefix argument of 1 files to the default location
13736 without further interaction. A prefix argument of 2 files to
13737 the currently clocking task.
13739 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13740 links in this buffer.
13742 - If the cursor is on a numbered item in a plain list, renumber the
13743 ordered list.
13745 - If the cursor is on a checkbox, toggle it."
13746 (interactive "P")
13747 (let ((org-enable-table-editor t))
13748 (cond
13749 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13750 org-occur-highlights
13751 org-latex-fragment-image-overlays)
13752 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13753 (org-remove-occur-highlights)
13754 (org-remove-latex-fragment-image-overlays)
13755 (message "Temporary highlights/overlays removed from current buffer"))
13756 ((and (local-variable-p 'org-finish-function (current-buffer))
13757 (fboundp org-finish-function))
13758 (funcall org-finish-function))
13759 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
13760 ((org-at-property-p)
13761 (call-interactively 'org-property-action))
13762 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13763 ((org-on-heading-p) (call-interactively 'org-set-tags))
13764 ((org-at-table.el-p)
13765 (require 'table)
13766 (beginning-of-line 1)
13767 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13768 (call-interactively 'table-recognize-table))
13769 ((org-at-table-p)
13770 (org-table-maybe-eval-formula)
13771 (if arg
13772 (call-interactively 'org-table-recalculate)
13773 (org-table-maybe-recalculate-line))
13774 (call-interactively 'org-table-align))
13775 ((or (org-footnote-at-reference-p)
13776 (org-footnote-at-definition-p))
13777 (call-interactively 'org-footnote-action))
13778 ((org-at-item-checkbox-p)
13779 (call-interactively 'org-toggle-checkbox))
13780 ((org-at-item-p)
13781 (if arg
13782 (call-interactively 'org-toggle-checkbox)
13783 (call-interactively 'org-maybe-renumber-ordered-list)))
13784 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13785 ;; Dynamic block
13786 (beginning-of-line 1)
13787 (save-excursion (org-update-dblock)))
13788 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13789 (cond
13790 ((equal (match-string 1) "TBLFM")
13791 ;; Recalculate the table before this line
13792 (save-excursion
13793 (beginning-of-line 1)
13794 (skip-chars-backward " \r\n\t")
13795 (if (org-at-table-p)
13796 (org-call-with-arg 'org-table-recalculate t))))
13798 ; (org-set-regexps-and-options)
13799 ; (org-restart-font-lock)
13800 (let ((org-inhibit-startup t)) (org-mode-restart))
13801 (message "Local setup has been refreshed"))))
13802 (t (error "C-c C-c can do nothing useful at this location.")))))
13804 (defun org-mode-restart ()
13805 "Restart Org-mode, to scan again for special lines.
13806 Also updates the keyword regular expressions."
13807 (interactive)
13808 (org-mode)
13809 (message "Org-mode restarted"))
13811 (defun org-kill-note-or-show-branches ()
13812 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13813 (interactive)
13814 (if (not org-finish-function)
13815 (call-interactively 'show-branches)
13816 (let ((org-note-abort t))
13817 (funcall org-finish-function))))
13819 (defun org-return (&optional indent)
13820 "Goto next table row or insert a newline.
13821 Calls `org-table-next-row' or `newline', depending on context.
13822 See the individual commands for more information."
13823 (interactive)
13824 (cond
13825 ((bobp) (if indent (newline-and-indent) (newline)))
13826 ((org-at-table-p)
13827 (org-table-justify-field-maybe)
13828 (call-interactively 'org-table-next-row))
13829 ((and org-return-follows-link
13830 (eq (get-text-property (point) 'face) 'org-link))
13831 (call-interactively 'org-open-at-point))
13832 ((and (org-at-heading-p)
13833 (looking-at
13834 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13835 (org-show-entry)
13836 (end-of-line 1)
13837 (newline))
13838 (t (if indent (newline-and-indent) (newline)))))
13840 (defun org-return-indent ()
13841 "Goto next table row or insert a newline and indent.
13842 Calls `org-table-next-row' or `newline-and-indent', depending on
13843 context. See the individual commands for more information."
13844 (interactive)
13845 (org-return t))
13847 (defun org-ctrl-c-star ()
13848 "Compute table, or change heading status of lines.
13849 Calls `org-table-recalculate' or `org-toggle-heading',
13850 depending on context."
13851 (interactive)
13852 (cond
13853 ((org-at-table-p)
13854 (call-interactively 'org-table-recalculate))
13856 ;; Convert all lines in region to list items
13857 (call-interactively 'org-toggle-heading))))
13859 (defun org-ctrl-c-minus ()
13860 "Insert separator line in table or modify bullet status of line.
13861 Also turns a plain line or a region of lines into list items.
13862 Calls `org-table-insert-hline', `org-toggle-item', or
13863 `org-cycle-list-bullet', depending on context."
13864 (interactive)
13865 (cond
13866 ((org-at-table-p)
13867 (call-interactively 'org-table-insert-hline))
13868 ((org-region-active-p)
13869 (call-interactively 'org-toggle-item))
13870 ((org-in-item-p)
13871 (call-interactively 'org-cycle-list-bullet))
13873 (call-interactively 'org-toggle-item))))
13875 (defun org-toggle-item ()
13876 "Convert headings or normal lines to items, items to normal lines.
13877 If there is no active region, only the current line is considered.
13879 If the first line in the region is a headline, convert all headlines to items.
13881 If the first line in the region is an item, convert all items to normal lines.
13883 If the first line is normal text, add an item bullet to each line."
13884 (interactive)
13885 (let (l2 l beg end)
13886 (if (org-region-active-p)
13887 (setq beg (region-beginning) end (region-end))
13888 (setq beg (point-at-bol)
13889 end (min (1+ (point-at-eol)) (point-max))))
13890 (save-excursion
13891 (goto-char end)
13892 (setq l2 (org-current-line))
13893 (goto-char beg)
13894 (beginning-of-line 1)
13895 (setq l (1- (org-current-line)))
13896 (if (org-at-item-p)
13897 ;; We already have items, de-itemize
13898 (while (< (setq l (1+ l)) l2)
13899 (when (org-at-item-p)
13900 (goto-char (match-beginning 2))
13901 (delete-region (match-beginning 2) (match-end 2))
13902 (and (looking-at "[ \t]+") (replace-match "")))
13903 (beginning-of-line 2))
13904 (if (org-on-heading-p)
13905 ;; Headings, convert to items
13906 (while (< (setq l (1+ l)) l2)
13907 (if (looking-at org-outline-regexp)
13908 (replace-match "- " t t))
13909 (beginning-of-line 2))
13910 ;; normal lines, turn them into items
13911 (while (< (setq l (1+ l)) l2)
13912 (unless (org-at-item-p)
13913 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13914 (replace-match "\\1- \\2")))
13915 (beginning-of-line 2)))))))
13917 (defun org-toggle-heading (&optional nstars)
13918 "Convert headings to normal text, or items or text to headings.
13919 If there is no active region, only the current line is considered.
13921 If the first line is a heading, remove the stars from all headlines
13922 in the region.
13924 If the first line is a plain list item, turn all plain list items into
13925 headings.
13927 If the first line is a normal line, turn each and every line in the region
13928 into a heading.
13930 When converting a line into a heading, the number of stars is chosen
13931 such that the lines become children of the current entry. However, when
13932 a prefix argument is given, its value determines the number of stars to add."
13933 (interactive "P")
13934 (let (l2 l itemp beg end)
13935 (if (org-region-active-p)
13936 (setq beg (region-beginning) end (region-end))
13937 (setq beg (point-at-bol)
13938 end (min (1+ (point-at-eol)) (point-max))))
13939 (save-excursion
13940 (goto-char end)
13941 (setq l2 (org-current-line))
13942 (goto-char beg)
13943 (beginning-of-line 1)
13944 (setq l (1- (org-current-line)))
13945 (if (org-on-heading-p)
13946 ;; We already have headlines, de-star them
13947 (while (< (setq l (1+ l)) l2)
13948 (when (org-on-heading-p t)
13949 (and (looking-at outline-regexp) (replace-match "")))
13950 (beginning-of-line 2))
13951 (setq itemp (org-at-item-p))
13952 (let* ((stars
13953 (if nstars
13954 (make-string (prefix-numeric-value current-prefix-arg)
13956 (save-excursion
13957 (re-search-backward org-complex-heading-regexp nil t)
13958 (or (match-string 1) "*"))))
13959 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13960 (rpl (concat stars add-stars " ")))
13961 (while (< (setq l (1+ l)) l2)
13962 (if itemp
13963 (and (org-at-item-p) (replace-match rpl t t))
13964 (unless (org-on-heading-p)
13965 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13966 (replace-match (concat rpl (match-string 2))))))
13967 (beginning-of-line 2)))))))
13969 (defun org-meta-return (&optional arg)
13970 "Insert a new heading or wrap a region in a table.
13971 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13972 See the individual commands for more information."
13973 (interactive "P")
13974 (cond
13975 ((run-hook-with-args-until-success 'org-metareturn-hook))
13976 ((org-at-table-p)
13977 (call-interactively 'org-table-wrap-region))
13978 (t (call-interactively 'org-insert-heading))))
13980 ;;; Menu entries
13982 ;; Define the Org-mode menus
13983 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13984 '("Tbl"
13985 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13986 ["Next Field" org-cycle (org-at-table-p)]
13987 ["Previous Field" org-shifttab (org-at-table-p)]
13988 ["Next Row" org-return (org-at-table-p)]
13989 "--"
13990 ["Blank Field" org-table-blank-field (org-at-table-p)]
13991 ["Edit Field" org-table-edit-field (org-at-table-p)]
13992 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13993 "--"
13994 ("Column"
13995 ["Move Column Left" org-metaleft (org-at-table-p)]
13996 ["Move Column Right" org-metaright (org-at-table-p)]
13997 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13998 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13999 ("Row"
14000 ["Move Row Up" org-metaup (org-at-table-p)]
14001 ["Move Row Down" org-metadown (org-at-table-p)]
14002 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14003 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14004 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14005 "--"
14006 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14007 ("Rectangle"
14008 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14009 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14010 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14011 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14012 "--"
14013 ("Calculate"
14014 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14015 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14016 ["Edit Formulas" org-edit-special (org-at-table-p)]
14017 "--"
14018 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14019 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14020 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14021 "--"
14022 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14023 "--"
14024 ["Sum Column/Rectangle" org-table-sum
14025 (or (org-at-table-p) (org-region-active-p))]
14026 ["Which Column?" org-table-current-column (org-at-table-p)])
14027 ["Debug Formulas"
14028 org-table-toggle-formula-debugger
14029 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14030 ["Show Col/Row Numbers"
14031 org-table-toggle-coordinate-overlays
14032 :style toggle
14033 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14034 "--"
14035 ["Create" org-table-create (and (not (org-at-table-p))
14036 org-enable-table-editor)]
14037 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14038 ["Import from File" org-table-import (not (org-at-table-p))]
14039 ["Export to File" org-table-export (org-at-table-p)]
14040 "--"
14041 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14043 (easy-menu-define org-org-menu org-mode-map "Org menu"
14044 '("Org"
14045 ("Show/Hide"
14046 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14047 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14048 ["Sparse Tree..." org-sparse-tree t]
14049 ["Reveal Context" org-reveal t]
14050 ["Show All" show-all t]
14051 "--"
14052 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14053 "--"
14054 ["New Heading" org-insert-heading t]
14055 ("Navigate Headings"
14056 ["Up" outline-up-heading t]
14057 ["Next" outline-next-visible-heading t]
14058 ["Previous" outline-previous-visible-heading t]
14059 ["Next Same Level" outline-forward-same-level t]
14060 ["Previous Same Level" outline-backward-same-level t]
14061 "--"
14062 ["Jump" org-goto t])
14063 ("Edit Structure"
14064 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14065 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14066 "--"
14067 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14068 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14069 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14070 "--"
14071 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14072 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14073 ["Demote Heading" org-metaright (not (org-at-table-p))]
14074 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14075 "--"
14076 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14077 "--"
14078 ["Convert to odd levels" org-convert-to-odd-levels t]
14079 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14080 ("Editing"
14081 ["Emphasis..." org-emphasize t]
14082 ["Edit Source Example" org-edit-special t]
14083 "--"
14084 ["Footnote new/jump" org-footnote-action t]
14085 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14086 ("Archive"
14087 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14088 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14089 ; :active t :keys "C-u C-c C-x C-a"]
14090 ["Sparse trees open ARCHIVE trees"
14091 (setq org-sparse-tree-open-archived-trees
14092 (not org-sparse-tree-open-archived-trees))
14093 :style toggle :selected org-sparse-tree-open-archived-trees]
14094 ["Cycling opens ARCHIVE trees"
14095 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14096 :style toggle :selected org-cycle-open-archived-trees]
14097 "--"
14098 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14099 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14100 ; ["Check and Move Children" (org-archive-subtree '(4))
14101 ; :active t :keys "C-u C-c C-x C-s"]
14103 "--"
14104 ("TODO Lists"
14105 ["TODO/DONE/-" org-todo t]
14106 ("Select keyword"
14107 ["Next keyword" org-shiftright (org-on-heading-p)]
14108 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14109 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14110 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14111 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14112 ["Show TODO Tree" org-show-todo-tree t]
14113 ["Global TODO list" org-todo-list t]
14114 "--"
14115 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14116 :selected org-enforce-todo-dependencies :style toggle :active t]
14117 "Settings for tree at point"
14118 ["Do Children sequentially" org-toggle-ordered-property :style radio
14119 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14120 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14121 ["Do Children parallel" org-toggle-ordered-property :style radio
14122 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14123 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14124 "--"
14125 ["Set Priority" org-priority t]
14126 ["Priority Up" org-shiftup t]
14127 ["Priority Down" org-shiftdown t])
14128 ("TAGS and Properties"
14129 ["Set Tags" org-set-tags-command t]
14130 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14131 "--"
14132 ["Set property" org-set-property t]
14133 ["Column view of properties" org-columns t]
14134 ["Insert Column View DBlock" org-insert-columns-dblock t])
14135 ("Dates and Scheduling"
14136 ["Timestamp" org-time-stamp t]
14137 ["Timestamp (inactive)" org-time-stamp-inactive t]
14138 ("Change Date"
14139 ["1 Day Later" org-shiftright t]
14140 ["1 Day Earlier" org-shiftleft t]
14141 ["1 ... Later" org-shiftup t]
14142 ["1 ... Earlier" org-shiftdown t])
14143 ["Compute Time Range" org-evaluate-time-range t]
14144 ["Schedule Item" org-schedule t]
14145 ["Deadline" org-deadline t]
14146 "--"
14147 ["Custom time format" org-toggle-time-stamp-overlays
14148 :style radio :selected org-display-custom-times]
14149 "--"
14150 ["Goto Calendar" org-goto-calendar t]
14151 ["Date from Calendar" org-date-from-calendar t]
14152 "--"
14153 ["Start/Restart Timer" org-timer-start t]
14154 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14155 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14156 ["Insert Timer String" org-timer t]
14157 ["Insert Timer Item" org-timer-item t])
14158 ("Logging work"
14159 ["Clock in" org-clock-in t]
14160 ["Clock out" org-clock-out t]
14161 ["Clock cancel" org-clock-cancel t]
14162 ["Goto running clock" org-clock-goto t]
14163 ["Display times" org-clock-display t]
14164 ["Create clock table" org-clock-report t]
14165 "--"
14166 ["Record DONE time"
14167 (progn (setq org-log-done (not org-log-done))
14168 (message "Switching to %s will %s record a timestamp"
14169 (car org-done-keywords)
14170 (if org-log-done "automatically" "not")))
14171 :style toggle :selected org-log-done])
14172 "--"
14173 ["Agenda Command..." org-agenda t]
14174 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14175 ("File List for Agenda")
14176 ("Special views current file"
14177 ["TODO Tree" org-show-todo-tree t]
14178 ["Check Deadlines" org-check-deadlines t]
14179 ["Timeline" org-timeline t]
14180 ["Tags Tree" org-tags-sparse-tree t])
14181 "--"
14182 ("Hyperlinks"
14183 ["Store Link (Global)" org-store-link t]
14184 ["Insert Link" org-insert-link t]
14185 ["Follow Link" org-open-at-point t]
14186 "--"
14187 ["Next link" org-next-link t]
14188 ["Previous link" org-previous-link t]
14189 "--"
14190 ["Descriptive Links"
14191 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14192 :style radio
14193 :selected (member '(org-link) buffer-invisibility-spec)]
14194 ["Literal Links"
14195 (progn
14196 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14197 :style radio
14198 :selected (not (member '(org-link) buffer-invisibility-spec))])
14199 "--"
14200 ["Export/Publish..." org-export t]
14201 ("LaTeX"
14202 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14203 :selected org-cdlatex-mode]
14204 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14205 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14206 ["Modify math symbol" org-cdlatex-math-modify
14207 (org-inside-LaTeX-fragment-p)]
14208 ["Export LaTeX fragments as images"
14209 (if (featurep 'org-exp)
14210 (setq org-export-with-LaTeX-fragments
14211 (not org-export-with-LaTeX-fragments))
14212 (require 'org-exp))
14213 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14214 org-export-with-LaTeX-fragments)])
14215 "--"
14216 ("Documentation"
14217 ["Show Version" org-version t]
14218 ["Info Documentation" org-info t])
14219 ("Customize"
14220 ["Browse Org Group" org-customize t]
14221 "--"
14222 ["Expand This Menu" org-create-customize-menu
14223 (fboundp 'customize-menu-create)])
14224 "--"
14225 ["Refresh setup" org-mode-restart t]
14228 (defun org-info (&optional node)
14229 "Read documentation for Org-mode in the info system.
14230 With optional NODE, go directly to that node."
14231 (interactive)
14232 (info (format "(org)%s" (or node ""))))
14234 (defun org-install-agenda-files-menu ()
14235 (let ((bl (buffer-list)))
14236 (save-excursion
14237 (while bl
14238 (set-buffer (pop bl))
14239 (if (org-mode-p) (setq bl nil)))
14240 (when (org-mode-p)
14241 (easy-menu-change
14242 '("Org") "File List for Agenda"
14243 (append
14244 (list
14245 ["Edit File List" (org-edit-agenda-file-list) t]
14246 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14247 ["Remove Current File from List" org-remove-file t]
14248 ["Cycle through agenda files" org-cycle-agenda-files t]
14249 ["Occur in all agenda files" org-occur-in-agenda-files t]
14250 "--")
14251 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14253 ;;;; Documentation
14255 ;;;###autoload
14256 (defun org-require-autoloaded-modules ()
14257 (interactive)
14258 (mapc 'require
14259 '(org-agenda org-archive org-attach org-clock org-colview
14260 org-exp org-id org-export-latex org-publish
14261 org-remember org-table org-timer)))
14263 ;;;###autoload
14264 (defun org-reload (&optional uncompiled)
14265 "Reload all org lisp files.
14266 With prefix arg UNCOMPILED, load the uncompiled versions."
14267 (interactive "P")
14268 (require 'find-func)
14269 (let* ((dir (file-name-directory (find-library-name "org")))
14270 (files (directory-files dir t "\\.el\\'"))
14271 (remove-re (concat (if (featurep 'xemacs)
14272 "org-colview" "org-colview-xemacs")
14273 "\\'")))
14274 (setq files (mapcar 'file-name-sans-extension files))
14275 (setq files (mapcar
14276 (lambda (x) (if (string-match remove-re x) nil x))
14277 files))
14278 (setq files (delq nil files))
14279 (mapc
14280 (lambda (f)
14281 (if (and (not uncompiled)
14282 (file-exists-p (concat f ".elc")))
14283 (load (concat f ".elc") nil nil t)
14284 (load (concat f ".el") nil nil t)))
14285 files)))
14287 ;;;###autoload
14288 (defun org-customize ()
14289 "Call the customize function with org as argument."
14290 (interactive)
14291 (org-load-modules-maybe)
14292 (org-require-autoloaded-modules)
14293 (customize-browse 'org))
14295 (defun org-create-customize-menu ()
14296 "Create a full customization menu for Org-mode, insert it into the menu."
14297 (interactive)
14298 (org-load-modules-maybe)
14299 (org-require-autoloaded-modules)
14300 (if (fboundp 'customize-menu-create)
14301 (progn
14302 (easy-menu-change
14303 '("Org") "Customize"
14304 `(["Browse Org group" org-customize t]
14305 "--"
14306 ,(customize-menu-create 'org)
14307 ["Set" Custom-set t]
14308 ["Save" Custom-save t]
14309 ["Reset to Current" Custom-reset-current t]
14310 ["Reset to Saved" Custom-reset-saved t]
14311 ["Reset to Standard Settings" Custom-reset-standard t]))
14312 (message "\"Org\"-menu now contains full customization menu"))
14313 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14315 ;;;; Miscellaneous stuff
14317 ;;; Generally useful functions
14319 (defun org-find-text-property-in-string (prop s)
14320 "Return the first non-nil value of property PROP in string S."
14321 (or (get-text-property 0 prop s)
14322 (get-text-property (or (next-single-property-change 0 prop s) 0)
14323 prop s)))
14325 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14326 "Display the given MESSAGE as a warning."
14327 (if (fboundp 'display-warning)
14328 (display-warning 'org message
14329 (if (featurep 'xemacs)
14330 'warning
14331 :warning))
14332 (let ((buf (get-buffer-create "*Org warnings*")))
14333 (with-current-buffer buf
14334 (goto-char (point-max))
14335 (insert "Warning (Org): " message)
14336 (unless (bolp)
14337 (newline)))
14338 (display-buffer buf)
14339 (sit-for 0))))
14341 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14342 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14343 (if (and marker (marker-buffer marker)
14344 (buffer-live-p (marker-buffer marker)))
14345 (progn
14346 (switch-to-buffer (marker-buffer marker))
14347 (if (or (> marker (point-max)) (< marker (point-min)))
14348 (widen))
14349 (goto-char marker)
14350 (org-show-context 'org-goto))
14351 (if bookmark
14352 (bookmark-jump bookmark)
14353 (error "Cannot find location"))))
14355 (defun org-quote-csv-field (s)
14356 "Quote field for inclusion in CSV material."
14357 (if (string-match "[\",]" s)
14358 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14361 (defun org-plist-delete (plist property)
14362 "Delete PROPERTY from PLIST.
14363 This is in contrast to merely setting it to 0."
14364 (let (p)
14365 (while plist
14366 (if (not (eq property (car plist)))
14367 (setq p (plist-put p (car plist) (nth 1 plist))))
14368 (setq plist (cddr plist)))
14371 (defun org-force-self-insert (N)
14372 "Needed to enforce self-insert under remapping."
14373 (interactive "p")
14374 (self-insert-command N))
14376 (defun org-string-width (s)
14377 "Compute width of string, ignoring invisible characters.
14378 This ignores character with invisibility property `org-link', and also
14379 characters with property `org-cwidth', because these will become invisible
14380 upon the next fontification round."
14381 (let (b l)
14382 (when (or (eq t buffer-invisibility-spec)
14383 (assq 'org-link buffer-invisibility-spec))
14384 (while (setq b (text-property-any 0 (length s)
14385 'invisible 'org-link s))
14386 (setq s (concat (substring s 0 b)
14387 (substring s (or (next-single-property-change
14388 b 'invisible s) (length s)))))))
14389 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14390 (setq s (concat (substring s 0 b)
14391 (substring s (or (next-single-property-change
14392 b 'org-cwidth s) (length s))))))
14393 (setq l (string-width s) b -1)
14394 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14395 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14398 (defun org-get-indentation (&optional line)
14399 "Get the indentation of the current line, interpreting tabs.
14400 When LINE is given, assume it represents a line and compute its indentation."
14401 (if line
14402 (if (string-match "^ *" (org-remove-tabs line))
14403 (match-end 0))
14404 (save-excursion
14405 (beginning-of-line 1)
14406 (skip-chars-forward " \t")
14407 (current-column))))
14409 (defun org-remove-tabs (s &optional width)
14410 "Replace tabulators in S with spaces.
14411 Assumes that s is a single line, starting in column 0."
14412 (setq width (or width tab-width))
14413 (while (string-match "\t" s)
14414 (setq s (replace-match
14415 (make-string
14416 (- (* width (/ (+ (match-beginning 0) width) width))
14417 (match-beginning 0)) ?\ )
14418 t t s)))
14421 (defun org-fix-indentation (line ind)
14422 "Fix indentation in LINE.
14423 IND is a cons cell with target and minimum indentation.
14424 If the current indentation in LINE is smaller than the minimum,
14425 leave it alone. If it is larger than ind, set it to the target."
14426 (let* ((l (org-remove-tabs line))
14427 (i (org-get-indentation l))
14428 (i1 (car ind)) (i2 (cdr ind)))
14429 (if (>= i i2) (setq l (substring line i2)))
14430 (if (> i1 0)
14431 (concat (make-string i1 ?\ ) l)
14432 l)))
14434 (defun org-base-buffer (buffer)
14435 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14436 (if (not buffer)
14437 buffer
14438 (or (buffer-base-buffer buffer)
14439 buffer)))
14441 (defun org-trim (s)
14442 "Remove whitespace at beginning and end of string."
14443 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14444 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14447 (defun org-wrap (string &optional width lines)
14448 "Wrap string to either a number of lines, or a width in characters.
14449 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14450 that costs. If there is a word longer than WIDTH, the text is actually
14451 wrapped to the length of that word.
14452 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14453 many lines, whatever width that takes.
14454 The return value is a list of lines, without newlines at the end."
14455 (let* ((words (org-split-string string "[ \t\n]+"))
14456 (maxword (apply 'max (mapcar 'org-string-width words)))
14457 w ll)
14458 (cond (width
14459 (org-do-wrap words (max maxword width)))
14460 (lines
14461 (setq w maxword)
14462 (setq ll (org-do-wrap words maxword))
14463 (if (<= (length ll) lines)
14465 (setq ll words)
14466 (while (> (length ll) lines)
14467 (setq w (1+ w))
14468 (setq ll (org-do-wrap words w)))
14469 ll))
14470 (t (error "Cannot wrap this")))))
14472 (defun org-do-wrap (words width)
14473 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14474 (let (lines line)
14475 (while words
14476 (setq line (pop words))
14477 (while (and words (< (+ (length line) (length (car words))) width))
14478 (setq line (concat line " " (pop words))))
14479 (setq lines (push line lines)))
14480 (nreverse lines)))
14482 (defun org-split-string (string &optional separators)
14483 "Splits STRING into substrings at SEPARATORS.
14484 No empty strings are returned if there are matches at the beginning
14485 and end of string."
14486 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14487 (start 0)
14488 notfirst
14489 (list nil))
14490 (while (and (string-match rexp string
14491 (if (and notfirst
14492 (= start (match-beginning 0))
14493 (< start (length string)))
14494 (1+ start) start))
14495 (< (match-beginning 0) (length string)))
14496 (setq notfirst t)
14497 (or (eq (match-beginning 0) 0)
14498 (and (eq (match-beginning 0) (match-end 0))
14499 (eq (match-beginning 0) start))
14500 (setq list
14501 (cons (substring string start (match-beginning 0))
14502 list)))
14503 (setq start (match-end 0)))
14504 (or (eq start (length string))
14505 (setq list
14506 (cons (substring string start)
14507 list)))
14508 (nreverse list)))
14510 (defun org-context ()
14511 "Return a list of contexts of the current cursor position.
14512 If several contexts apply, all are returned.
14513 Each context entry is a list with a symbol naming the context, and
14514 two positions indicating start and end of the context. Possible
14515 contexts are:
14517 :headline anywhere in a headline
14518 :headline-stars on the leading stars in a headline
14519 :todo-keyword on a TODO keyword (including DONE) in a headline
14520 :tags on the TAGS in a headline
14521 :priority on the priority cookie in a headline
14522 :item on the first line of a plain list item
14523 :item-bullet on the bullet/number of a plain list item
14524 :checkbox on the checkbox in a plain list item
14525 :table in an org-mode table
14526 :table-special on a special filed in a table
14527 :table-table in a table.el table
14528 :link on a hyperlink
14529 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14530 :target on a <<target>>
14531 :radio-target on a <<<radio-target>>>
14532 :latex-fragment on a LaTeX fragment
14533 :latex-preview on a LaTeX fragment with overlayed preview image
14535 This function expects the position to be visible because it uses font-lock
14536 faces as a help to recognize the following contexts: :table-special, :link,
14537 and :keyword."
14538 (let* ((f (get-text-property (point) 'face))
14539 (faces (if (listp f) f (list f)))
14540 (p (point)) clist o)
14541 ;; First the large context
14542 (cond
14543 ((org-on-heading-p t)
14544 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14545 (when (progn
14546 (beginning-of-line 1)
14547 (looking-at org-todo-line-tags-regexp))
14548 (push (org-point-in-group p 1 :headline-stars) clist)
14549 (push (org-point-in-group p 2 :todo-keyword) clist)
14550 (push (org-point-in-group p 4 :tags) clist))
14551 (goto-char p)
14552 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14553 (if (looking-at "\\[#[A-Z0-9]\\]")
14554 (push (org-point-in-group p 0 :priority) clist)))
14556 ((org-at-item-p)
14557 (push (org-point-in-group p 2 :item-bullet) clist)
14558 (push (list :item (point-at-bol)
14559 (save-excursion (org-end-of-item) (point)))
14560 clist)
14561 (and (org-at-item-checkbox-p)
14562 (push (org-point-in-group p 0 :checkbox) clist)))
14564 ((org-at-table-p)
14565 (push (list :table (org-table-begin) (org-table-end)) clist)
14566 (if (memq 'org-formula faces)
14567 (push (list :table-special
14568 (previous-single-property-change p 'face)
14569 (next-single-property-change p 'face)) clist)))
14570 ((org-at-table-p 'any)
14571 (push (list :table-table) clist)))
14572 (goto-char p)
14574 ;; Now the small context
14575 (cond
14576 ((org-at-timestamp-p)
14577 (push (org-point-in-group p 0 :timestamp) clist))
14578 ((memq 'org-link faces)
14579 (push (list :link
14580 (previous-single-property-change p 'face)
14581 (next-single-property-change p 'face)) clist))
14582 ((memq 'org-special-keyword faces)
14583 (push (list :keyword
14584 (previous-single-property-change p 'face)
14585 (next-single-property-change p 'face)) clist))
14586 ((org-on-target-p)
14587 (push (org-point-in-group p 0 :target) clist)
14588 (goto-char (1- (match-beginning 0)))
14589 (if (looking-at org-radio-target-regexp)
14590 (push (org-point-in-group p 0 :radio-target) clist))
14591 (goto-char p))
14592 ((setq o (car (delq nil
14593 (mapcar
14594 (lambda (x)
14595 (if (memq x org-latex-fragment-image-overlays) x))
14596 (org-overlays-at (point))))))
14597 (push (list :latex-fragment
14598 (org-overlay-start o) (org-overlay-end o)) clist)
14599 (push (list :latex-preview
14600 (org-overlay-start o) (org-overlay-end o)) clist))
14601 ((org-inside-LaTeX-fragment-p)
14602 ;; FIXME: positions wrong.
14603 (push (list :latex-fragment (point) (point)) clist)))
14605 (setq clist (nreverse (delq nil clist)))
14606 clist))
14608 ;; FIXME: Compare with at-regexp-p Do we need both?
14609 (defun org-in-regexp (re &optional nlines visually)
14610 "Check if point is inside a match of regexp.
14611 Normally only the current line is checked, but you can include NLINES extra
14612 lines both before and after point into the search.
14613 If VISUALLY is set, require that the cursor is not after the match but
14614 really on, so that the block visually is on the match."
14615 (catch 'exit
14616 (let ((pos (point))
14617 (eol (point-at-eol (+ 1 (or nlines 0))))
14618 (inc (if visually 1 0)))
14619 (save-excursion
14620 (beginning-of-line (- 1 (or nlines 0)))
14621 (while (re-search-forward re eol t)
14622 (if (and (<= (match-beginning 0) pos)
14623 (>= (+ inc (match-end 0)) pos))
14624 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14626 (defun org-at-regexp-p (regexp)
14627 "Is point inside a match of REGEXP in the current line?"
14628 (catch 'exit
14629 (save-excursion
14630 (let ((pos (point)) (end (point-at-eol)))
14631 (beginning-of-line 1)
14632 (while (re-search-forward regexp end t)
14633 (if (and (<= (match-beginning 0) pos)
14634 (>= (match-end 0) pos))
14635 (throw 'exit t)))
14636 nil))))
14638 (defun org-occur-in-agenda-files (regexp &optional nlines)
14639 "Call `multi-occur' with buffers for all agenda files."
14640 (interactive "sOrg-files matching: \np")
14641 (let* ((files (org-agenda-files))
14642 (tnames (mapcar 'file-truename files))
14643 (extra org-agenda-text-search-extra-files)
14645 (when (eq (car extra) 'agenda-archives)
14646 (setq extra (cdr extra))
14647 (setq files (org-add-archive-files files)))
14648 (while (setq f (pop extra))
14649 (unless (member (file-truename f) tnames)
14650 (add-to-list 'files f 'append)
14651 (add-to-list 'tnames (file-truename f) 'append)))
14652 (multi-occur
14653 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14654 regexp)))
14656 (if (boundp 'occur-mode-find-occurrence-hook)
14657 ;; Emacs 23
14658 (add-hook 'occur-mode-find-occurrence-hook
14659 (lambda ()
14660 (when (org-mode-p)
14661 (org-reveal))))
14662 ;; Emacs 22
14663 (defadvice occur-mode-goto-occurrence
14664 (after org-occur-reveal activate)
14665 (and (org-mode-p) (org-reveal)))
14666 (defadvice occur-mode-goto-occurrence-other-window
14667 (after org-occur-reveal activate)
14668 (and (org-mode-p) (org-reveal)))
14669 (defadvice occur-mode-display-occurrence
14670 (after org-occur-reveal activate)
14671 (when (org-mode-p)
14672 (let ((pos (occur-mode-find-occurrence)))
14673 (with-current-buffer (marker-buffer pos)
14674 (save-excursion
14675 (goto-char pos)
14676 (org-reveal)))))))
14678 (defun org-uniquify (list)
14679 "Remove duplicate elements from LIST."
14680 (let (res)
14681 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14682 res))
14684 (defun org-delete-all (elts list)
14685 "Remove all elements in ELTS from LIST."
14686 (while elts
14687 (setq list (delete (pop elts) list)))
14688 list)
14690 (defun org-back-over-empty-lines ()
14691 "Move backwards over whitespace, to the beginning of the first empty line.
14692 Returns the number of empty lines passed."
14693 (let ((pos (point)))
14694 (skip-chars-backward " \t\n\r")
14695 (beginning-of-line 2)
14696 (goto-char (min (point) pos))
14697 (count-lines (point) pos)))
14699 (defun org-skip-whitespace ()
14700 (skip-chars-forward " \t\n\r"))
14702 (defun org-point-in-group (point group &optional context)
14703 "Check if POINT is in match-group GROUP.
14704 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14705 match. If the match group does ot exist or point is not inside it,
14706 return nil."
14707 (and (match-beginning group)
14708 (>= point (match-beginning group))
14709 (<= point (match-end group))
14710 (if context
14711 (list context (match-beginning group) (match-end group))
14712 t)))
14714 (defun org-switch-to-buffer-other-window (&rest args)
14715 "Switch to buffer in a second window on the current frame.
14716 In particular, do not allow pop-up frames."
14717 (let (pop-up-frames special-display-buffer-names special-display-regexps
14718 special-display-function)
14719 (apply 'switch-to-buffer-other-window args)))
14721 (defun org-combine-plists (&rest plists)
14722 "Create a single property list from all plists in PLISTS.
14723 The process starts by copying the first list, and then setting properties
14724 from the other lists. Settings in the last list are the most significant
14725 ones and overrule settings in the other lists."
14726 (let ((rtn (copy-sequence (pop plists)))
14727 p v ls)
14728 (while plists
14729 (setq ls (pop plists))
14730 (while ls
14731 (setq p (pop ls) v (pop ls))
14732 (setq rtn (plist-put rtn p v))))
14733 rtn))
14735 (defun org-move-line-down (arg)
14736 "Move the current line down. With prefix argument, move it past ARG lines."
14737 (interactive "p")
14738 (let ((col (current-column))
14739 beg end pos)
14740 (beginning-of-line 1) (setq beg (point))
14741 (beginning-of-line 2) (setq end (point))
14742 (beginning-of-line (+ 1 arg))
14743 (setq pos (move-marker (make-marker) (point)))
14744 (insert (delete-and-extract-region beg end))
14745 (goto-char pos)
14746 (org-move-to-column col)))
14748 (defun org-move-line-up (arg)
14749 "Move the current line up. With prefix argument, move it past ARG lines."
14750 (interactive "p")
14751 (let ((col (current-column))
14752 beg end pos)
14753 (beginning-of-line 1) (setq beg (point))
14754 (beginning-of-line 2) (setq end (point))
14755 (beginning-of-line (- arg))
14756 (setq pos (move-marker (make-marker) (point)))
14757 (insert (delete-and-extract-region beg end))
14758 (goto-char pos)
14759 (org-move-to-column col)))
14761 (defun org-replace-escapes (string table)
14762 "Replace %-escapes in STRING with values in TABLE.
14763 TABLE is an association list with keys like \"%a\" and string values.
14764 The sequences in STRING may contain normal field width and padding information,
14765 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14766 so values can contain further %-escapes if they are define later in TABLE."
14767 (let ((case-fold-search nil)
14768 e re rpl)
14769 (while (setq e (pop table))
14770 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14771 (while (string-match re string)
14772 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14773 (cdr e)))
14774 (setq string (replace-match rpl t t string))))
14775 string))
14778 (defun org-sublist (list start end)
14779 "Return a section of LIST, from START to END.
14780 Counting starts at 1."
14781 (let (rtn (c start))
14782 (setq list (nthcdr (1- start) list))
14783 (while (and list (<= c end))
14784 (push (pop list) rtn)
14785 (setq c (1+ c)))
14786 (nreverse rtn)))
14788 (defun org-find-base-buffer-visiting (file)
14789 "Like `find-buffer-visiting' but alway return the base buffer and
14790 not an indirect buffer."
14791 (let ((buf (find-buffer-visiting file)))
14792 (if buf
14793 (or (buffer-base-buffer buf) buf)
14794 nil)))
14796 (defun org-image-file-name-regexp (&optional extensions)
14797 "Return regexp matching the file names of images.
14798 If EXTENSIONS is given, only match these."
14799 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14800 (image-file-name-regexp)
14801 (let ((image-file-name-extensions
14802 (or extensions
14803 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14804 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14805 (concat "\\."
14806 (regexp-opt (nconc (mapcar 'upcase
14807 image-file-name-extensions)
14808 image-file-name-extensions)
14810 "\\'"))))
14812 (defun org-file-image-p (file &optional extensions)
14813 "Return non-nil if FILE is an image."
14814 (save-match-data
14815 (string-match (org-image-file-name-regexp extensions) file)))
14817 (defun org-get-cursor-date ()
14818 "Return the date at cursor in as a time.
14819 This works in the calendar and in the agenda, anywhere else it just
14820 returns the current time."
14821 (let (date day defd)
14822 (cond
14823 ((eq major-mode 'calendar-mode)
14824 (setq date (calendar-cursor-to-date)
14825 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14826 ((eq major-mode 'org-agenda-mode)
14827 (setq day (get-text-property (point) 'day))
14828 (if day
14829 (setq date (calendar-gregorian-from-absolute day)
14830 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14831 (nth 2 date))))))
14832 (or defd (current-time))))
14834 (defvar org-agenda-action-marker (make-marker)
14835 "Marker pointing to the entry for the next agenda action.")
14837 (defun org-mark-entry-for-agenda-action ()
14838 "Mark the current entry as target of an agenda action.
14839 Agenda actions are actions executed from the agenda with the key `k',
14840 which make use of the date at the cursor."
14841 (interactive)
14842 (move-marker org-agenda-action-marker
14843 (save-excursion (org-back-to-heading t) (point))
14844 (current-buffer))
14845 (message
14846 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14848 ;;; Paragraph filling stuff.
14849 ;; We want this to be just right, so use the full arsenal.
14851 (defun org-indent-line-function ()
14852 "Indent line like previous, but further if previous was headline or item."
14853 (interactive)
14854 (let* ((pos (point))
14855 (itemp (org-at-item-p))
14856 (org-drawer-regexp (or org-drawer-regexp "\000"))
14857 column bpos bcol tpos tcol bullet btype bullet-type)
14858 ;; Find the previous relevant line
14859 (beginning-of-line 1)
14860 (cond
14861 ((looking-at "#") (setq column 0))
14862 ((looking-at "\\*+ ") (setq column 0))
14863 ((and (looking-at "[ \t]*:END:")
14864 (save-excursion (re-search-backward org-drawer-regexp nil t)))
14865 (save-excursion
14866 (goto-char (1- (match-beginning 1)))
14867 (setq column (current-column))))
14869 (beginning-of-line 0)
14870 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
14871 (not (looking-at "[ \t]*:END:"))
14872 (not (looking-at org-drawer-regexp)))
14873 (beginning-of-line 0))
14874 (cond
14875 ((looking-at "\\*+[ \t]+")
14876 (if (not org-adapt-indentation)
14877 (setq column 0)
14878 (goto-char (match-end 0))
14879 (setq column (current-column))))
14880 ((looking-at org-drawer-regexp)
14881 (goto-char (1- (match-beginning 1)))
14882 (setq column (current-column)))
14883 ((looking-at "\\([ \t]*\\):END:")
14884 (goto-char (match-end 1))
14885 (setq column (current-column)))
14886 ((org-in-item-p)
14887 (org-beginning-of-item)
14888 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14889 (setq bpos (match-beginning 1) tpos (match-end 0)
14890 bcol (progn (goto-char bpos) (current-column))
14891 tcol (progn (goto-char tpos) (current-column))
14892 bullet (match-string 1)
14893 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14894 (if (> tcol (+ bcol org-description-max-indent))
14895 (setq tcol (+ bcol 5)))
14896 (if (not itemp)
14897 (setq column tcol)
14898 (goto-char pos)
14899 (beginning-of-line 1)
14900 (if (looking-at "\\S-")
14901 (progn
14902 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14903 (setq bullet (match-string 1)
14904 btype (if (string-match "[0-9]" bullet) "n" bullet))
14905 (setq column (if (equal btype bullet-type) bcol tcol)))
14906 (setq column (org-get-indentation)))))
14907 (t (setq column (org-get-indentation))))))
14908 (goto-char pos)
14909 (if (<= (current-column) (current-indentation))
14910 (org-indent-line-to column)
14911 (save-excursion (org-indent-line-to column)))
14912 (setq column (current-column))
14913 (beginning-of-line 1)
14914 (if (looking-at
14915 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14916 (replace-match (concat "\\1" (format org-property-format
14917 (match-string 2) (match-string 3)))
14918 t nil))
14919 (org-move-to-column column)))
14921 (defun org-set-autofill-regexps ()
14922 (interactive)
14923 ;; In the paragraph separator we include headlines, because filling
14924 ;; text in a line directly attached to a headline would otherwise
14925 ;; fill the headline as well.
14926 (org-set-local 'comment-start-skip "^#+[ \t]*")
14927 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14928 ;; The paragraph starter includes hand-formatted lists.
14929 (org-set-local 'paragraph-start
14930 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14931 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14932 ;; But only if the user has not turned off tables or fixed-width regions
14933 (org-set-local
14934 'auto-fill-inhibit-regexp
14935 (concat "\\*+ \\|#\\+"
14936 "\\|[ \t]*" org-keyword-time-regexp
14937 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14938 (concat
14939 "\\|[ \t]*["
14940 (if org-enable-table-editor "|" "")
14941 (if org-enable-fixed-width-editor ":" "")
14942 "]"))))
14943 ;; We use our own fill-paragraph function, to make sure that tables
14944 ;; and fixed-width regions are not wrapped. That function will pass
14945 ;; through to `fill-paragraph' when appropriate.
14946 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14947 ; Adaptive filling: To get full control, first make sure that
14948 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14949 (org-set-local 'adaptive-fill-regexp "\000")
14950 (org-set-local 'adaptive-fill-function
14951 'org-adaptive-fill-function)
14952 (org-set-local
14953 'align-mode-rules-list
14954 '((org-in-buffer-settings
14955 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14956 (modes . '(org-mode))))))
14958 (defun org-fill-paragraph (&optional justify)
14959 "Re-align a table, pass through to fill-paragraph if no table."
14960 (let ((table-p (org-at-table-p))
14961 (table.el-p (org-at-table.el-p)))
14962 (cond ((and (equal (char-after (point-at-bol)) ?*)
14963 (save-excursion (goto-char (point-at-bol))
14964 (looking-at outline-regexp)))
14965 t) ; skip headlines
14966 (table.el-p t) ; skip table.el tables
14967 (table-p (org-table-align) t) ; align org-mode tables
14968 (t nil)))) ; call paragraph-fill
14970 ;; For reference, this is the default value of adaptive-fill-regexp
14971 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14973 (defun org-adaptive-fill-function ()
14974 "Return a fill prefix for org-mode files.
14975 In particular, this makes sure hanging paragraphs for hand-formatted lists
14976 work correctly."
14977 (cond ((looking-at "#[ \t]+")
14978 (match-string 0))
14979 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14980 (save-excursion
14981 (if (> (match-end 1) (+ (match-beginning 1)
14982 org-description-max-indent))
14983 (goto-char (+ (match-beginning 1) 5))
14984 (goto-char (match-end 0)))
14985 (make-string (current-column) ?\ )))
14986 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14987 (save-excursion
14988 (goto-char (match-end 0))
14989 (make-string (current-column) ?\ )))
14990 (t nil)))
14992 ;;; Other stuff.
14994 (defun org-toggle-fixed-width-section (arg)
14995 "Toggle the fixed-width export.
14996 If there is no active region, the QUOTE keyword at the current headline is
14997 inserted or removed. When present, it causes the text between this headline
14998 and the next to be exported as fixed-width text, and unmodified.
14999 If there is an active region, this command adds or removes a colon as the
15000 first character of this line. If the first character of a line is a colon,
15001 this line is also exported in fixed-width font."
15002 (interactive "P")
15003 (let* ((cc 0)
15004 (regionp (org-region-active-p))
15005 (beg (if regionp (region-beginning) (point)))
15006 (end (if regionp (region-end)))
15007 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15008 (case-fold-search nil)
15009 (re "[ \t]*\\(:\\)")
15010 off)
15011 (if regionp
15012 (save-excursion
15013 (goto-char beg)
15014 (setq cc (current-column))
15015 (beginning-of-line 1)
15016 (setq off (looking-at re))
15017 (while (> nlines 0)
15018 (setq nlines (1- nlines))
15019 (beginning-of-line 1)
15020 (cond
15021 (arg
15022 (org-move-to-column cc t)
15023 (insert ":\n")
15024 (forward-line -1))
15025 ((and off (looking-at re))
15026 (replace-match "" t t nil 1))
15027 ((not off) (org-move-to-column cc t) (insert ":")))
15028 (forward-line 1)))
15029 (save-excursion
15030 (org-back-to-heading)
15031 (if (looking-at (concat outline-regexp
15032 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15033 (replace-match "" t t nil 1)
15034 (if (looking-at outline-regexp)
15035 (progn
15036 (goto-char (match-end 0))
15037 (insert org-quote-string " "))))))))
15039 ;;;; Functions extending outline functionality
15041 (defun org-beginning-of-line (&optional arg)
15042 "Go to the beginning of the current line. If that is invisible, continue
15043 to a visible line beginning. This makes the function of C-a more intuitive.
15044 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15045 first attempt, and only move to after the tags when the cursor is already
15046 beyond the end of the headline."
15047 (interactive "P")
15048 (let ((pos (point)) refpos)
15049 (beginning-of-line 1)
15050 (if (and arg (fboundp 'move-beginning-of-line))
15051 (call-interactively 'move-beginning-of-line)
15052 (if (bobp)
15054 (backward-char 1)
15055 (if (org-invisible-p)
15056 (while (and (not (bobp)) (org-invisible-p))
15057 (backward-char 1)
15058 (beginning-of-line 1))
15059 (forward-char 1))))
15060 (when org-special-ctrl-a/e
15061 (cond
15062 ((and (looking-at org-complex-heading-regexp)
15063 (= (char-after (match-end 1)) ?\ ))
15064 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15065 (point-at-eol)))
15066 (goto-char
15067 (if (eq org-special-ctrl-a/e t)
15068 (cond ((> pos refpos) refpos)
15069 ((= pos (point)) refpos)
15070 (t (point)))
15071 (cond ((> pos (point)) (point))
15072 ((not (eq last-command this-command)) (point))
15073 (t refpos)))))
15074 ((org-at-item-p)
15075 (goto-char
15076 (if (eq org-special-ctrl-a/e t)
15077 (cond ((> pos (match-end 4)) (match-end 4))
15078 ((= pos (point)) (match-end 4))
15079 (t (point)))
15080 (cond ((> pos (point)) (point))
15081 ((not (eq last-command this-command)) (point))
15082 (t (match-end 4))))))))
15083 (org-no-warnings
15084 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15086 (defun org-end-of-line (&optional arg)
15087 "Go to the end of the line.
15088 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15089 first attempt, and only move to after the tags when the cursor is already
15090 beyond the end of the headline."
15091 (interactive "P")
15092 (if (or (not org-special-ctrl-a/e)
15093 (not (org-on-heading-p))
15094 arg)
15095 (call-interactively (if (fboundp 'move-end-of-line)
15096 'move-end-of-line
15097 'end-of-line))
15098 (let ((pos (point)))
15099 (beginning-of-line 1)
15100 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15101 (if (eq org-special-ctrl-a/e t)
15102 (if (or (< pos (match-beginning 1))
15103 (= pos (match-end 0)))
15104 (goto-char (match-beginning 1))
15105 (goto-char (match-end 0)))
15106 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15107 (goto-char (match-end 0))
15108 (goto-char (match-beginning 1))))
15109 (call-interactively (if (fboundp 'move-end-of-line)
15110 'move-end-of-line
15111 'end-of-line)))))
15112 (org-no-warnings
15113 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
15116 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15117 (define-key org-mode-map "\C-e" 'org-end-of-line)
15119 (defun org-kill-line (&optional arg)
15120 "Kill line, to tags or end of line."
15121 (interactive "P")
15122 (cond
15123 ((or (not org-special-ctrl-k)
15124 (bolp)
15125 (not (org-on-heading-p)))
15126 (call-interactively 'kill-line))
15127 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15128 (kill-region (point) (match-beginning 1))
15129 (org-set-tags nil t))
15130 (t (kill-region (point) (point-at-eol)))))
15132 (define-key org-mode-map "\C-k" 'org-kill-line)
15134 (defun org-yank (&optional arg)
15135 "Yank. If the kill is a subtree, treat it specially.
15136 This command will look at the current kill and check if is a single
15137 subtree, or a series of subtrees[1]. If it passes the test, and if the
15138 cursor is at the beginning of a line or after the stars of a currently
15139 empty headline, then the yank is handled specially. How exactly depends
15140 on the value of the following variables, both set by default.
15142 org-yank-folded-subtrees
15143 When set, the subtree(s) will be folded after insertion, but only
15144 if doing so would now swallow text after the yanked text.
15146 org-yank-adjusted-subtrees
15147 When set, the subtree will be promoted or demoted in order to
15148 fit into the local outline tree structure, which means that the level
15149 will be adjusted so that it becomes the smaller one of the two
15150 *visible* surrounding headings.
15152 Any prefix to this command will cause `yank' to be called directly with
15153 no special treatment. In particular, a simple `C-u' prefix will just
15154 plainly yank the text as it is.
15156 \[1] Basically, the test checks if the first non-white line is a heading
15157 and if there are no other headings with fewer stars."
15158 (interactive "P")
15159 (setq this-command 'yank)
15160 (if arg
15161 (call-interactively 'yank)
15162 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15163 (and (org-kill-is-subtree-p)
15164 (or (bolp)
15165 (and (looking-at "[ \t]*$")
15166 (string-match
15167 "\\`\\*+\\'"
15168 (buffer-substring (point-at-bol) (point)))))))
15169 swallowp)
15170 (cond
15171 ((and subtreep org-yank-folded-subtrees)
15172 (let ((beg (point))
15173 end)
15174 (if (and subtreep org-yank-adjusted-subtrees)
15175 (org-paste-subtree nil nil 'for-yank)
15176 (call-interactively 'yank))
15177 (setq end (point))
15178 (goto-char beg)
15179 (when (and (bolp) subtreep
15180 (not (setq swallowp
15181 (org-yank-folding-would-swallow-text beg end))))
15182 (or (looking-at outline-regexp)
15183 (re-search-forward (concat "^" outline-regexp) end t))
15184 (while (and (< (point) end) (looking-at outline-regexp))
15185 (hide-subtree)
15186 (org-cycle-show-empty-lines 'folded)
15187 (condition-case nil
15188 (outline-forward-same-level 1)
15189 (error (goto-char end)))))
15190 (when swallowp
15191 (message
15192 "Yanked text not folded because that would swallow text"))
15193 (goto-char end)
15194 (skip-chars-forward " \t\n\r")
15195 (beginning-of-line 1)
15196 (push-mark beg 'nomsg)))
15197 ((and subtreep org-yank-adjusted-subtrees)
15198 (let ((beg (point-at-bol)))
15199 (org-paste-subtree nil nil 'for-yank)
15200 (push-mark beg 'nomsg)))
15202 (call-interactively 'yank))))))
15204 (defun org-yank-folding-would-swallow-text (beg end)
15205 "Would hide-subtree at BEG swallow any text after END?"
15206 (let (level)
15207 (save-excursion
15208 (goto-char beg)
15209 (when (or (looking-at outline-regexp)
15210 (re-search-forward (concat "^" outline-regexp) end t))
15211 (setq level (org-outline-level)))
15212 (goto-char end)
15213 (skip-chars-forward " \t\r\n\v\f")
15214 (if (or (eobp)
15215 (and (bolp) (looking-at org-outline-regexp)
15216 (<= (org-outline-level) level)))
15217 nil ; Nothing would be swallowed
15218 t)))) ; something would swallow
15220 (define-key org-mode-map "\C-y" 'org-yank)
15222 (defun org-invisible-p ()
15223 "Check if point is at a character currently not visible."
15224 ;; Early versions of noutline don't have `outline-invisible-p'.
15225 (if (fboundp 'outline-invisible-p)
15226 (outline-invisible-p)
15227 (get-char-property (point) 'invisible)))
15229 (defun org-invisible-p2 ()
15230 "Check if point is at a character currently not visible."
15231 (save-excursion
15232 (if (and (eolp) (not (bobp))) (backward-char 1))
15233 ;; Early versions of noutline don't have `outline-invisible-p'.
15234 (if (fboundp 'outline-invisible-p)
15235 (outline-invisible-p)
15236 (get-char-property (point) 'invisible))))
15238 (defun org-back-to-heading (&optional invisible-ok)
15239 "Call `outline-back-to-heading', but provide a better error message."
15240 (condition-case nil
15241 (outline-back-to-heading invisible-ok)
15242 (error (error "Before first headline at position %d in buffer %s"
15243 (point) (current-buffer)))))
15245 (defun org-before-first-heading-p ()
15246 "Before first heading?"
15247 (save-excursion
15248 (null (re-search-backward "^\\*+ " nil t))))
15250 (defalias 'org-on-heading-p 'outline-on-heading-p)
15251 (defalias 'org-at-heading-p 'outline-on-heading-p)
15252 (defun org-at-heading-or-item-p ()
15253 (or (org-on-heading-p) (org-at-item-p)))
15255 (defun org-on-target-p ()
15256 (or (org-in-regexp org-radio-target-regexp)
15257 (org-in-regexp org-target-regexp)))
15259 (defun org-up-heading-all (arg)
15260 "Move to the heading line of which the present line is a subheading.
15261 This function considers both visible and invisible heading lines.
15262 With argument, move up ARG levels."
15263 (if (fboundp 'outline-up-heading-all)
15264 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15265 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15267 (defun org-up-heading-safe ()
15268 "Move to the heading line of which the present line is a subheading.
15269 This version will not throw an error. It will return the level of the
15270 headline found, or nil if no higher level is found."
15271 (let (start-level re)
15272 (org-back-to-heading t)
15273 (setq start-level (funcall outline-level))
15274 (if (equal start-level 1)
15276 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15277 (if (re-search-backward re nil t)
15278 (funcall outline-level)))))
15280 (defun org-first-sibling-p ()
15281 "Is this heading the first child of its parents?"
15282 (interactive)
15283 (let ((re (concat "^" outline-regexp))
15284 level l)
15285 (unless (org-at-heading-p t)
15286 (error "Not at a heading"))
15287 (setq level (funcall outline-level))
15288 (save-excursion
15289 (if (not (re-search-backward re nil t))
15291 (setq l (funcall outline-level))
15292 (< l level)))))
15294 (defun org-goto-sibling (&optional previous)
15295 "Goto the next sibling, even if it is invisible.
15296 When PREVIOUS is set, go to the previous sibling instead. Returns t
15297 when a sibling was found. When none is found, return nil and don't
15298 move point."
15299 (let ((fun (if previous 're-search-backward 're-search-forward))
15300 (pos (point))
15301 (re (concat "^" outline-regexp))
15302 level l)
15303 (when (condition-case nil (org-back-to-heading t) (error nil))
15304 (setq level (funcall outline-level))
15305 (catch 'exit
15306 (or previous (forward-char 1))
15307 (while (funcall fun re nil t)
15308 (setq l (funcall outline-level))
15309 (when (< l level) (goto-char pos) (throw 'exit nil))
15310 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15311 (goto-char pos)
15312 nil))))
15314 (defun org-show-siblings ()
15315 "Show all siblings of the current headline."
15316 (save-excursion
15317 (while (org-goto-sibling) (org-flag-heading nil)))
15318 (save-excursion
15319 (while (org-goto-sibling 'previous)
15320 (org-flag-heading nil))))
15322 (defun org-show-hidden-entry ()
15323 "Show an entry where even the heading is hidden."
15324 (save-excursion
15325 (org-show-entry)))
15327 (defun org-flag-heading (flag &optional entry)
15328 "Flag the current heading. FLAG non-nil means make invisible.
15329 When ENTRY is non-nil, show the entire entry."
15330 (save-excursion
15331 (org-back-to-heading t)
15332 ;; Check if we should show the entire entry
15333 (if entry
15334 (progn
15335 (org-show-entry)
15336 (save-excursion
15337 (and (outline-next-heading)
15338 (org-flag-heading nil))))
15339 (outline-flag-region (max (point-min) (1- (point)))
15340 (save-excursion (outline-end-of-heading) (point))
15341 flag))))
15343 (defun org-forward-same-level (arg)
15344 "Move forward to the ARG'th subheading at same level as this one.
15345 Stop at the first and last subheadings of a superior heading.
15346 This is like outline-forward-same-level, but invisible headings are ok."
15347 (interactive "p")
15348 (org-back-to-heading t)
15349 (while (> arg 0)
15350 (let ((point-to-move-to (save-excursion
15351 (org-get-next-sibling))))
15352 (if point-to-move-to
15353 (progn
15354 (goto-char point-to-move-to)
15355 (setq arg (1- arg)))
15356 (progn
15357 (setq arg 0)
15358 (error "No following same-level heading"))))))
15360 (defun org-get-next-sibling ()
15361 "Move to next heading of the same level, and return point.
15362 If there is no such heading, return nil.
15363 This is like outline-next-sibling, but invisible headings are ok."
15364 (let ((level (funcall outline-level)))
15365 (outline-next-heading)
15366 (while (and (not (eobp)) (> (funcall outline-level) level))
15367 (outline-next-heading))
15368 (if (or (eobp) (< (funcall outline-level) level))
15370 (point))))
15372 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15373 ;; This is an exact copy of the original function, but it uses
15374 ;; `org-back-to-heading', to make it work also in invisible
15375 ;; trees. And is uses an invisible-OK argument.
15376 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15377 (org-back-to-heading invisible-OK)
15378 (let ((first t)
15379 (level (funcall outline-level)))
15380 (while (and (not (eobp))
15381 (or first (> (funcall outline-level) level)))
15382 (setq first nil)
15383 (outline-next-heading))
15384 (unless to-heading
15385 (if (memq (preceding-char) '(?\n ?\^M))
15386 (progn
15387 ;; Go to end of line before heading
15388 (forward-char -1)
15389 (if (memq (preceding-char) '(?\n ?\^M))
15390 ;; leave blank line before heading
15391 (forward-char -1))))))
15392 (point))
15394 (defun org-show-subtree ()
15395 "Show everything after this heading at deeper levels."
15396 (outline-flag-region
15397 (point)
15398 (save-excursion
15399 (outline-end-of-subtree) (outline-next-heading) (point))
15400 nil))
15402 (defun org-show-entry ()
15403 "Show the body directly following this heading.
15404 Show the heading too, if it is currently invisible."
15405 (interactive)
15406 (save-excursion
15407 (condition-case nil
15408 (progn
15409 (org-back-to-heading t)
15410 (outline-flag-region
15411 (max (point-min) (1- (point)))
15412 (save-excursion
15413 (if (re-search-forward
15414 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15415 (match-beginning 1)
15416 (point-max)))
15417 nil))
15418 (error nil))))
15420 (defun org-make-options-regexp (kwds &optional extra)
15421 "Make a regular expression for keyword lines."
15422 (concat
15424 "#?[ \t]*\\+\\("
15425 (mapconcat 'regexp-quote kwds "\\|")
15426 (if extra (concat "\\|" extra))
15427 "\\):[ \t]*"
15428 "\\(.+\\)"))
15430 ;; Make isearch reveal the necessary context
15431 (defun org-isearch-end ()
15432 "Reveal context after isearch exits."
15433 (when isearch-success ; only if search was successful
15434 (if (featurep 'xemacs)
15435 ;; Under XEmacs, the hook is run in the correct place,
15436 ;; we directly show the context.
15437 (org-show-context 'isearch)
15438 ;; In Emacs the hook runs *before* restoring the overlays.
15439 ;; So we have to use a one-time post-command-hook to do this.
15440 ;; (Emacs 22 has a special variable, see function `org-mode')
15441 (unless (and (boundp 'isearch-mode-end-hook-quit)
15442 isearch-mode-end-hook-quit)
15443 ;; Only when the isearch was not quitted.
15444 (org-add-hook 'post-command-hook 'org-isearch-post-command
15445 'append 'local)))))
15447 (defun org-isearch-post-command ()
15448 "Remove self from hook, and show context."
15449 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15450 (org-show-context 'isearch))
15453 ;;;; Integration with and fixes for other packages
15455 ;;; Imenu support
15457 (defvar org-imenu-markers nil
15458 "All markers currently used by Imenu.")
15459 (make-variable-buffer-local 'org-imenu-markers)
15461 (defun org-imenu-new-marker (&optional pos)
15462 "Return a new marker for use by Imenu, and remember the marker."
15463 (let ((m (make-marker)))
15464 (move-marker m (or pos (point)))
15465 (push m org-imenu-markers)
15468 (defun org-imenu-get-tree ()
15469 "Produce the index for Imenu."
15470 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15471 (setq org-imenu-markers nil)
15472 (let* ((n org-imenu-depth)
15473 (re (concat "^" outline-regexp))
15474 (subs (make-vector (1+ n) nil))
15475 (last-level 0)
15476 m level head)
15477 (save-excursion
15478 (save-restriction
15479 (widen)
15480 (goto-char (point-max))
15481 (while (re-search-backward re nil t)
15482 (setq level (org-reduced-level (funcall outline-level)))
15483 (when (<= level n)
15484 (looking-at org-complex-heading-regexp)
15485 (setq head (org-link-display-format
15486 (org-match-string-no-properties 4))
15487 m (org-imenu-new-marker))
15488 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15489 (if (>= level last-level)
15490 (push (cons head m) (aref subs level))
15491 (push (cons head (aref subs (1+ level))) (aref subs level))
15492 (loop for i from (1+ level) to n do (aset subs i nil)))
15493 (setq last-level level)))))
15494 (aref subs 1)))
15496 (eval-after-load "imenu"
15497 '(progn
15498 (add-hook 'imenu-after-jump-hook
15499 (lambda ()
15500 (if (eq major-mode 'org-mode)
15501 (org-show-context 'org-goto))))))
15503 (defun org-link-display-format (link)
15504 "Replace a link with either the description, or the link target
15505 if no description is present"
15506 (save-match-data
15507 (if (string-match org-bracket-link-analytic-regexp link)
15508 (replace-match (or (match-string 5 link)
15509 (concat (match-string 1 link)
15510 (match-string 3 link)))
15511 nil nil link)
15512 link)))
15514 ;; Speedbar support
15516 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15517 "Overlay marking the agenda restriction line in speedbar.")
15518 (org-overlay-put org-speedbar-restriction-lock-overlay
15519 'face 'org-agenda-restriction-lock)
15520 (org-overlay-put org-speedbar-restriction-lock-overlay
15521 'help-echo "Agendas are currently limited to this item.")
15522 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15524 (defun org-speedbar-set-agenda-restriction ()
15525 "Restrict future agenda commands to the location at point in speedbar.
15526 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15527 (interactive)
15528 (require 'org-agenda)
15529 (let (p m tp np dir txt)
15530 (cond
15531 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15532 'org-imenu t))
15533 (setq m (get-text-property p 'org-imenu-marker))
15534 (save-excursion
15535 (save-restriction
15536 (set-buffer (marker-buffer m))
15537 (goto-char m)
15538 (org-agenda-set-restriction-lock 'subtree))))
15539 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15540 'speedbar-function 'speedbar-find-file))
15541 (setq tp (previous-single-property-change
15542 (1+ p) 'speedbar-function)
15543 np (next-single-property-change
15544 tp 'speedbar-function)
15545 dir (speedbar-line-directory)
15546 txt (buffer-substring-no-properties (or tp (point-min))
15547 (or np (point-max))))
15548 (save-excursion
15549 (save-restriction
15550 (set-buffer (find-file-noselect
15551 (let ((default-directory dir))
15552 (expand-file-name txt))))
15553 (unless (org-mode-p)
15554 (error "Cannot restrict to non-Org-mode file"))
15555 (org-agenda-set-restriction-lock 'file))))
15556 (t (error "Don't know how to restrict Org-mode's agenda")))
15557 (org-move-overlay org-speedbar-restriction-lock-overlay
15558 (point-at-bol) (point-at-eol))
15559 (setq current-prefix-arg nil)
15560 (org-agenda-maybe-redo)))
15562 (eval-after-load "speedbar"
15563 '(progn
15564 (speedbar-add-supported-extension ".org")
15565 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15566 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15567 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15568 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15569 (add-hook 'speedbar-visiting-tag-hook
15570 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15573 ;;; Fixes and Hacks for problems with other packages
15575 ;; Make flyspell not check words in links, to not mess up our keymap
15576 (defun org-mode-flyspell-verify ()
15577 "Don't let flyspell put overlays at active buttons."
15578 (not (get-text-property (point) 'keymap)))
15580 ;; Make `bookmark-jump' show the jump location if it was hidden.
15581 (eval-after-load "bookmark"
15582 '(if (boundp 'bookmark-after-jump-hook)
15583 ;; We can use the hook
15584 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15585 ;; Hook not available, use advice
15586 (defadvice bookmark-jump (after org-make-visible activate)
15587 "Make the position visible."
15588 (org-bookmark-jump-unhide))))
15590 ;; Make sure saveplace show the location if it was hidden
15591 (eval-after-load "saveplace"
15592 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15593 "Make the position visible."
15594 (org-bookmark-jump-unhide)))
15596 (defun org-bookmark-jump-unhide ()
15597 "Unhide the current position, to show the bookmark location."
15598 (and (org-mode-p)
15599 (or (org-invisible-p)
15600 (save-excursion (goto-char (max (point-min) (1- (point))))
15601 (org-invisible-p)))
15602 (org-show-context 'bookmark-jump)))
15604 ;; Make session.el ignore our circular variable
15605 (eval-after-load "session"
15606 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15608 ;;;; Experimental code
15610 (defun org-closed-in-range ()
15611 "Sparse tree of items closed in a certain time range.
15612 Still experimental, may disappear in the future."
15613 (interactive)
15614 ;; Get the time interval from the user.
15615 (let* ((time1 (time-to-seconds
15616 (org-read-date nil 'to-time nil "Starting date: ")))
15617 (time2 (time-to-seconds
15618 (org-read-date nil 'to-time nil "End date:")))
15619 ;; callback function
15620 (callback (lambda ()
15621 (let ((time
15622 (time-to-seconds
15623 (apply 'encode-time
15624 (org-parse-time-string
15625 (match-string 1))))))
15626 ;; check if time in interval
15627 (and (>= time time1) (<= time time2))))))
15628 ;; make tree, check each match with the callback
15629 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15632 ;;;; Finish up
15634 (provide 'org)
15636 (run-hooks 'org-load-hook)
15638 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15640 ;;; org.el ends here