Release 6.23
[org-mode.git] / lisp / org.el
blob55bc1c5825eb86dfd57a927e04f755c36d1232a3
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.23
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.23"
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 calendar-absolute-from-iso "cal-iso" (date))
2644 (declare-function calendar-forward-day "cal-move" (arg))
2645 (declare-function calendar-goto-date "cal-move" (date))
2646 (declare-function calendar-goto-today "cal-move" ())
2647 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2648 (defvar calc-embedded-close-formula)
2649 (defvar calc-embedded-open-formula)
2650 (declare-function cdlatex-tab "ext:cdlatex" ())
2651 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2652 (defvar font-lock-unfontify-region-function)
2653 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2654 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2655 (defvar iswitchb-temp-buflist)
2656 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2657 (defvar org-agenda-tags-todo-honor-ignore-options)
2658 (declare-function org-agenda-skip "org-agenda" ())
2659 (declare-function org-format-agenda-item "org-agenda"
2660 (extra txt &optional category tags dotime noprefix remove-re))
2661 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2662 (declare-function org-agenda-change-all-lines "org-agenda"
2663 (newhead hdmarker &optional fixface just-this))
2664 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2665 (declare-function org-agenda-maybe-redo "org-agenda" ())
2666 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2667 (beg end))
2668 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2669 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2670 "org-agenda" (&optional end))
2672 (declare-function parse-time-string "parse-time" (string))
2673 (declare-function remember "remember" (&optional initial))
2674 (declare-function remember-buffer-desc "remember" ())
2675 (declare-function remember-finalize "remember" ())
2676 (defvar remember-save-after-remembering)
2677 (defvar remember-data-file)
2678 (defvar remember-register)
2679 (defvar remember-buffer)
2680 (defvar remember-handler-functions)
2681 (defvar remember-annotation-functions)
2682 (defvar texmathp-why)
2683 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2684 (declare-function table--at-cell-p "table" (position &optional object at-column))
2686 (defvar w3m-current-url)
2687 (defvar w3m-current-title)
2689 (defvar org-latex-regexps)
2691 ;;; Autoload and prepare some org modules
2693 ;; Some table stuff that needs to be defined here, because it is used
2694 ;; by the functions setting up org-mode or checking for table context.
2696 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2697 "Detects an org-type or table-type table.")
2698 (defconst org-table-line-regexp "^[ \t]*|"
2699 "Detects an org-type table line.")
2700 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2701 "Detects an org-type table line.")
2702 (defconst org-table-hline-regexp "^[ \t]*|-"
2703 "Detects an org-type table hline.")
2704 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2705 "Detects a table-type table hline.")
2706 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2707 "Searching from within a table (any type) this finds the first line
2708 outside the table.")
2710 ;; Autoload the functions in org-table.el that are needed by functions here.
2712 (eval-and-compile
2713 (org-autoload "org-table"
2714 '(org-table-align org-table-begin org-table-blank-field
2715 org-table-convert org-table-convert-region org-table-copy-down
2716 org-table-copy-region org-table-create
2717 org-table-create-or-convert-from-region
2718 org-table-create-with-table.el org-table-current-dline
2719 org-table-cut-region org-table-delete-column org-table-edit-field
2720 org-table-edit-formulas org-table-end org-table-eval-formula
2721 org-table-export org-table-field-info
2722 org-table-get-stored-formulas org-table-goto-column
2723 org-table-hline-and-move org-table-import org-table-insert-column
2724 org-table-insert-hline org-table-insert-row org-table-iterate
2725 org-table-justify-field-maybe org-table-kill-row
2726 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2727 org-table-move-column org-table-move-column-left
2728 org-table-move-column-right org-table-move-row
2729 org-table-move-row-down org-table-move-row-up
2730 org-table-next-field org-table-next-row org-table-paste-rectangle
2731 org-table-previous-field org-table-recalculate
2732 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2733 org-table-toggle-coordinate-overlays
2734 org-table-toggle-formula-debugger org-table-wrap-region
2735 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2737 (defun org-at-table-p (&optional table-type)
2738 "Return t if the cursor is inside an org-type table.
2739 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2740 (if org-enable-table-editor
2741 (save-excursion
2742 (beginning-of-line 1)
2743 (looking-at (if table-type org-table-any-line-regexp
2744 org-table-line-regexp)))
2745 nil))
2746 (defsubst org-table-p () (org-at-table-p))
2748 (defun org-at-table.el-p ()
2749 "Return t if and only if we are at a table.el table."
2750 (and (org-at-table-p 'any)
2751 (save-excursion
2752 (goto-char (org-table-begin 'any))
2753 (looking-at org-table1-hline-regexp))))
2754 (defun org-table-recognize-table.el ()
2755 "If there is a table.el table nearby, recognize it and move into it."
2756 (if org-table-tab-recognizes-table.el
2757 (if (org-at-table.el-p)
2758 (progn
2759 (beginning-of-line 1)
2760 (if (looking-at org-table-dataline-regexp)
2762 (if (looking-at org-table1-hline-regexp)
2763 (progn
2764 (beginning-of-line 2)
2765 (if (looking-at org-table-any-border-regexp)
2766 (beginning-of-line -1)))))
2767 (if (re-search-forward "|" (org-table-end t) t)
2768 (progn
2769 (require 'table)
2770 (if (table--at-cell-p (point))
2772 (message "recognizing table.el table...")
2773 (table-recognize-table)
2774 (message "recognizing table.el table...done")))
2775 (error "This should not happen..."))
2777 nil)
2778 nil))
2780 (defun org-at-table-hline-p ()
2781 "Return t if the cursor is inside a hline in a table."
2782 (if org-enable-table-editor
2783 (save-excursion
2784 (beginning-of-line 1)
2785 (looking-at org-table-hline-regexp))
2786 nil))
2788 (defvar org-table-clean-did-remove-column nil)
2790 (defun org-table-map-tables (function)
2791 "Apply FUNCTION to the start of all tables in the buffer."
2792 (save-excursion
2793 (save-restriction
2794 (widen)
2795 (goto-char (point-min))
2796 (while (re-search-forward org-table-any-line-regexp nil t)
2797 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2798 (beginning-of-line 1)
2799 (if (looking-at org-table-line-regexp)
2800 (save-excursion (funcall function)))
2801 (re-search-forward org-table-any-border-regexp nil 1))))
2802 (message "Mapping tables: done"))
2804 ;; Declare and autoload functions from org-exp.el
2806 (declare-function org-default-export-plist "org-exp")
2807 (declare-function org-infile-export-plist "org-exp")
2808 (declare-function org-get-current-options "org-exp")
2809 (eval-and-compile
2810 (org-autoload "org-exp"
2811 '(org-export org-export-as-ascii org-export-visible
2812 org-insert-export-options-template org-export-as-html-and-open
2813 org-export-as-html-batch org-export-as-html-to-buffer
2814 org-replace-region-by-html org-export-region-as-html
2815 org-export-as-html org-export-icalendar-this-file
2816 org-export-icalendar-all-agenda-files
2817 org-table-clean-before-export
2818 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2820 ;; Declare and autoload functions from org-agenda.el
2822 (eval-and-compile
2823 (org-autoload "org-agenda"
2824 '(org-agenda org-agenda-list org-search-view
2825 org-todo-list org-tags-view org-agenda-list-stuck-projects
2826 org-diary org-agenda-to-appt
2827 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2829 ;; Autoload org-remember
2831 (eval-and-compile
2832 (org-autoload "org-remember"
2833 '(org-remember-insinuate org-remember-annotation
2834 org-remember-apply-template org-remember org-remember-handler)))
2836 ;; Autoload org-clock.el
2839 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2840 (beg end))
2841 (declare-function org-clock-update-mode-line "org-clock" ())
2842 (defvar org-clock-start-time)
2843 (defvar org-clock-marker (make-marker)
2844 "Marker recording the last clock-in.")
2846 (eval-and-compile
2847 (org-autoload
2848 "org-clock"
2849 '(org-clock-in org-clock-out org-clock-cancel
2850 org-clock-goto org-clock-sum org-clock-display
2851 org-clock-remove-overlays org-clock-report
2852 org-clocktable-shift org-dblock-write:clocktable
2853 org-get-clocktable)))
2855 (defun org-clock-update-time-maybe ()
2856 "If this is a CLOCK line, update it and return t.
2857 Otherwise, return nil."
2858 (interactive)
2859 (save-excursion
2860 (beginning-of-line 1)
2861 (skip-chars-forward " \t")
2862 (when (looking-at org-clock-string)
2863 (let ((re (concat "[ \t]*" org-clock-string
2864 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2865 "\\([ \t]*=>.*\\)?\\)?"))
2866 ts te h m s neg)
2867 (cond
2868 ((not (looking-at re))
2869 nil)
2870 ((not (match-end 2))
2871 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2872 (> org-clock-marker (point))
2873 (<= org-clock-marker (point-at-eol)))
2874 ;; The clock is running here
2875 (setq org-clock-start-time
2876 (apply 'encode-time
2877 (org-parse-time-string (match-string 1))))
2878 (org-clock-update-mode-line)))
2880 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2881 (end-of-line 1)
2882 (setq ts (match-string 1)
2883 te (match-string 3))
2884 (setq s (- (time-to-seconds
2885 (apply 'encode-time (org-parse-time-string te)))
2886 (time-to-seconds
2887 (apply 'encode-time (org-parse-time-string ts))))
2888 neg (< s 0)
2889 s (abs s)
2890 h (floor (/ s 3600))
2891 s (- s (* 3600 h))
2892 m (floor (/ s 60))
2893 s (- s (* 60 s)))
2894 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2895 t))))))
2897 (defun org-check-running-clock ()
2898 "Check if the current buffer contains the running clock.
2899 If yes, offer to stop it and to save the buffer with the changes."
2900 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2901 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2902 (buffer-name))))
2903 (org-clock-out)
2904 (when (y-or-n-p "Save changed buffer?")
2905 (save-buffer))))
2907 (defun org-clocktable-try-shift (dir n)
2908 "Check if this line starts a clock table, if yes, shift the time block."
2909 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2910 (org-clocktable-shift dir n)))
2912 ;; Autoload org-timer.el
2914 ;(declare-function org-timer "org-timer")
2916 (eval-and-compile
2917 (org-autoload
2918 "org-timer"
2919 '(org-timer-start org-timer org-timer-item
2920 org-timer-change-times-in-region)))
2923 ;; Autoload archiving code
2924 ;; The stuff that is needed for cycling and tags has to be defined here.
2926 (defgroup org-archive nil
2927 "Options concerning archiving in Org-mode."
2928 :tag "Org Archive"
2929 :group 'org-structure)
2931 (defcustom org-archive-location "%s_archive::"
2932 "The location where subtrees should be archived.
2934 The value of this variable is a string, consisting of two parts,
2935 separated by a double-colon. The first part is a filename and
2936 the second part is a headline.
2938 When the filename is omitted, archiving happens in the same file.
2939 %s in the filename will be replaced by the current file
2940 name (without the directory part). Archiving to a different file
2941 is useful to keep archived entries from contributing to the
2942 Org-mode Agenda.
2944 The archived entries will be filed as subtrees of the specified
2945 headline. When the headline is omitted, the subtrees are simply
2946 filed away at the end of the file, as top-level entries. Also in
2947 the heading you can use %s to represent the file name, this can be
2948 useful when using the same archive for a number of different files.
2950 Here are a few examples:
2951 \"%s_archive::\"
2952 If the current file is Projects.org, archive in file
2953 Projects.org_archive, as top-level trees. This is the default.
2955 \"::* Archived Tasks\"
2956 Archive in the current file, under the top-level headline
2957 \"* Archived Tasks\".
2959 \"~/org/archive.org::\"
2960 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2962 \"~/org/archive.org::From %s\"
2963 Archive in file ~/org/archive.org (absolute path), und headlines
2964 \"From FILENAME\" where file name is the current file name.
2966 \"basement::** Finished Tasks\"
2967 Archive in file ./basement (relative path), as level 3 trees
2968 below the level 2 heading \"** Finished Tasks\".
2970 You may set this option on a per-file basis by adding to the buffer a
2971 line like
2973 #+ARCHIVE: basement::** Finished Tasks
2975 You may also define it locally for a subtree by setting an ARCHIVE property
2976 in the entry. If such a property is found in an entry, or anywhere up
2977 the hierarchy, it will be used."
2978 :group 'org-archive
2979 :type 'string)
2981 (defcustom org-archive-tag "ARCHIVE"
2982 "The tag that marks a subtree as archived.
2983 An archived subtree does not open during visibility cycling, and does
2984 not contribute to the agenda listings.
2985 After changing this, font-lock must be restarted in the relevant buffers to
2986 get the proper fontification."
2987 :group 'org-archive
2988 :group 'org-keywords
2989 :type 'string)
2991 (defcustom org-agenda-skip-archived-trees t
2992 "Non-nil means, the agenda will skip any items located in archived trees.
2993 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2994 variable is no longer recommended, you should leave it at the value t.
2995 Instead, use the key `v' to cycle the archives-mode in the agenda."
2996 :group 'org-archive
2997 :group 'org-agenda-skip
2998 :type 'boolean)
3000 (defcustom org-cycle-open-archived-trees nil
3001 "Non-nil means, `org-cycle' will open archived trees.
3002 An archived tree is a tree marked with the tag ARCHIVE.
3003 When nil, archived trees will stay folded. You can still open them with
3004 normal outline commands like `show-all', but not with the cycling commands."
3005 :group 'org-archive
3006 :group 'org-cycle
3007 :type 'boolean)
3009 (defcustom org-sparse-tree-open-archived-trees nil
3010 "Non-nil means sparse tree construction shows matches in archived trees.
3011 When nil, matches in these trees are highlighted, but the trees are kept in
3012 collapsed state."
3013 :group 'org-archive
3014 :group 'org-sparse-trees
3015 :type 'boolean)
3017 (defun org-cycle-hide-archived-subtrees (state)
3018 "Re-hide all archived subtrees after a visibility state change."
3019 (when (and (not org-cycle-open-archived-trees)
3020 (not (memq state '(overview folded))))
3021 (save-excursion
3022 (let* ((globalp (memq state '(contents all)))
3023 (beg (if globalp (point-min) (point)))
3024 (end (if globalp (point-max) (org-end-of-subtree t))))
3025 (org-hide-archived-subtrees beg end)
3026 (goto-char beg)
3027 (if (looking-at (concat ".*:" org-archive-tag ":"))
3028 (message "%s" (substitute-command-keys
3029 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3031 (defun org-force-cycle-archived ()
3032 "Cycle subtree even if it is archived."
3033 (interactive)
3034 (setq this-command 'org-cycle)
3035 (let ((org-cycle-open-archived-trees t))
3036 (call-interactively 'org-cycle)))
3038 (defun org-hide-archived-subtrees (beg end)
3039 "Re-hide all archived subtrees after a visibility state change."
3040 (save-excursion
3041 (let* ((re (concat ":" org-archive-tag ":")))
3042 (goto-char beg)
3043 (while (re-search-forward re end t)
3044 (and (org-on-heading-p) (hide-subtree))
3045 (org-end-of-subtree t)))))
3047 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3049 (eval-and-compile
3050 (org-autoload "org-archive"
3051 '(org-add-archive-files org-archive-subtree
3052 org-archive-to-archive-sibling org-toggle-archive-tag)))
3054 ;; Autoload Column View Code
3056 (declare-function org-columns-number-to-string "org-colview")
3057 (declare-function org-columns-get-format-and-top-level "org-colview")
3058 (declare-function org-columns-compute "org-colview")
3060 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3061 '(org-columns-number-to-string org-columns-get-format-and-top-level
3062 org-columns-compute org-agenda-columns org-columns-remove-overlays
3063 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3065 ;; Autoload ID code
3067 (declare-function org-id-store-link "org-id")
3068 (declare-function org-id-locations-load "org-id")
3069 (declare-function org-id-locations-save "org-id")
3070 (defvar org-id-track-globally)
3071 (org-autoload "org-id"
3072 '(org-id-get-create org-id-new org-id-copy org-id-get
3073 org-id-get-with-outline-path-completion
3074 org-id-get-with-outline-drilling
3075 org-id-goto org-id-find org-id-store-link))
3077 ;; Autoload Plotting Code
3079 (org-autoload "org-plot"
3080 '(org-plot/gnuplot))
3082 ;;; Variables for pre-computed regular expressions, all buffer local
3084 (defvar org-drawer-regexp nil
3085 "Matches first line of a hidden block.")
3086 (make-variable-buffer-local 'org-drawer-regexp)
3087 (defvar org-todo-regexp nil
3088 "Matches any of the TODO state keywords.")
3089 (make-variable-buffer-local 'org-todo-regexp)
3090 (defvar org-not-done-regexp nil
3091 "Matches any of the TODO state keywords except the last one.")
3092 (make-variable-buffer-local 'org-not-done-regexp)
3093 (defvar org-todo-line-regexp nil
3094 "Matches a headline and puts TODO state into group 2 if present.")
3095 (make-variable-buffer-local 'org-todo-line-regexp)
3096 (defvar org-complex-heading-regexp nil
3097 "Matches a headline and puts everything into groups:
3098 group 1: the stars
3099 group 2: The todo keyword, maybe
3100 group 3: Priority cookie
3101 group 4: True headline
3102 group 5: Tags")
3103 (make-variable-buffer-local 'org-complex-heading-regexp)
3104 (defvar org-todo-line-tags-regexp nil
3105 "Matches a headline and puts TODO state into group 2 if present.
3106 Also put tags into group 4 if tags are present.")
3107 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3108 (defvar org-nl-done-regexp nil
3109 "Matches newline followed by a headline with the DONE keyword.")
3110 (make-variable-buffer-local 'org-nl-done-regexp)
3111 (defvar org-looking-at-done-regexp nil
3112 "Matches the DONE keyword a point.")
3113 (make-variable-buffer-local 'org-looking-at-done-regexp)
3114 (defvar org-ds-keyword-length 12
3115 "Maximum length of the Deadline and SCHEDULED keywords.")
3116 (make-variable-buffer-local 'org-ds-keyword-length)
3117 (defvar org-deadline-regexp nil
3118 "Matches the DEADLINE keyword.")
3119 (make-variable-buffer-local 'org-deadline-regexp)
3120 (defvar org-deadline-time-regexp nil
3121 "Matches the DEADLINE keyword together with a time stamp.")
3122 (make-variable-buffer-local 'org-deadline-time-regexp)
3123 (defvar org-deadline-line-regexp nil
3124 "Matches the DEADLINE keyword and the rest of the line.")
3125 (make-variable-buffer-local 'org-deadline-line-regexp)
3126 (defvar org-scheduled-regexp nil
3127 "Matches the SCHEDULED keyword.")
3128 (make-variable-buffer-local 'org-scheduled-regexp)
3129 (defvar org-scheduled-time-regexp nil
3130 "Matches the SCHEDULED keyword together with a time stamp.")
3131 (make-variable-buffer-local 'org-scheduled-time-regexp)
3132 (defvar org-closed-time-regexp nil
3133 "Matches the CLOSED keyword together with a time stamp.")
3134 (make-variable-buffer-local 'org-closed-time-regexp)
3136 (defvar org-keyword-time-regexp nil
3137 "Matches any of the 4 keywords, together with the time stamp.")
3138 (make-variable-buffer-local 'org-keyword-time-regexp)
3139 (defvar org-keyword-time-not-clock-regexp nil
3140 "Matches any of the 3 keywords, together with the time stamp.")
3141 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3142 (defvar org-maybe-keyword-time-regexp nil
3143 "Matches a timestamp, possibly preceeded by a keyword.")
3144 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3145 (defvar org-planning-or-clock-line-re nil
3146 "Matches a line with planning or clock info.")
3147 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3149 (defconst org-plain-time-of-day-regexp
3150 (concat
3151 "\\(\\<[012]?[0-9]"
3152 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3153 "\\(--?"
3154 "\\(\\<[012]?[0-9]"
3155 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3156 "\\)?")
3157 "Regular expression to match a plain time or time range.
3158 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3159 groups carry important information:
3160 0 the full match
3161 1 the first time, range or not
3162 8 the second time, if it is a range.")
3164 (defconst org-plain-time-extension-regexp
3165 (concat
3166 "\\(\\<[012]?[0-9]"
3167 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3168 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3169 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3170 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3171 groups carry important information:
3172 0 the full match
3173 7 hours of duration
3174 9 minutes of duration")
3176 (defconst org-stamp-time-of-day-regexp
3177 (concat
3178 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3179 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3180 "\\(--?"
3181 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3182 "Regular expression to match a timestamp time or time range.
3183 After a match, the following groups carry important information:
3184 0 the full match
3185 1 date plus weekday, for backreferencing to make sure both times on same day
3186 2 the first time, range or not
3187 4 the second time, if it is a range.")
3189 (defconst org-startup-options
3190 '(("fold" org-startup-folded t)
3191 ("overview" org-startup-folded t)
3192 ("nofold" org-startup-folded nil)
3193 ("showall" org-startup-folded nil)
3194 ("content" org-startup-folded content)
3195 ("hidestars" org-hide-leading-stars t)
3196 ("showstars" org-hide-leading-stars nil)
3197 ("odd" org-odd-levels-only t)
3198 ("oddeven" org-odd-levels-only nil)
3199 ("align" org-startup-align-all-tables t)
3200 ("noalign" org-startup-align-all-tables nil)
3201 ("customtime" org-display-custom-times t)
3202 ("logdone" org-log-done time)
3203 ("lognotedone" org-log-done note)
3204 ("nologdone" org-log-done nil)
3205 ("lognoteclock-out" org-log-note-clock-out t)
3206 ("nolognoteclock-out" org-log-note-clock-out nil)
3207 ("logrepeat" org-log-repeat state)
3208 ("lognoterepeat" org-log-repeat note)
3209 ("nologrepeat" org-log-repeat nil)
3210 ("fninline" org-footnote-define-inline t)
3211 ("nofninline" org-footnote-define-inline nil)
3212 ("fnlocal" org-footnote-section nil)
3213 ("fnauto" org-footnote-auto-label t)
3214 ("fnprompt" org-footnote-auto-label nil)
3215 ("fnconfirm" org-footnote-auto-label confirm)
3216 ("fnplain" org-footnote-auto-label plain)
3217 ("constcgs" constants-unit-system cgs)
3218 ("constSI" constants-unit-system SI))
3219 "Variable associated with STARTUP options for org-mode.
3220 Each element is a list of three items: The startup options as written
3221 in the #+STARTUP line, the corresponding variable, and the value to
3222 set this variable to if the option is found. An optional forth element PUSH
3223 means to push this value onto the list in the variable.")
3225 (defun org-set-regexps-and-options ()
3226 "Precompute regular expressions for current buffer."
3227 (when (org-mode-p)
3228 (org-set-local 'org-todo-kwd-alist nil)
3229 (org-set-local 'org-todo-key-alist nil)
3230 (org-set-local 'org-todo-key-trigger nil)
3231 (org-set-local 'org-todo-keywords-1 nil)
3232 (org-set-local 'org-done-keywords nil)
3233 (org-set-local 'org-todo-heads nil)
3234 (org-set-local 'org-todo-sets nil)
3235 (org-set-local 'org-todo-log-states nil)
3236 (org-set-local 'org-file-properties nil)
3237 (org-set-local 'org-file-tags nil)
3238 (let ((re (org-make-options-regexp
3239 '("CATEGORY" "TODO" "COLUMNS"
3240 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3241 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3242 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3243 (splitre "[ \t]+")
3244 kwds kws0 kwsa key log value cat arch tags const links hw dws
3245 tail sep kws1 prio props ftags drawers
3246 ext-setup-or-nil setup-contents (start 0))
3247 (save-excursion
3248 (save-restriction
3249 (widen)
3250 (goto-char (point-min))
3251 (while (or (and ext-setup-or-nil
3252 (string-match re ext-setup-or-nil start)
3253 (setq start (match-end 0)))
3254 (and (setq ext-setup-or-nil nil start 0)
3255 (re-search-forward re nil t)))
3256 (setq key (upcase (match-string 1 ext-setup-or-nil))
3257 value (org-match-string-no-properties 2 ext-setup-or-nil))
3258 (cond
3259 ((equal key "CATEGORY")
3260 (if (string-match "[ \t]+$" value)
3261 (setq value (replace-match "" t t value)))
3262 (setq cat value))
3263 ((member key '("SEQ_TODO" "TODO"))
3264 (push (cons 'sequence (org-split-string value splitre)) kwds))
3265 ((equal key "TYP_TODO")
3266 (push (cons 'type (org-split-string value splitre)) kwds))
3267 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3268 ;; general TODO-like setup
3269 (push (cons (intern (downcase (match-string 1 key)))
3270 (org-split-string value splitre)) kwds))
3271 ((equal key "TAGS")
3272 (setq tags (append tags (if tags '("\\n") nil)
3273 (org-split-string value splitre))))
3274 ((equal key "COLUMNS")
3275 (org-set-local 'org-columns-default-format value))
3276 ((equal key "LINK")
3277 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3278 (push (cons (match-string 1 value)
3279 (org-trim (match-string 2 value)))
3280 links)))
3281 ((equal key "PRIORITIES")
3282 (setq prio (org-split-string value " +")))
3283 ((equal key "PROPERTY")
3284 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3285 (push (cons (match-string 1 value) (match-string 2 value))
3286 props)))
3287 ((equal key "FILETAGS")
3288 (when (string-match "\\S-" value)
3289 (setq ftags
3290 (append
3291 ftags
3292 (apply 'append
3293 (mapcar (lambda (x) (org-split-string x ":"))
3294 (org-split-string value)))))))
3295 ((equal key "DRAWERS")
3296 (setq drawers (org-split-string value splitre)))
3297 ((equal key "CONSTANTS")
3298 (setq const (append const (org-split-string value splitre))))
3299 ((equal key "STARTUP")
3300 (let ((opts (org-split-string value splitre))
3301 l var val)
3302 (while (setq l (pop opts))
3303 (when (setq l (assoc l org-startup-options))
3304 (setq var (nth 1 l) val (nth 2 l))
3305 (if (not (nth 3 l))
3306 (set (make-local-variable var) val)
3307 (if (not (listp (symbol-value var)))
3308 (set (make-local-variable var) nil))
3309 (set (make-local-variable var) (symbol-value var))
3310 (add-to-list var val))))))
3311 ((equal key "ARCHIVE")
3312 (string-match " *$" value)
3313 (setq arch (replace-match "" t t value))
3314 (remove-text-properties 0 (length arch)
3315 '(face t fontified t) arch))
3316 ((equal key "SETUPFILE")
3317 (setq setup-contents (org-file-contents
3318 (expand-file-name
3319 (org-remove-double-quotes value))
3320 'noerror))
3321 (if (not ext-setup-or-nil)
3322 (setq ext-setup-or-nil setup-contents start 0)
3323 (setq ext-setup-or-nil
3324 (concat (substring ext-setup-or-nil 0 start)
3325 "\n" setup-contents "\n"
3326 (substring ext-setup-or-nil start)))))
3327 ))))
3328 (when cat
3329 (org-set-local 'org-category (intern cat))
3330 (push (cons "CATEGORY" cat) props))
3331 (when prio
3332 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3333 (setq prio (mapcar 'string-to-char prio))
3334 (org-set-local 'org-highest-priority (nth 0 prio))
3335 (org-set-local 'org-lowest-priority (nth 1 prio))
3336 (org-set-local 'org-default-priority (nth 2 prio)))
3337 (and props (org-set-local 'org-file-properties (nreverse props)))
3338 (and ftags (org-set-local 'org-file-tags ftags))
3339 (and drawers (org-set-local 'org-drawers drawers))
3340 (and arch (org-set-local 'org-archive-location arch))
3341 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3342 ;; Process the TODO keywords
3343 (unless kwds
3344 ;; Use the global values as if they had been given locally.
3345 (setq kwds (default-value 'org-todo-keywords))
3346 (if (stringp (car kwds))
3347 (setq kwds (list (cons org-todo-interpretation
3348 (default-value 'org-todo-keywords)))))
3349 (setq kwds (reverse kwds)))
3350 (setq kwds (nreverse kwds))
3351 (let (inter kws kw)
3352 (while (setq kws (pop kwds))
3353 (let ((kws (or
3354 (run-hook-with-args-until-success
3355 'org-todo-setup-filter-hook kws)
3356 kws)))
3357 (setq inter (pop kws) sep (member "|" kws)
3358 kws0 (delete "|" (copy-sequence kws))
3359 kwsa nil
3360 kws1 (mapcar
3361 (lambda (x)
3362 ;; 1 2
3363 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3364 (progn
3365 (setq kw (match-string 1 x)
3366 key (and (match-end 2) (match-string 2 x))
3367 log (org-extract-log-state-settings x))
3368 (push (cons kw (and key (string-to-char key))) kwsa)
3369 (and log (push log org-todo-log-states))
3371 (error "Invalid TODO keyword %s" x)))
3372 kws0)
3373 kwsa (if kwsa (append '((:startgroup))
3374 (nreverse kwsa)
3375 '((:endgroup))))
3376 hw (car kws1)
3377 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3378 tail (list inter hw (car dws) (org-last dws))))
3379 (add-to-list 'org-todo-heads hw 'append)
3380 (push kws1 org-todo-sets)
3381 (setq org-done-keywords (append org-done-keywords dws nil))
3382 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3383 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3384 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3385 (setq org-todo-sets (nreverse org-todo-sets)
3386 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3387 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3388 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3389 ;; Process the constants
3390 (when const
3391 (let (e cst)
3392 (while (setq e (pop const))
3393 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3394 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3395 (setq org-table-formula-constants-local cst)))
3397 ;; Process the tags.
3398 (when tags
3399 (let (e tgs)
3400 (while (setq e (pop tags))
3401 (cond
3402 ((equal e "{") (push '(:startgroup) tgs))
3403 ((equal e "}") (push '(:endgroup) tgs))
3404 ((equal e "\\n") (push '(:newline) tgs))
3405 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3406 (push (cons (match-string 1 e)
3407 (string-to-char (match-string 2 e)))
3408 tgs))
3409 (t (push (list e) tgs))))
3410 (org-set-local 'org-tag-alist nil)
3411 (while (setq e (pop tgs))
3412 (or (and (stringp (car e))
3413 (assoc (car e) org-tag-alist))
3414 (push e org-tag-alist)))))
3416 ;; Compute the regular expressions and other local variables
3417 (if (not org-done-keywords)
3418 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3419 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3420 (length org-scheduled-string)
3421 (length org-clock-string)
3422 (length org-closed-string)))
3423 org-drawer-regexp
3424 (concat "^[ \t]*:\\("
3425 (mapconcat 'regexp-quote org-drawers "\\|")
3426 "\\):[ \t]*$")
3427 org-not-done-keywords
3428 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3429 org-todo-regexp
3430 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3431 "\\|") "\\)\\>")
3432 org-not-done-regexp
3433 (concat "\\<\\("
3434 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3435 "\\)\\>")
3436 org-todo-line-regexp
3437 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3438 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3439 "\\)\\>\\)?[ \t]*\\(.*\\)")
3440 org-complex-heading-regexp
3441 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3442 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3443 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3444 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3445 org-nl-done-regexp
3446 (concat "\n\\*+[ \t]+"
3447 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3448 "\\)" "\\>")
3449 org-todo-line-tags-regexp
3450 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3451 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3452 (org-re
3453 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3454 org-looking-at-done-regexp
3455 (concat "^" "\\(?:"
3456 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3457 "\\>")
3458 org-deadline-regexp (concat "\\<" org-deadline-string)
3459 org-deadline-time-regexp
3460 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3461 org-deadline-line-regexp
3462 (concat "\\<\\(" org-deadline-string "\\).*")
3463 org-scheduled-regexp
3464 (concat "\\<" org-scheduled-string)
3465 org-scheduled-time-regexp
3466 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3467 org-closed-time-regexp
3468 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3469 org-keyword-time-regexp
3470 (concat "\\<\\(" org-scheduled-string
3471 "\\|" org-deadline-string
3472 "\\|" org-closed-string
3473 "\\|" org-clock-string "\\)"
3474 " *[[<]\\([^]>]+\\)[]>]")
3475 org-keyword-time-not-clock-regexp
3476 (concat "\\<\\(" org-scheduled-string
3477 "\\|" org-deadline-string
3478 "\\|" org-closed-string
3479 "\\)"
3480 " *[[<]\\([^]>]+\\)[]>]")
3481 org-maybe-keyword-time-regexp
3482 (concat "\\(\\<\\(" org-scheduled-string
3483 "\\|" org-deadline-string
3484 "\\|" org-closed-string
3485 "\\|" org-clock-string "\\)\\)?"
3486 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3487 org-planning-or-clock-line-re
3488 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3489 "\\|" org-deadline-string
3490 "\\|" org-closed-string "\\|" org-clock-string
3491 "\\)\\>\\)")
3493 (org-compute-latex-and-specials-regexp)
3494 (org-set-font-lock-defaults))))
3496 (defun org-file-contents (file &optional noerror)
3497 "Return the contents of FILE, as a string."
3498 (if (or (not file)
3499 (not (file-readable-p file)))
3500 (if noerror
3501 (progn
3502 (message "Cannot read file %s" file)
3503 (ding) (sit-for 2)
3505 (error "Cannot read file %s" file))
3506 (with-temp-buffer
3507 (insert-file-contents file)
3508 (buffer-string))))
3510 (defun org-extract-log-state-settings (x)
3511 "Extract the log state setting from a TODO keyword string.
3512 This will extract info from a string like \"WAIT(w@/!)\"."
3513 (let (kw key log1 log2)
3514 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3515 (setq kw (match-string 1 x)
3516 key (and (match-end 2) (match-string 2 x))
3517 log1 (and (match-end 3) (match-string 3 x))
3518 log2 (and (match-end 4) (match-string 4 x)))
3519 (and (or log1 log2)
3520 (list kw
3521 (and log1 (if (equal log1 "!") 'time 'note))
3522 (and log2 (if (equal log2 "!") 'time 'note)))))))
3524 (defun org-remove-keyword-keys (list)
3525 "Remove a pair of parenthesis at the end of each string in LIST."
3526 (mapcar (lambda (x)
3527 (if (string-match "(.*)$" x)
3528 (substring x 0 (match-beginning 0))
3530 list))
3532 ;; FIXME: this could be done much better, using second characters etc.
3533 (defun org-assign-fast-keys (alist)
3534 "Assign fast keys to a keyword-key alist.
3535 Respect keys that are already there."
3536 (let (new e k c c1 c2 (char ?a))
3537 (while (setq e (pop alist))
3538 (cond
3539 ((equal e '(:startgroup)) (push e new))
3540 ((equal e '(:endgroup)) (push e new))
3541 ((equal e '(:newline)) (push e new))
3543 (setq k (car e) c2 nil)
3544 (if (cdr e)
3545 (setq c (cdr e))
3546 ;; automatically assign a character.
3547 (setq c1 (string-to-char
3548 (downcase (substring
3549 k (if (= (string-to-char k) ?@) 1 0)))))
3550 (if (or (rassoc c1 new) (rassoc c1 alist))
3551 (while (or (rassoc char new) (rassoc char alist))
3552 (setq char (1+ char)))
3553 (setq c2 c1))
3554 (setq c (or c2 char)))
3555 (push (cons k c) new))))
3556 (nreverse new)))
3558 ;;; Some variables used in various places
3560 (defvar org-window-configuration nil
3561 "Used in various places to store a window configuration.")
3562 (defvar org-finish-function nil
3563 "Function to be called when `C-c C-c' is used.
3564 This is for getting out of special buffers like remember.")
3567 ;; FIXME: Occasionally check by commenting these, to make sure
3568 ;; no other functions uses these, forgetting to let-bind them.
3569 (defvar entry)
3570 (defvar state)
3571 (defvar last-state)
3572 (defvar date)
3573 (defvar description)
3575 ;; Defined somewhere in this file, but used before definition.
3576 (defvar org-html-entities)
3577 (defvar org-struct-menu)
3578 (defvar org-org-menu)
3579 (defvar org-tbl-menu)
3580 (defvar org-agenda-keymap)
3582 ;;;; Define the Org-mode
3584 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3585 (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."))
3588 ;; We use a before-change function to check if a table might need
3589 ;; an update.
3590 (defvar org-table-may-need-update t
3591 "Indicates that a table might need an update.
3592 This variable is set by `org-before-change-function'.
3593 `org-table-align' sets it back to nil.")
3594 (defun org-before-change-function (beg end)
3595 "Every change indicates that a table might need an update."
3596 (setq org-table-may-need-update t))
3597 (defvar org-mode-map)
3598 (defvar org-mode-hook nil
3599 "Mode hook for Org-mode, run after the mode was turned on.")
3600 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3601 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3602 (defvar org-table-buffer-is-an nil)
3603 (defconst org-outline-regexp "\\*+ ")
3605 ;;;###autoload
3606 (define-derived-mode org-mode outline-mode "Org"
3607 "Outline-based notes management and organizer, alias
3608 \"Carsten's outline-mode for keeping track of everything.\"
3610 Org-mode develops organizational tasks around a NOTES file which
3611 contains information about projects as plain text. Org-mode is
3612 implemented on top of outline-mode, which is ideal to keep the content
3613 of large files well structured. It supports ToDo items, deadlines and
3614 time stamps, which magically appear in the diary listing of the Emacs
3615 calendar. Tables are easily created with a built-in table editor.
3616 Plain text URL-like links connect to websites, emails (VM), Usenet
3617 messages (Gnus), BBDB entries, and any files related to the project.
3618 For printing and sharing of notes, an Org-mode file (or a part of it)
3619 can be exported as a structured ASCII or HTML file.
3621 The following commands are available:
3623 \\{org-mode-map}"
3625 ;; Get rid of Outline menus, they are not needed
3626 ;; Need to do this here because define-derived-mode sets up
3627 ;; the keymap so late. Still, it is a waste to call this each time
3628 ;; we switch another buffer into org-mode.
3629 (if (featurep 'xemacs)
3630 (when (boundp 'outline-mode-menu-heading)
3631 ;; Assume this is Greg's port, it used easymenu
3632 (easy-menu-remove outline-mode-menu-heading)
3633 (easy-menu-remove outline-mode-menu-show)
3634 (easy-menu-remove outline-mode-menu-hide))
3635 (define-key org-mode-map [menu-bar headings] 'undefined)
3636 (define-key org-mode-map [menu-bar hide] 'undefined)
3637 (define-key org-mode-map [menu-bar show] 'undefined))
3639 (org-load-modules-maybe)
3640 (easy-menu-add org-org-menu)
3641 (easy-menu-add org-tbl-menu)
3642 (org-install-agenda-files-menu)
3643 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3644 (org-add-to-invisibility-spec '(org-cwidth))
3645 (when (featurep 'xemacs)
3646 (org-set-local 'line-move-ignore-invisible t))
3647 (org-set-local 'outline-regexp org-outline-regexp)
3648 (org-set-local 'outline-level 'org-outline-level)
3649 (when (and org-ellipsis
3650 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3651 (fboundp 'make-glyph-code))
3652 (unless org-display-table
3653 (setq org-display-table (make-display-table)))
3654 (set-display-table-slot
3655 org-display-table 4
3656 (vconcat (mapcar
3657 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3658 org-ellipsis)))
3659 (if (stringp org-ellipsis) org-ellipsis "..."))))
3660 (setq buffer-display-table org-display-table))
3661 (org-set-regexps-and-options)
3662 (when (and org-tag-faces (not org-tags-special-faces-re))
3663 ;; tag faces set outside customize.... force initialization.
3664 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3665 ;; Calc embedded
3666 (org-set-local 'calc-embedded-open-mode "# ")
3667 (modify-syntax-entry ?# "<")
3668 (modify-syntax-entry ?@ "w")
3669 (if org-startup-truncated (setq truncate-lines t))
3670 (org-set-local 'font-lock-unfontify-region-function
3671 'org-unfontify-region)
3672 ;; Activate before-change-function
3673 (org-set-local 'org-table-may-need-update t)
3674 (org-add-hook 'before-change-functions 'org-before-change-function nil
3675 'local)
3676 ;; Check for running clock before killing a buffer
3677 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3678 ;; Paragraphs and auto-filling
3679 (org-set-autofill-regexps)
3680 (setq indent-line-function 'org-indent-line-function)
3681 (org-update-radio-target-regexp)
3682 ;; Make sure dependence stuff works reliably, even for users who set it
3683 ;; too late :-(
3684 (if org-enforce-todo-dependencies
3685 (add-hook 'org-blocker-hook
3686 'org-block-todo-from-children-or-siblings)
3687 (remove-hook 'org-blocker-hook
3688 'org-block-todo-from-children-or-siblings))
3689 (if org-enforce-todo-checkbox-dependencies
3690 (add-hook 'org-blocker-hook
3691 'org-block-todo-from-checkboxes)
3692 (remove-hook 'org-blocker-hook
3693 'org-block-todo-from-checkboxes))
3695 ;; Comment characters
3696 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3697 (org-set-local 'comment-padding " ")
3699 ;; Align options lines
3700 (org-set-local
3701 'align-mode-rules-list
3702 '((org-in-buffer-settings
3703 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3704 (modes . '(org-mode)))))
3706 ;; Imenu
3707 (org-set-local 'imenu-create-index-function
3708 'org-imenu-get-tree)
3710 ;; Make isearch reveal context
3711 (if (or (featurep 'xemacs)
3712 (not (boundp 'outline-isearch-open-invisible-function)))
3713 ;; Emacs 21 and XEmacs make use of the hook
3714 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3715 ;; Emacs 22 deals with this through a special variable
3716 (org-set-local 'outline-isearch-open-invisible-function
3717 (lambda (&rest ignore) (org-show-context 'isearch))))
3719 ;; If empty file that did not turn on org-mode automatically, make it to.
3720 (if (and org-insert-mode-line-in-empty-file
3721 (interactive-p)
3722 (= (point-min) (point-max)))
3723 (insert "# -*- mode: org -*-\n\n"))
3725 (unless org-inhibit-startup
3726 (when org-startup-align-all-tables
3727 (let ((bmp (buffer-modified-p)))
3728 (org-table-map-tables 'org-table-align)
3729 (set-buffer-modified-p bmp)))
3730 (org-set-startup-visibility)))
3732 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3734 (defun org-current-time ()
3735 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3736 (if (> (car org-time-stamp-rounding-minutes) 1)
3737 (let ((r (car org-time-stamp-rounding-minutes))
3738 (time (decode-time)))
3739 (apply 'encode-time
3740 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3741 (nthcdr 2 time))))
3742 (current-time)))
3744 ;;;; Font-Lock stuff, including the activators
3746 (defvar org-mouse-map (make-sparse-keymap))
3747 (org-defkey org-mouse-map
3748 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3749 (org-defkey org-mouse-map
3750 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3751 (when org-mouse-1-follows-link
3752 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3753 (when org-tab-follows-link
3754 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3755 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3757 (require 'font-lock)
3759 (defconst org-non-link-chars "]\t\n\r<>")
3760 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3761 "shell" "elisp"))
3762 (defvar org-link-types-re nil
3763 "Matches a link that has a url-like prefix like \"http:\"")
3764 (defvar org-link-re-with-space nil
3765 "Matches a link with spaces, optional angular brackets around it.")
3766 (defvar org-link-re-with-space2 nil
3767 "Matches a link with spaces, optional angular brackets around it.")
3768 (defvar org-link-re-with-space3 nil
3769 "Matches a link with spaces, only for internal part in bracket links.")
3770 (defvar org-angle-link-re nil
3771 "Matches link with angular brackets, spaces are allowed.")
3772 (defvar org-plain-link-re nil
3773 "Matches plain link, without spaces.")
3774 (defvar org-bracket-link-regexp nil
3775 "Matches a link in double brackets.")
3776 (defvar org-bracket-link-analytic-regexp nil
3777 "Regular expression used to analyze links.
3778 Here is what the match groups contain after a match:
3779 1: http:
3780 2: http
3781 3: path
3782 4: [desc]
3783 5: desc")
3784 (defvar org-bracket-link-analytic-regexp++ nil
3785 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3786 (defvar org-any-link-re nil
3787 "Regular expression matching any link.")
3789 (defun org-make-link-regexps ()
3790 "Update the link regular expressions.
3791 This should be called after the variable `org-link-types' has changed."
3792 (setq org-link-types-re
3793 (concat
3794 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3795 org-link-re-with-space
3796 (concat
3797 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3798 "\\([^" org-non-link-chars " ]"
3799 "[^" org-non-link-chars "]*"
3800 "[^" org-non-link-chars " ]\\)>?")
3801 org-link-re-with-space2
3802 (concat
3803 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3804 "\\([^" org-non-link-chars " ]"
3805 "[^\t\n\r]*"
3806 "[^" org-non-link-chars " ]\\)>?")
3807 org-link-re-with-space3
3808 (concat
3809 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3810 "\\([^" org-non-link-chars " ]"
3811 "[^\t\n\r]*\\)")
3812 org-angle-link-re
3813 (concat
3814 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3815 "\\([^" org-non-link-chars " ]"
3816 "[^" org-non-link-chars "]*"
3817 "\\)>")
3818 org-plain-link-re
3819 (concat
3820 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3821 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3822 org-bracket-link-regexp
3823 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3824 org-bracket-link-analytic-regexp
3825 (concat
3826 "\\[\\["
3827 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3828 "\\([^]]+\\)"
3829 "\\]"
3830 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3831 "\\]")
3832 org-bracket-link-analytic-regexp++
3833 (concat
3834 "\\[\\["
3835 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3836 "\\([^]]+\\)"
3837 "\\]"
3838 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3839 "\\]")
3840 org-any-link-re
3841 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3842 org-angle-link-re "\\)\\|\\("
3843 org-plain-link-re "\\)")))
3845 (org-make-link-regexps)
3847 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3848 "Regular expression for fast time stamp matching.")
3849 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3850 "Regular expression for fast time stamp matching.")
3851 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3852 "Regular expression matching time strings for analysis.
3853 This one does not require the space after the date, so it can be used
3854 on a string that terminates immediately after the date.")
3855 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3856 "Regular expression matching time strings for analysis.")
3857 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3858 "Regular expression matching time stamps, with groups.")
3859 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3860 "Regular expression matching time stamps (also [..]), with groups.")
3861 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3862 "Regular expression matching a time stamp range.")
3863 (defconst org-tr-regexp-both
3864 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3865 "Regular expression matching a time stamp range.")
3866 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3867 org-ts-regexp "\\)?")
3868 "Regular expression matching a time stamp or time stamp range.")
3869 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3870 org-ts-regexp-both "\\)?")
3871 "Regular expression matching a time stamp or time stamp range.
3872 The time stamps may be either active or inactive.")
3874 (defvar org-emph-face nil)
3876 (defun org-do-emphasis-faces (limit)
3877 "Run through the buffer and add overlays to links."
3878 (let (rtn)
3879 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3880 (if (not (= (char-after (match-beginning 3))
3881 (char-after (match-beginning 4))))
3882 (progn
3883 (setq rtn t)
3884 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3885 'face
3886 (nth 1 (assoc (match-string 3)
3887 org-emphasis-alist)))
3888 (add-text-properties (match-beginning 2) (match-end 2)
3889 '(font-lock-multiline t))
3890 (when org-hide-emphasis-markers
3891 (add-text-properties (match-end 4) (match-beginning 5)
3892 '(invisible org-link))
3893 (add-text-properties (match-beginning 3) (match-end 3)
3894 '(invisible org-link)))))
3895 (backward-char 1))
3896 rtn))
3898 (defun org-emphasize (&optional char)
3899 "Insert or change an emphasis, i.e. a font like bold or italic.
3900 If there is an active region, change that region to a new emphasis.
3901 If there is no region, just insert the marker characters and position
3902 the cursor between them.
3903 CHAR should be either the marker character, or the first character of the
3904 HTML tag associated with that emphasis. If CHAR is a space, the means
3905 to remove the emphasis of the selected region.
3906 If char is not given (for example in an interactive call) it
3907 will be prompted for."
3908 (interactive)
3909 (let ((eal org-emphasis-alist) e det
3910 (erc org-emphasis-regexp-components)
3911 (prompt "")
3912 (string "") beg end move tag c s)
3913 (if (org-region-active-p)
3914 (setq beg (region-beginning) end (region-end)
3915 string (buffer-substring beg end))
3916 (setq move t))
3918 (while (setq e (pop eal))
3919 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3920 c (aref tag 0))
3921 (push (cons c (string-to-char (car e))) det)
3922 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3923 (substring tag 1)))))
3924 (setq det (nreverse det))
3925 (unless char
3926 (message "%s" (concat "Emphasis marker or tag:" prompt))
3927 (setq char (read-char-exclusive)))
3928 (setq char (or (cdr (assoc char det)) char))
3929 (if (equal char ?\ )
3930 (setq s "" move nil)
3931 (unless (assoc (char-to-string char) org-emphasis-alist)
3932 (error "No such emphasis marker: \"%c\"" char))
3933 (setq s (char-to-string char)))
3934 (while (and (> (length string) 1)
3935 (equal (substring string 0 1) (substring string -1))
3936 (assoc (substring string 0 1) org-emphasis-alist))
3937 (setq string (substring string 1 -1)))
3938 (setq string (concat s string s))
3939 (if beg (delete-region beg end))
3940 (unless (or (bolp)
3941 (string-match (concat "[" (nth 0 erc) "\n]")
3942 (char-to-string (char-before (point)))))
3943 (insert " "))
3944 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3945 (char-to-string (char-after (point))))
3946 (insert " ") (backward-char 1))
3947 (insert string)
3948 (and move (backward-char 1))))
3950 (defconst org-nonsticky-props
3951 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3954 (defun org-activate-plain-links (limit)
3955 "Run through the buffer and add overlays to links."
3956 (catch 'exit
3957 (let (f)
3958 (while (re-search-forward org-plain-link-re limit t)
3959 (setq f (get-text-property (match-beginning 0) 'face))
3960 (if (or (eq f 'org-tag)
3961 (and (listp f) (memq 'org-tag f)))
3963 (add-text-properties (match-beginning 0) (match-end 0)
3964 (list 'mouse-face 'highlight
3965 'rear-nonsticky org-nonsticky-props
3966 'keymap org-mouse-map
3968 (throw 'exit t))))))
3970 (defun org-activate-code (limit)
3971 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3972 (progn
3973 (remove-text-properties (match-beginning 0) (match-end 0)
3974 '(display t invisible t intangible t))
3975 t)))
3977 (defun org-activate-angle-links (limit)
3978 "Run through the buffer and add overlays to links."
3979 (if (re-search-forward org-angle-link-re limit t)
3980 (progn
3981 (add-text-properties (match-beginning 0) (match-end 0)
3982 (list 'mouse-face 'highlight
3983 'rear-nonsticky org-nonsticky-props
3984 'keymap org-mouse-map
3986 t)))
3988 (defun org-activate-footnote-links (limit)
3989 "Run through the buffer and add overlays to links."
3990 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3991 limit t)
3992 (progn
3993 (add-text-properties (match-beginning 2) (match-end 2)
3994 (list 'mouse-face 'highlight
3995 'rear-nonsticky org-nonsticky-props
3996 'keymap org-mouse-map
3997 'help-echo
3998 (if (= (point-at-bol) (match-beginning 2))
3999 "Footnote definition"
4000 "Footnote reference")
4002 t)))
4004 (defun org-activate-bracket-links (limit)
4005 "Run through the buffer and add overlays to bracketed links."
4006 (if (re-search-forward org-bracket-link-regexp limit t)
4007 (let* ((help (concat "LINK: "
4008 (org-match-string-no-properties 1)))
4009 ;; FIXME: above we should remove the escapes.
4010 ;; but that requires another match, protecting match data,
4011 ;; a lot of overhead for font-lock.
4012 (ip (org-maybe-intangible
4013 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4014 'keymap org-mouse-map 'mouse-face 'highlight
4015 'font-lock-multiline t 'help-echo help)))
4016 (vp (list 'rear-nonsticky org-nonsticky-props
4017 'keymap org-mouse-map 'mouse-face 'highlight
4018 ' font-lock-multiline t 'help-echo help)))
4019 ;; We need to remove the invisible property here. Table narrowing
4020 ;; may have made some of this invisible.
4021 (remove-text-properties (match-beginning 0) (match-end 0)
4022 '(invisible nil))
4023 (if (match-end 3)
4024 (progn
4025 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4026 (add-text-properties (match-beginning 3) (match-end 3) vp)
4027 (add-text-properties (match-end 3) (match-end 0) ip))
4028 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4029 (add-text-properties (match-beginning 1) (match-end 1) vp)
4030 (add-text-properties (match-end 1) (match-end 0) ip))
4031 t)))
4033 (defun org-activate-dates (limit)
4034 "Run through the buffer and add overlays to dates."
4035 (if (re-search-forward org-tsr-regexp-both limit t)
4036 (progn
4037 (add-text-properties (match-beginning 0) (match-end 0)
4038 (list 'mouse-face 'highlight
4039 'rear-nonsticky org-nonsticky-props
4040 'keymap org-mouse-map))
4041 (when org-display-custom-times
4042 (if (match-end 3)
4043 (org-display-custom-time (match-beginning 3) (match-end 3)))
4044 (org-display-custom-time (match-beginning 1) (match-end 1)))
4045 t)))
4047 (defvar org-target-link-regexp nil
4048 "Regular expression matching radio targets in plain text.")
4049 (make-variable-buffer-local 'org-target-link-regexp)
4050 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4051 "Regular expression matching a link target.")
4052 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4053 "Regular expression matching a radio target.")
4054 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4055 "Regular expression matching any target.")
4057 (defun org-activate-target-links (limit)
4058 "Run through the buffer and add overlays to target matches."
4059 (when org-target-link-regexp
4060 (let ((case-fold-search t))
4061 (if (re-search-forward org-target-link-regexp limit t)
4062 (progn
4063 (add-text-properties (match-beginning 0) (match-end 0)
4064 (list 'mouse-face 'highlight
4065 'rear-nonsticky org-nonsticky-props
4066 'keymap org-mouse-map
4067 'help-echo "Radio target link"
4068 'org-linked-text t))
4069 t)))))
4071 (defun org-update-radio-target-regexp ()
4072 "Find all radio targets in this file and update the regular expression."
4073 (interactive)
4074 (when (memq 'radio org-activate-links)
4075 (setq org-target-link-regexp
4076 (org-make-target-link-regexp (org-all-targets 'radio)))
4077 (org-restart-font-lock)))
4079 (defun org-hide-wide-columns (limit)
4080 (let (s e)
4081 (setq s (text-property-any (point) (or limit (point-max))
4082 'org-cwidth t))
4083 (when s
4084 (setq e (next-single-property-change s 'org-cwidth))
4085 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4086 (goto-char e)
4087 t)))
4089 (defvar org-latex-and-specials-regexp nil
4090 "Regular expression for highlighting export special stuff.")
4091 (defvar org-match-substring-regexp)
4092 (defvar org-match-substring-with-braces-regexp)
4093 (defvar org-export-html-special-string-regexps)
4095 (defun org-compute-latex-and-specials-regexp ()
4096 "Compute regular expression for stuff treated specially by exporters."
4097 (if (not org-highlight-latex-fragments-and-specials)
4098 (org-set-local 'org-latex-and-specials-regexp nil)
4099 (require 'org-exp)
4100 (let*
4101 ((matchers (plist-get org-format-latex-options :matchers))
4102 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4103 org-latex-regexps)))
4104 (options (org-combine-plists (org-default-export-plist)
4105 (org-infile-export-plist)))
4106 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4107 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4108 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4109 (org-export-html-expand (plist-get options :expand-quoted-html))
4110 (org-export-with-special-strings (plist-get options :special-strings))
4111 (re-sub
4112 (cond
4113 ((equal org-export-with-sub-superscripts '{})
4114 (list org-match-substring-with-braces-regexp))
4115 (org-export-with-sub-superscripts
4116 (list org-match-substring-regexp))
4117 (t nil)))
4118 (re-latex
4119 (if org-export-with-LaTeX-fragments
4120 (mapcar (lambda (x) (nth 1 x)) latexs)))
4121 (re-macros
4122 (if org-export-with-TeX-macros
4123 (list (concat "\\\\"
4124 (regexp-opt
4125 (append (mapcar 'car org-html-entities)
4126 (if (boundp 'org-latex-entities)
4127 org-latex-entities nil))
4128 'words))) ; FIXME
4130 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4131 (re-special (if org-export-with-special-strings
4132 (mapcar (lambda (x) (car x))
4133 org-export-html-special-string-regexps)))
4134 (re-rest
4135 (delq nil
4136 (list
4137 (if org-export-html-expand "@<[^>\n]+>")
4138 ))))
4139 (org-set-local
4140 'org-latex-and-specials-regexp
4141 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4142 re-rest) "\\|")))))
4144 (defun org-do-latex-and-special-faces (limit)
4145 "Run through the buffer and add overlays to links."
4146 (when org-latex-and-specials-regexp
4147 (let (rtn d)
4148 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4149 limit t))
4150 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4151 'face))
4152 '(org-code org-verbatim underline)))
4153 (progn
4154 (setq rtn t
4155 d (cond ((member (char-after (1+ (match-beginning 0)))
4156 '(?_ ?^)) 1)
4157 (t 0)))
4158 (font-lock-prepend-text-property
4159 (+ d (match-beginning 0)) (match-end 0)
4160 'face 'org-latex-and-export-specials)
4161 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4162 '(font-lock-multiline t)))))
4163 rtn)))
4165 (defun org-restart-font-lock ()
4166 "Restart font-lock-mode, to force refontification."
4167 (when (and (boundp 'font-lock-mode) font-lock-mode)
4168 (font-lock-mode -1)
4169 (font-lock-mode 1)))
4171 (defun org-all-targets (&optional radio)
4172 "Return a list of all targets in this file.
4173 With optional argument RADIO, only find radio targets."
4174 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4175 rtn)
4176 (save-excursion
4177 (goto-char (point-min))
4178 (while (re-search-forward re nil t)
4179 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4180 rtn)))
4182 (defun org-make-target-link-regexp (targets)
4183 "Make regular expression matching all strings in TARGETS.
4184 The regular expression finds the targets also if there is a line break
4185 between words."
4186 (and targets
4187 (concat
4188 "\\<\\("
4189 (mapconcat
4190 (lambda (x)
4191 (while (string-match " +" x)
4192 (setq x (replace-match "\\s-+" t t x)))
4194 targets
4195 "\\|")
4196 "\\)\\>")))
4198 (defun org-activate-tags (limit)
4199 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4200 (progn
4201 (add-text-properties (match-beginning 1) (match-end 1)
4202 (list 'mouse-face 'highlight
4203 'rear-nonsticky org-nonsticky-props
4204 'keymap org-mouse-map))
4205 t)))
4207 (defun org-outline-level ()
4208 (save-excursion
4209 (looking-at outline-regexp)
4210 (if (match-beginning 1)
4211 (+ (org-get-string-indentation (match-string 1)) 1000)
4212 (1- (- (match-end 0) (match-beginning 0))))))
4214 (defvar org-font-lock-keywords nil)
4216 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4217 "Regular expression matching a property line.")
4219 (defvar org-font-lock-hook nil
4220 "Functions to be called for special font lock stuff.")
4222 (defun org-font-lock-hook (limit)
4223 (run-hook-with-args 'org-font-lock-hook limit))
4225 (defun org-set-font-lock-defaults ()
4226 (let* ((em org-fontify-emphasized-text)
4227 (lk org-activate-links)
4228 (org-font-lock-extra-keywords
4229 (list
4230 ;; Call the hook
4231 '(org-font-lock-hook)
4232 ;; Headlines
4233 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4234 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4235 ;; Table lines
4236 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4237 (1 'org-table t))
4238 ;; Table internals
4239 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4240 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4241 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4242 ;; Drawers
4243 (list org-drawer-regexp '(0 'org-special-keyword t))
4244 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4245 ;; Properties
4246 (list org-property-re
4247 '(1 'org-special-keyword t)
4248 '(3 'org-property-value t))
4249 (if org-format-transports-properties-p
4250 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4251 ;; Links
4252 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4253 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4254 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4255 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4256 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4257 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4258 (if (memq 'footnote lk) '(org-activate-footnote-links
4259 (2 'org-footnote t)))
4260 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4261 '(org-hide-wide-columns (0 nil append))
4262 ;; TODO lines
4263 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4264 '(1 (org-get-todo-face 1) t))
4265 ;; DONE
4266 (if org-fontify-done-headline
4267 (list (concat "^[*]+ +\\<\\("
4268 (mapconcat 'regexp-quote org-done-keywords "\\|")
4269 "\\)\\(.*\\)")
4270 '(2 'org-headline-done t))
4271 nil)
4272 ;; Priorities
4273 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4274 ;; Tags
4275 '(org-font-lock-add-tag-faces)
4276 ;; Special keywords
4277 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4278 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4279 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4280 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4281 ;; Emphasis
4282 (if em
4283 (if (featurep 'xemacs)
4284 '(org-do-emphasis-faces (0 nil append))
4285 '(org-do-emphasis-faces)))
4286 ;; Checkboxes
4287 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4288 2 'bold prepend)
4289 (if org-provide-checkbox-statistics
4290 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4291 (0 (org-get-checkbox-statistics-face) t)))
4292 ;; Description list items
4293 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4294 2 'bold prepend)
4295 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4296 '(1 'org-archived prepend))
4297 ;; Specials
4298 '(org-do-latex-and-special-faces)
4299 ;; Code
4300 '(org-activate-code (1 'org-code t))
4301 ;; COMMENT
4302 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4303 "\\|" org-quote-string "\\)\\>")
4304 '(1 'org-special-keyword t))
4305 '("^#.*" (0 'font-lock-comment-face t))
4307 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4308 ;; Now set the full font-lock-keywords
4309 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4310 (org-set-local 'font-lock-defaults
4311 '(org-font-lock-keywords t nil nil backward-paragraph))
4312 (kill-local-variable 'font-lock-keywords) nil))
4314 (defvar org-m nil)
4315 (defvar org-l nil)
4316 (defvar org-f nil)
4317 (defun org-get-level-face (n)
4318 "Get the right face for match N in font-lock matching of headlines."
4319 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4320 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4321 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4322 (cond
4323 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4324 ((eq n 2) org-f)
4325 (t (if org-level-color-stars-only nil org-f))))
4327 (defun org-get-todo-face (kwd)
4328 "Get the right face for a TODO keyword KWD.
4329 If KWD is a number, get the corresponding match group."
4330 (if (numberp kwd) (setq kwd (match-string kwd)))
4331 (or (cdr (assoc kwd org-todo-keyword-faces))
4332 (and (member kwd org-done-keywords) 'org-done)
4333 'org-todo))
4335 (defun org-font-lock-add-tag-faces (limit)
4336 "Add the special tag faces."
4337 (when (and org-tag-faces org-tags-special-faces-re)
4338 (while (re-search-forward org-tags-special-faces-re limit t)
4339 (add-text-properties (match-beginning 1) (match-end 1)
4340 (list 'face (org-get-tag-face 1)
4341 'font-lock-fontified t))
4342 (backward-char 1))))
4344 (defun org-get-tag-face (kwd)
4345 "Get the right face for a TODO keyword KWD.
4346 If KWD is a number, get the corresponding match group."
4347 (if (numberp kwd) (setq kwd (match-string kwd)))
4348 (or (cdr (assoc kwd org-tag-faces))
4349 'org-tag))
4351 (defun org-unfontify-region (beg end &optional maybe_loudly)
4352 "Remove fontification and activation overlays from links."
4353 (font-lock-default-unfontify-region beg end)
4354 (let* ((buffer-undo-list t)
4355 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4356 (inhibit-modification-hooks t)
4357 deactivate-mark buffer-file-name buffer-file-truename)
4358 (remove-text-properties beg end
4359 '(mouse-face t keymap t org-linked-text t
4360 invisible t intangible t))))
4362 ;;;; Visibility cycling, including org-goto and indirect buffer
4364 ;;; Cycling
4366 (defvar org-cycle-global-status nil)
4367 (make-variable-buffer-local 'org-cycle-global-status)
4368 (defvar org-cycle-subtree-status nil)
4369 (make-variable-buffer-local 'org-cycle-subtree-status)
4371 ;;;###autoload
4372 (defun org-cycle (&optional arg)
4373 "Visibility cycling for Org-mode.
4375 - When this function is called with a prefix argument, rotate the entire
4376 buffer through 3 states (global cycling)
4377 1. OVERVIEW: Show only top-level headlines.
4378 2. CONTENTS: Show all headlines of all levels, but no body text.
4379 3. SHOW ALL: Show everything.
4380 When called with two C-u C-u prefixes, switch to the startup visibility,
4381 determined by the variable `org-startup-folded', and by any VISIBILITY
4382 properties in the buffer.
4383 When called with three C-u C-u C-u prefixed, show the entire buffer,
4384 including drawers.
4386 - When point is at the beginning of a headline, rotate the subtree started
4387 by this line through 3 different states (local cycling)
4388 1. FOLDED: Only the main headline is shown.
4389 2. CHILDREN: The main headline and the direct children are shown.
4390 From this state, you can move to one of the children
4391 and zoom in further.
4392 3. SUBTREE: Show the entire subtree, including body text.
4394 - When there is a numeric prefix, go up to a heading with level ARG, do
4395 a `show-subtree' and return to the previous cursor position. If ARG
4396 is negative, go up that many levels.
4398 - When point is not at the beginning of a headline, execute the global
4399 binding for TAB, which is re-indenting the line. See the option
4400 `org-cycle-emulate-tab' for details.
4402 - Special case: if point is at the beginning of the buffer and there is
4403 no headline in line 1, this function will act as if called with prefix arg.
4404 But only if also the variable `org-cycle-global-at-bob' is t."
4405 (interactive "P")
4406 (org-load-modules-maybe)
4407 (let* ((outline-regexp
4408 (if (and (org-mode-p) org-cycle-include-plain-lists)
4409 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4410 outline-regexp))
4411 (bob-special (and org-cycle-global-at-bob (bobp)
4412 (not (looking-at outline-regexp))))
4413 (org-cycle-hook
4414 (if bob-special
4415 (delq 'org-optimize-window-after-visibility-change
4416 (copy-sequence org-cycle-hook))
4417 org-cycle-hook))
4418 (pos (point)))
4420 (if (or bob-special (equal arg '(4)))
4421 ;; special case: use global cycling
4422 (setq arg t))
4424 (cond
4426 ((equal arg '(16))
4427 (org-set-startup-visibility)
4428 (message "Startup visibility, plus VISIBILITY properties"))
4430 ((equal arg '(64))
4431 (show-all)
4432 (message "Entire buffer visible, including drawers"))
4434 ((org-at-table-p 'any)
4435 ;; Enter the table or move to the next field in the table
4436 (or (org-table-recognize-table.el)
4437 (progn
4438 (if arg (org-table-edit-field t)
4439 (org-table-justify-field-maybe)
4440 (call-interactively 'org-table-next-field)))))
4442 ((eq arg t) ;; Global cycling
4444 (cond
4445 ((and (eq last-command this-command)
4446 (eq org-cycle-global-status 'overview))
4447 ;; We just created the overview - now do table of contents
4448 ;; This can be slow in very large buffers, so indicate action
4449 (message "CONTENTS...")
4450 (org-content)
4451 (message "CONTENTS...done")
4452 (setq org-cycle-global-status 'contents)
4453 (run-hook-with-args 'org-cycle-hook 'contents))
4455 ((and (eq last-command this-command)
4456 (eq org-cycle-global-status 'contents))
4457 ;; We just showed the table of contents - now show everything
4458 (show-all)
4459 (message "SHOW ALL")
4460 (setq org-cycle-global-status 'all)
4461 (run-hook-with-args 'org-cycle-hook 'all))
4464 ;; Default action: go to overview
4465 (org-overview)
4466 (message "OVERVIEW")
4467 (setq org-cycle-global-status 'overview)
4468 (run-hook-with-args 'org-cycle-hook 'overview))))
4470 ((and org-drawers org-drawer-regexp
4471 (save-excursion
4472 (beginning-of-line 1)
4473 (looking-at org-drawer-regexp)))
4474 ;; Toggle block visibility
4475 (org-flag-drawer
4476 (not (get-char-property (match-end 0) 'invisible))))
4478 ((integerp arg)
4479 ;; Show-subtree, ARG levels up from here.
4480 (save-excursion
4481 (org-back-to-heading)
4482 (outline-up-heading (if (< arg 0) (- arg)
4483 (- (funcall outline-level) arg)))
4484 (org-show-subtree)))
4486 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4487 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4488 ;; At a heading: rotate between three different views
4489 (org-back-to-heading)
4490 (let ((goal-column 0) eoh eol eos)
4491 ;; First, some boundaries
4492 (save-excursion
4493 (org-back-to-heading)
4494 (save-excursion
4495 (beginning-of-line 2)
4496 (while (and (not (eobp)) ;; this is like `next-line'
4497 (get-char-property (1- (point)) 'invisible))
4498 (beginning-of-line 2)) (setq eol (point)))
4499 (outline-end-of-heading) (setq eoh (point))
4500 (org-end-of-subtree t)
4501 (unless (eobp)
4502 (skip-chars-forward " \t\n")
4503 (beginning-of-line 1) ; in case this is an item
4505 (setq eos (1- (point))))
4506 ;; Find out what to do next and set `this-command'
4507 (cond
4508 ((= eos eoh)
4509 ;; Nothing is hidden behind this heading
4510 (message "EMPTY ENTRY")
4511 (setq org-cycle-subtree-status nil)
4512 (save-excursion
4513 (goto-char eos)
4514 (outline-next-heading)
4515 (if (org-invisible-p) (org-flag-heading nil))))
4516 ((or (>= eol eos)
4517 (not (string-match "\\S-" (buffer-substring eol eos))))
4518 ;; Entire subtree is hidden in one line: open it
4519 (org-show-entry)
4520 (show-children)
4521 (message "CHILDREN")
4522 (save-excursion
4523 (goto-char eos)
4524 (outline-next-heading)
4525 (if (org-invisible-p) (org-flag-heading nil)))
4526 (setq org-cycle-subtree-status 'children)
4527 (run-hook-with-args 'org-cycle-hook 'children))
4528 ((and (eq last-command this-command)
4529 (eq org-cycle-subtree-status 'children))
4530 ;; We just showed the children, now show everything.
4531 (org-show-subtree)
4532 (message "SUBTREE")
4533 (setq org-cycle-subtree-status 'subtree)
4534 (run-hook-with-args 'org-cycle-hook 'subtree))
4536 ;; Default action: hide the subtree.
4537 (hide-subtree)
4538 (message "FOLDED")
4539 (setq org-cycle-subtree-status 'folded)
4540 (run-hook-with-args 'org-cycle-hook 'folded)))))
4542 ;; TAB emulation and template completion
4543 (buffer-read-only (org-back-to-heading))
4545 ((org-try-structure-completion))
4547 ((org-try-cdlatex-tab))
4549 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4550 (or (not (bolp))
4551 (not (looking-at outline-regexp))))
4552 (call-interactively (global-key-binding "\t")))
4554 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4555 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4556 (or (and (eq org-cycle-emulate-tab 'white)
4557 (= (match-end 0) (point-at-eol)))
4558 (and (eq org-cycle-emulate-tab 'whitestart)
4559 (>= (match-end 0) pos))))
4561 (eq org-cycle-emulate-tab t))
4562 (call-interactively (global-key-binding "\t")))
4564 (t (save-excursion
4565 (org-back-to-heading)
4566 (org-cycle))))))
4568 ;;;###autoload
4569 (defun org-global-cycle (&optional arg)
4570 "Cycle the global visibility. For details see `org-cycle'.
4571 With C-u prefix arg, switch to startup visibility.
4572 With a numeric prefix, show all headlines up to that level."
4573 (interactive "P")
4574 (let ((org-cycle-include-plain-lists
4575 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4576 (cond
4577 ((integerp arg)
4578 (show-all)
4579 (hide-sublevels arg)
4580 (setq org-cycle-global-status 'contents))
4581 ((equal arg '(4))
4582 (org-set-startup-visibility)
4583 (message "Startup visibility, plus VISIBILITY properties."))
4585 (org-cycle '(4))))))
4587 (defun org-set-startup-visibility ()
4588 "Set the visibility required by startup options and properties."
4589 (cond
4590 ((eq org-startup-folded t)
4591 (org-cycle '(4)))
4592 ((eq org-startup-folded 'content)
4593 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4594 (org-cycle '(4)) (org-cycle '(4)))))
4595 (org-set-visibility-according-to-property 'no-cleanup)
4596 (org-cycle-hide-archived-subtrees 'all)
4597 (org-cycle-hide-drawers 'all)
4598 (org-cycle-show-empty-lines 'all))
4600 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4601 "Switch subtree visibilities according to :VISIBILITY: property."
4602 (interactive)
4603 (let (org-show-entry-below state)
4604 (save-excursion
4605 (goto-char (point-min))
4606 (while (re-search-forward
4607 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4608 nil t)
4609 (setq state (match-string 1))
4610 (save-excursion
4611 (org-back-to-heading t)
4612 (hide-subtree)
4613 (org-reveal)
4614 (cond
4615 ((equal state '("fold" "folded"))
4616 (hide-subtree))
4617 ((equal state "children")
4618 (org-show-hidden-entry)
4619 (show-children))
4620 ((equal state "content")
4621 (save-excursion
4622 (save-restriction
4623 (org-narrow-to-subtree)
4624 (org-content))))
4625 ((member state '("all" "showall"))
4626 (show-subtree)))))
4627 (unless no-cleanup
4628 (org-cycle-hide-archived-subtrees 'all)
4629 (org-cycle-hide-drawers 'all)
4630 (org-cycle-show-empty-lines 'all)))))
4632 (defun org-overview ()
4633 "Switch to overview mode, showing only top-level headlines.
4634 Really, this shows all headlines with level equal or greater than the level
4635 of the first headline in the buffer. This is important, because if the
4636 first headline is not level one, then (hide-sublevels 1) gives confusing
4637 results."
4638 (interactive)
4639 (let ((level (save-excursion
4640 (goto-char (point-min))
4641 (if (re-search-forward (concat "^" outline-regexp) nil t)
4642 (progn
4643 (goto-char (match-beginning 0))
4644 (funcall outline-level))))))
4645 (and level (hide-sublevels level))))
4647 (defun org-content (&optional arg)
4648 "Show all headlines in the buffer, like a table of contents.
4649 With numerical argument N, show content up to level N."
4650 (interactive "P")
4651 (save-excursion
4652 ;; Visit all headings and show their offspring
4653 (and (integerp arg) (org-overview))
4654 (goto-char (point-max))
4655 (catch 'exit
4656 (while (and (progn (condition-case nil
4657 (outline-previous-visible-heading 1)
4658 (error (goto-char (point-min))))
4660 (looking-at outline-regexp))
4661 (if (integerp arg)
4662 (show-children (1- arg))
4663 (show-branches))
4664 (if (bobp) (throw 'exit nil))))))
4667 (defun org-optimize-window-after-visibility-change (state)
4668 "Adjust the window after a change in outline visibility.
4669 This function is the default value of the hook `org-cycle-hook'."
4670 (when (get-buffer-window (current-buffer))
4671 (cond
4672 ((eq state 'content) nil)
4673 ((eq state 'all) nil)
4674 ((eq state 'folded) nil)
4675 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4676 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4678 (defun org-compact-display-after-subtree-move ()
4679 "Show a compacter version of the tree of the entry's parent."
4680 (save-excursion
4681 (if (org-up-heading-safe)
4682 (progn
4683 (hide-subtree)
4684 (show-entry)
4685 (show-children)
4686 (org-cycle-show-empty-lines 'children)
4687 (org-cycle-hide-drawers 'children))
4688 (org-overview))))
4690 (defun org-cycle-show-empty-lines (state)
4691 "Show empty lines above all visible headlines.
4692 The region to be covered depends on STATE when called through
4693 `org-cycle-hook'. Lisp program can use t for STATE to get the
4694 entire buffer covered. Note that an empty line is only shown if there
4695 are at least `org-cycle-separator-lines' empty lines before the headline."
4696 (when (> org-cycle-separator-lines 0)
4697 (save-excursion
4698 (let* ((n org-cycle-separator-lines)
4699 (re (cond
4700 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4701 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4702 (t (let ((ns (number-to-string (- n 2))))
4703 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4704 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4705 beg end)
4706 (cond
4707 ((memq state '(overview contents t))
4708 (setq beg (point-min) end (point-max)))
4709 ((memq state '(children folded))
4710 (setq beg (point) end (progn (org-end-of-subtree t t)
4711 (beginning-of-line 2)
4712 (point)))))
4713 (when beg
4714 (goto-char beg)
4715 (while (re-search-forward re end t)
4716 (if (not (get-char-property (match-end 1) 'invisible))
4717 (outline-flag-region
4718 (match-beginning 1) (match-end 1) nil)))))))
4719 ;; Never hide empty lines at the end of the file.
4720 (save-excursion
4721 (goto-char (point-max))
4722 (outline-previous-heading)
4723 (outline-end-of-heading)
4724 (if (and (looking-at "[ \t\n]+")
4725 (= (match-end 0) (point-max)))
4726 (outline-flag-region (point) (match-end 0) nil))))
4728 (defun org-show-empty-lines-in-parent ()
4729 "Move to the parent and re-show empty lines before visible headlines."
4730 (save-excursion
4731 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4732 (org-cycle-show-empty-lines context))))
4734 (defun org-cycle-hide-drawers (state)
4735 "Re-hide all drawers after a visibility state change."
4736 (when (and (org-mode-p)
4737 (not (memq state '(overview folded))))
4738 (save-excursion
4739 (let* ((globalp (memq state '(contents all)))
4740 (beg (if globalp (point-min) (point)))
4741 (end (if globalp (point-max) (org-end-of-subtree t))))
4742 (goto-char beg)
4743 (while (re-search-forward org-drawer-regexp end t)
4744 (org-flag-drawer t))))))
4746 (defun org-flag-drawer (flag)
4747 (save-excursion
4748 (beginning-of-line 1)
4749 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4750 (let ((b (match-end 0))
4751 (outline-regexp org-outline-regexp))
4752 (if (re-search-forward
4753 "^[ \t]*:END:"
4754 (save-excursion (outline-next-heading) (point)) t)
4755 (outline-flag-region b (point-at-eol) flag)
4756 (error ":END: line missing"))))))
4758 (defun org-subtree-end-visible-p ()
4759 "Is the end of the current subtree visible?"
4760 (pos-visible-in-window-p
4761 (save-excursion (org-end-of-subtree t) (point))))
4763 (defun org-first-headline-recenter (&optional N)
4764 "Move cursor to the first headline and recenter the headline.
4765 Optional argument N means, put the headline into the Nth line of the window."
4766 (goto-char (point-min))
4767 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4768 (beginning-of-line)
4769 (recenter (prefix-numeric-value N))))
4771 ;;; Org-goto
4773 (defvar org-goto-window-configuration nil)
4774 (defvar org-goto-marker nil)
4775 (defvar org-goto-map
4776 (let ((map (make-sparse-keymap)))
4777 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4778 (while (setq cmd (pop cmds))
4779 (substitute-key-definition cmd cmd map global-map)))
4780 (suppress-keymap map)
4781 (org-defkey map "\C-m" 'org-goto-ret)
4782 (org-defkey map [(return)] 'org-goto-ret)
4783 (org-defkey map [(left)] 'org-goto-left)
4784 (org-defkey map [(right)] 'org-goto-right)
4785 (org-defkey map [(control ?g)] 'org-goto-quit)
4786 (org-defkey map "\C-i" 'org-cycle)
4787 (org-defkey map [(tab)] 'org-cycle)
4788 (org-defkey map [(down)] 'outline-next-visible-heading)
4789 (org-defkey map [(up)] 'outline-previous-visible-heading)
4790 (if org-goto-auto-isearch
4791 (if (fboundp 'define-key-after)
4792 (define-key-after map [t] 'org-goto-local-auto-isearch)
4793 nil)
4794 (org-defkey map "q" 'org-goto-quit)
4795 (org-defkey map "n" 'outline-next-visible-heading)
4796 (org-defkey map "p" 'outline-previous-visible-heading)
4797 (org-defkey map "f" 'outline-forward-same-level)
4798 (org-defkey map "b" 'outline-backward-same-level)
4799 (org-defkey map "u" 'outline-up-heading))
4800 (org-defkey map "/" 'org-occur)
4801 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4802 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4803 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4804 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4805 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4806 map))
4808 (defconst org-goto-help
4809 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4810 RET=jump to location [Q]uit and return to previous location
4811 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4813 (defvar org-goto-start-pos) ; dynamically scoped parameter
4815 ;; FIXME: Docstring doe not mention both interfaces
4816 (defun org-goto (&optional alternative-interface)
4817 "Look up a different location in the current file, keeping current visibility.
4819 When you want look-up or go to a different location in a document, the
4820 fastest way is often to fold the entire buffer and then dive into the tree.
4821 This method has the disadvantage, that the previous location will be folded,
4822 which may not be what you want.
4824 This command works around this by showing a copy of the current buffer
4825 in an indirect buffer, in overview mode. You can dive into the tree in
4826 that copy, use org-occur and incremental search to find a location.
4827 When pressing RET or `Q', the command returns to the original buffer in
4828 which the visibility is still unchanged. After RET is will also jump to
4829 the location selected in the indirect buffer and expose the
4830 the headline hierarchy above."
4831 (interactive "P")
4832 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4833 (org-refile-use-outline-path t)
4834 (interface
4835 (if (not alternative-interface)
4836 org-goto-interface
4837 (if (eq org-goto-interface 'outline)
4838 'outline-path-completion
4839 'outline)))
4840 (org-goto-start-pos (point))
4841 (selected-point
4842 (if (eq interface 'outline)
4843 (car (org-get-location (current-buffer) org-goto-help))
4844 (nth 3 (org-refile-get-location "Goto: ")))))
4845 (if selected-point
4846 (progn
4847 (org-mark-ring-push org-goto-start-pos)
4848 (goto-char selected-point)
4849 (if (or (org-invisible-p) (org-invisible-p2))
4850 (org-show-context 'org-goto)))
4851 (message "Quit"))))
4853 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4854 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4855 (defvar org-goto-local-auto-isearch-map) ; defined below
4857 (defun org-get-location (buf help)
4858 "Let the user select a location in the Org-mode buffer BUF.
4859 This function uses a recursive edit. It returns the selected position
4860 or nil."
4861 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4862 (isearch-hide-immediately nil)
4863 (isearch-search-fun-function
4864 (lambda () 'org-goto-local-search-headings))
4865 (org-goto-selected-point org-goto-exit-command))
4866 (save-excursion
4867 (save-window-excursion
4868 (delete-other-windows)
4869 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4870 (switch-to-buffer
4871 (condition-case nil
4872 (make-indirect-buffer (current-buffer) "*org-goto*")
4873 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4874 (with-output-to-temp-buffer "*Help*"
4875 (princ help))
4876 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4877 (setq buffer-read-only nil)
4878 (let ((org-startup-truncated t)
4879 (org-startup-folded nil)
4880 (org-startup-align-all-tables nil))
4881 (org-mode)
4882 (org-overview))
4883 (setq buffer-read-only t)
4884 (if (and (boundp 'org-goto-start-pos)
4885 (integer-or-marker-p org-goto-start-pos))
4886 (let ((org-show-hierarchy-above t)
4887 (org-show-siblings t)
4888 (org-show-following-heading t))
4889 (goto-char org-goto-start-pos)
4890 (and (org-invisible-p) (org-show-context)))
4891 (goto-char (point-min)))
4892 (let (org-special-ctrl-a/e) (org-beginning-of-line))
4893 (message "Select location and press RET")
4894 (use-local-map org-goto-map)
4895 (recursive-edit)
4897 (kill-buffer "*org-goto*")
4898 (cons org-goto-selected-point org-goto-exit-command)))
4900 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4901 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4902 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4903 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4905 (defun org-goto-local-search-headings (string bound noerror)
4906 "Search and make sure that any matches are in headlines."
4907 (catch 'return
4908 (while (if isearch-forward
4909 (search-forward string bound noerror)
4910 (search-backward string bound noerror))
4911 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4912 (and (member :headline context)
4913 (not (member :tags context))))
4914 (throw 'return (point))))))
4916 (defun org-goto-local-auto-isearch ()
4917 "Start isearch."
4918 (interactive)
4919 (goto-char (point-min))
4920 (let ((keys (this-command-keys)))
4921 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4922 (isearch-mode t)
4923 (isearch-process-search-char (string-to-char keys)))))
4925 (defun org-goto-ret (&optional arg)
4926 "Finish `org-goto' by going to the new location."
4927 (interactive "P")
4928 (setq org-goto-selected-point (point)
4929 org-goto-exit-command 'return)
4930 (throw 'exit nil))
4932 (defun org-goto-left ()
4933 "Finish `org-goto' by going to the new location."
4934 (interactive)
4935 (if (org-on-heading-p)
4936 (progn
4937 (beginning-of-line 1)
4938 (setq org-goto-selected-point (point)
4939 org-goto-exit-command 'left)
4940 (throw 'exit nil))
4941 (error "Not on a heading")))
4943 (defun org-goto-right ()
4944 "Finish `org-goto' by going to the new location."
4945 (interactive)
4946 (if (org-on-heading-p)
4947 (progn
4948 (setq org-goto-selected-point (point)
4949 org-goto-exit-command 'right)
4950 (throw 'exit nil))
4951 (error "Not on a heading")))
4953 (defun org-goto-quit ()
4954 "Finish `org-goto' without cursor motion."
4955 (interactive)
4956 (setq org-goto-selected-point nil)
4957 (setq org-goto-exit-command 'quit)
4958 (throw 'exit nil))
4960 ;;; Indirect buffer display of subtrees
4962 (defvar org-indirect-dedicated-frame nil
4963 "This is the frame being used for indirect tree display.")
4964 (defvar org-last-indirect-buffer nil)
4966 (defun org-tree-to-indirect-buffer (&optional arg)
4967 "Create indirect buffer and narrow it to current subtree.
4968 With numerical prefix ARG, go up to this level and then take that tree.
4969 If ARG is negative, go up that many levels.
4970 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4971 indirect buffer previously made with this command, to avoid proliferation of
4972 indirect buffers. However, when you call the command with a `C-u' prefix, or
4973 when `org-indirect-buffer-display' is `new-frame', the last buffer
4974 is kept so that you can work with several indirect buffers at the same time.
4975 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4976 requests that a new frame be made for the new buffer, so that the dedicated
4977 frame is not changed."
4978 (interactive "P")
4979 (let ((cbuf (current-buffer))
4980 (cwin (selected-window))
4981 (pos (point))
4982 beg end level heading ibuf)
4983 (save-excursion
4984 (org-back-to-heading t)
4985 (when (numberp arg)
4986 (setq level (org-outline-level))
4987 (if (< arg 0) (setq arg (+ level arg)))
4988 (while (> (setq level (org-outline-level)) arg)
4989 (outline-up-heading 1 t)))
4990 (setq beg (point)
4991 heading (org-get-heading))
4992 (org-end-of-subtree t) (setq end (point)))
4993 (if (and (buffer-live-p org-last-indirect-buffer)
4994 (not (eq org-indirect-buffer-display 'new-frame))
4995 (not arg))
4996 (kill-buffer org-last-indirect-buffer))
4997 (setq ibuf (org-get-indirect-buffer cbuf)
4998 org-last-indirect-buffer ibuf)
4999 (cond
5000 ((or (eq org-indirect-buffer-display 'new-frame)
5001 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5002 (select-frame (make-frame))
5003 (delete-other-windows)
5004 (switch-to-buffer ibuf)
5005 (org-set-frame-title heading))
5006 ((eq org-indirect-buffer-display 'dedicated-frame)
5007 (raise-frame
5008 (select-frame (or (and org-indirect-dedicated-frame
5009 (frame-live-p org-indirect-dedicated-frame)
5010 org-indirect-dedicated-frame)
5011 (setq org-indirect-dedicated-frame (make-frame)))))
5012 (delete-other-windows)
5013 (switch-to-buffer ibuf)
5014 (org-set-frame-title (concat "Indirect: " heading)))
5015 ((eq org-indirect-buffer-display 'current-window)
5016 (switch-to-buffer ibuf))
5017 ((eq org-indirect-buffer-display 'other-window)
5018 (pop-to-buffer ibuf))
5019 (t (error "Invalid value.")))
5020 (if (featurep 'xemacs)
5021 (save-excursion (org-mode) (turn-on-font-lock)))
5022 (narrow-to-region beg end)
5023 (show-all)
5024 (goto-char pos)
5025 (and (window-live-p cwin) (select-window cwin))))
5027 (defun org-get-indirect-buffer (&optional buffer)
5028 (setq buffer (or buffer (current-buffer)))
5029 (let ((n 1) (base (buffer-name buffer)) bname)
5030 (while (buffer-live-p
5031 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5032 (setq n (1+ n)))
5033 (condition-case nil
5034 (make-indirect-buffer buffer bname 'clone)
5035 (error (make-indirect-buffer buffer bname)))))
5037 (defun org-set-frame-title (title)
5038 "Set the title of the current frame to the string TITLE."
5039 ;; FIXME: how to name a single frame in XEmacs???
5040 (unless (featurep 'xemacs)
5041 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5043 ;;;; Structure editing
5045 ;;; Inserting headlines
5047 (defun org-previous-line-empty-p ()
5048 (save-excursion
5049 (and (not (bobp))
5050 (or (beginning-of-line 0) t)
5051 (save-match-data
5052 (looking-at "[ \t]*$")))))
5054 (defun org-insert-heading (&optional force-heading)
5055 "Insert a new heading or item with same depth at point.
5056 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5057 If point is at the beginning of a headline, insert a sibling before the
5058 current headline. If point is not at the beginning, do not split the line,
5059 but create the new headline after the current line."
5060 (interactive "P")
5061 (if (= (buffer-size) 0)
5062 (insert "\n* ")
5063 (when (or force-heading (not (org-insert-item)))
5064 (let* ((empty-line-p nil)
5065 (head (save-excursion
5066 (condition-case nil
5067 (progn
5068 (org-back-to-heading)
5069 (setq empty-line-p (org-previous-line-empty-p))
5070 (match-string 0))
5071 (error "*"))))
5072 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5073 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5074 pos hide-previous previous-pos)
5075 (cond
5076 ((and (org-on-heading-p) (bolp)
5077 (or (bobp)
5078 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5079 ;; insert before the current line
5080 (open-line (if blank 2 1)))
5081 ((and (bolp)
5082 (or (bobp)
5083 (save-excursion
5084 (backward-char 1) (not (org-invisible-p)))))
5085 ;; insert right here
5086 nil)
5088 ;; somewhere in the line
5089 (save-excursion
5090 (setq previous-pos (point-at-bol))
5091 (end-of-line)
5092 (setq hide-previous (org-invisible-p)))
5093 (and org-insert-heading-respect-content (org-show-subtree))
5094 (let ((split
5095 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5096 (save-excursion
5097 (let ((p (point)))
5098 (goto-char (point-at-bol))
5099 (and (looking-at org-complex-heading-regexp)
5100 (> p (match-beginning 4)))))))
5101 tags pos)
5102 (cond
5103 (org-insert-heading-respect-content
5104 (org-end-of-subtree nil t)
5105 (or (bolp) (newline))
5106 (or (org-previous-line-empty-p)
5107 (and blank (newline)))
5108 (open-line 1))
5109 ((org-on-heading-p)
5110 (when hide-previous
5111 (show-children)
5112 (org-show-entry))
5113 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5114 (setq tags (and (match-end 2) (match-string 2)))
5115 (and (match-end 1)
5116 (delete-region (match-beginning 1) (match-end 1)))
5117 (setq pos (point-at-bol))
5118 (or split (end-of-line 1))
5119 (delete-horizontal-space)
5120 (newline (if blank 2 1))
5121 (when tags
5122 (save-excursion
5123 (goto-char pos)
5124 (end-of-line 1)
5125 (insert " " tags)
5126 (org-set-tags nil 'align))))
5128 (or split (end-of-line 1))
5129 (newline (if blank 2 1)))))))
5130 (insert head) (just-one-space)
5131 (setq pos (point))
5132 (end-of-line 1)
5133 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5134 (when (and org-insert-heading-respect-content hide-previous)
5135 (save-excursion
5136 (goto-char previous-pos)
5137 (hide-subtree)))
5138 (run-hooks 'org-insert-heading-hook)))))
5140 (defun org-get-heading (&optional no-tags)
5141 "Return the heading of the current entry, without the stars."
5142 (save-excursion
5143 (org-back-to-heading t)
5144 (if (looking-at
5145 (if no-tags
5146 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5147 "\\*+[ \t]+\\([^\r\n]*\\)"))
5148 (match-string 1) "")))
5150 (defun org-heading-components ()
5151 "Return the components of the current heading.
5152 This is a list with the following elements:
5153 - the level as an integer
5154 - the reduced level, different if `org-odd-levels-only' is set.
5155 - the TODO keyword, or nil
5156 - the priority character, like ?A, or nil if no priority is given
5157 - the headline text itself, or the tags string if no headline text
5158 - the tags string, or nil."
5159 (save-excursion
5160 (org-back-to-heading t)
5161 (if (looking-at org-complex-heading-regexp)
5162 (list (length (match-string 1))
5163 (org-reduced-level (length (match-string 1)))
5164 (org-match-string-no-properties 2)
5165 (and (match-end 3) (aref (match-string 3) 2))
5166 (org-match-string-no-properties 4)
5167 (org-match-string-no-properties 5)))))
5169 (defun org-insert-heading-after-current ()
5170 "Insert a new heading with same level as current, after current subtree."
5171 (interactive)
5172 (org-back-to-heading)
5173 (org-insert-heading)
5174 (org-move-subtree-down)
5175 (end-of-line 1))
5177 (defun org-insert-heading-respect-content ()
5178 (interactive)
5179 (let ((org-insert-heading-respect-content t))
5180 (org-insert-heading t)))
5182 (defun org-insert-todo-heading-respect-content (&optional force-state)
5183 (interactive "P")
5184 (let ((org-insert-heading-respect-content t))
5185 (org-insert-todo-heading force-state t)))
5187 (defun org-insert-todo-heading (arg &optional force-heading)
5188 "Insert a new heading with the same level and TODO state as current heading.
5189 If the heading has no TODO state, or if the state is DONE, use the first
5190 state (TODO by default). Also with prefix arg, force first state."
5191 (interactive "P")
5192 (when (or force-heading (not (org-insert-item 'checkbox)))
5193 (org-insert-heading force-heading)
5194 (save-excursion
5195 (org-back-to-heading)
5196 (outline-previous-heading)
5197 (looking-at org-todo-line-regexp))
5198 (let*
5199 ((new-mark-x
5200 (if (or arg
5201 (not (match-beginning 2))
5202 (member (match-string 2) org-done-keywords))
5203 (car org-todo-keywords-1)
5204 (match-string 2)))
5205 (new-mark
5207 (run-hook-with-args-until-success
5208 'org-todo-get-default-hook new-mark-x nil)
5209 new-mark-x)))
5210 (insert new-mark " "))
5211 (when org-provide-todo-statistics
5212 (org-update-parent-todo-statistics))))
5214 (defun org-insert-subheading (arg)
5215 "Insert a new subheading and demote it.
5216 Works for outline headings and for plain lists alike."
5217 (interactive "P")
5218 (org-insert-heading arg)
5219 (cond
5220 ((org-on-heading-p) (org-do-demote))
5221 ((org-at-item-p) (org-indent-item 1))))
5223 (defun org-insert-todo-subheading (arg)
5224 "Insert a new subheading with TODO keyword or checkbox and demote it.
5225 Works for outline headings and for plain lists alike."
5226 (interactive "P")
5227 (org-insert-todo-heading arg)
5228 (cond
5229 ((org-on-heading-p) (org-do-demote))
5230 ((org-at-item-p) (org-indent-item 1))))
5232 ;;; Promotion and Demotion
5234 (defun org-promote-subtree ()
5235 "Promote the entire subtree.
5236 See also `org-promote'."
5237 (interactive)
5238 (save-excursion
5239 (org-map-tree 'org-promote))
5240 (org-fix-position-after-promote))
5242 (defun org-demote-subtree ()
5243 "Demote the entire subtree. See `org-demote'.
5244 See also `org-promote'."
5245 (interactive)
5246 (save-excursion
5247 (org-map-tree 'org-demote))
5248 (org-fix-position-after-promote))
5251 (defun org-do-promote ()
5252 "Promote the current heading higher up the tree.
5253 If the region is active in `transient-mark-mode', promote all headings
5254 in the region."
5255 (interactive)
5256 (save-excursion
5257 (if (org-region-active-p)
5258 (org-map-region 'org-promote (region-beginning) (region-end))
5259 (org-promote)))
5260 (org-fix-position-after-promote))
5262 (defun org-do-demote ()
5263 "Demote the current heading lower down the tree.
5264 If the region is active in `transient-mark-mode', demote all headings
5265 in the region."
5266 (interactive)
5267 (save-excursion
5268 (if (org-region-active-p)
5269 (org-map-region 'org-demote (region-beginning) (region-end))
5270 (org-demote)))
5271 (org-fix-position-after-promote))
5273 (defun org-fix-position-after-promote ()
5274 "Make sure that after pro/demotion cursor position is right."
5275 (let ((pos (point)))
5276 (when (save-excursion
5277 (beginning-of-line 1)
5278 (looking-at org-todo-line-regexp)
5279 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5280 (cond ((eobp) (insert " "))
5281 ((eolp) (insert " "))
5282 ((equal (char-after) ?\ ) (forward-char 1))))))
5284 (defun org-reduced-level (l)
5285 "Compute the effective level of a heading.
5286 This takes into account the setting of `org-odd-levels-only'."
5287 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5289 (defun org-get-valid-level (level &optional change)
5290 "Rectify a level change under the influence of `org-odd-levels-only'
5291 LEVEL is a current level, CHANGE is by how much the level should be
5292 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5293 even level numbers will become the next higher odd number."
5294 (if org-odd-levels-only
5295 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5296 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5297 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5298 (max 1 (+ level change))))
5300 (if (boundp 'define-obsolete-function-alias)
5301 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5302 (define-obsolete-function-alias 'org-get-legal-level
5303 'org-get-valid-level)
5304 (define-obsolete-function-alias 'org-get-legal-level
5305 'org-get-valid-level "23.1")))
5307 (defun org-promote ()
5308 "Promote the current heading higher up the tree.
5309 If the region is active in `transient-mark-mode', promote all headings
5310 in the region."
5311 (org-back-to-heading t)
5312 (let* ((level (save-match-data (funcall outline-level)))
5313 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5314 (diff (abs (- level (length up-head) -1))))
5315 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5316 (replace-match up-head nil t)
5317 ;; Fixup tag positioning
5318 (and org-auto-align-tags (org-set-tags nil t))
5319 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5321 (defun org-demote ()
5322 "Demote the current heading lower down the tree.
5323 If the region is active in `transient-mark-mode', demote all headings
5324 in the region."
5325 (org-back-to-heading t)
5326 (let* ((level (save-match-data (funcall outline-level)))
5327 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5328 (diff (abs (- level (length down-head) -1))))
5329 (replace-match down-head nil t)
5330 ;; Fixup tag positioning
5331 (and org-auto-align-tags (org-set-tags nil t))
5332 (if org-adapt-indentation (org-fixup-indentation diff))))
5334 (defun org-map-tree (fun)
5335 "Call FUN for every heading underneath the current one."
5336 (org-back-to-heading)
5337 (let ((level (funcall outline-level)))
5338 (save-excursion
5339 (funcall fun)
5340 (while (and (progn
5341 (outline-next-heading)
5342 (> (funcall outline-level) level))
5343 (not (eobp)))
5344 (funcall fun)))))
5346 (defun org-map-region (fun beg end)
5347 "Call FUN for every heading between BEG and END."
5348 (let ((org-ignore-region t))
5349 (save-excursion
5350 (setq end (copy-marker end))
5351 (goto-char beg)
5352 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5353 (< (point) end))
5354 (funcall fun))
5355 (while (and (progn
5356 (outline-next-heading)
5357 (< (point) end))
5358 (not (eobp)))
5359 (funcall fun)))))
5361 (defun org-fixup-indentation (diff)
5362 "Change the indentation in the current entry by DIFF
5363 However, if any line in the current entry has no indentation, or if it
5364 would end up with no indentation after the change, nothing at all is done."
5365 (save-excursion
5366 (let ((end (save-excursion (outline-next-heading)
5367 (point-marker)))
5368 (prohibit (if (> diff 0)
5369 "^\\S-"
5370 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5371 col)
5372 (unless (save-excursion (end-of-line 1)
5373 (re-search-forward prohibit end t))
5374 (while (and (< (point) end)
5375 (re-search-forward "^[ \t]+" end t))
5376 (goto-char (match-end 0))
5377 (setq col (current-column))
5378 (if (< diff 0) (replace-match ""))
5379 (org-indent-to-column (+ diff col))))
5380 (move-marker end nil))))
5382 (defun org-convert-to-odd-levels ()
5383 "Convert an org-mode file with all levels allowed to one with odd levels.
5384 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5385 level 5 etc."
5386 (interactive)
5387 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5388 (let ((org-odd-levels-only nil) n)
5389 (save-excursion
5390 (goto-char (point-min))
5391 (while (re-search-forward "^\\*\\*+ " nil t)
5392 (setq n (- (length (match-string 0)) 2))
5393 (while (>= (setq n (1- n)) 0)
5394 (org-demote))
5395 (end-of-line 1))))))
5398 (defun org-convert-to-oddeven-levels ()
5399 "Convert an org-mode file with only odd levels to one with odd and even levels.
5400 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5401 section with an even level, conversion would destroy the structure of the file. An error
5402 is signaled in this case."
5403 (interactive)
5404 (goto-char (point-min))
5405 ;; First check if there are no even levels
5406 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5407 (org-show-context t)
5408 (error "Not all levels are odd in this file. Conversion not possible."))
5409 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5410 (let ((org-odd-levels-only nil) n)
5411 (save-excursion
5412 (goto-char (point-min))
5413 (while (re-search-forward "^\\*\\*+ " nil t)
5414 (setq n (/ (1- (length (match-string 0))) 2))
5415 (while (>= (setq n (1- n)) 0)
5416 (org-promote))
5417 (end-of-line 1))))))
5419 (defun org-tr-level (n)
5420 "Make N odd if required."
5421 (if org-odd-levels-only (1+ (/ n 2)) n))
5423 ;;; Vertical tree motion, cutting and pasting of subtrees
5425 (defun org-move-subtree-up (&optional arg)
5426 "Move the current subtree up past ARG headlines of the same level."
5427 (interactive "p")
5428 (org-move-subtree-down (- (prefix-numeric-value arg))))
5430 (defun org-move-subtree-down (&optional arg)
5431 "Move the current subtree down past ARG headlines of the same level."
5432 (interactive "p")
5433 (setq arg (prefix-numeric-value arg))
5434 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5435 'outline-get-last-sibling))
5436 (ins-point (make-marker))
5437 (cnt (abs arg))
5438 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5439 ;; Select the tree
5440 (org-back-to-heading)
5441 (setq beg0 (point))
5442 (save-excursion
5443 (setq ne-beg (org-back-over-empty-lines))
5444 (setq beg (point)))
5445 (save-match-data
5446 (save-excursion (outline-end-of-heading)
5447 (setq folded (org-invisible-p)))
5448 (outline-end-of-subtree))
5449 (outline-next-heading)
5450 (setq ne-end (org-back-over-empty-lines))
5451 (setq end (point))
5452 (goto-char beg0)
5453 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5454 ;; include less whitespace
5455 (save-excursion
5456 (goto-char beg)
5457 (forward-line (- ne-beg ne-end))
5458 (setq beg (point))))
5459 ;; Find insertion point, with error handling
5460 (while (> cnt 0)
5461 (or (and (funcall movfunc) (looking-at outline-regexp))
5462 (progn (goto-char beg0)
5463 (error "Cannot move past superior level or buffer limit")))
5464 (setq cnt (1- cnt)))
5465 (if (> arg 0)
5466 ;; Moving forward - still need to move over subtree
5467 (progn (org-end-of-subtree t t)
5468 (save-excursion
5469 (org-back-over-empty-lines)
5470 (or (bolp) (newline)))))
5471 (setq ne-ins (org-back-over-empty-lines))
5472 (move-marker ins-point (point))
5473 (setq txt (buffer-substring beg end))
5474 (org-save-markers-in-region beg end)
5475 (delete-region beg end)
5476 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5477 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5478 (let ((bbb (point)))
5479 (insert-before-markers txt)
5480 (org-reinstall-markers-in-region bbb)
5481 (move-marker ins-point bbb))
5482 (or (bolp) (insert "\n"))
5483 (setq ins-end (point))
5484 (goto-char ins-point)
5485 (org-skip-whitespace)
5486 (when (and (< arg 0)
5487 (org-first-sibling-p)
5488 (> ne-ins ne-beg))
5489 ;; Move whitespace back to beginning
5490 (save-excursion
5491 (goto-char ins-end)
5492 (let ((kill-whole-line t))
5493 (kill-line (- ne-ins ne-beg)) (point)))
5494 (insert (make-string (- ne-ins ne-beg) ?\n)))
5495 (move-marker ins-point nil)
5496 (org-compact-display-after-subtree-move)
5497 (org-show-empty-lines-in-parent)
5498 (unless folded
5499 (org-show-entry)
5500 (show-children)
5501 (org-cycle-hide-drawers 'children))))
5503 (defvar org-subtree-clip ""
5504 "Clipboard for cut and paste of subtrees.
5505 This is actually only a copy of the kill, because we use the normal kill
5506 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5508 (defvar org-subtree-clip-folded nil
5509 "Was the last copied subtree folded?
5510 This is used to fold the tree back after pasting.")
5512 (defun org-cut-subtree (&optional n)
5513 "Cut the current subtree into the clipboard.
5514 With prefix arg N, cut this many sequential subtrees.
5515 This is a short-hand for marking the subtree and then cutting it."
5516 (interactive "p")
5517 (org-copy-subtree n 'cut))
5519 (defun org-copy-subtree (&optional n cut force-store-markers)
5520 "Cut the current subtree into the clipboard.
5521 With prefix arg N, cut this many sequential subtrees.
5522 This is a short-hand for marking the subtree and then copying it.
5523 If CUT is non-nil, actually cut the subtree.
5524 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5525 of some markers in the region, even if CUT is non-nil. This is
5526 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5527 (interactive "p")
5528 (let (beg end folded (beg0 (point)))
5529 (if (interactive-p)
5530 (org-back-to-heading nil) ; take what looks like a subtree
5531 (org-back-to-heading t)) ; take what is really there
5532 (org-back-over-empty-lines)
5533 (setq beg (point))
5534 (skip-chars-forward " \t\r\n")
5535 (save-match-data
5536 (save-excursion (outline-end-of-heading)
5537 (setq folded (org-invisible-p)))
5538 (condition-case nil
5539 (outline-forward-same-level (1- n))
5540 (error nil))
5541 (org-end-of-subtree t t))
5542 (org-back-over-empty-lines)
5543 (setq end (point))
5544 (goto-char beg0)
5545 (when (> end beg)
5546 (setq org-subtree-clip-folded folded)
5547 (when (or cut force-store-markers)
5548 (org-save-markers-in-region beg end))
5549 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5550 (setq org-subtree-clip (current-kill 0))
5551 (message "%s: Subtree(s) with %d characters"
5552 (if cut "Cut" "Copied")
5553 (length org-subtree-clip)))))
5555 (defun org-paste-subtree (&optional level tree for-yank)
5556 "Paste the clipboard as a subtree, with modification of headline level.
5557 The entire subtree is promoted or demoted in order to match a new headline
5558 level.
5560 If the cursor is at the beginning of a headline, the same level as
5561 that headline is used to paste the tree
5563 If not, the new level is derived from the *visible* headings
5564 before and after the insertion point, and taken to be the inferior headline
5565 level of the two. So if the previous visible heading is level 3 and the
5566 next is level 4 (or vice versa), level 4 will be used for insertion.
5567 This makes sure that the subtree remains an independent subtree and does
5568 not swallow low level entries.
5570 You can also force a different level, either by using a numeric prefix
5571 argument, or by inserting the heading marker by hand. For example, if the
5572 cursor is after \"*****\", then the tree will be shifted to level 5.
5574 If optional TREE is given, use this text instead of the kill ring.
5576 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5577 move back over whitespace before inserting, and move point to the end of
5578 the inserted text when done."
5579 (interactive "P")
5580 (unless (org-kill-is-subtree-p tree)
5581 (error "%s"
5582 (substitute-command-keys
5583 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5584 (let* ((visp (not (org-invisible-p)))
5585 (txt (or tree (and kill-ring (current-kill 0))))
5586 (^re (concat "^\\(" outline-regexp "\\)"))
5587 (re (concat "\\(" outline-regexp "\\)"))
5588 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5590 (old-level (if (string-match ^re txt)
5591 (- (match-end 0) (match-beginning 0) 1)
5592 -1))
5593 (force-level (cond (level (prefix-numeric-value level))
5594 ((and (looking-at "[ \t]*$")
5595 (string-match
5596 ^re_ (buffer-substring
5597 (point-at-bol) (point))))
5598 (- (match-end 1) (match-beginning 1)))
5599 ((and (bolp)
5600 (looking-at org-outline-regexp))
5601 (- (match-end 0) (point) 1))
5602 (t nil)))
5603 (previous-level (save-excursion
5604 (condition-case nil
5605 (progn
5606 (outline-previous-visible-heading 1)
5607 (if (looking-at re)
5608 (- (match-end 0) (match-beginning 0) 1)
5610 (error 1))))
5611 (next-level (save-excursion
5612 (condition-case nil
5613 (progn
5614 (or (looking-at outline-regexp)
5615 (outline-next-visible-heading 1))
5616 (if (looking-at re)
5617 (- (match-end 0) (match-beginning 0) 1)
5619 (error 1))))
5620 (new-level (or force-level (max previous-level next-level)))
5621 (shift (if (or (= old-level -1)
5622 (= new-level -1)
5623 (= old-level new-level))
5625 (- new-level old-level)))
5626 (delta (if (> shift 0) -1 1))
5627 (func (if (> shift 0) 'org-demote 'org-promote))
5628 (org-odd-levels-only nil)
5629 beg end newend)
5630 ;; Remove the forced level indicator
5631 (if force-level
5632 (delete-region (point-at-bol) (point)))
5633 ;; Paste
5634 (beginning-of-line 1)
5635 (unless for-yank (org-back-over-empty-lines))
5636 (setq beg (point))
5637 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5638 (insert-before-markers txt)
5639 (unless (string-match "\n\\'" txt) (insert "\n"))
5640 (setq newend (point))
5641 (org-reinstall-markers-in-region beg)
5642 (setq end (point))
5643 (goto-char beg)
5644 (skip-chars-forward " \t\n\r")
5645 (setq beg (point))
5646 (if (and (org-invisible-p) visp)
5647 (save-excursion (outline-show-heading)))
5648 ;; Shift if necessary
5649 (unless (= shift 0)
5650 (save-restriction
5651 (narrow-to-region beg end)
5652 (while (not (= shift 0))
5653 (org-map-region func (point-min) (point-max))
5654 (setq shift (+ delta shift)))
5655 (goto-char (point-min))
5656 (setq newend (point-max))))
5657 (when (or (interactive-p) for-yank)
5658 (message "Clipboard pasted as level %d subtree" new-level))
5659 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5660 kill-ring
5661 (eq org-subtree-clip (current-kill 0))
5662 org-subtree-clip-folded)
5663 ;; The tree was folded before it was killed/copied
5664 (hide-subtree))
5665 (and for-yank (goto-char newend))))
5667 (defun org-kill-is-subtree-p (&optional txt)
5668 "Check if the current kill is an outline subtree, or a set of trees.
5669 Returns nil if kill does not start with a headline, or if the first
5670 headline level is not the largest headline level in the tree.
5671 So this will actually accept several entries of equal levels as well,
5672 which is OK for `org-paste-subtree'.
5673 If optional TXT is given, check this string instead of the current kill."
5674 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5675 (start-level (and kill
5676 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5677 org-outline-regexp "\\)")
5678 kill)
5679 (- (match-end 2) (match-beginning 2) 1)))
5680 (re (concat "^" org-outline-regexp))
5681 (start (1+ (or (match-beginning 2) -1))))
5682 (if (not start-level)
5683 (progn
5684 nil) ;; does not even start with a heading
5685 (catch 'exit
5686 (while (setq start (string-match re kill (1+ start)))
5687 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5688 (throw 'exit nil)))
5689 t))))
5691 (defvar org-markers-to-move nil
5692 "Markers that should be moved with a cut-and-paste operation.
5693 Those markers are stored together with their positions relative to
5694 the start of the region.")
5696 (defun org-save-markers-in-region (beg end)
5697 "Check markers in region.
5698 If these markers are between BEG and END, record their position relative
5699 to BEG, so that after moving the block of text, we can put the markers back
5700 into place.
5701 This function gets called just before an entry or tree gets cut from the
5702 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5703 called immediately, to move the markers with the entries."
5704 (setq org-markers-to-move nil)
5705 (when (featurep 'org-clock)
5706 (org-clock-save-markers-for-cut-and-paste beg end))
5707 (when (featurep 'org-agenda)
5708 (org-agenda-save-markers-for-cut-and-paste beg end)))
5710 (defun org-check-and-save-marker (marker beg end)
5711 "Check if MARKER is between BEG and END.
5712 If yes, remember the marker and the distance to BEG."
5713 (when (and (marker-buffer marker)
5714 (equal (marker-buffer marker) (current-buffer)))
5715 (if (and (>= marker beg) (< marker end))
5716 (push (cons marker (- marker beg)) org-markers-to-move))))
5718 (defun org-reinstall-markers-in-region (beg)
5719 "Move all remembered markers to their position relative to BEG."
5720 (mapc (lambda (x)
5721 (move-marker (car x) (+ beg (cdr x))))
5722 org-markers-to-move)
5723 (setq org-markers-to-move nil))
5725 (defun org-narrow-to-subtree ()
5726 "Narrow buffer to the current subtree."
5727 (interactive)
5728 (save-excursion
5729 (save-match-data
5730 (narrow-to-region
5731 (progn (org-back-to-heading) (point))
5732 (progn (org-end-of-subtree t) (point))))))
5735 ;;; Outline Sorting
5737 (defun org-sort (with-case)
5738 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5739 Optional argument WITH-CASE means sort case-sensitively.
5740 With a double prefix argument, also remove duplicate entries."
5741 (interactive "P")
5742 (if (org-at-table-p)
5743 (org-call-with-arg 'org-table-sort-lines with-case)
5744 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5746 (defun org-sort-remove-invisible (s)
5747 (remove-text-properties 0 (length s) org-rm-props s)
5748 (while (string-match org-bracket-link-regexp s)
5749 (setq s (replace-match (if (match-end 2)
5750 (match-string 3 s)
5751 (match-string 1 s)) t t s)))
5754 (defvar org-priority-regexp) ; defined later in the file
5756 (defun org-sort-entries-or-items
5757 (&optional with-case sorting-type getkey-func compare-func property)
5758 "Sort entries on a certain level of an outline tree.
5759 If there is an active region, the entries in the region are sorted.
5760 Else, if the cursor is before the first entry, sort the top-level items.
5761 Else, the children of the entry at point are sorted.
5763 Sorting can be alphabetically, numerically, and by date/time as given by
5764 the first time stamp in the entry. The command prompts for the sorting
5765 type unless it has been given to the function through the SORTING-TYPE
5766 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5767 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5768 called with point at the beginning of the record. It must return either
5769 a string or a number that should serve as the sorting key for that record.
5771 Comparing entries ignores case by default. However, with an optional argument
5772 WITH-CASE, the sorting considers case as well."
5773 (interactive "P")
5774 (let ((case-func (if with-case 'identity 'downcase))
5775 start beg end stars re re2
5776 txt what tmp plain-list-p)
5777 ;; Find beginning and end of region to sort
5778 (cond
5779 ((org-region-active-p)
5780 ;; we will sort the region
5781 (setq end (region-end)
5782 what "region")
5783 (goto-char (region-beginning))
5784 (if (not (org-on-heading-p)) (outline-next-heading))
5785 (setq start (point)))
5786 ((org-at-item-p)
5787 ;; we will sort this plain list
5788 (org-beginning-of-item-list) (setq start (point))
5789 (org-end-of-item-list) (setq end (point))
5790 (goto-char start)
5791 (setq plain-list-p t
5792 what "plain list"))
5793 ((or (org-on-heading-p)
5794 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5795 ;; we will sort the children of the current headline
5796 (org-back-to-heading)
5797 (setq start (point)
5798 end (progn (org-end-of-subtree t t)
5799 (org-back-over-empty-lines)
5800 (point))
5801 what "children")
5802 (goto-char start)
5803 (show-subtree)
5804 (outline-next-heading))
5806 ;; we will sort the top-level entries in this file
5807 (goto-char (point-min))
5808 (or (org-on-heading-p) (outline-next-heading))
5809 (setq start (point) end (point-max) what "top-level")
5810 (goto-char start)
5811 (show-all)))
5813 (setq beg (point))
5814 (if (>= beg end) (error "Nothing to sort"))
5816 (unless plain-list-p
5817 (looking-at "\\(\\*+\\)")
5818 (setq stars (match-string 1)
5819 re (concat "^" (regexp-quote stars) " +")
5820 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5821 txt (buffer-substring beg end))
5822 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5823 (if (and (not (equal stars "*")) (string-match re2 txt))
5824 (error "Region to sort contains a level above the first entry")))
5826 (unless sorting-type
5827 (message
5828 (if plain-list-p
5829 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5830 "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:")
5831 what)
5832 (setq sorting-type (read-char-exclusive))
5834 (and (= (downcase sorting-type) ?f)
5835 (setq getkey-func
5836 (org-ido-completing-read "Sort using function: "
5837 obarray 'fboundp t nil nil))
5838 (setq getkey-func (intern getkey-func)))
5840 (and (= (downcase sorting-type) ?r)
5841 (setq property
5842 (org-ido-completing-read "Property: "
5843 (mapcar 'list (org-buffer-property-keys t))
5844 nil t))))
5846 (message "Sorting entries...")
5848 (save-restriction
5849 (narrow-to-region start end)
5851 (let ((dcst (downcase sorting-type))
5852 (now (current-time)))
5853 (sort-subr
5854 (/= dcst sorting-type)
5855 ;; This function moves to the beginning character of the "record" to
5856 ;; be sorted.
5857 (if plain-list-p
5858 (lambda nil
5859 (if (org-at-item-p) t (goto-char (point-max))))
5860 (lambda nil
5861 (if (re-search-forward re nil t)
5862 (goto-char (match-beginning 0))
5863 (goto-char (point-max)))))
5864 ;; This function moves to the last character of the "record" being
5865 ;; sorted.
5866 (if plain-list-p
5867 'org-end-of-item
5868 (lambda nil
5869 (save-match-data
5870 (condition-case nil
5871 (outline-forward-same-level 1)
5872 (error
5873 (goto-char (point-max)))))))
5875 ;; This function returns the value that gets sorted against.
5876 (if plain-list-p
5877 (lambda nil
5878 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5879 (cond
5880 ((= dcst ?n)
5881 (string-to-number (buffer-substring (match-end 0)
5882 (point-at-eol))))
5883 ((= dcst ?a)
5884 (buffer-substring (match-end 0) (point-at-eol)))
5885 ((= dcst ?t)
5886 (if (re-search-forward org-ts-regexp
5887 (point-at-eol) t)
5888 (org-time-string-to-time (match-string 0))
5889 now))
5890 ((= dcst ?f)
5891 (if getkey-func
5892 (progn
5893 (setq tmp (funcall getkey-func))
5894 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5895 tmp)
5896 (error "Invalid key function `%s'" getkey-func)))
5897 (t (error "Invalid sorting type `%c'" sorting-type)))))
5898 (lambda nil
5899 (cond
5900 ((= dcst ?n)
5901 (if (looking-at org-complex-heading-regexp)
5902 (string-to-number (match-string 4))
5903 nil))
5904 ((= dcst ?a)
5905 (if (looking-at org-complex-heading-regexp)
5906 (funcall case-func (match-string 4))
5907 nil))
5908 ((= dcst ?t)
5909 (if (re-search-forward org-ts-regexp
5910 (save-excursion
5911 (forward-line 2)
5912 (point)) t)
5913 (org-time-string-to-time (match-string 0))
5914 now))
5915 ((= dcst ?p)
5916 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5917 (string-to-char (match-string 2))
5918 org-default-priority))
5919 ((= dcst ?r)
5920 (or (org-entry-get nil property) ""))
5921 ((= dcst ?o)
5922 (if (looking-at org-complex-heading-regexp)
5923 (- 9999 (length (member (match-string 2)
5924 org-todo-keywords-1)))))
5925 ((= dcst ?f)
5926 (if getkey-func
5927 (progn
5928 (setq tmp (funcall getkey-func))
5929 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5930 tmp)
5931 (error "Invalid key function `%s'" getkey-func)))
5932 (t (error "Invalid sorting type `%c'" sorting-type)))))
5934 (cond
5935 ((= dcst ?a) 'string<)
5936 ((= dcst ?t) 'time-less-p)
5937 ((= dcst ?f) compare-func)
5938 (t nil)))))
5939 (message "Sorting entries...done")))
5941 (defun org-do-sort (table what &optional with-case sorting-type)
5942 "Sort TABLE of WHAT according to SORTING-TYPE.
5943 The user will be prompted for the SORTING-TYPE if the call to this
5944 function does not specify it. WHAT is only for the prompt, to indicate
5945 what is being sorted. The sorting key will be extracted from
5946 the car of the elements of the table.
5947 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5948 (unless sorting-type
5949 (message
5950 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5951 what)
5952 (setq sorting-type (read-char-exclusive)))
5953 (let ((dcst (downcase sorting-type))
5954 extractfun comparefun)
5955 ;; Define the appropriate functions
5956 (cond
5957 ((= dcst ?n)
5958 (setq extractfun 'string-to-number
5959 comparefun (if (= dcst sorting-type) '< '>)))
5960 ((= dcst ?a)
5961 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5962 (lambda(x) (downcase (org-sort-remove-invisible x))))
5963 comparefun (if (= dcst sorting-type)
5964 'string<
5965 (lambda (a b) (and (not (string< a b))
5966 (not (string= a b)))))))
5967 ((= dcst ?t)
5968 (setq extractfun
5969 (lambda (x)
5970 (if (or (string-match org-ts-regexp x)
5971 (string-match org-ts-regexp-both x))
5972 (time-to-seconds
5973 (org-time-string-to-time (match-string 0 x)))
5975 comparefun (if (= dcst sorting-type) '< '>)))
5976 (t (error "Invalid sorting type `%c'" sorting-type)))
5978 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5979 table)
5980 (lambda (a b) (funcall comparefun (car a) (car b))))))
5982 ;;; Editing source examples
5984 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5985 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5986 (defvar org-edit-src-force-single-line nil)
5987 (defvar org-edit-src-from-org-mode nil)
5988 (defvar org-edit-src-picture nil)
5990 (define-minor-mode org-exit-edit-mode
5991 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5993 (defun org-edit-src-code ()
5994 "Edit the source code example at point.
5995 An indirect buffer is created, and that buffer is then narrowed to the
5996 example at point and switched to the correct language mode. When done,
5997 exit by killing the buffer with \\[org-edit-src-exit]."
5998 (interactive)
5999 (let ((line (org-current-line))
6000 (case-fold-search t)
6001 (msg (substitute-command-keys
6002 "Edit, then exit with C-c ' (C-c and single quote)"))
6003 (info (org-edit-src-find-region-and-lang))
6004 (org-mode-p (eq major-mode 'org-mode))
6005 beg end lang lang-f single lfmt)
6006 (if (not info)
6008 (setq beg (nth 0 info)
6009 end (nth 1 info)
6010 lang (nth 2 info)
6011 single (nth 3 info)
6012 lfmt (nth 4 info)
6013 lang-f (intern (concat lang "-mode")))
6014 (unless (functionp lang-f)
6015 (error "No such language mode: %s" lang-f))
6016 (goto-line line)
6017 (if (get-buffer "*Org Edit Src Example*")
6018 (kill-buffer "*Org Edit Src Example*"))
6019 (switch-to-buffer (make-indirect-buffer (current-buffer)
6020 "*Org Edit Src Example*"))
6021 (narrow-to-region beg end)
6022 (remove-text-properties beg end '(display nil invisible nil
6023 intangible nil))
6024 (let ((org-inhibit-startup t))
6025 (funcall lang-f))
6026 (set (make-local-variable 'org-edit-src-force-single-line) single)
6027 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6028 (when lfmt
6029 (set (make-local-variable 'org-coderef-label-format) lfmt))
6030 (when org-mode-p
6031 (goto-char (point-min))
6032 (while (re-search-forward "^," nil t)
6033 (replace-match "")))
6034 (goto-line line)
6035 (org-exit-edit-mode)
6036 (org-set-local 'header-line-format msg)
6037 (message "%s" msg)
6038 t)))
6040 (defun org-edit-fixed-width-region ()
6041 "Edit the fixed-width ascii drawing at point.
6042 This must be a region where each line starts with a colon followed by
6043 a space character.
6044 An indirect buffer is created, and that buffer is then narrowed to the
6045 example at point and switched to artist-mode. When done,
6046 exit by killing the buffer with \\[org-edit-src-exit]."
6047 (interactive)
6048 (let ((line (org-current-line))
6049 (case-fold-search t)
6050 (msg (substitute-command-keys
6051 "Edit, then exit with C-c ' (C-c and single quote)"))
6052 (org-mode-p (eq major-mode 'org-mode))
6053 beg end)
6054 (beginning-of-line 1)
6055 (if (looking-at "[ \t]*[^:\n \t]")
6057 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6058 (setq beg (point) end beg)
6059 (save-excursion
6060 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6061 (setq beg (point-at-bol 2))
6062 (setq beg (point))))
6063 (save-excursion
6064 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6065 (setq end (1- (match-beginning 0)))
6066 (setq end (point))))
6067 (goto-line line))
6068 (if (get-buffer "*Org Edit Picture*")
6069 (kill-buffer "*Org Edit Picture*"))
6070 (switch-to-buffer (make-indirect-buffer (current-buffer)
6071 "*Org Edit Picture*"))
6072 (narrow-to-region beg end)
6073 (remove-text-properties beg end '(display nil invisible nil
6074 intangible nil))
6075 (when (fboundp 'font-lock-unfontify-region)
6076 (font-lock-unfontify-region (point-min) (point-max)))
6077 (cond
6078 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6079 (fundamental-mode)
6080 (artist-mode 1))
6081 (t (funcall org-edit-fixed-width-region-mode)))
6082 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6083 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6084 (set (make-local-variable 'org-edit-src-picture) t)
6085 (goto-char (point-min))
6086 (while (re-search-forward "^[ \t]*: ?" nil t)
6087 (replace-match ""))
6088 (goto-line line)
6089 (org-exit-edit-mode)
6090 (org-set-local 'header-line-format msg)
6091 (message "%s" msg)
6092 t)))
6095 (defun org-edit-src-find-region-and-lang ()
6096 "Find the region and language for a local edit.
6097 Return a list with beginning and end of the region, a string representing
6098 the language, a switch telling of the content should be in a single line."
6099 (let ((re-list
6100 (append
6101 org-edit-src-region-extra
6103 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6104 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6105 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6106 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6107 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6108 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6109 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6110 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6111 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6112 ("^#\\+html:" "\n" "html" single-line)
6113 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6114 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6115 ("^#\\+latex:" "\n" "latex" single-line)
6116 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6117 ("^#\\+ascii:" "\n" "ascii" single-line)
6119 (pos (point))
6120 re1 re2 single beg end lang lfmt match-re1)
6121 (catch 'exit
6122 (while (setq entry (pop re-list))
6123 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6124 single (nth 3 entry))
6125 (save-excursion
6126 (if (or (looking-at re1)
6127 (re-search-backward re1 nil t))
6128 (progn
6129 (setq match-re1 (match-string 0))
6130 (setq beg (match-end 0)
6131 lang (org-edit-src-get-lang lang)
6132 lfmt (org-edit-src-get-label-format match-re1))
6133 (if (and (re-search-forward re2 nil t)
6134 (>= (match-end 0) pos))
6135 (throw 'exit (list beg (match-beginning 0)
6136 lang single lfmt))))
6137 (if (or (looking-at re2)
6138 (re-search-forward re2 nil t))
6139 (progn
6140 (setq end (match-beginning 0))
6141 (if (and (re-search-backward re1 nil t)
6142 (<= (match-beginning 0) pos))
6143 (progn
6144 (setq lfmt (org-edit-src-get-label-format
6145 (match-string 0)))
6146 (throw 'exit
6147 (list (match-end 0) end
6148 (org-edit-src-get-lang lang)
6149 single lfmt))))))))))))
6151 (defun org-edit-src-get-lang (lang)
6152 "Extract the src language."
6153 (let ((m (match-string 0)))
6154 (cond
6155 ((stringp lang) lang)
6156 ((integerp lang) (match-string lang))
6157 ((and (eq lang 'lang)
6158 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6159 (match-string 1 m))
6160 ((and (eq lang 'style)
6161 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6162 (match-string 1 m))
6163 (t "fundamental"))))
6165 (defun org-edit-src-get-label-format (s)
6166 "Extract the label format."
6167 (save-match-data
6168 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6169 (match-string 1 s))))
6171 (defun org-edit-src-exit ()
6172 "Exit special edit and protect problematic lines."
6173 (interactive)
6174 (unless (buffer-base-buffer (current-buffer))
6175 (error "This is not an indirect buffer, something is wrong..."))
6176 (unless (> (point-min) 1)
6177 (error "This buffer is not narrowed, something is wrong..."))
6178 (goto-char (point-min))
6179 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6180 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6181 (when (org-bound-and-true-p org-edit-src-force-single-line)
6182 (goto-char (point-min))
6183 (while (re-search-forward "\n" nil t)
6184 (replace-match " "))
6185 (goto-char (point-min))
6186 (if (looking-at "\\s-*") (replace-match " "))
6187 (if (re-search-forward "\\s-+\\'" nil t)
6188 (replace-match "")))
6189 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6190 (goto-char (point-min))
6191 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6192 (replace-match ",\\1"))
6193 (when font-lock-mode
6194 (font-lock-unfontify-region (point-min) (point-max)))
6195 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6196 (when (org-bound-and-true-p org-edit-src-picture)
6197 (untabify (point-min) (point-max))
6198 (goto-char (point-min))
6199 (while (re-search-forward "^" nil t)
6200 (replace-match ": "))
6201 (when font-lock-mode
6202 (font-lock-unfontify-region (point-min) (point-max)))
6203 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6204 (kill-buffer (current-buffer))
6205 (and (org-mode-p) (org-restart-font-lock)))
6208 ;;; The orgstruct minor mode
6210 ;; Define a minor mode which can be used in other modes in order to
6211 ;; integrate the org-mode structure editing commands.
6213 ;; This is really a hack, because the org-mode structure commands use
6214 ;; keys which normally belong to the major mode. Here is how it
6215 ;; works: The minor mode defines all the keys necessary to operate the
6216 ;; structure commands, but wraps the commands into a function which
6217 ;; tests if the cursor is currently at a headline or a plain list
6218 ;; item. If that is the case, the structure command is used,
6219 ;; temporarily setting many Org-mode variables like regular
6220 ;; expressions for filling etc. However, when any of those keys is
6221 ;; used at a different location, function uses `key-binding' to look
6222 ;; up if the key has an associated command in another currently active
6223 ;; keymap (minor modes, major mode, global), and executes that
6224 ;; command. There might be problems if any of the keys is otherwise
6225 ;; used as a prefix key.
6227 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6228 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6229 ;; addresses this by checking explicitly for both bindings.
6231 (defvar orgstruct-mode-map (make-sparse-keymap)
6232 "Keymap for the minor `orgstruct-mode'.")
6234 (defvar org-local-vars nil
6235 "List of local variables, for use by `orgstruct-mode'")
6237 ;;;###autoload
6238 (define-minor-mode orgstruct-mode
6239 "Toggle the minor more `orgstruct-mode'.
6240 This mode is for using Org-mode structure commands in other modes.
6241 The following key behave as if Org-mode was active, if the cursor
6242 is on a headline, or on a plain list item (both in the definition
6243 of Org-mode).
6245 M-up Move entry/item up
6246 M-down Move entry/item down
6247 M-left Promote
6248 M-right Demote
6249 M-S-up Move entry/item up
6250 M-S-down Move entry/item down
6251 M-S-left Promote subtree
6252 M-S-right Demote subtree
6253 M-q Fill paragraph and items like in Org-mode
6254 C-c ^ Sort entries
6255 C-c - Cycle list bullet
6256 TAB Cycle item visibility
6257 M-RET Insert new heading/item
6258 S-M-RET Insert new TODO heading / Checkbox item
6259 C-c C-c Set tags / toggle checkbox"
6260 nil " OrgStruct" nil
6261 (org-load-modules-maybe)
6262 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6264 ;;;###autoload
6265 (defun turn-on-orgstruct ()
6266 "Unconditionally turn on `orgstruct-mode'."
6267 (orgstruct-mode 1))
6269 ;;;###autoload
6270 (defun turn-on-orgstruct++ ()
6271 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6272 In addition to setting orgstruct-mode, this also exports all indentation and
6273 autofilling variables from org-mode into the buffer. Note that turning
6274 off orgstruct-mode will *not* remove these additional settings."
6275 (orgstruct-mode 1)
6276 (let (var val)
6277 (mapc
6278 (lambda (x)
6279 (when (string-match
6280 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6281 (symbol-name (car x)))
6282 (setq var (car x) val (nth 1 x))
6283 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6284 org-local-vars)))
6286 (defun orgstruct-error ()
6287 "Error when there is no default binding for a structure key."
6288 (interactive)
6289 (error "This key has no function outside structure elements"))
6291 (defun orgstruct-setup ()
6292 "Setup orgstruct keymaps."
6293 (let ((nfunc 0)
6294 (bindings
6295 (list
6296 '([(meta up)] org-metaup)
6297 '([(meta down)] org-metadown)
6298 '([(meta left)] org-metaleft)
6299 '([(meta right)] org-metaright)
6300 '([(meta shift up)] org-shiftmetaup)
6301 '([(meta shift down)] org-shiftmetadown)
6302 '([(meta shift left)] org-shiftmetaleft)
6303 '([(meta shift right)] org-shiftmetaright)
6304 '([(shift up)] org-shiftup)
6305 '([(shift down)] org-shiftdown)
6306 '([(shift left)] org-shiftleft)
6307 '([(shift right)] org-shiftright)
6308 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6309 '("\M-q" fill-paragraph)
6310 '("\C-c^" org-sort)
6311 '("\C-c-" org-cycle-list-bullet)))
6312 elt key fun cmd)
6313 (while (setq elt (pop bindings))
6314 (setq nfunc (1+ nfunc))
6315 (setq key (org-key (car elt))
6316 fun (nth 1 elt)
6317 cmd (orgstruct-make-binding fun nfunc key))
6318 (org-defkey orgstruct-mode-map key cmd))
6320 ;; Special treatment needed for TAB and RET
6321 (org-defkey orgstruct-mode-map [(tab)]
6322 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6323 (org-defkey orgstruct-mode-map "\C-i"
6324 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6326 (org-defkey orgstruct-mode-map "\M-\C-m"
6327 (orgstruct-make-binding 'org-insert-heading 105
6328 "\M-\C-m" [(meta return)]))
6329 (org-defkey orgstruct-mode-map [(meta return)]
6330 (orgstruct-make-binding 'org-insert-heading 106
6331 [(meta return)] "\M-\C-m"))
6333 (org-defkey orgstruct-mode-map [(shift meta return)]
6334 (orgstruct-make-binding 'org-insert-todo-heading 107
6335 [(meta return)] "\M-\C-m"))
6337 (unless org-local-vars
6338 (setq org-local-vars (org-get-local-variables)))
6342 (defun orgstruct-make-binding (fun n &rest keys)
6343 "Create a function for binding in the structure minor mode.
6344 FUN is the command to call inside a table. N is used to create a unique
6345 command name. KEYS are keys that should be checked in for a command
6346 to execute outside of tables."
6347 (eval
6348 (list 'defun
6349 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6350 '(arg)
6351 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6352 "Outside of structure, run the binding of `"
6353 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6354 "'.")
6355 '(interactive "p")
6356 (list 'if
6357 '(org-context-p 'headline 'item)
6358 (list 'org-run-like-in-org-mode (list 'quote fun))
6359 (list 'let '(orgstruct-mode)
6360 (list 'call-interactively
6361 (append '(or)
6362 (mapcar (lambda (k)
6363 (list 'key-binding k))
6364 keys)
6365 '('orgstruct-error))))))))
6367 (defun org-context-p (&rest contexts)
6368 "Check if local context is any of CONTEXTS.
6369 Possible values in the list of contexts are `table', `headline', and `item'."
6370 (let ((pos (point)))
6371 (goto-char (point-at-bol))
6372 (prog1 (or (and (memq 'table contexts)
6373 (looking-at "[ \t]*|"))
6374 (and (memq 'headline contexts)
6375 ;;????????? (looking-at "\\*+"))
6376 (looking-at outline-regexp))
6377 (and (memq 'item contexts)
6378 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6379 (goto-char pos))))
6381 (defun org-get-local-variables ()
6382 "Return a list of all local variables in an org-mode buffer."
6383 (let (varlist)
6384 (with-current-buffer (get-buffer-create "*Org tmp*")
6385 (erase-buffer)
6386 (org-mode)
6387 (setq varlist (buffer-local-variables)))
6388 (kill-buffer "*Org tmp*")
6389 (delq nil
6390 (mapcar
6391 (lambda (x)
6392 (setq x
6393 (if (symbolp x)
6394 (list x)
6395 (list (car x) (list 'quote (cdr x)))))
6396 (if (string-match
6397 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6398 (symbol-name (car x)))
6399 x nil))
6400 varlist))))
6402 ;;;###autoload
6403 (defun org-run-like-in-org-mode (cmd)
6404 (org-load-modules-maybe)
6405 (unless org-local-vars
6406 (setq org-local-vars (org-get-local-variables)))
6407 (eval (list 'let org-local-vars
6408 (list 'call-interactively (list 'quote cmd)))))
6410 ;;;; Archiving
6412 (defun org-get-category (&optional pos)
6413 "Get the category applying to position POS."
6414 (get-text-property (or pos (point)) 'org-category))
6416 (defun org-refresh-category-properties ()
6417 "Refresh category text properties in the buffer."
6418 (let ((def-cat (cond
6419 ((null org-category)
6420 (if buffer-file-name
6421 (file-name-sans-extension
6422 (file-name-nondirectory buffer-file-name))
6423 "???"))
6424 ((symbolp org-category) (symbol-name org-category))
6425 (t org-category)))
6426 beg end cat pos optionp)
6427 (org-unmodified
6428 (save-excursion
6429 (save-restriction
6430 (widen)
6431 (goto-char (point-min))
6432 (put-text-property (point) (point-max) 'org-category def-cat)
6433 (while (re-search-forward
6434 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6435 (setq pos (match-end 0)
6436 optionp (equal (char-after (match-beginning 0)) ?#)
6437 cat (org-trim (match-string 2)))
6438 (if optionp
6439 (setq beg (point-at-bol) end (point-max))
6440 (org-back-to-heading t)
6441 (setq beg (point) end (org-end-of-subtree t t)))
6442 (put-text-property beg end 'org-category cat)
6443 (goto-char pos)))))))
6446 ;;;; Link Stuff
6448 ;;; Link abbreviations
6450 (defun org-link-expand-abbrev (link)
6451 "Apply replacements as defined in `org-link-abbrev-alist."
6452 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6453 (let* ((key (match-string 1 link))
6454 (as (or (assoc key org-link-abbrev-alist-local)
6455 (assoc key org-link-abbrev-alist)))
6456 (tag (and (match-end 2) (match-string 3 link)))
6457 rpl)
6458 (if (not as)
6459 link
6460 (setq rpl (cdr as))
6461 (cond
6462 ((symbolp rpl) (funcall rpl tag))
6463 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6464 ((string-match "%h" rpl)
6465 (replace-match (url-hexify-string (or tag "")) t t rpl))
6466 (t (concat rpl tag)))))
6467 link))
6469 ;;; Storing and inserting links
6471 (defvar org-insert-link-history nil
6472 "Minibuffer history for links inserted with `org-insert-link'.")
6474 (defvar org-stored-links nil
6475 "Contains the links stored with `org-store-link'.")
6477 (defvar org-store-link-plist nil
6478 "Plist with info about the most recently link created with `org-store-link'.")
6480 (defvar org-link-protocols nil
6481 "Link protocols added to Org-mode using `org-add-link-type'.")
6483 (defvar org-store-link-functions nil
6484 "List of functions that are called to create and store a link.
6485 Each function will be called in turn until one returns a non-nil
6486 value. Each function should check if it is responsible for creating
6487 this link (for example by looking at the major mode).
6488 If not, it must exit and return nil.
6489 If yes, it should return a non-nil value after a calling
6490 `org-store-link-props' with a list of properties and values.
6491 Special properties are:
6493 :type The link prefix. like \"http\". This must be given.
6494 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6495 This is obligatory as well.
6496 :description Optional default description for the second pair
6497 of brackets in an Org-mode link. The user can still change
6498 this when inserting this link into an Org-mode buffer.
6500 In addition to these, any additional properties can be specified
6501 and then used in remember templates.")
6503 (defun org-add-link-type (type &optional follow export)
6504 "Add TYPE to the list of `org-link-types'.
6505 Re-compute all regular expressions depending on `org-link-types'
6507 FOLLOW and EXPORT are two functions.
6509 FOLLOW should take the link path as the single argument and do whatever
6510 is necessary to follow the link, for example find a file or display
6511 a mail message.
6513 EXPORT should format the link path for export to one of the export formats.
6514 It should be a function accepting three arguments:
6516 path the path of the link, the text after the prefix (like \"http:\")
6517 desc the description of the link, if any, nil if there was no description
6518 format the export format, a symbol like `html' or `latex'.
6520 The function may use the FORMAT information to return different values
6521 depending on the format. The return value will be put literally into
6522 the exported file.
6523 Org-mode has a built-in default for exporting links. If you are happy with
6524 this default, there is no need to define an export function for the link
6525 type. For a simple example of an export function, see `org-bbdb.el'."
6526 (add-to-list 'org-link-types type t)
6527 (org-make-link-regexps)
6528 (if (assoc type org-link-protocols)
6529 (setcdr (assoc type org-link-protocols) (list follow export))
6530 (push (list type follow export) org-link-protocols)))
6532 ;;;###autoload
6533 (defun org-store-link (arg)
6534 "\\<org-mode-map>Store an org-link to the current location.
6535 This link is added to `org-stored-links' and can later be inserted
6536 into an org-buffer with \\[org-insert-link].
6538 For some link types, a prefix arg is interpreted:
6539 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6540 For file links, arg negates `org-context-in-file-links'."
6541 (interactive "P")
6542 (org-load-modules-maybe)
6543 (setq org-store-link-plist nil) ; reset
6544 (let (link cpltxt desc description search txt)
6545 (cond
6547 ((run-hook-with-args-until-success 'org-store-link-functions)
6548 (setq link (plist-get org-store-link-plist :link)
6549 desc (or (plist-get org-store-link-plist :description) link)))
6551 ((equal (buffer-name) "*Org Edit Src Example*")
6552 (let (label gc)
6553 (while (or (not label)
6554 (save-excursion
6555 (save-restriction
6556 (widen)
6557 (goto-char (point-min))
6558 (re-search-forward
6559 (regexp-quote (format org-coderef-label-format label))
6560 nil t))))
6561 (when label (message "Label exists already") (sit-for 2))
6562 (setq label (read-string "Code line label: " label)))
6563 (end-of-line 1)
6564 (setq link (format org-coderef-label-format label))
6565 (setq gc (- 79 (length link)))
6566 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6567 (insert link)
6568 (setq link (concat "(" label ")") desc nil)))
6570 ((eq major-mode 'calendar-mode)
6571 (let ((cd (calendar-cursor-to-date)))
6572 (setq link
6573 (format-time-string
6574 (car org-time-stamp-formats)
6575 (apply 'encode-time
6576 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6577 nil nil nil))))
6578 (org-store-link-props :type "calendar" :date cd)))
6580 ((eq major-mode 'w3-mode)
6581 (setq cpltxt (url-view-url t)
6582 link (org-make-link cpltxt))
6583 (org-store-link-props :type "w3" :url (url-view-url t)))
6585 ((eq major-mode 'w3m-mode)
6586 (setq cpltxt (or w3m-current-title w3m-current-url)
6587 link (org-make-link w3m-current-url))
6588 (org-store-link-props :type "w3m" :url (url-view-url t)))
6590 ((setq search (run-hook-with-args-until-success
6591 'org-create-file-search-functions))
6592 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6593 "::" search))
6594 (setq cpltxt (or description link)))
6596 ((eq major-mode 'image-mode)
6597 (setq cpltxt (concat "file:"
6598 (abbreviate-file-name buffer-file-name))
6599 link (org-make-link cpltxt))
6600 (org-store-link-props :type "image" :file buffer-file-name))
6602 ((eq major-mode 'dired-mode)
6603 ;; link to the file in the current line
6604 (setq cpltxt (concat "file:"
6605 (abbreviate-file-name
6606 (expand-file-name
6607 (dired-get-filename nil t))))
6608 link (org-make-link cpltxt)))
6610 ((and buffer-file-name (org-mode-p))
6611 (cond
6612 ((org-in-regexp "<<\\(.*?\\)>>")
6613 (setq cpltxt
6614 (concat "file:"
6615 (abbreviate-file-name buffer-file-name)
6616 "::" (match-string 1))
6617 link (org-make-link cpltxt)))
6618 ((and (featurep 'org-id)
6619 (or (eq org-link-to-org-use-id t)
6620 (and (eq org-link-to-org-use-id 'create-if-interactive)
6621 (interactive-p))
6622 (and org-link-to-org-use-id
6623 (condition-case nil
6624 (org-entry-get nil "ID")
6625 (error nil)))))
6626 ;; We can make a link using the ID.
6627 (setq link (condition-case nil
6628 (prog1 (org-id-store-link)
6629 (setq desc (plist-get org-store-link-plist
6630 :description)))
6631 (error
6632 ;; probably before first headline, link to file only
6633 (concat "file:"
6634 (abbreviate-file-name buffer-file-name))))))
6636 ;; Just link to current headline
6637 (setq cpltxt (concat "file:"
6638 (abbreviate-file-name buffer-file-name)))
6639 ;; Add a context search string
6640 (when (org-xor org-context-in-file-links arg)
6641 (setq txt (cond
6642 ((org-on-heading-p) nil)
6643 ((org-region-active-p)
6644 (buffer-substring (region-beginning) (region-end)))
6645 (t nil)))
6646 (when (or (null txt) (string-match "\\S-" txt))
6647 (setq cpltxt
6648 (concat cpltxt "::"
6649 (condition-case nil
6650 (org-make-org-heading-search-string txt)
6651 (error "")))
6652 desc "NONE")))
6653 (if (string-match "::\\'" cpltxt)
6654 (setq cpltxt (substring cpltxt 0 -2)))
6655 (setq link (org-make-link cpltxt)))))
6657 ((buffer-file-name (buffer-base-buffer))
6658 ;; Just link to this file here.
6659 (setq cpltxt (concat "file:"
6660 (abbreviate-file-name
6661 (buffer-file-name (buffer-base-buffer)))))
6662 ;; Add a context string
6663 (when (org-xor org-context-in-file-links arg)
6664 (setq txt (if (org-region-active-p)
6665 (buffer-substring (region-beginning) (region-end))
6666 (buffer-substring (point-at-bol) (point-at-eol))))
6667 ;; Only use search option if there is some text.
6668 (when (string-match "\\S-" txt)
6669 (setq cpltxt
6670 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6671 desc "NONE")))
6672 (setq link (org-make-link cpltxt)))
6674 ((interactive-p)
6675 (error "Cannot link to a buffer which is not visiting a file"))
6677 (t (setq link nil)))
6679 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6680 (setq link (or link cpltxt)
6681 desc (or desc cpltxt))
6682 (if (equal desc "NONE") (setq desc nil))
6684 (if (and (interactive-p) link)
6685 (progn
6686 (setq org-stored-links
6687 (cons (list link desc) org-stored-links))
6688 (message "Stored: %s" (or desc link)))
6689 (and link (org-make-link-string link desc)))))
6691 (defun org-store-link-props (&rest plist)
6692 "Store link properties, extract names and addresses."
6693 (let (x adr)
6694 (when (setq x (plist-get plist :from))
6695 (setq adr (mail-extract-address-components x))
6696 (setq plist (plist-put plist :fromname (car adr)))
6697 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6698 (when (setq x (plist-get plist :to))
6699 (setq adr (mail-extract-address-components x))
6700 (setq plist (plist-put plist :toname (car adr)))
6701 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6702 (let ((from (plist-get plist :from))
6703 (to (plist-get plist :to)))
6704 (when (and from to org-from-is-user-regexp)
6705 (setq plist
6706 (plist-put plist :fromto
6707 (if (string-match org-from-is-user-regexp from)
6708 (concat "to %t")
6709 (concat "from %f"))))))
6710 (setq org-store-link-plist plist))
6712 (defun org-add-link-props (&rest plist)
6713 "Add these properties to the link property list."
6714 (let (key value)
6715 (while plist
6716 (setq key (pop plist) value (pop plist))
6717 (setq org-store-link-plist
6718 (plist-put org-store-link-plist key value)))))
6720 (defun org-email-link-description (&optional fmt)
6721 "Return the description part of an email link.
6722 This takes information from `org-store-link-plist' and formats it
6723 according to FMT (default from `org-email-link-description-format')."
6724 (setq fmt (or fmt org-email-link-description-format))
6725 (let* ((p org-store-link-plist)
6726 (to (plist-get p :toaddress))
6727 (from (plist-get p :fromaddress))
6728 (table
6729 (list
6730 (cons "%c" (plist-get p :fromto))
6731 (cons "%F" (plist-get p :from))
6732 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6733 (cons "%T" (plist-get p :to))
6734 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6735 (cons "%s" (plist-get p :subject))
6736 (cons "%m" (plist-get p :message-id)))))
6737 (when (string-match "%c" fmt)
6738 ;; Check if the user wrote this message
6739 (if (and org-from-is-user-regexp from to
6740 (save-match-data (string-match org-from-is-user-regexp from)))
6741 (setq fmt (replace-match "to %t" t t fmt))
6742 (setq fmt (replace-match "from %f" t t fmt))))
6743 (org-replace-escapes fmt table)))
6745 (defun org-make-org-heading-search-string (&optional string heading)
6746 "Make search string for STRING or current headline."
6747 (interactive)
6748 (let ((s (or string (org-get-heading))))
6749 (unless (and string (not heading))
6750 ;; We are using a headline, clean up garbage in there.
6751 (if (string-match org-todo-regexp s)
6752 (setq s (replace-match "" t t s)))
6753 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6754 (setq s (replace-match "" t t s)))
6755 (setq s (org-trim s))
6756 (if (string-match (concat "^\\(" org-quote-string "\\|"
6757 org-comment-string "\\)") s)
6758 (setq s (replace-match "" t t s)))
6759 (while (string-match org-ts-regexp s)
6760 (setq s (replace-match "" t t s))))
6761 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6762 (setq s (replace-match " " t t s)))
6763 (or string (setq s (concat "*" s))) ; Add * for headlines
6764 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6766 (defun org-make-link (&rest strings)
6767 "Concatenate STRINGS."
6768 (apply 'concat strings))
6770 (defun org-make-link-string (link &optional description)
6771 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6772 (unless (string-match "\\S-" link)
6773 (error "Empty link"))
6774 (when (stringp description)
6775 ;; Remove brackets from the description, they are fatal.
6776 (while (string-match "\\[" description)
6777 (setq description (replace-match "{" t t description)))
6778 (while (string-match "\\]" description)
6779 (setq description (replace-match "}" t t description))))
6780 (when (equal (org-link-escape link) description)
6781 ;; No description needed, it is identical
6782 (setq description nil))
6783 (when (and (not description)
6784 (not (equal link (org-link-escape link))))
6785 (setq description (org-extract-attributes link)))
6786 (concat "[[" (org-link-escape link) "]"
6787 (if description (concat "[" description "]") "")
6788 "]"))
6790 (defconst org-link-escape-chars
6791 '((?\ . "%20")
6792 (?\[ . "%5B")
6793 (?\] . "%5D")
6794 (?\340 . "%E0") ; `a
6795 (?\342 . "%E2") ; ^a
6796 (?\347 . "%E7") ; ,c
6797 (?\350 . "%E8") ; `e
6798 (?\351 . "%E9") ; 'e
6799 (?\352 . "%EA") ; ^e
6800 (?\356 . "%EE") ; ^i
6801 (?\364 . "%F4") ; ^o
6802 (?\371 . "%F9") ; `u
6803 (?\373 . "%FB") ; ^u
6804 (?\; . "%3B")
6805 (?? . "%3F")
6806 (?= . "%3D")
6807 (?+ . "%2B")
6809 "Association list of escapes for some characters problematic in links.
6810 This is the list that is used for internal purposes.")
6812 (defconst org-link-escape-chars-browser
6813 '((?\ . "%20")) ; 32 for the SPC char
6814 "Association list of escapes for some characters problematic in links.
6815 This is the list that is used before handing over to the browser.")
6817 (defun org-link-escape (text &optional table)
6818 "Escape characters in TEXT that are problematic for links."
6819 (setq table (or table org-link-escape-chars))
6820 (when text
6821 (let ((re (mapconcat (lambda (x) (regexp-quote
6822 (char-to-string (car x))))
6823 table "\\|")))
6824 (while (string-match re text)
6825 (setq text
6826 (replace-match
6827 (cdr (assoc (string-to-char (match-string 0 text))
6828 table))
6829 t t text)))
6830 text)))
6832 (defun org-link-unescape (text &optional table)
6833 "Reverse the action of `org-link-escape'."
6834 (setq table (or table org-link-escape-chars))
6835 (when text
6836 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6837 table "\\|")))
6838 (while (string-match re text)
6839 (setq text
6840 (replace-match
6841 (char-to-string (car (rassoc (match-string 0 text) table)))
6842 t t text)))
6843 text)))
6845 (defun org-xor (a b)
6846 "Exclusive or."
6847 (if a (not b) b))
6849 (defun org-fixup-message-id-for-http (s)
6850 "Replace special characters in a message id, so it can be used in an http query."
6851 (while (string-match "<" s)
6852 (setq s (replace-match "%3C" t t s)))
6853 (while (string-match ">" s)
6854 (setq s (replace-match "%3E" t t s)))
6855 (while (string-match "@" s)
6856 (setq s (replace-match "%40" t t s)))
6859 ;;;###autoload
6860 (defun org-insert-link-global ()
6861 "Insert a link like Org-mode does.
6862 This command can be called in any mode to insert a link in Org-mode syntax."
6863 (interactive)
6864 (org-load-modules-maybe)
6865 (org-run-like-in-org-mode 'org-insert-link))
6867 (defun org-insert-link (&optional complete-file link-location)
6868 "Insert a link. At the prompt, enter the link.
6870 Completion can be used to insert any of the link protocol prefixes like
6871 http or ftp in use.
6873 The history can be used to select a link previously stored with
6874 `org-store-link'. When the empty string is entered (i.e. if you just
6875 press RET at the prompt), the link defaults to the most recently
6876 stored link. As SPC triggers completion in the minibuffer, you need to
6877 use M-SPC or C-q SPC to force the insertion of a space character.
6879 You will also be prompted for a description, and if one is given, it will
6880 be displayed in the buffer instead of the link.
6882 If there is already a link at point, this command will allow you to edit link
6883 and description parts.
6885 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6886 be selected using completion. The path to the file will be relative to the
6887 current directory if the file is in the current directory or a subdirectory.
6888 Otherwise, the link will be the absolute path as completed in the minibuffer
6889 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6890 option `org-link-file-path-type'.
6892 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6893 the current directory or below.
6895 With three \\[universal-argument] prefixes, negate the meaning of
6896 `org-keep-stored-link-after-insertion'.
6898 If `org-make-link-description-function' is non-nil, this function will be
6899 called with the link target, and the result will be the default
6900 link description.
6902 If the LINK-LOCATION parameter is non-nil, this value will be
6903 used as the link location instead of reading one interactively."
6904 (interactive "P")
6905 (let* ((wcf (current-window-configuration))
6906 (region (if (org-region-active-p)
6907 (buffer-substring (region-beginning) (region-end))))
6908 (remove (and region (list (region-beginning) (region-end))))
6909 (desc region)
6910 tmphist ; byte-compile incorrectly complains about this
6911 (link link-location)
6912 entry file)
6913 (cond
6914 (link-location) ; specified by arg, just use it.
6915 ((org-in-regexp org-bracket-link-regexp 1)
6916 ;; We do have a link at point, and we are going to edit it.
6917 (setq remove (list (match-beginning 0) (match-end 0)))
6918 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6919 (setq link (read-string "Link: "
6920 (org-link-unescape
6921 (org-match-string-no-properties 1)))))
6922 ((or (org-in-regexp org-angle-link-re)
6923 (org-in-regexp org-plain-link-re))
6924 ;; Convert to bracket link
6925 (setq remove (list (match-beginning 0) (match-end 0))
6926 link (read-string "Link: "
6927 (org-remove-angle-brackets (match-string 0)))))
6928 ((member complete-file '((4) (16)))
6929 ;; Completing read for file names.
6930 (setq file (read-file-name "File: "))
6931 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6932 (pwd1 (file-name-as-directory (abbreviate-file-name
6933 (expand-file-name ".")))))
6934 (cond
6935 ((equal complete-file '(16))
6936 (setq link (org-make-link
6937 "file:"
6938 (abbreviate-file-name (expand-file-name file)))))
6939 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6940 (setq link (org-make-link "file:" (match-string 1 file))))
6941 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6942 (expand-file-name file))
6943 (setq link (org-make-link
6944 "file:" (match-string 1 (expand-file-name file)))))
6945 (t (setq link (org-make-link "file:" file))))))
6947 ;; Read link, with completion for stored links.
6948 (with-output-to-temp-buffer "*Org Links*"
6949 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6950 (when org-stored-links
6951 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6952 (princ (mapconcat
6953 (lambda (x)
6954 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6955 (reverse org-stored-links) "\n"))))
6956 (let ((cw (selected-window)))
6957 (select-window (get-buffer-window "*Org Links*"))
6958 (setq truncate-lines t)
6959 (org-fit-window-to-buffer)
6960 (select-window cw))
6961 ;; Fake a link history, containing the stored links.
6962 (setq tmphist (append (mapcar 'car org-stored-links)
6963 org-insert-link-history))
6964 (unwind-protect
6965 (setq link
6966 (let ((org-completion-use-ido nil))
6967 (org-completing-read
6968 "Link: "
6969 (append
6970 (mapcar (lambda (x) (list (concat (car x) ":")))
6971 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6972 (mapcar (lambda (x) (list (concat x ":")))
6973 org-link-types))
6974 nil nil nil
6975 'tmphist
6976 (or (car (car org-stored-links))))))
6977 (set-window-configuration wcf)
6978 (kill-buffer "*Org Links*"))
6979 (setq entry (assoc link org-stored-links))
6980 (or entry (push link org-insert-link-history))
6981 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6982 (not org-keep-stored-link-after-insertion))
6983 (setq org-stored-links (delq (assoc link org-stored-links)
6984 org-stored-links)))
6985 (setq desc (or desc (nth 1 entry)))))
6987 (if (string-match org-plain-link-re link)
6988 ;; URL-like link, normalize the use of angular brackets.
6989 (setq link (org-make-link (org-remove-angle-brackets link))))
6991 ;; Check if we are linking to the current file with a search option
6992 ;; If yes, simplify the link by using only the search option.
6993 (when (and buffer-file-name
6994 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6995 (let* ((path (match-string 1 link))
6996 (case-fold-search nil)
6997 (search (match-string 2 link)))
6998 (save-match-data
6999 (if (equal (file-truename buffer-file-name) (file-truename path))
7000 ;; We are linking to this same file, with a search option
7001 (setq link search)))))
7003 ;; Check if we can/should use a relative path. If yes, simplify the link
7004 (when (string-match "^file:\\(.*\\)" link)
7005 (let* ((path (match-string 1 link))
7006 (origpath path)
7007 (case-fold-search nil))
7008 (cond
7009 ((or (eq org-link-file-path-type 'absolute)
7010 (equal complete-file '(16)))
7011 (setq path (abbreviate-file-name (expand-file-name path))))
7012 ((eq org-link-file-path-type 'noabbrev)
7013 (setq path (expand-file-name path)))
7014 ((eq org-link-file-path-type 'relative)
7015 (setq path (file-relative-name path)))
7017 (save-match-data
7018 (if (string-match (concat "^" (regexp-quote
7019 (file-name-as-directory
7020 (expand-file-name "."))))
7021 (expand-file-name path))
7022 ;; We are linking a file with relative path name.
7023 (setq path (substring (expand-file-name path)
7024 (match-end 0)))
7025 (setq path (abbreviate-file-name (expand-file-name path)))))))
7026 (setq link (concat "file:" path))
7027 (if (equal desc origpath)
7028 (setq desc path))))
7030 (if org-make-link-description-function
7031 (setq desc (funcall org-make-link-description-function link desc)))
7033 (setq desc (read-string "Description: " desc))
7034 (unless (string-match "\\S-" desc) (setq desc nil))
7035 (if remove (apply 'delete-region remove))
7036 (insert (org-make-link-string link desc))))
7038 (defun org-completing-read (&rest args)
7039 "Completing-read with SPACE being a normal character."
7040 (let ((minibuffer-local-completion-map
7041 (copy-keymap minibuffer-local-completion-map)))
7042 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7043 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7044 (apply 'org-ido-completing-read args)))
7046 (defun org-completing-read-no-ido (&rest args)
7047 (let (org-completion-use-ido)
7048 (apply 'org-completing-read args)))
7050 (defun org-ido-completing-read (&rest args)
7051 "Completing-read using `ido-mode' speedups if available"
7052 (if (and org-completion-use-ido
7053 (fboundp 'ido-completing-read)
7054 (boundp 'ido-mode) ido-mode
7055 (listp (second args)))
7056 (let ((ido-enter-matching-directory nil))
7057 (apply 'ido-completing-read (concat (car args))
7058 (mapcar (lambda (x) (car x)) (nth 1 args))
7059 (cddr args)))
7060 (apply 'completing-read args)))
7063 (defun org-extract-attributes (s)
7064 "Extract the attributes cookie from a string and set as text property."
7065 (let (a attr (start 0) key value)
7066 (save-match-data
7067 (when (string-match "{{\\([^}]+\\)}}$" s)
7068 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7069 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7070 (setq key (match-string 1 a) value (match-string 2 a)
7071 start (match-end 0)
7072 attr (plist-put attr (intern key) value))))
7073 (org-add-props s nil 'org-attr attr))
7076 (defun org-attributes-to-string (plist)
7077 "Format a property list into an HTML attribute list."
7078 (let ((s "") key value)
7079 (while plist
7080 (setq key (pop plist) value (pop plist))
7081 (and value
7082 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7085 ;;; Opening/following a link
7087 (defvar org-link-search-failed nil)
7089 (defun org-next-link ()
7090 "Move forward to the next link.
7091 If the link is in hidden text, expose it."
7092 (interactive)
7093 (when (and org-link-search-failed (eq this-command last-command))
7094 (goto-char (point-min))
7095 (message "Link search wrapped back to beginning of buffer"))
7096 (setq org-link-search-failed nil)
7097 (let* ((pos (point))
7098 (ct (org-context))
7099 (a (assoc :link ct)))
7100 (if a (goto-char (nth 2 a)))
7101 (if (re-search-forward org-any-link-re nil t)
7102 (progn
7103 (goto-char (match-beginning 0))
7104 (if (org-invisible-p) (org-show-context)))
7105 (goto-char pos)
7106 (setq org-link-search-failed t)
7107 (error "No further link found"))))
7109 (defun org-previous-link ()
7110 "Move backward to the previous link.
7111 If the link is in hidden text, expose it."
7112 (interactive)
7113 (when (and org-link-search-failed (eq this-command last-command))
7114 (goto-char (point-max))
7115 (message "Link search wrapped back to end of buffer"))
7116 (setq org-link-search-failed nil)
7117 (let* ((pos (point))
7118 (ct (org-context))
7119 (a (assoc :link ct)))
7120 (if a (goto-char (nth 1 a)))
7121 (if (re-search-backward org-any-link-re nil t)
7122 (progn
7123 (goto-char (match-beginning 0))
7124 (if (org-invisible-p) (org-show-context)))
7125 (goto-char pos)
7126 (setq org-link-search-failed t)
7127 (error "No further link found"))))
7129 (defun org-translate-link (s)
7130 "Translate a link string if a translation function has been defined."
7131 (if (and org-link-translation-function
7132 (fboundp org-link-translation-function)
7133 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7134 (progn
7135 (setq s (funcall org-link-translation-function
7136 (match-string 1) (match-string 2)))
7137 (concat (car s) ":" (cdr s)))
7140 (defun org-translate-link-from-planner (type path)
7141 "Translate a link from Emacs Planner syntax so that Org can follow it.
7142 This is still an experimental function, your mileage may vary."
7143 (cond
7144 ((member type '("http" "https" "news" "ftp"))
7145 ;; standard Internet links are the same.
7146 nil)
7147 ((and (equal type "irc") (string-match "^//" path))
7148 ;; Planner has two / at the beginning of an irc link, we have 1.
7149 ;; We should have zero, actually....
7150 (setq path (substring path 1)))
7151 ((and (equal type "lisp") (string-match "^/" path))
7152 ;; Planner has a slash, we do not.
7153 (setq type "elisp" path (substring path 1)))
7154 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7155 ;; A typical message link. Planner has the id after the fina slash,
7156 ;; we separate it with a hash mark
7157 (setq path (concat (match-string 1 path) "#"
7158 (org-remove-angle-brackets (match-string 2 path)))))
7160 (cons type path))
7162 (defun org-find-file-at-mouse (ev)
7163 "Open file link or URL at mouse."
7164 (interactive "e")
7165 (mouse-set-point ev)
7166 (org-open-at-point 'in-emacs))
7168 (defun org-open-at-mouse (ev)
7169 "Open file link or URL at mouse."
7170 (interactive "e")
7171 (mouse-set-point ev)
7172 (if (eq major-mode 'org-agenda-mode)
7173 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7174 (org-open-at-point))
7176 (defvar org-window-config-before-follow-link nil
7177 "The window configuration before following a link.
7178 This is saved in case the need arises to restore it.")
7180 (defvar org-open-link-marker (make-marker)
7181 "Marker pointing to the location where `org-open-at-point; was called.")
7183 ;;;###autoload
7184 (defun org-open-at-point-global ()
7185 "Follow a link like Org-mode does.
7186 This command can be called in any mode to follow a link that has
7187 Org-mode syntax."
7188 (interactive)
7189 (org-run-like-in-org-mode 'org-open-at-point))
7191 ;;;###autoload
7192 (defun org-open-link-from-string (s &optional arg)
7193 "Open a link in the string S, as if it was in Org-mode."
7194 (interactive "sLink: \nP")
7195 (with-temp-buffer
7196 (let ((org-inhibit-startup t))
7197 (org-mode)
7198 (insert s)
7199 (goto-char (point-min))
7200 (org-open-at-point arg))))
7202 (defun org-open-at-point (&optional in-emacs)
7203 "Open link at or after point.
7204 If there is no link at point, this function will search forward up to
7205 the end of the current subtree.
7206 Normally, files will be opened by an appropriate application. If the
7207 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7208 With a double prefix argument, try to open outside of Emacs, in the
7209 application the system uses for this file type."
7210 (interactive "P")
7211 (org-load-modules-maybe)
7212 (move-marker org-open-link-marker (point))
7213 (setq org-window-config-before-follow-link (current-window-configuration))
7214 (org-remove-occur-highlights nil nil t)
7215 (cond
7216 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7217 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7218 (org-footnote-action))
7220 (let (type path link line search (pos (point)))
7221 (catch 'match
7222 (save-excursion
7223 (skip-chars-forward "^]\n\r")
7224 (when (org-in-regexp org-bracket-link-regexp)
7225 (setq link (org-extract-attributes
7226 (org-link-unescape (org-match-string-no-properties 1))))
7227 (while (string-match " *\n *" link)
7228 (setq link (replace-match " " t t link)))
7229 (setq link (org-link-expand-abbrev link))
7230 (cond
7231 ((or (file-name-absolute-p link)
7232 (string-match "^\\.\\.?/" link))
7233 (setq type "file" path link))
7234 ((string-match org-link-re-with-space3 link)
7235 (setq type (match-string 1 link) path (match-string 2 link)))
7236 (t (setq type "thisfile" path link)))
7237 (throw 'match t)))
7239 (when (get-text-property (point) 'org-linked-text)
7240 (setq type "thisfile"
7241 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7242 (1+ (point)) (point))
7243 path (buffer-substring
7244 (previous-single-property-change pos 'org-linked-text)
7245 (next-single-property-change pos 'org-linked-text)))
7246 (throw 'match t))
7248 (save-excursion
7249 (when (or (org-in-regexp org-angle-link-re)
7250 (org-in-regexp org-plain-link-re))
7251 (setq type (match-string 1) path (match-string 2))
7252 (throw 'match t)))
7253 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7254 (setq type "tree-match"
7255 path (match-string 1))
7256 (throw 'match t))
7257 (save-excursion
7258 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7259 (setq type "tags"
7260 path (match-string 1))
7261 (while (string-match ":" path)
7262 (setq path (replace-match "+" t t path)))
7263 (throw 'match t))))
7264 (unless path
7265 (error "No link found"))
7266 ;; Remove any trailing spaces in path
7267 (if (string-match " +\\'" path)
7268 (setq path (replace-match "" t t path)))
7269 (if (and org-link-translation-function
7270 (fboundp org-link-translation-function))
7271 ;; Check if we need to translate the link
7272 (let ((tmp (funcall org-link-translation-function type path)))
7273 (setq type (car tmp) path (cdr tmp))))
7275 (cond
7277 ((assoc type org-link-protocols)
7278 (funcall (nth 1 (assoc type org-link-protocols)) path))
7280 ((equal type "mailto")
7281 (let ((cmd (car org-link-mailto-program))
7282 (args (cdr org-link-mailto-program)) args1
7283 (address path) (subject "") a)
7284 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7285 (setq address (match-string 1 path)
7286 subject (org-link-escape (match-string 2 path))))
7287 (while args
7288 (cond
7289 ((not (stringp (car args))) (push (pop args) args1))
7290 (t (setq a (pop args))
7291 (if (string-match "%a" a)
7292 (setq a (replace-match address t t a)))
7293 (if (string-match "%s" a)
7294 (setq a (replace-match subject t t a)))
7295 (push a args1))))
7296 (apply cmd (nreverse args1))))
7298 ((member type '("http" "https" "ftp" "news"))
7299 (browse-url (concat type ":" (org-link-escape
7300 path org-link-escape-chars-browser))))
7302 ((member type '("message"))
7303 (browse-url (concat type ":" path)))
7305 ((string= type "tags")
7306 (org-tags-view in-emacs path))
7307 ((string= type "thisfile")
7308 (if in-emacs
7309 (switch-to-buffer-other-window
7310 (org-get-buffer-for-internal-link (current-buffer)))
7311 (org-mark-ring-push))
7312 (let ((cmd `(org-link-search
7313 ,path
7314 ,(cond ((equal in-emacs '(4)) 'occur)
7315 ((equal in-emacs '(16)) 'org-occur)
7316 (t nil))
7317 ,pos)))
7318 (condition-case nil (eval cmd)
7319 (error (progn (widen) (eval cmd))))))
7321 ((string= type "tree-match")
7322 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7324 ((string= type "file")
7325 (if (string-match "::\\([0-9]+\\)\\'" path)
7326 (setq line (string-to-number (match-string 1 path))
7327 path (substring path 0 (match-beginning 0)))
7328 (if (string-match "::\\(.+\\)\\'" path)
7329 (setq search (match-string 1 path)
7330 path (substring path 0 (match-beginning 0)))))
7331 (if (string-match "[*?{]" (file-name-nondirectory path))
7332 (dired path)
7333 (org-open-file path in-emacs line search)))
7335 ((string= type "news")
7336 (require 'org-gnus)
7337 (org-gnus-follow-link path))
7339 ((string= type "shell")
7340 (let ((cmd path))
7341 (if (or (not org-confirm-shell-link-function)
7342 (funcall org-confirm-shell-link-function
7343 (format "Execute \"%s\" in shell? "
7344 (org-add-props cmd nil
7345 'face 'org-warning))))
7346 (progn
7347 (message "Executing %s" cmd)
7348 (shell-command cmd))
7349 (error "Abort"))))
7351 ((string= type "elisp")
7352 (let ((cmd path))
7353 (if (or (not org-confirm-elisp-link-function)
7354 (funcall org-confirm-elisp-link-function
7355 (format "Execute \"%s\" as elisp? "
7356 (org-add-props cmd nil
7357 'face 'org-warning))))
7358 (message "%s => %s" cmd
7359 (if (equal (string-to-char cmd) ?\()
7360 (eval (read cmd))
7361 (call-interactively (read cmd))))
7362 (error "Abort"))))
7365 (browse-url-at-point))))))
7366 (move-marker org-open-link-marker nil)
7367 (run-hook-with-args 'org-follow-link-hook))
7369 ;;;; Time estimates
7371 (defun org-get-effort (&optional pom)
7372 "Get the effort estimate for the current entry."
7373 (org-entry-get pom org-effort-property))
7375 ;;; File search
7377 (defvar org-create-file-search-functions nil
7378 "List of functions to construct the right search string for a file link.
7379 These functions are called in turn with point at the location to
7380 which the link should point.
7382 A function in the hook should first test if it would like to
7383 handle this file type, for example by checking the major-mode or
7384 the file extension. If it decides not to handle this file, it
7385 should just return nil to give other functions a chance. If it
7386 does handle the file, it must return the search string to be used
7387 when following the link. The search string will be part of the
7388 file link, given after a double colon, and `org-open-at-point'
7389 will automatically search for it. If special measures must be
7390 taken to make the search successful, another function should be
7391 added to the companion hook `org-execute-file-search-functions',
7392 which see.
7394 A function in this hook may also use `setq' to set the variable
7395 `description' to provide a suggestion for the descriptive text to
7396 be used for this link when it gets inserted into an Org-mode
7397 buffer with \\[org-insert-link].")
7399 (defvar org-execute-file-search-functions nil
7400 "List of functions to execute a file search triggered by a link.
7402 Functions added to this hook must accept a single argument, the
7403 search string that was part of the file link, the part after the
7404 double colon. The function must first check if it would like to
7405 handle this search, for example by checking the major-mode or the
7406 file extension. If it decides not to handle this search, it
7407 should just return nil to give other functions a chance. If it
7408 does handle the search, it must return a non-nil value to keep
7409 other functions from trying.
7411 Each function can access the current prefix argument through the
7412 variable `current-prefix-argument'. Note that a single prefix is
7413 used to force opening a link in Emacs, so it may be good to only
7414 use a numeric or double prefix to guide the search function.
7416 In case this is needed, a function in this hook can also restore
7417 the window configuration before `org-open-at-point' was called using:
7419 (set-window-configuration org-window-config-before-follow-link)")
7421 (defun org-link-search (s &optional type avoid-pos)
7422 "Search for a link search option.
7423 If S is surrounded by forward slashes, it is interpreted as a
7424 regular expression. In org-mode files, this will create an `org-occur'
7425 sparse tree. In ordinary files, `occur' will be used to list matches.
7426 If the current buffer is in `dired-mode', grep will be used to search
7427 in all files. If AVOID-POS is given, ignore matches near that position."
7428 (let ((case-fold-search t)
7429 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7430 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7431 (append '(("") (" ") ("\t") ("\n"))
7432 org-emphasis-alist)
7433 "\\|") "\\)"))
7434 (pos (point))
7435 (pre nil) (post nil)
7436 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7437 (cond
7438 ;; First check if there are any special
7439 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7440 ;; Now try the builtin stuff
7441 ((save-excursion
7442 (goto-char (point-min))
7443 (and
7444 (re-search-forward
7445 (concat "<<" (regexp-quote s0) ">>") nil t)
7446 (setq type 'dedicated
7447 pos (match-beginning 0))))
7448 ;; There is an exact target for this
7449 (goto-char pos))
7450 ((and (string-match "^(\\(.*\\))$" s0)
7451 (save-excursion
7452 (goto-char (point-min))
7453 (and
7454 (re-search-forward
7455 (concat "[^[]" (regexp-quote
7456 (format org-coderef-label-format
7457 (match-string 1 s0))))
7458 nil t)
7459 (setq type 'dedicated
7460 pos (1+ (match-beginning 0))))))
7461 ;; There is a coderef target for this
7462 (goto-char pos))
7463 ((string-match "^/\\(.*\\)/$" s)
7464 ;; A regular expression
7465 (cond
7466 ((org-mode-p)
7467 (org-occur (match-string 1 s)))
7468 ;;((eq major-mode 'dired-mode)
7469 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7470 (t (org-do-occur (match-string 1 s)))))
7472 ;; A normal search strings
7473 (when (equal (string-to-char s) ?*)
7474 ;; Anchor on headlines, post may include tags.
7475 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7476 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7477 s (substring s 1)))
7478 (remove-text-properties
7479 0 (length s)
7480 '(face nil mouse-face nil keymap nil fontified nil) s)
7481 ;; Make a series of regular expressions to find a match
7482 (setq words (org-split-string s "[ \n\r\t]+")
7484 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7485 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7486 "\\)" markers)
7487 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7488 re2a (concat "[ \t\r\n]" re2a_)
7489 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7490 re4 (concat "[^a-zA-Z_]" re4_)
7492 re1 (concat pre re2 post)
7493 re3 (concat pre (if pre re4_ re4) post)
7494 re5 (concat pre ".*" re4)
7495 re2 (concat pre re2)
7496 re2a (concat pre (if pre re2a_ re2a))
7497 re4 (concat pre (if pre re4_ re4))
7498 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7499 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7500 re5 "\\)"
7502 (cond
7503 ((eq type 'org-occur) (org-occur reall))
7504 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7505 (t (goto-char (point-min))
7506 (setq type 'fuzzy)
7507 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7508 (org-search-not-self 1 re1 nil t)
7509 (org-search-not-self 1 re2 nil t)
7510 (org-search-not-self 1 re2a nil t)
7511 (org-search-not-self 1 re3 nil t)
7512 (org-search-not-self 1 re4 nil t)
7513 (org-search-not-self 1 re5 nil t)
7515 (goto-char (match-beginning 1))
7516 (goto-char pos)
7517 (error "No match")))))
7519 ;; Normal string-search
7520 (goto-char (point-min))
7521 (if (search-forward s nil t)
7522 (goto-char (match-beginning 0))
7523 (error "No match"))))
7524 (and (org-mode-p) (org-show-context 'link-search))
7525 type))
7527 (defun org-search-not-self (group &rest args)
7528 "Execute `re-search-forward', but only accept matches that do not
7529 enclose the position of `org-open-link-marker'."
7530 (let ((m org-open-link-marker))
7531 (catch 'exit
7532 (while (apply 're-search-forward args)
7533 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7534 (goto-char (match-end group))
7535 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7536 (> (match-beginning 0) (marker-position m))
7537 (< (match-end 0) (marker-position m)))
7538 (save-match-data
7539 (or (not (org-in-regexp
7540 org-bracket-link-analytic-regexp 1))
7541 (not (match-end 4)) ; no description
7542 (and (<= (match-beginning 4) (point))
7543 (>= (match-end 4) (point))))))
7544 (throw 'exit (point))))))))
7546 (defun org-get-buffer-for-internal-link (buffer)
7547 "Return a buffer to be used for displaying the link target of internal links."
7548 (cond
7549 ((not org-display-internal-link-with-indirect-buffer)
7550 buffer)
7551 ((string-match "(Clone)$" (buffer-name buffer))
7552 (message "Buffer is already a clone, not making another one")
7553 ;; we also do not modify visibility in this case
7554 buffer)
7555 (t ; make a new indirect buffer for displaying the link
7556 (let* ((bn (buffer-name buffer))
7557 (ibn (concat bn "(Clone)"))
7558 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7559 (with-current-buffer ib (org-overview))
7560 ib))))
7562 (defun org-do-occur (regexp &optional cleanup)
7563 "Call the Emacs command `occur'.
7564 If CLEANUP is non-nil, remove the printout of the regular expression
7565 in the *Occur* buffer. This is useful if the regex is long and not useful
7566 to read."
7567 (occur regexp)
7568 (when cleanup
7569 (let ((cwin (selected-window)) win beg end)
7570 (when (setq win (get-buffer-window "*Occur*"))
7571 (select-window win))
7572 (goto-char (point-min))
7573 (when (re-search-forward "match[a-z]+" nil t)
7574 (setq beg (match-end 0))
7575 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7576 (setq end (1- (match-beginning 0)))))
7577 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7578 (goto-char (point-min))
7579 (select-window cwin))))
7581 ;;; The mark ring for links jumps
7583 (defvar org-mark-ring nil
7584 "Mark ring for positions before jumps in Org-mode.")
7585 (defvar org-mark-ring-last-goto nil
7586 "Last position in the mark ring used to go back.")
7587 ;; Fill and close the ring
7588 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7589 (loop for i from 1 to org-mark-ring-length do
7590 (push (make-marker) org-mark-ring))
7591 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7592 org-mark-ring)
7594 (defun org-mark-ring-push (&optional pos buffer)
7595 "Put the current position or POS into the mark ring and rotate it."
7596 (interactive)
7597 (setq pos (or pos (point)))
7598 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7599 (move-marker (car org-mark-ring)
7600 (or pos (point))
7601 (or buffer (current-buffer)))
7602 (message "%s"
7603 (substitute-command-keys
7604 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7606 (defun org-mark-ring-goto (&optional n)
7607 "Jump to the previous position in the mark ring.
7608 With prefix arg N, jump back that many stored positions. When
7609 called several times in succession, walk through the entire ring.
7610 Org-mode commands jumping to a different position in the current file,
7611 or to another Org-mode file, automatically push the old position
7612 onto the ring."
7613 (interactive "p")
7614 (let (p m)
7615 (if (eq last-command this-command)
7616 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7617 (setq p org-mark-ring))
7618 (setq org-mark-ring-last-goto p)
7619 (setq m (car p))
7620 (switch-to-buffer (marker-buffer m))
7621 (goto-char m)
7622 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7624 (defun org-remove-angle-brackets (s)
7625 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7626 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7628 (defun org-add-angle-brackets (s)
7629 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7630 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7632 (defun org-remove-double-quotes (s)
7633 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7634 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7637 ;;; Following specific links
7639 (defun org-follow-timestamp-link ()
7640 (cond
7641 ((org-at-date-range-p t)
7642 (let ((org-agenda-start-on-weekday)
7643 (t1 (match-string 1))
7644 (t2 (match-string 2)))
7645 (setq t1 (time-to-days (org-time-string-to-time t1))
7646 t2 (time-to-days (org-time-string-to-time t2)))
7647 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7648 ((org-at-timestamp-p t)
7649 (org-agenda-list nil (time-to-days (org-time-string-to-time
7650 (substring (match-string 1) 0 10)))
7652 (t (error "This should not happen"))))
7655 ;;; Following file links
7656 (defvar org-wait nil)
7657 (defun org-open-file (path &optional in-emacs line search)
7658 "Open the file at PATH.
7659 First, this expands any special file name abbreviations. Then the
7660 configuration variable `org-file-apps' is checked if it contains an
7661 entry for this file type, and if yes, the corresponding command is launched.
7663 If no application is found, Emacs simply visits the file.
7665 With optional prefix argument IN-EMACS, Emacs will visit the file.
7666 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7667 and o use an external application to visit the file.
7669 Optional LINE specifies a line to go to, optional SEARCH a string to
7670 search for. If LINE or SEARCH is given, the file will always be
7671 opened in Emacs.
7672 If the file does not exist, an error is thrown."
7673 (setq in-emacs (or in-emacs line search))
7674 (let* ((file (if (equal path "")
7675 buffer-file-name
7676 (substitute-in-file-name (expand-file-name path))))
7677 (apps (append org-file-apps (org-default-apps)))
7678 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7679 (dirp (if remp nil (file-directory-p file)))
7680 (file (if (and dirp org-open-directory-means-index-dot-org)
7681 (concat (file-name-as-directory file) "index.org")
7682 file))
7683 (a-m-a-p (assq 'auto-mode apps))
7684 (dfile (downcase file))
7685 (old-buffer (current-buffer))
7686 (old-pos (point))
7687 (old-mode major-mode)
7688 ext cmd)
7689 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7690 (setq ext (match-string 1 dfile))
7691 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7692 (setq ext (match-string 1 dfile))))
7693 (cond
7694 ((equal in-emacs '(16))
7695 (setq cmd (cdr (assoc 'system apps))))
7696 (in-emacs (setq cmd 'emacs))
7698 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7699 (and dirp (cdr (assoc 'directory apps)))
7700 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7701 'string-match)
7702 (cdr (assoc ext apps))
7703 (cdr (assoc t apps))))))
7704 (when (eq cmd 'system)
7705 (setq cmd (cdr (assoc 'system apps))))
7706 (when (eq cmd 'default)
7707 (setq cmd (cdr (assoc t apps))))
7708 (when (eq cmd 'mailcap)
7709 (require 'mailcap)
7710 (mailcap-parse-mailcaps)
7711 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7712 (command (mailcap-mime-info mime-type)))
7713 (if (stringp command)
7714 (setq cmd command)
7715 (setq cmd 'emacs))))
7716 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7717 (not (file-exists-p file))
7718 (not org-open-non-existing-files))
7719 (error "No such file: %s" file))
7720 (cond
7721 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7722 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7723 (while (string-match "['\"]%s['\"]" cmd)
7724 (setq cmd (replace-match "%s" t t cmd)))
7725 (while (string-match "%s" cmd)
7726 (setq cmd (replace-match
7727 (save-match-data
7728 (shell-quote-argument
7729 (convert-standard-filename file)))
7730 t t cmd)))
7731 (save-window-excursion
7732 (start-process-shell-command cmd nil cmd)
7733 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7735 ((or (stringp cmd)
7736 (eq cmd 'emacs))
7737 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7738 (widen)
7739 (if line (goto-line line)
7740 (if search (org-link-search search))))
7741 ((consp cmd)
7742 (let ((file (convert-standard-filename file)))
7743 (eval cmd)))
7744 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7745 (and (org-mode-p) (eq old-mode 'org-mode)
7746 (or (not (equal old-buffer (current-buffer)))
7747 (not (equal old-pos (point))))
7748 (org-mark-ring-push old-pos old-buffer))))
7750 (defun org-default-apps ()
7751 "Return the default applications for this operating system."
7752 (cond
7753 ((eq system-type 'darwin)
7754 org-file-apps-defaults-macosx)
7755 ((eq system-type 'windows-nt)
7756 org-file-apps-defaults-windowsnt)
7757 (t org-file-apps-defaults-gnu)))
7759 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7760 "Convert extensions to regular expressions in the cars of LIST.
7761 Also, weed out any non-string entries, because the return value is used
7762 only for regexp matching.
7763 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7764 point to the symbol `emacs', indicating that the file should
7765 be opened in Emacs."
7766 (append
7767 (delq nil
7768 (mapcar (lambda (x)
7769 (if (not (stringp (car x)))
7771 (if (string-match "\\W" (car x))
7773 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7774 list))
7775 (if add-auto-mode
7776 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7778 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7779 (defun org-file-remote-p (file)
7780 "Test whether FILE specifies a location on a remote system.
7781 Return non-nil if the location is indeed remote.
7783 For example, the filename \"/user@host:/foo\" specifies a location
7784 on the system \"/user@host:\"."
7785 (cond ((fboundp 'file-remote-p)
7786 (file-remote-p file))
7787 ((fboundp 'tramp-handle-file-remote-p)
7788 (tramp-handle-file-remote-p file))
7789 ((and (boundp 'ange-ftp-name-format)
7790 (string-match (car ange-ftp-name-format) file))
7792 (t nil)))
7795 ;;;; Refiling
7797 (defun org-get-org-file ()
7798 "Read a filename, with default directory `org-directory'."
7799 (let ((default (or org-default-notes-file remember-data-file)))
7800 (read-file-name (format "File name [%s]: " default)
7801 (file-name-as-directory org-directory)
7802 default)))
7804 (defun org-notes-order-reversed-p ()
7805 "Check if the current file should receive notes in reversed order."
7806 (cond
7807 ((not org-reverse-note-order) nil)
7808 ((eq t org-reverse-note-order) t)
7809 ((not (listp org-reverse-note-order)) nil)
7810 (t (catch 'exit
7811 (let ((all org-reverse-note-order)
7812 entry)
7813 (while (setq entry (pop all))
7814 (if (string-match (car entry) buffer-file-name)
7815 (throw 'exit (cdr entry))))
7816 nil)))))
7818 (defvar org-refile-target-table nil
7819 "The list of refile targets, created by `org-refile'.")
7821 (defvar org-agenda-new-buffers nil
7822 "Buffers created to visit agenda files.")
7824 (defun org-get-refile-targets (&optional default-buffer)
7825 "Produce a table with refile targets."
7826 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7827 targets txt re files f desc descre fast-path-p level)
7828 (message "Getting targets...")
7829 (with-current-buffer (or default-buffer (current-buffer))
7830 (while (setq entry (pop entries))
7831 (setq files (car entry) desc (cdr entry))
7832 (setq fast-path-p nil)
7833 (cond
7834 ((null files) (setq files (list (current-buffer))))
7835 ((eq files 'org-agenda-files)
7836 (setq files (org-agenda-files 'unrestricted)))
7837 ((and (symbolp files) (fboundp files))
7838 (setq files (funcall files)))
7839 ((and (symbolp files) (boundp files))
7840 (setq files (symbol-value files))))
7841 (if (stringp files) (setq files (list files)))
7842 (cond
7843 ((eq (car desc) :tag)
7844 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7845 ((eq (car desc) :todo)
7846 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7847 ((eq (car desc) :regexp)
7848 (setq descre (cdr desc)))
7849 ((eq (car desc) :level)
7850 (setq descre (concat "^\\*\\{" (number-to-string
7851 (if org-odd-levels-only
7852 (1- (* 2 (cdr desc)))
7853 (cdr desc)))
7854 "\\}[ \t]")))
7855 ((eq (car desc) :maxlevel)
7856 (setq fast-path-p t)
7857 (setq descre (concat "^\\*\\{1," (number-to-string
7858 (if org-odd-levels-only
7859 (1- (* 2 (cdr desc)))
7860 (cdr desc)))
7861 "\\}[ \t]")))
7862 (t (error "Bad refiling target description %s" desc)))
7863 (while (setq f (pop files))
7864 (save-excursion
7865 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7866 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7867 (setq f (expand-file-name f))
7868 (save-excursion
7869 (save-restriction
7870 (widen)
7871 (goto-char (point-min))
7872 (while (re-search-forward descre nil t)
7873 (goto-char (point-at-bol))
7874 (when (looking-at org-complex-heading-regexp)
7875 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7876 txt (org-link-display-format (match-string 4))
7877 re (concat "^" (regexp-quote
7878 (buffer-substring (match-beginning 1)
7879 (match-end 4)))))
7880 (if (match-end 5) (setq re (concat re "[ \t]+"
7881 (regexp-quote
7882 (match-string 5)))))
7883 (setq re (concat re "[ \t]*$"))
7884 (when org-refile-use-outline-path
7885 (setq txt (mapconcat 'org-protect-slash
7886 (append
7887 (if (eq org-refile-use-outline-path 'file)
7888 (list (file-name-nondirectory
7889 (buffer-file-name (buffer-base-buffer))))
7890 (if (eq org-refile-use-outline-path 'full-file-path)
7891 (list (buffer-file-name (buffer-base-buffer)))))
7892 (org-get-outline-path fast-path-p level txt)
7893 (list txt))
7894 "/")))
7895 (push (list txt f re (point)) targets))
7896 (goto-char (point-at-eol))))))))
7897 (message "Getting targets...done")
7898 (nreverse targets))))
7900 (defun org-protect-slash (s)
7901 (while (string-match "/" s)
7902 (setq s (replace-match "\\" t t s)))
7905 (defvar org-olpa (make-vector 20 nil))
7907 (defun org-get-outline-path (&optional fastp level heading)
7908 "Return the outline path to the current entry, as a list."
7909 (if fastp
7910 (progn
7911 (if (> level 19)
7912 (error "Outline path failure, more than 19 levels."))
7913 (loop for i from level upto 19 do
7914 (aset org-olpa i nil))
7915 (prog1
7916 (delq nil (append org-olpa nil))
7917 (aset org-olpa level heading)))
7918 (let (rtn)
7919 (save-excursion
7920 (while (org-up-heading-safe)
7921 (when (looking-at org-complex-heading-regexp)
7922 (push (org-match-string-no-properties 4) rtn)))
7923 rtn))))
7925 (defvar org-refile-history nil
7926 "History for refiling operations.")
7928 (defun org-refile (&optional goto default-buffer)
7929 "Move the entry at point to another heading.
7930 The list of target headings is compiled using the information in
7931 `org-refile-targets', which see. This list is created before each use
7932 and will therefore always be up-to-date.
7934 At the target location, the entry is filed as a subitem of the target heading.
7935 Depending on `org-reverse-note-order', the new subitem will either be the
7936 first or the last subitem.
7938 If there is an active region, all entries in that region will be moved.
7939 However, the region must fulfil the requirement that the first heading
7940 is the first one sets the top-level of the moved text - at most siblings
7941 below it are allowed.
7943 With prefix arg GOTO, the command will only visit the target location,
7944 not actually move anything.
7945 With a double prefix `C-u C-u', go to the location where the last refiling
7946 operation has put the subtree."
7947 (interactive "P")
7948 (let* ((cbuf (current-buffer))
7949 (regionp (org-region-active-p))
7950 (region-start (and regionp (region-beginning)))
7951 (region-end (and regionp (region-end)))
7952 (region-length (and regionp (- region-end region-start)))
7953 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7954 pos it nbuf file re level reversed)
7955 (when regionp (goto-char region-start)
7956 (unless (org-kill-is-subtree-p
7957 (buffer-substring region-start region-end))
7958 (error "The region is not a (sequence of) subtree(s)")))
7959 (if (equal goto '(16))
7960 (org-refile-goto-last-stored)
7961 (when (setq it (org-refile-get-location
7962 (if goto "Goto: " "Refile to: ") default-buffer))
7963 (setq file (nth 1 it)
7964 re (nth 2 it)
7965 pos (nth 3 it))
7966 (if (and (equal (buffer-file-name) file)
7967 (if regionp
7968 (and (>= pos region-start)
7969 (<= pos region-end))
7970 (and (>= pos (point))
7971 (< pos (save-excursion
7972 (org-end-of-subtree t t))))))
7973 (error "Cannot refile to position inside the tree or region"))
7975 (setq nbuf (or (find-buffer-visiting file)
7976 (find-file-noselect file)))
7977 (if goto
7978 (progn
7979 (switch-to-buffer nbuf)
7980 (goto-char pos)
7981 (org-show-context 'org-goto))
7982 (if regionp
7983 (progn
7984 (kill-new (buffer-substring region-start region-end))
7985 (org-save-markers-in-region region-start region-end))
7986 (org-copy-subtree 1 nil t))
7987 (save-excursion
7988 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7989 (find-file-noselect file))))
7990 (setq reversed (org-notes-order-reversed-p))
7991 (save-excursion
7992 (save-restriction
7993 (widen)
7994 (goto-char pos)
7995 (looking-at outline-regexp)
7996 (setq level (org-get-valid-level (funcall outline-level) 1))
7997 (goto-char
7998 (if reversed
7999 (or (outline-next-heading) (point-max))
8000 (or (save-excursion (outline-get-next-sibling))
8001 (org-end-of-subtree t t)
8002 (point-max))))
8003 (if (not (bolp)) (newline))
8004 (bookmark-set "org-refile-last-stored")
8005 (org-paste-subtree level))))
8006 (if regionp
8007 (delete-region (point) (+ (point) region-length))
8008 (org-cut-subtree))
8009 (setq org-markers-to-move nil)
8010 (message "Refiled to \"%s\"" (car it)))))))
8012 (defun org-refile-goto-last-stored ()
8013 "Go to the location where the last refile was stored."
8014 (interactive)
8015 (bookmark-jump "org-refile-last-stored")
8016 (message "This is the location of the last refile"))
8018 (defun org-refile-get-location (&optional prompt default-buffer)
8019 "Prompt the user for a refile location, using PROMPT."
8020 (let ((org-refile-targets org-refile-targets)
8021 (org-refile-use-outline-path org-refile-use-outline-path))
8022 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8023 (unless org-refile-target-table
8024 (error "No refile targets"))
8025 (let* ((cbuf (current-buffer))
8026 (partial-completion-mode nil)
8027 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8028 (cfunc (if (and org-refile-use-outline-path
8029 org-outline-path-complete-in-steps)
8030 'org-olpath-completing-read
8031 'org-ido-completing-read))
8032 (extra (if org-refile-use-outline-path "/" ""))
8033 (filename (and cfn (expand-file-name cfn)))
8034 (tbl (mapcar
8035 (lambda (x)
8036 (if (not (equal filename (nth 1 x)))
8037 (cons (concat (car x) extra " ("
8038 (file-name-nondirectory (nth 1 x)) ")")
8039 (cdr x))
8040 (cons (concat (car x) extra) (cdr x))))
8041 org-refile-target-table))
8042 (completion-ignore-case t))
8043 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8044 tbl)))
8046 (defun org-olpath-completing-read (prompt collection &rest args)
8047 "Read an outline path like a file name."
8048 (let ((thetable collection)
8049 (org-completion-use-ido nil)) ; does not work with ido.
8050 (apply
8051 'org-ido-completing-read prompt
8052 (lambda (string predicate &optional flag)
8053 (let (rtn r f (l (length string)))
8054 (cond
8055 ((eq flag nil)
8056 ;; try completion
8057 (try-completion string thetable))
8058 ((eq flag t)
8059 ;; all-completions
8060 (setq rtn (all-completions string thetable predicate))
8061 (mapcar
8062 (lambda (x)
8063 (setq r (substring x l))
8064 (if (string-match " ([^)]*)$" x)
8065 (setq f (match-string 0 x))
8066 (setq f ""))
8067 (if (string-match "/" r)
8068 (concat string (substring r 0 (match-end 0)) f)
8070 rtn))
8071 ((eq flag 'lambda)
8072 ;; exact match?
8073 (assoc string thetable)))
8075 args)))
8077 ;;;; Dynamic blocks
8079 (defun org-find-dblock (name)
8080 "Find the first dynamic block with name NAME in the buffer.
8081 If not found, stay at current position and return nil."
8082 (let (pos)
8083 (save-excursion
8084 (goto-char (point-min))
8085 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8086 nil t)
8087 (match-beginning 0))))
8088 (if pos (goto-char pos))
8089 pos))
8091 (defconst org-dblock-start-re
8092 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8093 "Matches the startline of a dynamic block, with parameters.")
8095 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8096 "Matches the end of a dynamic block.")
8098 (defun org-create-dblock (plist)
8099 "Create a dynamic block section, with parameters taken from PLIST.
8100 PLIST must contain a :name entry which is used as name of the block."
8101 (unless (bolp) (newline))
8102 (let ((name (plist-get plist :name)))
8103 (insert "#+BEGIN: " name)
8104 (while plist
8105 (if (eq (car plist) :name)
8106 (setq plist (cddr plist))
8107 (insert " " (prin1-to-string (pop plist)))))
8108 (insert "\n\n#+END:\n")
8109 (beginning-of-line -2)))
8111 (defun org-prepare-dblock ()
8112 "Prepare dynamic block for refresh.
8113 This empties the block, puts the cursor at the insert position and returns
8114 the property list including an extra property :name with the block name."
8115 (unless (looking-at org-dblock-start-re)
8116 (error "Not at a dynamic block"))
8117 (let* ((begdel (1+ (match-end 0)))
8118 (name (org-no-properties (match-string 1)))
8119 (params (append (list :name name)
8120 (read (concat "(" (match-string 3) ")")))))
8121 (unless (re-search-forward org-dblock-end-re nil t)
8122 (error "Dynamic block not terminated"))
8123 (setq params
8124 (append params
8125 (list :content (buffer-substring
8126 begdel (match-beginning 0)))))
8127 (delete-region begdel (match-beginning 0))
8128 (goto-char begdel)
8129 (open-line 1)
8130 params))
8132 (defun org-map-dblocks (&optional command)
8133 "Apply COMMAND to all dynamic blocks in the current buffer.
8134 If COMMAND is not given, use `org-update-dblock'."
8135 (let ((cmd (or command 'org-update-dblock))
8136 pos)
8137 (save-excursion
8138 (goto-char (point-min))
8139 (while (re-search-forward org-dblock-start-re nil t)
8140 (goto-char (setq pos (match-beginning 0)))
8141 (condition-case nil
8142 (funcall cmd)
8143 (error (message "Error during update of dynamic block")))
8144 (goto-char pos)
8145 (unless (re-search-forward org-dblock-end-re nil t)
8146 (error "Dynamic block not terminated"))))))
8148 (defun org-dblock-update (&optional arg)
8149 "User command for updating dynamic blocks.
8150 Update the dynamic block at point. With prefix ARG, update all dynamic
8151 blocks in the buffer."
8152 (interactive "P")
8153 (if arg
8154 (org-update-all-dblocks)
8155 (or (looking-at org-dblock-start-re)
8156 (org-beginning-of-dblock))
8157 (org-update-dblock)))
8159 (defun org-update-dblock ()
8160 "Update the dynamic block at point
8161 This means to empty the block, parse for parameters and then call
8162 the correct writing function."
8163 (save-window-excursion
8164 (let* ((pos (point))
8165 (line (org-current-line))
8166 (params (org-prepare-dblock))
8167 (name (plist-get params :name))
8168 (cmd (intern (concat "org-dblock-write:" name))))
8169 (message "Updating dynamic block `%s' at line %d..." name line)
8170 (funcall cmd params)
8171 (message "Updating dynamic block `%s' at line %d...done" name line)
8172 (goto-char pos))))
8174 (defun org-beginning-of-dblock ()
8175 "Find the beginning of the dynamic block at point.
8176 Error if there is no such block at point."
8177 (let ((pos (point))
8178 beg)
8179 (end-of-line 1)
8180 (if (and (re-search-backward org-dblock-start-re nil t)
8181 (setq beg (match-beginning 0))
8182 (re-search-forward org-dblock-end-re nil t)
8183 (> (match-end 0) pos))
8184 (goto-char beg)
8185 (goto-char pos)
8186 (error "Not in a dynamic block"))))
8188 (defun org-update-all-dblocks ()
8189 "Update all dynamic blocks in the buffer.
8190 This function can be used in a hook."
8191 (when (org-mode-p)
8192 (org-map-dblocks 'org-update-dblock)))
8195 ;;;; Completion
8197 (defconst org-additional-option-like-keywords
8198 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8199 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8200 "BEGIN_EXAMPLE" "END_EXAMPLE"
8201 "BEGIN_QUOTE" "END_QUOTE"
8202 "BEGIN_VERSE" "END_VERSE"
8203 "BEGIN_SRC" "END_SRC"
8204 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8206 (defcustom org-structure-template-alist
8208 ("s" "#+begin_src ?\n\n#+end_src"
8209 "<src lang=\"?\">\n\n</src>")
8210 ("e" "#+begin_example\n?\n#+end_example"
8211 "<example>\n?\n</example>")
8212 ("q" "#+begin_quote\n?\n#+end_quote"
8213 "<quote>\n?\n</quote>")
8214 ("v" "#+begin_verse\n?\n#+end_verse"
8215 "<verse>\n?\n/verse>")
8216 ("l" "#+begin_latex\n?\n#+end_latex"
8217 "<literal style=\"latex\">\n?\n</literal>")
8218 ("L" "#+latex: "
8219 "<literal style=\"latex\">?</literal>")
8220 ("h" "#+begin_html\n?\n#+end_html"
8221 "<literal style=\"html\">\n?\n</literal>")
8222 ("H" "#+html: "
8223 "<literal style=\"html\">?</literal>")
8224 ("a" "#+begin_ascii\n?\n#+end_ascii")
8225 ("A" "#+ascii: ")
8226 ("i" "#+include %file ?"
8227 "<include file=%file markup=\"?\">")
8229 "Structure completion elements.
8230 This is a list of abbreviation keys and values. The value gets inserted
8231 it you type @samp{.} followed by the key and then the completion key,
8232 usually `M-TAB'. %file will be replaced by a file name after prompting
8233 for the file using completion.
8234 There are two templates for each key, the first uses the original Org syntax,
8235 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8236 the default when the /org-mtags.el/ module has been loaded. See also the
8237 variable `org-mtags-prefer-muse-templates'.
8238 This is an experimental feature, it is undecided if it is going to stay in."
8239 :group 'org-completion
8240 :type '(repeat
8241 (string :tag "Key")
8242 (string :tag "Template")
8243 (string :tag "Muse Template")))
8245 (defun org-try-structure-completion ()
8246 "Try to complete a structure template before point.
8247 This looks for strings like \"<e\" on an otherwise empty line and
8248 expands them."
8249 (let ((l (buffer-substring (point-at-bol) (point)))
8251 (when (and (looking-at "[ \t]*$")
8252 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8253 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8254 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8255 (match-beginning 1)) a)
8256 t)))
8258 (defun org-complete-expand-structure-template (start cell)
8259 "Expand a structure template."
8260 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8261 (rpl (nth (if musep 2 1) cell)))
8262 (delete-region start (point))
8263 (when (string-match "\\`#\\+" rpl)
8264 (cond
8265 ((bolp))
8266 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8267 (delete-region (point-at-bol) (point)))
8268 (t (newline))))
8269 (setq start (point))
8270 (if (string-match "%file" rpl)
8271 (setq rpl (replace-match
8272 (concat
8273 "\""
8274 (save-match-data
8275 (abbreviate-file-name (read-file-name "Include file: ")))
8276 "\"")
8277 t t rpl)))
8278 (insert rpl)
8279 (if (re-search-backward "\\?" start t) (delete-char 1))))
8282 (defun org-complete (&optional arg)
8283 "Perform completion on word at point.
8284 At the beginning of a headline, this completes TODO keywords as given in
8285 `org-todo-keywords'.
8286 If the current word is preceded by a backslash, completes the TeX symbols
8287 that are supported for HTML support.
8288 If the current word is preceded by \"#+\", completes special words for
8289 setting file options.
8290 In the line after \"#+STARTUP:, complete valid keywords.\"
8291 At all other locations, this simply calls the value of
8292 `org-completion-fallback-command'."
8293 (interactive "P")
8294 (org-without-partial-completion
8295 (catch 'exit
8296 (let* ((a nil)
8297 (end (point))
8298 (beg1 (save-excursion
8299 (skip-chars-backward (org-re "[:alnum:]_@"))
8300 (point)))
8301 (beg (save-excursion
8302 (skip-chars-backward "a-zA-Z0-9_:$")
8303 (point)))
8304 (confirm (lambda (x) (stringp (car x))))
8305 (searchhead (equal (char-before beg) ?*))
8306 (struct
8307 (when (and (member (char-before beg1) '(?. ?<))
8308 (setq a (assoc (buffer-substring beg1 (point))
8309 org-structure-template-alist)))
8310 (org-complete-expand-structure-template (1- beg1) a)
8311 (throw 'exit t)))
8312 (tag (and (equal (char-before beg1) ?:)
8313 (equal (char-after (point-at-bol)) ?*)))
8314 (prop (and (equal (char-before beg1) ?:)
8315 (not (equal (char-after (point-at-bol)) ?*))))
8316 (texp (equal (char-before beg) ?\\))
8317 (link (equal (char-before beg) ?\[))
8318 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8319 beg)
8320 "#+"))
8321 (startup (string-match "^#\\+STARTUP:.*"
8322 (buffer-substring (point-at-bol) (point))))
8323 (completion-ignore-case opt)
8324 (type nil)
8325 (tbl nil)
8326 (table (cond
8327 (opt
8328 (setq type :opt)
8329 (require 'org-exp)
8330 (append
8331 (mapcar
8332 (lambda (x)
8333 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8334 (cons (match-string 2 x) (match-string 1 x)))
8335 (org-split-string (org-get-current-options) "\n"))
8336 (mapcar 'list org-additional-option-like-keywords)))
8337 (startup
8338 (setq type :startup)
8339 org-startup-options)
8340 (link (append org-link-abbrev-alist-local
8341 org-link-abbrev-alist))
8342 (texp
8343 (setq type :tex)
8344 org-html-entities)
8345 ((string-match "\\`\\*+[ \t]+\\'"
8346 (buffer-substring (point-at-bol) beg))
8347 (setq type :todo)
8348 (mapcar 'list org-todo-keywords-1))
8349 (searchhead
8350 (setq type :searchhead)
8351 (save-excursion
8352 (goto-char (point-min))
8353 (while (re-search-forward org-todo-line-regexp nil t)
8354 (push (list
8355 (org-make-org-heading-search-string
8356 (match-string 3) t))
8357 tbl)))
8358 tbl)
8359 (tag (setq type :tag beg beg1)
8360 (or org-tag-alist (org-get-buffer-tags)))
8361 (prop (setq type :prop beg beg1)
8362 (mapcar 'list (org-buffer-property-keys nil t t)))
8363 (t (progn
8364 (call-interactively org-completion-fallback-command)
8365 (throw 'exit nil)))))
8366 (pattern (buffer-substring-no-properties beg end))
8367 (completion (try-completion pattern table confirm)))
8368 (cond ((eq completion t)
8369 (if (not (assoc (upcase pattern) table))
8370 (message "Already complete")
8371 (if (and (equal type :opt)
8372 (not (member (car (assoc (upcase pattern) table))
8373 org-additional-option-like-keywords)))
8374 (insert (substring (cdr (assoc (upcase pattern) table))
8375 (length pattern)))
8376 (if (memq type '(:tag :prop)) (insert ":")))))
8377 ((null completion)
8378 (message "Can't find completion for \"%s\"" pattern)
8379 (ding))
8380 ((not (string= pattern completion))
8381 (delete-region beg end)
8382 (if (string-match " +$" completion)
8383 (setq completion (replace-match "" t t completion)))
8384 (insert completion)
8385 (if (get-buffer-window "*Completions*")
8386 (delete-window (get-buffer-window "*Completions*")))
8387 (if (assoc completion table)
8388 (if (eq type :todo) (insert " ")
8389 (if (memq type '(:tag :prop)) (insert ":"))))
8390 (if (and (equal type :opt) (assoc completion table))
8391 (message "%s" (substitute-command-keys
8392 "Press \\[org-complete] again to insert example settings"))))
8394 (message "Making completion list...")
8395 (let ((list (sort (all-completions pattern table confirm)
8396 'string<)))
8397 (with-output-to-temp-buffer "*Completions*"
8398 (condition-case nil
8399 ;; Protection needed for XEmacs and emacs 21
8400 (display-completion-list list pattern)
8401 (error (display-completion-list list)))))
8402 (message "Making completion list...%s" "done")))))))
8404 ;;;; TODO, DEADLINE, Comments
8406 (defun org-toggle-comment ()
8407 "Change the COMMENT state of an entry."
8408 (interactive)
8409 (save-excursion
8410 (org-back-to-heading)
8411 (let (case-fold-search)
8412 (if (looking-at (concat outline-regexp
8413 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8414 (replace-match "" t t nil 1)
8415 (if (looking-at outline-regexp)
8416 (progn
8417 (goto-char (match-end 0))
8418 (insert org-comment-string " ")))))))
8420 (defvar org-last-todo-state-is-todo nil
8421 "This is non-nil when the last TODO state change led to a TODO state.
8422 If the last change removed the TODO tag or switched to DONE, then
8423 this is nil.")
8425 (defvar org-setting-tags nil) ; dynamically skipped
8427 (defun org-parse-local-options (string var)
8428 "Parse STRING for startup setting relevant for variable VAR."
8429 (let ((rtn (symbol-value var))
8430 e opts)
8431 (save-match-data
8432 (if (or (not string) (not (string-match "\\S-" string)))
8434 (setq opts (delq nil (mapcar (lambda (x)
8435 (setq e (assoc x org-startup-options))
8436 (if (eq (nth 1 e) var) e nil))
8437 (org-split-string string "[ \t]+"))))
8438 (if (not opts)
8440 (setq rtn nil)
8441 (while (setq e (pop opts))
8442 (if (not (nth 3 e))
8443 (setq rtn (nth 2 e))
8444 (if (not (listp rtn)) (setq rtn nil))
8445 (push (nth 2 e) rtn)))
8446 rtn)))))
8448 (defvar org-todo-setup-filter-hook nil
8449 "Hook for functions that pre-filter todo specs.
8451 Each function takes a todo spec and returns either `nil' or the spec
8452 transformed into canonical form." )
8454 (defvar org-todo-get-default-hook nil
8455 "Hook for functions that get a default item for todo.
8457 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8458 `nil' or a string to be used for the todo mark." )
8460 (defvar org-agenda-headline-snapshot-before-repeat)
8461 (defun org-todo (&optional arg)
8462 "Change the TODO state of an item.
8463 The state of an item is given by a keyword at the start of the heading,
8464 like
8465 *** TODO Write paper
8466 *** DONE Call mom
8468 The different keywords are specified in the variable `org-todo-keywords'.
8469 By default the available states are \"TODO\" and \"DONE\".
8470 So for this example: when the item starts with TODO, it is changed to DONE.
8471 When it starts with DONE, the DONE is removed. And when neither TODO nor
8472 DONE are present, add TODO at the beginning of the heading.
8474 With C-u prefix arg, use completion to determine the new state.
8475 With numeric prefix arg, switch to that state.
8476 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8477 With a tripple C-u prefix, circumvent any state blocking.
8479 For calling through lisp, arg is also interpreted in the following way:
8480 'none -> empty state
8481 \"\"(empty string) -> switch to empty state
8482 'done -> switch to DONE
8483 'nextset -> switch to the next set of keywords
8484 'previousset -> switch to the previous set of keywords
8485 \"WAITING\" -> switch to the specified keyword, but only if it
8486 really is a member of `org-todo-keywords'."
8487 (interactive "P")
8488 (if (equal arg '(16)) (setq arg 'nextset))
8489 (let ((org-blocker-hook org-blocker-hook))
8490 (when (equal arg '(64))
8491 (setq arg nil org-blocker-hook nil))
8492 (save-excursion
8493 (catch 'exit
8494 (org-back-to-heading)
8495 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8496 (or (looking-at (concat " +" org-todo-regexp " *"))
8497 (looking-at " *"))
8498 (let* ((match-data (match-data))
8499 (startpos (point-at-bol))
8500 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8501 (org-log-done org-log-done)
8502 (org-log-repeat org-log-repeat)
8503 (org-todo-log-states org-todo-log-states)
8504 (this (match-string 1))
8505 (hl-pos (match-beginning 0))
8506 (head (org-get-todo-sequence-head this))
8507 (ass (assoc head org-todo-kwd-alist))
8508 (interpret (nth 1 ass))
8509 (done-word (nth 3 ass))
8510 (final-done-word (nth 4 ass))
8511 (last-state (or this ""))
8512 (completion-ignore-case t)
8513 (member (member this org-todo-keywords-1))
8514 (tail (cdr member))
8515 (state (cond
8516 ((and org-todo-key-trigger
8517 (or (and (equal arg '(4))
8518 (eq org-use-fast-todo-selection 'prefix))
8519 (and (not arg) org-use-fast-todo-selection
8520 (not (eq org-use-fast-todo-selection
8521 'prefix)))))
8522 ;; Use fast selection
8523 (org-fast-todo-selection))
8524 ((and (equal arg '(4))
8525 (or (not org-use-fast-todo-selection)
8526 (not org-todo-key-trigger)))
8527 ;; Read a state with completion
8528 (org-ido-completing-read
8529 "State: " (mapcar (lambda(x) (list x))
8530 org-todo-keywords-1)
8531 nil t))
8532 ((eq arg 'right)
8533 (if this
8534 (if tail (car tail) nil)
8535 (car org-todo-keywords-1)))
8536 ((eq arg 'left)
8537 (if (equal member org-todo-keywords-1)
8539 (if this
8540 (nth (- (length org-todo-keywords-1)
8541 (length tail) 2)
8542 org-todo-keywords-1)
8543 (org-last org-todo-keywords-1))))
8544 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8545 (setq arg nil))) ; hack to fall back to cycling
8546 (arg
8547 ;; user or caller requests a specific state
8548 (cond
8549 ((equal arg "") nil)
8550 ((eq arg 'none) nil)
8551 ((eq arg 'done) (or done-word (car org-done-keywords)))
8552 ((eq arg 'nextset)
8553 (or (car (cdr (member head org-todo-heads)))
8554 (car org-todo-heads)))
8555 ((eq arg 'previousset)
8556 (let ((org-todo-heads (reverse org-todo-heads)))
8557 (or (car (cdr (member head org-todo-heads)))
8558 (car org-todo-heads))))
8559 ((car (member arg org-todo-keywords-1)))
8560 ((nth (1- (prefix-numeric-value arg))
8561 org-todo-keywords-1))))
8562 ((null member) (or head (car org-todo-keywords-1)))
8563 ((equal this final-done-word) nil) ;; -> make empty
8564 ((null tail) nil) ;; -> first entry
8565 ((memq interpret '(type priority))
8566 (if (eq this-command last-command)
8567 (car tail)
8568 (if (> (length tail) 0)
8569 (or done-word (car org-done-keywords))
8570 nil)))
8572 (car tail))))
8573 (state (or
8574 (run-hook-with-args-until-success
8575 'org-todo-get-default-hook state last-state)
8576 state))
8577 (next (if state (concat " " state " ") " "))
8578 (change-plist (list :type 'todo-state-change :from this :to state
8579 :position startpos))
8580 dolog now-done-p)
8581 (when org-blocker-hook
8582 (setq org-last-todo-state-is-todo
8583 (not (member this org-done-keywords)))
8584 (unless (save-excursion
8585 (save-match-data
8586 (run-hook-with-args-until-failure
8587 'org-blocker-hook change-plist)))
8588 (if (interactive-p)
8589 (error "TODO state change from %s to %s blocked" this state)
8590 ;; fail silently
8591 (message "TODO state change from %s to %s blocked" this state)
8592 (throw 'exit nil))))
8593 (store-match-data match-data)
8594 (replace-match next t t)
8595 (unless (pos-visible-in-window-p hl-pos)
8596 (message "TODO state changed to %s" (org-trim next)))
8597 (unless head
8598 (setq head (org-get-todo-sequence-head state)
8599 ass (assoc head org-todo-kwd-alist)
8600 interpret (nth 1 ass)
8601 done-word (nth 3 ass)
8602 final-done-word (nth 4 ass)))
8603 (when (memq arg '(nextset previousset))
8604 (message "Keyword-Set %d/%d: %s"
8605 (- (length org-todo-sets) -1
8606 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8607 (length org-todo-sets)
8608 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8609 (setq org-last-todo-state-is-todo
8610 (not (member state org-done-keywords)))
8611 (setq now-done-p (and (member state org-done-keywords)
8612 (not (member this org-done-keywords))))
8613 (and logging (org-local-logging logging))
8614 (when (and (or org-todo-log-states org-log-done)
8615 (not (memq arg '(nextset previousset))))
8616 ;; we need to look at recording a time and note
8617 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8618 (nth 2 (assoc this org-todo-log-states))))
8619 (when (and state
8620 (member state org-not-done-keywords)
8621 (not (member this org-not-done-keywords)))
8622 ;; This is now a todo state and was not one before
8623 ;; If there was a CLOSED time stamp, get rid of it.
8624 (org-add-planning-info nil nil 'closed))
8625 (when (and now-done-p org-log-done)
8626 ;; It is now done, and it was not done before
8627 (org-add-planning-info 'closed (org-current-time))
8628 (if (and (not dolog) (eq 'note org-log-done))
8629 (org-add-log-setup 'done state this 'findpos 'note)))
8630 (when (and state dolog)
8631 ;; This is a non-nil state, and we need to log it
8632 (org-add-log-setup 'state state this 'findpos dolog)))
8633 ;; Fixup tag positioning
8634 (org-todo-trigger-tag-changes state)
8635 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8636 (when org-provide-todo-statistics
8637 (org-update-parent-todo-statistics))
8638 (run-hooks 'org-after-todo-state-change-hook)
8639 (if (and arg (not (member state org-done-keywords)))
8640 (setq head (org-get-todo-sequence-head state)))
8641 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8642 ;; Do we need to trigger a repeat?
8643 (when now-done-p
8644 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8645 ;; This is for the agenda, take a snapshot of the headline.
8646 (save-match-data
8647 (setq org-agenda-headline-snapshot-before-repeat
8648 (org-get-heading))))
8649 (org-auto-repeat-maybe state))
8650 ;; Fixup cursor location if close to the keyword
8651 (if (and (outline-on-heading-p)
8652 (not (bolp))
8653 (save-excursion (beginning-of-line 1)
8654 (looking-at org-todo-line-regexp))
8655 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8656 (progn
8657 (goto-char (or (match-end 2) (match-end 1)))
8658 (just-one-space)))
8659 (when org-trigger-hook
8660 (save-excursion
8661 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8663 (defun org-block-todo-from-children-or-siblings (change-plist)
8664 "Block turning an entry into a TODO, using the hierarchy.
8665 This checks whether the current task should be blocked from state
8666 changes. Such blocking occurs when:
8668 1. The task has children which are not all in a completed state.
8670 2. A task has a parent with the property :ORDERED:, and there
8671 are siblings prior to the current task with incomplete
8672 status."
8673 (catch 'dont-block
8674 ;; If this is not a todo state change, or if this entry is already DONE,
8675 ;; do not block
8676 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8677 (member (plist-get change-plist :from)
8678 (cons 'done org-done-keywords))
8679 (member (plist-get change-plist :to)
8680 (cons 'todo org-not-done-keywords)))
8681 (throw 'dont-block t))
8682 ;; If this task has children, and any are undone, it's blocked
8683 (save-excursion
8684 (org-back-to-heading t)
8685 (let ((this-level (funcall outline-level)))
8686 (outline-next-heading)
8687 (let ((child-level (funcall outline-level)))
8688 (while (and (not (eobp))
8689 (> child-level this-level))
8690 ;; this todo has children, check whether they are all
8691 ;; completed
8692 (if (and (not (org-entry-is-done-p))
8693 (org-entry-is-todo-p))
8694 (throw 'dont-block nil))
8695 (outline-next-heading)
8696 (setq child-level (funcall outline-level))))))
8697 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8698 ;; any previous siblings are undone, it's blocked
8699 (save-excursion
8700 (org-back-to-heading t)
8701 (when (save-excursion
8702 (ignore-errors
8703 (org-up-heading-all 1)
8704 (org-entry-get (point) "ORDERED")))
8705 (let* ((this-level (funcall outline-level))
8706 (current-level this-level))
8707 (while (and (not (bobp))
8708 (= current-level this-level))
8709 (outline-previous-heading)
8710 (setq current-level (funcall outline-level))
8711 (if (= current-level this-level)
8712 ;; this todo has children, check whether they are all
8713 ;; completed
8714 (if (and (not (org-entry-is-done-p))
8715 (org-entry-is-todo-p))
8716 (throw 'dont-block nil)))))))
8717 t)) ; don't block
8719 (defcustom org-track-ordered-property-with-tag nil
8720 "Should the ORDERED property also be shown as a tag?
8721 The ORDERED property decides if an entry should require subtasks to be
8722 completed in sequence. Since a property is not very visible, setting
8723 this option means that toggling the ORDERED property with the command
8724 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
8725 not relevant for the behavior, but it makes things more visible.
8727 Note that toggling the tag with tags commands will not change the property
8728 and therefore not influence behavior!
8730 This can be t, meaning the tag ORDERED should be used, It can also be a
8731 string to select a different tag for this task."
8732 :group 'org-todo
8733 :type '(choice
8734 (const :tag "No tracking" nil)
8735 (const :tag "Track with ORDERED tag" t)
8736 (string :tag "Use other tag")))
8738 (defun org-toggle-ordered-property ()
8739 "Toggle the ORDERED property of the current entry.
8740 For better visibility, you can track the value of this property with a tag.
8741 See variable `org-track-ordered-property-with-tag'."
8742 (interactive)
8743 (let* ((t1 org-track-ordered-property-with-tag)
8744 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
8745 (save-excursion
8746 (org-back-to-heading)
8747 (if (org-entry-get nil "ORDERED")
8748 (progn
8749 (org-delete-property "ORDERED")
8750 (and tag (org-toggle-tag tag 'off))
8751 (message "Subtasks can be completed in arbitrary order"))
8752 (org-entry-put nil "ORDERED" "t")
8753 (and tag (org-toggle-tag tag 'on))
8754 (message "Subtasks must be completed in sequence")))))
8756 (defvar org-blocked-by-checkboxes) ; dynamically scoped
8757 (defun org-block-todo-from-checkboxes (change-plist)
8758 "Block turning an entry into a TODO, using checkboxes.
8759 This checks whether the current task should be blocked from state
8760 changes because there are uncheckd boxes in this entry."
8761 (catch 'dont-block
8762 ;; If this is not a todo state change, or if this entry is already DONE,
8763 ;; do not block
8764 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8765 (member (plist-get change-plist :from)
8766 (cons 'done org-done-keywords))
8767 (member (plist-get change-plist :to)
8768 (cons 'todo org-not-done-keywords)))
8769 (throw 'dont-block t))
8770 ;; If this task has checkboxes that are not checked, it's blocked
8771 (save-excursion
8772 (org-back-to-heading t)
8773 (let ((beg (point)) end)
8774 (outline-next-heading)
8775 (setq end (point))
8776 (goto-char beg)
8777 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8778 end t)
8779 (progn
8780 (if (boundp 'org-blocked-by-checkboxes)
8781 (setq org-blocked-by-checkboxes t))
8782 (throw 'dont-block nil)))))
8783 t)) ; do not block
8785 (defun org-update-parent-todo-statistics ()
8786 "Update any statistics cookie in the parent of the current headline."
8787 (interactive)
8788 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8789 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
8790 (catch 'exit
8791 (save-excursion
8792 (setq level (org-up-heading-safe))
8793 (unless level
8794 (throw 'exit nil))
8795 (while (re-search-forward box-re (point-at-eol) t)
8796 (setq cnt-all 0 cnt-done 0 cookie-present t)
8797 (setq is-percent (match-end 2))
8798 (save-match-data
8799 (unless (outline-next-heading) (throw 'exit nil))
8800 (while (looking-at org-todo-line-regexp)
8801 (setq kwd (match-string 2))
8802 (and kwd (setq cnt-all (1+ cnt-all)))
8803 (and (member kwd org-done-keywords)
8804 (setq cnt-done (1+ cnt-done)))
8805 (condition-case nil
8806 (org-forward-same-level 1)
8807 (error (end-of-line 1)))))
8808 (replace-match
8809 (if is-percent
8810 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8811 (format "[%d/%d]" cnt-done cnt-all))))
8812 (when cookie-present
8813 (run-hook-with-args 'org-after-todo-statistics-hook
8814 cnt-done (- cnt-all cnt-done)))))))
8816 (defvar org-after-todo-statistics-hook nil
8817 "Hook that is called after a TODO statistics cookie has been updated.
8818 Each function is called with two arguments: the number of not-done entries
8819 and the number of done entries.
8821 For example, the following function, when added to this hook, will switch
8822 an entry to DONE when all children are done, and back to TODO when new
8823 entries are set to a TODO status. Note that this hook is only called
8824 when there is a statistics cookie in the headline!
8826 (defun org-summary-todo (n-done n-not-done)
8827 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8828 (let (org-log-done org-log-states) ; turn off logging
8829 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8832 (defun org-todo-trigger-tag-changes (state)
8833 "Apply the changes defined in `org-todo-state-tags-triggers'."
8834 (let ((l org-todo-state-tags-triggers)
8835 changes)
8836 (when (or (not state) (equal state ""))
8837 (setq changes (append changes (cdr (assoc "" l)))))
8838 (when (and (stringp state) (> (length state) 0))
8839 (setq changes (append changes (cdr (assoc state l)))))
8840 (when (member state org-not-done-keywords)
8841 (setq changes (append changes (cdr (assoc 'todo l)))))
8842 (when (member state org-done-keywords)
8843 (setq changes (append changes (cdr (assoc 'done l)))))
8844 (dolist (c changes)
8845 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8847 (defun org-local-logging (value)
8848 "Get logging settings from a property VALUE."
8849 (let* (words w a)
8850 ;; directly set the variables, they are already local.
8851 (setq org-log-done nil
8852 org-log-repeat nil
8853 org-todo-log-states nil)
8854 (setq words (org-split-string value))
8855 (while (setq w (pop words))
8856 (cond
8857 ((setq a (assoc w org-startup-options))
8858 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8859 (set (nth 1 a) (nth 2 a))))
8860 ((setq a (org-extract-log-state-settings w))
8861 (and (member (car a) org-todo-keywords-1)
8862 (push a org-todo-log-states)))))))
8864 (defun org-get-todo-sequence-head (kwd)
8865 "Return the head of the TODO sequence to which KWD belongs.
8866 If KWD is not set, check if there is a text property remembering the
8867 right sequence."
8868 (let (p)
8869 (cond
8870 ((not kwd)
8871 (or (get-text-property (point-at-bol) 'org-todo-head)
8872 (progn
8873 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8874 nil (point-at-eol)))
8875 (get-text-property p 'org-todo-head))))
8876 ((not (member kwd org-todo-keywords-1))
8877 (car org-todo-keywords-1))
8878 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8880 (defun org-fast-todo-selection ()
8881 "Fast TODO keyword selection with single keys.
8882 Returns the new TODO keyword, or nil if no state change should occur."
8883 (let* ((fulltable org-todo-key-alist)
8884 (done-keywords org-done-keywords) ;; needed for the faces.
8885 (maxlen (apply 'max (mapcar
8886 (lambda (x)
8887 (if (stringp (car x)) (string-width (car x)) 0))
8888 fulltable)))
8889 (expert nil)
8890 (fwidth (+ maxlen 3 1 3))
8891 (ncol (/ (- (window-width) 4) fwidth))
8892 tg cnt e c tbl
8893 groups ingroup)
8894 (save-excursion
8895 (save-window-excursion
8896 (if expert
8897 (set-buffer (get-buffer-create " *Org todo*"))
8898 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8899 (erase-buffer)
8900 (org-set-local 'org-done-keywords done-keywords)
8901 (setq tbl fulltable cnt 0)
8902 (while (setq e (pop tbl))
8903 (cond
8904 ((equal e '(:startgroup))
8905 (push '() groups) (setq ingroup t)
8906 (when (not (= cnt 0))
8907 (setq cnt 0)
8908 (insert "\n"))
8909 (insert "{ "))
8910 ((equal e '(:endgroup))
8911 (setq ingroup nil cnt 0)
8912 (insert "}\n"))
8913 ((equal e '(:newline))
8914 (insert "\n "))
8916 (setq tg (car e) c (cdr e))
8917 (if ingroup (push tg (car groups)))
8918 (setq tg (org-add-props tg nil 'face
8919 (org-get-todo-face tg)))
8920 (if (and (= cnt 0) (not ingroup)) (insert " "))
8921 (insert "[" c "] " tg (make-string
8922 (- fwidth 4 (length tg)) ?\ ))
8923 (when (= (setq cnt (1+ cnt)) ncol)
8924 (insert "\n")
8925 (if ingroup (insert " "))
8926 (setq cnt 0)))))
8927 (insert "\n")
8928 (goto-char (point-min))
8929 (if (not expert) (org-fit-window-to-buffer))
8930 (message "[a-z..]:Set [SPC]:clear")
8931 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8932 (cond
8933 ((or (= c ?\C-g)
8934 (and (= c ?q) (not (rassoc c fulltable))))
8935 (setq quit-flag t))
8936 ((= c ?\ ) nil)
8937 ((setq e (rassoc c fulltable) tg (car e))
8939 (t (setq quit-flag t)))))))
8941 (defun org-entry-is-todo-p ()
8942 (member (org-get-todo-state) org-not-done-keywords))
8944 (defun org-entry-is-done-p ()
8945 (member (org-get-todo-state) org-done-keywords))
8947 (defun org-get-todo-state ()
8948 (save-excursion
8949 (org-back-to-heading t)
8950 (and (looking-at org-todo-line-regexp)
8951 (match-end 2)
8952 (match-string 2))))
8954 (defun org-at-date-range-p (&optional inactive-ok)
8955 "Is the cursor inside a date range?"
8956 (interactive)
8957 (save-excursion
8958 (catch 'exit
8959 (let ((pos (point)))
8960 (skip-chars-backward "^[<\r\n")
8961 (skip-chars-backward "<[")
8962 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8963 (>= (match-end 0) pos)
8964 (throw 'exit t))
8965 (skip-chars-backward "^<[\r\n")
8966 (skip-chars-backward "<[")
8967 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8968 (>= (match-end 0) pos)
8969 (throw 'exit t)))
8970 nil)))
8972 (defun org-get-repeat ()
8973 "Check if there is a deadline/schedule with repeater in this entry."
8974 (save-match-data
8975 (save-excursion
8976 (org-back-to-heading t)
8977 (if (re-search-forward
8978 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8979 (match-string 1)))))
8981 (defvar org-last-changed-timestamp)
8982 (defvar org-last-inserted-timestamp)
8983 (defvar org-log-post-message)
8984 (defvar org-log-note-purpose)
8985 (defvar org-log-note-how)
8986 (defvar org-log-note-extra)
8987 (defun org-auto-repeat-maybe (done-word)
8988 "Check if the current headline contains a repeated deadline/schedule.
8989 If yes, set TODO state back to what it was and change the base date
8990 of repeating deadline/scheduled time stamps to new date.
8991 This function is run automatically after each state change to a DONE state."
8992 ;; last-state is dynamically scoped into this function
8993 (let* ((repeat (org-get-repeat))
8994 (aa (assoc last-state org-todo-kwd-alist))
8995 (interpret (nth 1 aa))
8996 (head (nth 2 aa))
8997 (whata '(("d" . day) ("m" . month) ("y" . year)))
8998 (msg "Entry repeats: ")
8999 (org-log-done nil)
9000 (org-todo-log-states nil)
9001 (nshiftmax 10) (nshift 0)
9002 re type n what ts time)
9003 (when repeat
9004 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9005 (org-todo (if (eq interpret 'type) last-state head))
9006 (when org-log-repeat
9007 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9008 (memq 'org-add-log-note post-command-hook))
9009 ;; OK, we are already setup for some record
9010 (if (eq org-log-repeat 'note)
9011 ;; make sure we take a note, not only a time stamp
9012 (setq org-log-note-how 'note))
9013 ;; Set up for taking a record
9014 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9015 last-state
9016 'findpos org-log-repeat)))
9017 (org-back-to-heading t)
9018 (org-add-planning-info nil nil 'closed)
9019 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9020 org-deadline-time-regexp "\\)\\|\\("
9021 org-ts-regexp "\\)"))
9022 (while (re-search-forward
9023 re (save-excursion (outline-next-heading) (point)) t)
9024 (setq type (if (match-end 1) org-scheduled-string
9025 (if (match-end 3) org-deadline-string "Plain:"))
9026 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9027 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9028 (setq n (string-to-number (match-string 2 ts))
9029 what (match-string 3 ts))
9030 (if (equal what "w") (setq n (* n 7) what "d"))
9031 ;; Preparation, see if we need to modify the start date for the change
9032 (when (match-end 1)
9033 (setq time (save-match-data (org-time-string-to-time ts)))
9034 (cond
9035 ((equal (match-string 1 ts) ".")
9036 ;; Shift starting date to today
9037 (org-timestamp-change
9038 (- (time-to-days (current-time)) (time-to-days time))
9039 'day))
9040 ((equal (match-string 1 ts) "+")
9041 (while (or (= nshift 0)
9042 (<= (time-to-days time) (time-to-days (current-time))))
9043 (when (= (incf nshift) nshiftmax)
9044 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9045 (error "Abort")))
9046 (org-timestamp-change n (cdr (assoc what whata)))
9047 (org-at-timestamp-p t)
9048 (setq ts (match-string 1))
9049 (setq time (save-match-data (org-time-string-to-time ts))))
9050 (org-timestamp-change (- n) (cdr (assoc what whata)))
9051 ;; rematch, so that we have everything in place for the real shift
9052 (org-at-timestamp-p t)
9053 (setq ts (match-string 1))
9054 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9055 (org-timestamp-change n (cdr (assoc what whata)))
9056 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9057 (setq org-log-post-message msg)
9058 (message "%s" msg))))
9060 (defun org-show-todo-tree (arg)
9061 "Make a compact tree which shows all headlines marked with TODO.
9062 The tree will show the lines where the regexp matches, and all higher
9063 headlines above the match.
9064 With a \\[universal-argument] prefix, also show the DONE entries.
9065 With a numeric prefix N, construct a sparse tree for the Nth element
9066 of `org-todo-keywords-1'."
9067 (interactive "P")
9068 (let ((case-fold-search nil)
9069 (kwd-re
9070 (cond ((null arg) org-not-done-regexp)
9071 ((equal arg '(4))
9072 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9073 (mapcar 'list org-todo-keywords-1))))
9074 (concat "\\("
9075 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9076 "\\)\\>")))
9077 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9078 (regexp-quote (nth (1- (prefix-numeric-value arg))
9079 org-todo-keywords-1)))
9080 (t (error "Invalid prefix argument: %s" arg)))))
9081 (message "%d TODO entries found"
9082 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9084 (defun org-deadline (&optional remove time)
9085 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9086 With argument REMOVE, remove any deadline from the item.
9087 When TIME is set, it should be an internal time specification, and the
9088 scheduling will use the corresponding date."
9089 (interactive "P")
9090 (if remove
9091 (progn
9092 (org-remove-timestamp-with-keyword org-deadline-string)
9093 (message "Item no longer has a deadline."))
9094 (if (org-get-repeat)
9095 (error "Cannot change deadline on task with repeater, please do that by hand")
9096 (org-add-planning-info 'deadline time 'closed)
9097 (message "Deadline on %s" org-last-inserted-timestamp))))
9099 (defun org-schedule (&optional remove time)
9100 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9101 With argument REMOVE, remove any scheduling date from the item.
9102 When TIME is set, it should be an internal time specification, and the
9103 scheduling will use the corresponding date."
9104 (interactive "P")
9105 (if remove
9106 (progn
9107 (org-remove-timestamp-with-keyword org-scheduled-string)
9108 (message "Item is no longer scheduled."))
9109 (if (org-get-repeat)
9110 (error "Cannot reschedule task with repeater, please do that by hand")
9111 (org-add-planning-info 'scheduled time 'closed)
9112 (message "Scheduled to %s" org-last-inserted-timestamp))))
9114 (defun org-get-scheduled-time (pom &optional inherit)
9115 "Get the scheduled time as a time tuple, of a format suitable
9116 for calling org-schedule with, or if there is no scheduling,
9117 returns nil."
9118 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9119 (when time
9120 (apply 'encode-time (org-parse-time-string time)))))
9122 (defun org-get-deadline-time (pom &optional inherit)
9123 "Get the deadine as a time tuple, of a format suitable for
9124 calling org-deadlin with, or if there is no scheduling, returns
9125 nil."
9126 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9127 (when time
9128 (apply 'encode-time (org-parse-time-string time)))))
9130 (defun org-remove-timestamp-with-keyword (keyword)
9131 "Remove all time stamps with KEYWORD in the current entry."
9132 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9133 beg)
9134 (save-excursion
9135 (org-back-to-heading t)
9136 (setq beg (point))
9137 (org-end-of-subtree t t)
9138 (while (re-search-backward re beg t)
9139 (replace-match "")
9140 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9141 (equal (char-before) ?\ ))
9142 (backward-delete-char 1)
9143 (if (string-match "^[ \t]*$" (buffer-substring
9144 (point-at-bol) (point-at-eol)))
9145 (delete-region (point-at-bol)
9146 (min (point-max) (1+ (point-at-eol))))))))))
9148 (defun org-add-planning-info (what &optional time &rest remove)
9149 "Insert new timestamp with keyword in the line directly after the headline.
9150 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9151 If non is given, the user is prompted for a date.
9152 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9153 be removed."
9154 (interactive)
9155 (let (org-time-was-given org-end-time-was-given ts
9156 end default-time default-input)
9158 (when (and (not time) (memq what '(scheduled deadline)))
9159 ;; Try to get a default date/time from existing timestamp
9160 (save-excursion
9161 (org-back-to-heading t)
9162 (setq end (save-excursion (outline-next-heading) (point)))
9163 (when (re-search-forward (if (eq what 'scheduled)
9164 org-scheduled-time-regexp
9165 org-deadline-time-regexp)
9166 end t)
9167 (setq ts (match-string 1)
9168 default-time
9169 (apply 'encode-time (org-parse-time-string ts))
9170 default-input (and ts (org-get-compact-tod ts))))))
9171 (when what
9172 ;; If necessary, get the time from the user
9173 (setq time (or time (org-read-date nil 'to-time nil nil
9174 default-time default-input))))
9176 (when (and org-insert-labeled-timestamps-at-point
9177 (member what '(scheduled deadline)))
9178 (insert
9179 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9180 (org-insert-time-stamp time org-time-was-given
9181 nil nil nil (list org-end-time-was-given))
9182 (setq what nil))
9183 (save-excursion
9184 (save-restriction
9185 (let (col list elt ts buffer-invisibility-spec)
9186 (org-back-to-heading t)
9187 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9188 (goto-char (match-end 1))
9189 (setq col (current-column))
9190 (goto-char (match-end 0))
9191 (if (eobp) (insert "\n") (forward-char 1))
9192 (if (and (not (looking-at outline-regexp))
9193 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9194 "[^\r\n]*"))
9195 (not (equal (match-string 1) org-clock-string)))
9196 (narrow-to-region (match-beginning 0) (match-end 0))
9197 (insert-before-markers "\n")
9198 (backward-char 1)
9199 (narrow-to-region (point) (point))
9200 (and org-adapt-indentation (org-indent-to-column col)))
9201 ;; Check if we have to remove something.
9202 (setq list (cons what remove))
9203 (while list
9204 (setq elt (pop list))
9205 (goto-char (point-min))
9206 (when (or (and (eq elt 'scheduled)
9207 (re-search-forward org-scheduled-time-regexp nil t))
9208 (and (eq elt 'deadline)
9209 (re-search-forward org-deadline-time-regexp nil t))
9210 (and (eq elt 'closed)
9211 (re-search-forward org-closed-time-regexp nil t)))
9212 (replace-match "")
9213 (if (looking-at "--+<[^>]+>") (replace-match ""))
9214 (if (looking-at " +") (replace-match ""))))
9215 (goto-char (point-max))
9216 (when what
9217 (insert
9218 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9219 (cond ((eq what 'scheduled) org-scheduled-string)
9220 ((eq what 'deadline) org-deadline-string)
9221 ((eq what 'closed) org-closed-string))
9222 " ")
9223 (setq ts (org-insert-time-stamp
9224 time
9225 (or org-time-was-given
9226 (and (eq what 'closed) org-log-done-with-time))
9227 (eq what 'closed)
9228 nil nil (list org-end-time-was-given)))
9229 (end-of-line 1))
9230 (goto-char (point-min))
9231 (widen)
9232 (if (and (looking-at "[ \t]+\n")
9233 (equal (char-before) ?\n))
9234 (delete-region (1- (point)) (point-at-eol)))
9235 ts)))))
9237 (defvar org-log-note-marker (make-marker))
9238 (defvar org-log-note-purpose nil)
9239 (defvar org-log-note-state nil)
9240 (defvar org-log-note-previous-state nil)
9241 (defvar org-log-note-how nil)
9242 (defvar org-log-note-extra nil)
9243 (defvar org-log-note-window-configuration nil)
9244 (defvar org-log-note-return-to (make-marker))
9245 (defvar org-log-post-message nil
9246 "Message to be displayed after a log note has been stored.
9247 The auto-repeater uses this.")
9249 (defun org-add-note ()
9250 "Add a note to the current entry.
9251 This is done in the same way as adding a state change note."
9252 (interactive)
9253 (org-add-log-setup 'note nil nil 'findpos nil))
9255 (defvar org-property-end-re)
9256 (defun org-add-log-setup (&optional purpose state prev-state
9257 findpos how &optional extra)
9258 "Set up the post command hook to take a note.
9259 If this is about to TODO state change, the new state is expected in STATE.
9260 When FINDPOS is non-nil, find the correct position for the note in
9261 the current entry. If not, assume that it can be inserted at point.
9262 HOW is an indicator what kind of note should be created.
9263 EXTRA is additional text that will be inserted into the notes buffer."
9264 (let ((drawer (cond ((stringp org-log-into-drawer)
9265 org-log-into-drawer)
9266 (org-log-into-drawer "LOGBOOK")
9267 (t nil))))
9268 (save-restriction
9269 (save-excursion
9270 (when findpos
9271 (org-back-to-heading t)
9272 (narrow-to-region (point) (save-excursion
9273 (outline-next-heading) (point)))
9274 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9275 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9276 "[^\r\n]*\\)?"))
9277 (goto-char (match-end 0))
9278 (cond
9279 (drawer
9280 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9281 nil t)
9282 (progn
9283 (goto-char (match-end 0))
9284 (or org-log-states-order-reversed
9285 (and (re-search-forward org-property-end-re nil t)
9286 (goto-char (1- (match-beginning 0))))))
9287 (insert "\n:" drawer ":\n:END:")
9288 (beginning-of-line 0)
9289 (org-indent-line-function)
9290 (beginning-of-line 2)
9291 (org-indent-line-function)
9292 (end-of-line 0)))
9293 ((and org-log-state-notes-insert-after-drawers
9294 (save-excursion
9295 (forward-line) (looking-at org-drawer-regexp)))
9296 (forward-line)
9297 (while (looking-at org-drawer-regexp)
9298 (goto-char (match-end 0))
9299 (re-search-forward org-property-end-re (point-max) t)
9300 (forward-line))
9301 (forward-line -1)))
9302 (unless org-log-states-order-reversed
9303 (and (= (char-after) ?\n) (forward-char 1))
9304 (org-skip-over-state-notes)
9305 (skip-chars-backward " \t\n\r")))
9306 (move-marker org-log-note-marker (point))
9307 (setq org-log-note-purpose purpose
9308 org-log-note-state state
9309 org-log-note-previous-state prev-state
9310 org-log-note-how how
9311 org-log-note-extra extra)
9312 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9314 (defun org-skip-over-state-notes ()
9315 "Skip past the list of State notes in an entry."
9316 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9317 (while (looking-at "[ \t]*- State")
9318 (condition-case nil
9319 (org-next-item)
9320 (error (org-end-of-item)))))
9322 (defun org-add-log-note (&optional purpose)
9323 "Pop up a window for taking a note, and add this note later at point."
9324 (remove-hook 'post-command-hook 'org-add-log-note)
9325 (setq org-log-note-window-configuration (current-window-configuration))
9326 (delete-other-windows)
9327 (move-marker org-log-note-return-to (point))
9328 (switch-to-buffer (marker-buffer org-log-note-marker))
9329 (goto-char org-log-note-marker)
9330 (org-switch-to-buffer-other-window "*Org Note*")
9331 (erase-buffer)
9332 (if (memq org-log-note-how '(time state))
9333 (let (current-prefix-arg) (org-store-log-note))
9334 (let ((org-inhibit-startup t)) (org-mode))
9335 (insert (format "# Insert note for %s.
9336 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9337 (cond
9338 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9339 ((eq org-log-note-purpose 'done) "closed todo item")
9340 ((eq org-log-note-purpose 'state)
9341 (format "state change from \"%s\" to \"%s\""
9342 (or org-log-note-previous-state "")
9343 (or org-log-note-state "")))
9344 ((eq org-log-note-purpose 'note)
9345 "this entry")
9346 (t (error "This should not happen")))))
9347 (if org-log-note-extra (insert org-log-note-extra))
9348 (org-set-local 'org-finish-function 'org-store-log-note)))
9350 (defvar org-note-abort nil) ; dynamically scoped
9351 (defun org-store-log-note ()
9352 "Finish taking a log note, and insert it to where it belongs."
9353 (let ((txt (buffer-string))
9354 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9355 lines ind)
9356 (kill-buffer (current-buffer))
9357 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9358 (setq txt (replace-match "" t t txt)))
9359 (if (string-match "\\s-+\\'" txt)
9360 (setq txt (replace-match "" t t txt)))
9361 (setq lines (org-split-string txt "\n"))
9362 (when (and note (string-match "\\S-" note))
9363 (setq note
9364 (org-replace-escapes
9365 note
9366 (list (cons "%u" (user-login-name))
9367 (cons "%U" user-full-name)
9368 (cons "%t" (format-time-string
9369 (org-time-stamp-format 'long 'inactive)
9370 (current-time)))
9371 (cons "%s" (if org-log-note-state
9372 (concat "\"" org-log-note-state "\"")
9373 ""))
9374 (cons "%S" (if org-log-note-previous-state
9375 (concat "\"" org-log-note-previous-state "\"")
9376 "\"\"")))))
9377 (if lines (setq note (concat note " \\\\")))
9378 (push note lines))
9379 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9380 (when lines
9381 (save-excursion
9382 (set-buffer (marker-buffer org-log-note-marker))
9383 (save-excursion
9384 (goto-char org-log-note-marker)
9385 (move-marker org-log-note-marker nil)
9386 (end-of-line 1)
9387 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9388 (insert "- " (pop lines))
9389 (org-indent-line-function)
9390 (beginning-of-line 1)
9391 (looking-at "[ \t]*")
9392 (setq ind (concat (match-string 0) " "))
9393 (end-of-line 1)
9394 (while lines (insert "\n" ind (pop lines)))
9395 (message "Note stored")
9396 (org-back-to-heading t)
9397 (org-cycle-hide-drawers 'children)))))
9398 (set-window-configuration org-log-note-window-configuration)
9399 (with-current-buffer (marker-buffer org-log-note-return-to)
9400 (goto-char org-log-note-return-to))
9401 (move-marker org-log-note-return-to nil)
9402 (and org-log-post-message (message "%s" org-log-post-message)))
9404 (defun org-sparse-tree (&optional arg)
9405 "Create a sparse tree, prompt for the details.
9406 This command can create sparse trees. You first need to select the type
9407 of match used to create the tree:
9409 t Show entries with a specific TODO keyword.
9410 T Show entries selected by a tags match.
9411 p Enter a property name and its value (both with completion on existing
9412 names/values) and show entries with that property.
9413 r Show entries matching a regular expression
9414 d Show deadlines due within `org-deadline-warning-days'."
9415 (interactive "P")
9416 (let (ans kwd value)
9417 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9418 (setq ans (read-char-exclusive))
9419 (cond
9420 ((equal ans ?d)
9421 (call-interactively 'org-check-deadlines))
9422 ((equal ans ?b)
9423 (call-interactively 'org-check-before-date))
9424 ((equal ans ?t)
9425 (org-show-todo-tree '(4)))
9426 ((equal ans ?T)
9427 (call-interactively 'org-tags-sparse-tree))
9428 ((member ans '(?p ?P))
9429 (setq kwd (org-ido-completing-read "Property: "
9430 (mapcar 'list (org-buffer-property-keys))))
9431 (setq value (org-ido-completing-read "Value: "
9432 (mapcar 'list (org-property-values kwd))))
9433 (unless (string-match "\\`{.*}\\'" value)
9434 (setq value (concat "\"" value "\"")))
9435 (org-tags-sparse-tree arg (concat kwd "=" value)))
9436 ((member ans '(?r ?R ?/))
9437 (call-interactively 'org-occur))
9438 (t (error "No such sparse tree command \"%c\"" ans)))))
9440 (defvar org-occur-highlights nil
9441 "List of overlays used for occur matches.")
9442 (make-variable-buffer-local 'org-occur-highlights)
9443 (defvar org-occur-parameters nil
9444 "Parameters of the active org-occur calls.
9445 This is a list, each call to org-occur pushes as cons cell,
9446 containing the regular expression and the callback, onto the list.
9447 The list can contain several entries if `org-occur' has been called
9448 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9449 will only contain one set of parameters. When the highlights are
9450 removed (for example with `C-c C-c', or with the next edit (depending
9451 on `org-remove-highlights-with-change'), this variable is emptied
9452 as well.")
9453 (make-variable-buffer-local 'org-occur-parameters)
9455 (defun org-occur (regexp &optional keep-previous callback)
9456 "Make a compact tree which shows all matches of REGEXP.
9457 The tree will show the lines where the regexp matches, and all higher
9458 headlines above the match. It will also show the heading after the match,
9459 to make sure editing the matching entry is easy.
9460 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9461 call to `org-occur' will be kept, to allow stacking of calls to this
9462 command.
9463 If CALLBACK is non-nil, it is a function which is called to confirm
9464 that the match should indeed be shown."
9465 (interactive "sRegexp: \nP")
9466 (unless keep-previous
9467 (org-remove-occur-highlights nil nil t))
9468 (push (cons regexp callback) org-occur-parameters)
9469 (let ((cnt 0))
9470 (save-excursion
9471 (goto-char (point-min))
9472 (if (or (not keep-previous) ; do not want to keep
9473 (not org-occur-highlights)) ; no previous matches
9474 ;; hide everything
9475 (org-overview))
9476 (while (re-search-forward regexp nil t)
9477 (when (or (not callback)
9478 (save-match-data (funcall callback)))
9479 (setq cnt (1+ cnt))
9480 (when org-highlight-sparse-tree-matches
9481 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9482 (org-show-context 'occur-tree))))
9483 (when org-remove-highlights-with-change
9484 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9485 nil 'local))
9486 (unless org-sparse-tree-open-archived-trees
9487 (org-hide-archived-subtrees (point-min) (point-max)))
9488 (run-hooks 'org-occur-hook)
9489 (if (interactive-p)
9490 (message "%d match(es) for regexp %s" cnt regexp))
9491 cnt))
9493 (defun org-show-context (&optional key)
9494 "Make sure point and context and visible.
9495 How much context is shown depends upon the variables
9496 `org-show-hierarchy-above', `org-show-following-heading'. and
9497 `org-show-siblings'."
9498 (let ((heading-p (org-on-heading-p t))
9499 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9500 (following-p (org-get-alist-option org-show-following-heading key))
9501 (entry-p (org-get-alist-option org-show-entry-below key))
9502 (siblings-p (org-get-alist-option org-show-siblings key)))
9503 (catch 'exit
9504 ;; Show heading or entry text
9505 (if (and heading-p (not entry-p))
9506 (org-flag-heading nil) ; only show the heading
9507 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9508 (org-show-hidden-entry))) ; show entire entry
9509 (when following-p
9510 ;; Show next sibling, or heading below text
9511 (save-excursion
9512 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9513 (org-flag-heading nil))))
9514 (when siblings-p (org-show-siblings))
9515 (when hierarchy-p
9516 ;; show all higher headings, possibly with siblings
9517 (save-excursion
9518 (while (and (condition-case nil
9519 (progn (org-up-heading-all 1) t)
9520 (error nil))
9521 (not (bobp)))
9522 (org-flag-heading nil)
9523 (when siblings-p (org-show-siblings))))))))
9525 (defun org-reveal (&optional siblings)
9526 "Show current entry, hierarchy above it, and the following headline.
9527 This can be used to show a consistent set of context around locations
9528 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9529 not t for the search context.
9531 With optional argument SIBLINGS, on each level of the hierarchy all
9532 siblings are shown. This repairs the tree structure to what it would
9533 look like when opened with hierarchical calls to `org-cycle'."
9534 (interactive "P")
9535 (let ((org-show-hierarchy-above t)
9536 (org-show-following-heading t)
9537 (org-show-siblings (if siblings t org-show-siblings)))
9538 (org-show-context nil)))
9540 (defun org-highlight-new-match (beg end)
9541 "Highlight from BEG to END and mark the highlight is an occur headline."
9542 (let ((ov (org-make-overlay beg end)))
9543 (org-overlay-put ov 'face 'secondary-selection)
9544 (push ov org-occur-highlights)))
9546 (defun org-remove-occur-highlights (&optional beg end noremove)
9547 "Remove the occur highlights from the buffer.
9548 BEG and END are ignored. If NOREMOVE is nil, remove this function
9549 from the `before-change-functions' in the current buffer."
9550 (interactive)
9551 (unless org-inhibit-highlight-removal
9552 (mapc 'org-delete-overlay org-occur-highlights)
9553 (setq org-occur-highlights nil)
9554 (setq org-occur-parameters nil)
9555 (unless noremove
9556 (remove-hook 'before-change-functions
9557 'org-remove-occur-highlights 'local))))
9559 ;;;; Priorities
9561 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9562 "Regular expression matching the priority indicator.")
9564 (defvar org-remove-priority-next-time nil)
9566 (defun org-priority-up ()
9567 "Increase the priority of the current item."
9568 (interactive)
9569 (org-priority 'up))
9571 (defun org-priority-down ()
9572 "Decrease the priority of the current item."
9573 (interactive)
9574 (org-priority 'down))
9576 (defun org-priority (&optional action)
9577 "Change the priority of an item by ARG.
9578 ACTION can be `set', `up', `down', or a character."
9579 (interactive)
9580 (setq action (or action 'set))
9581 (let (current new news have remove)
9582 (save-excursion
9583 (org-back-to-heading t)
9584 (if (looking-at org-priority-regexp)
9585 (setq current (string-to-char (match-string 2))
9586 have t)
9587 (setq current org-default-priority))
9588 (cond
9589 ((or (eq action 'set)
9590 (if (featurep 'xemacs) (characterp action) (integerp action)))
9591 (if (not (eq action 'set))
9592 (setq new action)
9593 (message "Priority %c-%c, SPC to remove: "
9594 org-highest-priority org-lowest-priority)
9595 (setq new (read-char-exclusive)))
9596 (if (and (= (upcase org-highest-priority) org-highest-priority)
9597 (= (upcase org-lowest-priority) org-lowest-priority))
9598 (setq new (upcase new)))
9599 (cond ((equal new ?\ ) (setq remove t))
9600 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9601 (error "Priority must be between `%c' and `%c'"
9602 org-highest-priority org-lowest-priority))))
9603 ((eq action 'up)
9604 (if (and (not have) (eq last-command this-command))
9605 (setq new org-lowest-priority)
9606 (setq new (if (and org-priority-start-cycle-with-default (not have))
9607 org-default-priority (1- current)))))
9608 ((eq action 'down)
9609 (if (and (not have) (eq last-command this-command))
9610 (setq new org-highest-priority)
9611 (setq new (if (and org-priority-start-cycle-with-default (not have))
9612 org-default-priority (1+ current)))))
9613 (t (error "Invalid action")))
9614 (if (or (< (upcase new) org-highest-priority)
9615 (> (upcase new) org-lowest-priority))
9616 (setq remove t))
9617 (setq news (format "%c" new))
9618 (if have
9619 (if remove
9620 (replace-match "" t t nil 1)
9621 (replace-match news t t nil 2))
9622 (if remove
9623 (error "No priority cookie found in line")
9624 (looking-at org-todo-line-regexp)
9625 (if (match-end 2)
9626 (progn
9627 (goto-char (match-end 2))
9628 (insert " [#" news "]"))
9629 (goto-char (match-beginning 3))
9630 (insert "[#" news "] ")))))
9631 (org-preserve-lc (org-set-tags nil 'align))
9632 (if remove
9633 (message "Priority removed")
9634 (message "Priority of current item set to %s" news))))
9637 (defun org-get-priority (s)
9638 "Find priority cookie and return priority."
9639 (save-match-data
9640 (if (not (string-match org-priority-regexp s))
9641 (* 1000 (- org-lowest-priority org-default-priority))
9642 (* 1000 (- org-lowest-priority
9643 (string-to-char (match-string 2 s)))))))
9645 ;;;; Tags
9647 (defvar org-agenda-archives-mode)
9648 (defun org-scan-tags (action matcher &optional todo-only)
9649 "Scan headline tags with inheritance and produce output ACTION.
9651 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9652 or `agenda' to produce an entry list for an agenda view. It can also be
9653 a Lisp form or a function that should be called at each matched headline, in
9654 this case the return value is a list of all return values from these calls.
9656 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9657 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9658 only lines with a TODO keyword are included in the output."
9659 (require 'org-agenda)
9660 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9661 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9662 (org-re
9663 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9664 (props (list 'face 'default
9665 'done-face 'org-done
9666 'undone-face 'default
9667 'mouse-face 'highlight
9668 'org-not-done-regexp org-not-done-regexp
9669 'org-todo-regexp org-todo-regexp
9670 'keymap org-agenda-keymap
9671 'help-echo
9672 (format "mouse-2 or RET jump to org file %s"
9673 (abbreviate-file-name
9674 (or (buffer-file-name (buffer-base-buffer))
9675 (buffer-name (buffer-base-buffer)))))))
9676 (case-fold-search nil)
9677 lspos tags tags-list
9678 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9679 (llast 0) rtn rtn1 level category i txt
9680 todo marker entry priority)
9681 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9682 (setq action (list 'lambda nil action)))
9683 (save-excursion
9684 (goto-char (point-min))
9685 (when (eq action 'sparse-tree)
9686 (org-overview)
9687 (org-remove-occur-highlights))
9688 (while (re-search-forward re nil t)
9689 (catch :skip
9690 (setq todo (if (match-end 1) (match-string 2))
9691 tags (if (match-end 4) (match-string 4)))
9692 (goto-char (setq lspos (1+ (match-beginning 0))))
9693 (setq level (org-reduced-level (funcall outline-level))
9694 category (org-get-category))
9695 (setq i llast llast level)
9696 ;; remove tag lists from same and sublevels
9697 (while (>= i level)
9698 (when (setq entry (assoc i tags-alist))
9699 (setq tags-alist (delete entry tags-alist)))
9700 (setq i (1- i)))
9701 ;; add the next tags
9702 (when tags
9703 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9704 tags-alist
9705 (cons (cons level tags) tags-alist)))
9706 ;; compile tags for current headline
9707 (setq tags-list
9708 (if org-use-tag-inheritance
9709 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9710 tags))
9711 (when org-use-tag-inheritance
9712 (setcdr (car tags-alist)
9713 (mapcar (lambda (x)
9714 (setq x (copy-sequence x))
9715 (org-add-prop-inherited x))
9716 (cdar tags-alist))))
9717 (when (and tags org-use-tag-inheritance
9718 (not (eq t org-use-tag-inheritance)))
9719 ;; selective inheritance, remove uninherited ones
9720 (setcdr (car tags-alist)
9721 (org-remove-uniherited-tags (cdar tags-alist))))
9722 (when (and (or (not todo-only)
9723 (and (member todo org-not-done-keywords)
9724 (or (not org-agenda-tags-todo-honor-ignore-options)
9725 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9726 (let ((case-fold-search t)) (eval matcher))
9728 (not (member org-archive-tag tags-list))
9729 ;; we have an archive tag, should we use this anyway?
9730 (or (not org-agenda-skip-archived-trees)
9731 (and (eq action 'agenda) org-agenda-archives-mode))))
9732 (unless (eq action 'sparse-tree) (org-agenda-skip))
9734 ;; select this headline
9736 (cond
9737 ((eq action 'sparse-tree)
9738 (and org-highlight-sparse-tree-matches
9739 (org-get-heading) (match-end 0)
9740 (org-highlight-new-match
9741 (match-beginning 0) (match-beginning 1)))
9742 (org-show-context 'tags-tree))
9743 ((eq action 'agenda)
9744 (setq txt (org-format-agenda-item
9746 (concat
9747 (if org-tags-match-list-sublevels
9748 (make-string (1- level) ?.) "")
9749 (org-get-heading))
9750 category (org-get-tags-at))
9751 priority (org-get-priority txt))
9752 (goto-char lspos)
9753 (setq marker (org-agenda-new-marker))
9754 (org-add-props txt props
9755 'org-marker marker 'org-hd-marker marker 'org-category category
9756 'todo-state todo
9757 'priority priority 'type "tagsmatch")
9758 (push txt rtn))
9759 ((functionp action)
9760 (save-excursion
9761 (setq rtn1 (funcall action))
9762 (push rtn1 rtn))
9763 (goto-char (point-at-eol)))
9764 (t (error "Invalid action")))
9766 ;; if we are to skip sublevels, jump to end of subtree
9767 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9768 (when (and (eq action 'sparse-tree)
9769 (not org-sparse-tree-open-archived-trees))
9770 (org-hide-archived-subtrees (point-min) (point-max)))
9771 (nreverse rtn)))
9773 (defun org-remove-uniherited-tags (tags)
9774 "Remove all tags that are not inherited from the list TAGS."
9775 (cond
9776 ((eq org-use-tag-inheritance t)
9777 (if org-tags-exclude-from-inheritance
9778 (org-delete-all org-tags-exclude-from-inheritance tags)
9779 tags))
9780 ((not org-use-tag-inheritance) nil)
9781 ((stringp org-use-tag-inheritance)
9782 (delq nil (mapcar
9783 (lambda (x)
9784 (if (and (string-match org-use-tag-inheritance x)
9785 (not (member x org-tags-exclude-from-inheritance)))
9786 x nil))
9787 tags)))
9788 ((listp org-use-tag-inheritance)
9789 (delq nil (mapcar
9790 (lambda (x)
9791 (if (member x org-use-tag-inheritance) x nil))
9792 tags)))))
9794 (defvar todo-only) ;; dynamically scoped
9796 (defun org-tags-sparse-tree (&optional todo-only match)
9797 "Create a sparse tree according to tags string MATCH.
9798 MATCH can contain positive and negative selection of tags, like
9799 \"+WORK+URGENT-WITHBOSS\".
9800 If optional argument TODO-ONLY is non-nil, only select lines that are
9801 also TODO lines."
9802 (interactive "P")
9803 (org-prepare-agenda-buffers (list (current-buffer)))
9804 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9806 (defvar org-cached-props nil)
9807 (defun org-cached-entry-get (pom property)
9808 (if (or (eq t org-use-property-inheritance)
9809 (and (stringp org-use-property-inheritance)
9810 (string-match org-use-property-inheritance property))
9811 (and (listp org-use-property-inheritance)
9812 (member property org-use-property-inheritance)))
9813 ;; Caching is not possible, check it directly
9814 (org-entry-get pom property 'inherit)
9815 ;; Get all properties, so that we can do complicated checks easily
9816 (cdr (assoc property (or org-cached-props
9817 (setq org-cached-props
9818 (org-entry-properties pom)))))))
9820 (defun org-global-tags-completion-table (&optional files)
9821 "Return the list of all tags in all agenda buffer/files."
9822 (save-excursion
9823 (org-uniquify
9824 (delq nil
9825 (apply 'append
9826 (mapcar
9827 (lambda (file)
9828 (set-buffer (find-file-noselect file))
9829 (append (org-get-buffer-tags)
9830 (mapcar (lambda (x) (if (stringp (car-safe x))
9831 (list (car-safe x)) nil))
9832 org-tag-alist)))
9833 (if (and files (car files))
9834 files
9835 (org-agenda-files))))))))
9837 (defun org-make-tags-matcher (match)
9838 "Create the TAGS//TODO matcher form for the selection string MATCH."
9839 ;; todo-only is scoped dynamically into this function, and the function
9840 ;; may change it if the matcher asks for it.
9841 (unless match
9842 ;; Get a new match request, with completion
9843 (let ((org-last-tags-completion-table
9844 (org-global-tags-completion-table)))
9845 (setq match (org-completing-read-no-ido
9846 "Match: " 'org-tags-completion-function nil nil nil
9847 'org-tags-history))))
9849 ;; Parse the string and create a lisp form
9850 (let ((match0 match)
9851 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9852 minus tag mm
9853 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9854 orterms term orlist re-p str-p level-p level-op time-p
9855 prop-p pn pv po cat-p gv rest)
9856 (if (string-match "/+" match)
9857 ;; match contains also a todo-matching request
9858 (progn
9859 (setq tagsmatch (substring match 0 (match-beginning 0))
9860 todomatch (substring match (match-end 0)))
9861 (if (string-match "^!" todomatch)
9862 (setq todo-only t todomatch (substring todomatch 1)))
9863 (if (string-match "^\\s-*$" todomatch)
9864 (setq todomatch nil)))
9865 ;; only matching tags
9866 (setq tagsmatch match todomatch nil))
9868 ;; Make the tags matcher
9869 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9870 (setq tagsmatcher t)
9871 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9872 (while (setq term (pop orterms))
9873 (while (and (equal (substring term -1) "\\") orterms)
9874 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9875 (while (string-match re term)
9876 (setq rest (substring term (match-end 0))
9877 minus (and (match-end 1)
9878 (equal (match-string 1 term) "-"))
9879 tag (match-string 2 term)
9880 re-p (equal (string-to-char tag) ?{)
9881 level-p (match-end 4)
9882 prop-p (match-end 5)
9883 mm (cond
9884 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9885 (level-p
9886 (setq level-op (org-op-to-function (match-string 3 term)))
9887 `(,level-op level ,(string-to-number
9888 (match-string 4 term))))
9889 (prop-p
9890 (setq pn (match-string 5 term)
9891 po (match-string 6 term)
9892 pv (match-string 7 term)
9893 cat-p (equal pn "CATEGORY")
9894 re-p (equal (string-to-char pv) ?{)
9895 str-p (equal (string-to-char pv) ?\")
9896 time-p (save-match-data
9897 (string-match "^\"[[<].*[]>]\"$" pv))
9898 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9899 (if time-p (setq pv (org-matcher-time pv)))
9900 (setq po (org-op-to-function po (if time-p 'time str-p)))
9901 (cond
9902 ((equal pn "CATEGORY")
9903 (setq gv '(get-text-property (point) 'org-category)))
9904 ((equal pn "TODO")
9905 (setq gv 'todo))
9907 (setq gv `(org-cached-entry-get nil ,pn))))
9908 (if re-p
9909 (if (eq po 'org<>)
9910 `(not (string-match ,pv (or ,gv "")))
9911 `(string-match ,pv (or ,gv "")))
9912 (if str-p
9913 `(,po (or ,gv "") ,pv)
9914 `(,po (string-to-number (or ,gv ""))
9915 ,(string-to-number pv) ))))
9916 (t `(member ,(downcase tag) tags-list)))
9917 mm (if minus (list 'not mm) mm)
9918 term rest)
9919 (push mm tagsmatcher))
9920 (push (if (> (length tagsmatcher) 1)
9921 (cons 'and tagsmatcher)
9922 (car tagsmatcher))
9923 orlist)
9924 (setq tagsmatcher nil))
9925 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9926 (setq tagsmatcher
9927 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9928 ;; Make the todo matcher
9929 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9930 (setq todomatcher t)
9931 (setq orterms (org-split-string todomatch "|") orlist nil)
9932 (while (setq term (pop orterms))
9933 (while (string-match re term)
9934 (setq minus (and (match-end 1)
9935 (equal (match-string 1 term) "-"))
9936 kwd (match-string 2 term)
9937 re-p (equal (string-to-char kwd) ?{)
9938 term (substring term (match-end 0))
9939 mm (if re-p
9940 `(string-match ,(substring kwd 1 -1) todo)
9941 (list 'equal 'todo kwd))
9942 mm (if minus (list 'not mm) mm))
9943 (push mm todomatcher))
9944 (push (if (> (length todomatcher) 1)
9945 (cons 'and todomatcher)
9946 (car todomatcher))
9947 orlist)
9948 (setq todomatcher nil))
9949 (setq todomatcher (if (> (length orlist) 1)
9950 (cons 'or orlist) (car orlist))))
9952 ;; Return the string and lisp forms of the matcher
9953 (setq matcher (if todomatcher
9954 (list 'and tagsmatcher todomatcher)
9955 tagsmatcher))
9956 (cons match0 matcher)))
9958 (defun org-op-to-function (op &optional stringp)
9959 "Turn an operator into the appropriate function."
9960 (setq op
9961 (cond
9962 ((equal op "<" ) '(< string< org-time<))
9963 ((equal op ">" ) '(> org-string> org-time>))
9964 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9965 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9966 ((member op '("=" "==")) '(= string= org-time=))
9967 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9968 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9970 (defun org<> (a b) (not (= a b)))
9971 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9972 (defun org-string>= (a b) (not (string< a b)))
9973 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9974 (defun org-string<> (a b) (not (string= a b)))
9975 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= 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) (org<> a b)))
9981 (defun org-2ft (s)
9982 "Convert S to a floating point time.
9983 If S is already a number, just return it. If it is a string, parse
9984 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9985 (cond
9986 ((numberp s) s)
9987 ((stringp s)
9988 (condition-case nil
9989 (float-time (apply 'encode-time (org-parse-time-string s)))
9990 (error 0.)))
9991 (t 0.)))
9993 (defun org-time-today ()
9994 "Time in seconds today at 0:00.
9995 Returns the float number of seconds since the beginning of the
9996 epoch to the beginning of today (00:00)."
9997 (float-time (apply 'encode-time
9998 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10000 (defun org-matcher-time (s)
10001 "Interpret a time comparison value."
10002 (save-match-data
10003 (cond
10004 ((string= s "<now>") (float-time))
10005 ((string= s "<today>") (org-time-today))
10006 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10007 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10008 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10009 (+ (org-time-today)
10010 (* (string-to-number (match-string 1 s))
10011 (cdr (assoc (match-string 2 s)
10012 '(("d" . 86400.0) ("w" . 604800.0)
10013 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10014 (t (org-2ft s)))))
10016 (defun org-match-any-p (re list)
10017 "Does re match any element of list?"
10018 (setq list (mapcar (lambda (x) (string-match re x)) list))
10019 (delq nil list))
10021 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10022 (defvar org-tags-overlay (org-make-overlay 1 1))
10023 (org-detach-overlay org-tags-overlay)
10025 (defun org-get-local-tags-at (&optional pos)
10026 "Get a list of tags defined in the current headline."
10027 (org-get-tags-at pos 'local))
10029 (defun org-get-local-tags ()
10030 "Get a list of tags defined in the current headline."
10031 (org-get-tags-at nil 'local))
10033 (defun org-get-tags-at (&optional pos local)
10034 "Get a list of all headline tags applicable at POS.
10035 POS defaults to point. If tags are inherited, the list contains
10036 the targets in the same sequence as the headlines appear, i.e.
10037 the tags of the current headline come last.
10038 When LOCAL is non-nil, only return tags from the current headline,
10039 ignore inherited ones."
10040 (interactive)
10041 (let (tags ltags lastpos parent)
10042 (save-excursion
10043 (save-restriction
10044 (widen)
10045 (goto-char (or pos (point)))
10046 (save-match-data
10047 (catch 'done
10048 (condition-case nil
10049 (progn
10050 (org-back-to-heading t)
10051 (while (not (equal lastpos (point)))
10052 (setq lastpos (point))
10053 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10054 (setq ltags (org-split-string
10055 (org-match-string-no-properties 1) ":"))
10056 (when parent
10057 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10058 (setq tags (append
10059 (if parent
10060 (org-remove-uniherited-tags ltags)
10061 ltags)
10062 tags)))
10063 (or org-use-tag-inheritance (throw 'done t))
10064 (if local (throw 'done t))
10065 (org-up-heading-all 1)
10066 (setq parent t)))
10067 (error nil)))))
10068 (append (org-remove-uniherited-tags org-file-tags) tags))))
10070 (defun org-add-prop-inherited (s)
10071 (add-text-properties 0 (length s) '(inherited t) s)
10074 (defun org-toggle-tag (tag &optional onoff)
10075 "Toggle the tag TAG for the current line.
10076 If ONOFF is `on' or `off', don't toggle but set to this state."
10077 (let (res current)
10078 (save-excursion
10079 (org-back-to-heading t)
10080 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10081 (point-at-eol) t)
10082 (progn
10083 (setq current (match-string 1))
10084 (replace-match ""))
10085 (setq current ""))
10086 (setq current (nreverse (org-split-string current ":")))
10087 (cond
10088 ((eq onoff 'on)
10089 (setq res t)
10090 (or (member tag current) (push tag current)))
10091 ((eq onoff 'off)
10092 (or (not (member tag current)) (setq current (delete tag current))))
10093 (t (if (member tag current)
10094 (setq current (delete tag current))
10095 (setq res t)
10096 (push tag current))))
10097 (end-of-line 1)
10098 (if current
10099 (progn
10100 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10101 (org-set-tags nil t))
10102 (delete-horizontal-space))
10103 (run-hooks 'org-after-tags-change-hook))
10104 res))
10106 (defun org-align-tags-here (to-col)
10107 ;; Assumes that this is a headline
10108 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10109 (beginning-of-line 1)
10110 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10111 (< pos (match-beginning 2)))
10112 (progn
10113 (setq tags-l (- (match-end 2) (match-beginning 2)))
10114 (goto-char (match-beginning 1))
10115 (insert " ")
10116 (delete-region (point) (1+ (match-beginning 2)))
10117 (setq ncol (max (1+ (current-column))
10118 (1+ col)
10119 (if (> to-col 0)
10120 to-col
10121 (- (abs to-col) tags-l))))
10122 (setq p (point))
10123 (insert (make-string (- ncol (current-column)) ?\ ))
10124 (setq ncol (current-column))
10125 (when indent-tabs-mode (tabify p (point-at-eol)))
10126 (org-move-to-column (min ncol col) t))
10127 (goto-char pos))))
10129 (defun org-set-tags-command (&optional arg just-align)
10130 "Call the set-tags command for the current entry."
10131 (interactive "P")
10132 (if (org-on-heading-p)
10133 (org-set-tags arg just-align)
10134 (save-excursion
10135 (org-back-to-heading t)
10136 (org-set-tags arg just-align))))
10138 (defun org-set-tags (&optional arg just-align)
10139 "Set the tags for the current headline.
10140 With prefix ARG, realign all tags in headings in the current buffer."
10141 (interactive "P")
10142 (let* ((re (concat "^" outline-regexp))
10143 (current (org-get-tags-string))
10144 (col (current-column))
10145 (org-setting-tags t)
10146 table current-tags inherited-tags ; computed below when needed
10147 tags p0 c0 c1 rpl)
10148 (if arg
10149 (save-excursion
10150 (goto-char (point-min))
10151 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10152 (while (re-search-forward re nil t)
10153 (org-set-tags nil t)
10154 (end-of-line 1)))
10155 (message "All tags realigned to column %d" org-tags-column))
10156 (if just-align
10157 (setq tags current)
10158 ;; Get a new set of tags from the user
10159 (save-excursion
10160 (setq table (or org-tag-alist (org-get-buffer-tags))
10161 org-last-tags-completion-table table
10162 current-tags (org-split-string current ":")
10163 inherited-tags (nreverse
10164 (nthcdr (length current-tags)
10165 (nreverse (org-get-tags-at))))
10166 tags
10167 (if (or (eq t org-use-fast-tag-selection)
10168 (and org-use-fast-tag-selection
10169 (delq nil (mapcar 'cdr table))))
10170 (org-fast-tag-selection
10171 current-tags inherited-tags table
10172 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10173 (let ((org-add-colon-after-tag-completion t))
10174 (org-trim
10175 (org-without-partial-completion
10176 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10177 nil nil current 'org-tags-history)))))))
10178 (while (string-match "[-+&]+" tags)
10179 ;; No boolean logic, just a list
10180 (setq tags (replace-match ":" t t tags))))
10182 (if (string-match "\\`[\t ]*\\'" tags)
10183 (setq tags "")
10184 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10185 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10187 ;; Insert new tags at the correct column
10188 (beginning-of-line 1)
10189 (cond
10190 ((and (equal current "") (equal tags "")))
10191 ((re-search-forward
10192 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10193 (point-at-eol) t)
10194 (if (equal tags "")
10195 (setq rpl "")
10196 (goto-char (match-beginning 0))
10197 (setq c0 (current-column) p0 (point)
10198 c1 (max (1+ c0) (if (> org-tags-column 0)
10199 org-tags-column
10200 (- (- org-tags-column) (length tags))))
10201 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10202 (replace-match rpl t t)
10203 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10204 tags)
10205 (t (error "Tags alignment failed")))
10206 (org-move-to-column col)
10207 (unless just-align
10208 (run-hooks 'org-after-tags-change-hook)))))
10210 (defun org-change-tag-in-region (beg end tag off)
10211 "Add or remove TAG for each entry in the region.
10212 This works in the agenda, and also in an org-mode buffer."
10213 (interactive
10214 (list (region-beginning) (region-end)
10215 (let ((org-last-tags-completion-table
10216 (if (org-mode-p)
10217 (org-get-buffer-tags)
10218 (org-global-tags-completion-table))))
10219 (org-ido-completing-read
10220 "Tag: " 'org-tags-completion-function nil nil nil
10221 'org-tags-history))
10222 (progn
10223 (message "[s]et or [r]emove? ")
10224 (equal (read-char-exclusive) ?r))))
10225 (if (fboundp 'deactivate-mark) (deactivate-mark))
10226 (let ((agendap (equal major-mode 'org-agenda-mode))
10227 l1 l2 m buf pos newhead (cnt 0))
10228 (goto-char end)
10229 (setq l2 (1- (org-current-line)))
10230 (goto-char beg)
10231 (setq l1 (org-current-line))
10232 (loop for l from l1 to l2 do
10233 (goto-line l)
10234 (setq m (get-text-property (point) 'org-hd-marker))
10235 (when (or (and (org-mode-p) (org-on-heading-p))
10236 (and agendap m))
10237 (setq buf (if agendap (marker-buffer m) (current-buffer))
10238 pos (if agendap m (point)))
10239 (with-current-buffer buf
10240 (save-excursion
10241 (save-restriction
10242 (goto-char pos)
10243 (setq cnt (1+ cnt))
10244 (org-toggle-tag tag (if off 'off 'on))
10245 (setq newhead (org-get-heading)))))
10246 (and agendap (org-agenda-change-all-lines newhead m))))
10247 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10249 (defun org-tags-completion-function (string predicate &optional flag)
10250 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10251 (confirm (lambda (x) (stringp (car x)))))
10252 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10253 (setq s1 (match-string 1 string)
10254 s2 (match-string 2 string))
10255 (setq s1 "" s2 string))
10256 (cond
10257 ((eq flag nil)
10258 ;; try completion
10259 (setq rtn (try-completion s2 ctable confirm))
10260 (if (stringp rtn)
10261 (setq rtn
10262 (concat s1 s2 (substring rtn (length s2))
10263 (if (and org-add-colon-after-tag-completion
10264 (assoc rtn ctable))
10265 ":" ""))))
10266 rtn)
10267 ((eq flag t)
10268 ;; all-completions
10269 (all-completions s2 ctable confirm)
10271 ((eq flag 'lambda)
10272 ;; exact match?
10273 (assoc s2 ctable)))
10276 (defun org-fast-tag-insert (kwd tags face &optional end)
10277 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10278 (insert (format "%-12s" (concat kwd ":"))
10279 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10280 (or end "")))
10282 (defun org-fast-tag-show-exit (flag)
10283 (save-excursion
10284 (goto-line 3)
10285 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10286 (replace-match ""))
10287 (when flag
10288 (end-of-line 1)
10289 (org-move-to-column (- (window-width) 19) t)
10290 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10292 (defun org-set-current-tags-overlay (current prefix)
10293 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10294 (if (featurep 'xemacs)
10295 (org-overlay-display org-tags-overlay (concat prefix s)
10296 'secondary-selection)
10297 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10298 (org-overlay-display org-tags-overlay (concat prefix s)))))
10300 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10301 "Fast tag selection with single keys.
10302 CURRENT is the current list of tags in the headline, INHERITED is the
10303 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10304 possibly with grouping information. TODO-TABLE is a similar table with
10305 TODO keywords, should these have keys assigned to them.
10306 If the keys are nil, a-z are automatically assigned.
10307 Returns the new tags string, or nil to not change the current settings."
10308 (let* ((fulltable (append table todo-table))
10309 (maxlen (apply 'max (mapcar
10310 (lambda (x)
10311 (if (stringp (car x)) (string-width (car x)) 0))
10312 fulltable)))
10313 (buf (current-buffer))
10314 (expert (eq org-fast-tag-selection-single-key 'expert))
10315 (buffer-tags nil)
10316 (fwidth (+ maxlen 3 1 3))
10317 (ncol (/ (- (window-width) 4) fwidth))
10318 (i-face 'org-done)
10319 (c-face 'org-todo)
10320 tg cnt e c char c1 c2 ntable tbl rtn
10321 ov-start ov-end ov-prefix
10322 (exit-after-next org-fast-tag-selection-single-key)
10323 (done-keywords org-done-keywords)
10324 groups ingroup)
10325 (save-excursion
10326 (beginning-of-line 1)
10327 (if (looking-at
10328 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10329 (setq ov-start (match-beginning 1)
10330 ov-end (match-end 1)
10331 ov-prefix "")
10332 (setq ov-start (1- (point-at-eol))
10333 ov-end (1+ ov-start))
10334 (skip-chars-forward "^\n\r")
10335 (setq ov-prefix
10336 (concat
10337 (buffer-substring (1- (point)) (point))
10338 (if (> (current-column) org-tags-column)
10340 (make-string (- org-tags-column (current-column)) ?\ ))))))
10341 (org-move-overlay org-tags-overlay ov-start ov-end)
10342 (save-window-excursion
10343 (if expert
10344 (set-buffer (get-buffer-create " *Org tags*"))
10345 (delete-other-windows)
10346 (split-window-vertically)
10347 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10348 (erase-buffer)
10349 (org-set-local 'org-done-keywords done-keywords)
10350 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10351 (org-fast-tag-insert "Current" current c-face "\n\n")
10352 (org-fast-tag-show-exit exit-after-next)
10353 (org-set-current-tags-overlay current ov-prefix)
10354 (setq tbl fulltable char ?a cnt 0)
10355 (while (setq e (pop tbl))
10356 (cond
10357 ((equal e '(:startgroup))
10358 (push '() groups) (setq ingroup t)
10359 (when (not (= cnt 0))
10360 (setq cnt 0)
10361 (insert "\n"))
10362 (insert "{ "))
10363 ((equal e '(:endgroup))
10364 (setq ingroup nil cnt 0)
10365 (insert "}\n"))
10366 ((equal e '(:newline))
10367 (insert "\n "))
10369 (setq tg (car e) c2 nil)
10370 (if (cdr e)
10371 (setq c (cdr e))
10372 ;; automatically assign a character.
10373 (setq c1 (string-to-char
10374 (downcase (substring
10375 tg (if (= (string-to-char tg) ?@) 1 0)))))
10376 (if (or (rassoc c1 ntable) (rassoc c1 table))
10377 (while (or (rassoc char ntable) (rassoc char table))
10378 (setq char (1+ char)))
10379 (setq c2 c1))
10380 (setq c (or c2 char)))
10381 (if ingroup (push tg (car groups)))
10382 (setq tg (org-add-props tg nil 'face
10383 (cond
10384 ((not (assoc tg table))
10385 (org-get-todo-face tg))
10386 ((member tg current) c-face)
10387 ((member tg inherited) i-face)
10388 (t nil))))
10389 (if (and (= cnt 0) (not ingroup)) (insert " "))
10390 (insert "[" c "] " tg (make-string
10391 (- fwidth 4 (length tg)) ?\ ))
10392 (push (cons tg c) ntable)
10393 (when (= (setq cnt (1+ cnt)) ncol)
10394 (insert "\n")
10395 (if ingroup (insert " "))
10396 (setq cnt 0)))))
10397 (setq ntable (nreverse ntable))
10398 (insert "\n")
10399 (goto-char (point-min))
10400 (if (not expert) (org-fit-window-to-buffer))
10401 (setq rtn
10402 (catch 'exit
10403 (while t
10404 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10405 (if groups " [!] no groups" " [!]groups")
10406 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10407 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10408 (cond
10409 ((= c ?\r) (throw 'exit t))
10410 ((= c ?!)
10411 (setq groups (not groups))
10412 (goto-char (point-min))
10413 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10414 ((= c ?\C-c)
10415 (if (not expert)
10416 (org-fast-tag-show-exit
10417 (setq exit-after-next (not exit-after-next)))
10418 (setq expert nil)
10419 (delete-other-windows)
10420 (split-window-vertically)
10421 (org-switch-to-buffer-other-window " *Org tags*")
10422 (org-fit-window-to-buffer)))
10423 ((or (= c ?\C-g)
10424 (and (= c ?q) (not (rassoc c ntable))))
10425 (org-detach-overlay org-tags-overlay)
10426 (setq quit-flag t))
10427 ((= c ?\ )
10428 (setq current nil)
10429 (if exit-after-next (setq exit-after-next 'now)))
10430 ((= c ?\t)
10431 (condition-case nil
10432 (setq tg (org-ido-completing-read
10433 "Tag: "
10434 (or buffer-tags
10435 (with-current-buffer buf
10436 (org-get-buffer-tags)))))
10437 (quit (setq tg "")))
10438 (when (string-match "\\S-" tg)
10439 (add-to-list 'buffer-tags (list tg))
10440 (if (member tg current)
10441 (setq current (delete tg current))
10442 (push tg current)))
10443 (if exit-after-next (setq exit-after-next 'now)))
10444 ((setq e (rassoc c todo-table) tg (car e))
10445 (with-current-buffer buf
10446 (save-excursion (org-todo tg)))
10447 (if exit-after-next (setq exit-after-next 'now)))
10448 ((setq e (rassoc c ntable) tg (car e))
10449 (if (member tg current)
10450 (setq current (delete tg current))
10451 (loop for g in groups do
10452 (if (member tg g)
10453 (mapc (lambda (x)
10454 (setq current (delete x current)))
10455 g)))
10456 (push tg current))
10457 (if exit-after-next (setq exit-after-next 'now))))
10459 ;; Create a sorted list
10460 (setq current
10461 (sort current
10462 (lambda (a b)
10463 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10464 (if (eq exit-after-next 'now) (throw 'exit t))
10465 (goto-char (point-min))
10466 (beginning-of-line 2)
10467 (delete-region (point) (point-at-eol))
10468 (org-fast-tag-insert "Current" current c-face)
10469 (org-set-current-tags-overlay current ov-prefix)
10470 (while (re-search-forward
10471 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10472 (setq tg (match-string 1))
10473 (add-text-properties
10474 (match-beginning 1) (match-end 1)
10475 (list 'face
10476 (cond
10477 ((member tg current) c-face)
10478 ((member tg inherited) i-face)
10479 (t (get-text-property (match-beginning 1) 'face))))))
10480 (goto-char (point-min)))))
10481 (org-detach-overlay org-tags-overlay)
10482 (if rtn
10483 (mapconcat 'identity current ":")
10484 nil))))
10486 (defun org-get-tags-string ()
10487 "Get the TAGS string in the current headline."
10488 (unless (org-on-heading-p t)
10489 (error "Not on a heading"))
10490 (save-excursion
10491 (beginning-of-line 1)
10492 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10493 (org-match-string-no-properties 1)
10494 "")))
10496 (defun org-get-tags ()
10497 "Get the list of tags specified in the current headline."
10498 (org-split-string (org-get-tags-string) ":"))
10500 (defun org-get-buffer-tags ()
10501 "Get a table of all tags used in the buffer, for completion."
10502 (let (tags)
10503 (save-excursion
10504 (goto-char (point-min))
10505 (while (re-search-forward
10506 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10507 (when (equal (char-after (point-at-bol 0)) ?*)
10508 (mapc (lambda (x) (add-to-list 'tags x))
10509 (org-split-string (org-match-string-no-properties 1) ":")))))
10510 (mapcar 'list tags)))
10512 ;;;; The mapping API
10514 ;;;###autoload
10515 (defun org-map-entries (func &optional match scope &rest skip)
10516 "Call FUNC at each headline selected by MATCH in SCOPE.
10518 FUNC is a function or a lisp form. The function will be called without
10519 arguments, with the cursor positioned at the beginning of the headline.
10520 The return values of all calls to the function will be collected and
10521 returned as a list.
10523 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10524 Only headlines that are matched by this query will be considered during
10525 the iteration. When MATCH is nil or t, all headlines will be
10526 visited by the iteration.
10528 SCOPE determines the scope of this command. It can be any of:
10530 nil The current buffer, respecting the restriction if any
10531 tree The subtree started with the entry at point
10532 file The current buffer, without restriction
10533 file-with-archives
10534 The current buffer, and any archives associated with it
10535 agenda All agenda files
10536 agenda-with-archives
10537 All agenda files with any archive files associated with them
10538 \(file1 file2 ...)
10539 If this is a list, all files in the list will be scanned
10541 The remaining args are treated as settings for the skipping facilities of
10542 the scanner. The following items can be given here:
10544 archive skip trees with the archive tag.
10545 comment skip trees with the COMMENT keyword
10546 function or Emacs Lisp form:
10547 will be used as value for `org-agenda-skip-function', so whenever
10548 the the function returns t, FUNC will not be called for that
10549 entry and search will continue from the point where the
10550 function leaves it."
10551 (let* ((org-agenda-archives-mode nil) ; just to make sure
10552 (org-agenda-skip-archived-trees (memq 'archive skip))
10553 (org-agenda-skip-comment-trees (memq 'comment skip))
10554 (org-agenda-skip-function
10555 (car (org-delete-all '(comment archive) skip)))
10556 (org-tags-match-list-sublevels t)
10557 matcher file res
10558 org-todo-keywords-for-agenda
10559 org-done-keywords-for-agenda
10560 org-todo-keyword-alist-for-agenda
10561 org-tag-alist-for-agenda)
10563 (cond
10564 ((eq match t) (setq matcher t))
10565 ((eq match nil) (setq matcher t))
10566 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10568 (save-excursion
10569 (save-restriction
10570 (when (eq scope 'tree)
10571 (org-back-to-heading t)
10572 (org-narrow-to-subtree)
10573 (setq scope nil))
10575 (if (not scope)
10576 (progn
10577 (org-prepare-agenda-buffers
10578 (list (buffer-file-name (current-buffer))))
10579 (setq res (org-scan-tags func matcher)))
10580 ;; Get the right scope
10581 (cond
10582 ((and scope (listp scope) (symbolp (car scope)))
10583 (setq scope (eval scope)))
10584 ((eq scope 'agenda)
10585 (setq scope (org-agenda-files t)))
10586 ((eq scope 'agenda-with-archives)
10587 (setq scope (org-agenda-files t))
10588 (setq scope (org-add-archive-files scope)))
10589 ((eq scope 'file)
10590 (setq scope (list (buffer-file-name))))
10591 ((eq scope 'file-with-archives)
10592 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10593 (org-prepare-agenda-buffers scope)
10594 (while (setq file (pop scope))
10595 (with-current-buffer (org-find-base-buffer-visiting file)
10596 (save-excursion
10597 (save-restriction
10598 (widen)
10599 (goto-char (point-min))
10600 (setq res (append res (org-scan-tags func matcher))))))))))
10601 res))
10603 ;;;; Properties
10605 ;;; Setting and retrieving properties
10607 (defconst org-special-properties
10608 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10609 "TIMESTAMP" "TIMESTAMP_IA")
10610 "The special properties valid in Org-mode.
10612 These are properties that are not defined in the property drawer,
10613 but in some other way.")
10615 (defconst org-default-properties
10616 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10617 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10618 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10619 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10620 "Some properties that are used by Org-mode for various purposes.
10621 Being in this list makes sure that they are offered for completion.")
10623 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10624 "Regular expression matching the first line of a property drawer.")
10626 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10627 "Regular expression matching the first line of a property drawer.")
10629 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10630 "Regular expression matching the first line of a property drawer.")
10632 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10633 "Regular expression matching the first line of a property drawer.")
10635 (defconst org-property-drawer-re
10636 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10637 org-property-end-re "\\)\n?")
10638 "Matches an entire property drawer.")
10640 (defconst org-clock-drawer-re
10641 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10642 org-property-end-re "\\)\n?")
10643 "Matches an entire clock drawer.")
10645 (defun org-property-action ()
10646 "Do an action on properties."
10647 (interactive)
10648 (let (c)
10649 (org-at-property-p)
10650 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10651 (setq c (read-char-exclusive))
10652 (cond
10653 ((equal c ?s)
10654 (call-interactively 'org-set-property))
10655 ((equal c ?d)
10656 (call-interactively 'org-delete-property))
10657 ((equal c ?D)
10658 (call-interactively 'org-delete-property-globally))
10659 ((equal c ?c)
10660 (call-interactively 'org-compute-property-at-point))
10661 (t (error "No such property action %c" c)))))
10663 (defun org-at-property-p ()
10664 "Is the cursor in a property line?"
10665 ;; FIXME: Does not check if we are actually in the drawer.
10666 ;; FIXME: also returns true on any drawers.....
10667 ;; This is used by C-c C-c for property action.
10668 (save-excursion
10669 (beginning-of-line 1)
10670 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10672 (defun org-get-property-block (&optional beg end force)
10673 "Return the (beg . end) range of the body of the property drawer.
10674 BEG and END can be beginning and end of subtree, if not given
10675 they will be found.
10676 If the drawer does not exist and FORCE is non-nil, create the drawer."
10677 (catch 'exit
10678 (save-excursion
10679 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10680 (end (or end (progn (outline-next-heading) (point)))))
10681 (goto-char beg)
10682 (if (re-search-forward org-property-start-re end t)
10683 (setq beg (1+ (match-end 0)))
10684 (if force
10685 (save-excursion
10686 (org-insert-property-drawer)
10687 (setq end (progn (outline-next-heading) (point))))
10688 (throw 'exit nil))
10689 (goto-char beg)
10690 (if (re-search-forward org-property-start-re end t)
10691 (setq beg (1+ (match-end 0)))))
10692 (if (re-search-forward org-property-end-re end t)
10693 (setq end (match-beginning 0))
10694 (or force (throw 'exit nil))
10695 (goto-char beg)
10696 (setq end beg)
10697 (org-indent-line-function)
10698 (insert ":END:\n"))
10699 (cons beg end)))))
10701 (defun org-entry-properties (&optional pom which)
10702 "Get all properties of the entry at point-or-marker POM.
10703 This includes the TODO keyword, the tags, time strings for deadline,
10704 scheduled, and clocking, and any additional properties defined in the
10705 entry. The return value is an alist, keys may occur multiple times
10706 if the property key was used several times.
10707 POM may also be nil, in which case the current entry is used.
10708 If WHICH is nil or `all', get all properties. If WHICH is
10709 `special' or `standard', only get that subclass."
10710 (setq which (or which 'all))
10711 (org-with-point-at pom
10712 (let ((clockstr (substring org-clock-string 0 -1))
10713 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10714 beg end range props sum-props key value string clocksum)
10715 (save-excursion
10716 (when (condition-case nil
10717 (and (org-mode-p) (org-back-to-heading t))
10718 (error nil))
10719 (setq beg (point))
10720 (setq sum-props (get-text-property (point) 'org-summaries))
10721 (setq clocksum (get-text-property (point) :org-clock-minutes))
10722 (outline-next-heading)
10723 (setq end (point))
10724 (when (memq which '(all special))
10725 ;; Get the special properties, like TODO and tags
10726 (goto-char beg)
10727 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10728 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10729 (when (looking-at org-priority-regexp)
10730 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10731 (when (and (setq value (org-get-tags-string))
10732 (string-match "\\S-" value))
10733 (push (cons "TAGS" value) props))
10734 (when (setq value (org-get-tags-at))
10735 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10736 props))
10737 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10738 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10739 string (if (equal key clockstr)
10740 (org-no-properties
10741 (org-trim
10742 (buffer-substring
10743 (match-beginning 3) (goto-char (point-at-eol)))))
10744 (substring (org-match-string-no-properties 3) 1 -1)))
10745 (unless key
10746 (if (= (char-after (match-beginning 3)) ?\[)
10747 (setq key "TIMESTAMP_IA")
10748 (setq key "TIMESTAMP")))
10749 (when (or (equal key clockstr) (not (assoc key props)))
10750 (push (cons key string) props)))
10754 (when (memq which '(all standard))
10755 ;; Get the standard properties, like :PORP: ...
10756 (setq range (org-get-property-block beg end))
10757 (when range
10758 (goto-char (car range))
10759 (while (re-search-forward
10760 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10761 (cdr range) t)
10762 (setq key (org-match-string-no-properties 1)
10763 value (org-trim (or (org-match-string-no-properties 2) "")))
10764 (unless (member key excluded)
10765 (push (cons key (or value "")) props)))))
10766 (if clocksum
10767 (push (cons "CLOCKSUM"
10768 (org-columns-number-to-string (/ (float clocksum) 60.)
10769 'add_times))
10770 props))
10771 (unless (assoc "CATEGORY" props)
10772 (setq value (or (org-get-category)
10773 (progn (org-refresh-category-properties)
10774 (org-get-category))))
10775 (push (cons "CATEGORY" value) props))
10776 (append sum-props (nreverse props)))))))
10778 (defun org-entry-get (pom property &optional inherit)
10779 "Get value of PROPERTY for entry at point-or-marker POM.
10780 If INHERIT is non-nil and the entry does not have the property,
10781 then also check higher levels of the hierarchy.
10782 If INHERIT is the symbol `selective', use inheritance only if the setting
10783 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10784 If the property is present but empty, the return value is the empty string.
10785 If the property is not present at all, nil is returned."
10786 (org-with-point-at pom
10787 (if (and inherit (if (eq inherit 'selective)
10788 (org-property-inherit-p property)
10790 (org-entry-get-with-inheritance property)
10791 (if (member property org-special-properties)
10792 ;; We need a special property. Use brute force, get all properties.
10793 (cdr (assoc property (org-entry-properties nil 'special)))
10794 (let ((range (org-get-property-block)))
10795 (if (and range
10796 (goto-char (car range))
10797 (re-search-forward
10798 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10799 (cdr range) t))
10800 ;; Found the property, return it.
10801 (if (match-end 1)
10802 (org-match-string-no-properties 1)
10803 "")))))))
10805 (defun org-property-or-variable-value (var &optional inherit)
10806 "Check if there is a property fixing the value of VAR.
10807 If yes, return this value. If not, return the current value of the variable."
10808 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10809 (if (and prop (stringp prop) (string-match "\\S-" prop))
10810 (read prop)
10811 (symbol-value var))))
10813 (defun org-entry-delete (pom property)
10814 "Delete the property PROPERTY from entry at point-or-marker POM."
10815 (org-with-point-at pom
10816 (if (member property org-special-properties)
10817 nil ; cannot delete these properties.
10818 (let ((range (org-get-property-block)))
10819 (if (and range
10820 (goto-char (car range))
10821 (re-search-forward
10822 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10823 (cdr range) t))
10824 (progn
10825 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10827 nil)))))
10829 ;; Multi-values properties are properties that contain multiple values
10830 ;; These values are assumed to be single words, separated by whitespace.
10831 (defun org-entry-add-to-multivalued-property (pom property value)
10832 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10833 (let* ((old (org-entry-get pom property))
10834 (values (and old (org-split-string old "[ \t]"))))
10835 (setq value (org-entry-protect-space value))
10836 (unless (member value values)
10837 (setq values (cons value values))
10838 (org-entry-put pom property
10839 (mapconcat 'identity values " ")))))
10841 (defun org-entry-remove-from-multivalued-property (pom property value)
10842 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10843 (let* ((old (org-entry-get pom property))
10844 (values (and old (org-split-string old "[ \t]"))))
10845 (setq value (org-entry-protect-space value))
10846 (when (member value values)
10847 (setq values (delete value values))
10848 (org-entry-put pom property
10849 (mapconcat 'identity values " ")))))
10851 (defun org-entry-member-in-multivalued-property (pom property value)
10852 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10853 (let* ((old (org-entry-get pom property))
10854 (values (and old (org-split-string old "[ \t]"))))
10855 (setq value (org-entry-protect-space value))
10856 (member value values)))
10858 (defun org-entry-get-multivalued-property (pom property)
10859 "Return a list of values in a multivalued property."
10860 (let* ((value (org-entry-get pom property))
10861 (values (and value (org-split-string value "[ \t]"))))
10862 (mapcar 'org-entry-restore-space values)))
10864 (defun org-entry-put-multivalued-property (pom property &rest values)
10865 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10866 VALUES should be a list of strings. Spaces will be protected."
10867 (org-entry-put pom property
10868 (mapconcat 'org-entry-protect-space values " "))
10869 (let* ((value (org-entry-get pom property))
10870 (values (and value (org-split-string value "[ \t]"))))
10871 (mapcar 'org-entry-restore-space values)))
10873 (defun org-entry-protect-space (s)
10874 "Protect spaces and newline in string S."
10875 (while (string-match " " s)
10876 (setq s (replace-match "%20" t t s)))
10877 (while (string-match "\n" s)
10878 (setq s (replace-match "%0A" t t s)))
10881 (defun org-entry-restore-space (s)
10882 "Restore spaces and newline in string S."
10883 (while (string-match "%20" s)
10884 (setq s (replace-match " " t t s)))
10885 (while (string-match "%0A" s)
10886 (setq s (replace-match "\n" t t s)))
10889 (defvar org-entry-property-inherited-from (make-marker)
10890 "Marker pointing to the entry from where a property was inherited.
10891 Each call to `org-entry-get-with-inheritance' will set this marker to the
10892 location of the entry where the inheritance search matched. If there was
10893 no match, the marker will point nowhere.
10894 Note that also `org-entry-get' calls this function, if the INHERIT flag
10895 is set.")
10897 (defun org-entry-get-with-inheritance (property)
10898 "Get entry property, and search higher levels if not present."
10899 (move-marker org-entry-property-inherited-from nil)
10900 (let (tmp)
10901 (save-excursion
10902 (save-restriction
10903 (widen)
10904 (catch 'ex
10905 (while t
10906 (when (setq tmp (org-entry-get nil property))
10907 (org-back-to-heading t)
10908 (move-marker org-entry-property-inherited-from (point))
10909 (throw 'ex tmp))
10910 (or (org-up-heading-safe) (throw 'ex nil)))))
10911 (or tmp
10912 (cdr (assoc property org-file-properties))
10913 (cdr (assoc property org-global-properties))
10914 (cdr (assoc property org-global-properties-fixed))))))
10916 (defun org-entry-put (pom property value)
10917 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10918 (org-with-point-at pom
10919 (org-back-to-heading t)
10920 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10921 range)
10922 (cond
10923 ((equal property "TODO")
10924 (when (and (stringp value) (string-match "\\S-" value)
10925 (not (member value org-todo-keywords-1)))
10926 (error "\"%s\" is not a valid TODO state" value))
10927 (if (or (not value)
10928 (not (string-match "\\S-" value)))
10929 (setq value 'none))
10930 (org-todo value)
10931 (org-set-tags nil 'align))
10932 ((equal property "PRIORITY")
10933 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10934 (string-to-char value) ?\ ))
10935 (org-set-tags nil 'align))
10936 ((equal property "SCHEDULED")
10937 (if (re-search-forward org-scheduled-time-regexp end t)
10938 (cond
10939 ((eq value 'earlier) (org-timestamp-change -1 'day))
10940 ((eq value 'later) (org-timestamp-change 1 'day))
10941 (t (call-interactively 'org-schedule)))
10942 (call-interactively 'org-schedule)))
10943 ((equal property "DEADLINE")
10944 (if (re-search-forward org-deadline-time-regexp end t)
10945 (cond
10946 ((eq value 'earlier) (org-timestamp-change -1 'day))
10947 ((eq value 'later) (org-timestamp-change 1 'day))
10948 (t (call-interactively 'org-deadline)))
10949 (call-interactively 'org-deadline)))
10950 ((member property org-special-properties)
10951 (error "The %s property can not yet be set with `org-entry-put'"
10952 property))
10953 (t ; a non-special property
10954 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10955 (setq range (org-get-property-block beg end 'force))
10956 (goto-char (car range))
10957 (if (re-search-forward
10958 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10959 (progn
10960 (delete-region (match-beginning 1) (match-end 1))
10961 (goto-char (match-beginning 1)))
10962 (goto-char (cdr range))
10963 (insert "\n")
10964 (backward-char 1)
10965 (org-indent-line-function)
10966 (insert ":" property ":"))
10967 (and value (insert " " value))
10968 (org-indent-line-function)))))))
10970 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10971 "Get all property keys in the current buffer.
10972 With INCLUDE-SPECIALS, also list the special properties that reflect things
10973 like tags and TODO state.
10974 With INCLUDE-DEFAULTS, also include properties that has special meaning
10975 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10976 With INCLUDE-COLUMNS, also include property names given in COLUMN
10977 formats in the current buffer."
10978 (let (rtn range cfmt s p)
10979 (save-excursion
10980 (save-restriction
10981 (widen)
10982 (goto-char (point-min))
10983 (while (re-search-forward org-property-start-re nil t)
10984 (setq range (org-get-property-block))
10985 (goto-char (car range))
10986 (while (re-search-forward
10987 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10988 (cdr range) t)
10989 (add-to-list 'rtn (org-match-string-no-properties 1)))
10990 (outline-next-heading))))
10992 (when include-specials
10993 (setq rtn (append org-special-properties rtn)))
10995 (when include-defaults
10996 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10998 (when include-columns
10999 (save-excursion
11000 (save-restriction
11001 (widen)
11002 (goto-char (point-min))
11003 (while (re-search-forward
11004 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11005 nil t)
11006 (setq cfmt (match-string 2) s 0)
11007 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11008 cfmt s)
11009 (setq s (match-end 0)
11010 p (match-string 1 cfmt))
11011 (unless (or (equal p "ITEM")
11012 (member p org-special-properties))
11013 (add-to-list 'rtn (match-string 1 cfmt))))))))
11015 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11017 (defun org-property-values (key)
11018 "Return a list of all values of property KEY."
11019 (save-excursion
11020 (save-restriction
11021 (widen)
11022 (goto-char (point-min))
11023 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11024 values)
11025 (while (re-search-forward re nil t)
11026 (add-to-list 'values (org-trim (match-string 1))))
11027 (delete "" values)))))
11029 (defun org-insert-property-drawer ()
11030 "Insert a property drawer into the current entry."
11031 (interactive)
11032 (org-back-to-heading t)
11033 (looking-at outline-regexp)
11034 (let ((indent (- (match-end 0)(match-beginning 0)))
11035 (beg (point))
11036 (re (concat "^[ \t]*" org-keyword-time-regexp))
11037 end hiddenp)
11038 (outline-next-heading)
11039 (setq end (point))
11040 (goto-char beg)
11041 (while (re-search-forward re end t))
11042 (setq hiddenp (org-invisible-p))
11043 (end-of-line 1)
11044 (and (equal (char-after) ?\n) (forward-char 1))
11045 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11046 (if (member (match-string 1) '("CLOCK:" ":END:"))
11047 ;; just skip this line
11048 (beginning-of-line 2)
11049 ;; Drawer start, find the end
11050 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11051 (beginning-of-line 1)))
11052 (org-skip-over-state-notes)
11053 (skip-chars-backward " \t\n\r")
11054 (if (eq (char-before) ?*) (forward-char 1))
11055 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11056 (beginning-of-line 0)
11057 (org-indent-to-column indent)
11058 (beginning-of-line 2)
11059 (org-indent-to-column indent)
11060 (beginning-of-line 0)
11061 (if hiddenp
11062 (save-excursion
11063 (org-back-to-heading t)
11064 (hide-entry))
11065 (org-flag-drawer t))))
11067 (defun org-set-property (property value)
11068 "In the current entry, set PROPERTY to VALUE.
11069 When called interactively, this will prompt for a property name, offering
11070 completion on existing and default properties. And then it will prompt
11071 for a value, offering completion either on allowed values (via an inherited
11072 xxx_ALL property) or on existing values in other instances of this property
11073 in the current file."
11074 (interactive
11075 (let* ((completion-ignore-case t)
11076 (keys (org-buffer-property-keys nil t t))
11077 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11078 (prop (if (member prop0 keys)
11079 prop0
11080 (or (cdr (assoc (downcase prop0)
11081 (mapcar (lambda (x) (cons (downcase x) x))
11082 keys)))
11083 prop0)))
11084 (cur (org-entry-get nil prop))
11085 (allowed (org-property-get-allowed-values nil prop 'table))
11086 (existing (mapcar 'list (org-property-values prop)))
11087 (val (if allowed
11088 (org-completing-read "Value: " allowed nil 'req-match)
11089 (let (org-completion-use-ido)
11090 (org-completing-read
11091 (concat "Value" (if (and cur (string-match "\\S-" cur))
11092 (concat "[" cur "]") "")
11093 ": ")
11094 existing nil nil "" nil cur)))))
11095 (list prop (if (equal val "") cur val))))
11096 (unless (equal (org-entry-get nil property) value)
11097 (org-entry-put nil property value)))
11099 (defun org-delete-property (property)
11100 "In the current entry, delete PROPERTY."
11101 (interactive
11102 (let* ((completion-ignore-case t)
11103 (prop (org-ido-completing-read
11104 "Property: " (org-entry-properties nil 'standard))))
11105 (list prop)))
11106 (message "Property %s %s" property
11107 (if (org-entry-delete nil property)
11108 "deleted"
11109 "was not present in the entry")))
11111 (defun org-delete-property-globally (property)
11112 "Remove PROPERTY globally, from all entries."
11113 (interactive
11114 (let* ((completion-ignore-case t)
11115 (prop (org-ido-completing-read
11116 "Globally remove property: "
11117 (mapcar 'list (org-buffer-property-keys)))))
11118 (list prop)))
11119 (save-excursion
11120 (save-restriction
11121 (widen)
11122 (goto-char (point-min))
11123 (let ((cnt 0))
11124 (while (re-search-forward
11125 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11126 nil t)
11127 (setq cnt (1+ cnt))
11128 (replace-match ""))
11129 (message "Property \"%s\" removed from %d entries" property cnt)))))
11131 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11133 (defun org-compute-property-at-point ()
11134 "Compute the property at point.
11135 This looks for an enclosing column format, extracts the operator and
11136 then applies it to the property in the column format's scope."
11137 (interactive)
11138 (unless (org-at-property-p)
11139 (error "Not at a property"))
11140 (let ((prop (org-match-string-no-properties 2)))
11141 (org-columns-get-format-and-top-level)
11142 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11143 (error "No operator defined for property %s" prop))
11144 (org-columns-compute prop)))
11146 (defun org-property-get-allowed-values (pom property &optional table)
11147 "Get allowed values for the property PROPERTY.
11148 When TABLE is non-nil, return an alist that can directly be used for
11149 completion."
11150 (let (vals)
11151 (cond
11152 ((equal property "TODO")
11153 (setq vals (org-with-point-at pom
11154 (append org-todo-keywords-1 '("")))))
11155 ((equal property "PRIORITY")
11156 (let ((n org-lowest-priority))
11157 (while (>= n org-highest-priority)
11158 (push (char-to-string n) vals)
11159 (setq n (1- n)))))
11160 ((member property org-special-properties))
11162 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11164 (when (and vals (string-match "\\S-" vals))
11165 (setq vals (car (read-from-string (concat "(" vals ")"))))
11166 (setq vals (mapcar (lambda (x)
11167 (cond ((stringp x) x)
11168 ((numberp x) (number-to-string x))
11169 ((symbolp x) (symbol-name x))
11170 (t "???")))
11171 vals)))))
11172 (if table (mapcar 'list vals) vals)))
11174 (defun org-property-previous-allowed-value (&optional previous)
11175 "Switch to the next allowed value for this property."
11176 (interactive)
11177 (org-property-next-allowed-value t))
11179 (defun org-property-next-allowed-value (&optional previous)
11180 "Switch to the next allowed value for this property."
11181 (interactive)
11182 (unless (org-at-property-p)
11183 (error "Not at a property"))
11184 (let* ((key (match-string 2))
11185 (value (match-string 3))
11186 (allowed (or (org-property-get-allowed-values (point) key)
11187 (and (member value '("[ ]" "[-]" "[X]"))
11188 '("[ ]" "[X]"))))
11189 nval)
11190 (unless allowed
11191 (error "Allowed values for this property have not been defined"))
11192 (if previous (setq allowed (reverse allowed)))
11193 (if (member value allowed)
11194 (setq nval (car (cdr (member value allowed)))))
11195 (setq nval (or nval (car allowed)))
11196 (if (equal nval value)
11197 (error "Only one allowed value for this property"))
11198 (org-at-property-p)
11199 (replace-match (concat " :" key ": " nval) t t)
11200 (org-indent-line-function)
11201 (beginning-of-line 1)
11202 (skip-chars-forward " \t")))
11204 (defun org-find-entry-with-id (ident)
11205 "Locate the entry that contains the ID property with exact value IDENT.
11206 IDENT can be a string, a symbol or a number, this function will search for
11207 the string representation of it.
11208 Return the position where this entry starts, or nil if there is no such entry."
11209 (interactive "sID: ")
11210 (let ((id (cond
11211 ((stringp ident) ident)
11212 ((symbol-name ident) (symbol-name ident))
11213 ((numberp ident) (number-to-string ident))
11214 (t (error "IDENT %s must be a string, symbol or number" ident))))
11215 (case-fold-search nil))
11216 (save-excursion
11217 (save-restriction
11218 (widen)
11219 (goto-char (point-min))
11220 (when (re-search-forward
11221 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11222 nil t)
11223 (org-back-to-heading)
11224 (point))))))
11226 ;;;; Timestamps
11228 (defvar org-last-changed-timestamp nil)
11229 (defvar org-last-inserted-timestamp nil
11230 "The last time stamp inserted with `org-insert-time-stamp'.")
11231 (defvar org-time-was-given) ; dynamically scoped parameter
11232 (defvar org-end-time-was-given) ; dynamically scoped parameter
11233 (defvar org-ts-what) ; dynamically scoped parameter
11235 (defun org-time-stamp (arg &optional inactive)
11236 "Prompt for a date/time and insert a time stamp.
11237 If the user specifies a time like HH:MM, or if this command is called
11238 with a prefix argument, the time stamp will contain date and time.
11239 Otherwise, only the date will be included. All parts of a date not
11240 specified by the user will be filled in from the current date/time.
11241 So if you press just return without typing anything, the time stamp
11242 will represent the current date/time. If there is already a timestamp
11243 at the cursor, it will be modified."
11244 (interactive "P")
11245 (let* ((ts nil)
11246 (default-time
11247 ;; Default time is either today, or, when entering a range,
11248 ;; the range start.
11249 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11250 (save-excursion
11251 (re-search-backward
11252 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11253 (- (point) 20) t)))
11254 (apply 'encode-time (org-parse-time-string (match-string 1)))
11255 (current-time)))
11256 (default-input (and ts (org-get-compact-tod ts)))
11257 org-time-was-given org-end-time-was-given time)
11258 (cond
11259 ((and (org-at-timestamp-p t)
11260 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11261 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11262 (insert "--")
11263 (setq time (let ((this-command this-command))
11264 (org-read-date arg 'totime nil nil
11265 default-time default-input)))
11266 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11267 ((org-at-timestamp-p t)
11268 (setq time (let ((this-command this-command))
11269 (org-read-date arg 'totime nil nil default-time default-input)))
11270 (when (org-at-timestamp-p t) ; just to get the match data
11271 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11272 (replace-match "")
11273 (setq org-last-changed-timestamp
11274 (org-insert-time-stamp
11275 time (or org-time-was-given arg)
11276 inactive nil nil (list org-end-time-was-given))))
11277 (message "Timestamp updated"))
11279 (setq time (let ((this-command this-command))
11280 (org-read-date arg 'totime nil nil default-time default-input)))
11281 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11282 nil nil (list org-end-time-was-given))))))
11284 ;; FIXME: can we use this for something else, like computing time differences?
11285 (defun org-get-compact-tod (s)
11286 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11287 (let* ((t1 (match-string 1 s))
11288 (h1 (string-to-number (match-string 2 s)))
11289 (m1 (string-to-number (match-string 3 s)))
11290 (t2 (and (match-end 4) (match-string 5 s)))
11291 (h2 (and t2 (string-to-number (match-string 6 s))))
11292 (m2 (and t2 (string-to-number (match-string 7 s))))
11293 dh dm)
11294 (if (not t2)
11296 (setq dh (- h2 h1) dm (- m2 m1))
11297 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11298 (concat t1 "+" (number-to-string dh)
11299 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11301 (defun org-time-stamp-inactive (&optional arg)
11302 "Insert an inactive time stamp.
11303 An inactive time stamp is enclosed in square brackets instead of angle
11304 brackets. It is inactive in the sense that it does not trigger agenda entries,
11305 does not link to the calendar and cannot be changed with the S-cursor keys.
11306 So these are more for recording a certain time/date."
11307 (interactive "P")
11308 (org-time-stamp arg 'inactive))
11310 (defvar org-date-ovl (org-make-overlay 1 1))
11311 (org-overlay-put org-date-ovl 'face 'org-warning)
11312 (org-detach-overlay org-date-ovl)
11314 (defvar org-ans1) ; dynamically scoped parameter
11315 (defvar org-ans2) ; dynamically scoped parameter
11317 (defvar org-plain-time-of-day-regexp) ; defined below
11319 (defvar org-overriding-default-time nil) ; dynamically scoped
11320 (defvar org-read-date-overlay nil)
11321 (defvar org-dcst nil) ; dynamically scoped
11323 (defun org-read-date (&optional with-time to-time from-string prompt
11324 default-time default-input)
11325 "Read a date, possibly a time, and make things smooth for the user.
11326 The prompt will suggest to enter an ISO date, but you can also enter anything
11327 which will at least partially be understood by `parse-time-string'.
11328 Unrecognized parts of the date will default to the current day, month, year,
11329 hour and minute. If this command is called to replace a timestamp at point,
11330 of to enter the second timestamp of a range, the default time is taken from the
11331 existing stamp. For example,
11332 3-2-5 --> 2003-02-05
11333 feb 15 --> currentyear-02-15
11334 sep 12 9 --> 2009-09-12
11335 12:45 --> today 12:45
11336 22 sept 0:34 --> currentyear-09-22 0:34
11337 12 --> currentyear-currentmonth-12
11338 Fri --> nearest Friday (today or later)
11339 etc.
11341 Furthermore you can specify a relative date by giving, as the *first* thing
11342 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11343 change in days weeks, months, years.
11344 With a single plus or minus, the date is relative to today. With a double
11345 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11346 +4d --> four days from today
11347 +4 --> same as above
11348 +2w --> two weeks from today
11349 ++5 --> five days from default date
11351 The function understands only English month and weekday abbreviations,
11352 but this can be configured with the variables `parse-time-months' and
11353 `parse-time-weekdays'.
11355 While prompting, a calendar is popped up - you can also select the
11356 date with the mouse (button 1). The calendar shows a period of three
11357 months. To scroll it to other months, use the keys `>' and `<'.
11358 If you don't like the calendar, turn it off with
11359 \(setq org-read-date-popup-calendar nil)
11361 With optional argument TO-TIME, the date will immediately be converted
11362 to an internal time.
11363 With an optional argument WITH-TIME, the prompt will suggest to also
11364 insert a time. Note that when WITH-TIME is not set, you can still
11365 enter a time, and this function will inform the calling routine about
11366 this change. The calling routine may then choose to change the format
11367 used to insert the time stamp into the buffer to include the time.
11368 With optional argument FROM-STRING, read from this string instead from
11369 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11370 the time/date that is used for everything that is not specified by the
11371 user."
11372 (require 'parse-time)
11373 (let* ((org-time-stamp-rounding-minutes
11374 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11375 (org-dcst org-display-custom-times)
11376 (ct (org-current-time))
11377 (def (or org-overriding-default-time default-time ct))
11378 (defdecode (decode-time def))
11379 (dummy (progn
11380 (when (< (nth 2 defdecode) org-extend-today-until)
11381 (setcar (nthcdr 2 defdecode) -1)
11382 (setcar (nthcdr 1 defdecode) 59)
11383 (setq def (apply 'encode-time defdecode)
11384 defdecode (decode-time def)))))
11385 (calendar-move-hook nil)
11386 (calendar-view-diary-initially-flag nil)
11387 (view-diary-entries-initially nil)
11388 (calendar-view-holidays-initially-flag nil)
11389 (view-calendar-holidays-initially nil)
11390 (timestr (format-time-string
11391 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11392 (prompt (concat (if prompt (concat prompt " ") "")
11393 (format "Date+time [%s]: " timestr)))
11394 ans (org-ans0 "") org-ans1 org-ans2 final)
11396 (cond
11397 (from-string (setq ans from-string))
11398 (org-read-date-popup-calendar
11399 (save-excursion
11400 (save-window-excursion
11401 (calendar)
11402 (calendar-forward-day (- (time-to-days def)
11403 (calendar-absolute-from-gregorian
11404 (calendar-current-date))))
11405 (org-eval-in-calendar nil t)
11406 (let* ((old-map (current-local-map))
11407 (map (copy-keymap calendar-mode-map))
11408 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11409 (org-defkey map (kbd "RET") 'org-calendar-select)
11410 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11411 'org-calendar-select-mouse)
11412 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11413 'org-calendar-select-mouse)
11414 (org-defkey minibuffer-local-map [(meta shift left)]
11415 (lambda () (interactive)
11416 (org-eval-in-calendar '(calendar-backward-month 1))))
11417 (org-defkey minibuffer-local-map [(meta shift right)]
11418 (lambda () (interactive)
11419 (org-eval-in-calendar '(calendar-forward-month 1))))
11420 (org-defkey minibuffer-local-map [(meta shift up)]
11421 (lambda () (interactive)
11422 (org-eval-in-calendar '(calendar-backward-year 1))))
11423 (org-defkey minibuffer-local-map [(meta shift down)]
11424 (lambda () (interactive)
11425 (org-eval-in-calendar '(calendar-forward-year 1))))
11426 (org-defkey minibuffer-local-map [(shift up)]
11427 (lambda () (interactive)
11428 (org-eval-in-calendar '(calendar-backward-week 1))))
11429 (org-defkey minibuffer-local-map [(shift down)]
11430 (lambda () (interactive)
11431 (org-eval-in-calendar '(calendar-forward-week 1))))
11432 (org-defkey minibuffer-local-map [(shift left)]
11433 (lambda () (interactive)
11434 (org-eval-in-calendar '(calendar-backward-day 1))))
11435 (org-defkey minibuffer-local-map [(shift right)]
11436 (lambda () (interactive)
11437 (org-eval-in-calendar '(calendar-forward-day 1))))
11438 (org-defkey minibuffer-local-map ">"
11439 (lambda () (interactive)
11440 (org-eval-in-calendar '(scroll-calendar-left 1))))
11441 (org-defkey minibuffer-local-map "<"
11442 (lambda () (interactive)
11443 (org-eval-in-calendar '(scroll-calendar-right 1))))
11444 (unwind-protect
11445 (progn
11446 (use-local-map map)
11447 (add-hook 'post-command-hook 'org-read-date-display)
11448 (setq org-ans0 (read-string prompt default-input nil nil))
11449 ;; org-ans0: from prompt
11450 ;; org-ans1: from mouse click
11451 ;; org-ans2: from calendar motion
11452 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11453 (remove-hook 'post-command-hook 'org-read-date-display)
11454 (use-local-map old-map)
11455 (when org-read-date-overlay
11456 (org-delete-overlay org-read-date-overlay)
11457 (setq org-read-date-overlay nil)))))))
11459 (t ; Naked prompt only
11460 (unwind-protect
11461 (setq ans (read-string prompt default-input nil timestr))
11462 (when org-read-date-overlay
11463 (org-delete-overlay org-read-date-overlay)
11464 (setq org-read-date-overlay nil)))))
11466 (setq final (org-read-date-analyze ans def defdecode))
11468 (if to-time
11469 (apply 'encode-time final)
11470 (if (and (boundp 'org-time-was-given) org-time-was-given)
11471 (format "%04d-%02d-%02d %02d:%02d"
11472 (nth 5 final) (nth 4 final) (nth 3 final)
11473 (nth 2 final) (nth 1 final))
11474 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11475 (defvar def)
11476 (defvar defdecode)
11477 (defvar with-time)
11478 (defun org-read-date-display ()
11479 "Display the current date prompt interpretation in the minibuffer."
11480 (when org-read-date-display-live
11481 (when org-read-date-overlay
11482 (org-delete-overlay org-read-date-overlay))
11483 (let ((p (point)))
11484 (end-of-line 1)
11485 (while (not (equal (buffer-substring
11486 (max (point-min) (- (point) 4)) (point))
11487 " "))
11488 (insert " "))
11489 (goto-char p))
11490 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11491 " " (or org-ans1 org-ans2)))
11492 (org-end-time-was-given nil)
11493 (f (org-read-date-analyze ans def defdecode))
11494 (fmts (if org-dcst
11495 org-time-stamp-custom-formats
11496 org-time-stamp-formats))
11497 (fmt (if (or with-time
11498 (and (boundp 'org-time-was-given) org-time-was-given))
11499 (cdr fmts)
11500 (car fmts)))
11501 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11502 (when (and org-end-time-was-given
11503 (string-match org-plain-time-of-day-regexp txt))
11504 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11505 org-end-time-was-given
11506 (substring txt (match-end 0)))))
11507 (setq org-read-date-overlay
11508 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11509 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11511 (defun org-read-date-analyze (ans def defdecode)
11512 "Analyse the combined answer of the date prompt."
11513 ;; FIXME: cleanup and comment
11514 (let (delta deltan deltaw deltadef year month day
11515 hour minute second wday pm h2 m2 tl wday1
11516 iso-year iso-weekday iso-week iso-year iso-date)
11518 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11519 (setq ans "+0"))
11521 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11522 (setq ans (replace-match "" t t ans)
11523 deltan (car delta)
11524 deltaw (nth 1 delta)
11525 deltadef (nth 2 delta)))
11527 ;; Check if there is an iso week date in there
11528 ;; If yes, sore the info and postpone interpreting it until the rest
11529 ;; of the parsing is done
11530 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11531 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11532 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11533 iso-week (string-to-number (match-string 2 ans)))
11534 (setq ans (replace-match "" t t ans)))
11536 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11537 (when (string-match
11538 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11539 (setq year (if (match-end 2)
11540 (string-to-number (match-string 2 ans))
11541 (string-to-number (format-time-string "%Y")))
11542 month (string-to-number (match-string 3 ans))
11543 day (string-to-number (match-string 4 ans)))
11544 (if (< year 100) (setq year (+ 2000 year)))
11545 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11546 t nil ans)))
11547 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11548 ;; If there is a time with am/pm, and *no* time without it, we convert
11549 ;; so that matching will be successful.
11550 (loop for i from 1 to 2 do ; twice, for end time as well
11551 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11552 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11553 (setq hour (string-to-number (match-string 1 ans))
11554 minute (if (match-end 3)
11555 (string-to-number (match-string 3 ans))
11557 pm (equal ?p
11558 (string-to-char (downcase (match-string 4 ans)))))
11559 (if (and (= hour 12) (not pm))
11560 (setq hour 0)
11561 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11562 (setq ans (replace-match (format "%02d:%02d" hour minute)
11563 t t ans))))
11565 ;; Check if a time range is given as a duration
11566 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11567 (setq hour (string-to-number (match-string 1 ans))
11568 h2 (+ hour (string-to-number (match-string 3 ans)))
11569 minute (string-to-number (match-string 2 ans))
11570 m2 (+ minute (if (match-end 5) (string-to-number
11571 (match-string 5 ans))0)))
11572 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11573 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11574 t t ans)))
11576 ;; Check if there is a time range
11577 (when (boundp 'org-end-time-was-given)
11578 (setq org-time-was-given nil)
11579 (when (and (string-match org-plain-time-of-day-regexp ans)
11580 (match-end 8))
11581 (setq org-end-time-was-given (match-string 8 ans))
11582 (setq ans (concat (substring ans 0 (match-beginning 7))
11583 (substring ans (match-end 7))))))
11585 (setq tl (parse-time-string ans)
11586 day (or (nth 3 tl) (nth 3 defdecode))
11587 month (or (nth 4 tl)
11588 (if (and org-read-date-prefer-future
11589 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11590 (1+ (nth 4 defdecode))
11591 (nth 4 defdecode)))
11592 year (or (nth 5 tl)
11593 (if (and org-read-date-prefer-future
11594 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11595 (1+ (nth 5 defdecode))
11596 (nth 5 defdecode)))
11597 hour (or (nth 2 tl) (nth 2 defdecode))
11598 minute (or (nth 1 tl) (nth 1 defdecode))
11599 second (or (nth 0 tl) 0)
11600 wday (nth 6 tl))
11602 ;; Special date definitions below
11603 (cond
11604 (iso-week
11605 ;; There was an iso week
11606 (setq year (or iso-year year)
11607 day (or iso-weekday wday 1)
11608 wday nil ; to make sure that the trigger below does not match
11609 iso-date (calendar-gregorian-from-absolute
11610 (calendar-absolute-from-iso
11611 (list iso-week day year))))
11612 ; FIXME: Should we also push ISO weeks into the future?
11613 ; (when (and org-read-date-prefer-future
11614 ; (not iso-year)
11615 ; (< (calendar-absolute-from-gregorian iso-date)
11616 ; (time-to-days (current-time))))
11617 ; (setq year (1+ year)
11618 ; iso-date (calendar-gregorian-from-absolute
11619 ; (calendar-absolute-from-iso
11620 ; (list iso-week day year)))))
11621 (setq month (car iso-date)
11622 year (nth 2 iso-date)
11623 day (nth 1 iso-date)))
11624 (deltan
11625 (unless deltadef
11626 (let ((now (decode-time (current-time))))
11627 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11628 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11629 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11630 ((equal deltaw "m") (setq month (+ month deltan)))
11631 ((equal deltaw "y") (setq year (+ year deltan)))))
11632 ((and wday (not (nth 3 tl)))
11633 ;; Weekday was given, but no day, so pick that day in the week
11634 ;; on or after the derived date.
11635 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11636 (unless (equal wday wday1)
11637 (setq day (+ day (% (- wday wday1 -7) 7))))))
11638 (if (and (boundp 'org-time-was-given)
11639 (nth 2 tl))
11640 (setq org-time-was-given t))
11641 (if (< year 100) (setq year (+ 2000 year)))
11642 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11643 (list second minute hour day month year)))
11645 (defvar parse-time-weekdays)
11647 (defun org-read-date-get-relative (s today default)
11648 "Check string S for special relative date string.
11649 TODAY and DEFAULT are internal times, for today and for a default.
11650 Return shift list (N what def-flag)
11651 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11652 N is the number of WHATs to shift.
11653 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11654 the DEFAULT date rather than TODAY."
11655 (when (and
11656 (string-match
11657 (concat
11658 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11659 "\\([0-9]+\\)?"
11660 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11661 "\\([ \t]\\|$\\)") s)
11662 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11663 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11664 (string-to-char (substring (match-string 1 s) -1))
11665 ?+))
11666 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11667 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11668 (what (if (match-end 3) (match-string 3 s) "d"))
11669 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11670 (date (if rel default today))
11671 (wday (nth 6 (decode-time date)))
11672 delta)
11673 (if wday1
11674 (progn
11675 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11676 (if (= dir ?-) (setq delta (- delta 7)))
11677 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11678 (list delta "d" rel))
11679 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11681 (defun org-eval-in-calendar (form &optional keepdate)
11682 "Eval FORM in the calendar window and return to current window.
11683 Also, store the cursor date in variable org-ans2."
11684 (let ((sw (selected-window)))
11685 (select-window (get-buffer-window "*Calendar*"))
11686 (eval form)
11687 (when (and (not keepdate) (calendar-cursor-to-date))
11688 (let* ((date (calendar-cursor-to-date))
11689 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11690 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11691 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11692 (select-window sw)))
11694 (defun org-calendar-select ()
11695 "Return to `org-read-date' with the date currently selected.
11696 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11697 (interactive)
11698 (when (calendar-cursor-to-date)
11699 (let* ((date (calendar-cursor-to-date))
11700 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11701 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11702 (if (active-minibuffer-window) (exit-minibuffer))))
11704 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11705 "Insert a date stamp for the date given by the internal TIME.
11706 WITH-HM means, use the stamp format that includes the time of the day.
11707 INACTIVE means use square brackets instead of angular ones, so that the
11708 stamp will not contribute to the agenda.
11709 PRE and POST are optional strings to be inserted before and after the
11710 stamp.
11711 The command returns the inserted time stamp."
11712 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11713 stamp)
11714 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11715 (insert-before-markers (or pre ""))
11716 (insert-before-markers (setq stamp (format-time-string fmt time)))
11717 (when (listp extra)
11718 (setq extra (car extra))
11719 (if (and (stringp extra)
11720 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11721 (setq extra (format "-%02d:%02d"
11722 (string-to-number (match-string 1 extra))
11723 (string-to-number (match-string 2 extra))))
11724 (setq extra nil)))
11725 (when extra
11726 (backward-char 1)
11727 (insert-before-markers extra)
11728 (forward-char 1))
11729 (insert-before-markers (or post ""))
11730 (setq org-last-inserted-timestamp stamp)))
11732 (defun org-toggle-time-stamp-overlays ()
11733 "Toggle the use of custom time stamp formats."
11734 (interactive)
11735 (setq org-display-custom-times (not org-display-custom-times))
11736 (unless org-display-custom-times
11737 (let ((p (point-min)) (bmp (buffer-modified-p)))
11738 (while (setq p (next-single-property-change p 'display))
11739 (if (and (get-text-property p 'display)
11740 (eq (get-text-property p 'face) 'org-date))
11741 (remove-text-properties
11742 p (setq p (next-single-property-change p 'display))
11743 '(display t))))
11744 (set-buffer-modified-p bmp)))
11745 (if (featurep 'xemacs)
11746 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11747 (org-restart-font-lock)
11748 (setq org-table-may-need-update t)
11749 (if org-display-custom-times
11750 (message "Time stamps are overlayed with custom format")
11751 (message "Time stamp overlays removed")))
11753 (defun org-display-custom-time (beg end)
11754 "Overlay modified time stamp format over timestamp between BEG and END."
11755 (let* ((ts (buffer-substring beg end))
11756 t1 w1 with-hm tf time str w2 (off 0))
11757 (save-match-data
11758 (setq t1 (org-parse-time-string ts t))
11759 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11760 (setq off (- (match-end 0) (match-beginning 0)))))
11761 (setq end (- end off))
11762 (setq w1 (- end beg)
11763 with-hm (and (nth 1 t1) (nth 2 t1))
11764 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11765 time (org-fix-decoded-time t1)
11766 str (org-add-props
11767 (format-time-string
11768 (substring tf 1 -1) (apply 'encode-time time))
11769 nil 'mouse-face 'highlight)
11770 w2 (length str))
11771 (if (not (= w2 w1))
11772 (add-text-properties (1+ beg) (+ 2 beg)
11773 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11774 (if (featurep 'xemacs)
11775 (progn
11776 (put-text-property beg end 'invisible t)
11777 (put-text-property beg end 'end-glyph (make-glyph str)))
11778 (put-text-property beg end 'display str))))
11780 (defun org-translate-time (string)
11781 "Translate all timestamps in STRING to custom format.
11782 But do this only if the variable `org-display-custom-times' is set."
11783 (when org-display-custom-times
11784 (save-match-data
11785 (let* ((start 0)
11786 (re org-ts-regexp-both)
11787 t1 with-hm inactive tf time str beg end)
11788 (while (setq start (string-match re string start))
11789 (setq beg (match-beginning 0)
11790 end (match-end 0)
11791 t1 (save-match-data
11792 (org-parse-time-string (substring string beg end) t))
11793 with-hm (and (nth 1 t1) (nth 2 t1))
11794 inactive (equal (substring string beg (1+ beg)) "[")
11795 tf (funcall (if with-hm 'cdr 'car)
11796 org-time-stamp-custom-formats)
11797 time (org-fix-decoded-time t1)
11798 str (format-time-string
11799 (concat
11800 (if inactive "[" "<") (substring tf 1 -1)
11801 (if inactive "]" ">"))
11802 (apply 'encode-time time))
11803 string (replace-match str t t string)
11804 start (+ start (length str)))))))
11805 string)
11807 (defun org-fix-decoded-time (time)
11808 "Set 0 instead of nil for the first 6 elements of time.
11809 Don't touch the rest."
11810 (let ((n 0))
11811 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11813 (defun org-days-to-time (timestamp-string)
11814 "Difference between TIMESTAMP-STRING and now in days."
11815 (- (time-to-days (org-time-string-to-time timestamp-string))
11816 (time-to-days (current-time))))
11818 (defun org-deadline-close (timestamp-string &optional ndays)
11819 "Is the time in TIMESTAMP-STRING close to the current date?"
11820 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11821 (and (< (org-days-to-time timestamp-string) ndays)
11822 (not (org-entry-is-done-p))))
11824 (defun org-get-wdays (ts)
11825 "Get the deadline lead time appropriate for timestring TS."
11826 (cond
11827 ((<= org-deadline-warning-days 0)
11828 ;; 0 or negative, enforce this value no matter what
11829 (- org-deadline-warning-days))
11830 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
11831 ;; lead time is specified.
11832 (floor (* (string-to-number (match-string 1 ts))
11833 (cdr (assoc (match-string 2 ts)
11834 '(("d" . 1) ("w" . 7)
11835 ("m" . 30.4) ("y" . 365.25)))))))
11836 ;; go for the default.
11837 (t org-deadline-warning-days)))
11839 (defun org-calendar-select-mouse (ev)
11840 "Return to `org-read-date' with the date currently selected.
11841 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11842 (interactive "e")
11843 (mouse-set-point ev)
11844 (when (calendar-cursor-to-date)
11845 (let* ((date (calendar-cursor-to-date))
11846 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11847 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11848 (if (active-minibuffer-window) (exit-minibuffer))))
11850 (defun org-check-deadlines (ndays)
11851 "Check if there are any deadlines due or past due.
11852 A deadline is considered due if it happens within `org-deadline-warning-days'
11853 days from today's date. If the deadline appears in an entry marked DONE,
11854 it is not shown. The prefix arg NDAYS can be used to test that many
11855 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11856 (interactive "P")
11857 (let* ((org-warn-days
11858 (cond
11859 ((equal ndays '(4)) 100000)
11860 (ndays (prefix-numeric-value ndays))
11861 (t (abs org-deadline-warning-days))))
11862 (case-fold-search nil)
11863 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11864 (callback
11865 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11867 (message "%d deadlines past-due or due within %d days"
11868 (org-occur regexp nil callback)
11869 org-warn-days)))
11871 (defun org-check-before-date (date)
11872 "Check if there are deadlines or scheduled entries before DATE."
11873 (interactive (list (org-read-date)))
11874 (let ((case-fold-search nil)
11875 (regexp (concat "\\<\\(" org-deadline-string
11876 "\\|" org-scheduled-string
11877 "\\) *<\\([^>]+\\)>"))
11878 (callback
11879 (lambda () (time-less-p
11880 (org-time-string-to-time (match-string 2))
11881 (org-time-string-to-time date)))))
11882 (message "%d entries before %s"
11883 (org-occur regexp nil callback) date)))
11885 (defun org-evaluate-time-range (&optional to-buffer)
11886 "Evaluate a time range by computing the difference between start and end.
11887 Normally the result is just printed in the echo area, but with prefix arg
11888 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11889 If the time range is actually in a table, the result is inserted into the
11890 next column.
11891 For time difference computation, a year is assumed to be exactly 365
11892 days in order to avoid rounding problems."
11893 (interactive "P")
11895 (org-clock-update-time-maybe)
11896 (save-excursion
11897 (unless (org-at-date-range-p t)
11898 (goto-char (point-at-bol))
11899 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11900 (if (not (org-at-date-range-p t))
11901 (error "Not at a time-stamp range, and none found in current line")))
11902 (let* ((ts1 (match-string 1))
11903 (ts2 (match-string 2))
11904 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11905 (match-end (match-end 0))
11906 (time1 (org-time-string-to-time ts1))
11907 (time2 (org-time-string-to-time ts2))
11908 (t1 (time-to-seconds time1))
11909 (t2 (time-to-seconds time2))
11910 (diff (abs (- t2 t1)))
11911 (negative (< (- t2 t1) 0))
11912 ;; (ys (floor (* 365 24 60 60)))
11913 (ds (* 24 60 60))
11914 (hs (* 60 60))
11915 (fy "%dy %dd %02d:%02d")
11916 (fy1 "%dy %dd")
11917 (fd "%dd %02d:%02d")
11918 (fd1 "%dd")
11919 (fh "%02d:%02d")
11920 y d h m align)
11921 (if havetime
11922 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11924 d (floor (/ diff ds)) diff (mod diff ds)
11925 h (floor (/ diff hs)) diff (mod diff hs)
11926 m (floor (/ diff 60)))
11927 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11929 d (floor (+ (/ diff ds) 0.5))
11930 h 0 m 0))
11931 (if (not to-buffer)
11932 (message "%s" (org-make-tdiff-string y d h m))
11933 (if (org-at-table-p)
11934 (progn
11935 (goto-char match-end)
11936 (setq align t)
11937 (and (looking-at " *|") (goto-char (match-end 0))))
11938 (goto-char match-end))
11939 (if (looking-at
11940 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11941 (replace-match ""))
11942 (if negative (insert " -"))
11943 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11944 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11945 (insert " " (format fh h m))))
11946 (if align (org-table-align))
11947 (message "Time difference inserted")))))
11949 (defun org-make-tdiff-string (y d h m)
11950 (let ((fmt "")
11951 (l nil))
11952 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11953 l (push y l)))
11954 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11955 l (push d l)))
11956 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11957 l (push h l)))
11958 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11959 l (push m l)))
11960 (apply 'format fmt (nreverse l))))
11962 (defun org-time-string-to-time (s)
11963 (apply 'encode-time (org-parse-time-string s)))
11965 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11966 "Convert a time stamp to an absolute day number.
11967 If there is a specifyer for a cyclic time stamp, get the closest date to
11968 DAYNR.
11969 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11970 (cond
11971 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11972 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11973 daynr
11974 (+ daynr 1000)))
11975 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11976 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11977 (time-to-days (current-time))) (match-string 0 s)
11978 prefer show-all))
11979 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11981 (defun org-days-to-iso-week (days)
11982 "Return the iso week number."
11983 (require 'cal-iso)
11984 (car (calendar-iso-from-absolute days)))
11986 (defun org-small-year-to-year (year)
11987 "Convert 2-digit years into 4-digit years.
11988 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11989 The year 2000 cannot be abbreviated. Any year larger than 99
11990 is returned unchanged."
11991 (if (< year 38)
11992 (setq year (+ 2000 year))
11993 (if (< year 100)
11994 (setq year (+ 1900 year))))
11995 year)
11997 (defun org-time-from-absolute (d)
11998 "Return the time corresponding to date D.
11999 D may be an absolute day number, or a calendar-type list (month day year)."
12000 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12001 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12003 (defun org-calendar-holiday ()
12004 "List of holidays, for Diary display in Org-mode."
12005 (require 'holidays)
12006 (let ((hl (funcall
12007 (if (fboundp 'calendar-check-holidays)
12008 'calendar-check-holidays 'check-calendar-holidays) date)))
12009 (if hl (mapconcat 'identity hl "; "))))
12011 (defun org-diary-sexp-entry (sexp entry date)
12012 "Process a SEXP diary ENTRY for DATE."
12013 (require 'diary-lib)
12014 (let ((result (if calendar-debug-sexp
12015 (let ((stack-trace-on-error t))
12016 (eval (car (read-from-string sexp))))
12017 (condition-case nil
12018 (eval (car (read-from-string sexp)))
12019 (error
12020 (beep)
12021 (message "Bad sexp at line %d in %s: %s"
12022 (org-current-line)
12023 (buffer-file-name) sexp)
12024 (sleep-for 2))))))
12025 (cond ((stringp result) result)
12026 ((and (consp result)
12027 (stringp (cdr result))) (cdr result))
12028 (result entry)
12029 (t nil))))
12031 (defun org-diary-to-ical-string (frombuf)
12032 "Get iCalendar entries from diary entries in buffer FROMBUF.
12033 This uses the icalendar.el library."
12034 (let* ((tmpdir (if (featurep 'xemacs)
12035 (temp-directory)
12036 temporary-file-directory))
12037 (tmpfile (make-temp-name
12038 (expand-file-name "orgics" tmpdir)))
12039 buf rtn b e)
12040 (save-excursion
12041 (set-buffer frombuf)
12042 (icalendar-export-region (point-min) (point-max) tmpfile)
12043 (setq buf (find-buffer-visiting tmpfile))
12044 (set-buffer buf)
12045 (goto-char (point-min))
12046 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12047 (setq b (match-beginning 0)))
12048 (goto-char (point-max))
12049 (if (re-search-backward "^END:VEVENT" nil t)
12050 (setq e (match-end 0)))
12051 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12052 (kill-buffer buf)
12053 (delete-file tmpfile)
12054 rtn))
12056 (defun org-closest-date (start current change prefer show-all)
12057 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12058 When PREFER is `past' return a date that is either CURRENT or past.
12059 When PREFER is `future', return a date that is either CURRENT or future.
12060 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12061 ;; Make the proper lists from the dates
12062 (catch 'exit
12063 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12064 dn dw sday cday n1 n2 n0
12065 d m y y1 y2 date1 date2 nmonths nm ny m2)
12067 (setq start (org-date-to-gregorian start)
12068 current (org-date-to-gregorian
12069 (if show-all
12070 current
12071 (time-to-days (current-time))))
12072 sday (calendar-absolute-from-gregorian start)
12073 cday (calendar-absolute-from-gregorian current))
12075 (if (<= cday sday) (throw 'exit sday))
12077 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12078 (setq dn (string-to-number (match-string 1 change))
12079 dw (cdr (assoc (match-string 2 change) a1)))
12080 (error "Invalid change specifyer: %s" change))
12081 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12082 (cond
12083 ((eq dw 'day)
12084 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12085 n2 (+ n1 dn)))
12086 ((eq dw 'year)
12087 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12088 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12089 (setq date1 (list m d y1)
12090 n1 (calendar-absolute-from-gregorian date1)
12091 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12092 n2 (calendar-absolute-from-gregorian date2)))
12093 ((eq dw 'month)
12094 ;; approx number of month between the two dates
12095 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12096 ;; How often does dn fit in there?
12097 (setq d (nth 1 start) m (car start) y (nth 2 start)
12098 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12099 m (+ m nm)
12100 ny (floor (/ m 12))
12101 y (+ y ny)
12102 m (- m (* ny 12)))
12103 (while (> m 12) (setq m (- m 12) y (1+ y)))
12104 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12105 (setq m2 (+ m dn) y2 y)
12106 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12107 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12108 (while (<= n2 cday)
12109 (setq n1 n2 m m2 y y2)
12110 (setq m2 (+ m dn) y2 y)
12111 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12112 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12113 ;; Make sure n1 is the earlier date
12114 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12115 (if show-all
12116 (cond
12117 ((eq prefer 'past) n1)
12118 ((eq prefer 'future) (if (= cday n1) n1 n2))
12119 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12120 (cond
12121 ((eq prefer 'past) n1)
12122 ((eq prefer 'future) (if (= cday n1) n1 n2))
12123 (t (if (= cday n1) n1 n2)))))))
12125 (defun org-date-to-gregorian (date)
12126 "Turn any specification of DATE into a gregorian date for the calendar."
12127 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12128 ((and (listp date) (= (length date) 3)) date)
12129 ((stringp date)
12130 (setq date (org-parse-time-string date))
12131 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12132 ((listp date)
12133 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12135 (defun org-parse-time-string (s &optional nodefault)
12136 "Parse the standard Org-mode time string.
12137 This should be a lot faster than the normal `parse-time-string'.
12138 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12139 hour and minute fields will be nil if not given."
12140 (if (string-match org-ts-regexp0 s)
12141 (list 0
12142 (if (or (match-beginning 8) (not nodefault))
12143 (string-to-number (or (match-string 8 s) "0")))
12144 (if (or (match-beginning 7) (not nodefault))
12145 (string-to-number (or (match-string 7 s) "0")))
12146 (string-to-number (match-string 4 s))
12147 (string-to-number (match-string 3 s))
12148 (string-to-number (match-string 2 s))
12149 nil nil nil)
12150 (make-list 9 0)))
12152 (defun org-timestamp-up (&optional arg)
12153 "Increase the date item at the cursor by one.
12154 If the cursor is on the year, change the year. If it is on the month or
12155 the day, change that.
12156 With prefix ARG, change by that many units."
12157 (interactive "p")
12158 (org-timestamp-change (prefix-numeric-value arg)))
12160 (defun org-timestamp-down (&optional arg)
12161 "Decrease the date item at the cursor by one.
12162 If the cursor is on the year, change the year. If it is on the month or
12163 the day, change that.
12164 With prefix ARG, change by that many units."
12165 (interactive "p")
12166 (org-timestamp-change (- (prefix-numeric-value arg))))
12168 (defun org-timestamp-up-day (&optional arg)
12169 "Increase the date in the time stamp by one day.
12170 With prefix ARG, change that many days."
12171 (interactive "p")
12172 (if (and (not (org-at-timestamp-p t))
12173 (org-on-heading-p))
12174 (org-todo 'up)
12175 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12177 (defun org-timestamp-down-day (&optional arg)
12178 "Decrease the date in the time stamp by one day.
12179 With prefix ARG, change that many days."
12180 (interactive "p")
12181 (if (and (not (org-at-timestamp-p t))
12182 (org-on-heading-p))
12183 (org-todo 'down)
12184 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12186 (defun org-at-timestamp-p (&optional inactive-ok)
12187 "Determine if the cursor is in or at a timestamp."
12188 (interactive)
12189 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12190 (pos (point))
12191 (ans (or (looking-at tsr)
12192 (save-excursion
12193 (skip-chars-backward "^[<\n\r\t")
12194 (if (> (point) (point-min)) (backward-char 1))
12195 (and (looking-at tsr)
12196 (> (- (match-end 0) pos) -1))))))
12197 (and ans
12198 (boundp 'org-ts-what)
12199 (setq org-ts-what
12200 (cond
12201 ((= pos (match-beginning 0)) 'bracket)
12202 ((= pos (1- (match-end 0))) 'bracket)
12203 ((org-pos-in-match-range pos 2) 'year)
12204 ((org-pos-in-match-range pos 3) 'month)
12205 ((org-pos-in-match-range pos 7) 'hour)
12206 ((org-pos-in-match-range pos 8) 'minute)
12207 ((or (org-pos-in-match-range pos 4)
12208 (org-pos-in-match-range pos 5)) 'day)
12209 ((and (> pos (or (match-end 8) (match-end 5)))
12210 (< pos (match-end 0)))
12211 (- pos (or (match-end 8) (match-end 5))))
12212 (t 'day))))
12213 ans))
12215 (defun org-toggle-timestamp-type ()
12216 "Toggle the type (<active> or [inactive]) of a time stamp."
12217 (interactive)
12218 (when (org-at-timestamp-p t)
12219 (let ((beg (match-beginning 0)) (end (match-end 0))
12220 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12221 (save-excursion
12222 (goto-char beg)
12223 (while (re-search-forward "[][<>]" end t)
12224 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12225 t t)))
12226 (message "Timestamp is now %sactive"
12227 (if (equal (char-after beg) ?<) "" "in")))))
12229 (defun org-timestamp-change (n &optional what)
12230 "Change the date in the time stamp at point.
12231 The date will be changed by N times WHAT. WHAT can be `day', `month',
12232 `year', `minute', `second'. If WHAT is not given, the cursor position
12233 in the timestamp determines what will be changed."
12234 (let ((pos (point))
12235 with-hm inactive
12236 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12237 org-ts-what
12238 extra rem
12239 ts time time0)
12240 (if (not (org-at-timestamp-p t))
12241 (error "Not at a timestamp"))
12242 (if (and (not what) (eq org-ts-what 'bracket))
12243 (org-toggle-timestamp-type)
12244 (if (and (not what) (not (eq org-ts-what 'day))
12245 org-display-custom-times
12246 (get-text-property (point) 'display)
12247 (not (get-text-property (1- (point)) 'display)))
12248 (setq org-ts-what 'day))
12249 (setq org-ts-what (or what org-ts-what)
12250 inactive (= (char-after (match-beginning 0)) ?\[)
12251 ts (match-string 0))
12252 (replace-match "")
12253 (if (string-match
12254 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12256 (setq extra (match-string 1 ts)))
12257 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12258 (setq with-hm t))
12259 (setq time0 (org-parse-time-string ts))
12260 (when (and (eq org-ts-what 'minute)
12261 (eq current-prefix-arg nil))
12262 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12263 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12264 (setcar (cdr time0) (+ (nth 1 time0)
12265 (if (> n 0) (- rem) (- dm rem))))))
12266 (setq time
12267 (encode-time (or (car time0) 0)
12268 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12269 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12270 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12271 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12272 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12273 (nthcdr 6 time0)))
12274 (when (integerp org-ts-what)
12275 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12276 (if (eq what 'calendar)
12277 (let ((cal-date (org-get-date-from-calendar)))
12278 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12279 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12280 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12281 (setcar time0 (or (car time0) 0))
12282 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12283 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12284 (setq time (apply 'encode-time time0))))
12285 (setq org-last-changed-timestamp
12286 (org-insert-time-stamp time with-hm inactive nil nil extra))
12287 (org-clock-update-time-maybe)
12288 (goto-char pos)
12289 ;; Try to recenter the calendar window, if any
12290 (if (and org-calendar-follow-timestamp-change
12291 (get-buffer-window "*Calendar*" t)
12292 (memq org-ts-what '(day month year)))
12293 (org-recenter-calendar (time-to-days time))))))
12295 (defun org-modify-ts-extra (s pos n dm)
12296 "Change the different parts of the lead-time and repeat fields in timestamp."
12297 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12298 ng h m new rem)
12299 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12300 (cond
12301 ((or (org-pos-in-match-range pos 2)
12302 (org-pos-in-match-range pos 3))
12303 (setq m (string-to-number (match-string 3 s))
12304 h (string-to-number (match-string 2 s)))
12305 (if (org-pos-in-match-range pos 2)
12306 (setq h (+ h n))
12307 (setq n (* dm (org-no-warnings (signum n))))
12308 (when (not (= 0 (setq rem (% m dm))))
12309 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12310 (setq m (+ m n)))
12311 (if (< m 0) (setq m (+ m 60) h (1- h)))
12312 (if (> m 59) (setq m (- m 60) h (1+ h)))
12313 (setq h (min 24 (max 0 h)))
12314 (setq ng 1 new (format "-%02d:%02d" h m)))
12315 ((org-pos-in-match-range pos 6)
12316 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12317 ((org-pos-in-match-range pos 5)
12318 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12320 ((org-pos-in-match-range pos 9)
12321 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12322 ((org-pos-in-match-range pos 8)
12323 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12325 (when ng
12326 (setq s (concat
12327 (substring s 0 (match-beginning ng))
12329 (substring s (match-end ng))))))
12332 (defun org-recenter-calendar (date)
12333 "If the calendar is visible, recenter it to DATE."
12334 (let* ((win (selected-window))
12335 (cwin (get-buffer-window "*Calendar*" t))
12336 (calendar-move-hook nil))
12337 (when cwin
12338 (select-window cwin)
12339 (calendar-goto-date (if (listp date) date
12340 (calendar-gregorian-from-absolute date)))
12341 (select-window win))))
12343 (defun org-goto-calendar (&optional arg)
12344 "Go to the Emacs calendar at the current date.
12345 If there is a time stamp in the current line, go to that date.
12346 A prefix ARG can be used to force the current date."
12347 (interactive "P")
12348 (let ((tsr org-ts-regexp) diff
12349 (calendar-move-hook nil)
12350 (calendar-view-holidays-initially-flag nil)
12351 (view-calendar-holidays-initially nil)
12352 (calendar-view-diary-initially-flag nil)
12353 (view-diary-entries-initially nil))
12354 (if (or (org-at-timestamp-p)
12355 (save-excursion
12356 (beginning-of-line 1)
12357 (looking-at (concat ".*" tsr))))
12358 (let ((d1 (time-to-days (current-time)))
12359 (d2 (time-to-days
12360 (org-time-string-to-time (match-string 1)))))
12361 (setq diff (- d2 d1))))
12362 (calendar)
12363 (calendar-goto-today)
12364 (if (and diff (not arg)) (calendar-forward-day diff))))
12366 (defun org-get-date-from-calendar ()
12367 "Return a list (month day year) of date at point in calendar."
12368 (with-current-buffer "*Calendar*"
12369 (save-match-data
12370 (calendar-cursor-to-date))))
12372 (defun org-date-from-calendar ()
12373 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12374 If there is already a time stamp at the cursor position, update it."
12375 (interactive)
12376 (if (org-at-timestamp-p t)
12377 (org-timestamp-change 0 'calendar)
12378 (let ((cal-date (org-get-date-from-calendar)))
12379 (org-insert-time-stamp
12380 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12382 (defun org-minutes-to-hh:mm-string (m)
12383 "Compute H:MM from a number of minutes."
12384 (let ((h (/ m 60)))
12385 (setq m (- m (* 60 h)))
12386 (format org-time-clocksum-format h m)))
12388 (defun org-hh:mm-string-to-minutes (s)
12389 "Convert a string H:MM to a number of minutes."
12390 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12391 (+ (* (string-to-number (match-string 1 s)) 60)
12392 (string-to-number (match-string 2 s)))
12395 ;;;; Files
12397 (defun org-save-all-org-buffers ()
12398 "Save all Org-mode buffers without user confirmation."
12399 (interactive)
12400 (message "Saving all Org-mode buffers...")
12401 (save-some-buffers t 'org-mode-p)
12402 (when (featurep 'org-id) (org-id-locations-save))
12403 (message "Saving all Org-mode buffers... done"))
12405 (defun org-revert-all-org-buffers ()
12406 "Revert all Org-mode buffers.
12407 Prompt for confirmation when there are unsaved changes.
12408 Be sure you know what you are doing before letting this function
12409 overwrite your changes.
12411 This function is useful in a setup where one tracks org files
12412 with a version control system, to revert on one machine after pulling
12413 changes from another. I believe the procedure must be like this:
12415 1. M-x org-save-all-org-buffers
12416 2. Pull changes from the other machine, resolve conflicts
12417 3. M-x org-revert-all-org-buffers"
12418 (interactive)
12419 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12420 (error "Abort"))
12421 (save-excursion
12422 (save-window-excursion
12423 (mapc
12424 (lambda (b)
12425 (when (and (with-current-buffer b (org-mode-p))
12426 (with-current-buffer b buffer-file-name))
12427 (switch-to-buffer b)
12428 (revert-buffer t 'no-confirm)))
12429 (buffer-list))
12430 (when (and (featurep 'org-id) org-id-track-globally)
12431 (org-id-locations-load)))))
12433 ;;;; Agenda files
12435 ;;;###autoload
12436 (defun org-iswitchb (&optional arg)
12437 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12438 With a prefix argument, restrict available to files.
12439 With two prefix arguments, restrict available buffers to agenda files.
12441 Due to some yet unresolved reason, the global function
12442 `iswitchb-mode' needs to be active for this function to work."
12443 (interactive "P")
12444 (require 'iswitchb)
12445 (let ((enabled iswitchb-mode) blist)
12446 (or enabled (iswitchb-mode 1))
12447 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12448 ((equal arg '(16)) (org-buffer-list 'agenda))
12449 (t (org-buffer-list))))
12450 (unwind-protect
12451 (let ((iswitchb-make-buflist-hook
12452 (lambda ()
12453 (setq iswitchb-temp-buflist
12454 (mapcar 'buffer-name blist)))))
12455 (switch-to-buffer
12456 (iswitchb-read-buffer
12457 "Switch-to: " nil t))
12458 (or enabled (iswitchb-mode -1))))))
12460 ;;;###autoload
12461 (defun org-ido-switchb (&optional arg)
12462 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12463 With a prefix argument, restrict available to files.
12464 With two prefix arguments, restrict available buffers to agenda files."
12465 (interactive "P")
12466 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12467 ((equal arg '(16)) (org-buffer-list 'agenda))
12468 (t (org-buffer-list)))))
12469 (switch-to-buffer
12470 (org-ido-completing-read "Org buffer: "
12471 (mapcar 'buffer-name blist)
12472 nil t))))
12474 (defun org-buffer-list (&optional predicate exclude-tmp)
12475 "Return a list of Org buffers.
12476 PREDICATE can be `export', `files' or `agenda'.
12478 export restrict the list to Export buffers.
12479 files restrict the list to buffers visiting Org files.
12480 agenda restrict the list to buffers visiting agenda files.
12482 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12483 (let* ((bfn nil)
12484 (agenda-files (and (eq predicate 'agenda)
12485 (mapcar 'file-truename (org-agenda-files t))))
12486 (filter
12487 (cond
12488 ((eq predicate 'files)
12489 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12490 ((eq predicate 'export)
12491 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12492 ((eq predicate 'agenda)
12493 (lambda (b)
12494 (with-current-buffer b
12495 (and (eq major-mode 'org-mode)
12496 (setq bfn (buffer-file-name b))
12497 (member (file-truename bfn) agenda-files)))))
12498 (t (lambda (b) (with-current-buffer b
12499 (or (eq major-mode 'org-mode)
12500 (string-match "\*Org .*Export"
12501 (buffer-name b)))))))))
12502 (delq nil
12503 (mapcar
12504 (lambda(b)
12505 (if (and (funcall filter b)
12506 (or (not exclude-tmp)
12507 (not (string-match "tmp" (buffer-name b)))))
12509 nil))
12510 (buffer-list)))))
12512 (defun org-agenda-files (&optional unrestricted archives)
12513 "Get the list of agenda files.
12514 Optional UNRESTRICTED means return the full list even if a restriction
12515 is currently in place.
12516 When ARCHIVES is t, include all archive files hat are really being
12517 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12518 `org-agenda-archives-mode' is t."
12519 (let ((files
12520 (cond
12521 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12522 ((stringp org-agenda-files) (org-read-agenda-file-list))
12523 ((listp org-agenda-files) org-agenda-files)
12524 (t (error "Invalid value of `org-agenda-files'")))))
12525 (setq files (apply 'append
12526 (mapcar (lambda (f)
12527 (if (file-directory-p f)
12528 (directory-files
12529 f t org-agenda-file-regexp)
12530 (list f)))
12531 files)))
12532 (when org-agenda-skip-unavailable-files
12533 (setq files (delq nil
12534 (mapcar (function
12535 (lambda (file)
12536 (and (file-readable-p file) file)))
12537 files))))
12538 (when (or (eq archives t)
12539 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12540 (setq files (org-add-archive-files files)))
12541 files))
12543 (defun org-edit-agenda-file-list ()
12544 "Edit the list of agenda files.
12545 Depending on setup, this either uses customize to edit the variable
12546 `org-agenda-files', or it visits the file that is holding the list. In the
12547 latter case, the buffer is set up in a way that saving it automatically kills
12548 the buffer and restores the previous window configuration."
12549 (interactive)
12550 (if (stringp org-agenda-files)
12551 (let ((cw (current-window-configuration)))
12552 (find-file org-agenda-files)
12553 (org-set-local 'org-window-configuration cw)
12554 (org-add-hook 'after-save-hook
12555 (lambda ()
12556 (set-window-configuration
12557 (prog1 org-window-configuration
12558 (kill-buffer (current-buffer))))
12559 (org-install-agenda-files-menu)
12560 (message "New agenda file list installed"))
12561 nil 'local)
12562 (message "%s" (substitute-command-keys
12563 "Edit list and finish with \\[save-buffer]")))
12564 (customize-variable 'org-agenda-files)))
12566 (defun org-store-new-agenda-file-list (list)
12567 "Set new value for the agenda file list and save it correctly."
12568 (if (stringp org-agenda-files)
12569 (let ((f org-agenda-files) b)
12570 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12571 (with-temp-file f
12572 (insert (mapconcat 'identity list "\n") "\n")))
12573 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12574 (setq org-agenda-files list)
12575 (customize-save-variable 'org-agenda-files org-agenda-files))))
12577 (defun org-read-agenda-file-list ()
12578 "Read the list of agenda files from a file."
12579 (when (file-directory-p org-agenda-files)
12580 (error "`org-agenda-files' cannot be a single directory"))
12581 (when (stringp org-agenda-files)
12582 (with-temp-buffer
12583 (insert-file-contents org-agenda-files)
12584 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12587 ;;;###autoload
12588 (defun org-cycle-agenda-files ()
12589 "Cycle through the files in `org-agenda-files'.
12590 If the current buffer visits an agenda file, find the next one in the list.
12591 If the current buffer does not, find the first agenda file."
12592 (interactive)
12593 (let* ((fs (org-agenda-files t))
12594 (files (append fs (list (car fs))))
12595 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12596 file)
12597 (unless files (error "No agenda files"))
12598 (catch 'exit
12599 (while (setq file (pop files))
12600 (if (equal (file-truename file) tcf)
12601 (when (car files)
12602 (find-file (car files))
12603 (throw 'exit t))))
12604 (find-file (car fs)))
12605 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12607 (defun org-agenda-file-to-front (&optional to-end)
12608 "Move/add the current file to the top of the agenda file list.
12609 If the file is not present in the list, it is added to the front. If it is
12610 present, it is moved there. With optional argument TO-END, add/move to the
12611 end of the list."
12612 (interactive "P")
12613 (let ((org-agenda-skip-unavailable-files nil)
12614 (file-alist (mapcar (lambda (x)
12615 (cons (file-truename x) x))
12616 (org-agenda-files t)))
12617 (ctf (file-truename buffer-file-name))
12618 x had)
12619 (setq x (assoc ctf file-alist) had x)
12621 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12622 (if to-end
12623 (setq file-alist (append (delq x file-alist) (list x)))
12624 (setq file-alist (cons x (delq x file-alist))))
12625 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12626 (org-install-agenda-files-menu)
12627 (message "File %s to %s of agenda file list"
12628 (if had "moved" "added") (if to-end "end" "front"))))
12630 (defun org-remove-file (&optional file)
12631 "Remove current file from the list of files in variable `org-agenda-files'.
12632 These are the files which are being checked for agenda entries.
12633 Optional argument FILE means, use this file instead of the current."
12634 (interactive)
12635 (let* ((org-agenda-skip-unavailable-files nil)
12636 (file (or file buffer-file-name))
12637 (true-file (file-truename file))
12638 (afile (abbreviate-file-name file))
12639 (files (delq nil (mapcar
12640 (lambda (x)
12641 (if (equal true-file
12642 (file-truename x))
12643 nil x))
12644 (org-agenda-files t)))))
12645 (if (not (= (length files) (length (org-agenda-files t))))
12646 (progn
12647 (org-store-new-agenda-file-list files)
12648 (org-install-agenda-files-menu)
12649 (message "Removed file: %s" afile))
12650 (message "File was not in list: %s (not removed)" afile))))
12652 (defun org-file-menu-entry (file)
12653 (vector file (list 'find-file file) t))
12655 (defun org-check-agenda-file (file)
12656 "Make sure FILE exists. If not, ask user what to do."
12657 (when (not (file-exists-p file))
12658 (message "non-existent file %s. [R]emove from list or [A]bort?"
12659 (abbreviate-file-name file))
12660 (let ((r (downcase (read-char-exclusive))))
12661 (cond
12662 ((equal r ?r)
12663 (org-remove-file file)
12664 (throw 'nextfile t))
12665 (t (error "Abort"))))))
12667 (defun org-get-agenda-file-buffer (file)
12668 "Get a buffer visiting FILE. If the buffer needs to be created, add
12669 it to the list of buffers which might be released later."
12670 (let ((buf (org-find-base-buffer-visiting file)))
12671 (if buf
12672 buf ; just return it
12673 ;; Make a new buffer and remember it
12674 (setq buf (find-file-noselect file))
12675 (if buf (push buf org-agenda-new-buffers))
12676 buf)))
12678 (defun org-release-buffers (blist)
12679 "Release all buffers in list, asking the user for confirmation when needed.
12680 When a buffer is unmodified, it is just killed. When modified, it is saved
12681 \(if the user agrees) and then killed."
12682 (let (buf file)
12683 (while (setq buf (pop blist))
12684 (setq file (buffer-file-name buf))
12685 (when (and (buffer-modified-p buf)
12686 file
12687 (y-or-n-p (format "Save file %s? " file)))
12688 (with-current-buffer buf (save-buffer)))
12689 (kill-buffer buf))))
12691 (defun org-prepare-agenda-buffers (files)
12692 "Create buffers for all agenda files, protect archived trees and comments."
12693 (interactive)
12694 (let ((pa '(:org-archived t))
12695 (pc '(:org-comment t))
12696 (pall '(:org-archived t :org-comment t))
12697 (inhibit-read-only t)
12698 (rea (concat ":" org-archive-tag ":"))
12699 bmp file re)
12700 (save-excursion
12701 (save-restriction
12702 (while (setq file (pop files))
12703 (if (bufferp file)
12704 (set-buffer file)
12705 (org-check-agenda-file file)
12706 (set-buffer (org-get-agenda-file-buffer file)))
12707 (widen)
12708 (setq bmp (buffer-modified-p))
12709 (org-refresh-category-properties)
12710 (setq org-todo-keywords-for-agenda
12711 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12712 (setq org-done-keywords-for-agenda
12713 (append org-done-keywords-for-agenda org-done-keywords))
12714 (setq org-todo-keyword-alist-for-agenda
12715 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12716 (setq org-tag-alist-for-agenda
12717 (append org-tag-alist-for-agenda org-tag-alist))
12719 (save-excursion
12720 (remove-text-properties (point-min) (point-max) pall)
12721 (when org-agenda-skip-archived-trees
12722 (goto-char (point-min))
12723 (while (re-search-forward rea nil t)
12724 (if (org-on-heading-p t)
12725 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12726 (goto-char (point-min))
12727 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12728 (while (re-search-forward re nil t)
12729 (add-text-properties
12730 (match-beginning 0) (org-end-of-subtree t) pc)))
12731 (set-buffer-modified-p bmp))))
12732 (setq org-todo-keyword-alist-for-agenda
12733 (org-uniquify org-todo-keyword-alist-for-agenda)
12734 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12736 ;;;; Embedded LaTeX
12738 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12739 "Keymap for the minor `org-cdlatex-mode'.")
12741 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12742 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12743 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12744 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12745 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12747 (defvar org-cdlatex-texmathp-advice-is-done nil
12748 "Flag remembering if we have applied the advice to texmathp already.")
12750 (define-minor-mode org-cdlatex-mode
12751 "Toggle the minor `org-cdlatex-mode'.
12752 This mode supports entering LaTeX environment and math in LaTeX fragments
12753 in Org-mode.
12754 \\{org-cdlatex-mode-map}"
12755 nil " OCDL" nil
12756 (when org-cdlatex-mode (require 'cdlatex))
12757 (unless org-cdlatex-texmathp-advice-is-done
12758 (setq org-cdlatex-texmathp-advice-is-done t)
12759 (defadvice texmathp (around org-math-always-on activate)
12760 "Always return t in org-mode buffers.
12761 This is because we want to insert math symbols without dollars even outside
12762 the LaTeX math segments. If Orgmode thinks that point is actually inside
12763 an embedded LaTeX fragment, let texmathp do its job.
12764 \\[org-cdlatex-mode-map]"
12765 (interactive)
12766 (let (p)
12767 (cond
12768 ((not (org-mode-p)) ad-do-it)
12769 ((eq this-command 'cdlatex-math-symbol)
12770 (setq ad-return-value t
12771 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12773 (let ((p (org-inside-LaTeX-fragment-p)))
12774 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12775 (setq ad-return-value t
12776 texmathp-why '("Org-mode embedded math" . 0))
12777 (if p ad-do-it)))))))))
12779 (defun turn-on-org-cdlatex ()
12780 "Unconditionally turn on `org-cdlatex-mode'."
12781 (org-cdlatex-mode 1))
12783 (defun org-inside-LaTeX-fragment-p ()
12784 "Test if point is inside a LaTeX fragment.
12785 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12786 sequence appearing also before point.
12787 Even though the matchers for math are configurable, this function assumes
12788 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12789 delimiters are skipped when they have been removed by customization.
12790 The return value is nil, or a cons cell with the delimiter and
12791 and the position of this delimiter.
12793 This function does a reasonably good job, but can locally be fooled by
12794 for example currency specifications. For example it will assume being in
12795 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12796 fragments that are properly closed, but during editing, we have to live
12797 with the uncertainty caused by missing closing delimiters. This function
12798 looks only before point, not after."
12799 (catch 'exit
12800 (let ((pos (point))
12801 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12802 (lim (progn
12803 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12804 (point)))
12805 dd-on str (start 0) m re)
12806 (goto-char pos)
12807 (when dodollar
12808 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12809 re (nth 1 (assoc "$" org-latex-regexps)))
12810 (while (string-match re str start)
12811 (cond
12812 ((= (match-end 0) (length str))
12813 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12814 ((= (match-end 0) (- (length str) 5))
12815 (throw 'exit nil))
12816 (t (setq start (match-end 0))))))
12817 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12818 (goto-char pos)
12819 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12820 (and (match-beginning 2) (throw 'exit nil))
12821 ;; count $$
12822 (while (re-search-backward "\\$\\$" lim t)
12823 (setq dd-on (not dd-on)))
12824 (goto-char pos)
12825 (if dd-on (cons "$$" m))))))
12828 (defun org-try-cdlatex-tab ()
12829 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12830 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12831 - inside a LaTeX fragment, or
12832 - after the first word in a line, where an abbreviation expansion could
12833 insert a LaTeX environment."
12834 (when org-cdlatex-mode
12835 (cond
12836 ((save-excursion
12837 (skip-chars-backward "a-zA-Z0-9*")
12838 (skip-chars-backward " \t")
12839 (bolp))
12840 (cdlatex-tab) t)
12841 ((org-inside-LaTeX-fragment-p)
12842 (cdlatex-tab) t)
12843 (t nil))))
12845 (defun org-cdlatex-underscore-caret (&optional arg)
12846 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12847 Revert to the normal definition outside of these fragments."
12848 (interactive "P")
12849 (if (org-inside-LaTeX-fragment-p)
12850 (call-interactively 'cdlatex-sub-superscript)
12851 (let (org-cdlatex-mode)
12852 (call-interactively (key-binding (vector last-input-event))))))
12854 (defun org-cdlatex-math-modify (&optional arg)
12855 "Execute `cdlatex-math-modify' in LaTeX fragments.
12856 Revert to the normal definition outside of these fragments."
12857 (interactive "P")
12858 (if (org-inside-LaTeX-fragment-p)
12859 (call-interactively 'cdlatex-math-modify)
12860 (let (org-cdlatex-mode)
12861 (call-interactively (key-binding (vector last-input-event))))))
12863 (defvar org-latex-fragment-image-overlays nil
12864 "List of overlays carrying the images of latex fragments.")
12865 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12867 (defun org-remove-latex-fragment-image-overlays ()
12868 "Remove all overlays with LaTeX fragment images in current buffer."
12869 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12870 (setq org-latex-fragment-image-overlays nil))
12872 (defun org-preview-latex-fragment (&optional subtree)
12873 "Preview the LaTeX fragment at point, or all locally or globally.
12874 If the cursor is in a LaTeX fragment, create the image and overlay
12875 it over the source code. If there is no fragment at point, display
12876 all fragments in the current text, from one headline to the next. With
12877 prefix SUBTREE, display all fragments in the current subtree. With a
12878 double prefix `C-u C-u', or when the cursor is before the first headline,
12879 display all fragments in the buffer.
12880 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12881 (interactive "P")
12882 (org-remove-latex-fragment-image-overlays)
12883 (save-excursion
12884 (save-restriction
12885 (let (beg end at msg)
12886 (cond
12887 ((or (equal subtree '(16))
12888 (not (save-excursion
12889 (re-search-backward (concat "^" outline-regexp) nil t))))
12890 (setq beg (point-min) end (point-max)
12891 msg "Creating images for buffer...%s"))
12892 ((equal subtree '(4))
12893 (org-back-to-heading)
12894 (setq beg (point) end (org-end-of-subtree t)
12895 msg "Creating images for subtree...%s"))
12897 (if (setq at (org-inside-LaTeX-fragment-p))
12898 (goto-char (max (point-min) (- (cdr at) 2)))
12899 (org-back-to-heading))
12900 (setq beg (point) end (progn (outline-next-heading) (point))
12901 msg (if at "Creating image...%s"
12902 "Creating images for entry...%s"))))
12903 (message msg "")
12904 (narrow-to-region beg end)
12905 (goto-char beg)
12906 (org-format-latex
12907 (concat "ltxpng/" (file-name-sans-extension
12908 (file-name-nondirectory
12909 buffer-file-name)))
12910 default-directory 'overlays msg at 'forbuffer)
12911 (message msg "done. Use `C-c C-c' to remove images.")))))
12913 (defvar org-latex-regexps
12914 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12915 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12916 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12917 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12918 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12919 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12920 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12921 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12922 "Regular expressions for matching embedded LaTeX.")
12924 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12925 "Replace LaTeX fragments with links to an image, and produce images."
12926 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12927 (let* ((prefixnodir (file-name-nondirectory prefix))
12928 (absprefix (expand-file-name prefix dir))
12929 (todir (file-name-directory absprefix))
12930 (opt org-format-latex-options)
12931 (matchers (plist-get opt :matchers))
12932 (re-list org-latex-regexps)
12933 (cnt 0) txt link beg end re e checkdir
12934 m n block linkfile movefile ov)
12935 ;; Check if there are old images files with this prefix, and remove them
12936 (when (file-directory-p todir)
12937 (mapc 'delete-file
12938 (directory-files
12939 todir 'full
12940 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12941 ;; Check the different regular expressions
12942 (while (setq e (pop re-list))
12943 (setq m (car e) re (nth 1 e) n (nth 2 e)
12944 block (if (nth 3 e) "\n\n" ""))
12945 (when (member m matchers)
12946 (goto-char (point-min))
12947 (while (re-search-forward re nil t)
12948 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
12949 (not (get-text-property (match-beginning n)
12950 'org-protected)))
12951 (setq txt (match-string n)
12952 beg (match-beginning n) end (match-end n)
12953 cnt (1+ cnt)
12954 linkfile (format "%s_%04d.png" prefix cnt)
12955 movefile (format "%s_%04d.png" absprefix cnt)
12956 link (concat block "[[file:" linkfile "]]" block))
12957 (if msg (message msg cnt))
12958 (goto-char beg)
12959 (unless checkdir ; make sure the directory exists
12960 (setq checkdir t)
12961 (or (file-directory-p todir) (make-directory todir)))
12962 (org-create-formula-image
12963 txt movefile opt forbuffer)
12964 (if overlays
12965 (progn
12966 (setq ov (org-make-overlay beg end))
12967 (if (featurep 'xemacs)
12968 (progn
12969 (org-overlay-put ov 'invisible t)
12970 (org-overlay-put
12971 ov 'end-glyph
12972 (make-glyph (vector 'png :file movefile))))
12973 (org-overlay-put
12974 ov 'display
12975 (list 'image :type 'png :file movefile :ascent 'center)))
12976 (push ov org-latex-fragment-image-overlays)
12977 (goto-char end))
12978 (delete-region beg end)
12979 (insert link))))))))
12981 ;; This function borrows from Ganesh Swami's latex2png.el
12982 (defun org-create-formula-image (string tofile options buffer)
12983 (let* ((tmpdir (if (featurep 'xemacs)
12984 (temp-directory)
12985 temporary-file-directory))
12986 (texfilebase (make-temp-name
12987 (expand-file-name "orgtex" tmpdir)))
12988 (texfile (concat texfilebase ".tex"))
12989 (dvifile (concat texfilebase ".dvi"))
12990 (pngfile (concat texfilebase ".png"))
12991 (fnh (if (featurep 'xemacs)
12992 (font-height (get-face-font 'default))
12993 (face-attribute 'default :height nil)))
12994 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12995 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12996 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12997 "Black"))
12998 (bg (or (plist-get options (if buffer :background :html-background))
12999 "Transparent")))
13000 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13001 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13002 (with-temp-file texfile
13003 (insert org-format-latex-header
13004 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13005 (let ((dir default-directory))
13006 (condition-case nil
13007 (progn
13008 (cd tmpdir)
13009 (call-process "latex" nil nil nil texfile))
13010 (error nil))
13011 (cd dir))
13012 (if (not (file-exists-p dvifile))
13013 (progn (message "Failed to create dvi file from %s" texfile) nil)
13014 (condition-case nil
13015 (call-process "dvipng" nil nil nil
13016 "-E" "-fg" fg "-bg" bg
13017 "-D" dpi
13018 ;;"-x" scale "-y" scale
13019 "-T" "tight"
13020 "-o" pngfile
13021 dvifile)
13022 (error nil))
13023 (if (not (file-exists-p pngfile))
13024 (progn (message "Failed to create png file from %s" texfile) nil)
13025 ;; Use the requested file name and clean up
13026 (copy-file pngfile tofile 'replace)
13027 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13028 (delete-file (concat texfilebase e)))
13029 pngfile))))
13031 (defun org-dvipng-color (attr)
13032 "Return an rgb color specification for dvipng."
13033 (apply 'format "rgb %s %s %s"
13034 (mapcar 'org-normalize-color
13035 (color-values (face-attribute 'default attr nil)))))
13037 (defun org-normalize-color (value)
13038 "Return string to be used as color value for an RGB component."
13039 (format "%g" (/ value 65535.0)))
13041 ;;;; Key bindings
13043 ;; Make `C-c C-x' a prefix key
13044 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13046 ;; TAB key with modifiers
13047 (org-defkey org-mode-map "\C-i" 'org-cycle)
13048 (org-defkey org-mode-map [(tab)] 'org-cycle)
13049 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13050 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13051 (org-defkey org-mode-map "\M-\t" 'org-complete)
13052 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13053 ;; The following line is necessary under Suse GNU/Linux
13054 (unless (featurep 'xemacs)
13055 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13056 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13057 (define-key org-mode-map [backtab] 'org-shifttab)
13059 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13060 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13061 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13063 ;; Cursor keys with modifiers
13064 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13065 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13066 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13067 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13069 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13070 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13071 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13072 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13074 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13075 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13076 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13077 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13079 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13080 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13082 ;;; Extra keys for tty access.
13083 ;; We only set them when really needed because otherwise the
13084 ;; menus don't show the simple keys
13086 (when (or org-use-extra-keys
13087 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13088 (not window-system))
13089 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13090 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13091 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13092 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13093 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13094 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13095 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13096 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13097 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13098 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13099 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13100 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13101 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13102 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13103 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13104 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13105 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13106 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13107 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13108 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13109 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13110 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13112 ;; All the other keys
13114 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13115 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13116 (if (boundp 'narrow-map)
13117 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13118 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13119 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13120 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13121 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13122 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13123 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13124 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13125 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13126 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13127 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13128 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13129 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13130 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13131 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13132 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13133 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13134 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
13135 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13136 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13137 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13138 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13139 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13140 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13141 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13142 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13143 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13144 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13145 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13146 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13147 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13148 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13149 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13150 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13151 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13152 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13153 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13154 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13155 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13156 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13157 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13158 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13159 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13160 (org-defkey org-mode-map "\C-c^" 'org-sort)
13161 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13162 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13163 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13164 (org-defkey org-mode-map "\C-m" 'org-return)
13165 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13166 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13167 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13168 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13169 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13170 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13171 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13172 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13173 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13174 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13175 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13176 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13177 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13178 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13179 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13180 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13181 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13183 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13184 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13185 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13186 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13188 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13189 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13190 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13191 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13192 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13193 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13194 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13195 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13196 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13197 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13198 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13199 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13200 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13202 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13203 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13204 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13205 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13207 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13209 (when (featurep 'xemacs)
13210 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13212 (defvar org-table-auto-blank-field) ; defined in org-table.el
13213 (defun org-self-insert-command (N)
13214 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13215 If the cursor is in a table looking at whitespace, the whitespace is
13216 overwritten, and the table is not marked as requiring realignment."
13217 (interactive "p")
13218 (if (and (org-table-p)
13219 (progn
13220 ;; check if we blank the field, and if that triggers align
13221 (and (featurep 'org-table) org-table-auto-blank-field
13222 (member last-command
13223 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13224 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13225 ;; got extra space, this field does not determine column width
13226 (let (org-table-may-need-update) (org-table-blank-field))
13227 ;; no extra space, this field may determine column width
13228 (org-table-blank-field)))
13230 (eq N 1)
13231 (looking-at "[^|\n]* |"))
13232 (let (org-table-may-need-update)
13233 (goto-char (1- (match-end 0)))
13234 (delete-backward-char 1)
13235 (goto-char (match-beginning 0))
13236 (self-insert-command N))
13237 (setq org-table-may-need-update t)
13238 (self-insert-command N)
13239 (org-fix-tags-on-the-fly)))
13241 (defun org-fix-tags-on-the-fly ()
13242 (when (and (equal (char-after (point-at-bol)) ?*)
13243 (org-on-heading-p))
13244 (org-align-tags-here org-tags-column)))
13246 (defun org-delete-backward-char (N)
13247 "Like `delete-backward-char', insert whitespace at field end in tables.
13248 When deleting backwards, in tables this function will insert whitespace in
13249 front of the next \"|\" separator, to keep the table aligned. The table will
13250 still be marked for re-alignment if the field did fill the entire column,
13251 because, in this case the deletion might narrow the column."
13252 (interactive "p")
13253 (if (and (org-table-p)
13254 (eq N 1)
13255 (string-match "|" (buffer-substring (point-at-bol) (point)))
13256 (looking-at ".*?|"))
13257 (let ((pos (point))
13258 (noalign (looking-at "[^|\n\r]* |"))
13259 (c org-table-may-need-update))
13260 (backward-delete-char N)
13261 (skip-chars-forward "^|")
13262 (insert " ")
13263 (goto-char (1- pos))
13264 ;; noalign: if there were two spaces at the end, this field
13265 ;; does not determine the width of the column.
13266 (if noalign (setq org-table-may-need-update c)))
13267 (backward-delete-char N)
13268 (org-fix-tags-on-the-fly)))
13270 (defun org-delete-char (N)
13271 "Like `delete-char', but insert whitespace at field end in tables.
13272 When deleting characters, in tables this function will insert whitespace in
13273 front of the next \"|\" separator, to keep the table aligned. The table will
13274 still be marked for re-alignment if the field did fill the entire column,
13275 because, in this case the deletion might narrow the column."
13276 (interactive "p")
13277 (if (and (org-table-p)
13278 (not (bolp))
13279 (not (= (char-after) ?|))
13280 (eq N 1))
13281 (if (looking-at ".*?|")
13282 (let ((pos (point))
13283 (noalign (looking-at "[^|\n\r]* |"))
13284 (c org-table-may-need-update))
13285 (replace-match (concat
13286 (substring (match-string 0) 1 -1)
13287 " |"))
13288 (goto-char pos)
13289 ;; noalign: if there were two spaces at the end, this field
13290 ;; does not determine the width of the column.
13291 (if noalign (setq org-table-may-need-update c)))
13292 (delete-char N))
13293 (delete-char N)
13294 (org-fix-tags-on-the-fly)))
13296 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13297 (put 'org-self-insert-command 'delete-selection t)
13298 (put 'orgtbl-self-insert-command 'delete-selection t)
13299 (put 'org-delete-char 'delete-selection 'supersede)
13300 (put 'org-delete-backward-char 'delete-selection 'supersede)
13301 (put 'org-yank 'delete-selection 'yank)
13303 ;; Make `flyspell-mode' delay after some commands
13304 (put 'org-self-insert-command 'flyspell-delayed t)
13305 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13306 (put 'org-delete-char 'flyspell-delayed t)
13307 (put 'org-delete-backward-char 'flyspell-delayed t)
13309 ;; Make pabbrev-mode expand after org-mode commands
13310 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13311 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13313 ;; How to do this: Measure non-white length of current string
13314 ;; If equal to column width, we should realign.
13316 (defun org-remap (map &rest commands)
13317 "In MAP, remap the functions given in COMMANDS.
13318 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13319 (let (new old)
13320 (while commands
13321 (setq old (pop commands) new (pop commands))
13322 (if (fboundp 'command-remapping)
13323 (org-defkey map (vector 'remap old) new)
13324 (substitute-key-definition old new map global-map)))))
13326 (when (eq org-enable-table-editor 'optimized)
13327 ;; If the user wants maximum table support, we need to hijack
13328 ;; some standard editing functions
13329 (org-remap org-mode-map
13330 'self-insert-command 'org-self-insert-command
13331 'delete-char 'org-delete-char
13332 'delete-backward-char 'org-delete-backward-char)
13333 (org-defkey org-mode-map "|" 'org-force-self-insert))
13335 (defvar org-ctrl-c-ctrl-c-hook nil
13336 "Hook for functions attaching themselves to `C-c C-c'.
13337 This can be used to add additional functionality to the C-c C-c key which
13338 executes context-dependent commands.
13339 Each function will be called with no arguments. The function must check
13340 if the context is appropriate for it to act. If yes, it should do its
13341 thing and then return a non-nil value. If the context is wrong,
13342 just do nothing.")
13344 (defvar org-metaleft-hook nil
13345 "Hook for functions attaching themselves to `M-left'.
13346 See `org-ctrl-c-ctrl-c-hook' for more information.")
13347 (defvar org-metaright-hook nil
13348 "Hook for functions attaching themselves to `M-right'.
13349 See `org-ctrl-c-ctrl-c-hook' for more information.")
13350 (defvar org-metaup-hook nil
13351 "Hook for functions attaching themselves to `M-up'.
13352 See `org-ctrl-c-ctrl-c-hook' for more information.")
13353 (defvar org-metadown-hook nil
13354 "Hook for functions attaching themselves to `M-down'.
13355 See `org-ctrl-c-ctrl-c-hook' for more information.")
13356 (defvar org-shiftmetaleft-hook nil
13357 "Hook for functions attaching themselves to `M-S-left'.
13358 See `org-ctrl-c-ctrl-c-hook' for more information.")
13359 (defvar org-shiftmetaright-hook nil
13360 "Hook for functions attaching themselves to `M-S-right'.
13361 See `org-ctrl-c-ctrl-c-hook' for more information.")
13362 (defvar org-shiftmetaup-hook nil
13363 "Hook for functions attaching themselves to `M-S-up'.
13364 See `org-ctrl-c-ctrl-c-hook' for more information.")
13365 (defvar org-shiftmetadown-hook nil
13366 "Hook for functions attaching themselves to `M-S-down'.
13367 See `org-ctrl-c-ctrl-c-hook' for more information.")
13368 (defvar org-metareturn-hook nil
13369 "Hook for functions attaching themselves to `M-RET'.
13370 See `org-ctrl-c-ctrl-c-hook' for more information.")
13372 (defun org-modifier-cursor-error ()
13373 "Throw an error, a modified cursor command was applied in wrong context."
13374 (error "This command is active in special context like tables, headlines or items"))
13376 (defun org-shiftselect-error ()
13377 "Throw an error because Shift-Cursor command was applied in wrong context."
13378 (if (and (boundp 'shift-select-mode) shift-select-mode)
13379 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13380 (error "This command works only in special context like headlines or timestamps.")))
13382 (defun org-call-for-shift-select (cmd)
13383 (let ((this-command-keys-shift-translated t))
13384 (call-interactively cmd)))
13386 (defun org-shifttab (&optional arg)
13387 "Global visibility cycling or move to previous table field.
13388 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13389 on context.
13390 See the individual commands for more information."
13391 (interactive "P")
13392 (cond
13393 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13394 ((integerp arg)
13395 (message "Content view to level: %d" arg)
13396 (org-content (prefix-numeric-value arg))
13397 (setq org-cycle-global-status 'overview))
13398 (t (call-interactively 'org-global-cycle))))
13400 (defun org-shiftmetaleft ()
13401 "Promote subtree or delete table column.
13402 Calls `org-promote-subtree', `org-outdent-item',
13403 or `org-table-delete-column', depending on context.
13404 See the individual commands for more information."
13405 (interactive)
13406 (cond
13407 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13408 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13409 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13410 ((org-at-item-p) (call-interactively 'org-outdent-item))
13411 (t (org-modifier-cursor-error))))
13413 (defun org-shiftmetaright ()
13414 "Demote subtree or insert table column.
13415 Calls `org-demote-subtree', `org-indent-item',
13416 or `org-table-insert-column', depending on context.
13417 See the individual commands for more information."
13418 (interactive)
13419 (cond
13420 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13421 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13422 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13423 ((org-at-item-p) (call-interactively 'org-indent-item))
13424 (t (org-modifier-cursor-error))))
13426 (defun org-shiftmetaup (&optional arg)
13427 "Move subtree up or kill table row.
13428 Calls `org-move-subtree-up' or `org-table-kill-row' or
13429 `org-move-item-up' depending on context. See the individual commands
13430 for more information."
13431 (interactive "P")
13432 (cond
13433 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13434 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13435 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13436 ((org-at-item-p) (call-interactively 'org-move-item-up))
13437 (t (org-modifier-cursor-error))))
13439 (defun org-shiftmetadown (&optional arg)
13440 "Move subtree down or insert table row.
13441 Calls `org-move-subtree-down' or `org-table-insert-row' or
13442 `org-move-item-down', depending on context. See the individual
13443 commands for more information."
13444 (interactive "P")
13445 (cond
13446 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13447 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13448 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13449 ((org-at-item-p) (call-interactively 'org-move-item-down))
13450 (t (org-modifier-cursor-error))))
13452 (defun org-metaleft (&optional arg)
13453 "Promote heading or move table column to left.
13454 Calls `org-do-promote' or `org-table-move-column', depending on context.
13455 With no specific context, calls the Emacs default `backward-word'.
13456 See the individual commands for more information."
13457 (interactive "P")
13458 (cond
13459 ((run-hook-with-args-until-success 'org-metaleft-hook))
13460 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13461 ((or (org-on-heading-p) (org-region-active-p))
13462 (call-interactively 'org-do-promote))
13463 ((org-at-item-p) (call-interactively 'org-outdent-item))
13464 (t (call-interactively 'backward-word))))
13466 (defun org-metaright (&optional arg)
13467 "Demote subtree or move table column to right.
13468 Calls `org-do-demote' or `org-table-move-column', depending on context.
13469 With no specific context, calls the Emacs default `forward-word'.
13470 See the individual commands for more information."
13471 (interactive "P")
13472 (cond
13473 ((run-hook-with-args-until-success 'org-metaright-hook))
13474 ((org-at-table-p) (call-interactively 'org-table-move-column))
13475 ((or (org-on-heading-p) (org-region-active-p))
13476 (call-interactively 'org-do-demote))
13477 ((org-at-item-p) (call-interactively 'org-indent-item))
13478 (t (call-interactively 'forward-word))))
13480 (defun org-metaup (&optional arg)
13481 "Move subtree up or move table row up.
13482 Calls `org-move-subtree-up' or `org-table-move-row' or
13483 `org-move-item-up', depending on context. See the individual commands
13484 for more information."
13485 (interactive "P")
13486 (cond
13487 ((run-hook-with-args-until-success 'org-metaup-hook))
13488 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13489 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13490 ((org-at-item-p) (call-interactively 'org-move-item-up))
13491 (t (transpose-lines 1) (beginning-of-line -1))))
13493 (defun org-metadown (&optional arg)
13494 "Move subtree down or move table row down.
13495 Calls `org-move-subtree-down' or `org-table-move-row' or
13496 `org-move-item-down', depending on context. See the individual
13497 commands for more information."
13498 (interactive "P")
13499 (cond
13500 ((run-hook-with-args-until-success 'org-metadown-hook))
13501 ((org-at-table-p) (call-interactively 'org-table-move-row))
13502 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13503 ((org-at-item-p) (call-interactively 'org-move-item-down))
13504 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13506 (defun org-shiftup (&optional arg)
13507 "Increase item in timestamp or increase priority of current headline.
13508 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13509 depending on context. See the individual commands for more information."
13510 (interactive "P")
13511 (cond
13512 ((and org-support-shift-select (org-region-active-p))
13513 (org-call-for-shift-select 'previous-line))
13514 ((org-at-timestamp-p t)
13515 (call-interactively (if org-edit-timestamp-down-means-later
13516 'org-timestamp-down 'org-timestamp-up)))
13517 ((and (not (eq org-support-shift-select 'always))
13518 (org-on-heading-p))
13519 (call-interactively 'org-priority-up))
13520 ((and (not org-support-shift-select) (org-at-item-p))
13521 (call-interactively 'org-previous-item))
13522 ((org-clocktable-try-shift 'up arg))
13523 (org-support-shift-select
13524 (org-call-for-shift-select 'previous-line))
13525 (t (org-shiftselect-error))))
13527 (defun org-shiftdown (&optional arg)
13528 "Decrease item in timestamp or decrease priority of current headline.
13529 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13530 depending on context. See the individual commands for more information."
13531 (interactive "P")
13532 (cond
13533 ((and org-support-shift-select (org-region-active-p))
13534 (org-call-for-shift-select 'next-line))
13535 ((org-at-timestamp-p t)
13536 (call-interactively (if org-edit-timestamp-down-means-later
13537 'org-timestamp-up 'org-timestamp-down)))
13538 ((and (not (eq org-support-shift-select 'always))
13539 (org-on-heading-p))
13540 (call-interactively 'org-priority-down))
13541 ((and (not org-support-shift-select) (org-at-item-p))
13542 (call-interactively 'org-next-item))
13543 ((org-clocktable-try-shift 'down arg))
13544 (org-support-shift-select
13545 (org-call-for-shift-select 'next-line))
13546 (t (org-shiftselect-error))))
13548 (defun org-shiftright (&optional arg)
13549 "Cycle the thing at point or in the current line, depending on context.
13550 Depending on context, this does one of the following:
13552 - switch a timestamp at point one day into the future
13553 - on a headline, switch to the next TODO keyword.
13554 - on an item, switch entire list to the next bullet type
13555 - on a property line, switch to the next allowed value
13556 - on a clocktable definition line, move time block into the future"
13557 (interactive "P")
13558 (cond
13559 ((and org-support-shift-select (org-region-active-p))
13560 (org-call-for-shift-select 'forward-char))
13561 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13562 ((and (not (eq org-support-shift-select 'always))
13563 (org-on-heading-p))
13564 (org-call-with-arg 'org-todo 'right))
13565 ((or (and org-support-shift-select
13566 (not (eq org-support-shift-select 'always))
13567 (org-at-item-bullet-p))
13568 (and (not org-support-shift-select) (org-at-item-p)))
13569 (org-call-with-arg 'org-cycle-list-bullet nil))
13570 ((and (not (eq org-support-shift-select 'always))
13571 (org-at-property-p))
13572 (call-interactively 'org-property-next-allowed-value))
13573 ((org-clocktable-try-shift 'right arg))
13574 (org-support-shift-select
13575 (org-call-for-shift-select 'forward-char))
13576 (t (org-shiftselect-error))))
13578 (defun org-shiftleft (&optional arg)
13579 "Cycle the thing at point or in the current line, depending on context.
13580 Depending on context, this does one of the following:
13582 - switch a timestamp at point one day into the past
13583 - on a headline, switch to the previous TODO keyword.
13584 - on an item, switch entire list to the previous bullet type
13585 - on a property line, switch to the previous allowed value
13586 - on a clocktable definition line, move time block into the past"
13587 (interactive "P")
13588 (cond
13589 ((and org-support-shift-select (org-region-active-p))
13590 (org-call-for-shift-select 'backward-char))
13591 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13592 ((and (not (eq org-support-shift-select 'always))
13593 (org-on-heading-p))
13594 (org-call-with-arg 'org-todo 'left))
13595 ((or (and org-support-shift-select
13596 (not (eq org-support-shift-select 'always))
13597 (org-at-item-bullet-p))
13598 (and (not org-support-shift-select) (org-at-item-p)))
13599 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13600 ((and (not (eq org-support-shift-select 'always))
13601 (org-at-property-p))
13602 (call-interactively 'org-property-previous-allowed-value))
13603 ((org-clocktable-try-shift 'left arg))
13604 (org-support-shift-select
13605 (org-call-for-shift-select 'backward-char))
13606 (t (org-shiftselect-error))))
13608 (defun org-shiftcontrolright ()
13609 "Switch to next TODO set."
13610 (interactive)
13611 (cond
13612 ((and org-support-shift-select (org-region-active-p))
13613 (org-call-for-shift-select 'forward-word))
13614 ((and (not (eq org-support-shift-select 'always))
13615 (org-on-heading-p))
13616 (org-call-with-arg 'org-todo 'nextset))
13617 (org-support-shift-select
13618 (org-call-for-shift-select 'forward-word))
13619 (t (org-shiftselect-error))))
13621 (defun org-shiftcontrolleft ()
13622 "Switch to previous TODO set."
13623 (interactive)
13624 (cond
13625 ((and org-support-shift-select (org-region-active-p))
13626 (org-call-for-shift-select 'backward-word))
13627 ((and (not (eq org-support-shift-select 'always))
13628 (org-on-heading-p))
13629 (org-call-with-arg 'org-todo 'previousset))
13630 (org-support-shift-select
13631 (org-call-for-shift-select 'backward-word))
13632 (t (org-shiftselect-error))))
13634 (defun org-ctrl-c-ret ()
13635 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13636 (interactive)
13637 (cond
13638 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13639 (t (call-interactively 'org-insert-heading))))
13641 (defun org-copy-special ()
13642 "Copy region in table or copy current subtree.
13643 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13644 See the individual commands for more information."
13645 (interactive)
13646 (call-interactively
13647 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13649 (defun org-cut-special ()
13650 "Cut region in table or cut current subtree.
13651 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13652 See the individual commands for more information."
13653 (interactive)
13654 (call-interactively
13655 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13657 (defun org-paste-special (arg)
13658 "Paste rectangular region into table, or past subtree relative to level.
13659 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13660 See the individual commands for more information."
13661 (interactive "P")
13662 (if (org-at-table-p)
13663 (org-table-paste-rectangle)
13664 (org-paste-subtree arg)))
13666 (defun org-edit-special ()
13667 "Call a special editor for the stuff at point.
13668 When at a table, call the formula editor with `org-table-edit-formulas'.
13669 When at the first line of an src example, call `org-edit-src-code'.
13670 When in an #+include line, visit the include file. Otherwise call
13671 `ffap' to visit the file at point."
13672 (interactive)
13673 (cond
13674 ((org-at-table-p)
13675 (call-interactively 'org-table-edit-formulas))
13676 ((save-excursion
13677 (beginning-of-line 1)
13678 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13679 (find-file (org-trim (match-string 1))))
13680 ((org-edit-src-code))
13681 ((org-edit-fixed-width-region))
13682 (t (call-interactively 'ffap))))
13685 (defun org-ctrl-c-ctrl-c (&optional arg)
13686 "Set tags in headline, or update according to changed information at point.
13688 This command does many different things, depending on context:
13690 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
13691 this is what we do.
13693 - If the cursor is in a headline, prompt for tags and insert them
13694 into the current line, aligned to `org-tags-column'. When called
13695 with prefix arg, realign all tags in the current buffer.
13697 - If the cursor is in one of the special #+KEYWORD lines, this
13698 triggers scanning the buffer for these lines and updating the
13699 information.
13701 - If the cursor is inside a table, realign the table. This command
13702 works even if the automatic table editor has been turned off.
13704 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13705 the entire table.
13707 - If the cursor is at a footnote reference or definition, jump to
13708 the corresponding definition or references, respectively.
13710 - If the cursor is a the beginning of a dynamic block, update it.
13712 - If the cursor is inside a table created by the table.el package,
13713 activate that table.
13715 - If the current buffer is a remember buffer, close note and file
13716 it. A prefix argument of 1 files to the default location
13717 without further interaction. A prefix argument of 2 files to
13718 the currently clocking task.
13720 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13721 links in this buffer.
13723 - If the cursor is on a numbered item in a plain list, renumber the
13724 ordered list.
13726 - If the cursor is on a checkbox, toggle it."
13727 (interactive "P")
13728 (let ((org-enable-table-editor t))
13729 (cond
13730 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13731 org-occur-highlights
13732 org-latex-fragment-image-overlays)
13733 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13734 (org-remove-occur-highlights)
13735 (org-remove-latex-fragment-image-overlays)
13736 (message "Temporary highlights/overlays removed from current buffer"))
13737 ((and (local-variable-p 'org-finish-function (current-buffer))
13738 (fboundp org-finish-function))
13739 (funcall org-finish-function))
13740 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
13741 ((org-at-property-p)
13742 (call-interactively 'org-property-action))
13743 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13744 ((org-on-heading-p) (call-interactively 'org-set-tags))
13745 ((org-at-table.el-p)
13746 (require 'table)
13747 (beginning-of-line 1)
13748 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13749 (call-interactively 'table-recognize-table))
13750 ((org-at-table-p)
13751 (org-table-maybe-eval-formula)
13752 (if arg
13753 (call-interactively 'org-table-recalculate)
13754 (org-table-maybe-recalculate-line))
13755 (call-interactively 'org-table-align))
13756 ((or (org-footnote-at-reference-p)
13757 (org-footnote-at-definition-p))
13758 (call-interactively 'org-footnote-action))
13759 ((org-at-item-checkbox-p)
13760 (call-interactively 'org-toggle-checkbox))
13761 ((org-at-item-p)
13762 (if arg
13763 (call-interactively 'org-toggle-checkbox)
13764 (call-interactively 'org-maybe-renumber-ordered-list)))
13765 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13766 ;; Dynamic block
13767 (beginning-of-line 1)
13768 (save-excursion (org-update-dblock)))
13769 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13770 (cond
13771 ((equal (match-string 1) "TBLFM")
13772 ;; Recalculate the table before this line
13773 (save-excursion
13774 (beginning-of-line 1)
13775 (skip-chars-backward " \r\n\t")
13776 (if (org-at-table-p)
13777 (org-call-with-arg 'org-table-recalculate t))))
13779 ; (org-set-regexps-and-options)
13780 ; (org-restart-font-lock)
13781 (let ((org-inhibit-startup t)) (org-mode-restart))
13782 (message "Local setup has been refreshed"))))
13783 (t (error "C-c C-c can do nothing useful at this location.")))))
13785 (defun org-mode-restart ()
13786 "Restart Org-mode, to scan again for special lines.
13787 Also updates the keyword regular expressions."
13788 (interactive)
13789 (org-mode)
13790 (message "Org-mode restarted"))
13792 (defun org-kill-note-or-show-branches ()
13793 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13794 (interactive)
13795 (if (not org-finish-function)
13796 (call-interactively 'show-branches)
13797 (let ((org-note-abort t))
13798 (funcall org-finish-function))))
13800 (defun org-return (&optional indent)
13801 "Goto next table row or insert a newline.
13802 Calls `org-table-next-row' or `newline', depending on context.
13803 See the individual commands for more information."
13804 (interactive)
13805 (cond
13806 ((bobp) (if indent (newline-and-indent) (newline)))
13807 ((org-at-table-p)
13808 (org-table-justify-field-maybe)
13809 (call-interactively 'org-table-next-row))
13810 ((and org-return-follows-link
13811 (eq (get-text-property (point) 'face) 'org-link))
13812 (call-interactively 'org-open-at-point))
13813 ((and (org-at-heading-p)
13814 (looking-at
13815 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13816 (org-show-entry)
13817 (end-of-line 1)
13818 (newline))
13819 (t (if indent (newline-and-indent) (newline)))))
13821 (defun org-return-indent ()
13822 "Goto next table row or insert a newline and indent.
13823 Calls `org-table-next-row' or `newline-and-indent', depending on
13824 context. See the individual commands for more information."
13825 (interactive)
13826 (org-return t))
13828 (defun org-ctrl-c-star ()
13829 "Compute table, or change heading status of lines.
13830 Calls `org-table-recalculate' or `org-toggle-heading',
13831 depending on context."
13832 (interactive)
13833 (cond
13834 ((org-at-table-p)
13835 (call-interactively 'org-table-recalculate))
13837 ;; Convert all lines in region to list items
13838 (call-interactively 'org-toggle-heading))))
13840 (defun org-ctrl-c-minus ()
13841 "Insert separator line in table or modify bullet status of line.
13842 Also turns a plain line or a region of lines into list items.
13843 Calls `org-table-insert-hline', `org-toggle-item', or
13844 `org-cycle-list-bullet', depending on context."
13845 (interactive)
13846 (cond
13847 ((org-at-table-p)
13848 (call-interactively 'org-table-insert-hline))
13849 ((org-region-active-p)
13850 (call-interactively 'org-toggle-item))
13851 ((org-in-item-p)
13852 (call-interactively 'org-cycle-list-bullet))
13854 (call-interactively 'org-toggle-item))))
13856 (defun org-toggle-item ()
13857 "Convert headings or normal lines to items, items to normal lines.
13858 If there is no active region, only the current line is considered.
13860 If the first line in the region is a headline, convert all headlines to items.
13862 If the first line in the region is an item, convert all items to normal lines.
13864 If the first line is normal text, add an item bullet to each line."
13865 (interactive)
13866 (let (l2 l beg end)
13867 (if (org-region-active-p)
13868 (setq beg (region-beginning) end (region-end))
13869 (setq beg (point-at-bol)
13870 end (min (1+ (point-at-eol)) (point-max))))
13871 (save-excursion
13872 (goto-char end)
13873 (setq l2 (org-current-line))
13874 (goto-char beg)
13875 (beginning-of-line 1)
13876 (setq l (1- (org-current-line)))
13877 (if (org-at-item-p)
13878 ;; We already have items, de-itemize
13879 (while (< (setq l (1+ l)) l2)
13880 (when (org-at-item-p)
13881 (goto-char (match-beginning 2))
13882 (delete-region (match-beginning 2) (match-end 2))
13883 (and (looking-at "[ \t]+") (replace-match "")))
13884 (beginning-of-line 2))
13885 (if (org-on-heading-p)
13886 ;; Headings, convert to items
13887 (while (< (setq l (1+ l)) l2)
13888 (if (looking-at org-outline-regexp)
13889 (replace-match "- " t t))
13890 (beginning-of-line 2))
13891 ;; normal lines, turn them into items
13892 (while (< (setq l (1+ l)) l2)
13893 (unless (org-at-item-p)
13894 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13895 (replace-match "\\1- \\2")))
13896 (beginning-of-line 2)))))))
13898 (defun org-toggle-heading (&optional nstars)
13899 "Convert headings to normal text, or items or text to headings.
13900 If there is no active region, only the current line is considered.
13902 If the first line is a heading, remove the stars from all headlines
13903 in the region.
13905 If the first line is a plain list item, turn all plain list items into
13906 headings.
13908 If the first line is a normal line, turn each and every line in the region
13909 into a heading.
13911 When converting a line into a heading, the number of stars is chosen
13912 such that the lines become children of the current entry. However, when
13913 a prefix argument is given, its value determines the number of stars to add."
13914 (interactive "P")
13915 (let (l2 l itemp beg end)
13916 (if (org-region-active-p)
13917 (setq beg (region-beginning) end (region-end))
13918 (setq beg (point-at-bol)
13919 end (min (1+ (point-at-eol)) (point-max))))
13920 (save-excursion
13921 (goto-char end)
13922 (setq l2 (org-current-line))
13923 (goto-char beg)
13924 (beginning-of-line 1)
13925 (setq l (1- (org-current-line)))
13926 (if (org-on-heading-p)
13927 ;; We already have headlines, de-star them
13928 (while (< (setq l (1+ l)) l2)
13929 (when (org-on-heading-p t)
13930 (and (looking-at outline-regexp) (replace-match "")))
13931 (beginning-of-line 2))
13932 (setq itemp (org-at-item-p))
13933 (let* ((stars
13934 (if nstars
13935 (make-string (prefix-numeric-value current-prefix-arg)
13937 (save-excursion
13938 (re-search-backward org-complex-heading-regexp nil t)
13939 (or (match-string 1) "*"))))
13940 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13941 (rpl (concat stars add-stars " ")))
13942 (while (< (setq l (1+ l)) l2)
13943 (if itemp
13944 (and (org-at-item-p) (replace-match rpl t t))
13945 (unless (org-on-heading-p)
13946 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13947 (replace-match (concat rpl (match-string 2))))))
13948 (beginning-of-line 2)))))))
13950 (defun org-meta-return (&optional arg)
13951 "Insert a new heading or wrap a region in a table.
13952 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13953 See the individual commands for more information."
13954 (interactive "P")
13955 (cond
13956 ((run-hook-with-args-until-success 'org-metareturn-hook))
13957 ((org-at-table-p)
13958 (call-interactively 'org-table-wrap-region))
13959 (t (call-interactively 'org-insert-heading))))
13961 ;;; Menu entries
13963 ;; Define the Org-mode menus
13964 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13965 '("Tbl"
13966 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13967 ["Next Field" org-cycle (org-at-table-p)]
13968 ["Previous Field" org-shifttab (org-at-table-p)]
13969 ["Next Row" org-return (org-at-table-p)]
13970 "--"
13971 ["Blank Field" org-table-blank-field (org-at-table-p)]
13972 ["Edit Field" org-table-edit-field (org-at-table-p)]
13973 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13974 "--"
13975 ("Column"
13976 ["Move Column Left" org-metaleft (org-at-table-p)]
13977 ["Move Column Right" org-metaright (org-at-table-p)]
13978 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13979 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13980 ("Row"
13981 ["Move Row Up" org-metaup (org-at-table-p)]
13982 ["Move Row Down" org-metadown (org-at-table-p)]
13983 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13984 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13985 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13986 "--"
13987 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13988 ("Rectangle"
13989 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13990 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13991 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13992 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13993 "--"
13994 ("Calculate"
13995 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13996 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13997 ["Edit Formulas" org-edit-special (org-at-table-p)]
13998 "--"
13999 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14000 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14001 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14002 "--"
14003 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14004 "--"
14005 ["Sum Column/Rectangle" org-table-sum
14006 (or (org-at-table-p) (org-region-active-p))]
14007 ["Which Column?" org-table-current-column (org-at-table-p)])
14008 ["Debug Formulas"
14009 org-table-toggle-formula-debugger
14010 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14011 ["Show Col/Row Numbers"
14012 org-table-toggle-coordinate-overlays
14013 :style toggle
14014 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14015 "--"
14016 ["Create" org-table-create (and (not (org-at-table-p))
14017 org-enable-table-editor)]
14018 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14019 ["Import from File" org-table-import (not (org-at-table-p))]
14020 ["Export to File" org-table-export (org-at-table-p)]
14021 "--"
14022 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14024 (easy-menu-define org-org-menu org-mode-map "Org menu"
14025 '("Org"
14026 ("Show/Hide"
14027 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14028 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14029 ["Sparse Tree..." org-sparse-tree t]
14030 ["Reveal Context" org-reveal t]
14031 ["Show All" show-all t]
14032 "--"
14033 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14034 "--"
14035 ["New Heading" org-insert-heading t]
14036 ("Navigate Headings"
14037 ["Up" outline-up-heading t]
14038 ["Next" outline-next-visible-heading t]
14039 ["Previous" outline-previous-visible-heading t]
14040 ["Next Same Level" outline-forward-same-level t]
14041 ["Previous Same Level" outline-backward-same-level t]
14042 "--"
14043 ["Jump" org-goto t])
14044 ("Edit Structure"
14045 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14046 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14047 "--"
14048 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14049 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14050 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14051 "--"
14052 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14053 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14054 ["Demote Heading" org-metaright (not (org-at-table-p))]
14055 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14056 "--"
14057 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14058 "--"
14059 ["Convert to odd levels" org-convert-to-odd-levels t]
14060 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14061 ("Editing"
14062 ["Emphasis..." org-emphasize t]
14063 ["Edit Source Example" org-edit-special t]
14064 "--"
14065 ["Footnote new/jump" org-footnote-action t]
14066 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14067 ("Archive"
14068 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14069 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14070 ; :active t :keys "C-u C-c C-x C-a"]
14071 ["Sparse trees open ARCHIVE trees"
14072 (setq org-sparse-tree-open-archived-trees
14073 (not org-sparse-tree-open-archived-trees))
14074 :style toggle :selected org-sparse-tree-open-archived-trees]
14075 ["Cycling opens ARCHIVE trees"
14076 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14077 :style toggle :selected org-cycle-open-archived-trees]
14078 "--"
14079 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14080 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14081 ; ["Check and Move Children" (org-archive-subtree '(4))
14082 ; :active t :keys "C-u C-c C-x C-s"]
14084 "--"
14085 ("TODO Lists"
14086 ["TODO/DONE/-" org-todo t]
14087 ("Select keyword"
14088 ["Next keyword" org-shiftright (org-on-heading-p)]
14089 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14090 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14091 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14092 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14093 ["Show TODO Tree" org-show-todo-tree t]
14094 ["Global TODO list" org-todo-list t]
14095 "--"
14096 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14097 :selected org-enforce-todo-dependencies :style toggle :active t]
14098 "Settings for tree at point"
14099 ["Do Children sequentially" org-toggle-ordered-property :style radio
14100 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14101 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14102 ["Do Children parallel" org-toggle-ordered-property :style radio
14103 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14104 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14105 "--"
14106 ["Set Priority" org-priority t]
14107 ["Priority Up" org-shiftup t]
14108 ["Priority Down" org-shiftdown t])
14109 ("TAGS and Properties"
14110 ["Set Tags" org-set-tags-command t]
14111 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14112 "--"
14113 ["Set property" org-set-property t]
14114 ["Column view of properties" org-columns t]
14115 ["Insert Column View DBlock" org-insert-columns-dblock t])
14116 ("Dates and Scheduling"
14117 ["Timestamp" org-time-stamp t]
14118 ["Timestamp (inactive)" org-time-stamp-inactive t]
14119 ("Change Date"
14120 ["1 Day Later" org-shiftright t]
14121 ["1 Day Earlier" org-shiftleft t]
14122 ["1 ... Later" org-shiftup t]
14123 ["1 ... Earlier" org-shiftdown t])
14124 ["Compute Time Range" org-evaluate-time-range t]
14125 ["Schedule Item" org-schedule t]
14126 ["Deadline" org-deadline t]
14127 "--"
14128 ["Custom time format" org-toggle-time-stamp-overlays
14129 :style radio :selected org-display-custom-times]
14130 "--"
14131 ["Goto Calendar" org-goto-calendar t]
14132 ["Date from Calendar" org-date-from-calendar t]
14133 "--"
14134 ["Start/Restart Timer" org-timer-start t]
14135 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14136 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14137 ["Insert Timer String" org-timer t]
14138 ["Insert Timer Item" org-timer-item t])
14139 ("Logging work"
14140 ["Clock in" org-clock-in t]
14141 ["Clock out" org-clock-out t]
14142 ["Clock cancel" org-clock-cancel t]
14143 ["Goto running clock" org-clock-goto t]
14144 ["Display times" org-clock-display t]
14145 ["Create clock table" org-clock-report t]
14146 "--"
14147 ["Record DONE time"
14148 (progn (setq org-log-done (not org-log-done))
14149 (message "Switching to %s will %s record a timestamp"
14150 (car org-done-keywords)
14151 (if org-log-done "automatically" "not")))
14152 :style toggle :selected org-log-done])
14153 "--"
14154 ["Agenda Command..." org-agenda t]
14155 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14156 ("File List for Agenda")
14157 ("Special views current file"
14158 ["TODO Tree" org-show-todo-tree t]
14159 ["Check Deadlines" org-check-deadlines t]
14160 ["Timeline" org-timeline t]
14161 ["Tags Tree" org-tags-sparse-tree t])
14162 "--"
14163 ("Hyperlinks"
14164 ["Store Link (Global)" org-store-link t]
14165 ["Insert Link" org-insert-link t]
14166 ["Follow Link" org-open-at-point t]
14167 "--"
14168 ["Next link" org-next-link t]
14169 ["Previous link" org-previous-link t]
14170 "--"
14171 ["Descriptive Links"
14172 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14173 :style radio
14174 :selected (member '(org-link) buffer-invisibility-spec)]
14175 ["Literal Links"
14176 (progn
14177 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14178 :style radio
14179 :selected (not (member '(org-link) buffer-invisibility-spec))])
14180 "--"
14181 ["Export/Publish..." org-export t]
14182 ("LaTeX"
14183 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14184 :selected org-cdlatex-mode]
14185 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14186 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14187 ["Modify math symbol" org-cdlatex-math-modify
14188 (org-inside-LaTeX-fragment-p)]
14189 ["Export LaTeX fragments as images"
14190 (if (featurep 'org-exp)
14191 (setq org-export-with-LaTeX-fragments
14192 (not org-export-with-LaTeX-fragments))
14193 (require 'org-exp))
14194 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14195 org-export-with-LaTeX-fragments)])
14196 "--"
14197 ("Documentation"
14198 ["Show Version" org-version t]
14199 ["Info Documentation" org-info t])
14200 ("Customize"
14201 ["Browse Org Group" org-customize t]
14202 "--"
14203 ["Expand This Menu" org-create-customize-menu
14204 (fboundp 'customize-menu-create)])
14205 "--"
14206 ["Refresh setup" org-mode-restart t]
14209 (defun org-info (&optional node)
14210 "Read documentation for Org-mode in the info system.
14211 With optional NODE, go directly to that node."
14212 (interactive)
14213 (info (format "(org)%s" (or node ""))))
14215 (defun org-install-agenda-files-menu ()
14216 (let ((bl (buffer-list)))
14217 (save-excursion
14218 (while bl
14219 (set-buffer (pop bl))
14220 (if (org-mode-p) (setq bl nil)))
14221 (when (org-mode-p)
14222 (easy-menu-change
14223 '("Org") "File List for Agenda"
14224 (append
14225 (list
14226 ["Edit File List" (org-edit-agenda-file-list) t]
14227 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14228 ["Remove Current File from List" org-remove-file t]
14229 ["Cycle through agenda files" org-cycle-agenda-files t]
14230 ["Occur in all agenda files" org-occur-in-agenda-files t]
14231 "--")
14232 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14234 ;;;; Documentation
14236 ;;;###autoload
14237 (defun org-require-autoloaded-modules ()
14238 (interactive)
14239 (mapc 'require
14240 '(org-agenda org-archive org-attach org-clock org-colview
14241 org-exp org-id org-export-latex org-publish
14242 org-remember org-table org-timer)))
14244 ;;;###autoload
14245 (defun org-customize ()
14246 "Call the customize function with org as argument."
14247 (interactive)
14248 (org-load-modules-maybe)
14249 (org-require-autoloaded-modules)
14250 (customize-browse 'org))
14252 (defun org-create-customize-menu ()
14253 "Create a full customization menu for Org-mode, insert it into the menu."
14254 (interactive)
14255 (org-load-modules-maybe)
14256 (org-require-autoloaded-modules)
14257 (if (fboundp 'customize-menu-create)
14258 (progn
14259 (easy-menu-change
14260 '("Org") "Customize"
14261 `(["Browse Org group" org-customize t]
14262 "--"
14263 ,(customize-menu-create 'org)
14264 ["Set" Custom-set t]
14265 ["Save" Custom-save t]
14266 ["Reset to Current" Custom-reset-current t]
14267 ["Reset to Saved" Custom-reset-saved t]
14268 ["Reset to Standard Settings" Custom-reset-standard t]))
14269 (message "\"Org\"-menu now contains full customization menu"))
14270 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14272 ;;;; Miscellaneous stuff
14274 ;;; Generally useful functions
14276 (defun org-find-text-property-in-string (prop s)
14277 "Return the first non-nil value of property PROP in string S."
14278 (or (get-text-property 0 prop s)
14279 (get-text-property (or (next-single-property-change 0 prop s) 0)
14280 prop s)))
14282 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14283 "Display the given MESSAGE as a warning."
14284 (if (fboundp 'display-warning)
14285 (display-warning 'org message
14286 (if (featurep 'xemacs)
14287 'warning
14288 :warning))
14289 (let ((buf (get-buffer-create "*Org warnings*")))
14290 (with-current-buffer buf
14291 (goto-char (point-max))
14292 (insert "Warning (Org): " message)
14293 (unless (bolp)
14294 (newline)))
14295 (display-buffer buf)
14296 (sit-for 0))))
14298 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14299 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14300 (if (and marker (marker-buffer marker)
14301 (buffer-live-p (marker-buffer marker)))
14302 (progn
14303 (switch-to-buffer (marker-buffer marker))
14304 (if (or (> marker (point-max)) (< marker (point-min)))
14305 (widen))
14306 (goto-char marker)
14307 (org-show-context 'org-goto))
14308 (if bookmark
14309 (bookmark-jump bookmark)
14310 (error "Cannot find location"))))
14312 (defun org-quote-csv-field (s)
14313 "Quote field for inclusion in CSV material."
14314 (if (string-match "[\",]" s)
14315 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14318 (defun org-plist-delete (plist property)
14319 "Delete PROPERTY from PLIST.
14320 This is in contrast to merely setting it to 0."
14321 (let (p)
14322 (while plist
14323 (if (not (eq property (car plist)))
14324 (setq p (plist-put p (car plist) (nth 1 plist))))
14325 (setq plist (cddr plist)))
14328 (defun org-force-self-insert (N)
14329 "Needed to enforce self-insert under remapping."
14330 (interactive "p")
14331 (self-insert-command N))
14333 (defun org-string-width (s)
14334 "Compute width of string, ignoring invisible characters.
14335 This ignores character with invisibility property `org-link', and also
14336 characters with property `org-cwidth', because these will become invisible
14337 upon the next fontification round."
14338 (let (b l)
14339 (when (or (eq t buffer-invisibility-spec)
14340 (assq 'org-link buffer-invisibility-spec))
14341 (while (setq b (text-property-any 0 (length s)
14342 'invisible 'org-link s))
14343 (setq s (concat (substring s 0 b)
14344 (substring s (or (next-single-property-change
14345 b 'invisible s) (length s)))))))
14346 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14347 (setq s (concat (substring s 0 b)
14348 (substring s (or (next-single-property-change
14349 b 'org-cwidth s) (length s))))))
14350 (setq l (string-width s) b -1)
14351 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14352 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14355 (defun org-get-indentation (&optional line)
14356 "Get the indentation of the current line, interpreting tabs.
14357 When LINE is given, assume it represents a line and compute its indentation."
14358 (if line
14359 (if (string-match "^ *" (org-remove-tabs line))
14360 (match-end 0))
14361 (save-excursion
14362 (beginning-of-line 1)
14363 (skip-chars-forward " \t")
14364 (current-column))))
14366 (defun org-remove-tabs (s &optional width)
14367 "Replace tabulators in S with spaces.
14368 Assumes that s is a single line, starting in column 0."
14369 (setq width (or width tab-width))
14370 (while (string-match "\t" s)
14371 (setq s (replace-match
14372 (make-string
14373 (- (* width (/ (+ (match-beginning 0) width) width))
14374 (match-beginning 0)) ?\ )
14375 t t s)))
14378 (defun org-fix-indentation (line ind)
14379 "Fix indentation in LINE.
14380 IND is a cons cell with target and minimum indentation.
14381 If the current indentation in LINE is smaller than the minimum,
14382 leave it alone. If it is larger than ind, set it to the target."
14383 (let* ((l (org-remove-tabs line))
14384 (i (org-get-indentation l))
14385 (i1 (car ind)) (i2 (cdr ind)))
14386 (if (>= i i2) (setq l (substring line i2)))
14387 (if (> i1 0)
14388 (concat (make-string i1 ?\ ) l)
14389 l)))
14391 (defun org-base-buffer (buffer)
14392 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14393 (if (not buffer)
14394 buffer
14395 (or (buffer-base-buffer buffer)
14396 buffer)))
14398 (defun org-trim (s)
14399 "Remove whitespace at beginning and end of string."
14400 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14401 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14404 (defun org-wrap (string &optional width lines)
14405 "Wrap string to either a number of lines, or a width in characters.
14406 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14407 that costs. If there is a word longer than WIDTH, the text is actually
14408 wrapped to the length of that word.
14409 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14410 many lines, whatever width that takes.
14411 The return value is a list of lines, without newlines at the end."
14412 (let* ((words (org-split-string string "[ \t\n]+"))
14413 (maxword (apply 'max (mapcar 'org-string-width words)))
14414 w ll)
14415 (cond (width
14416 (org-do-wrap words (max maxword width)))
14417 (lines
14418 (setq w maxword)
14419 (setq ll (org-do-wrap words maxword))
14420 (if (<= (length ll) lines)
14422 (setq ll words)
14423 (while (> (length ll) lines)
14424 (setq w (1+ w))
14425 (setq ll (org-do-wrap words w)))
14426 ll))
14427 (t (error "Cannot wrap this")))))
14429 (defun org-do-wrap (words width)
14430 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14431 (let (lines line)
14432 (while words
14433 (setq line (pop words))
14434 (while (and words (< (+ (length line) (length (car words))) width))
14435 (setq line (concat line " " (pop words))))
14436 (setq lines (push line lines)))
14437 (nreverse lines)))
14439 (defun org-split-string (string &optional separators)
14440 "Splits STRING into substrings at SEPARATORS.
14441 No empty strings are returned if there are matches at the beginning
14442 and end of string."
14443 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14444 (start 0)
14445 notfirst
14446 (list nil))
14447 (while (and (string-match rexp string
14448 (if (and notfirst
14449 (= start (match-beginning 0))
14450 (< start (length string)))
14451 (1+ start) start))
14452 (< (match-beginning 0) (length string)))
14453 (setq notfirst t)
14454 (or (eq (match-beginning 0) 0)
14455 (and (eq (match-beginning 0) (match-end 0))
14456 (eq (match-beginning 0) start))
14457 (setq list
14458 (cons (substring string start (match-beginning 0))
14459 list)))
14460 (setq start (match-end 0)))
14461 (or (eq start (length string))
14462 (setq list
14463 (cons (substring string start)
14464 list)))
14465 (nreverse list)))
14467 (defun org-context ()
14468 "Return a list of contexts of the current cursor position.
14469 If several contexts apply, all are returned.
14470 Each context entry is a list with a symbol naming the context, and
14471 two positions indicating start and end of the context. Possible
14472 contexts are:
14474 :headline anywhere in a headline
14475 :headline-stars on the leading stars in a headline
14476 :todo-keyword on a TODO keyword (including DONE) in a headline
14477 :tags on the TAGS in a headline
14478 :priority on the priority cookie in a headline
14479 :item on the first line of a plain list item
14480 :item-bullet on the bullet/number of a plain list item
14481 :checkbox on the checkbox in a plain list item
14482 :table in an org-mode table
14483 :table-special on a special filed in a table
14484 :table-table in a table.el table
14485 :link on a hyperlink
14486 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14487 :target on a <<target>>
14488 :radio-target on a <<<radio-target>>>
14489 :latex-fragment on a LaTeX fragment
14490 :latex-preview on a LaTeX fragment with overlayed preview image
14492 This function expects the position to be visible because it uses font-lock
14493 faces as a help to recognize the following contexts: :table-special, :link,
14494 and :keyword."
14495 (let* ((f (get-text-property (point) 'face))
14496 (faces (if (listp f) f (list f)))
14497 (p (point)) clist o)
14498 ;; First the large context
14499 (cond
14500 ((org-on-heading-p t)
14501 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14502 (when (progn
14503 (beginning-of-line 1)
14504 (looking-at org-todo-line-tags-regexp))
14505 (push (org-point-in-group p 1 :headline-stars) clist)
14506 (push (org-point-in-group p 2 :todo-keyword) clist)
14507 (push (org-point-in-group p 4 :tags) clist))
14508 (goto-char p)
14509 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14510 (if (looking-at "\\[#[A-Z0-9]\\]")
14511 (push (org-point-in-group p 0 :priority) clist)))
14513 ((org-at-item-p)
14514 (push (org-point-in-group p 2 :item-bullet) clist)
14515 (push (list :item (point-at-bol)
14516 (save-excursion (org-end-of-item) (point)))
14517 clist)
14518 (and (org-at-item-checkbox-p)
14519 (push (org-point-in-group p 0 :checkbox) clist)))
14521 ((org-at-table-p)
14522 (push (list :table (org-table-begin) (org-table-end)) clist)
14523 (if (memq 'org-formula faces)
14524 (push (list :table-special
14525 (previous-single-property-change p 'face)
14526 (next-single-property-change p 'face)) clist)))
14527 ((org-at-table-p 'any)
14528 (push (list :table-table) clist)))
14529 (goto-char p)
14531 ;; Now the small context
14532 (cond
14533 ((org-at-timestamp-p)
14534 (push (org-point-in-group p 0 :timestamp) clist))
14535 ((memq 'org-link faces)
14536 (push (list :link
14537 (previous-single-property-change p 'face)
14538 (next-single-property-change p 'face)) clist))
14539 ((memq 'org-special-keyword faces)
14540 (push (list :keyword
14541 (previous-single-property-change p 'face)
14542 (next-single-property-change p 'face)) clist))
14543 ((org-on-target-p)
14544 (push (org-point-in-group p 0 :target) clist)
14545 (goto-char (1- (match-beginning 0)))
14546 (if (looking-at org-radio-target-regexp)
14547 (push (org-point-in-group p 0 :radio-target) clist))
14548 (goto-char p))
14549 ((setq o (car (delq nil
14550 (mapcar
14551 (lambda (x)
14552 (if (memq x org-latex-fragment-image-overlays) x))
14553 (org-overlays-at (point))))))
14554 (push (list :latex-fragment
14555 (org-overlay-start o) (org-overlay-end o)) clist)
14556 (push (list :latex-preview
14557 (org-overlay-start o) (org-overlay-end o)) clist))
14558 ((org-inside-LaTeX-fragment-p)
14559 ;; FIXME: positions wrong.
14560 (push (list :latex-fragment (point) (point)) clist)))
14562 (setq clist (nreverse (delq nil clist)))
14563 clist))
14565 ;; FIXME: Compare with at-regexp-p Do we need both?
14566 (defun org-in-regexp (re &optional nlines visually)
14567 "Check if point is inside a match of regexp.
14568 Normally only the current line is checked, but you can include NLINES extra
14569 lines both before and after point into the search.
14570 If VISUALLY is set, require that the cursor is not after the match but
14571 really on, so that the block visually is on the match."
14572 (catch 'exit
14573 (let ((pos (point))
14574 (eol (point-at-eol (+ 1 (or nlines 0))))
14575 (inc (if visually 1 0)))
14576 (save-excursion
14577 (beginning-of-line (- 1 (or nlines 0)))
14578 (while (re-search-forward re eol t)
14579 (if (and (<= (match-beginning 0) pos)
14580 (>= (+ inc (match-end 0)) pos))
14581 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14583 (defun org-at-regexp-p (regexp)
14584 "Is point inside a match of REGEXP in the current line?"
14585 (catch 'exit
14586 (save-excursion
14587 (let ((pos (point)) (end (point-at-eol)))
14588 (beginning-of-line 1)
14589 (while (re-search-forward regexp end t)
14590 (if (and (<= (match-beginning 0) pos)
14591 (>= (match-end 0) pos))
14592 (throw 'exit t)))
14593 nil))))
14595 (defun org-occur-in-agenda-files (regexp &optional nlines)
14596 "Call `multi-occur' with buffers for all agenda files."
14597 (interactive "sOrg-files matching: \np")
14598 (let* ((files (org-agenda-files))
14599 (tnames (mapcar 'file-truename files))
14600 (extra org-agenda-text-search-extra-files)
14602 (when (eq (car extra) 'agenda-archives)
14603 (setq extra (cdr extra))
14604 (setq files (org-add-archive-files files)))
14605 (while (setq f (pop extra))
14606 (unless (member (file-truename f) tnames)
14607 (add-to-list 'files f 'append)
14608 (add-to-list 'tnames (file-truename f) 'append)))
14609 (multi-occur
14610 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14611 regexp)))
14613 (if (boundp 'occur-mode-find-occurrence-hook)
14614 ;; Emacs 23
14615 (add-hook 'occur-mode-find-occurrence-hook
14616 (lambda ()
14617 (when (org-mode-p)
14618 (org-reveal))))
14619 ;; Emacs 22
14620 (defadvice occur-mode-goto-occurrence
14621 (after org-occur-reveal activate)
14622 (and (org-mode-p) (org-reveal)))
14623 (defadvice occur-mode-goto-occurrence-other-window
14624 (after org-occur-reveal activate)
14625 (and (org-mode-p) (org-reveal)))
14626 (defadvice occur-mode-display-occurrence
14627 (after org-occur-reveal activate)
14628 (when (org-mode-p)
14629 (let ((pos (occur-mode-find-occurrence)))
14630 (with-current-buffer (marker-buffer pos)
14631 (save-excursion
14632 (goto-char pos)
14633 (org-reveal)))))))
14635 (defun org-uniquify (list)
14636 "Remove duplicate elements from LIST."
14637 (let (res)
14638 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14639 res))
14641 (defun org-delete-all (elts list)
14642 "Remove all elements in ELTS from LIST."
14643 (while elts
14644 (setq list (delete (pop elts) list)))
14645 list)
14647 (defun org-back-over-empty-lines ()
14648 "Move backwards over whitespace, to the beginning of the first empty line.
14649 Returns the number of empty lines passed."
14650 (let ((pos (point)))
14651 (skip-chars-backward " \t\n\r")
14652 (beginning-of-line 2)
14653 (goto-char (min (point) pos))
14654 (count-lines (point) pos)))
14656 (defun org-skip-whitespace ()
14657 (skip-chars-forward " \t\n\r"))
14659 (defun org-point-in-group (point group &optional context)
14660 "Check if POINT is in match-group GROUP.
14661 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14662 match. If the match group does ot exist or point is not inside it,
14663 return nil."
14664 (and (match-beginning group)
14665 (>= point (match-beginning group))
14666 (<= point (match-end group))
14667 (if context
14668 (list context (match-beginning group) (match-end group))
14669 t)))
14671 (defun org-switch-to-buffer-other-window (&rest args)
14672 "Switch to buffer in a second window on the current frame.
14673 In particular, do not allow pop-up frames."
14674 (let (pop-up-frames special-display-buffer-names special-display-regexps
14675 special-display-function)
14676 (apply 'switch-to-buffer-other-window args)))
14678 (defun org-combine-plists (&rest plists)
14679 "Create a single property list from all plists in PLISTS.
14680 The process starts by copying the first list, and then setting properties
14681 from the other lists. Settings in the last list are the most significant
14682 ones and overrule settings in the other lists."
14683 (let ((rtn (copy-sequence (pop plists)))
14684 p v ls)
14685 (while plists
14686 (setq ls (pop plists))
14687 (while ls
14688 (setq p (pop ls) v (pop ls))
14689 (setq rtn (plist-put rtn p v))))
14690 rtn))
14692 (defun org-move-line-down (arg)
14693 "Move the current line down. With prefix argument, move it past ARG lines."
14694 (interactive "p")
14695 (let ((col (current-column))
14696 beg end pos)
14697 (beginning-of-line 1) (setq beg (point))
14698 (beginning-of-line 2) (setq end (point))
14699 (beginning-of-line (+ 1 arg))
14700 (setq pos (move-marker (make-marker) (point)))
14701 (insert (delete-and-extract-region beg end))
14702 (goto-char pos)
14703 (org-move-to-column col)))
14705 (defun org-move-line-up (arg)
14706 "Move the current line up. With prefix argument, move it past ARG lines."
14707 (interactive "p")
14708 (let ((col (current-column))
14709 beg end pos)
14710 (beginning-of-line 1) (setq beg (point))
14711 (beginning-of-line 2) (setq end (point))
14712 (beginning-of-line (- arg))
14713 (setq pos (move-marker (make-marker) (point)))
14714 (insert (delete-and-extract-region beg end))
14715 (goto-char pos)
14716 (org-move-to-column col)))
14718 (defun org-replace-escapes (string table)
14719 "Replace %-escapes in STRING with values in TABLE.
14720 TABLE is an association list with keys like \"%a\" and string values.
14721 The sequences in STRING may contain normal field width and padding information,
14722 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14723 so values can contain further %-escapes if they are define later in TABLE."
14724 (let ((case-fold-search nil)
14725 e re rpl)
14726 (while (setq e (pop table))
14727 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14728 (while (string-match re string)
14729 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14730 (cdr e)))
14731 (setq string (replace-match rpl t t string))))
14732 string))
14735 (defun org-sublist (list start end)
14736 "Return a section of LIST, from START to END.
14737 Counting starts at 1."
14738 (let (rtn (c start))
14739 (setq list (nthcdr (1- start) list))
14740 (while (and list (<= c end))
14741 (push (pop list) rtn)
14742 (setq c (1+ c)))
14743 (nreverse rtn)))
14745 (defun org-find-base-buffer-visiting (file)
14746 "Like `find-buffer-visiting' but alway return the base buffer and
14747 not an indirect buffer."
14748 (let ((buf (find-buffer-visiting file)))
14749 (if buf
14750 (or (buffer-base-buffer buf) buf)
14751 nil)))
14753 (defun org-image-file-name-regexp (&optional extensions)
14754 "Return regexp matching the file names of images.
14755 If EXTENSIONS is given, only match these."
14756 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14757 (image-file-name-regexp)
14758 (let ((image-file-name-extensions
14759 (or extensions
14760 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14761 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14762 (concat "\\."
14763 (regexp-opt (nconc (mapcar 'upcase
14764 image-file-name-extensions)
14765 image-file-name-extensions)
14767 "\\'"))))
14769 (defun org-file-image-p (file &optional extensions)
14770 "Return non-nil if FILE is an image."
14771 (save-match-data
14772 (string-match (org-image-file-name-regexp extensions) file)))
14774 (defun org-get-cursor-date ()
14775 "Return the date at cursor in as a time.
14776 This works in the calendar and in the agenda, anywhere else it just
14777 returns the current time."
14778 (let (date day defd)
14779 (cond
14780 ((eq major-mode 'calendar-mode)
14781 (setq date (calendar-cursor-to-date)
14782 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14783 ((eq major-mode 'org-agenda-mode)
14784 (setq day (get-text-property (point) 'day))
14785 (if day
14786 (setq date (calendar-gregorian-from-absolute day)
14787 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14788 (nth 2 date))))))
14789 (or defd (current-time))))
14791 (defvar org-agenda-action-marker (make-marker)
14792 "Marker pointing to the entry for the next agenda action.")
14794 (defun org-mark-entry-for-agenda-action ()
14795 "Mark the current entry as target of an agenda action.
14796 Agenda actions are actions executed from the agenda with the key `k',
14797 which make use of the date at the cursor."
14798 (interactive)
14799 (move-marker org-agenda-action-marker
14800 (save-excursion (org-back-to-heading t) (point))
14801 (current-buffer))
14802 (message
14803 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14805 ;;; Paragraph filling stuff.
14806 ;; We want this to be just right, so use the full arsenal.
14808 (defun org-indent-line-function ()
14809 "Indent line like previous, but further if previous was headline or item."
14810 (interactive)
14811 (let* ((pos (point))
14812 (itemp (org-at-item-p))
14813 (org-drawer-regexp (or org-drawer-regexp "\000"))
14814 column bpos bcol tpos tcol bullet btype bullet-type)
14815 ;; Find the previous relevant line
14816 (beginning-of-line 1)
14817 (cond
14818 ((looking-at "#") (setq column 0))
14819 ((looking-at "\\*+ ") (setq column 0))
14820 ((and (looking-at "[ \t]*:END:")
14821 (save-excursion (re-search-backward org-drawer-regexp nil t)))
14822 (save-excursion
14823 (goto-char (1- (match-beginning 1)))
14824 (setq column (current-column))))
14826 (beginning-of-line 0)
14827 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
14828 (not (looking-at "[ \t]*:END:"))
14829 (not (looking-at org-drawer-regexp)))
14830 (beginning-of-line 0))
14831 (cond
14832 ((looking-at "\\*+[ \t]+")
14833 (if (not org-adapt-indentation)
14834 (setq column 0)
14835 (goto-char (match-end 0))
14836 (setq column (current-column))))
14837 ((looking-at org-drawer-regexp)
14838 (goto-char (1- (match-beginning 1)))
14839 (setq column (current-column)))
14840 ((looking-at "\\([ \t]*\\):END:")
14841 (goto-char (match-end 1))
14842 (setq column (current-column)))
14843 ((org-in-item-p)
14844 (org-beginning-of-item)
14845 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14846 (setq bpos (match-beginning 1) tpos (match-end 0)
14847 bcol (progn (goto-char bpos) (current-column))
14848 tcol (progn (goto-char tpos) (current-column))
14849 bullet (match-string 1)
14850 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14851 (if (> tcol (+ bcol org-description-max-indent))
14852 (setq tcol (+ bcol 5)))
14853 (if (not itemp)
14854 (setq column tcol)
14855 (goto-char pos)
14856 (beginning-of-line 1)
14857 (if (looking-at "\\S-")
14858 (progn
14859 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14860 (setq bullet (match-string 1)
14861 btype (if (string-match "[0-9]" bullet) "n" bullet))
14862 (setq column (if (equal btype bullet-type) bcol tcol)))
14863 (setq column (org-get-indentation)))))
14864 (t (setq column (org-get-indentation))))))
14865 (goto-char pos)
14866 (if (<= (current-column) (current-indentation))
14867 (org-indent-line-to column)
14868 (save-excursion (org-indent-line-to column)))
14869 (setq column (current-column))
14870 (beginning-of-line 1)
14871 (if (looking-at
14872 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14873 (replace-match (concat "\\1" (format org-property-format
14874 (match-string 2) (match-string 3)))
14875 t nil))
14876 (org-move-to-column column)))
14878 (defun org-set-autofill-regexps ()
14879 (interactive)
14880 ;; In the paragraph separator we include headlines, because filling
14881 ;; text in a line directly attached to a headline would otherwise
14882 ;; fill the headline as well.
14883 (org-set-local 'comment-start-skip "^#+[ \t]*")
14884 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14885 ;; The paragraph starter includes hand-formatted lists.
14886 (org-set-local 'paragraph-start
14887 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14888 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14889 ;; But only if the user has not turned off tables or fixed-width regions
14890 (org-set-local
14891 'auto-fill-inhibit-regexp
14892 (concat "\\*+ \\|#\\+"
14893 "\\|[ \t]*" org-keyword-time-regexp
14894 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14895 (concat
14896 "\\|[ \t]*["
14897 (if org-enable-table-editor "|" "")
14898 (if org-enable-fixed-width-editor ":" "")
14899 "]"))))
14900 ;; We use our own fill-paragraph function, to make sure that tables
14901 ;; and fixed-width regions are not wrapped. That function will pass
14902 ;; through to `fill-paragraph' when appropriate.
14903 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14904 ; Adaptive filling: To get full control, first make sure that
14905 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14906 (org-set-local 'adaptive-fill-regexp "\000")
14907 (org-set-local 'adaptive-fill-function
14908 'org-adaptive-fill-function)
14909 (org-set-local
14910 'align-mode-rules-list
14911 '((org-in-buffer-settings
14912 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14913 (modes . '(org-mode))))))
14915 (defun org-fill-paragraph (&optional justify)
14916 "Re-align a table, pass through to fill-paragraph if no table."
14917 (let ((table-p (org-at-table-p))
14918 (table.el-p (org-at-table.el-p)))
14919 (cond ((and (equal (char-after (point-at-bol)) ?*)
14920 (save-excursion (goto-char (point-at-bol))
14921 (looking-at outline-regexp)))
14922 t) ; skip headlines
14923 (table.el-p t) ; skip table.el tables
14924 (table-p (org-table-align) t) ; align org-mode tables
14925 (t nil)))) ; call paragraph-fill
14927 ;; For reference, this is the default value of adaptive-fill-regexp
14928 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14930 (defun org-adaptive-fill-function ()
14931 "Return a fill prefix for org-mode files.
14932 In particular, this makes sure hanging paragraphs for hand-formatted lists
14933 work correctly."
14934 (cond ((looking-at "#[ \t]+")
14935 (match-string 0))
14936 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14937 (save-excursion
14938 (if (> (match-end 1) (+ (match-beginning 1)
14939 org-description-max-indent))
14940 (goto-char (+ (match-beginning 1) 5))
14941 (goto-char (match-end 0)))
14942 (make-string (current-column) ?\ )))
14943 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14944 (save-excursion
14945 (goto-char (match-end 0))
14946 (make-string (current-column) ?\ )))
14947 (t nil)))
14949 ;;; Other stuff.
14951 (defun org-toggle-fixed-width-section (arg)
14952 "Toggle the fixed-width export.
14953 If there is no active region, the QUOTE keyword at the current headline is
14954 inserted or removed. When present, it causes the text between this headline
14955 and the next to be exported as fixed-width text, and unmodified.
14956 If there is an active region, this command adds or removes a colon as the
14957 first character of this line. If the first character of a line is a colon,
14958 this line is also exported in fixed-width font."
14959 (interactive "P")
14960 (let* ((cc 0)
14961 (regionp (org-region-active-p))
14962 (beg (if regionp (region-beginning) (point)))
14963 (end (if regionp (region-end)))
14964 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14965 (case-fold-search nil)
14966 (re "[ \t]*\\(:\\)")
14967 off)
14968 (if regionp
14969 (save-excursion
14970 (goto-char beg)
14971 (setq cc (current-column))
14972 (beginning-of-line 1)
14973 (setq off (looking-at re))
14974 (while (> nlines 0)
14975 (setq nlines (1- nlines))
14976 (beginning-of-line 1)
14977 (cond
14978 (arg
14979 (org-move-to-column cc t)
14980 (insert ":\n")
14981 (forward-line -1))
14982 ((and off (looking-at re))
14983 (replace-match "" t t nil 1))
14984 ((not off) (org-move-to-column cc t) (insert ":")))
14985 (forward-line 1)))
14986 (save-excursion
14987 (org-back-to-heading)
14988 (if (looking-at (concat outline-regexp
14989 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14990 (replace-match "" t t nil 1)
14991 (if (looking-at outline-regexp)
14992 (progn
14993 (goto-char (match-end 0))
14994 (insert org-quote-string " "))))))))
14996 ;;;; Functions extending outline functionality
14998 (defun org-beginning-of-line (&optional arg)
14999 "Go to the beginning of the current line. If that is invisible, continue
15000 to a visible line beginning. This makes the function of C-a more intuitive.
15001 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15002 first attempt, and only move to after the tags when the cursor is already
15003 beyond the end of the headline."
15004 (interactive "P")
15005 (let ((pos (point)) refpos)
15006 (beginning-of-line 1)
15007 (if (and arg (fboundp 'move-beginning-of-line))
15008 (call-interactively 'move-beginning-of-line)
15009 (if (bobp)
15011 (backward-char 1)
15012 (if (org-invisible-p)
15013 (while (and (not (bobp)) (org-invisible-p))
15014 (backward-char 1)
15015 (beginning-of-line 1))
15016 (forward-char 1))))
15017 (when org-special-ctrl-a/e
15018 (cond
15019 ((and (looking-at org-complex-heading-regexp)
15020 (= (char-after (match-end 1)) ?\ ))
15021 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15022 (point-at-eol)))
15023 (goto-char
15024 (if (eq org-special-ctrl-a/e t)
15025 (cond ((> pos refpos) refpos)
15026 ((= pos (point)) refpos)
15027 (t (point)))
15028 (cond ((> pos (point)) (point))
15029 ((not (eq last-command this-command)) (point))
15030 (t refpos)))))
15031 ((org-at-item-p)
15032 (goto-char
15033 (if (eq org-special-ctrl-a/e t)
15034 (cond ((> pos (match-end 4)) (match-end 4))
15035 ((= pos (point)) (match-end 4))
15036 (t (point)))
15037 (cond ((> pos (point)) (point))
15038 ((not (eq last-command this-command)) (point))
15039 (t (match-end 4))))))))
15040 (org-no-warnings
15041 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15043 (defun org-end-of-line (&optional arg)
15044 "Go to the end of the line.
15045 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15046 first attempt, and only move to after the tags when the cursor is already
15047 beyond the end of the headline."
15048 (interactive "P")
15049 (if (or (not org-special-ctrl-a/e)
15050 (not (org-on-heading-p))
15051 arg)
15052 (call-interactively (if (fboundp 'move-end-of-line)
15053 'move-end-of-line
15054 'end-of-line))
15055 (let ((pos (point)))
15056 (beginning-of-line 1)
15057 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15058 (if (eq org-special-ctrl-a/e t)
15059 (if (or (< pos (match-beginning 1))
15060 (= pos (match-end 0)))
15061 (goto-char (match-beginning 1))
15062 (goto-char (match-end 0)))
15063 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15064 (goto-char (match-end 0))
15065 (goto-char (match-beginning 1))))
15066 (call-interactively (if (fboundp 'move-end-of-line)
15067 'move-end-of-line
15068 'end-of-line)))))
15069 (org-no-warnings
15070 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
15073 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15074 (define-key org-mode-map "\C-e" 'org-end-of-line)
15076 (defun org-kill-line (&optional arg)
15077 "Kill line, to tags or end of line."
15078 (interactive "P")
15079 (cond
15080 ((or (not org-special-ctrl-k)
15081 (bolp)
15082 (not (org-on-heading-p)))
15083 (call-interactively 'kill-line))
15084 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15085 (kill-region (point) (match-beginning 1))
15086 (org-set-tags nil t))
15087 (t (kill-region (point) (point-at-eol)))))
15089 (define-key org-mode-map "\C-k" 'org-kill-line)
15091 (defun org-yank (&optional arg)
15092 "Yank. If the kill is a subtree, treat it specially.
15093 This command will look at the current kill and check if is a single
15094 subtree, or a series of subtrees[1]. If it passes the test, and if the
15095 cursor is at the beginning of a line or after the stars of a currently
15096 empty headline, then the yank is handled specially. How exactly depends
15097 on the value of the following variables, both set by default.
15099 org-yank-folded-subtrees
15100 When set, the subtree(s) will be folded after insertion, but only
15101 if doing so would now swallow text after the yanked text.
15103 org-yank-adjusted-subtrees
15104 When set, the subtree will be promoted or demoted in order to
15105 fit into the local outline tree structure, which means that the level
15106 will be adjusted so that it becomes the smaller one of the two
15107 *visible* surrounding headings.
15109 Any prefix to this command will cause `yank' to be called directly with
15110 no special treatment. In particular, a simple `C-u' prefix will just
15111 plainly yank the text as it is.
15113 \[1] Basically, the test checks if the first non-white line is a heading
15114 and if there are no other headings with fewer stars."
15115 (interactive "P")
15116 (setq this-command 'yank)
15117 (if arg
15118 (call-interactively 'yank)
15119 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15120 (and (org-kill-is-subtree-p)
15121 (or (bolp)
15122 (and (looking-at "[ \t]*$")
15123 (string-match
15124 "\\`\\*+\\'"
15125 (buffer-substring (point-at-bol) (point)))))))
15126 swallowp)
15127 (cond
15128 ((and subtreep org-yank-folded-subtrees)
15129 (let ((beg (point))
15130 end)
15131 (if (and subtreep org-yank-adjusted-subtrees)
15132 (org-paste-subtree nil nil 'for-yank)
15133 (call-interactively 'yank))
15134 (setq end (point))
15135 (goto-char beg)
15136 (when (and (bolp) subtreep
15137 (not (setq swallowp
15138 (org-yank-folding-would-swallow-text beg end))))
15139 (or (looking-at outline-regexp)
15140 (re-search-forward (concat "^" outline-regexp) end t))
15141 (while (and (< (point) end) (looking-at outline-regexp))
15142 (hide-subtree)
15143 (org-cycle-show-empty-lines 'folded)
15144 (condition-case nil
15145 (outline-forward-same-level 1)
15146 (error (goto-char end)))))
15147 (when swallowp
15148 (message
15149 "Yanked text not folded because that would swallow text"))
15150 (goto-char end)
15151 (skip-chars-forward " \t\n\r")
15152 (beginning-of-line 1)
15153 (push-mark beg 'nomsg)))
15154 ((and subtreep org-yank-adjusted-subtrees)
15155 (let ((beg (point-at-bol)))
15156 (org-paste-subtree nil nil 'for-yank)
15157 (push-mark beg 'nomsg)))
15159 (call-interactively 'yank))))))
15161 (defun org-yank-folding-would-swallow-text (beg end)
15162 "Would hide-subtree at BEG swallow any text after END?"
15163 (let (level)
15164 (save-excursion
15165 (goto-char beg)
15166 (when (or (looking-at outline-regexp)
15167 (re-search-forward (concat "^" outline-regexp) end t))
15168 (setq level (org-outline-level)))
15169 (goto-char end)
15170 (skip-chars-forward " \t\r\n\v\f")
15171 (if (or (eobp)
15172 (and (bolp) (looking-at org-outline-regexp)
15173 (<= (org-outline-level) level)))
15174 nil ; Nothing would be swallowed
15175 t)))) ; something would swallow
15177 (define-key org-mode-map "\C-y" 'org-yank)
15179 (defun org-invisible-p ()
15180 "Check if point is at a character currently not visible."
15181 ;; Early versions of noutline don't have `outline-invisible-p'.
15182 (if (fboundp 'outline-invisible-p)
15183 (outline-invisible-p)
15184 (get-char-property (point) 'invisible)))
15186 (defun org-invisible-p2 ()
15187 "Check if point is at a character currently not visible."
15188 (save-excursion
15189 (if (and (eolp) (not (bobp))) (backward-char 1))
15190 ;; Early versions of noutline don't have `outline-invisible-p'.
15191 (if (fboundp 'outline-invisible-p)
15192 (outline-invisible-p)
15193 (get-char-property (point) 'invisible))))
15195 (defun org-back-to-heading (&optional invisible-ok)
15196 "Call `outline-back-to-heading', but provide a better error message."
15197 (condition-case nil
15198 (outline-back-to-heading invisible-ok)
15199 (error (error "Before first headline at position %d in buffer %s"
15200 (point) (current-buffer)))))
15202 (defun org-before-first-heading-p ()
15203 "Before first heading?"
15204 (save-excursion
15205 (null (re-search-backward "^\\*+ " nil t))))
15207 (defalias 'org-on-heading-p 'outline-on-heading-p)
15208 (defalias 'org-at-heading-p 'outline-on-heading-p)
15209 (defun org-at-heading-or-item-p ()
15210 (or (org-on-heading-p) (org-at-item-p)))
15212 (defun org-on-target-p ()
15213 (or (org-in-regexp org-radio-target-regexp)
15214 (org-in-regexp org-target-regexp)))
15216 (defun org-up-heading-all (arg)
15217 "Move to the heading line of which the present line is a subheading.
15218 This function considers both visible and invisible heading lines.
15219 With argument, move up ARG levels."
15220 (if (fboundp 'outline-up-heading-all)
15221 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15222 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15224 (defun org-up-heading-safe ()
15225 "Move to the heading line of which the present line is a subheading.
15226 This version will not throw an error. It will return the level of the
15227 headline found, or nil if no higher level is found."
15228 (let (start-level re)
15229 (org-back-to-heading t)
15230 (setq start-level (funcall outline-level))
15231 (if (equal start-level 1)
15233 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15234 (if (re-search-backward re nil t)
15235 (funcall outline-level)))))
15237 (defun org-first-sibling-p ()
15238 "Is this heading the first child of its parents?"
15239 (interactive)
15240 (let ((re (concat "^" outline-regexp))
15241 level l)
15242 (unless (org-at-heading-p t)
15243 (error "Not at a heading"))
15244 (setq level (funcall outline-level))
15245 (save-excursion
15246 (if (not (re-search-backward re nil t))
15248 (setq l (funcall outline-level))
15249 (< l level)))))
15251 (defun org-goto-sibling (&optional previous)
15252 "Goto the next sibling, even if it is invisible.
15253 When PREVIOUS is set, go to the previous sibling instead. Returns t
15254 when a sibling was found. When none is found, return nil and don't
15255 move point."
15256 (let ((fun (if previous 're-search-backward 're-search-forward))
15257 (pos (point))
15258 (re (concat "^" outline-regexp))
15259 level l)
15260 (when (condition-case nil (org-back-to-heading t) (error nil))
15261 (setq level (funcall outline-level))
15262 (catch 'exit
15263 (or previous (forward-char 1))
15264 (while (funcall fun re nil t)
15265 (setq l (funcall outline-level))
15266 (when (< l level) (goto-char pos) (throw 'exit nil))
15267 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15268 (goto-char pos)
15269 nil))))
15271 (defun org-show-siblings ()
15272 "Show all siblings of the current headline."
15273 (save-excursion
15274 (while (org-goto-sibling) (org-flag-heading nil)))
15275 (save-excursion
15276 (while (org-goto-sibling 'previous)
15277 (org-flag-heading nil))))
15279 (defun org-show-hidden-entry ()
15280 "Show an entry where even the heading is hidden."
15281 (save-excursion
15282 (org-show-entry)))
15284 (defun org-flag-heading (flag &optional entry)
15285 "Flag the current heading. FLAG non-nil means make invisible.
15286 When ENTRY is non-nil, show the entire entry."
15287 (save-excursion
15288 (org-back-to-heading t)
15289 ;; Check if we should show the entire entry
15290 (if entry
15291 (progn
15292 (org-show-entry)
15293 (save-excursion
15294 (and (outline-next-heading)
15295 (org-flag-heading nil))))
15296 (outline-flag-region (max (point-min) (1- (point)))
15297 (save-excursion (outline-end-of-heading) (point))
15298 flag))))
15300 (defun org-forward-same-level (arg)
15301 "Move forward to the ARG'th subheading at same level as this one.
15302 Stop at the first and last subheadings of a superior heading.
15303 This is like outline-forward-same-level, but invisible headings are ok."
15304 (interactive "p")
15305 (org-back-to-heading t)
15306 (while (> arg 0)
15307 (let ((point-to-move-to (save-excursion
15308 (org-get-next-sibling))))
15309 (if point-to-move-to
15310 (progn
15311 (goto-char point-to-move-to)
15312 (setq arg (1- arg)))
15313 (progn
15314 (setq arg 0)
15315 (error "No following same-level heading"))))))
15317 (defun org-get-next-sibling ()
15318 "Move to next heading of the same level, and return point.
15319 If there is no such heading, return nil.
15320 This is like outline-next-sibling, but invisible headings are ok."
15321 (let ((level (funcall outline-level)))
15322 (outline-next-heading)
15323 (while (and (not (eobp)) (> (funcall outline-level) level))
15324 (outline-next-heading))
15325 (if (or (eobp) (< (funcall outline-level) level))
15327 (point))))
15329 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15330 ;; This is an exact copy of the original function, but it uses
15331 ;; `org-back-to-heading', to make it work also in invisible
15332 ;; trees. And is uses an invisible-OK argument.
15333 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15334 (org-back-to-heading invisible-OK)
15335 (let ((first t)
15336 (level (funcall outline-level)))
15337 (while (and (not (eobp))
15338 (or first (> (funcall outline-level) level)))
15339 (setq first nil)
15340 (outline-next-heading))
15341 (unless to-heading
15342 (if (memq (preceding-char) '(?\n ?\^M))
15343 (progn
15344 ;; Go to end of line before heading
15345 (forward-char -1)
15346 (if (memq (preceding-char) '(?\n ?\^M))
15347 ;; leave blank line before heading
15348 (forward-char -1))))))
15349 (point))
15351 (defun org-show-subtree ()
15352 "Show everything after this heading at deeper levels."
15353 (outline-flag-region
15354 (point)
15355 (save-excursion
15356 (outline-end-of-subtree) (outline-next-heading) (point))
15357 nil))
15359 (defun org-show-entry ()
15360 "Show the body directly following this heading.
15361 Show the heading too, if it is currently invisible."
15362 (interactive)
15363 (save-excursion
15364 (condition-case nil
15365 (progn
15366 (org-back-to-heading t)
15367 (outline-flag-region
15368 (max (point-min) (1- (point)))
15369 (save-excursion
15370 (if (re-search-forward
15371 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15372 (match-beginning 1)
15373 (point-max)))
15374 nil))
15375 (error nil))))
15377 (defun org-make-options-regexp (kwds &optional extra)
15378 "Make a regular expression for keyword lines."
15379 (concat
15381 "#?[ \t]*\\+\\("
15382 (mapconcat 'regexp-quote kwds "\\|")
15383 (if extra (concat "\\|" extra))
15384 "\\):[ \t]*"
15385 "\\(.+\\)"))
15387 ;; Make isearch reveal the necessary context
15388 (defun org-isearch-end ()
15389 "Reveal context after isearch exits."
15390 (when isearch-success ; only if search was successful
15391 (if (featurep 'xemacs)
15392 ;; Under XEmacs, the hook is run in the correct place,
15393 ;; we directly show the context.
15394 (org-show-context 'isearch)
15395 ;; In Emacs the hook runs *before* restoring the overlays.
15396 ;; So we have to use a one-time post-command-hook to do this.
15397 ;; (Emacs 22 has a special variable, see function `org-mode')
15398 (unless (and (boundp 'isearch-mode-end-hook-quit)
15399 isearch-mode-end-hook-quit)
15400 ;; Only when the isearch was not quitted.
15401 (org-add-hook 'post-command-hook 'org-isearch-post-command
15402 'append 'local)))))
15404 (defun org-isearch-post-command ()
15405 "Remove self from hook, and show context."
15406 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15407 (org-show-context 'isearch))
15410 ;;;; Integration with and fixes for other packages
15412 ;;; Imenu support
15414 (defvar org-imenu-markers nil
15415 "All markers currently used by Imenu.")
15416 (make-variable-buffer-local 'org-imenu-markers)
15418 (defun org-imenu-new-marker (&optional pos)
15419 "Return a new marker for use by Imenu, and remember the marker."
15420 (let ((m (make-marker)))
15421 (move-marker m (or pos (point)))
15422 (push m org-imenu-markers)
15425 (defun org-imenu-get-tree ()
15426 "Produce the index for Imenu."
15427 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15428 (setq org-imenu-markers nil)
15429 (let* ((n org-imenu-depth)
15430 (re (concat "^" outline-regexp))
15431 (subs (make-vector (1+ n) nil))
15432 (last-level 0)
15433 m level head)
15434 (save-excursion
15435 (save-restriction
15436 (widen)
15437 (goto-char (point-max))
15438 (while (re-search-backward re nil t)
15439 (setq level (org-reduced-level (funcall outline-level)))
15440 (when (<= level n)
15441 (looking-at org-complex-heading-regexp)
15442 (setq head (org-link-display-format
15443 (org-match-string-no-properties 4))
15444 m (org-imenu-new-marker))
15445 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15446 (if (>= level last-level)
15447 (push (cons head m) (aref subs level))
15448 (push (cons head (aref subs (1+ level))) (aref subs level))
15449 (loop for i from (1+ level) to n do (aset subs i nil)))
15450 (setq last-level level)))))
15451 (aref subs 1)))
15453 (eval-after-load "imenu"
15454 '(progn
15455 (add-hook 'imenu-after-jump-hook
15456 (lambda ()
15457 (if (eq major-mode 'org-mode)
15458 (org-show-context 'org-goto))))))
15460 (defun org-link-display-format (link)
15461 "Replace a link with either the description, or the link target
15462 if no description is present"
15463 (save-match-data
15464 (if (string-match org-bracket-link-analytic-regexp link)
15465 (replace-match (or (match-string 5 link)
15466 (concat (match-string 1 link)
15467 (match-string 3 link)))
15468 nil nil link)
15469 link)))
15471 ;; Speedbar support
15473 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15474 "Overlay marking the agenda restriction line in speedbar.")
15475 (org-overlay-put org-speedbar-restriction-lock-overlay
15476 'face 'org-agenda-restriction-lock)
15477 (org-overlay-put org-speedbar-restriction-lock-overlay
15478 'help-echo "Agendas are currently limited to this item.")
15479 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15481 (defun org-speedbar-set-agenda-restriction ()
15482 "Restrict future agenda commands to the location at point in speedbar.
15483 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15484 (interactive)
15485 (require 'org-agenda)
15486 (let (p m tp np dir txt)
15487 (cond
15488 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15489 'org-imenu t))
15490 (setq m (get-text-property p 'org-imenu-marker))
15491 (save-excursion
15492 (save-restriction
15493 (set-buffer (marker-buffer m))
15494 (goto-char m)
15495 (org-agenda-set-restriction-lock 'subtree))))
15496 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15497 'speedbar-function 'speedbar-find-file))
15498 (setq tp (previous-single-property-change
15499 (1+ p) 'speedbar-function)
15500 np (next-single-property-change
15501 tp 'speedbar-function)
15502 dir (speedbar-line-directory)
15503 txt (buffer-substring-no-properties (or tp (point-min))
15504 (or np (point-max))))
15505 (save-excursion
15506 (save-restriction
15507 (set-buffer (find-file-noselect
15508 (let ((default-directory dir))
15509 (expand-file-name txt))))
15510 (unless (org-mode-p)
15511 (error "Cannot restrict to non-Org-mode file"))
15512 (org-agenda-set-restriction-lock 'file))))
15513 (t (error "Don't know how to restrict Org-mode's agenda")))
15514 (org-move-overlay org-speedbar-restriction-lock-overlay
15515 (point-at-bol) (point-at-eol))
15516 (setq current-prefix-arg nil)
15517 (org-agenda-maybe-redo)))
15519 (eval-after-load "speedbar"
15520 '(progn
15521 (speedbar-add-supported-extension ".org")
15522 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15523 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15524 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15525 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15526 (add-hook 'speedbar-visiting-tag-hook
15527 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15530 ;;; Fixes and Hacks for problems with other packages
15532 ;; Make flyspell not check words in links, to not mess up our keymap
15533 (defun org-mode-flyspell-verify ()
15534 "Don't let flyspell put overlays at active buttons."
15535 (not (get-text-property (point) 'keymap)))
15537 ;; Make `bookmark-jump' show the jump location if it was hidden.
15538 (eval-after-load "bookmark"
15539 '(if (boundp 'bookmark-after-jump-hook)
15540 ;; We can use the hook
15541 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15542 ;; Hook not available, use advice
15543 (defadvice bookmark-jump (after org-make-visible activate)
15544 "Make the position visible."
15545 (org-bookmark-jump-unhide))))
15547 ;; Make sure saveplace show the location if it was hidden
15548 (eval-after-load "saveplace"
15549 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15550 "Make the position visible."
15551 (org-bookmark-jump-unhide)))
15553 (defun org-bookmark-jump-unhide ()
15554 "Unhide the current position, to show the bookmark location."
15555 (and (org-mode-p)
15556 (or (org-invisible-p)
15557 (save-excursion (goto-char (max (point-min) (1- (point))))
15558 (org-invisible-p)))
15559 (org-show-context 'bookmark-jump)))
15561 ;; Make session.el ignore our circular variable
15562 (eval-after-load "session"
15563 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15565 ;;;; Experimental code
15567 (defun org-closed-in-range ()
15568 "Sparse tree of items closed in a certain time range.
15569 Still experimental, may disappear in the future."
15570 (interactive)
15571 ;; Get the time interval from the user.
15572 (let* ((time1 (time-to-seconds
15573 (org-read-date nil 'to-time nil "Starting date: ")))
15574 (time2 (time-to-seconds
15575 (org-read-date nil 'to-time nil "End date:")))
15576 ;; callback function
15577 (callback (lambda ()
15578 (let ((time
15579 (time-to-seconds
15580 (apply 'encode-time
15581 (org-parse-time-string
15582 (match-string 1))))))
15583 ;; check if time in interval
15584 (and (>= time time1) (<= time time2))))))
15585 ;; make tree, check each match with the callback
15586 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15589 ;;;; Finish up
15591 (provide 'org)
15593 (run-hooks 'org-load-hook)
15595 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15597 ;;; org.el ends here