Tags: Fix implementation of line breaks in fast tag interface
[org-mode/org-tableheadings.git] / lisp / org.el
blob85f4ec5d9ff9604b8116ba94e8dd40037c6c10bd
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.23trans
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.23trans"
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.
654 When t, `C-a' will bring back the cursor to the beginning of the
655 headline text, i.e. after the stars and after a possible TODO keyword.
656 In an item, this will be the position after the bullet.
657 When the cursor is already at that position, another `C-a' will bring
658 it to the beginning of the line.
660 `C-e' will jump to the end of the headline, ignoring the presence of tags
661 in the headline. A second `C-e' will then jump to the true end of the
662 line, after any tags.
664 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
665 and only a directly following, identical keypress will bring the cursor
666 to the special positions.
668 This may also be a cons cell where the behavior for `C-a' and `C-e' is
669 set separately."
670 :group 'org-edit-structure
671 :type '(choice
672 (const :tag "off" nil)
673 (const :tag "after stars/bullet and before tags first" t)
674 (const :tag "true line boundary first" reversed)
675 (cons :tag "Set C-a and C-e separately"
676 (choice :tag "Special C-a"
677 (const :tag "off" nil)
678 (const :tag "after stars/bullet first" t)
679 (const :tag "before stars/bullet first" reversed))
680 (choice :tag "Special C-e"
681 (const :tag "off" nil)
682 (const :tag "before tags first" t)
683 (const :tag "after tags first" reversed)))))
684 (if (fboundp 'defvaralias)
685 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
687 (defcustom org-special-ctrl-k nil
688 "Non-nil means `C-k' will behave specially in headlines.
689 When nil, `C-k' will call the default `kill-line' command.
690 When t, the following will happen while the cursor is in the headline:
692 - When the cursor is at the beginning of a headline, kill the entire
693 line and possible the folded subtree below the line.
694 - When in the middle of the headline text, kill the headline up to the tags.
695 - When after the headline text, kill the tags."
696 :group 'org-edit-structure
697 :type 'boolean)
699 (defcustom org-yank-folded-subtrees t
700 "Non-nil means, when yanking subtrees, fold them.
701 If the kill is a single subtree, or a sequence of subtrees, i.e. if
702 it starts with a heading and all other headings in it are either children
703 or siblings, then fold all the subtrees. However, do this only if no
704 text after the yank would be swallowed into a folded tree by this action."
705 :group 'org-edit-structure
706 :type 'boolean)
708 (defcustom org-yank-adjusted-subtrees nil
709 "Non-nil means, when yanking subtrees, adjust the level.
710 With this setting, `org-paste-subtree' is used to insert the subtree, see
711 this function for details."
712 :group 'org-edit-structure
713 :type 'boolean)
715 (defcustom org-M-RET-may-split-line '((default . t))
716 "Non-nil means, M-RET will split the line at the cursor position.
717 When nil, it will go to the end of the line before making a
718 new line.
719 You may also set this option in a different way for different
720 contexts. Valid contexts are:
722 headline when creating a new headline
723 item when creating a new item
724 table in a table field
725 default the value to be used for all contexts not explicitly
726 customized"
727 :group 'org-structure
728 :group 'org-table
729 :type '(choice
730 (const :tag "Always" t)
731 (const :tag "Never" nil)
732 (repeat :greedy t :tag "Individual contexts"
733 (cons
734 (choice :tag "Context"
735 (const headline)
736 (const item)
737 (const table)
738 (const default))
739 (boolean)))))
742 (defcustom org-insert-heading-respect-content nil
743 "Non-nil means, insert new headings after the current subtree.
744 When nil, the new heading is created directly after the current line.
745 The commands \\[org-insert-heading-respect-content] and
746 \\[org-insert-todo-heading-respect-content] turn this variable on
747 for the duration of the command."
748 :group 'org-structure
749 :type 'boolean)
751 (defcustom org-blank-before-new-entry '((heading . auto)
752 (plain-list-item . auto))
753 "Should `org-insert-heading' leave a blank line before new heading/item?
754 The value is an alist, with `heading' and `plain-list-item' as car,
755 and a boolean flag as cdr. For plain lists, if the variable
756 `org-empty-line-terminates-plain-lists' is set, the setting here
757 is ignored and no empty line is inserted, to keep the list in tact."
758 :group 'org-edit-structure
759 :type '(list
760 (cons (const heading)
761 (choice (const :tag "Never" nil)
762 (const :tag "Always" t)
763 (const :tag "Auto" auto)))
764 (cons (const plain-list-item)
765 (choice (const :tag "Never" nil)
766 (const :tag "Always" t)
767 (const :tag "Auto" auto)))))
769 (defcustom org-insert-heading-hook nil
770 "Hook being run after inserting a new heading."
771 :group 'org-edit-structure
772 :type 'hook)
774 (defcustom org-enable-fixed-width-editor t
775 "Non-nil means, lines starting with \":\" are treated as fixed-width.
776 This currently only means, they are never auto-wrapped.
777 When nil, such lines will be treated like ordinary lines.
778 See also the QUOTE keyword."
779 :group 'org-edit-structure
780 :type 'boolean)
782 (defcustom org-edit-src-region-extra nil
783 "Additional regexps to identify regions for editing with `org-edit-src-code'.
784 For examples see the function `org-edit-src-find-region-and-lang'.
785 The regular expression identifying the begin marker should end with a newline,
786 and the regexp marking the end line should start with a newline, to make sure
787 there are kept outside the narrowed region."
788 :group 'org-edit-structure
789 :type '(repeat
790 (list
791 (regexp :tag "begin regexp")
792 (regexp :tag "end regexp")
793 (choice :tag "language"
794 (string :tag "specify")
795 (integer :tag "from match group")
796 (const :tag "from `lang' element")
797 (const :tag "from `style' element")))))
799 (defcustom org-coderef-label-format "(ref:%s)"
800 "The default coderef format.
801 This format string will be used to search for coderef labels in literal
802 examples (EXAMPLE and SRC blocks). The format can be overwritten
803 an individual literal example with the -f option, like
805 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
807 #+END_SRC
809 If you want to use this for HTML export, make sure that the format does
810 not introduce special font-locking, and avoid the HTML special
811 characters `<', `>', and `&'. The reason for this restriction is that
812 the labels are searched for only after htmlize has done its job."
813 :group 'org-edit-structure ; FIXME this is not in the right group
814 :type 'string)
816 (defcustom org-edit-fixed-width-region-mode 'artist-mode
817 "The mode that should be used to edit fixed-width regions.
818 These are the regions where each line starts with a colon."
819 :group 'org-edit-structure
820 :type '(choice
821 (const artist-mode)
822 (const picture-mode)
823 (const fundamental-mode)
824 (function :tag "Other (specify)")))
826 (defcustom org-goto-auto-isearch t
827 "Non-nil means, typing characters in org-goto starts incremental search."
828 :group 'org-edit-structure
829 :type 'boolean)
831 (defgroup org-sparse-trees nil
832 "Options concerning sparse trees in Org-mode."
833 :tag "Org Sparse Trees"
834 :group 'org-structure)
836 (defcustom org-highlight-sparse-tree-matches t
837 "Non-nil means, highlight all matches that define a sparse tree.
838 The highlights will automatically disappear the next time the buffer is
839 changed by an edit command."
840 :group 'org-sparse-trees
841 :type 'boolean)
843 (defcustom org-remove-highlights-with-change t
844 "Non-nil means, any change to the buffer will remove temporary highlights.
845 Such highlights are created by `org-occur' and `org-clock-display'.
846 When nil, `C-c C-c needs to be used to get rid of the highlights.
847 The highlights created by `org-preview-latex-fragment' always need
848 `C-c C-c' to be removed."
849 :group 'org-sparse-trees
850 :group 'org-time
851 :type 'boolean)
854 (defcustom org-occur-hook '(org-first-headline-recenter)
855 "Hook that is run after `org-occur' has constructed a sparse tree.
856 This can be used to recenter the window to show as much of the structure
857 as possible."
858 :group 'org-sparse-trees
859 :type 'hook)
861 (defgroup org-imenu-and-speedbar nil
862 "Options concerning imenu and speedbar in Org-mode."
863 :tag "Org Imenu and Speedbar"
864 :group 'org-structure)
866 (defcustom org-imenu-depth 2
867 "The maximum level for Imenu access to Org-mode headlines.
868 This also applied for speedbar access."
869 :group 'org-imenu-and-speedbar
870 :type 'number)
872 (defgroup org-table nil
873 "Options concerning tables in Org-mode."
874 :tag "Org Table"
875 :group 'org)
877 (defcustom org-enable-table-editor 'optimized
878 "Non-nil means, lines starting with \"|\" are handled by the table editor.
879 When nil, such lines will be treated like ordinary lines.
881 When equal to the symbol `optimized', the table editor will be optimized to
882 do the following:
883 - Automatic overwrite mode in front of whitespace in table fields.
884 This makes the structure of the table stay in tact as long as the edited
885 field does not exceed the column width.
886 - Minimize the number of realigns. Normally, the table is aligned each time
887 TAB or RET are pressed to move to another field. With optimization this
888 happens only if changes to a field might have changed the column width.
889 Optimization requires replacing the functions `self-insert-command',
890 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
891 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
892 very good at guessing when a re-align will be necessary, but you can always
893 force one with \\[org-ctrl-c-ctrl-c].
895 If you would like to use the optimized version in Org-mode, but the
896 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
898 This variable can be used to turn on and off the table editor during a session,
899 but in order to toggle optimization, a restart is required.
901 See also the variable `org-table-auto-blank-field'."
902 :group 'org-table
903 :type '(choice
904 (const :tag "off" nil)
905 (const :tag "on" t)
906 (const :tag "on, optimized" optimized)))
908 (defcustom org-self-insert-cluster-for-undo t
909 "Non-nil means cluster self-insert commands for undo when possible.
910 If this is set, then, like in the Emacs command loop, 20 consequtive
911 characters will be undone together.
912 This is configurable, because there is some impact on typing performance."
913 :group 'org-table
914 :type 'boolean)
916 (defcustom org-table-tab-recognizes-table.el t
917 "Non-nil means, TAB will automatically notice a table.el table.
918 When it sees such a table, it moves point into it and - if necessary -
919 calls `table-recognize-table'."
920 :group 'org-table-editing
921 :type 'boolean)
923 (defgroup org-link nil
924 "Options concerning links in Org-mode."
925 :tag "Org Link"
926 :group 'org)
928 (defvar org-link-abbrev-alist-local nil
929 "Buffer-local version of `org-link-abbrev-alist', which see.
930 The value of this is taken from the #+LINK lines.")
931 (make-variable-buffer-local 'org-link-abbrev-alist-local)
933 (defcustom org-link-abbrev-alist nil
934 "Alist of link abbreviations.
935 The car of each element is a string, to be replaced at the start of a link.
936 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
937 links in Org-mode buffers can have an optional tag after a double colon, e.g.
939 [[linkkey:tag][description]]
941 The 'linkkey' must be a word word, starting with a letter, followed
942 by letters, numbers, '-' or '_'.
944 If REPLACE is a string, the tag will simply be appended to create the link.
945 If the string contains \"%s\", the tag will be inserted there. Alternatively,
946 the placeholder \"%h\" will cause a url-encoded version of the tag to
947 be inserted at that point (see the function `url-hexify-string').
949 REPLACE may also be a function that will be called with the tag as the
950 only argument to create the link, which should be returned as a string.
952 See the manual for examples."
953 :group 'org-link
954 :type '(repeat
955 (cons
956 (string :tag "Protocol")
957 (choice
958 (string :tag "Format")
959 (function)))))
961 (defcustom org-descriptive-links t
962 "Non-nil means, hide link part and only show description of bracket links.
963 Bracket links are like [[link][description]]. This variable sets the initial
964 state in new org-mode buffers. The setting can then be toggled on a
965 per-buffer basis from the Org->Hyperlinks menu."
966 :group 'org-link
967 :type 'boolean)
969 (defcustom org-link-file-path-type 'adaptive
970 "How the path name in file links should be stored.
971 Valid values are:
973 relative Relative to the current directory, i.e. the directory of the file
974 into which the link is being inserted.
975 absolute Absolute path, if possible with ~ for home directory.
976 noabbrev Absolute path, no abbreviation of home directory.
977 adaptive Use relative path for files in the current directory and sub-
978 directories of it. For other files, use an absolute path."
979 :group 'org-link
980 :type '(choice
981 (const relative)
982 (const absolute)
983 (const noabbrev)
984 (const adaptive)))
986 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
987 "Types of links that should be activated in Org-mode files.
988 This is a list of symbols, each leading to the activation of a certain link
989 type. In principle, it does not hurt to turn on most link types - there may
990 be a small gain when turning off unused link types. The types are:
992 bracket The recommended [[link][description]] or [[link]] links with hiding.
993 angular Links in angular brackets that may contain whitespace like
994 <bbdb:Carsten Dominik>.
995 plain Plain links in normal text, no whitespace, like http://google.com.
996 radio Text that is matched by a radio target, see manual for details.
997 tag Tag settings in a headline (link to tag search).
998 date Time stamps (link to calendar).
999 footnote Footnote labels.
1001 Changing this variable requires a restart of Emacs to become effective."
1002 :group 'org-link
1003 :type '(set :greedy t
1004 (const :tag "Double bracket links (new style)" bracket)
1005 (const :tag "Angular bracket links (old style)" angular)
1006 (const :tag "Plain text links" plain)
1007 (const :tag "Radio target matches" radio)
1008 (const :tag "Tags" tag)
1009 (const :tag "Timestamps" date)
1010 (const :tag "Footnotes" footnote)))
1012 (defcustom org-make-link-description-function nil
1013 "Function to use to generate link descriptions from links. If
1014 nil the link location will be used. This function must take two
1015 parameters; the first is the link and the second the description
1016 org-insert-link has generated, and should return the description
1017 to use."
1018 :group 'org-link
1019 :type 'function)
1021 (defgroup org-link-store nil
1022 "Options concerning storing links in Org-mode."
1023 :tag "Org Store Link"
1024 :group 'org-link)
1026 (defcustom org-email-link-description-format "Email %c: %.30s"
1027 "Format of the description part of a link to an email or usenet message.
1028 The following %-escapes will be replaced by corresponding information:
1030 %F full \"From\" field
1031 %f name, taken from \"From\" field, address if no name
1032 %T full \"To\" field
1033 %t first name in \"To\" field, address if no name
1034 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1035 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1036 %s subject
1037 %m message-id.
1039 You may use normal field width specification between the % and the letter.
1040 This is for example useful to limit the length of the subject.
1042 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1043 :group 'org-link-store
1044 :type 'string)
1046 (defcustom org-from-is-user-regexp
1047 (let (r1 r2)
1048 (when (and user-mail-address (not (string= user-mail-address "")))
1049 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1050 (when (and user-full-name (not (string= user-full-name "")))
1051 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1052 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1053 "Regexp matched against the \"From:\" header of an email or usenet message.
1054 It should match if the message is from the user him/herself."
1055 :group 'org-link-store
1056 :type 'regexp)
1058 (defcustom org-link-to-org-use-id 'create-if-interactive
1059 "Non-nil means, storing a link to an Org file will use entry IDs.
1061 Note that before this variable is even considered, org-id must be loaded,
1062 to please customize `org-modules' and turn it on.
1064 The variable can have the following values:
1066 t Create an ID if needed to make a link to the current entry.
1068 create-if-interactive
1069 If `org-store-link' is called directly (interactively, as a user
1070 command), do create an ID to support the link. But when doing the
1071 job for remember, only use the ID if it already exists. The
1072 purpose of this setting is to avoid proliferation of unwanted
1073 IDs, just because you happen to be in an Org file when you
1074 call `org-remember' that automatically and preemptively
1075 creates a link. If you do want to get an ID link in a remember
1076 template to an entry not having an ID, create it first by
1077 explicitly creating a link to it, using `C-c C-l' first.
1079 use-existing
1080 Use existing ID, do not create one.
1082 nil Never use an ID to make a link, instead link using a text search for
1083 the headline text."
1084 :group 'org-link-store
1085 :type '(choice
1086 (const :tag "Create ID to make link" t)
1087 (const :tag "Create if string link interactively"
1088 'create-if-interactive)
1089 (const :tag "Only use existing" 'use-existing)
1090 (const :tag "Do not use ID to create link" nil)))
1092 (defcustom org-context-in-file-links t
1093 "Non-nil means, file links from `org-store-link' contain context.
1094 A search string will be added to the file name with :: as separator and
1095 used to find the context when the link is activated by the command
1096 `org-open-at-point'.
1097 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1098 negates this setting for the duration of the command."
1099 :group 'org-link-store
1100 :type 'boolean)
1102 (defcustom org-keep-stored-link-after-insertion nil
1103 "Non-nil means, keep link in list for entire session.
1105 The command `org-store-link' adds a link pointing to the current
1106 location to an internal list. These links accumulate during a session.
1107 The command `org-insert-link' can be used to insert links into any
1108 Org-mode file (offering completion for all stored links). When this
1109 option is nil, every link which has been inserted once using \\[org-insert-link]
1110 will be removed from the list, to make completing the unused links
1111 more efficient."
1112 :group 'org-link-store
1113 :type 'boolean)
1115 (defgroup org-link-follow nil
1116 "Options concerning following links in Org-mode."
1117 :tag "Org Follow Link"
1118 :group 'org-link)
1120 (defcustom org-link-translation-function nil
1121 "Function to translate links with different syntax to Org syntax.
1122 This can be used to translate links created for example by the Planner
1123 or emacs-wiki packages to Org syntax.
1124 The function must accept two parameters, a TYPE containing the link
1125 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1126 which is everything after the link protocol. It should return a cons
1127 with possibly modified values of type and path.
1128 Org contains a function for this, so if you set this variable to
1129 `org-translate-link-from-planner', you should be able follow many
1130 links created by planner."
1131 :group 'org-link-follow
1132 :type 'function)
1134 (defcustom org-follow-link-hook nil
1135 "Hook that is run after a link has been followed."
1136 :group 'org-link-follow
1137 :type 'hook)
1139 (defcustom org-tab-follows-link nil
1140 "Non-nil means, on links TAB will follow the link.
1141 Needs to be set before org.el is loaded.
1142 This really should not be used, it does not make sense, and the
1143 implementation is bad."
1144 :group 'org-link-follow
1145 :type 'boolean)
1147 (defcustom org-return-follows-link nil
1148 "Non-nil means, on links RET will follow the link.
1149 Needs to be set before org.el is loaded."
1150 :group 'org-link-follow
1151 :type 'boolean)
1153 (defcustom org-mouse-1-follows-link
1154 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1155 "Non-nil means, mouse-1 on a link will follow the link.
1156 A longer mouse click will still set point. Does not work on XEmacs.
1157 Needs to be set before org.el is loaded."
1158 :group 'org-link-follow
1159 :type 'boolean)
1161 (defcustom org-mark-ring-length 4
1162 "Number of different positions to be recorded in the ring
1163 Changing this requires a restart of Emacs to work correctly."
1164 :group 'org-link-follow
1165 :type 'integer)
1167 (defcustom org-link-frame-setup
1168 '((vm . vm-visit-folder-other-frame)
1169 (gnus . gnus-other-frame)
1170 (file . find-file-other-window))
1171 "Setup the frame configuration for following links.
1172 When following a link with Emacs, it may often be useful to display
1173 this link in another window or frame. This variable can be used to
1174 set this up for the different types of links.
1175 For VM, use any of
1176 `vm-visit-folder'
1177 `vm-visit-folder-other-frame'
1178 For Gnus, use any of
1179 `gnus'
1180 `gnus-other-frame'
1181 `org-gnus-no-new-news'
1182 For FILE, use any of
1183 `find-file'
1184 `find-file-other-window'
1185 `find-file-other-frame'
1186 For the calendar, use the variable `calendar-setup'.
1187 For BBDB, it is currently only possible to display the matches in
1188 another window."
1189 :group 'org-link-follow
1190 :type '(list
1191 (cons (const vm)
1192 (choice
1193 (const vm-visit-folder)
1194 (const vm-visit-folder-other-window)
1195 (const vm-visit-folder-other-frame)))
1196 (cons (const gnus)
1197 (choice
1198 (const gnus)
1199 (const gnus-other-frame)
1200 (const org-gnus-no-new-news)))
1201 (cons (const file)
1202 (choice
1203 (const find-file)
1204 (const find-file-other-window)
1205 (const find-file-other-frame)))))
1207 (defcustom org-display-internal-link-with-indirect-buffer nil
1208 "Non-nil means, use indirect buffer to display infile links.
1209 Activating internal links (from one location in a file to another location
1210 in the same file) normally just jumps to the location. When the link is
1211 activated with a C-u prefix (or with mouse-3), the link is displayed in
1212 another window. When this option is set, the other window actually displays
1213 an indirect buffer clone of the current buffer, to avoid any visibility
1214 changes to the current buffer."
1215 :group 'org-link-follow
1216 :type 'boolean)
1218 (defcustom org-open-non-existing-files nil
1219 "Non-nil means, `org-open-file' will open non-existing files.
1220 When nil, an error will be generated."
1221 :group 'org-link-follow
1222 :type 'boolean)
1224 (defcustom org-open-directory-means-index-dot-org nil
1225 "Non-nil means, a link to a directory really means to index.org.
1226 When nil, following a directory link will run dired or open a finder/explorer
1227 window on that directory."
1228 :group 'org-link-follow
1229 :type 'boolean)
1231 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1232 "Function and arguments to call for following mailto links.
1233 This is a list with the first element being a lisp function, and the
1234 remaining elements being arguments to the function. In string arguments,
1235 %a will be replaced by the address, and %s will be replaced by the subject
1236 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1237 :group 'org-link-follow
1238 :type '(choice
1239 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1240 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1241 (const :tag "message-mail" (message-mail "%a" "%s"))
1242 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1244 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1245 "Non-nil means, ask for confirmation before executing shell links.
1246 Shell links can be dangerous: just think about a link
1248 [[shell:rm -rf ~/*][Google Search]]
1250 This link would show up in your Org-mode document as \"Google Search\",
1251 but really it would remove your entire home directory.
1252 Therefore we advise against setting this variable to nil.
1253 Just change it to `y-or-n-p' of you want to confirm with a
1254 single keystroke rather than having to type \"yes\"."
1255 :group 'org-link-follow
1256 :type '(choice
1257 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1258 (const :tag "with y-or-n (faster)" y-or-n-p)
1259 (const :tag "no confirmation (dangerous)" nil)))
1261 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1262 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1263 Elisp links can be dangerous: just think about a link
1265 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1267 This link would show up in your Org-mode document as \"Google Search\",
1268 but really it would remove your entire home directory.
1269 Therefore we advise against setting this variable to nil.
1270 Just change it to `y-or-n-p' of you want to confirm with a
1271 single keystroke rather than having to type \"yes\"."
1272 :group 'org-link-follow
1273 :type '(choice
1274 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1275 (const :tag "with y-or-n (faster)" y-or-n-p)
1276 (const :tag "no confirmation (dangerous)" nil)))
1278 (defconst org-file-apps-defaults-gnu
1279 '((remote . emacs)
1280 (system . mailcap)
1281 (t . mailcap))
1282 "Default file applications on a UNIX or GNU/Linux system.
1283 See `org-file-apps'.")
1285 (defconst org-file-apps-defaults-macosx
1286 '((remote . emacs)
1287 (t . "open %s")
1288 (system . "open %s")
1289 ("ps.gz" . "gv %s")
1290 ("eps.gz" . "gv %s")
1291 ("dvi" . "xdvi %s")
1292 ("fig" . "xfig %s"))
1293 "Default file applications on a MacOS X system.
1294 The system \"open\" is known as a default, but we use X11 applications
1295 for some files for which the OS does not have a good default.
1296 See `org-file-apps'.")
1298 (defconst org-file-apps-defaults-windowsnt
1299 (list
1300 '(remote . emacs)
1301 (cons t
1302 (list (if (featurep 'xemacs)
1303 'mswindows-shell-execute
1304 'w32-shell-execute)
1305 "open" 'file))
1306 (cons 'system
1307 (list (if (featurep 'xemacs)
1308 'mswindows-shell-execute
1309 'w32-shell-execute)
1310 "open" 'file)))
1311 "Default file applications on a Windows NT system.
1312 The system \"open\" is used for most files.
1313 See `org-file-apps'.")
1315 (defcustom org-file-apps
1317 (auto-mode . emacs)
1318 ("\\.x?html?\\'" . default)
1319 ("\\.pdf\\'" . default)
1321 "External applications for opening `file:path' items in a document.
1322 Org-mode uses system defaults for different file types, but
1323 you can use this variable to set the application for a given file
1324 extension. The entries in this list are cons cells where the car identifies
1325 files and the cdr the corresponding command. Possible values for the
1326 file identifier are
1327 \"regex\" Regular expression matched against the file name. For backward
1328 compatibility, this can also be a string with only alphanumeric
1329 characters, which is then interpreted as an extension.
1330 `directory' Matches a directory
1331 `remote' Matches a remote file, accessible through tramp or efs.
1332 Remote files most likely should be visited through Emacs
1333 because external applications cannot handle such paths.
1334 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1335 so all files Emacs knows how to handle. Using this with
1336 command `emacs' will open most files in Emacs. Beware that this
1337 will also open html files inside Emacs, unless you add
1338 (\"html\" . default) to the list as well.
1339 t Default for files not matched by any of the other options.
1340 `system' The system command to open files, like `open' on Windows
1341 and Mac OS X, and mailcap under GNU/Linux. This is the command
1342 that will be selected if you call `C-c C-o' with a double
1343 `C-u C-u' prefix.
1345 Possible values for the command are:
1346 `emacs' The file will be visited by the current Emacs process.
1347 `default' Use the default application for this file type, which is the
1348 association for t in the list, most likely in the system-specific
1349 part.
1350 This can be used to overrule an unwanted setting in the
1351 system-specific variable.
1352 `system' Use the system command for opening files, like \"open\".
1353 This command is specified by the entry whose car is `system'.
1354 Most likely, the system-specific version of this variable
1355 does define this command, but you can overrule/replace it
1356 here.
1357 string A command to be executed by a shell; %s will be replaced
1358 by the path to the file.
1359 sexp A Lisp form which will be evaluated. The file path will
1360 be available in the Lisp variable `file'.
1361 For more examples, see the system specific constants
1362 `org-file-apps-defaults-macosx'
1363 `org-file-apps-defaults-windowsnt'
1364 `org-file-apps-defaults-gnu'."
1365 :group 'org-link-follow
1366 :type '(repeat
1367 (cons (choice :value ""
1368 (string :tag "Extension")
1369 (const :tag "System command to open files" system)
1370 (const :tag "Default for unrecognized files" t)
1371 (const :tag "Remote file" remote)
1372 (const :tag "Links to a directory" directory)
1373 (const :tag "Any files that have Emacs modes"
1374 auto-mode))
1375 (choice :value ""
1376 (const :tag "Visit with Emacs" emacs)
1377 (const :tag "Use default" default)
1378 (const :tag "Use the system command" system)
1379 (string :tag "Command")
1380 (sexp :tag "Lisp form")))))
1382 (defgroup org-refile nil
1383 "Options concerning refiling entries in Org-mode."
1384 :tag "Org Refile"
1385 :group 'org)
1387 (defcustom org-directory "~/org"
1388 "Directory with org files.
1389 This is just a default location to look for Org files. There is no need
1390 at all to put your files into this directory. It is only used in the
1391 following situations:
1393 1. When a remember template specifies a target file that is not an
1394 absolute path. The path will then be interpreted relative to
1395 `org-directory'
1396 2. When a remember note is filed away in an interactive way (when exiting the
1397 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1398 with `org-directory' as the default path."
1399 :group 'org-refile
1400 :group 'org-remember
1401 :type 'directory)
1403 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1404 "Default target for storing notes.
1405 Used by the hooks for remember.el. This can be a string, or nil to mean
1406 the value of `remember-data-file'.
1407 You can set this on a per-template basis with the variable
1408 `org-remember-templates'."
1409 :group 'org-refile
1410 :group 'org-remember
1411 :type '(choice
1412 (const :tag "Default from remember-data-file" nil)
1413 file))
1415 (defcustom org-goto-interface 'outline
1416 "The default interface to be used for `org-goto'.
1417 Allowed values are:
1418 outline The interface shows an outline of the relevant file
1419 and the correct heading is found by moving through
1420 the outline or by searching with incremental search.
1421 outline-path-completion Headlines in the current buffer are offered via
1422 completion. This is the interface also used by
1423 the refile command."
1424 :group 'org-refile
1425 :type '(choice
1426 (const :tag "Outline" outline)
1427 (const :tag "Outline-path-completion" outline-path-completion)))
1429 (defcustom org-goto-max-level 5
1430 "Maximum level to be considered when running org-goto with refile interface."
1431 :group 'org-refile
1432 :type 'number)
1434 (defcustom org-reverse-note-order nil
1435 "Non-nil means, store new notes at the beginning of a file or entry.
1436 When nil, new notes will be filed to the end of a file or entry.
1437 This can also be a list with cons cells of regular expressions that
1438 are matched against file names, and values."
1439 :group 'org-remember
1440 :group 'org-refile
1441 :type '(choice
1442 (const :tag "Reverse always" t)
1443 (const :tag "Reverse never" nil)
1444 (repeat :tag "By file name regexp"
1445 (cons regexp boolean))))
1447 (defcustom org-refile-targets nil
1448 "Targets for refiling entries with \\[org-refile].
1449 This is list of cons cells. Each cell contains:
1450 - a specification of the files to be considered, either a list of files,
1451 or a symbol whose function or variable value will be used to retrieve
1452 a file name or a list of file names. If you use `org-agenda-files' for
1453 that, all agenda files will be scanned for targets. Nil means, consider
1454 headings in the current buffer.
1455 - A specification of how to find candidate refile targets. This may be
1456 any of:
1457 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1458 This tag has to be present in all target headlines, inheritance will
1459 not be considered.
1460 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1461 todo keyword.
1462 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1463 headlines that are refiling targets.
1464 - a cons cell (:level . N). Any headline of level N is considered a target.
1465 Note that, when `org-odd-levels-only' is set, level corresponds to
1466 order in hierarchy, not to the number of stars.
1467 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1468 Note that, when `org-odd-levels-only' is set, level corresponds to
1469 order in hierarchy, not to the number of stars.
1471 When this variable is nil, all top-level headlines in the current buffer
1472 are used, equivalent to the value `((nil . (:level . 1))'."
1473 :group 'org-refile
1474 :type '(repeat
1475 (cons
1476 (choice :value org-agenda-files
1477 (const :tag "All agenda files" org-agenda-files)
1478 (const :tag "Current buffer" nil)
1479 (function) (variable) (file))
1480 (choice :tag "Identify target headline by"
1481 (cons :tag "Specific tag" (const :value :tag) (string))
1482 (cons :tag "TODO keyword" (const :value :todo) (string))
1483 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1484 (cons :tag "Level number" (const :value :level) (integer))
1485 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1487 (defcustom org-refile-use-outline-path nil
1488 "Non-nil means, provide refile targets as paths.
1489 So a level 3 headline will be available as level1/level2/level3.
1490 When the value is `file', also include the file name (without directory)
1491 into the path. When `full-file-path', include the full file path."
1492 :group 'org-refile
1493 :type '(choice
1494 (const :tag "Not" nil)
1495 (const :tag "Yes" t)
1496 (const :tag "Start with file name" file)
1497 (const :tag "Start with full file path" full-file-path)))
1499 (defcustom org-outline-path-complete-in-steps t
1500 "Non-nil means, complete the outline path in hierarchical steps.
1501 When Org-mode uses the refile interface to select an outline path
1502 \(see variable `org-refile-use-outline-path'), the completion of
1503 the path can be done is a single go, or if can be done in steps down
1504 the headline hierarchy. Going in steps is probably the best if you
1505 do not use a special completion package like `ido' or `icicles'.
1506 However, when using these packages, going in one step can be very
1507 fast, while still showing the whole path to the entry."
1508 :group 'org-refile
1509 :type 'boolean)
1511 (defgroup org-todo nil
1512 "Options concerning TODO items in Org-mode."
1513 :tag "Org TODO"
1514 :group 'org)
1516 (defgroup org-progress nil
1517 "Options concerning Progress logging in Org-mode."
1518 :tag "Org Progress"
1519 :group 'org-time)
1521 (defvar org-todo-interpretation-widgets
1523 (:tag "Sequence (cycling hits every state)" sequence)
1524 (:tag "Type (cycling directly to DONE)" type))
1525 "The available interpretation symbols for customizing
1526 `org-todo-keywords'.
1527 Interested libraries should add to this list.")
1529 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1530 "List of TODO entry keyword sequences and their interpretation.
1531 \\<org-mode-map>This is a list of sequences.
1533 Each sequence starts with a symbol, either `sequence' or `type',
1534 indicating if the keywords should be interpreted as a sequence of
1535 action steps, or as different types of TODO items. The first
1536 keywords are states requiring action - these states will select a headline
1537 for inclusion into the global TODO list Org-mode produces. If one of
1538 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1539 signify that no further action is necessary. If \"|\" is not found,
1540 the last keyword is treated as the only DONE state of the sequence.
1542 The command \\[org-todo] cycles an entry through these states, and one
1543 additional state where no keyword is present. For details about this
1544 cycling, see the manual.
1546 TODO keywords and interpretation can also be set on a per-file basis with
1547 the special #+SEQ_TODO and #+TYP_TODO lines.
1549 Each keyword can optionally specify a character for fast state selection
1550 \(in combination with the variable `org-use-fast-todo-selection')
1551 and specifiers for state change logging, using the same syntax
1552 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1553 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1554 indicates to record a time stamp each time this state is selected.
1556 Each keyword may also specify if a timestamp or a note should be
1557 recorded when entering or leaving the state, by adding additional
1558 characters in the parenthesis after the keyword. This looks like this:
1559 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1560 record only the time of the state change. With X and Y being either
1561 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1562 Y when leaving the state if and only if the *target* state does not
1563 define X. You may omit any of the fast-selection key or X or /Y,
1564 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1566 For backward compatibility, this variable may also be just a list
1567 of keywords - in this case the interpretation (sequence or type) will be
1568 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1569 :group 'org-todo
1570 :group 'org-keywords
1571 :type '(choice
1572 (repeat :tag "Old syntax, just keywords"
1573 (string :tag "Keyword"))
1574 (repeat :tag "New syntax"
1575 (cons
1576 (choice
1577 :tag "Interpretation"
1578 ;;Quick and dirty way to see
1579 ;;`org-todo-interpretations'. This takes the
1580 ;;place of item arguments
1581 :convert-widget
1582 (lambda (widget)
1583 (widget-put widget
1584 :args (mapcar
1585 #'(lambda (x)
1586 (widget-convert
1587 (cons 'const x)))
1588 org-todo-interpretation-widgets))
1589 widget))
1590 (repeat
1591 (string :tag "Keyword"))))))
1593 (defvar org-todo-keywords-1 nil
1594 "All TODO and DONE keywords active in a buffer.")
1595 (make-variable-buffer-local 'org-todo-keywords-1)
1596 (defvar org-todo-keywords-for-agenda nil)
1597 (defvar org-done-keywords-for-agenda nil)
1598 (defvar org-todo-keyword-alist-for-agenda nil)
1599 (defvar org-tag-alist-for-agenda nil)
1600 (defvar org-agenda-contributing-files nil)
1601 (defvar org-not-done-keywords nil)
1602 (make-variable-buffer-local 'org-not-done-keywords)
1603 (defvar org-done-keywords nil)
1604 (make-variable-buffer-local 'org-done-keywords)
1605 (defvar org-todo-heads nil)
1606 (make-variable-buffer-local 'org-todo-heads)
1607 (defvar org-todo-sets nil)
1608 (make-variable-buffer-local 'org-todo-sets)
1609 (defvar org-todo-log-states nil)
1610 (make-variable-buffer-local 'org-todo-log-states)
1611 (defvar org-todo-kwd-alist nil)
1612 (make-variable-buffer-local 'org-todo-kwd-alist)
1613 (defvar org-todo-key-alist nil)
1614 (make-variable-buffer-local 'org-todo-key-alist)
1615 (defvar org-todo-key-trigger nil)
1616 (make-variable-buffer-local 'org-todo-key-trigger)
1618 (defcustom org-todo-interpretation 'sequence
1619 "Controls how TODO keywords are interpreted.
1620 This variable is in principle obsolete and is only used for
1621 backward compatibility, if the interpretation of todo keywords is
1622 not given already in `org-todo-keywords'. See that variable for
1623 more information."
1624 :group 'org-todo
1625 :group 'org-keywords
1626 :type '(choice (const sequence)
1627 (const type)))
1629 (defcustom org-use-fast-todo-selection t
1630 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1631 This variable describes if and under what circumstances the cycling
1632 mechanism for TODO keywords will be replaced by a single-key, direct
1633 selection scheme.
1635 When nil, fast selection is never used.
1637 When the symbol `prefix', it will be used when `org-todo' is called with
1638 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1639 in an agenda buffer.
1641 When t, fast selection is used by default. In this case, the prefix
1642 argument forces cycling instead.
1644 In all cases, the special interface is only used if access keys have actually
1645 been assigned by the user, i.e. if keywords in the configuration are followed
1646 by a letter in parenthesis, like TODO(t)."
1647 :group 'org-todo
1648 :type '(choice
1649 (const :tag "Never" nil)
1650 (const :tag "By default" t)
1651 (const :tag "Only with C-u C-c C-t" prefix)))
1653 (defcustom org-provide-todo-statistics t
1654 "Non-nil means, update todo statistics after insert and toggle.
1655 When this is set, todo statistics is updated in the parent of the current
1656 entry each time a todo state is changed."
1657 :group 'org-todo
1658 :type 'boolean)
1660 (defcustom org-after-todo-state-change-hook nil
1661 "Hook which is run after the state of a TODO item was changed.
1662 The new state (a string with a TODO keyword, or nil) is available in the
1663 Lisp variable `state'."
1664 :group 'org-todo
1665 :type 'hook)
1667 (defvar org-blocker-hook nil
1668 "Hook for functions that are allowed to block a state change.
1670 Each function gets as its single argument a property list, see
1671 `org-trigger-hook' for more information about this list.
1673 If any of the functions in this hook returns nil, the state change
1674 is blocked.")
1676 (defvar org-trigger-hook nil
1677 "Hook for functions that are triggered by a state change.
1679 Each function gets as its single argument a property list with at least
1680 the following elements:
1682 (:type type-of-change :position pos-at-entry-start
1683 :from old-state :to new-state)
1685 Depending on the type, more properties may be present.
1687 This mechanism is currently implemented for:
1689 TODO state changes
1690 ------------------
1691 :type todo-state-change
1692 :from previous state (keyword as a string), or nil, or a symbol
1693 'todo' or 'done', to indicate the general type of state.
1694 :to new state, like in :from")
1696 (defcustom org-enforce-todo-dependencies nil
1697 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1698 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1699 be blocked if any prior sibling is not yet done.
1700 This variable needs to be set before org.el is loaded, and you need to
1701 restart Emacs after a change to make the change effective. The only way
1702 to change is while Emacs is running is through the customize interface."
1703 :set (lambda (var val)
1704 (set var val)
1705 (if val
1706 (add-hook 'org-blocker-hook
1707 'org-block-todo-from-children-or-siblings)
1708 (remove-hook 'org-blocker-hook
1709 'org-block-todo-from-children-or-siblings)))
1710 :group 'org-todo
1711 :type 'boolean)
1713 (defcustom org-enforce-todo-checkbox-dependencies nil
1714 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1715 When this is nil, checkboxes have no influence on switching TODO states.
1716 When non-nil, you first need to check off all check boxes before the TODO
1717 entry can be switched to DONE.
1718 This variable needs to be set before org.el is loaded, and you need to
1719 restart Emacs after a change to make the change effective. The only way
1720 to change is while Emacs is running is through the customize interface."
1721 :set (lambda (var val)
1722 (set var val)
1723 (if val
1724 (add-hook 'org-blocker-hook
1725 'org-block-todo-from-checkboxes)
1726 (remove-hook 'org-blocker-hook
1727 'org-block-todo-from-checkboxes)))
1728 :group 'org-todo
1729 :type 'boolean)
1731 (defcustom org-todo-state-tags-triggers nil
1732 "Tag changes that should be triggered by TODO state changes.
1733 This is a list. Each entry is
1735 (state-change (tag . flag) .......)
1737 State-change can be a string with a state, and empty string to indicate the
1738 state that has no TODO keyword, or it can be one of the symbols `todo'
1739 or `done', meaning any not-done or done state, respectively."
1740 :group 'org-todo
1741 :group 'org-tags
1742 :type '(repeat
1743 (cons (choice :tag "When changing to"
1744 (const :tag "Not-done state" todo)
1745 (const :tag "Done state" done)
1746 (string :tag "State"))
1747 (repeat
1748 (cons :tag "Tag action"
1749 (string :tag "Tag")
1750 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1752 (defcustom org-log-done nil
1753 "Information to record when a task moves to the DONE state.
1755 Possible values are:
1757 nil Don't add anything, just change the keyword
1758 time Add a time stamp to the task
1759 note Prompt a closing note and add it with template `org-log-note-headings'
1761 This option can also be set with on a per-file-basis with
1763 #+STARTUP: nologdone
1764 #+STARTUP: logdone
1765 #+STARTUP: lognotedone
1767 You can have local logging settings for a subtree by setting the LOGGING
1768 property to one or more of these keywords."
1769 :group 'org-todo
1770 :group 'org-progress
1771 :type '(choice
1772 (const :tag "No logging" nil)
1773 (const :tag "Record CLOSED timestamp" time)
1774 (const :tag "Record CLOSED timestamp with closing note." note)))
1776 ;; Normalize old uses of org-log-done.
1777 (cond
1778 ((eq org-log-done t) (setq org-log-done 'time))
1779 ((and (listp org-log-done) (memq 'done org-log-done))
1780 (setq org-log-done 'note)))
1782 (defcustom org-log-note-clock-out nil
1783 "Non-nil means, record a note when clocking out of an item.
1784 This can also be configured on a per-file basis by adding one of
1785 the following lines anywhere in the buffer:
1787 #+STARTUP: lognoteclock-out
1788 #+STARTUP: nolognoteclock-out"
1789 :group 'org-todo
1790 :group 'org-progress
1791 :type 'boolean)
1793 (defcustom org-log-done-with-time t
1794 "Non-nil means, the CLOSED time stamp will contain date and time.
1795 When nil, only the date will be recorded."
1796 :group 'org-progress
1797 :type 'boolean)
1799 (defcustom org-log-note-headings
1800 '((done . "CLOSING NOTE %t")
1801 (state . "State %-12s from %-12S %t")
1802 (note . "Note taken on %t")
1803 (clock-out . ""))
1804 "Headings for notes added to entries.
1805 The value is an alist, with the car being a symbol indicating the note
1806 context, and the cdr is the heading to be used. The heading may also be the
1807 empty string.
1808 %t in the heading will be replaced by a time stamp.
1809 %s will be replaced by the new TODO state, in double quotes.
1810 %S will be replaced by the old TODO state, in double quotes.
1811 %u will be replaced by the user name.
1812 %U will be replaced by the full user name."
1813 :group 'org-todo
1814 :group 'org-progress
1815 :type '(list :greedy t
1816 (cons (const :tag "Heading when closing an item" done) string)
1817 (cons (const :tag
1818 "Heading when changing todo state (todo sequence only)"
1819 state) string)
1820 (cons (const :tag "Heading when just taking a note" note) string)
1821 (cons (const :tag "Heading when clocking out" clock-out) string)))
1823 (unless (assq 'note org-log-note-headings)
1824 (push '(note . "%t") org-log-note-headings))
1826 (defcustom org-log-into-drawer nil
1827 "Non-nil means, insert state change notes and time stamps into a drawer.
1828 When nil, state changes notes will be inserted after the headline and
1829 any scheduling and clock lines, but not inside a drawer.
1831 The value of this variable should be the name of the drawer to use.
1832 LOGBOOK is proposed at the default drawer for this purpose, you can
1833 also set this to a string to define the drawer of your choice.
1835 A value of t is also allowed, representing \"LOGBOOK\".
1837 If this variable is set, `org-log-state-notes-insert-after-drawers'
1838 will be ognored."
1839 :group 'org-todo
1840 :group 'org-progress
1841 :type '(choice
1842 (const :tag "Not into a drawer" nil)
1843 (const :tag "LOGBOOK" t)
1844 (string :tag "Other")))
1846 (if (fboundp 'defvaralias)
1847 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1849 (defcustom org-log-state-notes-insert-after-drawers nil
1850 "Non-nil means, insert state change notes after any drawers in entry.
1851 Only the drawers that *immediately* follow the headline and the
1852 deadline/scheduled line are skipped.
1853 When nil, insert notes right after the heading and perhaps the line
1854 with deadline/scheduling if present.
1856 This variable will have no effect if `org-log-into-drawer' is
1857 set."
1858 :group 'org-todo
1859 :group 'org-progress
1860 :type 'boolean)
1862 (defcustom org-log-states-order-reversed t
1863 "Non-nil means, the latest state change note will be directly after heading.
1864 When nil, the notes will be orderer according to time."
1865 :group 'org-todo
1866 :group 'org-progress
1867 :type 'boolean)
1869 (defcustom org-log-repeat 'time
1870 "Non-nil means, record moving through the DONE state when triggering repeat.
1871 An auto-repeating tasks is immediately switched back to TODO when marked
1872 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1873 the TODO keyword definition, or recording a closing note by setting
1874 `org-log-done', there will be no record of the task moving through DONE.
1875 This variable forces taking a note anyway. Possible values are:
1877 nil Don't force a record
1878 time Record a time stamp
1879 note Record a note
1881 This option can also be set with on a per-file-basis with
1883 #+STARTUP: logrepeat
1884 #+STARTUP: lognoterepeat
1885 #+STARTUP: nologrepeat
1887 You can have local logging settings for a subtree by setting the LOGGING
1888 property to one or more of these keywords."
1889 :group 'org-todo
1890 :group 'org-progress
1891 :type '(choice
1892 (const :tag "Don't force a record" nil)
1893 (const :tag "Force recording the DONE state" time)
1894 (const :tag "Force recording a note with the DONE state" note)))
1897 (defgroup org-priorities nil
1898 "Priorities in Org-mode."
1899 :tag "Org Priorities"
1900 :group 'org-todo)
1902 (defcustom org-highest-priority ?A
1903 "The highest priority of TODO items. A character like ?A, ?B etc.
1904 Must have a smaller ASCII number than `org-lowest-priority'."
1905 :group 'org-priorities
1906 :type 'character)
1908 (defcustom org-lowest-priority ?C
1909 "The lowest priority of TODO items. A character like ?A, ?B etc.
1910 Must have a larger ASCII number than `org-highest-priority'."
1911 :group 'org-priorities
1912 :type 'character)
1914 (defcustom org-default-priority ?B
1915 "The default priority of TODO items.
1916 This is the priority an item get if no explicit priority is given."
1917 :group 'org-priorities
1918 :type 'character)
1920 (defcustom org-priority-start-cycle-with-default t
1921 "Non-nil means, start with default priority when starting to cycle.
1922 When this is nil, the first step in the cycle will be (depending on the
1923 command used) one higher or lower that the default priority."
1924 :group 'org-priorities
1925 :type 'boolean)
1927 (defgroup org-time nil
1928 "Options concerning time stamps and deadlines in Org-mode."
1929 :tag "Org Time"
1930 :group 'org)
1932 (defcustom org-insert-labeled-timestamps-at-point nil
1933 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1934 When nil, these labeled time stamps are forces into the second line of an
1935 entry, just after the headline. When scheduling from the global TODO list,
1936 the time stamp will always be forced into the second line."
1937 :group 'org-time
1938 :type 'boolean)
1940 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1941 "Formats for `format-time-string' which are used for time stamps.
1942 It is not recommended to change this constant.")
1944 (defcustom org-time-stamp-rounding-minutes '(0 5)
1945 "Number of minutes to round time stamps to.
1946 These are two values, the first applies when first creating a time stamp.
1947 The second applies when changing it with the commands `S-up' and `S-down'.
1948 When changing the time stamp, this means that it will change in steps
1949 of N minutes, as given by the second value.
1951 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1952 numbers should be factors of 60, so for example 5, 10, 15.
1954 When this is larger than 1, you can still force an exact time-stamp by using
1955 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1956 and by using a prefix arg to `S-up/down' to specify the exact number
1957 of minutes to shift."
1958 :group 'org-time
1959 :get '(lambda (var) ; Make sure all entries have 5 elements
1960 (if (integerp (default-value var))
1961 (list (default-value var) 5)
1962 (default-value var)))
1963 :type '(list
1964 (integer :tag "when inserting times")
1965 (integer :tag "when modifying times")))
1967 ;; Normalize old customizations of this variable.
1968 (when (integerp org-time-stamp-rounding-minutes)
1969 (setq org-time-stamp-rounding-minutes
1970 (list org-time-stamp-rounding-minutes
1971 org-time-stamp-rounding-minutes)))
1973 (defcustom org-display-custom-times nil
1974 "Non-nil means, overlay custom formats over all time stamps.
1975 The formats are defined through the variable `org-time-stamp-custom-formats'.
1976 To turn this on on a per-file basis, insert anywhere in the file:
1977 #+STARTUP: customtime"
1978 :group 'org-time
1979 :set 'set-default
1980 :type 'sexp)
1981 (make-variable-buffer-local 'org-display-custom-times)
1983 (defcustom org-time-stamp-custom-formats
1984 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1985 "Custom formats for time stamps. See `format-time-string' for the syntax.
1986 These are overlayed over the default ISO format if the variable
1987 `org-display-custom-times' is set. Time like %H:%M should be at the
1988 end of the second format."
1989 :group 'org-time
1990 :type 'sexp)
1992 (defun org-time-stamp-format (&optional long inactive)
1993 "Get the right format for a time string."
1994 (let ((f (if long (cdr org-time-stamp-formats)
1995 (car org-time-stamp-formats))))
1996 (if inactive
1997 (concat "[" (substring f 1 -1) "]")
1998 f)))
2000 (defcustom org-time-clocksum-format "%d:%02d"
2001 "The format string used when creating CLOCKSUM lines, or when
2002 org-mode generates a time duration."
2003 :group 'org-time
2004 :type 'string)
2006 (defcustom org-deadline-warning-days 14
2007 "No. of days before expiration during which a deadline becomes active.
2008 This variable governs the display in sparse trees and in the agenda.
2009 When 0 or negative, it means use this number (the absolute value of it)
2010 even if a deadline has a different individual lead time specified."
2011 :group 'org-time
2012 :group 'org-agenda-daily/weekly
2013 :type 'number)
2015 (defcustom org-read-date-prefer-future t
2016 "Non-nil means, assume future for incomplete date input from user.
2017 This affects the following situations:
2018 1. The user gives a day, but no month.
2019 For example, if today is the 15th, and you enter \"3\", Org-mode will
2020 read this as the third of *next* month. However, if you enter \"17\",
2021 it will be considered as *this* month.
2022 2. The user gives a month but not a year.
2023 For example, if it is april and you enter \"feb 2\", this will be read
2024 as feb 2, *next* year. \"May 5\", however, will be this year.
2026 Currently this does not work for ISO week specifications.
2028 When this option is nil, the current month and year will always be used
2029 as defaults."
2030 :group 'org-time
2031 :type 'boolean)
2033 (defcustom org-read-date-display-live t
2034 "Non-nil means, display current interpretation of date prompt live.
2035 This display will be in an overlay, in the minibuffer."
2036 :group 'org-time
2037 :type 'boolean)
2039 (defcustom org-read-date-popup-calendar t
2040 "Non-nil means, pop up a calendar when prompting for a date.
2041 In the calendar, the date can be selected with mouse-1. However, the
2042 minibuffer will also be active, and you can simply enter the date as well.
2043 When nil, only the minibuffer will be available."
2044 :group 'org-time
2045 :type 'boolean)
2046 (if (fboundp 'defvaralias)
2047 (defvaralias 'org-popup-calendar-for-date-prompt
2048 'org-read-date-popup-calendar))
2050 (defcustom org-extend-today-until 0
2051 "The hour when your day really ends. Must be an integer.
2052 This has influence for the following applications:
2053 - When switching the agenda to \"today\". It it is still earlier than
2054 the time given here, the day recognized as TODAY is actually yesterday.
2055 - When a date is read from the user and it is still before the time given
2056 here, the current date and time will be assumed to be yesterday, 23:59.
2057 Also, timestamps inserted in remember templates follow this rule.
2059 IMPORTANT: This is a feature whose implementation is and likely will
2060 remain incomplete. Really, it is only here because past midnight seems to
2061 be the favorite working time of John Wiegley :-)"
2062 :group 'org-time
2063 :type 'number)
2065 (defcustom org-edit-timestamp-down-means-later nil
2066 "Non-nil means, S-down will increase the time in a time stamp.
2067 When nil, S-up will increase."
2068 :group 'org-time
2069 :type 'boolean)
2071 (defcustom org-calendar-follow-timestamp-change t
2072 "Non-nil means, make the calendar window follow timestamp changes.
2073 When a timestamp is modified and the calendar window is visible, it will be
2074 moved to the new date."
2075 :group 'org-time
2076 :type 'boolean)
2078 (defgroup org-tags nil
2079 "Options concerning tags in Org-mode."
2080 :tag "Org Tags"
2081 :group 'org)
2083 (defcustom org-tag-alist nil
2084 "List of tags allowed in Org-mode files.
2085 When this list is nil, Org-mode will base TAG input on what is already in the
2086 buffer.
2087 The value of this variable is an alist, the car of each entry must be a
2088 keyword as a string, the cdr may be a character that is used to select
2089 that tag through the fast-tag-selection interface.
2090 See the manual for details."
2091 :group 'org-tags
2092 :type '(repeat
2093 (choice
2094 (cons (string :tag "Tag name")
2095 (character :tag "Access char"))
2096 (const :tag "Start radio group" (:startgroup))
2097 (const :tag "End radio group" (:endgroup))
2098 (const :tag "New line" (:newline)))))
2100 (defcustom org-tag-persistent-alist nil
2101 "List of tags that will always appear in all Org-mode files.
2102 This is in addition to any in buffer settings or customizations
2103 of `org-tag-alist'.
2104 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2105 The value of this variable is an alist, the car of each entry must be a
2106 keyword as a string, the cdr may be a character that is used to select
2107 that tag through the fast-tag-selection interface.
2108 See the manual for details.
2109 To disable these tags on a per-file basis, insert anywhere in the file:
2110 #+STARTUP: noptag"
2111 :group 'org-tags
2112 :type '(repeat
2113 (choice
2114 (cons (string :tag "Tag name")
2115 (character :tag "Access char"))
2116 (const :tag "Start radio group" (:startgroup))
2117 (const :tag "End radio group" (:endgroup))
2118 (const :tag "New line" (:newline)))))
2120 (defvar org-file-tags nil
2121 "List of tags that can be inherited by all entries in the file.
2122 The tags will be inherited if the variable `org-use-tag-inheritance'
2123 says they should be.
2124 This variable is populated from #+TAG lines.")
2126 (defcustom org-use-fast-tag-selection 'auto
2127 "Non-nil means, use fast tag selection scheme.
2128 This is a special interface to select and deselect tags with single keys.
2129 When nil, fast selection is never used.
2130 When the symbol `auto', fast selection is used if and only if selection
2131 characters for tags have been configured, either through the variable
2132 `org-tag-alist' or through a #+TAGS line in the buffer.
2133 When t, fast selection is always used and selection keys are assigned
2134 automatically if necessary."
2135 :group 'org-tags
2136 :type '(choice
2137 (const :tag "Always" t)
2138 (const :tag "Never" nil)
2139 (const :tag "When selection characters are configured" 'auto)))
2141 (defcustom org-fast-tag-selection-single-key nil
2142 "Non-nil means, fast tag selection exits after first change.
2143 When nil, you have to press RET to exit it.
2144 During fast tag selection, you can toggle this flag with `C-c'.
2145 This variable can also have the value `expert'. In this case, the window
2146 displaying the tags menu is not even shown, until you press C-c again."
2147 :group 'org-tags
2148 :type '(choice
2149 (const :tag "No" nil)
2150 (const :tag "Yes" t)
2151 (const :tag "Expert" expert)))
2153 (defvar org-fast-tag-selection-include-todo nil
2154 "Non-nil means, fast tags selection interface will also offer TODO states.
2155 This is an undocumented feature, you should not rely on it.")
2157 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2158 "The column to which tags should be indented in a headline.
2159 If this number is positive, it specifies the column. If it is negative,
2160 it means that the tags should be flushright to that column. For example,
2161 -80 works well for a normal 80 character screen."
2162 :group 'org-tags
2163 :type 'integer)
2165 (defcustom org-auto-align-tags t
2166 "Non-nil means, realign tags after pro/demotion of TODO state change.
2167 These operations change the length of a headline and therefore shift
2168 the tags around. With this options turned on, after each such operation
2169 the tags are again aligned to `org-tags-column'."
2170 :group 'org-tags
2171 :type 'boolean)
2173 (defcustom org-use-tag-inheritance t
2174 "Non-nil means, tags in levels apply also for sublevels.
2175 When nil, only the tags directly given in a specific line apply there.
2176 This may also be a list of tags that should be inherited, or a regexp that
2177 matches tags that should be inherited. Additional control is possible
2178 with the variable `org-tags-exclude-from-inheritance' which gives an
2179 explicit list of tags to be excluded from inheritance., even if the value of
2180 `org-use-tag-inheritance' would select it for inheritance.
2182 If this option is t, a match early-on in a tree can lead to a large
2183 number of matches in the subtree when constructing the agenda or creating
2184 a sparse tree. If you only want to see the first match in a tree during
2185 a search, check out the variable `org-tags-match-list-sublevels'."
2186 :group 'org-tags
2187 :type '(choice
2188 (const :tag "Not" nil)
2189 (const :tag "Always" t)
2190 (repeat :tag "Specific tags" (string :tag "Tag"))
2191 (regexp :tag "Tags matched by regexp")))
2193 (defcustom org-tags-exclude-from-inheritance nil
2194 "List of tags that should never be inherited.
2195 This is a way to exclude a few tags from inheritance. For way to do
2196 the opposite, to actively allow inheritance for selected tags,
2197 see the variable `org-use-tag-inheritance'."
2198 :group 'org-tags
2199 :type '(repeat (string :tag "Tag")))
2201 (defun org-tag-inherit-p (tag)
2202 "Check if TAG is one that should be inherited."
2203 (cond
2204 ((member tag org-tags-exclude-from-inheritance) nil)
2205 ((eq org-use-tag-inheritance t) t)
2206 ((not org-use-tag-inheritance) nil)
2207 ((stringp org-use-tag-inheritance)
2208 (string-match org-use-tag-inheritance tag))
2209 ((listp org-use-tag-inheritance)
2210 (member tag org-use-tag-inheritance))
2211 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2213 (defcustom org-tags-match-list-sublevels t
2214 "Non-nil means list also sublevels of headlines matching tag search.
2215 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2216 the sublevels of a headline matching a tag search often also match
2217 the same search. Listing all of them can create very long lists.
2218 Setting this variable to nil causes subtrees of a match to be skipped.
2219 This option is off by default, because inheritance in on. If you turn
2220 inheritance off, you very likely want to turn this option on.
2222 As a special case, if the tag search is restricted to TODO items, the
2223 value of this variable is ignored and sublevels are always checked, to
2224 make sure all corresponding TODO items find their way into the list.
2226 This variable is semi-obsolete and probably should always be true. It
2227 is better to limit inheritance to certain tags using the variables
2228 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2229 :group 'org-tags
2230 :type 'boolean)
2232 (defvar org-tags-history nil
2233 "History of minibuffer reads for tags.")
2234 (defvar org-last-tags-completion-table nil
2235 "The last used completion table for tags.")
2236 (defvar org-after-tags-change-hook nil
2237 "Hook that is run after the tags in a line have changed.")
2239 (defgroup org-properties nil
2240 "Options concerning properties in Org-mode."
2241 :tag "Org Properties"
2242 :group 'org)
2244 (defcustom org-property-format "%-10s %s"
2245 "How property key/value pairs should be formatted by `indent-line'.
2246 When `indent-line' hits a property definition, it will format the line
2247 according to this format, mainly to make sure that the values are
2248 lined-up with respect to each other."
2249 :group 'org-properties
2250 :type 'string)
2252 (defcustom org-use-property-inheritance nil
2253 "Non-nil means, properties apply also for sublevels.
2255 This setting is chiefly used during property searches. Turning it on can
2256 cause significant overhead when doing a search, which is why it is not
2257 on by default.
2259 When nil, only the properties directly given in the current entry count.
2260 When t, every property is inherited. The value may also be a list of
2261 properties that should have inheritance, or a regular expression matching
2262 properties that should be inherited.
2264 However, note that some special properties use inheritance under special
2265 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2266 and the properties ending in \"_ALL\" when they are used as descriptor
2267 for valid values of a property.
2269 Note for programmers:
2270 When querying an entry with `org-entry-get', you can control if inheritance
2271 should be used. By default, `org-entry-get' looks only at the local
2272 properties. You can request inheritance by setting the inherit argument
2273 to t (to force inheritance) or to `selective' (to respect the setting
2274 in this variable)."
2275 :group 'org-properties
2276 :type '(choice
2277 (const :tag "Not" nil)
2278 (const :tag "Always" t)
2279 (repeat :tag "Specific properties" (string :tag "Property"))
2280 (regexp :tag "Properties matched by regexp")))
2282 (defun org-property-inherit-p (property)
2283 "Check if PROPERTY is one that should be inherited."
2284 (cond
2285 ((eq org-use-property-inheritance t) t)
2286 ((not org-use-property-inheritance) nil)
2287 ((stringp org-use-property-inheritance)
2288 (string-match org-use-property-inheritance property))
2289 ((listp org-use-property-inheritance)
2290 (member property org-use-property-inheritance))
2291 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2293 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2294 "The default column format, if no other format has been defined.
2295 This variable can be set on the per-file basis by inserting a line
2297 #+COLUMNS: %25ITEM ....."
2298 :group 'org-properties
2299 :type 'string)
2301 (defcustom org-columns-ellipses ".."
2302 "The ellipses to be used when a field in column view is truncated.
2303 When this is the empty string, as many characters as possible are shown,
2304 but then there will be no visual indication that the field has been truncated.
2305 When this is a string of length N, the last N characters of a truncated
2306 field are replaced by this string. If the column is narrower than the
2307 ellipses string, only part of the ellipses string will be shown."
2308 :group 'org-properties
2309 :type 'string)
2311 (defcustom org-columns-modify-value-for-display-function nil
2312 "Function that modifies values for display in column view.
2313 For example, it can be used to cut out a certain part from a time stamp.
2314 The function must take 2 arguments:
2316 column-title The title of the column (*not* the property name)
2317 value The value that should be modified.
2319 The function should return the value that should be displayed,
2320 or nil if the normal value should be used."
2321 :group 'org-properties
2322 :type 'function)
2324 (defcustom org-effort-property "Effort"
2325 "The property that is being used to keep track of effort estimates.
2326 Effort estimates given in this property need to have the format H:MM."
2327 :group 'org-properties
2328 :group 'org-progress
2329 :type '(string :tag "Property"))
2331 (defconst org-global-properties-fixed
2332 '(("VISIBILITY_ALL" . "folded children content all"))
2333 "List of property/value pairs that can be inherited by any entry.
2335 These are fixed values, for the preset properties. The user variable
2336 that can be used to add to this list is `org-global-properties'.
2338 The entries in this list are cons cells where the car is a property
2339 name and cdr is a string with the value. If the value represents
2340 multiple items like an \"_ALL\" property, separate the items by
2341 spaces.")
2343 (defcustom org-global-properties nil
2344 "List of property/value pairs that can be inherited by any entry.
2346 This list will be combined with the constant `org-global-properties-fixed'.
2348 The entries in this list are cons cells where the car is a property
2349 name and cdr is a string with the value.
2351 You can set buffer-local values for the same purpose in the variable
2352 `org-file-properties' this by adding lines like
2354 #+PROPERTY: NAME VALUE"
2355 :group 'org-properties
2356 :type '(repeat
2357 (cons (string :tag "Property")
2358 (string :tag "Value"))))
2360 (defvar org-file-properties nil
2361 "List of property/value pairs that can be inherited by any entry.
2362 Valid for the current buffer.
2363 This variable is populated from #+PROPERTY lines.")
2364 (make-variable-buffer-local 'org-file-properties)
2366 (defgroup org-agenda nil
2367 "Options concerning agenda views in Org-mode."
2368 :tag "Org Agenda"
2369 :group 'org)
2371 (defvar org-category nil
2372 "Variable used by org files to set a category for agenda display.
2373 Such files should use a file variable to set it, for example
2375 # -*- mode: org; org-category: \"ELisp\"
2377 or contain a special line
2379 #+CATEGORY: ELisp
2381 If the file does not specify a category, then file's base name
2382 is used instead.")
2383 (make-variable-buffer-local 'org-category)
2384 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2386 (defcustom org-agenda-files nil
2387 "The files to be used for agenda display.
2388 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2389 \\[org-remove-file]. You can also use customize to edit the list.
2391 If an entry is a directory, all files in that directory that are matched by
2392 `org-agenda-file-regexp' will be part of the file list.
2394 If the value of the variable is not a list but a single file name, then
2395 the list of agenda files is actually stored and maintained in that file, one
2396 agenda file per line."
2397 :group 'org-agenda
2398 :type '(choice
2399 (repeat :tag "List of files and directories" file)
2400 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2402 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2403 "Regular expression to match files for `org-agenda-files'.
2404 If any element in the list in that variable contains a directory instead
2405 of a normal file, all files in that directory that are matched by this
2406 regular expression will be included."
2407 :group 'org-agenda
2408 :type 'regexp)
2410 (defcustom org-agenda-text-search-extra-files nil
2411 "List of extra files to be searched by text search commands.
2412 These files will be search in addition to the agenda files by the
2413 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2414 Note that these files will only be searched for text search commands,
2415 not for the other agenda views like todo lists, tag searches or the weekly
2416 agenda. This variable is intended to list notes and possibly archive files
2417 that should also be searched by these two commands.
2418 In fact, if the first element in the list is the symbol `agenda-archives',
2419 than all archive files of all agenda files will be added to the search
2420 scope."
2421 :group 'org-agenda
2422 :type '(set :greedy t
2423 (const :tag "Agenda Archives" agenda-archives)
2424 (repeat :inline t (file))))
2426 (if (fboundp 'defvaralias)
2427 (defvaralias 'org-agenda-multi-occur-extra-files
2428 'org-agenda-text-search-extra-files))
2430 (defcustom org-agenda-skip-unavailable-files nil
2431 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2432 A nil value means to remove them, after a query, from the list."
2433 :group 'org-agenda
2434 :type 'boolean)
2436 (defcustom org-calendar-to-agenda-key [?c]
2437 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2438 The command `org-calendar-goto-agenda' will be bound to this key. The
2439 default is the character `c' because then `c' can be used to switch back and
2440 forth between agenda and calendar."
2441 :group 'org-agenda
2442 :type 'sexp)
2444 (defcustom org-calendar-agenda-action-key [?k]
2445 "The key to be installed in `calendar-mode-map' for agenda-action.
2446 The command `org-agenda-action' will be bound to this key. The
2447 default is the character `k' because we use the same key in the agenda."
2448 :group 'org-agenda
2449 :type 'sexp)
2451 (eval-after-load "calendar"
2452 '(progn
2453 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2454 'org-calendar-goto-agenda)
2455 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2456 'org-agenda-action)))
2458 (defgroup org-latex nil
2459 "Options for embedding LaTeX code into Org-mode."
2460 :tag "Org LaTeX"
2461 :group 'org)
2463 (defcustom org-format-latex-options
2464 '(:foreground default :background default :scale 1.0
2465 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2466 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2467 "Options for creating images from LaTeX fragments.
2468 This is a property list with the following properties:
2469 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2470 `default' means use the foreground of the default face.
2471 :background the background color, or \"Transparent\".
2472 `default' means use the background of the default face.
2473 :scale a scaling factor for the size of the images.
2474 :html-foreground, :html-background, :html-scale
2475 the same numbers for HTML export.
2476 :matchers a list indicating which matchers should be used to
2477 find LaTeX fragments. Valid members of this list are:
2478 \"begin\" find environments
2479 \"$1\" find single characters surrounded by $.$
2480 \"$\" find math expressions surrounded by $...$
2481 \"$$\" find math expressions surrounded by $$....$$
2482 \"\\(\" find math expressions surrounded by \\(...\\)
2483 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2484 :group 'org-latex
2485 :type 'plist)
2487 (defcustom org-format-latex-header "\\documentclass{article}
2488 \\usepackage{fullpage} % do not remove
2489 \\usepackage{amssymb}
2490 \\usepackage[usenames]{color}
2491 \\usepackage{amsmath}
2492 \\usepackage{latexsym}
2493 \\usepackage[mathscr]{eucal}
2494 \\pagestyle{empty} % do not remove"
2495 "The document header used for processing LaTeX fragments."
2496 :group 'org-latex
2497 :type 'string)
2500 (defgroup org-font-lock nil
2501 "Font-lock settings for highlighting in Org-mode."
2502 :tag "Org Font Lock"
2503 :group 'org)
2505 (defcustom org-level-color-stars-only nil
2506 "Non-nil means fontify only the stars in each headline.
2507 When nil, the entire headline is fontified.
2508 Changing it requires restart of `font-lock-mode' to become effective
2509 also in regions already fontified."
2510 :group 'org-font-lock
2511 :type 'boolean)
2513 (defcustom org-hide-leading-stars nil
2514 "Non-nil means, hide the first N-1 stars in a headline.
2515 This works by using the face `org-hide' for these stars. This
2516 face is white for a light background, and black for a dark
2517 background. You may have to customize the face `org-hide' to
2518 make this work.
2519 Changing it requires restart of `font-lock-mode' to become effective
2520 also in regions already fontified.
2521 You may also set this on a per-file basis by adding one of the following
2522 lines to the buffer:
2524 #+STARTUP: hidestars
2525 #+STARTUP: showstars"
2526 :group 'org-font-lock
2527 :type 'boolean)
2529 (defcustom org-fontify-done-headline nil
2530 "Non-nil means, change the face of a headline if it is marked DONE.
2531 Normally, only the TODO/DONE keyword indicates the state of a headline.
2532 When this is non-nil, the headline after the keyword is set to the
2533 `org-headline-done' as an additional indication."
2534 :group 'org-font-lock
2535 :type 'boolean)
2537 (defcustom org-fontify-emphasized-text t
2538 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2539 Changing this variable requires a restart of Emacs to take effect."
2540 :group 'org-font-lock
2541 :type 'boolean)
2543 (defcustom org-highlight-latex-fragments-and-specials nil
2544 "Non-nil means, fontify what is treated specially by the exporters."
2545 :group 'org-font-lock
2546 :type 'boolean)
2548 (defcustom org-hide-emphasis-markers nil
2549 "Non-nil mean font-lock should hide the emphasis marker characters."
2550 :group 'org-font-lock
2551 :type 'boolean)
2553 (defvar org-emph-re nil
2554 "Regular expression for matching emphasis.")
2555 (defvar org-verbatim-re nil
2556 "Regular expression for matching verbatim text.")
2557 (defvar org-emphasis-regexp-components) ; defined just below
2558 (defvar org-emphasis-alist) ; defined just below
2559 (defun org-set-emph-re (var val)
2560 "Set variable and compute the emphasis regular expression."
2561 (set var val)
2562 (when (and (boundp 'org-emphasis-alist)
2563 (boundp 'org-emphasis-regexp-components)
2564 org-emphasis-alist org-emphasis-regexp-components)
2565 (let* ((e org-emphasis-regexp-components)
2566 (pre (car e))
2567 (post (nth 1 e))
2568 (border (nth 2 e))
2569 (body (nth 3 e))
2570 (nl (nth 4 e))
2571 (body1 (concat body "*?"))
2572 (markers (mapconcat 'car org-emphasis-alist ""))
2573 (vmarkers (mapconcat
2574 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2575 org-emphasis-alist "")))
2576 ;; make sure special characters appear at the right position in the class
2577 (if (string-match "\\^" markers)
2578 (setq markers (concat (replace-match "" t t markers) "^")))
2579 (if (string-match "-" markers)
2580 (setq markers (concat (replace-match "" t t markers) "-")))
2581 (if (string-match "\\^" vmarkers)
2582 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2583 (if (string-match "-" vmarkers)
2584 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2585 (if (> nl 0)
2586 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2587 (int-to-string nl) "\\}")))
2588 ;; Make the regexp
2589 (setq org-emph-re
2590 (concat "\\([" pre "]\\|^\\)"
2591 "\\("
2592 "\\([" markers "]\\)"
2593 "\\("
2594 "[^" border "]\\|"
2595 "[^" border "]"
2596 body1
2597 "[^" border "]"
2598 "\\)"
2599 "\\3\\)"
2600 "\\([" post "]\\|$\\)"))
2601 (setq org-verbatim-re
2602 (concat "\\([" pre "]\\|^\\)"
2603 "\\("
2604 "\\([" vmarkers "]\\)"
2605 "\\("
2606 "[^" border "]\\|"
2607 "[^" border "]"
2608 body1
2609 "[^" border "]"
2610 "\\)"
2611 "\\3\\)"
2612 "\\([" post "]\\|$\\)")))))
2614 (defcustom org-emphasis-regexp-components
2615 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2616 "Components used to build the regular expression for emphasis.
2617 This is a list with 6 entries. Terminology: In an emphasis string
2618 like \" *strong word* \", we call the initial space PREMATCH, the final
2619 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2620 and \"trong wor\" is the body. The different components in this variable
2621 specify what is allowed/forbidden in each part:
2623 pre Chars allowed as prematch. Beginning of line will be allowed too.
2624 post Chars allowed as postmatch. End of line will be allowed too.
2625 border The chars *forbidden* as border characters.
2626 body-regexp A regexp like \".\" to match a body character. Don't use
2627 non-shy groups here, and don't allow newline here.
2628 newline The maximum number of newlines allowed in an emphasis exp.
2630 Use customize to modify this, or restart Emacs after changing it."
2631 :group 'org-font-lock
2632 :set 'org-set-emph-re
2633 :type '(list
2634 (sexp :tag "Allowed chars in pre ")
2635 (sexp :tag "Allowed chars in post ")
2636 (sexp :tag "Forbidden chars in border ")
2637 (sexp :tag "Regexp for body ")
2638 (integer :tag "number of newlines allowed")
2639 (option (boolean :tag "Please ignore this button"))))
2641 (defcustom org-emphasis-alist
2642 `(("*" bold "<b>" "</b>")
2643 ("/" italic "<i>" "</i>")
2644 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2645 ("=" org-code "<code>" "</code>" verbatim)
2646 ("~" org-verbatim "<code>" "</code>" verbatim)
2647 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2648 "<del>" "</del>")
2650 "Special syntax for emphasized text.
2651 Text starting and ending with a special character will be emphasized, for
2652 example *bold*, _underlined_ and /italic/. This variable sets the marker
2653 characters, the face to be used by font-lock for highlighting in Org-mode
2654 Emacs buffers, and the HTML tags to be used for this.
2655 Use customize to modify this, or restart Emacs after changing it."
2656 :group 'org-font-lock
2657 :set 'org-set-emph-re
2658 :type '(repeat
2659 (list
2660 (string :tag "Marker character")
2661 (choice
2662 (face :tag "Font-lock-face")
2663 (plist :tag "Face property list"))
2664 (string :tag "HTML start tag")
2665 (string :tag "HTML end tag")
2666 (option (const verbatim)))))
2668 ;;; Miscellaneous options
2670 (defgroup org-completion nil
2671 "Completion in Org-mode."
2672 :tag "Org Completion"
2673 :group 'org)
2675 (defcustom org-completion-use-ido nil
2676 "Non-nil means, use ido completion wherever possible.
2677 Note that `ido-mode' must be active for this variable to be relevant.
2678 If you decide to turn this variable on, you might well want to turn off
2679 `org-outline-path-complete-in-steps'."
2680 :group 'org-completion
2681 :type 'boolean)
2683 (defcustom org-completion-fallback-command 'hippie-expand
2684 "The expansion command called by \\[org-complete] in normal context.
2685 Normal means, no org-mode-specific context."
2686 :group 'org-completion
2687 :type 'function)
2689 ;;; Functions and variables from ther packages
2690 ;; Declared here to avoid compiler warnings
2692 ;; XEmacs only
2693 (defvar outline-mode-menu-heading)
2694 (defvar outline-mode-menu-show)
2695 (defvar outline-mode-menu-hide)
2696 (defvar zmacs-regions) ; XEmacs regions
2698 ;; Emacs only
2699 (defvar mark-active)
2701 ;; Various packages
2702 (declare-function find-library-name "find-func" (library))
2703 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2704 (declare-function calendar-forward-day "cal-move" (arg))
2705 (declare-function calendar-goto-date "cal-move" (date))
2706 (declare-function calendar-goto-today "cal-move" ())
2707 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2708 (defvar calc-embedded-close-formula)
2709 (defvar calc-embedded-open-formula)
2710 (declare-function cdlatex-tab "ext:cdlatex" ())
2711 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2712 (defvar font-lock-unfontify-region-function)
2713 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2714 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2715 (defvar iswitchb-temp-buflist)
2716 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2717 (defvar org-agenda-tags-todo-honor-ignore-options)
2718 (declare-function org-agenda-skip "org-agenda" ())
2719 (declare-function org-format-agenda-item "org-agenda"
2720 (extra txt &optional category tags dotime noprefix remove-re))
2721 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2722 (declare-function org-agenda-change-all-lines "org-agenda"
2723 (newhead hdmarker &optional fixface just-this))
2724 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2725 (declare-function org-agenda-maybe-redo "org-agenda" ())
2726 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2727 (beg end))
2728 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2729 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2730 "org-agenda" (&optional end))
2732 (declare-function parse-time-string "parse-time" (string))
2733 (declare-function remember "remember" (&optional initial))
2734 (declare-function remember-buffer-desc "remember" ())
2735 (declare-function remember-finalize "remember" ())
2736 (defvar remember-save-after-remembering)
2737 (defvar remember-data-file)
2738 (defvar remember-register)
2739 (defvar remember-buffer)
2740 (defvar remember-handler-functions)
2741 (defvar remember-annotation-functions)
2742 (defvar texmathp-why)
2743 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2744 (declare-function table--at-cell-p "table" (position &optional object at-column))
2746 (defvar w3m-current-url)
2747 (defvar w3m-current-title)
2749 (defvar org-latex-regexps)
2751 ;;; Autoload and prepare some org modules
2753 ;; Some table stuff that needs to be defined here, because it is used
2754 ;; by the functions setting up org-mode or checking for table context.
2756 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2757 "Detects an org-type or table-type table.")
2758 (defconst org-table-line-regexp "^[ \t]*|"
2759 "Detects an org-type table line.")
2760 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2761 "Detects an org-type table line.")
2762 (defconst org-table-hline-regexp "^[ \t]*|-"
2763 "Detects an org-type table hline.")
2764 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2765 "Detects a table-type table hline.")
2766 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2767 "Searching from within a table (any type) this finds the first line
2768 outside the table.")
2770 ;; Autoload the functions in org-table.el that are needed by functions here.
2772 (eval-and-compile
2773 (org-autoload "org-table"
2774 '(org-table-align org-table-begin org-table-blank-field
2775 org-table-convert org-table-convert-region org-table-copy-down
2776 org-table-copy-region org-table-create
2777 org-table-create-or-convert-from-region
2778 org-table-create-with-table.el org-table-current-dline
2779 org-table-cut-region org-table-delete-column org-table-edit-field
2780 org-table-edit-formulas org-table-end org-table-eval-formula
2781 org-table-export org-table-field-info
2782 org-table-get-stored-formulas org-table-goto-column
2783 org-table-hline-and-move org-table-import org-table-insert-column
2784 org-table-insert-hline org-table-insert-row org-table-iterate
2785 org-table-justify-field-maybe org-table-kill-row
2786 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2787 org-table-move-column org-table-move-column-left
2788 org-table-move-column-right org-table-move-row
2789 org-table-move-row-down org-table-move-row-up
2790 org-table-next-field org-table-next-row org-table-paste-rectangle
2791 org-table-previous-field org-table-recalculate
2792 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2793 org-table-toggle-coordinate-overlays
2794 org-table-toggle-formula-debugger org-table-wrap-region
2795 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2797 (defun org-at-table-p (&optional table-type)
2798 "Return t if the cursor is inside an org-type table.
2799 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2800 (if org-enable-table-editor
2801 (save-excursion
2802 (beginning-of-line 1)
2803 (looking-at (if table-type org-table-any-line-regexp
2804 org-table-line-regexp)))
2805 nil))
2806 (defsubst org-table-p () (org-at-table-p))
2808 (defun org-at-table.el-p ()
2809 "Return t if and only if we are at a table.el table."
2810 (and (org-at-table-p 'any)
2811 (save-excursion
2812 (goto-char (org-table-begin 'any))
2813 (looking-at org-table1-hline-regexp))))
2814 (defun org-table-recognize-table.el ()
2815 "If there is a table.el table nearby, recognize it and move into it."
2816 (if org-table-tab-recognizes-table.el
2817 (if (org-at-table.el-p)
2818 (progn
2819 (beginning-of-line 1)
2820 (if (looking-at org-table-dataline-regexp)
2822 (if (looking-at org-table1-hline-regexp)
2823 (progn
2824 (beginning-of-line 2)
2825 (if (looking-at org-table-any-border-regexp)
2826 (beginning-of-line -1)))))
2827 (if (re-search-forward "|" (org-table-end t) t)
2828 (progn
2829 (require 'table)
2830 (if (table--at-cell-p (point))
2832 (message "recognizing table.el table...")
2833 (table-recognize-table)
2834 (message "recognizing table.el table...done")))
2835 (error "This should not happen..."))
2837 nil)
2838 nil))
2840 (defun org-at-table-hline-p ()
2841 "Return t if the cursor is inside a hline in a table."
2842 (if org-enable-table-editor
2843 (save-excursion
2844 (beginning-of-line 1)
2845 (looking-at org-table-hline-regexp))
2846 nil))
2848 (defvar org-table-clean-did-remove-column nil)
2850 (defun org-table-map-tables (function)
2851 "Apply FUNCTION to the start of all tables in the buffer."
2852 (save-excursion
2853 (save-restriction
2854 (widen)
2855 (goto-char (point-min))
2856 (while (re-search-forward org-table-any-line-regexp nil t)
2857 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2858 (beginning-of-line 1)
2859 (if (looking-at org-table-line-regexp)
2860 (save-excursion (funcall function)))
2861 (re-search-forward org-table-any-border-regexp nil 1))))
2862 (message "Mapping tables: done"))
2864 ;; Declare and autoload functions from org-exp.el
2866 (declare-function org-default-export-plist "org-exp")
2867 (declare-function org-infile-export-plist "org-exp")
2868 (declare-function org-get-current-options "org-exp")
2869 (eval-and-compile
2870 (org-autoload "org-exp"
2871 '(org-export org-export-as-ascii org-export-visible
2872 org-insert-export-options-template org-export-as-html-and-open
2873 org-export-as-html-batch org-export-as-html-to-buffer
2874 org-replace-region-by-html org-export-region-as-html
2875 org-export-as-html org-export-icalendar-this-file
2876 org-export-icalendar-all-agenda-files
2877 org-table-clean-before-export
2878 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2880 ;; Declare and autoload functions from org-agenda.el
2882 (eval-and-compile
2883 (org-autoload "org-agenda"
2884 '(org-agenda org-agenda-list org-search-view
2885 org-todo-list org-tags-view org-agenda-list-stuck-projects
2886 org-diary org-agenda-to-appt
2887 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2889 ;; Autoload org-remember
2891 (eval-and-compile
2892 (org-autoload "org-remember"
2893 '(org-remember-insinuate org-remember-annotation
2894 org-remember-apply-template org-remember org-remember-handler)))
2896 ;; Autoload org-clock.el
2899 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2900 (beg end))
2901 (declare-function org-clock-update-mode-line "org-clock" ())
2902 (defvar org-clock-start-time)
2903 (defvar org-clock-marker (make-marker)
2904 "Marker recording the last clock-in.")
2906 (eval-and-compile
2907 (org-autoload
2908 "org-clock"
2909 '(org-clock-in org-clock-out org-clock-cancel
2910 org-clock-goto org-clock-sum org-clock-display
2911 org-clock-remove-overlays org-clock-report
2912 org-clocktable-shift org-dblock-write:clocktable
2913 org-get-clocktable)))
2915 (defun org-clock-update-time-maybe ()
2916 "If this is a CLOCK line, update it and return t.
2917 Otherwise, return nil."
2918 (interactive)
2919 (save-excursion
2920 (beginning-of-line 1)
2921 (skip-chars-forward " \t")
2922 (when (looking-at org-clock-string)
2923 (let ((re (concat "[ \t]*" org-clock-string
2924 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2925 "\\([ \t]*=>.*\\)?\\)?"))
2926 ts te h m s neg)
2927 (cond
2928 ((not (looking-at re))
2929 nil)
2930 ((not (match-end 2))
2931 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2932 (> org-clock-marker (point))
2933 (<= org-clock-marker (point-at-eol)))
2934 ;; The clock is running here
2935 (setq org-clock-start-time
2936 (apply 'encode-time
2937 (org-parse-time-string (match-string 1))))
2938 (org-clock-update-mode-line)))
2940 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2941 (end-of-line 1)
2942 (setq ts (match-string 1)
2943 te (match-string 3))
2944 (setq s (- (time-to-seconds
2945 (apply 'encode-time (org-parse-time-string te)))
2946 (time-to-seconds
2947 (apply 'encode-time (org-parse-time-string ts))))
2948 neg (< s 0)
2949 s (abs s)
2950 h (floor (/ s 3600))
2951 s (- s (* 3600 h))
2952 m (floor (/ s 60))
2953 s (- s (* 60 s)))
2954 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2955 t))))))
2957 (defun org-check-running-clock ()
2958 "Check if the current buffer contains the running clock.
2959 If yes, offer to stop it and to save the buffer with the changes."
2960 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2961 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2962 (buffer-name))))
2963 (org-clock-out)
2964 (when (y-or-n-p "Save changed buffer?")
2965 (save-buffer))))
2967 (defun org-clocktable-try-shift (dir n)
2968 "Check if this line starts a clock table, if yes, shift the time block."
2969 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2970 (org-clocktable-shift dir n)))
2972 ;; Autoload org-timer.el
2974 ;(declare-function org-timer "org-timer")
2976 (eval-and-compile
2977 (org-autoload
2978 "org-timer"
2979 '(org-timer-start org-timer org-timer-item
2980 org-timer-change-times-in-region)))
2983 ;; Autoload archiving code
2984 ;; The stuff that is needed for cycling and tags has to be defined here.
2986 (defgroup org-archive nil
2987 "Options concerning archiving in Org-mode."
2988 :tag "Org Archive"
2989 :group 'org-structure)
2991 (defcustom org-archive-location "%s_archive::"
2992 "The location where subtrees should be archived.
2994 The value of this variable is a string, consisting of two parts,
2995 separated by a double-colon. The first part is a filename and
2996 the second part is a headline.
2998 When the filename is omitted, archiving happens in the same file.
2999 %s in the filename will be replaced by the current file
3000 name (without the directory part). Archiving to a different file
3001 is useful to keep archived entries from contributing to the
3002 Org-mode Agenda.
3004 The archived entries will be filed as subtrees of the specified
3005 headline. When the headline is omitted, the subtrees are simply
3006 filed away at the end of the file, as top-level entries. Also in
3007 the heading you can use %s to represent the file name, this can be
3008 useful when using the same archive for a number of different files.
3010 Here are a few examples:
3011 \"%s_archive::\"
3012 If the current file is Projects.org, archive in file
3013 Projects.org_archive, as top-level trees. This is the default.
3015 \"::* Archived Tasks\"
3016 Archive in the current file, under the top-level headline
3017 \"* Archived Tasks\".
3019 \"~/org/archive.org::\"
3020 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3022 \"~/org/archive.org::From %s\"
3023 Archive in file ~/org/archive.org (absolute path), und headlines
3024 \"From FILENAME\" where file name is the current file name.
3026 \"basement::** Finished Tasks\"
3027 Archive in file ./basement (relative path), as level 3 trees
3028 below the level 2 heading \"** Finished Tasks\".
3030 You may set this option on a per-file basis by adding to the buffer a
3031 line like
3033 #+ARCHIVE: basement::** Finished Tasks
3035 You may also define it locally for a subtree by setting an ARCHIVE property
3036 in the entry. If such a property is found in an entry, or anywhere up
3037 the hierarchy, it will be used."
3038 :group 'org-archive
3039 :type 'string)
3041 (defcustom org-archive-tag "ARCHIVE"
3042 "The tag that marks a subtree as archived.
3043 An archived subtree does not open during visibility cycling, and does
3044 not contribute to the agenda listings.
3045 After changing this, font-lock must be restarted in the relevant buffers to
3046 get the proper fontification."
3047 :group 'org-archive
3048 :group 'org-keywords
3049 :type 'string)
3051 (defcustom org-agenda-skip-archived-trees t
3052 "Non-nil means, the agenda will skip any items located in archived trees.
3053 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3054 variable is no longer recommended, you should leave it at the value t.
3055 Instead, use the key `v' to cycle the archives-mode in the agenda."
3056 :group 'org-archive
3057 :group 'org-agenda-skip
3058 :type 'boolean)
3060 (defcustom org-cycle-open-archived-trees nil
3061 "Non-nil means, `org-cycle' will open archived trees.
3062 An archived tree is a tree marked with the tag ARCHIVE.
3063 When nil, archived trees will stay folded. You can still open them with
3064 normal outline commands like `show-all', but not with the cycling commands."
3065 :group 'org-archive
3066 :group 'org-cycle
3067 :type 'boolean)
3069 (defcustom org-sparse-tree-open-archived-trees nil
3070 "Non-nil means sparse tree construction shows matches in archived trees.
3071 When nil, matches in these trees are highlighted, but the trees are kept in
3072 collapsed state."
3073 :group 'org-archive
3074 :group 'org-sparse-trees
3075 :type 'boolean)
3077 (defun org-cycle-hide-archived-subtrees (state)
3078 "Re-hide all archived subtrees after a visibility state change."
3079 (when (and (not org-cycle-open-archived-trees)
3080 (not (memq state '(overview folded))))
3081 (save-excursion
3082 (let* ((globalp (memq state '(contents all)))
3083 (beg (if globalp (point-min) (point)))
3084 (end (if globalp (point-max) (org-end-of-subtree t))))
3085 (org-hide-archived-subtrees beg end)
3086 (goto-char beg)
3087 (if (looking-at (concat ".*:" org-archive-tag ":"))
3088 (message "%s" (substitute-command-keys
3089 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3091 (defun org-force-cycle-archived ()
3092 "Cycle subtree even if it is archived."
3093 (interactive)
3094 (setq this-command 'org-cycle)
3095 (let ((org-cycle-open-archived-trees t))
3096 (call-interactively 'org-cycle)))
3098 (defun org-hide-archived-subtrees (beg end)
3099 "Re-hide all archived subtrees after a visibility state change."
3100 (save-excursion
3101 (let* ((re (concat ":" org-archive-tag ":")))
3102 (goto-char beg)
3103 (while (re-search-forward re end t)
3104 (and (org-on-heading-p) (hide-subtree))
3105 (org-end-of-subtree t)))))
3107 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3109 (eval-and-compile
3110 (org-autoload "org-archive"
3111 '(org-add-archive-files org-archive-subtree
3112 org-archive-to-archive-sibling org-toggle-archive-tag)))
3114 ;; Autoload Column View Code
3116 (declare-function org-columns-number-to-string "org-colview")
3117 (declare-function org-columns-get-format-and-top-level "org-colview")
3118 (declare-function org-columns-compute "org-colview")
3120 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3121 '(org-columns-number-to-string org-columns-get-format-and-top-level
3122 org-columns-compute org-agenda-columns org-columns-remove-overlays
3123 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3125 ;; Autoload ID code
3127 (declare-function org-id-store-link "org-id")
3128 (declare-function org-id-locations-load "org-id")
3129 (declare-function org-id-locations-save "org-id")
3130 (defvar org-id-track-globally)
3131 (org-autoload "org-id"
3132 '(org-id-get-create org-id-new org-id-copy org-id-get
3133 org-id-get-with-outline-path-completion
3134 org-id-get-with-outline-drilling
3135 org-id-goto org-id-find org-id-store-link))
3137 ;; Autoload Plotting Code
3139 (org-autoload "org-plot"
3140 '(org-plot/gnuplot))
3142 ;;; Variables for pre-computed regular expressions, all buffer local
3144 (defvar org-drawer-regexp nil
3145 "Matches first line of a hidden block.")
3146 (make-variable-buffer-local 'org-drawer-regexp)
3147 (defvar org-todo-regexp nil
3148 "Matches any of the TODO state keywords.")
3149 (make-variable-buffer-local 'org-todo-regexp)
3150 (defvar org-not-done-regexp nil
3151 "Matches any of the TODO state keywords except the last one.")
3152 (make-variable-buffer-local 'org-not-done-regexp)
3153 (defvar org-todo-line-regexp nil
3154 "Matches a headline and puts TODO state into group 2 if present.")
3155 (make-variable-buffer-local 'org-todo-line-regexp)
3156 (defvar org-complex-heading-regexp nil
3157 "Matches a headline and puts everything into groups:
3158 group 1: the stars
3159 group 2: The todo keyword, maybe
3160 group 3: Priority cookie
3161 group 4: True headline
3162 group 5: Tags")
3163 (make-variable-buffer-local 'org-complex-heading-regexp)
3164 (defvar org-todo-line-tags-regexp nil
3165 "Matches a headline and puts TODO state into group 2 if present.
3166 Also put tags into group 4 if tags are present.")
3167 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3168 (defvar org-nl-done-regexp nil
3169 "Matches newline followed by a headline with the DONE keyword.")
3170 (make-variable-buffer-local 'org-nl-done-regexp)
3171 (defvar org-looking-at-done-regexp nil
3172 "Matches the DONE keyword a point.")
3173 (make-variable-buffer-local 'org-looking-at-done-regexp)
3174 (defvar org-ds-keyword-length 12
3175 "Maximum length of the Deadline and SCHEDULED keywords.")
3176 (make-variable-buffer-local 'org-ds-keyword-length)
3177 (defvar org-deadline-regexp nil
3178 "Matches the DEADLINE keyword.")
3179 (make-variable-buffer-local 'org-deadline-regexp)
3180 (defvar org-deadline-time-regexp nil
3181 "Matches the DEADLINE keyword together with a time stamp.")
3182 (make-variable-buffer-local 'org-deadline-time-regexp)
3183 (defvar org-deadline-line-regexp nil
3184 "Matches the DEADLINE keyword and the rest of the line.")
3185 (make-variable-buffer-local 'org-deadline-line-regexp)
3186 (defvar org-scheduled-regexp nil
3187 "Matches the SCHEDULED keyword.")
3188 (make-variable-buffer-local 'org-scheduled-regexp)
3189 (defvar org-scheduled-time-regexp nil
3190 "Matches the SCHEDULED keyword together with a time stamp.")
3191 (make-variable-buffer-local 'org-scheduled-time-regexp)
3192 (defvar org-closed-time-regexp nil
3193 "Matches the CLOSED keyword together with a time stamp.")
3194 (make-variable-buffer-local 'org-closed-time-regexp)
3196 (defvar org-keyword-time-regexp nil
3197 "Matches any of the 4 keywords, together with the time stamp.")
3198 (make-variable-buffer-local 'org-keyword-time-regexp)
3199 (defvar org-keyword-time-not-clock-regexp nil
3200 "Matches any of the 3 keywords, together with the time stamp.")
3201 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3202 (defvar org-maybe-keyword-time-regexp nil
3203 "Matches a timestamp, possibly preceeded by a keyword.")
3204 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3205 (defvar org-planning-or-clock-line-re nil
3206 "Matches a line with planning or clock info.")
3207 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3209 (defconst org-plain-time-of-day-regexp
3210 (concat
3211 "\\(\\<[012]?[0-9]"
3212 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3213 "\\(--?"
3214 "\\(\\<[012]?[0-9]"
3215 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3216 "\\)?")
3217 "Regular expression to match a plain time or time range.
3218 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3219 groups carry important information:
3220 0 the full match
3221 1 the first time, range or not
3222 8 the second time, if it is a range.")
3224 (defconst org-plain-time-extension-regexp
3225 (concat
3226 "\\(\\<[012]?[0-9]"
3227 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3228 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3229 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3230 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3231 groups carry important information:
3232 0 the full match
3233 7 hours of duration
3234 9 minutes of duration")
3236 (defconst org-stamp-time-of-day-regexp
3237 (concat
3238 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3239 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3240 "\\(--?"
3241 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3242 "Regular expression to match a timestamp time or time range.
3243 After a match, the following groups carry important information:
3244 0 the full match
3245 1 date plus weekday, for backreferencing to make sure both times on same day
3246 2 the first time, range or not
3247 4 the second time, if it is a range.")
3249 (defconst org-startup-options
3250 '(("fold" org-startup-folded t)
3251 ("overview" org-startup-folded t)
3252 ("nofold" org-startup-folded nil)
3253 ("showall" org-startup-folded nil)
3254 ("content" org-startup-folded content)
3255 ("hidestars" org-hide-leading-stars t)
3256 ("showstars" org-hide-leading-stars nil)
3257 ("odd" org-odd-levels-only t)
3258 ("oddeven" org-odd-levels-only nil)
3259 ("align" org-startup-align-all-tables t)
3260 ("noalign" org-startup-align-all-tables nil)
3261 ("customtime" org-display-custom-times t)
3262 ("logdone" org-log-done time)
3263 ("lognotedone" org-log-done note)
3264 ("nologdone" org-log-done nil)
3265 ("lognoteclock-out" org-log-note-clock-out t)
3266 ("nolognoteclock-out" org-log-note-clock-out nil)
3267 ("logrepeat" org-log-repeat state)
3268 ("lognoterepeat" org-log-repeat note)
3269 ("nologrepeat" org-log-repeat nil)
3270 ("fninline" org-footnote-define-inline t)
3271 ("nofninline" org-footnote-define-inline nil)
3272 ("fnlocal" org-footnote-section nil)
3273 ("fnauto" org-footnote-auto-label t)
3274 ("fnprompt" org-footnote-auto-label nil)
3275 ("fnconfirm" org-footnote-auto-label confirm)
3276 ("fnplain" org-footnote-auto-label plain)
3277 ("constcgs" constants-unit-system cgs)
3278 ("constSI" constants-unit-system SI)
3279 ("noptag" org-tag-persistent-alist nil))
3280 "Variable associated with STARTUP options for org-mode.
3281 Each element is a list of three items: The startup options as written
3282 in the #+STARTUP line, the corresponding variable, and the value to
3283 set this variable to if the option is found. An optional forth element PUSH
3284 means to push this value onto the list in the variable.")
3286 (defun org-set-regexps-and-options ()
3287 "Precompute regular expressions for current buffer."
3288 (when (org-mode-p)
3289 (org-set-local 'org-todo-kwd-alist nil)
3290 (org-set-local 'org-todo-key-alist nil)
3291 (org-set-local 'org-todo-key-trigger nil)
3292 (org-set-local 'org-todo-keywords-1 nil)
3293 (org-set-local 'org-done-keywords nil)
3294 (org-set-local 'org-todo-heads nil)
3295 (org-set-local 'org-todo-sets nil)
3296 (org-set-local 'org-todo-log-states nil)
3297 (org-set-local 'org-file-properties nil)
3298 (org-set-local 'org-file-tags nil)
3299 (let ((re (org-make-options-regexp
3300 '("CATEGORY" "TODO" "COLUMNS"
3301 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3302 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3303 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3304 (splitre "[ \t]+")
3305 kwds kws0 kwsa key log value cat arch tags const links hw dws
3306 tail sep kws1 prio props ftags drawers
3307 ext-setup-or-nil setup-contents (start 0))
3308 (save-excursion
3309 (save-restriction
3310 (widen)
3311 (goto-char (point-min))
3312 (while (or (and ext-setup-or-nil
3313 (string-match re ext-setup-or-nil start)
3314 (setq start (match-end 0)))
3315 (and (setq ext-setup-or-nil nil start 0)
3316 (re-search-forward re nil t)))
3317 (setq key (upcase (match-string 1 ext-setup-or-nil))
3318 value (org-match-string-no-properties 2 ext-setup-or-nil))
3319 (cond
3320 ((equal key "CATEGORY")
3321 (if (string-match "[ \t]+$" value)
3322 (setq value (replace-match "" t t value)))
3323 (setq cat value))
3324 ((member key '("SEQ_TODO" "TODO"))
3325 (push (cons 'sequence (org-split-string value splitre)) kwds))
3326 ((equal key "TYP_TODO")
3327 (push (cons 'type (org-split-string value splitre)) kwds))
3328 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3329 ;; general TODO-like setup
3330 (push (cons (intern (downcase (match-string 1 key)))
3331 (org-split-string value splitre)) kwds))
3332 ((equal key "TAGS")
3333 (setq tags (append tags (if tags '("\\n") nil)
3334 (org-split-string value splitre))))
3335 ((equal key "COLUMNS")
3336 (org-set-local 'org-columns-default-format value))
3337 ((equal key "LINK")
3338 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3339 (push (cons (match-string 1 value)
3340 (org-trim (match-string 2 value)))
3341 links)))
3342 ((equal key "PRIORITIES")
3343 (setq prio (org-split-string value " +")))
3344 ((equal key "PROPERTY")
3345 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3346 (push (cons (match-string 1 value) (match-string 2 value))
3347 props)))
3348 ((equal key "FILETAGS")
3349 (when (string-match "\\S-" value)
3350 (setq ftags
3351 (append
3352 ftags
3353 (apply 'append
3354 (mapcar (lambda (x) (org-split-string x ":"))
3355 (org-split-string value)))))))
3356 ((equal key "DRAWERS")
3357 (setq drawers (org-split-string value splitre)))
3358 ((equal key "CONSTANTS")
3359 (setq const (append const (org-split-string value splitre))))
3360 ((equal key "STARTUP")
3361 (let ((opts (org-split-string value splitre))
3362 l var val)
3363 (while (setq l (pop opts))
3364 (when (setq l (assoc l org-startup-options))
3365 (setq var (nth 1 l) val (nth 2 l))
3366 (if (not (nth 3 l))
3367 (set (make-local-variable var) val)
3368 (if (not (listp (symbol-value var)))
3369 (set (make-local-variable var) nil))
3370 (set (make-local-variable var) (symbol-value var))
3371 (add-to-list var val))))))
3372 ((equal key "ARCHIVE")
3373 (string-match " *$" value)
3374 (setq arch (replace-match "" t t value))
3375 (remove-text-properties 0 (length arch)
3376 '(face t fontified t) arch))
3377 ((equal key "SETUPFILE")
3378 (setq setup-contents (org-file-contents
3379 (expand-file-name
3380 (org-remove-double-quotes value))
3381 'noerror))
3382 (if (not ext-setup-or-nil)
3383 (setq ext-setup-or-nil setup-contents start 0)
3384 (setq ext-setup-or-nil
3385 (concat (substring ext-setup-or-nil 0 start)
3386 "\n" setup-contents "\n"
3387 (substring ext-setup-or-nil start)))))
3388 ))))
3389 (when cat
3390 (org-set-local 'org-category (intern cat))
3391 (push (cons "CATEGORY" cat) props))
3392 (when prio
3393 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3394 (setq prio (mapcar 'string-to-char prio))
3395 (org-set-local 'org-highest-priority (nth 0 prio))
3396 (org-set-local 'org-lowest-priority (nth 1 prio))
3397 (org-set-local 'org-default-priority (nth 2 prio)))
3398 (and props (org-set-local 'org-file-properties (nreverse props)))
3399 (and ftags (org-set-local 'org-file-tags ftags))
3400 (and drawers (org-set-local 'org-drawers drawers))
3401 (and arch (org-set-local 'org-archive-location arch))
3402 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3403 ;; Process the TODO keywords
3404 (unless kwds
3405 ;; Use the global values as if they had been given locally.
3406 (setq kwds (default-value 'org-todo-keywords))
3407 (if (stringp (car kwds))
3408 (setq kwds (list (cons org-todo-interpretation
3409 (default-value 'org-todo-keywords)))))
3410 (setq kwds (reverse kwds)))
3411 (setq kwds (nreverse kwds))
3412 (let (inter kws kw)
3413 (while (setq kws (pop kwds))
3414 (let ((kws (or
3415 (run-hook-with-args-until-success
3416 'org-todo-setup-filter-hook kws)
3417 kws)))
3418 (setq inter (pop kws) sep (member "|" kws)
3419 kws0 (delete "|" (copy-sequence kws))
3420 kwsa nil
3421 kws1 (mapcar
3422 (lambda (x)
3423 ;; 1 2
3424 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3425 (progn
3426 (setq kw (match-string 1 x)
3427 key (and (match-end 2) (match-string 2 x))
3428 log (org-extract-log-state-settings x))
3429 (push (cons kw (and key (string-to-char key))) kwsa)
3430 (and log (push log org-todo-log-states))
3432 (error "Invalid TODO keyword %s" x)))
3433 kws0)
3434 kwsa (if kwsa (append '((:startgroup))
3435 (nreverse kwsa)
3436 '((:endgroup))))
3437 hw (car kws1)
3438 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3439 tail (list inter hw (car dws) (org-last dws))))
3440 (add-to-list 'org-todo-heads hw 'append)
3441 (push kws1 org-todo-sets)
3442 (setq org-done-keywords (append org-done-keywords dws nil))
3443 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3444 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3445 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3446 (setq org-todo-sets (nreverse org-todo-sets)
3447 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3448 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3449 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3450 ;; Process the constants
3451 (when const
3452 (let (e cst)
3453 (while (setq e (pop const))
3454 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3455 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3456 (setq org-table-formula-constants-local cst)))
3458 ;; Process the tags.
3459 (when tags
3460 (let (e tgs)
3461 (while (setq e (pop tags))
3462 (cond
3463 ((equal e "{") (push '(:startgroup) tgs))
3464 ((equal e "}") (push '(:endgroup) tgs))
3465 ((equal e "\\n") (push '(:newline) tgs))
3466 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3467 (push (cons (match-string 1 e)
3468 (string-to-char (match-string 2 e)))
3469 tgs))
3470 (t (push (list e) tgs))))
3471 (org-set-local 'org-tag-alist nil)
3472 (while (setq e (pop tgs))
3473 (or (and (stringp (car e))
3474 (assoc (car e) org-tag-alist))
3475 (push e org-tag-alist)))))
3477 ;; Compute the regular expressions and other local variables
3478 (if (not org-done-keywords)
3479 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3480 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3481 (length org-scheduled-string)
3482 (length org-clock-string)
3483 (length org-closed-string)))
3484 org-drawer-regexp
3485 (concat "^[ \t]*:\\("
3486 (mapconcat 'regexp-quote org-drawers "\\|")
3487 "\\):[ \t]*$")
3488 org-not-done-keywords
3489 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3490 org-todo-regexp
3491 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3492 "\\|") "\\)\\>")
3493 org-not-done-regexp
3494 (concat "\\<\\("
3495 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3496 "\\)\\>")
3497 org-todo-line-regexp
3498 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3499 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3500 "\\)\\>\\)?[ \t]*\\(.*\\)")
3501 org-complex-heading-regexp
3502 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3503 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3504 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3505 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3506 org-nl-done-regexp
3507 (concat "\n\\*+[ \t]+"
3508 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3509 "\\)" "\\>")
3510 org-todo-line-tags-regexp
3511 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3512 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3513 (org-re
3514 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3515 org-looking-at-done-regexp
3516 (concat "^" "\\(?:"
3517 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3518 "\\>")
3519 org-deadline-regexp (concat "\\<" org-deadline-string)
3520 org-deadline-time-regexp
3521 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3522 org-deadline-line-regexp
3523 (concat "\\<\\(" org-deadline-string "\\).*")
3524 org-scheduled-regexp
3525 (concat "\\<" org-scheduled-string)
3526 org-scheduled-time-regexp
3527 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3528 org-closed-time-regexp
3529 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3530 org-keyword-time-regexp
3531 (concat "\\<\\(" org-scheduled-string
3532 "\\|" org-deadline-string
3533 "\\|" org-closed-string
3534 "\\|" org-clock-string "\\)"
3535 " *[[<]\\([^]>]+\\)[]>]")
3536 org-keyword-time-not-clock-regexp
3537 (concat "\\<\\(" org-scheduled-string
3538 "\\|" org-deadline-string
3539 "\\|" org-closed-string
3540 "\\)"
3541 " *[[<]\\([^]>]+\\)[]>]")
3542 org-maybe-keyword-time-regexp
3543 (concat "\\(\\<\\(" org-scheduled-string
3544 "\\|" org-deadline-string
3545 "\\|" org-closed-string
3546 "\\|" org-clock-string "\\)\\)?"
3547 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3548 org-planning-or-clock-line-re
3549 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3550 "\\|" org-deadline-string
3551 "\\|" org-closed-string "\\|" org-clock-string
3552 "\\)\\>\\)")
3554 (org-compute-latex-and-specials-regexp)
3555 (org-set-font-lock-defaults))))
3557 (defun org-file-contents (file &optional noerror)
3558 "Return the contents of FILE, as a string."
3559 (if (or (not file)
3560 (not (file-readable-p file)))
3561 (if noerror
3562 (progn
3563 (message "Cannot read file %s" file)
3564 (ding) (sit-for 2)
3566 (error "Cannot read file %s" file))
3567 (with-temp-buffer
3568 (insert-file-contents file)
3569 (buffer-string))))
3571 (defun org-extract-log-state-settings (x)
3572 "Extract the log state setting from a TODO keyword string.
3573 This will extract info from a string like \"WAIT(w@/!)\"."
3574 (let (kw key log1 log2)
3575 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3576 (setq kw (match-string 1 x)
3577 key (and (match-end 2) (match-string 2 x))
3578 log1 (and (match-end 3) (match-string 3 x))
3579 log2 (and (match-end 4) (match-string 4 x)))
3580 (and (or log1 log2)
3581 (list kw
3582 (and log1 (if (equal log1 "!") 'time 'note))
3583 (and log2 (if (equal log2 "!") 'time 'note)))))))
3585 (defun org-remove-keyword-keys (list)
3586 "Remove a pair of parenthesis at the end of each string in LIST."
3587 (mapcar (lambda (x)
3588 (if (string-match "(.*)$" x)
3589 (substring x 0 (match-beginning 0))
3591 list))
3593 ;; FIXME: this could be done much better, using second characters etc.
3594 (defun org-assign-fast-keys (alist)
3595 "Assign fast keys to a keyword-key alist.
3596 Respect keys that are already there."
3597 (let (new e k c c1 c2 (char ?a))
3598 (while (setq e (pop alist))
3599 (cond
3600 ((equal e '(:startgroup)) (push e new))
3601 ((equal e '(:endgroup)) (push e new))
3602 ((equal e '(:newline)) (push e new))
3604 (setq k (car e) c2 nil)
3605 (if (cdr e)
3606 (setq c (cdr e))
3607 ;; automatically assign a character.
3608 (setq c1 (string-to-char
3609 (downcase (substring
3610 k (if (= (string-to-char k) ?@) 1 0)))))
3611 (if (or (rassoc c1 new) (rassoc c1 alist))
3612 (while (or (rassoc char new) (rassoc char alist))
3613 (setq char (1+ char)))
3614 (setq c2 c1))
3615 (setq c (or c2 char)))
3616 (push (cons k c) new))))
3617 (nreverse new)))
3619 ;;; Some variables used in various places
3621 (defvar org-window-configuration nil
3622 "Used in various places to store a window configuration.")
3623 (defvar org-finish-function nil
3624 "Function to be called when `C-c C-c' is used.
3625 This is for getting out of special buffers like remember.")
3628 ;; FIXME: Occasionally check by commenting these, to make sure
3629 ;; no other functions uses these, forgetting to let-bind them.
3630 (defvar entry)
3631 (defvar state)
3632 (defvar last-state)
3633 (defvar date)
3634 (defvar description)
3636 ;; Defined somewhere in this file, but used before definition.
3637 (defvar org-html-entities)
3638 (defvar org-struct-menu)
3639 (defvar org-org-menu)
3640 (defvar org-tbl-menu)
3641 (defvar org-agenda-keymap)
3643 ;;;; Define the Org-mode
3645 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3646 (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."))
3649 ;; We use a before-change function to check if a table might need
3650 ;; an update.
3651 (defvar org-table-may-need-update t
3652 "Indicates that a table might need an update.
3653 This variable is set by `org-before-change-function'.
3654 `org-table-align' sets it back to nil.")
3655 (defun org-before-change-function (beg end)
3656 "Every change indicates that a table might need an update."
3657 (setq org-table-may-need-update t))
3658 (defvar org-mode-map)
3659 (defvar org-mode-hook nil
3660 "Mode hook for Org-mode, run after the mode was turned on.")
3661 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3662 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3663 (defvar org-table-buffer-is-an nil)
3664 (defconst org-outline-regexp "\\*+ ")
3666 ;;;###autoload
3667 (define-derived-mode org-mode outline-mode "Org"
3668 "Outline-based notes management and organizer, alias
3669 \"Carsten's outline-mode for keeping track of everything.\"
3671 Org-mode develops organizational tasks around a NOTES file which
3672 contains information about projects as plain text. Org-mode is
3673 implemented on top of outline-mode, which is ideal to keep the content
3674 of large files well structured. It supports ToDo items, deadlines and
3675 time stamps, which magically appear in the diary listing of the Emacs
3676 calendar. Tables are easily created with a built-in table editor.
3677 Plain text URL-like links connect to websites, emails (VM), Usenet
3678 messages (Gnus), BBDB entries, and any files related to the project.
3679 For printing and sharing of notes, an Org-mode file (or a part of it)
3680 can be exported as a structured ASCII or HTML file.
3682 The following commands are available:
3684 \\{org-mode-map}"
3686 ;; Get rid of Outline menus, they are not needed
3687 ;; Need to do this here because define-derived-mode sets up
3688 ;; the keymap so late. Still, it is a waste to call this each time
3689 ;; we switch another buffer into org-mode.
3690 (if (featurep 'xemacs)
3691 (when (boundp 'outline-mode-menu-heading)
3692 ;; Assume this is Greg's port, it used easymenu
3693 (easy-menu-remove outline-mode-menu-heading)
3694 (easy-menu-remove outline-mode-menu-show)
3695 (easy-menu-remove outline-mode-menu-hide))
3696 (define-key org-mode-map [menu-bar headings] 'undefined)
3697 (define-key org-mode-map [menu-bar hide] 'undefined)
3698 (define-key org-mode-map [menu-bar show] 'undefined))
3700 (org-load-modules-maybe)
3701 (easy-menu-add org-org-menu)
3702 (easy-menu-add org-tbl-menu)
3703 (org-install-agenda-files-menu)
3704 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3705 (org-add-to-invisibility-spec '(org-cwidth))
3706 (when (featurep 'xemacs)
3707 (org-set-local 'line-move-ignore-invisible t))
3708 (org-set-local 'outline-regexp org-outline-regexp)
3709 (org-set-local 'outline-level 'org-outline-level)
3710 (when (and org-ellipsis
3711 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3712 (fboundp 'make-glyph-code))
3713 (unless org-display-table
3714 (setq org-display-table (make-display-table)))
3715 (set-display-table-slot
3716 org-display-table 4
3717 (vconcat (mapcar
3718 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3719 org-ellipsis)))
3720 (if (stringp org-ellipsis) org-ellipsis "..."))))
3721 (setq buffer-display-table org-display-table))
3722 (org-set-regexps-and-options)
3723 (when (and org-tag-faces (not org-tags-special-faces-re))
3724 ;; tag faces set outside customize.... force initialization.
3725 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3726 ;; Calc embedded
3727 (org-set-local 'calc-embedded-open-mode "# ")
3728 (modify-syntax-entry ?# "<")
3729 (modify-syntax-entry ?@ "w")
3730 (if org-startup-truncated (setq truncate-lines t))
3731 (org-set-local 'font-lock-unfontify-region-function
3732 'org-unfontify-region)
3733 ;; Activate before-change-function
3734 (org-set-local 'org-table-may-need-update t)
3735 (org-add-hook 'before-change-functions 'org-before-change-function nil
3736 'local)
3737 ;; Check for running clock before killing a buffer
3738 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3739 ;; Paragraphs and auto-filling
3740 (org-set-autofill-regexps)
3741 (setq indent-line-function 'org-indent-line-function)
3742 (org-update-radio-target-regexp)
3743 ;; Make sure dependence stuff works reliably, even for users who set it
3744 ;; too late :-(
3745 (if org-enforce-todo-dependencies
3746 (add-hook 'org-blocker-hook
3747 'org-block-todo-from-children-or-siblings)
3748 (remove-hook 'org-blocker-hook
3749 'org-block-todo-from-children-or-siblings))
3750 (if org-enforce-todo-checkbox-dependencies
3751 (add-hook 'org-blocker-hook
3752 'org-block-todo-from-checkboxes)
3753 (remove-hook 'org-blocker-hook
3754 'org-block-todo-from-checkboxes))
3756 ;; Comment characters
3757 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3758 (org-set-local 'comment-padding " ")
3760 ;; Align options lines
3761 (org-set-local
3762 'align-mode-rules-list
3763 '((org-in-buffer-settings
3764 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3765 (modes . '(org-mode)))))
3767 ;; Imenu
3768 (org-set-local 'imenu-create-index-function
3769 'org-imenu-get-tree)
3771 ;; Make isearch reveal context
3772 (if (or (featurep 'xemacs)
3773 (not (boundp 'outline-isearch-open-invisible-function)))
3774 ;; Emacs 21 and XEmacs make use of the hook
3775 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3776 ;; Emacs 22 deals with this through a special variable
3777 (org-set-local 'outline-isearch-open-invisible-function
3778 (lambda (&rest ignore) (org-show-context 'isearch))))
3780 ;; If empty file that did not turn on org-mode automatically, make it to.
3781 (if (and org-insert-mode-line-in-empty-file
3782 (interactive-p)
3783 (= (point-min) (point-max)))
3784 (insert "# -*- mode: org -*-\n\n"))
3786 (unless org-inhibit-startup
3787 (when org-startup-align-all-tables
3788 (let ((bmp (buffer-modified-p)))
3789 (org-table-map-tables 'org-table-align)
3790 (set-buffer-modified-p bmp)))
3791 (org-set-startup-visibility)))
3793 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3795 (defun org-current-time ()
3796 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3797 (if (> (car org-time-stamp-rounding-minutes) 1)
3798 (let ((r (car org-time-stamp-rounding-minutes))
3799 (time (decode-time)))
3800 (apply 'encode-time
3801 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3802 (nthcdr 2 time))))
3803 (current-time)))
3805 ;;;; Font-Lock stuff, including the activators
3807 (defvar org-mouse-map (make-sparse-keymap))
3808 (org-defkey org-mouse-map
3809 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3810 (org-defkey org-mouse-map
3811 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3812 (when org-mouse-1-follows-link
3813 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3814 (when org-tab-follows-link
3815 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3816 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3818 (require 'font-lock)
3820 (defconst org-non-link-chars "]\t\n\r<>")
3821 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3822 "shell" "elisp"))
3823 (defvar org-link-types-re nil
3824 "Matches a link that has a url-like prefix like \"http:\"")
3825 (defvar org-link-re-with-space nil
3826 "Matches a link with spaces, optional angular brackets around it.")
3827 (defvar org-link-re-with-space2 nil
3828 "Matches a link with spaces, optional angular brackets around it.")
3829 (defvar org-link-re-with-space3 nil
3830 "Matches a link with spaces, only for internal part in bracket links.")
3831 (defvar org-angle-link-re nil
3832 "Matches link with angular brackets, spaces are allowed.")
3833 (defvar org-plain-link-re nil
3834 "Matches plain link, without spaces.")
3835 (defvar org-bracket-link-regexp nil
3836 "Matches a link in double brackets.")
3837 (defvar org-bracket-link-analytic-regexp nil
3838 "Regular expression used to analyze links.
3839 Here is what the match groups contain after a match:
3840 1: http:
3841 2: http
3842 3: path
3843 4: [desc]
3844 5: desc")
3845 (defvar org-bracket-link-analytic-regexp++ nil
3846 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3847 (defvar org-any-link-re nil
3848 "Regular expression matching any link.")
3850 (defun org-make-link-regexps ()
3851 "Update the link regular expressions.
3852 This should be called after the variable `org-link-types' has changed."
3853 (setq org-link-types-re
3854 (concat
3855 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3856 org-link-re-with-space
3857 (concat
3858 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3859 "\\([^" org-non-link-chars " ]"
3860 "[^" org-non-link-chars "]*"
3861 "[^" org-non-link-chars " ]\\)>?")
3862 org-link-re-with-space2
3863 (concat
3864 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3865 "\\([^" org-non-link-chars " ]"
3866 "[^\t\n\r]*"
3867 "[^" org-non-link-chars " ]\\)>?")
3868 org-link-re-with-space3
3869 (concat
3870 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3871 "\\([^" org-non-link-chars " ]"
3872 "[^\t\n\r]*\\)")
3873 org-angle-link-re
3874 (concat
3875 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3876 "\\([^" org-non-link-chars " ]"
3877 "[^" org-non-link-chars "]*"
3878 "\\)>")
3879 org-plain-link-re
3880 (concat
3881 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3882 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3883 org-bracket-link-regexp
3884 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3885 org-bracket-link-analytic-regexp
3886 (concat
3887 "\\[\\["
3888 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3889 "\\([^]]+\\)"
3890 "\\]"
3891 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3892 "\\]")
3893 org-bracket-link-analytic-regexp++
3894 (concat
3895 "\\[\\["
3896 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3897 "\\([^]]+\\)"
3898 "\\]"
3899 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3900 "\\]")
3901 org-any-link-re
3902 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3903 org-angle-link-re "\\)\\|\\("
3904 org-plain-link-re "\\)")))
3906 (org-make-link-regexps)
3908 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3909 "Regular expression for fast time stamp matching.")
3910 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3911 "Regular expression for fast time stamp matching.")
3912 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3913 "Regular expression matching time strings for analysis.
3914 This one does not require the space after the date, so it can be used
3915 on a string that terminates immediately after the date.")
3916 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3917 "Regular expression matching time strings for analysis.")
3918 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3919 "Regular expression matching time stamps, with groups.")
3920 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3921 "Regular expression matching time stamps (also [..]), with groups.")
3922 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3923 "Regular expression matching a time stamp range.")
3924 (defconst org-tr-regexp-both
3925 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3926 "Regular expression matching a time stamp range.")
3927 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3928 org-ts-regexp "\\)?")
3929 "Regular expression matching a time stamp or time stamp range.")
3930 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3931 org-ts-regexp-both "\\)?")
3932 "Regular expression matching a time stamp or time stamp range.
3933 The time stamps may be either active or inactive.")
3935 (defvar org-emph-face nil)
3937 (defun org-do-emphasis-faces (limit)
3938 "Run through the buffer and add overlays to links."
3939 (let (rtn)
3940 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3941 (if (not (= (char-after (match-beginning 3))
3942 (char-after (match-beginning 4))))
3943 (progn
3944 (setq rtn t)
3945 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3946 'face
3947 (nth 1 (assoc (match-string 3)
3948 org-emphasis-alist)))
3949 (add-text-properties (match-beginning 2) (match-end 2)
3950 '(font-lock-multiline t))
3951 (when org-hide-emphasis-markers
3952 (add-text-properties (match-end 4) (match-beginning 5)
3953 '(invisible org-link))
3954 (add-text-properties (match-beginning 3) (match-end 3)
3955 '(invisible org-link)))))
3956 (backward-char 1))
3957 rtn))
3959 (defun org-emphasize (&optional char)
3960 "Insert or change an emphasis, i.e. a font like bold or italic.
3961 If there is an active region, change that region to a new emphasis.
3962 If there is no region, just insert the marker characters and position
3963 the cursor between them.
3964 CHAR should be either the marker character, or the first character of the
3965 HTML tag associated with that emphasis. If CHAR is a space, the means
3966 to remove the emphasis of the selected region.
3967 If char is not given (for example in an interactive call) it
3968 will be prompted for."
3969 (interactive)
3970 (let ((eal org-emphasis-alist) e det
3971 (erc org-emphasis-regexp-components)
3972 (prompt "")
3973 (string "") beg end move tag c s)
3974 (if (org-region-active-p)
3975 (setq beg (region-beginning) end (region-end)
3976 string (buffer-substring beg end))
3977 (setq move t))
3979 (while (setq e (pop eal))
3980 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3981 c (aref tag 0))
3982 (push (cons c (string-to-char (car e))) det)
3983 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3984 (substring tag 1)))))
3985 (setq det (nreverse det))
3986 (unless char
3987 (message "%s" (concat "Emphasis marker or tag:" prompt))
3988 (setq char (read-char-exclusive)))
3989 (setq char (or (cdr (assoc char det)) char))
3990 (if (equal char ?\ )
3991 (setq s "" move nil)
3992 (unless (assoc (char-to-string char) org-emphasis-alist)
3993 (error "No such emphasis marker: \"%c\"" char))
3994 (setq s (char-to-string char)))
3995 (while (and (> (length string) 1)
3996 (equal (substring string 0 1) (substring string -1))
3997 (assoc (substring string 0 1) org-emphasis-alist))
3998 (setq string (substring string 1 -1)))
3999 (setq string (concat s string s))
4000 (if beg (delete-region beg end))
4001 (unless (or (bolp)
4002 (string-match (concat "[" (nth 0 erc) "\n]")
4003 (char-to-string (char-before (point)))))
4004 (insert " "))
4005 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4006 (char-to-string (char-after (point))))
4007 (insert " ") (backward-char 1))
4008 (insert string)
4009 (and move (backward-char 1))))
4011 (defconst org-nonsticky-props
4012 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4015 (defun org-activate-plain-links (limit)
4016 "Run through the buffer and add overlays to links."
4017 (catch 'exit
4018 (let (f)
4019 (while (re-search-forward org-plain-link-re limit t)
4020 (setq f (get-text-property (match-beginning 0) 'face))
4021 (if (or (eq f 'org-tag)
4022 (and (listp f) (memq 'org-tag f)))
4024 (add-text-properties (match-beginning 0) (match-end 0)
4025 (list 'mouse-face 'highlight
4026 'rear-nonsticky org-nonsticky-props
4027 'keymap org-mouse-map
4029 (throw 'exit t))))))
4031 (defun org-activate-code (limit)
4032 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4033 (progn
4034 (remove-text-properties (match-beginning 0) (match-end 0)
4035 '(display t invisible t intangible t))
4036 t)))
4038 (defun org-activate-angle-links (limit)
4039 "Run through the buffer and add overlays to links."
4040 (if (re-search-forward org-angle-link-re limit t)
4041 (progn
4042 (add-text-properties (match-beginning 0) (match-end 0)
4043 (list 'mouse-face 'highlight
4044 'rear-nonsticky org-nonsticky-props
4045 'keymap org-mouse-map
4047 t)))
4049 (defun org-activate-footnote-links (limit)
4050 "Run through the buffer and add overlays to links."
4051 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4052 limit t)
4053 (progn
4054 (add-text-properties (match-beginning 2) (match-end 2)
4055 (list 'mouse-face 'highlight
4056 'rear-nonsticky org-nonsticky-props
4057 'keymap org-mouse-map
4058 'help-echo
4059 (if (= (point-at-bol) (match-beginning 2))
4060 "Footnote definition"
4061 "Footnote reference")
4063 t)))
4065 (defun org-activate-bracket-links (limit)
4066 "Run through the buffer and add overlays to bracketed links."
4067 (if (re-search-forward org-bracket-link-regexp limit t)
4068 (let* ((help (concat "LINK: "
4069 (org-match-string-no-properties 1)))
4070 ;; FIXME: above we should remove the escapes.
4071 ;; but that requires another match, protecting match data,
4072 ;; a lot of overhead for font-lock.
4073 (ip (org-maybe-intangible
4074 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4075 'keymap org-mouse-map 'mouse-face 'highlight
4076 'font-lock-multiline t 'help-echo help)))
4077 (vp (list 'rear-nonsticky org-nonsticky-props
4078 'keymap org-mouse-map 'mouse-face 'highlight
4079 ' font-lock-multiline t 'help-echo help)))
4080 ;; We need to remove the invisible property here. Table narrowing
4081 ;; may have made some of this invisible.
4082 (remove-text-properties (match-beginning 0) (match-end 0)
4083 '(invisible nil))
4084 (if (match-end 3)
4085 (progn
4086 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4087 (add-text-properties (match-beginning 3) (match-end 3) vp)
4088 (add-text-properties (match-end 3) (match-end 0) ip))
4089 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4090 (add-text-properties (match-beginning 1) (match-end 1) vp)
4091 (add-text-properties (match-end 1) (match-end 0) ip))
4092 t)))
4094 (defun org-activate-dates (limit)
4095 "Run through the buffer and add overlays to dates."
4096 (if (re-search-forward org-tsr-regexp-both limit t)
4097 (progn
4098 (add-text-properties (match-beginning 0) (match-end 0)
4099 (list 'mouse-face 'highlight
4100 'rear-nonsticky org-nonsticky-props
4101 'keymap org-mouse-map))
4102 (when org-display-custom-times
4103 (if (match-end 3)
4104 (org-display-custom-time (match-beginning 3) (match-end 3)))
4105 (org-display-custom-time (match-beginning 1) (match-end 1)))
4106 t)))
4108 (defvar org-target-link-regexp nil
4109 "Regular expression matching radio targets in plain text.")
4110 (make-variable-buffer-local 'org-target-link-regexp)
4111 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4112 "Regular expression matching a link target.")
4113 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4114 "Regular expression matching a radio target.")
4115 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4116 "Regular expression matching any target.")
4118 (defun org-activate-target-links (limit)
4119 "Run through the buffer and add overlays to target matches."
4120 (when org-target-link-regexp
4121 (let ((case-fold-search t))
4122 (if (re-search-forward org-target-link-regexp limit t)
4123 (progn
4124 (add-text-properties (match-beginning 0) (match-end 0)
4125 (list 'mouse-face 'highlight
4126 'rear-nonsticky org-nonsticky-props
4127 'keymap org-mouse-map
4128 'help-echo "Radio target link"
4129 'org-linked-text t))
4130 t)))))
4132 (defun org-update-radio-target-regexp ()
4133 "Find all radio targets in this file and update the regular expression."
4134 (interactive)
4135 (when (memq 'radio org-activate-links)
4136 (setq org-target-link-regexp
4137 (org-make-target-link-regexp (org-all-targets 'radio)))
4138 (org-restart-font-lock)))
4140 (defun org-hide-wide-columns (limit)
4141 (let (s e)
4142 (setq s (text-property-any (point) (or limit (point-max))
4143 'org-cwidth t))
4144 (when s
4145 (setq e (next-single-property-change s 'org-cwidth))
4146 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4147 (goto-char e)
4148 t)))
4150 (defvar org-latex-and-specials-regexp nil
4151 "Regular expression for highlighting export special stuff.")
4152 (defvar org-match-substring-regexp)
4153 (defvar org-match-substring-with-braces-regexp)
4154 (defvar org-export-html-special-string-regexps)
4156 (defun org-compute-latex-and-specials-regexp ()
4157 "Compute regular expression for stuff treated specially by exporters."
4158 (if (not org-highlight-latex-fragments-and-specials)
4159 (org-set-local 'org-latex-and-specials-regexp nil)
4160 (require 'org-exp)
4161 (let*
4162 ((matchers (plist-get org-format-latex-options :matchers))
4163 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4164 org-latex-regexps)))
4165 (options (org-combine-plists (org-default-export-plist)
4166 (org-infile-export-plist)))
4167 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4168 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4169 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4170 (org-export-html-expand (plist-get options :expand-quoted-html))
4171 (org-export-with-special-strings (plist-get options :special-strings))
4172 (re-sub
4173 (cond
4174 ((equal org-export-with-sub-superscripts '{})
4175 (list org-match-substring-with-braces-regexp))
4176 (org-export-with-sub-superscripts
4177 (list org-match-substring-regexp))
4178 (t nil)))
4179 (re-latex
4180 (if org-export-with-LaTeX-fragments
4181 (mapcar (lambda (x) (nth 1 x)) latexs)))
4182 (re-macros
4183 (if org-export-with-TeX-macros
4184 (list (concat "\\\\"
4185 (regexp-opt
4186 (append (mapcar 'car org-html-entities)
4187 (if (boundp 'org-latex-entities)
4188 org-latex-entities nil))
4189 'words))) ; FIXME
4191 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4192 (re-special (if org-export-with-special-strings
4193 (mapcar (lambda (x) (car x))
4194 org-export-html-special-string-regexps)))
4195 (re-rest
4196 (delq nil
4197 (list
4198 (if org-export-html-expand "@<[^>\n]+>")
4199 ))))
4200 (org-set-local
4201 'org-latex-and-specials-regexp
4202 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4203 re-rest) "\\|")))))
4205 (defun org-do-latex-and-special-faces (limit)
4206 "Run through the buffer and add overlays to links."
4207 (when org-latex-and-specials-regexp
4208 (let (rtn d)
4209 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4210 limit t))
4211 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4212 'face))
4213 '(org-code org-verbatim underline)))
4214 (progn
4215 (setq rtn t
4216 d (cond ((member (char-after (1+ (match-beginning 0)))
4217 '(?_ ?^)) 1)
4218 (t 0)))
4219 (font-lock-prepend-text-property
4220 (+ d (match-beginning 0)) (match-end 0)
4221 'face 'org-latex-and-export-specials)
4222 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4223 '(font-lock-multiline t)))))
4224 rtn)))
4226 (defun org-restart-font-lock ()
4227 "Restart font-lock-mode, to force refontification."
4228 (when (and (boundp 'font-lock-mode) font-lock-mode)
4229 (font-lock-mode -1)
4230 (font-lock-mode 1)))
4232 (defun org-all-targets (&optional radio)
4233 "Return a list of all targets in this file.
4234 With optional argument RADIO, only find radio targets."
4235 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4236 rtn)
4237 (save-excursion
4238 (goto-char (point-min))
4239 (while (re-search-forward re nil t)
4240 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4241 rtn)))
4243 (defun org-make-target-link-regexp (targets)
4244 "Make regular expression matching all strings in TARGETS.
4245 The regular expression finds the targets also if there is a line break
4246 between words."
4247 (and targets
4248 (concat
4249 "\\<\\("
4250 (mapconcat
4251 (lambda (x)
4252 (while (string-match " +" x)
4253 (setq x (replace-match "\\s-+" t t x)))
4255 targets
4256 "\\|")
4257 "\\)\\>")))
4259 (defun org-activate-tags (limit)
4260 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4261 (progn
4262 (add-text-properties (match-beginning 1) (match-end 1)
4263 (list 'mouse-face 'highlight
4264 'rear-nonsticky org-nonsticky-props
4265 'keymap org-mouse-map))
4266 t)))
4268 (defun org-outline-level ()
4269 (save-excursion
4270 (looking-at outline-regexp)
4271 (if (match-beginning 1)
4272 (+ (org-get-string-indentation (match-string 1)) 1000)
4273 (1- (- (match-end 0) (match-beginning 0))))))
4275 (defvar org-font-lock-keywords nil)
4277 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4278 "Regular expression matching a property line.")
4280 (defvar org-font-lock-hook nil
4281 "Functions to be called for special font lock stuff.")
4283 (defun org-font-lock-hook (limit)
4284 (run-hook-with-args 'org-font-lock-hook limit))
4286 (defun org-set-font-lock-defaults ()
4287 (let* ((em org-fontify-emphasized-text)
4288 (lk org-activate-links)
4289 (org-font-lock-extra-keywords
4290 (list
4291 ;; Call the hook
4292 '(org-font-lock-hook)
4293 ;; Headlines
4294 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4295 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4296 ;; Table lines
4297 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4298 (1 'org-table t))
4299 ;; Table internals
4300 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4301 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4302 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4303 ;; Drawers
4304 (list org-drawer-regexp '(0 'org-special-keyword t))
4305 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4306 ;; Properties
4307 (list org-property-re
4308 '(1 'org-special-keyword t)
4309 '(3 'org-property-value t))
4310 (if org-format-transports-properties-p
4311 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4312 ;; Links
4313 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4314 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4315 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4316 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4317 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4318 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4319 (if (memq 'footnote lk) '(org-activate-footnote-links
4320 (2 'org-footnote t)))
4321 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4322 '(org-hide-wide-columns (0 nil append))
4323 ;; TODO lines
4324 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4325 '(1 (org-get-todo-face 1) t))
4326 ;; DONE
4327 (if org-fontify-done-headline
4328 (list (concat "^[*]+ +\\<\\("
4329 (mapconcat 'regexp-quote org-done-keywords "\\|")
4330 "\\)\\(.*\\)")
4331 '(2 'org-headline-done t))
4332 nil)
4333 ;; Priorities
4334 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4335 ;; Tags
4336 '(org-font-lock-add-tag-faces)
4337 ;; Special keywords
4338 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4339 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4340 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4341 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4342 ;; Emphasis
4343 (if em
4344 (if (featurep 'xemacs)
4345 '(org-do-emphasis-faces (0 nil append))
4346 '(org-do-emphasis-faces)))
4347 ;; Checkboxes
4348 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4349 2 'bold prepend)
4350 (if org-provide-checkbox-statistics
4351 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4352 (0 (org-get-checkbox-statistics-face) t)))
4353 ;; Description list items
4354 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4355 2 'bold prepend)
4356 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4357 '(1 'org-archived prepend))
4358 ;; Specials
4359 '(org-do-latex-and-special-faces)
4360 ;; Code
4361 '(org-activate-code (1 'org-code t))
4362 ;; COMMENT
4363 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4364 "\\|" org-quote-string "\\)\\>")
4365 '(1 'org-special-keyword t))
4366 '("^#.*" (0 'font-lock-comment-face t))
4368 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4369 ;; Now set the full font-lock-keywords
4370 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4371 (org-set-local 'font-lock-defaults
4372 '(org-font-lock-keywords t nil nil backward-paragraph))
4373 (kill-local-variable 'font-lock-keywords) nil))
4375 (defvar org-m nil)
4376 (defvar org-l nil)
4377 (defvar org-f nil)
4378 (defun org-get-level-face (n)
4379 "Get the right face for match N in font-lock matching of headlines."
4380 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4381 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4382 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4383 (cond
4384 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4385 ((eq n 2) org-f)
4386 (t (if org-level-color-stars-only nil org-f))))
4388 (defun org-get-todo-face (kwd)
4389 "Get the right face for a TODO keyword KWD.
4390 If KWD is a number, get the corresponding match group."
4391 (if (numberp kwd) (setq kwd (match-string kwd)))
4392 (or (cdr (assoc kwd org-todo-keyword-faces))
4393 (and (member kwd org-done-keywords) 'org-done)
4394 'org-todo))
4396 (defun org-font-lock-add-tag-faces (limit)
4397 "Add the special tag faces."
4398 (when (and org-tag-faces org-tags-special-faces-re)
4399 (while (re-search-forward org-tags-special-faces-re limit t)
4400 (add-text-properties (match-beginning 1) (match-end 1)
4401 (list 'face (org-get-tag-face 1)
4402 'font-lock-fontified t))
4403 (backward-char 1))))
4405 (defun org-get-tag-face (kwd)
4406 "Get the right face for a TODO keyword KWD.
4407 If KWD is a number, get the corresponding match group."
4408 (if (numberp kwd) (setq kwd (match-string kwd)))
4409 (or (cdr (assoc kwd org-tag-faces))
4410 'org-tag))
4412 (defun org-unfontify-region (beg end &optional maybe_loudly)
4413 "Remove fontification and activation overlays from links."
4414 (font-lock-default-unfontify-region beg end)
4415 (let* ((buffer-undo-list t)
4416 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4417 (inhibit-modification-hooks t)
4418 deactivate-mark buffer-file-name buffer-file-truename)
4419 (remove-text-properties beg end
4420 '(mouse-face t keymap t org-linked-text t
4421 invisible t intangible t))))
4423 ;;;; Visibility cycling, including org-goto and indirect buffer
4425 ;;; Cycling
4427 (defvar org-cycle-global-status nil)
4428 (make-variable-buffer-local 'org-cycle-global-status)
4429 (defvar org-cycle-subtree-status nil)
4430 (make-variable-buffer-local 'org-cycle-subtree-status)
4432 ;;;###autoload
4433 (defun org-cycle (&optional arg)
4434 "Visibility cycling for Org-mode.
4436 - When this function is called with a prefix argument, rotate the entire
4437 buffer through 3 states (global cycling)
4438 1. OVERVIEW: Show only top-level headlines.
4439 2. CONTENTS: Show all headlines of all levels, but no body text.
4440 3. SHOW ALL: Show everything.
4441 When called with two C-u C-u prefixes, switch to the startup visibility,
4442 determined by the variable `org-startup-folded', and by any VISIBILITY
4443 properties in the buffer.
4444 When called with three C-u C-u C-u prefixed, show the entire buffer,
4445 including drawers.
4447 - When point is at the beginning of a headline, rotate the subtree started
4448 by this line through 3 different states (local cycling)
4449 1. FOLDED: Only the main headline is shown.
4450 2. CHILDREN: The main headline and the direct children are shown.
4451 From this state, you can move to one of the children
4452 and zoom in further.
4453 3. SUBTREE: Show the entire subtree, including body text.
4455 - When there is a numeric prefix, go up to a heading with level ARG, do
4456 a `show-subtree' and return to the previous cursor position. If ARG
4457 is negative, go up that many levels.
4459 - When point is not at the beginning of a headline, execute the global
4460 binding for TAB, which is re-indenting the line. See the option
4461 `org-cycle-emulate-tab' for details.
4463 - Special case: if point is at the beginning of the buffer and there is
4464 no headline in line 1, this function will act as if called with prefix arg.
4465 But only if also the variable `org-cycle-global-at-bob' is t."
4466 (interactive "P")
4467 (org-load-modules-maybe)
4468 (let* ((outline-regexp
4469 (if (and (org-mode-p) org-cycle-include-plain-lists)
4470 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4471 outline-regexp))
4472 (bob-special (and org-cycle-global-at-bob (bobp)
4473 (not (looking-at outline-regexp))))
4474 (org-cycle-hook
4475 (if bob-special
4476 (delq 'org-optimize-window-after-visibility-change
4477 (copy-sequence org-cycle-hook))
4478 org-cycle-hook))
4479 (pos (point)))
4481 (if (or bob-special (equal arg '(4)))
4482 ;; special case: use global cycling
4483 (setq arg t))
4485 (cond
4487 ((equal arg '(16))
4488 (org-set-startup-visibility)
4489 (message "Startup visibility, plus VISIBILITY properties"))
4491 ((equal arg '(64))
4492 (show-all)
4493 (message "Entire buffer visible, including drawers"))
4495 ((org-at-table-p 'any)
4496 ;; Enter the table or move to the next field in the table
4497 (or (org-table-recognize-table.el)
4498 (progn
4499 (if arg (org-table-edit-field t)
4500 (org-table-justify-field-maybe)
4501 (call-interactively 'org-table-next-field)))))
4503 ((eq arg t) ;; Global cycling
4505 (cond
4506 ((and (eq last-command this-command)
4507 (eq org-cycle-global-status 'overview))
4508 ;; We just created the overview - now do table of contents
4509 ;; This can be slow in very large buffers, so indicate action
4510 (message "CONTENTS...")
4511 (org-content)
4512 (message "CONTENTS...done")
4513 (setq org-cycle-global-status 'contents)
4514 (run-hook-with-args 'org-cycle-hook 'contents))
4516 ((and (eq last-command this-command)
4517 (eq org-cycle-global-status 'contents))
4518 ;; We just showed the table of contents - now show everything
4519 (show-all)
4520 (message "SHOW ALL")
4521 (setq org-cycle-global-status 'all)
4522 (run-hook-with-args 'org-cycle-hook 'all))
4525 ;; Default action: go to overview
4526 (org-overview)
4527 (message "OVERVIEW")
4528 (setq org-cycle-global-status 'overview)
4529 (run-hook-with-args 'org-cycle-hook 'overview))))
4531 ((and org-drawers org-drawer-regexp
4532 (save-excursion
4533 (beginning-of-line 1)
4534 (looking-at org-drawer-regexp)))
4535 ;; Toggle block visibility
4536 (org-flag-drawer
4537 (not (get-char-property (match-end 0) 'invisible))))
4539 ((integerp arg)
4540 ;; Show-subtree, ARG levels up from here.
4541 (save-excursion
4542 (org-back-to-heading)
4543 (outline-up-heading (if (< arg 0) (- arg)
4544 (- (funcall outline-level) arg)))
4545 (org-show-subtree)))
4547 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4548 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4549 ;; At a heading: rotate between three different views
4550 (org-back-to-heading)
4551 (let ((goal-column 0) eoh eol eos)
4552 ;; First, some boundaries
4553 (save-excursion
4554 (org-back-to-heading)
4555 (save-excursion
4556 (beginning-of-line 2)
4557 (while (and (not (eobp)) ;; this is like `next-line'
4558 (get-char-property (1- (point)) 'invisible))
4559 (beginning-of-line 2)) (setq eol (point)))
4560 (outline-end-of-heading) (setq eoh (point))
4561 (org-end-of-subtree t)
4562 (unless (eobp)
4563 (skip-chars-forward " \t\n")
4564 (beginning-of-line 1) ; in case this is an item
4566 (setq eos (1- (point))))
4567 ;; Find out what to do next and set `this-command'
4568 (cond
4569 ((= eos eoh)
4570 ;; Nothing is hidden behind this heading
4571 (message "EMPTY ENTRY")
4572 (setq org-cycle-subtree-status nil)
4573 (save-excursion
4574 (goto-char eos)
4575 (outline-next-heading)
4576 (if (org-invisible-p) (org-flag-heading nil))))
4577 ((or (>= eol eos)
4578 (not (string-match "\\S-" (buffer-substring eol eos))))
4579 ;; Entire subtree is hidden in one line: open it
4580 (org-show-entry)
4581 (show-children)
4582 (message "CHILDREN")
4583 (save-excursion
4584 (goto-char eos)
4585 (outline-next-heading)
4586 (if (org-invisible-p) (org-flag-heading nil)))
4587 (setq org-cycle-subtree-status 'children)
4588 (run-hook-with-args 'org-cycle-hook 'children))
4589 ((and (eq last-command this-command)
4590 (eq org-cycle-subtree-status 'children))
4591 ;; We just showed the children, now show everything.
4592 (org-show-subtree)
4593 (message "SUBTREE")
4594 (setq org-cycle-subtree-status 'subtree)
4595 (run-hook-with-args 'org-cycle-hook 'subtree))
4597 ;; Default action: hide the subtree.
4598 (hide-subtree)
4599 (message "FOLDED")
4600 (setq org-cycle-subtree-status 'folded)
4601 (run-hook-with-args 'org-cycle-hook 'folded)))))
4603 ;; TAB emulation and template completion
4604 (buffer-read-only (org-back-to-heading))
4606 ((org-try-structure-completion))
4608 ((org-try-cdlatex-tab))
4610 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4611 (or (not (bolp))
4612 (not (looking-at outline-regexp))))
4613 (call-interactively (global-key-binding "\t")))
4615 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4616 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4617 (or (and (eq org-cycle-emulate-tab 'white)
4618 (= (match-end 0) (point-at-eol)))
4619 (and (eq org-cycle-emulate-tab 'whitestart)
4620 (>= (match-end 0) pos))))
4622 (eq org-cycle-emulate-tab t))
4623 (call-interactively (global-key-binding "\t")))
4625 (t (save-excursion
4626 (org-back-to-heading)
4627 (org-cycle))))))
4629 ;;;###autoload
4630 (defun org-global-cycle (&optional arg)
4631 "Cycle the global visibility. For details see `org-cycle'.
4632 With C-u prefix arg, switch to startup visibility.
4633 With a numeric prefix, show all headlines up to that level."
4634 (interactive "P")
4635 (let ((org-cycle-include-plain-lists
4636 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4637 (cond
4638 ((integerp arg)
4639 (show-all)
4640 (hide-sublevels arg)
4641 (setq org-cycle-global-status 'contents))
4642 ((equal arg '(4))
4643 (org-set-startup-visibility)
4644 (message "Startup visibility, plus VISIBILITY properties."))
4646 (org-cycle '(4))))))
4648 (defun org-set-startup-visibility ()
4649 "Set the visibility required by startup options and properties."
4650 (cond
4651 ((eq org-startup-folded t)
4652 (org-cycle '(4)))
4653 ((eq org-startup-folded 'content)
4654 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4655 (org-cycle '(4)) (org-cycle '(4)))))
4656 (org-set-visibility-according-to-property 'no-cleanup)
4657 (org-cycle-hide-archived-subtrees 'all)
4658 (org-cycle-hide-drawers 'all)
4659 (org-cycle-show-empty-lines 'all))
4661 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4662 "Switch subtree visibilities according to :VISIBILITY: property."
4663 (interactive)
4664 (let (org-show-entry-below state)
4665 (save-excursion
4666 (goto-char (point-min))
4667 (while (re-search-forward
4668 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4669 nil t)
4670 (setq state (match-string 1))
4671 (save-excursion
4672 (org-back-to-heading t)
4673 (hide-subtree)
4674 (org-reveal)
4675 (cond
4676 ((equal state '("fold" "folded"))
4677 (hide-subtree))
4678 ((equal state "children")
4679 (org-show-hidden-entry)
4680 (show-children))
4681 ((equal state "content")
4682 (save-excursion
4683 (save-restriction
4684 (org-narrow-to-subtree)
4685 (org-content))))
4686 ((member state '("all" "showall"))
4687 (show-subtree)))))
4688 (unless no-cleanup
4689 (org-cycle-hide-archived-subtrees 'all)
4690 (org-cycle-hide-drawers 'all)
4691 (org-cycle-show-empty-lines 'all)))))
4693 (defun org-overview ()
4694 "Switch to overview mode, showing only top-level headlines.
4695 Really, this shows all headlines with level equal or greater than the level
4696 of the first headline in the buffer. This is important, because if the
4697 first headline is not level one, then (hide-sublevels 1) gives confusing
4698 results."
4699 (interactive)
4700 (let ((level (save-excursion
4701 (goto-char (point-min))
4702 (if (re-search-forward (concat "^" outline-regexp) nil t)
4703 (progn
4704 (goto-char (match-beginning 0))
4705 (funcall outline-level))))))
4706 (and level (hide-sublevels level))))
4708 (defun org-content (&optional arg)
4709 "Show all headlines in the buffer, like a table of contents.
4710 With numerical argument N, show content up to level N."
4711 (interactive "P")
4712 (save-excursion
4713 ;; Visit all headings and show their offspring
4714 (and (integerp arg) (org-overview))
4715 (goto-char (point-max))
4716 (catch 'exit
4717 (while (and (progn (condition-case nil
4718 (outline-previous-visible-heading 1)
4719 (error (goto-char (point-min))))
4721 (looking-at outline-regexp))
4722 (if (integerp arg)
4723 (show-children (1- arg))
4724 (show-branches))
4725 (if (bobp) (throw 'exit nil))))))
4728 (defun org-optimize-window-after-visibility-change (state)
4729 "Adjust the window after a change in outline visibility.
4730 This function is the default value of the hook `org-cycle-hook'."
4731 (when (get-buffer-window (current-buffer))
4732 (cond
4733 ((eq state 'content) nil)
4734 ((eq state 'all) nil)
4735 ((eq state 'folded) nil)
4736 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4737 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4739 (defun org-compact-display-after-subtree-move ()
4740 "Show a compacter version of the tree of the entry's parent."
4741 (save-excursion
4742 (if (org-up-heading-safe)
4743 (progn
4744 (hide-subtree)
4745 (show-entry)
4746 (show-children)
4747 (org-cycle-show-empty-lines 'children)
4748 (org-cycle-hide-drawers 'children))
4749 (org-overview))))
4751 (defun org-cycle-show-empty-lines (state)
4752 "Show empty lines above all visible headlines.
4753 The region to be covered depends on STATE when called through
4754 `org-cycle-hook'. Lisp program can use t for STATE to get the
4755 entire buffer covered. Note that an empty line is only shown if there
4756 are at least `org-cycle-separator-lines' empty lines before the headline."
4757 (when (> org-cycle-separator-lines 0)
4758 (save-excursion
4759 (let* ((n org-cycle-separator-lines)
4760 (re (cond
4761 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4762 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4763 (t (let ((ns (number-to-string (- n 2))))
4764 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4765 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4766 beg end)
4767 (cond
4768 ((memq state '(overview contents t))
4769 (setq beg (point-min) end (point-max)))
4770 ((memq state '(children folded))
4771 (setq beg (point) end (progn (org-end-of-subtree t t)
4772 (beginning-of-line 2)
4773 (point)))))
4774 (when beg
4775 (goto-char beg)
4776 (while (re-search-forward re end t)
4777 (if (not (get-char-property (match-end 1) 'invisible))
4778 (outline-flag-region
4779 (match-beginning 1) (match-end 1) nil)))))))
4780 ;; Never hide empty lines at the end of the file.
4781 (save-excursion
4782 (goto-char (point-max))
4783 (outline-previous-heading)
4784 (outline-end-of-heading)
4785 (if (and (looking-at "[ \t\n]+")
4786 (= (match-end 0) (point-max)))
4787 (outline-flag-region (point) (match-end 0) nil))))
4789 (defun org-show-empty-lines-in-parent ()
4790 "Move to the parent and re-show empty lines before visible headlines."
4791 (save-excursion
4792 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4793 (org-cycle-show-empty-lines context))))
4795 (defun org-cycle-hide-drawers (state)
4796 "Re-hide all drawers after a visibility state change."
4797 (when (and (org-mode-p)
4798 (not (memq state '(overview folded))))
4799 (save-excursion
4800 (let* ((globalp (memq state '(contents all)))
4801 (beg (if globalp (point-min) (point)))
4802 (end (if globalp (point-max) (org-end-of-subtree t))))
4803 (goto-char beg)
4804 (while (re-search-forward org-drawer-regexp end t)
4805 (org-flag-drawer t))))))
4807 (defun org-flag-drawer (flag)
4808 (save-excursion
4809 (beginning-of-line 1)
4810 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4811 (let ((b (match-end 0))
4812 (outline-regexp org-outline-regexp))
4813 (if (re-search-forward
4814 "^[ \t]*:END:"
4815 (save-excursion (outline-next-heading) (point)) t)
4816 (outline-flag-region b (point-at-eol) flag)
4817 (error ":END: line missing"))))))
4819 (defun org-subtree-end-visible-p ()
4820 "Is the end of the current subtree visible?"
4821 (pos-visible-in-window-p
4822 (save-excursion (org-end-of-subtree t) (point))))
4824 (defun org-first-headline-recenter (&optional N)
4825 "Move cursor to the first headline and recenter the headline.
4826 Optional argument N means, put the headline into the Nth line of the window."
4827 (goto-char (point-min))
4828 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4829 (beginning-of-line)
4830 (recenter (prefix-numeric-value N))))
4832 ;;; Org-goto
4834 (defvar org-goto-window-configuration nil)
4835 (defvar org-goto-marker nil)
4836 (defvar org-goto-map
4837 (let ((map (make-sparse-keymap)))
4838 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4839 (while (setq cmd (pop cmds))
4840 (substitute-key-definition cmd cmd map global-map)))
4841 (suppress-keymap map)
4842 (org-defkey map "\C-m" 'org-goto-ret)
4843 (org-defkey map [(return)] 'org-goto-ret)
4844 (org-defkey map [(left)] 'org-goto-left)
4845 (org-defkey map [(right)] 'org-goto-right)
4846 (org-defkey map [(control ?g)] 'org-goto-quit)
4847 (org-defkey map "\C-i" 'org-cycle)
4848 (org-defkey map [(tab)] 'org-cycle)
4849 (org-defkey map [(down)] 'outline-next-visible-heading)
4850 (org-defkey map [(up)] 'outline-previous-visible-heading)
4851 (if org-goto-auto-isearch
4852 (if (fboundp 'define-key-after)
4853 (define-key-after map [t] 'org-goto-local-auto-isearch)
4854 nil)
4855 (org-defkey map "q" 'org-goto-quit)
4856 (org-defkey map "n" 'outline-next-visible-heading)
4857 (org-defkey map "p" 'outline-previous-visible-heading)
4858 (org-defkey map "f" 'outline-forward-same-level)
4859 (org-defkey map "b" 'outline-backward-same-level)
4860 (org-defkey map "u" 'outline-up-heading))
4861 (org-defkey map "/" 'org-occur)
4862 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4863 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4864 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4865 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4866 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4867 map))
4869 (defconst org-goto-help
4870 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4871 RET=jump to location [Q]uit and return to previous location
4872 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4874 (defvar org-goto-start-pos) ; dynamically scoped parameter
4876 ;; FIXME: Docstring doe not mention both interfaces
4877 (defun org-goto (&optional alternative-interface)
4878 "Look up a different location in the current file, keeping current visibility.
4880 When you want look-up or go to a different location in a document, the
4881 fastest way is often to fold the entire buffer and then dive into the tree.
4882 This method has the disadvantage, that the previous location will be folded,
4883 which may not be what you want.
4885 This command works around this by showing a copy of the current buffer
4886 in an indirect buffer, in overview mode. You can dive into the tree in
4887 that copy, use org-occur and incremental search to find a location.
4888 When pressing RET or `Q', the command returns to the original buffer in
4889 which the visibility is still unchanged. After RET is will also jump to
4890 the location selected in the indirect buffer and expose the
4891 the headline hierarchy above."
4892 (interactive "P")
4893 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4894 (org-refile-use-outline-path t)
4895 (interface
4896 (if (not alternative-interface)
4897 org-goto-interface
4898 (if (eq org-goto-interface 'outline)
4899 'outline-path-completion
4900 'outline)))
4901 (org-goto-start-pos (point))
4902 (selected-point
4903 (if (eq interface 'outline)
4904 (car (org-get-location (current-buffer) org-goto-help))
4905 (nth 3 (org-refile-get-location "Goto: ")))))
4906 (if selected-point
4907 (progn
4908 (org-mark-ring-push org-goto-start-pos)
4909 (goto-char selected-point)
4910 (if (or (org-invisible-p) (org-invisible-p2))
4911 (org-show-context 'org-goto)))
4912 (message "Quit"))))
4914 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4915 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4916 (defvar org-goto-local-auto-isearch-map) ; defined below
4918 (defun org-get-location (buf help)
4919 "Let the user select a location in the Org-mode buffer BUF.
4920 This function uses a recursive edit. It returns the selected position
4921 or nil."
4922 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4923 (isearch-hide-immediately nil)
4924 (isearch-search-fun-function
4925 (lambda () 'org-goto-local-search-headings))
4926 (org-goto-selected-point org-goto-exit-command))
4927 (save-excursion
4928 (save-window-excursion
4929 (delete-other-windows)
4930 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4931 (switch-to-buffer
4932 (condition-case nil
4933 (make-indirect-buffer (current-buffer) "*org-goto*")
4934 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4935 (with-output-to-temp-buffer "*Help*"
4936 (princ help))
4937 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4938 (setq buffer-read-only nil)
4939 (let ((org-startup-truncated t)
4940 (org-startup-folded nil)
4941 (org-startup-align-all-tables nil))
4942 (org-mode)
4943 (org-overview))
4944 (setq buffer-read-only t)
4945 (if (and (boundp 'org-goto-start-pos)
4946 (integer-or-marker-p org-goto-start-pos))
4947 (let ((org-show-hierarchy-above t)
4948 (org-show-siblings t)
4949 (org-show-following-heading t))
4950 (goto-char org-goto-start-pos)
4951 (and (org-invisible-p) (org-show-context)))
4952 (goto-char (point-min)))
4953 (let (org-special-ctrl-a/e) (org-beginning-of-line))
4954 (message "Select location and press RET")
4955 (use-local-map org-goto-map)
4956 (recursive-edit)
4958 (kill-buffer "*org-goto*")
4959 (cons org-goto-selected-point org-goto-exit-command)))
4961 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4962 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4963 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4964 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4966 (defun org-goto-local-search-headings (string bound noerror)
4967 "Search and make sure that any matches are in headlines."
4968 (catch 'return
4969 (while (if isearch-forward
4970 (search-forward string bound noerror)
4971 (search-backward string bound noerror))
4972 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4973 (and (member :headline context)
4974 (not (member :tags context))))
4975 (throw 'return (point))))))
4977 (defun org-goto-local-auto-isearch ()
4978 "Start isearch."
4979 (interactive)
4980 (goto-char (point-min))
4981 (let ((keys (this-command-keys)))
4982 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4983 (isearch-mode t)
4984 (isearch-process-search-char (string-to-char keys)))))
4986 (defun org-goto-ret (&optional arg)
4987 "Finish `org-goto' by going to the new location."
4988 (interactive "P")
4989 (setq org-goto-selected-point (point)
4990 org-goto-exit-command 'return)
4991 (throw 'exit nil))
4993 (defun org-goto-left ()
4994 "Finish `org-goto' by going to the new location."
4995 (interactive)
4996 (if (org-on-heading-p)
4997 (progn
4998 (beginning-of-line 1)
4999 (setq org-goto-selected-point (point)
5000 org-goto-exit-command 'left)
5001 (throw 'exit nil))
5002 (error "Not on a heading")))
5004 (defun org-goto-right ()
5005 "Finish `org-goto' by going to the new location."
5006 (interactive)
5007 (if (org-on-heading-p)
5008 (progn
5009 (setq org-goto-selected-point (point)
5010 org-goto-exit-command 'right)
5011 (throw 'exit nil))
5012 (error "Not on a heading")))
5014 (defun org-goto-quit ()
5015 "Finish `org-goto' without cursor motion."
5016 (interactive)
5017 (setq org-goto-selected-point nil)
5018 (setq org-goto-exit-command 'quit)
5019 (throw 'exit nil))
5021 ;;; Indirect buffer display of subtrees
5023 (defvar org-indirect-dedicated-frame nil
5024 "This is the frame being used for indirect tree display.")
5025 (defvar org-last-indirect-buffer nil)
5027 (defun org-tree-to-indirect-buffer (&optional arg)
5028 "Create indirect buffer and narrow it to current subtree.
5029 With numerical prefix ARG, go up to this level and then take that tree.
5030 If ARG is negative, go up that many levels.
5031 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5032 indirect buffer previously made with this command, to avoid proliferation of
5033 indirect buffers. However, when you call the command with a `C-u' prefix, or
5034 when `org-indirect-buffer-display' is `new-frame', the last buffer
5035 is kept so that you can work with several indirect buffers at the same time.
5036 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5037 requests that a new frame be made for the new buffer, so that the dedicated
5038 frame is not changed."
5039 (interactive "P")
5040 (let ((cbuf (current-buffer))
5041 (cwin (selected-window))
5042 (pos (point))
5043 beg end level heading ibuf)
5044 (save-excursion
5045 (org-back-to-heading t)
5046 (when (numberp arg)
5047 (setq level (org-outline-level))
5048 (if (< arg 0) (setq arg (+ level arg)))
5049 (while (> (setq level (org-outline-level)) arg)
5050 (outline-up-heading 1 t)))
5051 (setq beg (point)
5052 heading (org-get-heading))
5053 (org-end-of-subtree t) (setq end (point)))
5054 (if (and (buffer-live-p org-last-indirect-buffer)
5055 (not (eq org-indirect-buffer-display 'new-frame))
5056 (not arg))
5057 (kill-buffer org-last-indirect-buffer))
5058 (setq ibuf (org-get-indirect-buffer cbuf)
5059 org-last-indirect-buffer ibuf)
5060 (cond
5061 ((or (eq org-indirect-buffer-display 'new-frame)
5062 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5063 (select-frame (make-frame))
5064 (delete-other-windows)
5065 (switch-to-buffer ibuf)
5066 (org-set-frame-title heading))
5067 ((eq org-indirect-buffer-display 'dedicated-frame)
5068 (raise-frame
5069 (select-frame (or (and org-indirect-dedicated-frame
5070 (frame-live-p org-indirect-dedicated-frame)
5071 org-indirect-dedicated-frame)
5072 (setq org-indirect-dedicated-frame (make-frame)))))
5073 (delete-other-windows)
5074 (switch-to-buffer ibuf)
5075 (org-set-frame-title (concat "Indirect: " heading)))
5076 ((eq org-indirect-buffer-display 'current-window)
5077 (switch-to-buffer ibuf))
5078 ((eq org-indirect-buffer-display 'other-window)
5079 (pop-to-buffer ibuf))
5080 (t (error "Invalid value.")))
5081 (if (featurep 'xemacs)
5082 (save-excursion (org-mode) (turn-on-font-lock)))
5083 (narrow-to-region beg end)
5084 (show-all)
5085 (goto-char pos)
5086 (and (window-live-p cwin) (select-window cwin))))
5088 (defun org-get-indirect-buffer (&optional buffer)
5089 (setq buffer (or buffer (current-buffer)))
5090 (let ((n 1) (base (buffer-name buffer)) bname)
5091 (while (buffer-live-p
5092 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5093 (setq n (1+ n)))
5094 (condition-case nil
5095 (make-indirect-buffer buffer bname 'clone)
5096 (error (make-indirect-buffer buffer bname)))))
5098 (defun org-set-frame-title (title)
5099 "Set the title of the current frame to the string TITLE."
5100 ;; FIXME: how to name a single frame in XEmacs???
5101 (unless (featurep 'xemacs)
5102 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5104 ;;;; Structure editing
5106 ;;; Inserting headlines
5108 (defun org-previous-line-empty-p ()
5109 (save-excursion
5110 (and (not (bobp))
5111 (or (beginning-of-line 0) t)
5112 (save-match-data
5113 (looking-at "[ \t]*$")))))
5115 (defun org-insert-heading (&optional force-heading)
5116 "Insert a new heading or item with same depth at point.
5117 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5118 If point is at the beginning of a headline, insert a sibling before the
5119 current headline. If point is not at the beginning, do not split the line,
5120 but create the new headline after the current line."
5121 (interactive "P")
5122 (if (= (buffer-size) 0)
5123 (insert "\n* ")
5124 (when (or force-heading (not (org-insert-item)))
5125 (let* ((empty-line-p nil)
5126 (head (save-excursion
5127 (condition-case nil
5128 (progn
5129 (org-back-to-heading)
5130 (setq empty-line-p (org-previous-line-empty-p))
5131 (match-string 0))
5132 (error "*"))))
5133 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5134 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5135 pos hide-previous previous-pos)
5136 (cond
5137 ((and (org-on-heading-p) (bolp)
5138 (or (bobp)
5139 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5140 ;; insert before the current line
5141 (open-line (if blank 2 1)))
5142 ((and (bolp)
5143 (or (bobp)
5144 (save-excursion
5145 (backward-char 1) (not (org-invisible-p)))))
5146 ;; insert right here
5147 nil)
5149 ;; somewhere in the line
5150 (save-excursion
5151 (setq previous-pos (point-at-bol))
5152 (end-of-line)
5153 (setq hide-previous (org-invisible-p)))
5154 (and org-insert-heading-respect-content (org-show-subtree))
5155 (let ((split
5156 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5157 (save-excursion
5158 (let ((p (point)))
5159 (goto-char (point-at-bol))
5160 (and (looking-at org-complex-heading-regexp)
5161 (> p (match-beginning 4)))))))
5162 tags pos)
5163 (cond
5164 (org-insert-heading-respect-content
5165 (org-end-of-subtree nil t)
5166 (or (bolp) (newline))
5167 (or (org-previous-line-empty-p)
5168 (and blank (newline)))
5169 (open-line 1))
5170 ((org-on-heading-p)
5171 (when hide-previous
5172 (show-children)
5173 (org-show-entry))
5174 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5175 (setq tags (and (match-end 2) (match-string 2)))
5176 (and (match-end 1)
5177 (delete-region (match-beginning 1) (match-end 1)))
5178 (setq pos (point-at-bol))
5179 (or split (end-of-line 1))
5180 (delete-horizontal-space)
5181 (newline (if blank 2 1))
5182 (when tags
5183 (save-excursion
5184 (goto-char pos)
5185 (end-of-line 1)
5186 (insert " " tags)
5187 (org-set-tags nil 'align))))
5189 (or split (end-of-line 1))
5190 (newline (if blank 2 1)))))))
5191 (insert head) (just-one-space)
5192 (setq pos (point))
5193 (end-of-line 1)
5194 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5195 (when (and org-insert-heading-respect-content hide-previous)
5196 (save-excursion
5197 (goto-char previous-pos)
5198 (hide-subtree)))
5199 (run-hooks 'org-insert-heading-hook)))))
5201 (defun org-get-heading (&optional no-tags)
5202 "Return the heading of the current entry, without the stars."
5203 (save-excursion
5204 (org-back-to-heading t)
5205 (if (looking-at
5206 (if no-tags
5207 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5208 "\\*+[ \t]+\\([^\r\n]*\\)"))
5209 (match-string 1) "")))
5211 (defun org-heading-components ()
5212 "Return the components of the current heading.
5213 This is a list with the following elements:
5214 - the level as an integer
5215 - the reduced level, different if `org-odd-levels-only' is set.
5216 - the TODO keyword, or nil
5217 - the priority character, like ?A, or nil if no priority is given
5218 - the headline text itself, or the tags string if no headline text
5219 - the tags string, or nil."
5220 (save-excursion
5221 (org-back-to-heading t)
5222 (if (looking-at org-complex-heading-regexp)
5223 (list (length (match-string 1))
5224 (org-reduced-level (length (match-string 1)))
5225 (org-match-string-no-properties 2)
5226 (and (match-end 3) (aref (match-string 3) 2))
5227 (org-match-string-no-properties 4)
5228 (org-match-string-no-properties 5)))))
5230 (defun org-insert-heading-after-current ()
5231 "Insert a new heading with same level as current, after current subtree."
5232 (interactive)
5233 (org-back-to-heading)
5234 (org-insert-heading)
5235 (org-move-subtree-down)
5236 (end-of-line 1))
5238 (defun org-insert-heading-respect-content ()
5239 (interactive)
5240 (let ((org-insert-heading-respect-content t))
5241 (org-insert-heading t)))
5243 (defun org-insert-todo-heading-respect-content (&optional force-state)
5244 (interactive "P")
5245 (let ((org-insert-heading-respect-content t))
5246 (org-insert-todo-heading force-state t)))
5248 (defun org-insert-todo-heading (arg &optional force-heading)
5249 "Insert a new heading with the same level and TODO state as current heading.
5250 If the heading has no TODO state, or if the state is DONE, use the first
5251 state (TODO by default). Also with prefix arg, force first state."
5252 (interactive "P")
5253 (when (or force-heading (not (org-insert-item 'checkbox)))
5254 (org-insert-heading force-heading)
5255 (save-excursion
5256 (org-back-to-heading)
5257 (outline-previous-heading)
5258 (looking-at org-todo-line-regexp))
5259 (let*
5260 ((new-mark-x
5261 (if (or arg
5262 (not (match-beginning 2))
5263 (member (match-string 2) org-done-keywords))
5264 (car org-todo-keywords-1)
5265 (match-string 2)))
5266 (new-mark
5268 (run-hook-with-args-until-success
5269 'org-todo-get-default-hook new-mark-x nil)
5270 new-mark-x)))
5271 (insert new-mark " "))
5272 (when org-provide-todo-statistics
5273 (org-update-parent-todo-statistics))))
5275 (defun org-insert-subheading (arg)
5276 "Insert a new subheading and demote it.
5277 Works for outline headings and for plain lists alike."
5278 (interactive "P")
5279 (org-insert-heading arg)
5280 (cond
5281 ((org-on-heading-p) (org-do-demote))
5282 ((org-at-item-p) (org-indent-item 1))))
5284 (defun org-insert-todo-subheading (arg)
5285 "Insert a new subheading with TODO keyword or checkbox and demote it.
5286 Works for outline headings and for plain lists alike."
5287 (interactive "P")
5288 (org-insert-todo-heading arg)
5289 (cond
5290 ((org-on-heading-p) (org-do-demote))
5291 ((org-at-item-p) (org-indent-item 1))))
5293 ;;; Promotion and Demotion
5295 (defun org-promote-subtree ()
5296 "Promote the entire subtree.
5297 See also `org-promote'."
5298 (interactive)
5299 (save-excursion
5300 (org-map-tree 'org-promote))
5301 (org-fix-position-after-promote))
5303 (defun org-demote-subtree ()
5304 "Demote the entire subtree. See `org-demote'.
5305 See also `org-promote'."
5306 (interactive)
5307 (save-excursion
5308 (org-map-tree 'org-demote))
5309 (org-fix-position-after-promote))
5312 (defun org-do-promote ()
5313 "Promote the current heading higher up the tree.
5314 If the region is active in `transient-mark-mode', promote all headings
5315 in the region."
5316 (interactive)
5317 (save-excursion
5318 (if (org-region-active-p)
5319 (org-map-region 'org-promote (region-beginning) (region-end))
5320 (org-promote)))
5321 (org-fix-position-after-promote))
5323 (defun org-do-demote ()
5324 "Demote the current heading lower down the tree.
5325 If the region is active in `transient-mark-mode', demote all headings
5326 in the region."
5327 (interactive)
5328 (save-excursion
5329 (if (org-region-active-p)
5330 (org-map-region 'org-demote (region-beginning) (region-end))
5331 (org-demote)))
5332 (org-fix-position-after-promote))
5334 (defun org-fix-position-after-promote ()
5335 "Make sure that after pro/demotion cursor position is right."
5336 (let ((pos (point)))
5337 (when (save-excursion
5338 (beginning-of-line 1)
5339 (looking-at org-todo-line-regexp)
5340 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5341 (cond ((eobp) (insert " "))
5342 ((eolp) (insert " "))
5343 ((equal (char-after) ?\ ) (forward-char 1))))))
5345 (defun org-reduced-level (l)
5346 "Compute the effective level of a heading.
5347 This takes into account the setting of `org-odd-levels-only'."
5348 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5350 (defun org-get-valid-level (level &optional change)
5351 "Rectify a level change under the influence of `org-odd-levels-only'
5352 LEVEL is a current level, CHANGE is by how much the level should be
5353 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5354 even level numbers will become the next higher odd number."
5355 (if org-odd-levels-only
5356 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5357 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5358 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5359 (max 1 (+ level change))))
5361 (if (boundp 'define-obsolete-function-alias)
5362 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5363 (define-obsolete-function-alias 'org-get-legal-level
5364 'org-get-valid-level)
5365 (define-obsolete-function-alias 'org-get-legal-level
5366 'org-get-valid-level "23.1")))
5368 (defun org-promote ()
5369 "Promote the current heading higher up the tree.
5370 If the region is active in `transient-mark-mode', promote all headings
5371 in the region."
5372 (org-back-to-heading t)
5373 (let* ((level (save-match-data (funcall outline-level)))
5374 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5375 (diff (abs (- level (length up-head) -1))))
5376 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5377 (replace-match up-head nil t)
5378 ;; Fixup tag positioning
5379 (and org-auto-align-tags (org-set-tags nil t))
5380 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5382 (defun org-demote ()
5383 "Demote the current heading lower down the tree.
5384 If the region is active in `transient-mark-mode', demote all headings
5385 in the region."
5386 (org-back-to-heading t)
5387 (let* ((level (save-match-data (funcall outline-level)))
5388 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5389 (diff (abs (- level (length down-head) -1))))
5390 (replace-match down-head nil t)
5391 ;; Fixup tag positioning
5392 (and org-auto-align-tags (org-set-tags nil t))
5393 (if org-adapt-indentation (org-fixup-indentation diff))))
5395 (defun org-map-tree (fun)
5396 "Call FUN for every heading underneath the current one."
5397 (org-back-to-heading)
5398 (let ((level (funcall outline-level)))
5399 (save-excursion
5400 (funcall fun)
5401 (while (and (progn
5402 (outline-next-heading)
5403 (> (funcall outline-level) level))
5404 (not (eobp)))
5405 (funcall fun)))))
5407 (defun org-map-region (fun beg end)
5408 "Call FUN for every heading between BEG and END."
5409 (let ((org-ignore-region t))
5410 (save-excursion
5411 (setq end (copy-marker end))
5412 (goto-char beg)
5413 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5414 (< (point) end))
5415 (funcall fun))
5416 (while (and (progn
5417 (outline-next-heading)
5418 (< (point) end))
5419 (not (eobp)))
5420 (funcall fun)))))
5422 (defun org-fixup-indentation (diff)
5423 "Change the indentation in the current entry by DIFF
5424 However, if any line in the current entry has no indentation, or if it
5425 would end up with no indentation after the change, nothing at all is done."
5426 (save-excursion
5427 (let ((end (save-excursion (outline-next-heading)
5428 (point-marker)))
5429 (prohibit (if (> diff 0)
5430 "^\\S-"
5431 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5432 col)
5433 (unless (save-excursion (end-of-line 1)
5434 (re-search-forward prohibit end t))
5435 (while (and (< (point) end)
5436 (re-search-forward "^[ \t]+" end t))
5437 (goto-char (match-end 0))
5438 (setq col (current-column))
5439 (if (< diff 0) (replace-match ""))
5440 (org-indent-to-column (+ diff col))))
5441 (move-marker end nil))))
5443 (defun org-convert-to-odd-levels ()
5444 "Convert an org-mode file with all levels allowed to one with odd levels.
5445 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5446 level 5 etc."
5447 (interactive)
5448 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5449 (let ((org-odd-levels-only nil) n)
5450 (save-excursion
5451 (goto-char (point-min))
5452 (while (re-search-forward "^\\*\\*+ " nil t)
5453 (setq n (- (length (match-string 0)) 2))
5454 (while (>= (setq n (1- n)) 0)
5455 (org-demote))
5456 (end-of-line 1))))))
5459 (defun org-convert-to-oddeven-levels ()
5460 "Convert an org-mode file with only odd levels to one with odd and even levels.
5461 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5462 section with an even level, conversion would destroy the structure of the file. An error
5463 is signaled in this case."
5464 (interactive)
5465 (goto-char (point-min))
5466 ;; First check if there are no even levels
5467 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5468 (org-show-context t)
5469 (error "Not all levels are odd in this file. Conversion not possible."))
5470 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5471 (let ((org-odd-levels-only nil) n)
5472 (save-excursion
5473 (goto-char (point-min))
5474 (while (re-search-forward "^\\*\\*+ " nil t)
5475 (setq n (/ (1- (length (match-string 0))) 2))
5476 (while (>= (setq n (1- n)) 0)
5477 (org-promote))
5478 (end-of-line 1))))))
5480 (defun org-tr-level (n)
5481 "Make N odd if required."
5482 (if org-odd-levels-only (1+ (/ n 2)) n))
5484 ;;; Vertical tree motion, cutting and pasting of subtrees
5486 (defun org-move-subtree-up (&optional arg)
5487 "Move the current subtree up past ARG headlines of the same level."
5488 (interactive "p")
5489 (org-move-subtree-down (- (prefix-numeric-value arg))))
5491 (defun org-move-subtree-down (&optional arg)
5492 "Move the current subtree down past ARG headlines of the same level."
5493 (interactive "p")
5494 (setq arg (prefix-numeric-value arg))
5495 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5496 'outline-get-last-sibling))
5497 (ins-point (make-marker))
5498 (cnt (abs arg))
5499 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5500 ;; Select the tree
5501 (org-back-to-heading)
5502 (setq beg0 (point))
5503 (save-excursion
5504 (setq ne-beg (org-back-over-empty-lines))
5505 (setq beg (point)))
5506 (save-match-data
5507 (save-excursion (outline-end-of-heading)
5508 (setq folded (org-invisible-p)))
5509 (outline-end-of-subtree))
5510 (outline-next-heading)
5511 (setq ne-end (org-back-over-empty-lines))
5512 (setq end (point))
5513 (goto-char beg0)
5514 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5515 ;; include less whitespace
5516 (save-excursion
5517 (goto-char beg)
5518 (forward-line (- ne-beg ne-end))
5519 (setq beg (point))))
5520 ;; Find insertion point, with error handling
5521 (while (> cnt 0)
5522 (or (and (funcall movfunc) (looking-at outline-regexp))
5523 (progn (goto-char beg0)
5524 (error "Cannot move past superior level or buffer limit")))
5525 (setq cnt (1- cnt)))
5526 (if (> arg 0)
5527 ;; Moving forward - still need to move over subtree
5528 (progn (org-end-of-subtree t t)
5529 (save-excursion
5530 (org-back-over-empty-lines)
5531 (or (bolp) (newline)))))
5532 (setq ne-ins (org-back-over-empty-lines))
5533 (move-marker ins-point (point))
5534 (setq txt (buffer-substring beg end))
5535 (org-save-markers-in-region beg end)
5536 (delete-region beg end)
5537 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5538 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5539 (let ((bbb (point)))
5540 (insert-before-markers txt)
5541 (org-reinstall-markers-in-region bbb)
5542 (move-marker ins-point bbb))
5543 (or (bolp) (insert "\n"))
5544 (setq ins-end (point))
5545 (goto-char ins-point)
5546 (org-skip-whitespace)
5547 (when (and (< arg 0)
5548 (org-first-sibling-p)
5549 (> ne-ins ne-beg))
5550 ;; Move whitespace back to beginning
5551 (save-excursion
5552 (goto-char ins-end)
5553 (let ((kill-whole-line t))
5554 (kill-line (- ne-ins ne-beg)) (point)))
5555 (insert (make-string (- ne-ins ne-beg) ?\n)))
5556 (move-marker ins-point nil)
5557 (org-compact-display-after-subtree-move)
5558 (org-show-empty-lines-in-parent)
5559 (unless folded
5560 (org-show-entry)
5561 (show-children)
5562 (org-cycle-hide-drawers 'children))))
5564 (defvar org-subtree-clip ""
5565 "Clipboard for cut and paste of subtrees.
5566 This is actually only a copy of the kill, because we use the normal kill
5567 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5569 (defvar org-subtree-clip-folded nil
5570 "Was the last copied subtree folded?
5571 This is used to fold the tree back after pasting.")
5573 (defun org-cut-subtree (&optional n)
5574 "Cut the current subtree into the clipboard.
5575 With prefix arg N, cut this many sequential subtrees.
5576 This is a short-hand for marking the subtree and then cutting it."
5577 (interactive "p")
5578 (org-copy-subtree n 'cut))
5580 (defun org-copy-subtree (&optional n cut force-store-markers)
5581 "Cut the current subtree into the clipboard.
5582 With prefix arg N, cut this many sequential subtrees.
5583 This is a short-hand for marking the subtree and then copying it.
5584 If CUT is non-nil, actually cut the subtree.
5585 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5586 of some markers in the region, even if CUT is non-nil. This is
5587 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5588 (interactive "p")
5589 (let (beg end folded (beg0 (point)))
5590 (if (interactive-p)
5591 (org-back-to-heading nil) ; take what looks like a subtree
5592 (org-back-to-heading t)) ; take what is really there
5593 (org-back-over-empty-lines)
5594 (setq beg (point))
5595 (skip-chars-forward " \t\r\n")
5596 (save-match-data
5597 (save-excursion (outline-end-of-heading)
5598 (setq folded (org-invisible-p)))
5599 (condition-case nil
5600 (outline-forward-same-level (1- n))
5601 (error nil))
5602 (org-end-of-subtree t t))
5603 (org-back-over-empty-lines)
5604 (setq end (point))
5605 (goto-char beg0)
5606 (when (> end beg)
5607 (setq org-subtree-clip-folded folded)
5608 (when (or cut force-store-markers)
5609 (org-save-markers-in-region beg end))
5610 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5611 (setq org-subtree-clip (current-kill 0))
5612 (message "%s: Subtree(s) with %d characters"
5613 (if cut "Cut" "Copied")
5614 (length org-subtree-clip)))))
5616 (defun org-paste-subtree (&optional level tree for-yank)
5617 "Paste the clipboard as a subtree, with modification of headline level.
5618 The entire subtree is promoted or demoted in order to match a new headline
5619 level.
5621 If the cursor is at the beginning of a headline, the same level as
5622 that headline is used to paste the tree
5624 If not, the new level is derived from the *visible* headings
5625 before and after the insertion point, and taken to be the inferior headline
5626 level of the two. So if the previous visible heading is level 3 and the
5627 next is level 4 (or vice versa), level 4 will be used for insertion.
5628 This makes sure that the subtree remains an independent subtree and does
5629 not swallow low level entries.
5631 You can also force a different level, either by using a numeric prefix
5632 argument, or by inserting the heading marker by hand. For example, if the
5633 cursor is after \"*****\", then the tree will be shifted to level 5.
5635 If optional TREE is given, use this text instead of the kill ring.
5637 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5638 move back over whitespace before inserting, and move point to the end of
5639 the inserted text when done."
5640 (interactive "P")
5641 (unless (org-kill-is-subtree-p tree)
5642 (error "%s"
5643 (substitute-command-keys
5644 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5645 (let* ((visp (not (org-invisible-p)))
5646 (txt (or tree (and kill-ring (current-kill 0))))
5647 (^re (concat "^\\(" outline-regexp "\\)"))
5648 (re (concat "\\(" outline-regexp "\\)"))
5649 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5651 (old-level (if (string-match ^re txt)
5652 (- (match-end 0) (match-beginning 0) 1)
5653 -1))
5654 (force-level (cond (level (prefix-numeric-value level))
5655 ((and (looking-at "[ \t]*$")
5656 (string-match
5657 ^re_ (buffer-substring
5658 (point-at-bol) (point))))
5659 (- (match-end 1) (match-beginning 1)))
5660 ((and (bolp)
5661 (looking-at org-outline-regexp))
5662 (- (match-end 0) (point) 1))
5663 (t nil)))
5664 (previous-level (save-excursion
5665 (condition-case nil
5666 (progn
5667 (outline-previous-visible-heading 1)
5668 (if (looking-at re)
5669 (- (match-end 0) (match-beginning 0) 1)
5671 (error 1))))
5672 (next-level (save-excursion
5673 (condition-case nil
5674 (progn
5675 (or (looking-at outline-regexp)
5676 (outline-next-visible-heading 1))
5677 (if (looking-at re)
5678 (- (match-end 0) (match-beginning 0) 1)
5680 (error 1))))
5681 (new-level (or force-level (max previous-level next-level)))
5682 (shift (if (or (= old-level -1)
5683 (= new-level -1)
5684 (= old-level new-level))
5686 (- new-level old-level)))
5687 (delta (if (> shift 0) -1 1))
5688 (func (if (> shift 0) 'org-demote 'org-promote))
5689 (org-odd-levels-only nil)
5690 beg end newend)
5691 ;; Remove the forced level indicator
5692 (if force-level
5693 (delete-region (point-at-bol) (point)))
5694 ;; Paste
5695 (beginning-of-line 1)
5696 (unless for-yank (org-back-over-empty-lines))
5697 (setq beg (point))
5698 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5699 (insert-before-markers txt)
5700 (unless (string-match "\n\\'" txt) (insert "\n"))
5701 (setq newend (point))
5702 (org-reinstall-markers-in-region beg)
5703 (setq end (point))
5704 (goto-char beg)
5705 (skip-chars-forward " \t\n\r")
5706 (setq beg (point))
5707 (if (and (org-invisible-p) visp)
5708 (save-excursion (outline-show-heading)))
5709 ;; Shift if necessary
5710 (unless (= shift 0)
5711 (save-restriction
5712 (narrow-to-region beg end)
5713 (while (not (= shift 0))
5714 (org-map-region func (point-min) (point-max))
5715 (setq shift (+ delta shift)))
5716 (goto-char (point-min))
5717 (setq newend (point-max))))
5718 (when (or (interactive-p) for-yank)
5719 (message "Clipboard pasted as level %d subtree" new-level))
5720 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5721 kill-ring
5722 (eq org-subtree-clip (current-kill 0))
5723 org-subtree-clip-folded)
5724 ;; The tree was folded before it was killed/copied
5725 (hide-subtree))
5726 (and for-yank (goto-char newend))))
5728 (defun org-kill-is-subtree-p (&optional txt)
5729 "Check if the current kill is an outline subtree, or a set of trees.
5730 Returns nil if kill does not start with a headline, or if the first
5731 headline level is not the largest headline level in the tree.
5732 So this will actually accept several entries of equal levels as well,
5733 which is OK for `org-paste-subtree'.
5734 If optional TXT is given, check this string instead of the current kill."
5735 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5736 (start-level (and kill
5737 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5738 org-outline-regexp "\\)")
5739 kill)
5740 (- (match-end 2) (match-beginning 2) 1)))
5741 (re (concat "^" org-outline-regexp))
5742 (start (1+ (or (match-beginning 2) -1))))
5743 (if (not start-level)
5744 (progn
5745 nil) ;; does not even start with a heading
5746 (catch 'exit
5747 (while (setq start (string-match re kill (1+ start)))
5748 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5749 (throw 'exit nil)))
5750 t))))
5752 (defvar org-markers-to-move nil
5753 "Markers that should be moved with a cut-and-paste operation.
5754 Those markers are stored together with their positions relative to
5755 the start of the region.")
5757 (defun org-save-markers-in-region (beg end)
5758 "Check markers in region.
5759 If these markers are between BEG and END, record their position relative
5760 to BEG, so that after moving the block of text, we can put the markers back
5761 into place.
5762 This function gets called just before an entry or tree gets cut from the
5763 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5764 called immediately, to move the markers with the entries."
5765 (setq org-markers-to-move nil)
5766 (when (featurep 'org-clock)
5767 (org-clock-save-markers-for-cut-and-paste beg end))
5768 (when (featurep 'org-agenda)
5769 (org-agenda-save-markers-for-cut-and-paste beg end)))
5771 (defun org-check-and-save-marker (marker beg end)
5772 "Check if MARKER is between BEG and END.
5773 If yes, remember the marker and the distance to BEG."
5774 (when (and (marker-buffer marker)
5775 (equal (marker-buffer marker) (current-buffer)))
5776 (if (and (>= marker beg) (< marker end))
5777 (push (cons marker (- marker beg)) org-markers-to-move))))
5779 (defun org-reinstall-markers-in-region (beg)
5780 "Move all remembered markers to their position relative to BEG."
5781 (mapc (lambda (x)
5782 (move-marker (car x) (+ beg (cdr x))))
5783 org-markers-to-move)
5784 (setq org-markers-to-move nil))
5786 (defun org-narrow-to-subtree ()
5787 "Narrow buffer to the current subtree."
5788 (interactive)
5789 (save-excursion
5790 (save-match-data
5791 (narrow-to-region
5792 (progn (org-back-to-heading) (point))
5793 (progn (org-end-of-subtree t) (point))))))
5796 ;;; Outline Sorting
5798 (defun org-sort (with-case)
5799 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5800 Optional argument WITH-CASE means sort case-sensitively.
5801 With a double prefix argument, also remove duplicate entries."
5802 (interactive "P")
5803 (if (org-at-table-p)
5804 (org-call-with-arg 'org-table-sort-lines with-case)
5805 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5807 (defun org-sort-remove-invisible (s)
5808 (remove-text-properties 0 (length s) org-rm-props s)
5809 (while (string-match org-bracket-link-regexp s)
5810 (setq s (replace-match (if (match-end 2)
5811 (match-string 3 s)
5812 (match-string 1 s)) t t s)))
5815 (defvar org-priority-regexp) ; defined later in the file
5817 (defun org-sort-entries-or-items
5818 (&optional with-case sorting-type getkey-func compare-func property)
5819 "Sort entries on a certain level of an outline tree.
5820 If there is an active region, the entries in the region are sorted.
5821 Else, if the cursor is before the first entry, sort the top-level items.
5822 Else, the children of the entry at point are sorted.
5824 Sorting can be alphabetically, numerically, and by date/time as given by
5825 the first time stamp in the entry. The command prompts for the sorting
5826 type unless it has been given to the function through the SORTING-TYPE
5827 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5828 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5829 called with point at the beginning of the record. It must return either
5830 a string or a number that should serve as the sorting key for that record.
5832 Comparing entries ignores case by default. However, with an optional argument
5833 WITH-CASE, the sorting considers case as well."
5834 (interactive "P")
5835 (let ((case-func (if with-case 'identity 'downcase))
5836 start beg end stars re re2
5837 txt what tmp plain-list-p)
5838 ;; Find beginning and end of region to sort
5839 (cond
5840 ((org-region-active-p)
5841 ;; we will sort the region
5842 (setq end (region-end)
5843 what "region")
5844 (goto-char (region-beginning))
5845 (if (not (org-on-heading-p)) (outline-next-heading))
5846 (setq start (point)))
5847 ((org-at-item-p)
5848 ;; we will sort this plain list
5849 (org-beginning-of-item-list) (setq start (point))
5850 (org-end-of-item-list) (setq end (point))
5851 (goto-char start)
5852 (setq plain-list-p t
5853 what "plain list"))
5854 ((or (org-on-heading-p)
5855 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5856 ;; we will sort the children of the current headline
5857 (org-back-to-heading)
5858 (setq start (point)
5859 end (progn (org-end-of-subtree t t)
5860 (org-back-over-empty-lines)
5861 (point))
5862 what "children")
5863 (goto-char start)
5864 (show-subtree)
5865 (outline-next-heading))
5867 ;; we will sort the top-level entries in this file
5868 (goto-char (point-min))
5869 (or (org-on-heading-p) (outline-next-heading))
5870 (setq start (point) end (point-max) what "top-level")
5871 (goto-char start)
5872 (show-all)))
5874 (setq beg (point))
5875 (if (>= beg end) (error "Nothing to sort"))
5877 (unless plain-list-p
5878 (looking-at "\\(\\*+\\)")
5879 (setq stars (match-string 1)
5880 re (concat "^" (regexp-quote stars) " +")
5881 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5882 txt (buffer-substring beg end))
5883 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5884 (if (and (not (equal stars "*")) (string-match re2 txt))
5885 (error "Region to sort contains a level above the first entry")))
5887 (unless sorting-type
5888 (message
5889 (if plain-list-p
5890 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5891 "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:")
5892 what)
5893 (setq sorting-type (read-char-exclusive))
5895 (and (= (downcase sorting-type) ?f)
5896 (setq getkey-func
5897 (org-ido-completing-read "Sort using function: "
5898 obarray 'fboundp t nil nil))
5899 (setq getkey-func (intern getkey-func)))
5901 (and (= (downcase sorting-type) ?r)
5902 (setq property
5903 (org-ido-completing-read "Property: "
5904 (mapcar 'list (org-buffer-property-keys t))
5905 nil t))))
5907 (message "Sorting entries...")
5909 (save-restriction
5910 (narrow-to-region start end)
5912 (let ((dcst (downcase sorting-type))
5913 (now (current-time)))
5914 (sort-subr
5915 (/= dcst sorting-type)
5916 ;; This function moves to the beginning character of the "record" to
5917 ;; be sorted.
5918 (if plain-list-p
5919 (lambda nil
5920 (if (org-at-item-p) t (goto-char (point-max))))
5921 (lambda nil
5922 (if (re-search-forward re nil t)
5923 (goto-char (match-beginning 0))
5924 (goto-char (point-max)))))
5925 ;; This function moves to the last character of the "record" being
5926 ;; sorted.
5927 (if plain-list-p
5928 'org-end-of-item
5929 (lambda nil
5930 (save-match-data
5931 (condition-case nil
5932 (outline-forward-same-level 1)
5933 (error
5934 (goto-char (point-max)))))))
5936 ;; This function returns the value that gets sorted against.
5937 (if plain-list-p
5938 (lambda nil
5939 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5940 (cond
5941 ((= dcst ?n)
5942 (string-to-number (buffer-substring (match-end 0)
5943 (point-at-eol))))
5944 ((= dcst ?a)
5945 (buffer-substring (match-end 0) (point-at-eol)))
5946 ((= dcst ?t)
5947 (if (re-search-forward org-ts-regexp
5948 (point-at-eol) t)
5949 (org-time-string-to-time (match-string 0))
5950 now))
5951 ((= dcst ?f)
5952 (if getkey-func
5953 (progn
5954 (setq tmp (funcall getkey-func))
5955 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5956 tmp)
5957 (error "Invalid key function `%s'" getkey-func)))
5958 (t (error "Invalid sorting type `%c'" sorting-type)))))
5959 (lambda nil
5960 (cond
5961 ((= dcst ?n)
5962 (if (looking-at org-complex-heading-regexp)
5963 (string-to-number (match-string 4))
5964 nil))
5965 ((= dcst ?a)
5966 (if (looking-at org-complex-heading-regexp)
5967 (funcall case-func (match-string 4))
5968 nil))
5969 ((= dcst ?t)
5970 (if (re-search-forward org-ts-regexp
5971 (save-excursion
5972 (forward-line 2)
5973 (point)) t)
5974 (org-time-string-to-time (match-string 0))
5975 now))
5976 ((= dcst ?p)
5977 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5978 (string-to-char (match-string 2))
5979 org-default-priority))
5980 ((= dcst ?r)
5981 (or (org-entry-get nil property) ""))
5982 ((= dcst ?o)
5983 (if (looking-at org-complex-heading-regexp)
5984 (- 9999 (length (member (match-string 2)
5985 org-todo-keywords-1)))))
5986 ((= dcst ?f)
5987 (if getkey-func
5988 (progn
5989 (setq tmp (funcall getkey-func))
5990 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5991 tmp)
5992 (error "Invalid key function `%s'" getkey-func)))
5993 (t (error "Invalid sorting type `%c'" sorting-type)))))
5995 (cond
5996 ((= dcst ?a) 'string<)
5997 ((= dcst ?t) 'time-less-p)
5998 ((= dcst ?f) compare-func)
5999 (t nil)))))
6000 (message "Sorting entries...done")))
6002 (defun org-do-sort (table what &optional with-case sorting-type)
6003 "Sort TABLE of WHAT according to SORTING-TYPE.
6004 The user will be prompted for the SORTING-TYPE if the call to this
6005 function does not specify it. WHAT is only for the prompt, to indicate
6006 what is being sorted. The sorting key will be extracted from
6007 the car of the elements of the table.
6008 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6009 (unless sorting-type
6010 (message
6011 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6012 what)
6013 (setq sorting-type (read-char-exclusive)))
6014 (let ((dcst (downcase sorting-type))
6015 extractfun comparefun)
6016 ;; Define the appropriate functions
6017 (cond
6018 ((= dcst ?n)
6019 (setq extractfun 'string-to-number
6020 comparefun (if (= dcst sorting-type) '< '>)))
6021 ((= dcst ?a)
6022 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6023 (lambda(x) (downcase (org-sort-remove-invisible x))))
6024 comparefun (if (= dcst sorting-type)
6025 'string<
6026 (lambda (a b) (and (not (string< a b))
6027 (not (string= a b)))))))
6028 ((= dcst ?t)
6029 (setq extractfun
6030 (lambda (x)
6031 (if (or (string-match org-ts-regexp x)
6032 (string-match org-ts-regexp-both x))
6033 (time-to-seconds
6034 (org-time-string-to-time (match-string 0 x)))
6036 comparefun (if (= dcst sorting-type) '< '>)))
6037 (t (error "Invalid sorting type `%c'" sorting-type)))
6039 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6040 table)
6041 (lambda (a b) (funcall comparefun (car a) (car b))))))
6043 ;;; Editing source examples
6045 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6046 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6047 (defvar org-edit-src-force-single-line nil)
6048 (defvar org-edit-src-from-org-mode nil)
6049 (defvar org-edit-src-picture nil)
6051 (define-minor-mode org-exit-edit-mode
6052 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6054 (defun org-edit-src-code ()
6055 "Edit the source code example at point.
6056 An indirect buffer is created, and that buffer is then narrowed to the
6057 example at point and switched to the correct language mode. When done,
6058 exit by killing the buffer with \\[org-edit-src-exit]."
6059 (interactive)
6060 (let ((line (org-current-line))
6061 (case-fold-search t)
6062 (msg (substitute-command-keys
6063 "Edit, then exit with C-c ' (C-c and single quote)"))
6064 (info (org-edit-src-find-region-and-lang))
6065 (org-mode-p (eq major-mode 'org-mode))
6066 beg end lang lang-f single lfmt)
6067 (if (not info)
6069 (setq beg (nth 0 info)
6070 end (nth 1 info)
6071 lang (nth 2 info)
6072 single (nth 3 info)
6073 lfmt (nth 4 info)
6074 lang-f (intern (concat lang "-mode")))
6075 (unless (functionp lang-f)
6076 (error "No such language mode: %s" lang-f))
6077 (goto-line line)
6078 (if (get-buffer "*Org Edit Src Example*")
6079 (kill-buffer "*Org Edit Src Example*"))
6080 (switch-to-buffer (make-indirect-buffer (current-buffer)
6081 "*Org Edit Src Example*"))
6082 (narrow-to-region beg end)
6083 (remove-text-properties beg end '(display nil invisible nil
6084 intangible nil))
6085 (let ((org-inhibit-startup t))
6086 (funcall lang-f))
6087 (set (make-local-variable 'org-edit-src-force-single-line) single)
6088 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6089 (when lfmt
6090 (set (make-local-variable 'org-coderef-label-format) lfmt))
6091 (when org-mode-p
6092 (goto-char (point-min))
6093 (while (re-search-forward "^," nil t)
6094 (replace-match "")))
6095 (goto-line line)
6096 (org-exit-edit-mode)
6097 (org-set-local 'header-line-format msg)
6098 (message "%s" msg)
6099 t)))
6101 (defun org-edit-fixed-width-region ()
6102 "Edit the fixed-width ascii drawing at point.
6103 This must be a region where each line starts with a colon followed by
6104 a space character.
6105 An indirect buffer is created, and that buffer is then narrowed to the
6106 example at point and switched to artist-mode. When done,
6107 exit by killing the buffer with \\[org-edit-src-exit]."
6108 (interactive)
6109 (let ((line (org-current-line))
6110 (case-fold-search t)
6111 (msg (substitute-command-keys
6112 "Edit, then exit with C-c ' (C-c and single quote)"))
6113 (org-mode-p (eq major-mode 'org-mode))
6114 beg end)
6115 (beginning-of-line 1)
6116 (if (looking-at "[ \t]*[^:\n \t]")
6118 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6119 (setq beg (point) end beg)
6120 (save-excursion
6121 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6122 (setq beg (point-at-bol 2))
6123 (setq beg (point))))
6124 (save-excursion
6125 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6126 (setq end (1- (match-beginning 0)))
6127 (setq end (point))))
6128 (goto-line line))
6129 (if (get-buffer "*Org Edit Picture*")
6130 (kill-buffer "*Org Edit Picture*"))
6131 (switch-to-buffer (make-indirect-buffer (current-buffer)
6132 "*Org Edit Picture*"))
6133 (narrow-to-region beg end)
6134 (remove-text-properties beg end '(display nil invisible nil
6135 intangible nil))
6136 (when (fboundp 'font-lock-unfontify-region)
6137 (font-lock-unfontify-region (point-min) (point-max)))
6138 (cond
6139 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6140 (fundamental-mode)
6141 (artist-mode 1))
6142 (t (funcall org-edit-fixed-width-region-mode)))
6143 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6144 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6145 (set (make-local-variable 'org-edit-src-picture) t)
6146 (goto-char (point-min))
6147 (while (re-search-forward "^[ \t]*: ?" nil t)
6148 (replace-match ""))
6149 (goto-line line)
6150 (org-exit-edit-mode)
6151 (org-set-local 'header-line-format msg)
6152 (message "%s" msg)
6153 t)))
6156 (defun org-edit-src-find-region-and-lang ()
6157 "Find the region and language for a local edit.
6158 Return a list with beginning and end of the region, a string representing
6159 the language, a switch telling of the content should be in a single line."
6160 (let ((re-list
6161 (append
6162 org-edit-src-region-extra
6164 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6165 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6166 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6167 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6168 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6169 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6170 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6171 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6172 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6173 ("^#\\+html:" "\n" "html" single-line)
6174 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6175 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6176 ("^#\\+latex:" "\n" "latex" single-line)
6177 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6178 ("^#\\+ascii:" "\n" "ascii" single-line)
6180 (pos (point))
6181 re1 re2 single beg end lang lfmt match-re1)
6182 (catch 'exit
6183 (while (setq entry (pop re-list))
6184 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6185 single (nth 3 entry))
6186 (save-excursion
6187 (if (or (looking-at re1)
6188 (re-search-backward re1 nil t))
6189 (progn
6190 (setq match-re1 (match-string 0))
6191 (setq beg (match-end 0)
6192 lang (org-edit-src-get-lang lang)
6193 lfmt (org-edit-src-get-label-format match-re1))
6194 (if (and (re-search-forward re2 nil t)
6195 (>= (match-end 0) pos))
6196 (throw 'exit (list beg (match-beginning 0)
6197 lang single lfmt))))
6198 (if (or (looking-at re2)
6199 (re-search-forward re2 nil t))
6200 (progn
6201 (setq end (match-beginning 0))
6202 (if (and (re-search-backward re1 nil t)
6203 (<= (match-beginning 0) pos))
6204 (progn
6205 (setq lfmt (org-edit-src-get-label-format
6206 (match-string 0)))
6207 (throw 'exit
6208 (list (match-end 0) end
6209 (org-edit-src-get-lang lang)
6210 single lfmt))))))))))))
6212 (defun org-edit-src-get-lang (lang)
6213 "Extract the src language."
6214 (let ((m (match-string 0)))
6215 (cond
6216 ((stringp lang) lang)
6217 ((integerp lang) (match-string lang))
6218 ((and (eq lang 'lang)
6219 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6220 (match-string 1 m))
6221 ((and (eq lang 'style)
6222 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6223 (match-string 1 m))
6224 (t "fundamental"))))
6226 (defun org-edit-src-get-label-format (s)
6227 "Extract the label format."
6228 (save-match-data
6229 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6230 (match-string 1 s))))
6232 (defun org-edit-src-exit ()
6233 "Exit special edit and protect problematic lines."
6234 (interactive)
6235 (unless (buffer-base-buffer (current-buffer))
6236 (error "This is not an indirect buffer, something is wrong..."))
6237 (unless (> (point-min) 1)
6238 (error "This buffer is not narrowed, something is wrong..."))
6239 (goto-char (point-min))
6240 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6241 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6242 (when (org-bound-and-true-p org-edit-src-force-single-line)
6243 (goto-char (point-min))
6244 (while (re-search-forward "\n" nil t)
6245 (replace-match " "))
6246 (goto-char (point-min))
6247 (if (looking-at "\\s-*") (replace-match " "))
6248 (if (re-search-forward "\\s-+\\'" nil t)
6249 (replace-match "")))
6250 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6251 (goto-char (point-min))
6252 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6253 (replace-match ",\\1"))
6254 (when font-lock-mode
6255 (font-lock-unfontify-region (point-min) (point-max)))
6256 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6257 (when (org-bound-and-true-p org-edit-src-picture)
6258 (untabify (point-min) (point-max))
6259 (goto-char (point-min))
6260 (while (re-search-forward "^" nil t)
6261 (replace-match ": "))
6262 (when font-lock-mode
6263 (font-lock-unfontify-region (point-min) (point-max)))
6264 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6265 (kill-buffer (current-buffer))
6266 (and (org-mode-p) (org-restart-font-lock)))
6269 ;;; The orgstruct minor mode
6271 ;; Define a minor mode which can be used in other modes in order to
6272 ;; integrate the org-mode structure editing commands.
6274 ;; This is really a hack, because the org-mode structure commands use
6275 ;; keys which normally belong to the major mode. Here is how it
6276 ;; works: The minor mode defines all the keys necessary to operate the
6277 ;; structure commands, but wraps the commands into a function which
6278 ;; tests if the cursor is currently at a headline or a plain list
6279 ;; item. If that is the case, the structure command is used,
6280 ;; temporarily setting many Org-mode variables like regular
6281 ;; expressions for filling etc. However, when any of those keys is
6282 ;; used at a different location, function uses `key-binding' to look
6283 ;; up if the key has an associated command in another currently active
6284 ;; keymap (minor modes, major mode, global), and executes that
6285 ;; command. There might be problems if any of the keys is otherwise
6286 ;; used as a prefix key.
6288 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6289 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6290 ;; addresses this by checking explicitly for both bindings.
6292 (defvar orgstruct-mode-map (make-sparse-keymap)
6293 "Keymap for the minor `orgstruct-mode'.")
6295 (defvar org-local-vars nil
6296 "List of local variables, for use by `orgstruct-mode'")
6298 ;;;###autoload
6299 (define-minor-mode orgstruct-mode
6300 "Toggle the minor more `orgstruct-mode'.
6301 This mode is for using Org-mode structure commands in other modes.
6302 The following key behave as if Org-mode was active, if the cursor
6303 is on a headline, or on a plain list item (both in the definition
6304 of Org-mode).
6306 M-up Move entry/item up
6307 M-down Move entry/item down
6308 M-left Promote
6309 M-right Demote
6310 M-S-up Move entry/item up
6311 M-S-down Move entry/item down
6312 M-S-left Promote subtree
6313 M-S-right Demote subtree
6314 M-q Fill paragraph and items like in Org-mode
6315 C-c ^ Sort entries
6316 C-c - Cycle list bullet
6317 TAB Cycle item visibility
6318 M-RET Insert new heading/item
6319 S-M-RET Insert new TODO heading / Checkbox item
6320 C-c C-c Set tags / toggle checkbox"
6321 nil " OrgStruct" nil
6322 (org-load-modules-maybe)
6323 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6325 ;;;###autoload
6326 (defun turn-on-orgstruct ()
6327 "Unconditionally turn on `orgstruct-mode'."
6328 (orgstruct-mode 1))
6330 (defun orgstruct++-mode (&optional arg)
6331 "Toggle `orgstruct-mode', the enhanced version of it.
6332 In addition to setting orgstruct-mode, this also exports all indentation and
6333 autofilling variables from org-mode into the buffer. It will also
6334 recognize item context in multiline items.
6335 Note that turning off orgstruct-mode will *not* remove the
6336 indentation/paragraph settings. This can only be done by refreshing the
6337 major mode, for example with \[normal-mode]."
6338 (interactive "P")
6339 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6340 (if (< arg 1)
6341 (orgstruct-mode -1)
6342 (orgstruct-mode 1)
6343 (let (var val)
6344 (mapc
6345 (lambda (x)
6346 (when (string-match
6347 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6348 (symbol-name (car x)))
6349 (setq var (car x) val (nth 1 x))
6350 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6351 org-local-vars)
6352 (org-set-local 'orgstruct-is-++ t))))
6354 (defvar orgstruct-is-++ nil
6355 "Is orgstruct-mode in ++ version in the current-buffer?")
6356 (make-variable-buffer-local 'orgstruct-is-++)
6358 ;;;###autoload
6359 (defun turn-on-orgstruct++ ()
6360 "Unconditionally turn on `orgstruct++-mode'."
6361 (orgstruct++-mode 1))
6363 (defun orgstruct-error ()
6364 "Error when there is no default binding for a structure key."
6365 (interactive)
6366 (error "This key has no function outside structure elements"))
6368 (defun orgstruct-setup ()
6369 "Setup orgstruct keymaps."
6370 (let ((nfunc 0)
6371 (bindings
6372 (list
6373 '([(meta up)] org-metaup)
6374 '([(meta down)] org-metadown)
6375 '([(meta left)] org-metaleft)
6376 '([(meta right)] org-metaright)
6377 '([(meta shift up)] org-shiftmetaup)
6378 '([(meta shift down)] org-shiftmetadown)
6379 '([(meta shift left)] org-shiftmetaleft)
6380 '([(meta shift right)] org-shiftmetaright)
6381 '([(shift up)] org-shiftup)
6382 '([(shift down)] org-shiftdown)
6383 '([(shift left)] org-shiftleft)
6384 '([(shift right)] org-shiftright)
6385 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6386 '("\M-q" fill-paragraph)
6387 '("\C-c^" org-sort)
6388 '("\C-c-" org-cycle-list-bullet)))
6389 elt key fun cmd)
6390 (while (setq elt (pop bindings))
6391 (setq nfunc (1+ nfunc))
6392 (setq key (org-key (car elt))
6393 fun (nth 1 elt)
6394 cmd (orgstruct-make-binding fun nfunc key))
6395 (org-defkey orgstruct-mode-map key cmd))
6397 ;; Special treatment needed for TAB and RET
6398 (org-defkey orgstruct-mode-map [(tab)]
6399 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6400 (org-defkey orgstruct-mode-map "\C-i"
6401 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6403 (org-defkey orgstruct-mode-map "\M-\C-m"
6404 (orgstruct-make-binding 'org-insert-heading 105
6405 "\M-\C-m" [(meta return)]))
6406 (org-defkey orgstruct-mode-map [(meta return)]
6407 (orgstruct-make-binding 'org-insert-heading 106
6408 [(meta return)] "\M-\C-m"))
6410 (org-defkey orgstruct-mode-map [(shift meta return)]
6411 (orgstruct-make-binding 'org-insert-todo-heading 107
6412 [(meta return)] "\M-\C-m"))
6414 (unless org-local-vars
6415 (setq org-local-vars (org-get-local-variables)))
6419 (defun orgstruct-make-binding (fun n &rest keys)
6420 "Create a function for binding in the structure minor mode.
6421 FUN is the command to call inside a table. N is used to create a unique
6422 command name. KEYS are keys that should be checked in for a command
6423 to execute outside of tables."
6424 (eval
6425 (list 'defun
6426 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6427 '(arg)
6428 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6429 "Outside of structure, run the binding of `"
6430 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6431 "'.")
6432 '(interactive "p")
6433 (list 'if
6434 `(org-context-p 'headline 'item
6435 (and orgstruct-is-++
6436 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6437 'item-body))
6438 (list 'org-run-like-in-org-mode (list 'quote fun))
6439 (list 'let '(orgstruct-mode)
6440 (list 'call-interactively
6441 (append '(or)
6442 (mapcar (lambda (k)
6443 (list 'key-binding k))
6444 keys)
6445 '('orgstruct-error))))))))
6447 (defun org-context-p (&rest contexts)
6448 "Check if local context is any of CONTEXTS.
6449 Possible values in the list of contexts are `table', `headline', and `item'."
6450 (let ((pos (point)))
6451 (goto-char (point-at-bol))
6452 (prog1 (or (and (memq 'table contexts)
6453 (looking-at "[ \t]*|"))
6454 (and (memq 'headline contexts)
6455 ;;????????? (looking-at "\\*+"))
6456 (looking-at outline-regexp))
6457 (and (memq 'item contexts)
6458 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6459 (and (memq 'item-body contexts)
6460 (org-in-item-p)))
6461 (goto-char pos))))
6463 (defun org-get-local-variables ()
6464 "Return a list of all local variables in an org-mode buffer."
6465 (let (varlist)
6466 (with-current-buffer (get-buffer-create "*Org tmp*")
6467 (erase-buffer)
6468 (org-mode)
6469 (setq varlist (buffer-local-variables)))
6470 (kill-buffer "*Org tmp*")
6471 (delq nil
6472 (mapcar
6473 (lambda (x)
6474 (setq x
6475 (if (symbolp x)
6476 (list x)
6477 (list (car x) (list 'quote (cdr x)))))
6478 (if (string-match
6479 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6480 (symbol-name (car x)))
6481 x nil))
6482 varlist))))
6484 ;;;###autoload
6485 (defun org-run-like-in-org-mode (cmd)
6486 "Run a command, pretending that the current buffer is in Org-mode.
6487 This will temporarily bind local variables that are typically bound in
6488 Org-mode to the values they have in Org-mode, and then interactively
6489 call CMD."
6490 (org-load-modules-maybe)
6491 (unless org-local-vars
6492 (setq org-local-vars (org-get-local-variables)))
6493 (eval (list 'let org-local-vars
6494 (list 'call-interactively (list 'quote cmd)))))
6496 ;;;; Archiving
6498 (defun org-get-category (&optional pos)
6499 "Get the category applying to position POS."
6500 (get-text-property (or pos (point)) 'org-category))
6502 (defun org-refresh-category-properties ()
6503 "Refresh category text properties in the buffer."
6504 (let ((def-cat (cond
6505 ((null org-category)
6506 (if buffer-file-name
6507 (file-name-sans-extension
6508 (file-name-nondirectory buffer-file-name))
6509 "???"))
6510 ((symbolp org-category) (symbol-name org-category))
6511 (t org-category)))
6512 beg end cat pos optionp)
6513 (org-unmodified
6514 (save-excursion
6515 (save-restriction
6516 (widen)
6517 (goto-char (point-min))
6518 (put-text-property (point) (point-max) 'org-category def-cat)
6519 (while (re-search-forward
6520 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6521 (setq pos (match-end 0)
6522 optionp (equal (char-after (match-beginning 0)) ?#)
6523 cat (org-trim (match-string 2)))
6524 (if optionp
6525 (setq beg (point-at-bol) end (point-max))
6526 (org-back-to-heading t)
6527 (setq beg (point) end (org-end-of-subtree t t)))
6528 (put-text-property beg end 'org-category cat)
6529 (goto-char pos)))))))
6532 ;;;; Link Stuff
6534 ;;; Link abbreviations
6536 (defun org-link-expand-abbrev (link)
6537 "Apply replacements as defined in `org-link-abbrev-alist."
6538 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6539 (let* ((key (match-string 1 link))
6540 (as (or (assoc key org-link-abbrev-alist-local)
6541 (assoc key org-link-abbrev-alist)))
6542 (tag (and (match-end 2) (match-string 3 link)))
6543 rpl)
6544 (if (not as)
6545 link
6546 (setq rpl (cdr as))
6547 (cond
6548 ((symbolp rpl) (funcall rpl tag))
6549 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6550 ((string-match "%h" rpl)
6551 (replace-match (url-hexify-string (or tag "")) t t rpl))
6552 (t (concat rpl tag)))))
6553 link))
6555 ;;; Storing and inserting links
6557 (defvar org-insert-link-history nil
6558 "Minibuffer history for links inserted with `org-insert-link'.")
6560 (defvar org-stored-links nil
6561 "Contains the links stored with `org-store-link'.")
6563 (defvar org-store-link-plist nil
6564 "Plist with info about the most recently link created with `org-store-link'.")
6566 (defvar org-link-protocols nil
6567 "Link protocols added to Org-mode using `org-add-link-type'.")
6569 (defvar org-store-link-functions nil
6570 "List of functions that are called to create and store a link.
6571 Each function will be called in turn until one returns a non-nil
6572 value. Each function should check if it is responsible for creating
6573 this link (for example by looking at the major mode).
6574 If not, it must exit and return nil.
6575 If yes, it should return a non-nil value after a calling
6576 `org-store-link-props' with a list of properties and values.
6577 Special properties are:
6579 :type The link prefix. like \"http\". This must be given.
6580 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6581 This is obligatory as well.
6582 :description Optional default description for the second pair
6583 of brackets in an Org-mode link. The user can still change
6584 this when inserting this link into an Org-mode buffer.
6586 In addition to these, any additional properties can be specified
6587 and then used in remember templates.")
6589 (defun org-add-link-type (type &optional follow export)
6590 "Add TYPE to the list of `org-link-types'.
6591 Re-compute all regular expressions depending on `org-link-types'
6593 FOLLOW and EXPORT are two functions.
6595 FOLLOW should take the link path as the single argument and do whatever
6596 is necessary to follow the link, for example find a file or display
6597 a mail message.
6599 EXPORT should format the link path for export to one of the export formats.
6600 It should be a function accepting three arguments:
6602 path the path of the link, the text after the prefix (like \"http:\")
6603 desc the description of the link, if any, nil if there was no description
6604 format the export format, a symbol like `html' or `latex'.
6606 The function may use the FORMAT information to return different values
6607 depending on the format. The return value will be put literally into
6608 the exported file.
6609 Org-mode has a built-in default for exporting links. If you are happy with
6610 this default, there is no need to define an export function for the link
6611 type. For a simple example of an export function, see `org-bbdb.el'."
6612 (add-to-list 'org-link-types type t)
6613 (org-make-link-regexps)
6614 (if (assoc type org-link-protocols)
6615 (setcdr (assoc type org-link-protocols) (list follow export))
6616 (push (list type follow export) org-link-protocols)))
6618 ;;;###autoload
6619 (defun org-store-link (arg)
6620 "\\<org-mode-map>Store an org-link to the current location.
6621 This link is added to `org-stored-links' and can later be inserted
6622 into an org-buffer with \\[org-insert-link].
6624 For some link types, a prefix arg is interpreted:
6625 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6626 For file links, arg negates `org-context-in-file-links'."
6627 (interactive "P")
6628 (org-load-modules-maybe)
6629 (setq org-store-link-plist nil) ; reset
6630 (let (link cpltxt desc description search txt)
6631 (cond
6633 ((run-hook-with-args-until-success 'org-store-link-functions)
6634 (setq link (plist-get org-store-link-plist :link)
6635 desc (or (plist-get org-store-link-plist :description) link)))
6637 ((equal (buffer-name) "*Org Edit Src Example*")
6638 (let (label gc)
6639 (while (or (not label)
6640 (save-excursion
6641 (save-restriction
6642 (widen)
6643 (goto-char (point-min))
6644 (re-search-forward
6645 (regexp-quote (format org-coderef-label-format label))
6646 nil t))))
6647 (when label (message "Label exists already") (sit-for 2))
6648 (setq label (read-string "Code line label: " label)))
6649 (end-of-line 1)
6650 (setq link (format org-coderef-label-format label))
6651 (setq gc (- 79 (length link)))
6652 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6653 (insert link)
6654 (setq link (concat "(" label ")") desc nil)))
6656 ((eq major-mode 'calendar-mode)
6657 (let ((cd (calendar-cursor-to-date)))
6658 (setq link
6659 (format-time-string
6660 (car org-time-stamp-formats)
6661 (apply 'encode-time
6662 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6663 nil nil nil))))
6664 (org-store-link-props :type "calendar" :date cd)))
6666 ((eq major-mode 'w3-mode)
6667 (setq cpltxt (url-view-url t)
6668 link (org-make-link cpltxt))
6669 (org-store-link-props :type "w3" :url (url-view-url t)))
6671 ((eq major-mode 'w3m-mode)
6672 (setq cpltxt (or w3m-current-title w3m-current-url)
6673 link (org-make-link w3m-current-url))
6674 (org-store-link-props :type "w3m" :url (url-view-url t)))
6676 ((setq search (run-hook-with-args-until-success
6677 'org-create-file-search-functions))
6678 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6679 "::" search))
6680 (setq cpltxt (or description link)))
6682 ((eq major-mode 'image-mode)
6683 (setq cpltxt (concat "file:"
6684 (abbreviate-file-name buffer-file-name))
6685 link (org-make-link cpltxt))
6686 (org-store-link-props :type "image" :file buffer-file-name))
6688 ((eq major-mode 'dired-mode)
6689 ;; link to the file in the current line
6690 (setq cpltxt (concat "file:"
6691 (abbreviate-file-name
6692 (expand-file-name
6693 (dired-get-filename nil t))))
6694 link (org-make-link cpltxt)))
6696 ((and buffer-file-name (org-mode-p))
6697 (cond
6698 ((org-in-regexp "<<\\(.*?\\)>>")
6699 (setq cpltxt
6700 (concat "file:"
6701 (abbreviate-file-name buffer-file-name)
6702 "::" (match-string 1))
6703 link (org-make-link cpltxt)))
6704 ((and (featurep 'org-id)
6705 (or (eq org-link-to-org-use-id t)
6706 (and (eq org-link-to-org-use-id 'create-if-interactive)
6707 (interactive-p))
6708 (and org-link-to-org-use-id
6709 (condition-case nil
6710 (org-entry-get nil "ID")
6711 (error nil)))))
6712 ;; We can make a link using the ID.
6713 (setq link (condition-case nil
6714 (prog1 (org-id-store-link)
6715 (setq desc (plist-get org-store-link-plist
6716 :description)))
6717 (error
6718 ;; probably before first headline, link to file only
6719 (concat "file:"
6720 (abbreviate-file-name buffer-file-name))))))
6722 ;; Just link to current headline
6723 (setq cpltxt (concat "file:"
6724 (abbreviate-file-name buffer-file-name)))
6725 ;; Add a context search string
6726 (when (org-xor org-context-in-file-links arg)
6727 (setq txt (cond
6728 ((org-on-heading-p) nil)
6729 ((org-region-active-p)
6730 (buffer-substring (region-beginning) (region-end)))
6731 (t nil)))
6732 (when (or (null txt) (string-match "\\S-" txt))
6733 (setq cpltxt
6734 (concat cpltxt "::"
6735 (condition-case nil
6736 (org-make-org-heading-search-string txt)
6737 (error "")))
6738 desc "NONE")))
6739 (if (string-match "::\\'" cpltxt)
6740 (setq cpltxt (substring cpltxt 0 -2)))
6741 (setq link (org-make-link cpltxt)))))
6743 ((buffer-file-name (buffer-base-buffer))
6744 ;; Just link to this file here.
6745 (setq cpltxt (concat "file:"
6746 (abbreviate-file-name
6747 (buffer-file-name (buffer-base-buffer)))))
6748 ;; Add a context string
6749 (when (org-xor org-context-in-file-links arg)
6750 (setq txt (if (org-region-active-p)
6751 (buffer-substring (region-beginning) (region-end))
6752 (buffer-substring (point-at-bol) (point-at-eol))))
6753 ;; Only use search option if there is some text.
6754 (when (string-match "\\S-" txt)
6755 (setq cpltxt
6756 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6757 desc "NONE")))
6758 (setq link (org-make-link cpltxt)))
6760 ((interactive-p)
6761 (error "Cannot link to a buffer which is not visiting a file"))
6763 (t (setq link nil)))
6765 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6766 (setq link (or link cpltxt)
6767 desc (or desc cpltxt))
6768 (if (equal desc "NONE") (setq desc nil))
6770 (if (and (interactive-p) link)
6771 (progn
6772 (setq org-stored-links
6773 (cons (list link desc) org-stored-links))
6774 (message "Stored: %s" (or desc link)))
6775 (and link (org-make-link-string link desc)))))
6777 (defun org-store-link-props (&rest plist)
6778 "Store link properties, extract names and addresses."
6779 (let (x adr)
6780 (when (setq x (plist-get plist :from))
6781 (setq adr (mail-extract-address-components x))
6782 (setq plist (plist-put plist :fromname (car adr)))
6783 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6784 (when (setq x (plist-get plist :to))
6785 (setq adr (mail-extract-address-components x))
6786 (setq plist (plist-put plist :toname (car adr)))
6787 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6788 (let ((from (plist-get plist :from))
6789 (to (plist-get plist :to)))
6790 (when (and from to org-from-is-user-regexp)
6791 (setq plist
6792 (plist-put plist :fromto
6793 (if (string-match org-from-is-user-regexp from)
6794 (concat "to %t")
6795 (concat "from %f"))))))
6796 (setq org-store-link-plist plist))
6798 (defun org-add-link-props (&rest plist)
6799 "Add these properties to the link property list."
6800 (let (key value)
6801 (while plist
6802 (setq key (pop plist) value (pop plist))
6803 (setq org-store-link-plist
6804 (plist-put org-store-link-plist key value)))))
6806 (defun org-email-link-description (&optional fmt)
6807 "Return the description part of an email link.
6808 This takes information from `org-store-link-plist' and formats it
6809 according to FMT (default from `org-email-link-description-format')."
6810 (setq fmt (or fmt org-email-link-description-format))
6811 (let* ((p org-store-link-plist)
6812 (to (plist-get p :toaddress))
6813 (from (plist-get p :fromaddress))
6814 (table
6815 (list
6816 (cons "%c" (plist-get p :fromto))
6817 (cons "%F" (plist-get p :from))
6818 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6819 (cons "%T" (plist-get p :to))
6820 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6821 (cons "%s" (plist-get p :subject))
6822 (cons "%m" (plist-get p :message-id)))))
6823 (when (string-match "%c" fmt)
6824 ;; Check if the user wrote this message
6825 (if (and org-from-is-user-regexp from to
6826 (save-match-data (string-match org-from-is-user-regexp from)))
6827 (setq fmt (replace-match "to %t" t t fmt))
6828 (setq fmt (replace-match "from %f" t t fmt))))
6829 (org-replace-escapes fmt table)))
6831 (defun org-make-org-heading-search-string (&optional string heading)
6832 "Make search string for STRING or current headline."
6833 (interactive)
6834 (let ((s (or string (org-get-heading))))
6835 (unless (and string (not heading))
6836 ;; We are using a headline, clean up garbage in there.
6837 (if (string-match org-todo-regexp s)
6838 (setq s (replace-match "" t t s)))
6839 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6840 (setq s (replace-match "" t t s)))
6841 (setq s (org-trim s))
6842 (if (string-match (concat "^\\(" org-quote-string "\\|"
6843 org-comment-string "\\)") s)
6844 (setq s (replace-match "" t t s)))
6845 (while (string-match org-ts-regexp s)
6846 (setq s (replace-match "" t t s))))
6847 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6848 (setq s (replace-match " " t t s)))
6849 (or string (setq s (concat "*" s))) ; Add * for headlines
6850 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6852 (defun org-make-link (&rest strings)
6853 "Concatenate STRINGS."
6854 (apply 'concat strings))
6856 (defun org-make-link-string (link &optional description)
6857 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6858 (unless (string-match "\\S-" link)
6859 (error "Empty link"))
6860 (when (stringp description)
6861 ;; Remove brackets from the description, they are fatal.
6862 (while (string-match "\\[" description)
6863 (setq description (replace-match "{" t t description)))
6864 (while (string-match "\\]" description)
6865 (setq description (replace-match "}" t t description))))
6866 (when (equal (org-link-escape link) description)
6867 ;; No description needed, it is identical
6868 (setq description nil))
6869 (when (and (not description)
6870 (not (equal link (org-link-escape link))))
6871 (setq description (org-extract-attributes link)))
6872 (concat "[[" (org-link-escape link) "]"
6873 (if description (concat "[" description "]") "")
6874 "]"))
6876 (defconst org-link-escape-chars
6877 '((?\ . "%20")
6878 (?\[ . "%5B")
6879 (?\] . "%5D")
6880 (?\340 . "%E0") ; `a
6881 (?\342 . "%E2") ; ^a
6882 (?\347 . "%E7") ; ,c
6883 (?\350 . "%E8") ; `e
6884 (?\351 . "%E9") ; 'e
6885 (?\352 . "%EA") ; ^e
6886 (?\356 . "%EE") ; ^i
6887 (?\364 . "%F4") ; ^o
6888 (?\371 . "%F9") ; `u
6889 (?\373 . "%FB") ; ^u
6890 (?\; . "%3B")
6891 (?? . "%3F")
6892 (?= . "%3D")
6893 (?+ . "%2B")
6895 "Association list of escapes for some characters problematic in links.
6896 This is the list that is used for internal purposes.")
6898 (defconst org-link-escape-chars-browser
6899 '((?\ . "%20")) ; 32 for the SPC char
6900 "Association list of escapes for some characters problematic in links.
6901 This is the list that is used before handing over to the browser.")
6903 (defun org-link-escape (text &optional table)
6904 "Escape characters in TEXT that are problematic for links."
6905 (setq table (or table org-link-escape-chars))
6906 (when text
6907 (let ((re (mapconcat (lambda (x) (regexp-quote
6908 (char-to-string (car x))))
6909 table "\\|")))
6910 (while (string-match re text)
6911 (setq text
6912 (replace-match
6913 (cdr (assoc (string-to-char (match-string 0 text))
6914 table))
6915 t t text)))
6916 text)))
6918 (defun org-link-unescape (text &optional table)
6919 "Reverse the action of `org-link-escape'."
6920 (setq table (or table org-link-escape-chars))
6921 (when text
6922 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6923 table "\\|")))
6924 (while (string-match re text)
6925 (setq text
6926 (replace-match
6927 (char-to-string (car (rassoc (match-string 0 text) table)))
6928 t t text)))
6929 text)))
6931 (defun org-xor (a b)
6932 "Exclusive or."
6933 (if a (not b) b))
6935 (defun org-fixup-message-id-for-http (s)
6936 "Replace special characters in a message id, so it can be used in an http query."
6937 (while (string-match "<" s)
6938 (setq s (replace-match "%3C" t t s)))
6939 (while (string-match ">" s)
6940 (setq s (replace-match "%3E" t t s)))
6941 (while (string-match "@" s)
6942 (setq s (replace-match "%40" t t s)))
6945 ;;;###autoload
6946 (defun org-insert-link-global ()
6947 "Insert a link like Org-mode does.
6948 This command can be called in any mode to insert a link in Org-mode syntax."
6949 (interactive)
6950 (org-load-modules-maybe)
6951 (org-run-like-in-org-mode 'org-insert-link))
6953 (defun org-insert-link (&optional complete-file link-location)
6954 "Insert a link. At the prompt, enter the link.
6956 Completion can be used to insert any of the link protocol prefixes like
6957 http or ftp in use.
6959 The history can be used to select a link previously stored with
6960 `org-store-link'. When the empty string is entered (i.e. if you just
6961 press RET at the prompt), the link defaults to the most recently
6962 stored link. As SPC triggers completion in the minibuffer, you need to
6963 use M-SPC or C-q SPC to force the insertion of a space character.
6965 You will also be prompted for a description, and if one is given, it will
6966 be displayed in the buffer instead of the link.
6968 If there is already a link at point, this command will allow you to edit link
6969 and description parts.
6971 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6972 be selected using completion. The path to the file will be relative to the
6973 current directory if the file is in the current directory or a subdirectory.
6974 Otherwise, the link will be the absolute path as completed in the minibuffer
6975 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6976 option `org-link-file-path-type'.
6978 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6979 the current directory or below.
6981 With three \\[universal-argument] prefixes, negate the meaning of
6982 `org-keep-stored-link-after-insertion'.
6984 If `org-make-link-description-function' is non-nil, this function will be
6985 called with the link target, and the result will be the default
6986 link description.
6988 If the LINK-LOCATION parameter is non-nil, this value will be
6989 used as the link location instead of reading one interactively."
6990 (interactive "P")
6991 (let* ((wcf (current-window-configuration))
6992 (region (if (org-region-active-p)
6993 (buffer-substring (region-beginning) (region-end))))
6994 (remove (and region (list (region-beginning) (region-end))))
6995 (desc region)
6996 tmphist ; byte-compile incorrectly complains about this
6997 (link link-location)
6998 entry file)
6999 (cond
7000 (link-location) ; specified by arg, just use it.
7001 ((org-in-regexp org-bracket-link-regexp 1)
7002 ;; We do have a link at point, and we are going to edit it.
7003 (setq remove (list (match-beginning 0) (match-end 0)))
7004 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7005 (setq link (read-string "Link: "
7006 (org-link-unescape
7007 (org-match-string-no-properties 1)))))
7008 ((or (org-in-regexp org-angle-link-re)
7009 (org-in-regexp org-plain-link-re))
7010 ;; Convert to bracket link
7011 (setq remove (list (match-beginning 0) (match-end 0))
7012 link (read-string "Link: "
7013 (org-remove-angle-brackets (match-string 0)))))
7014 ((member complete-file '((4) (16)))
7015 ;; Completing read for file names.
7016 (setq file (read-file-name "File: "))
7017 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7018 (pwd1 (file-name-as-directory (abbreviate-file-name
7019 (expand-file-name ".")))))
7020 (cond
7021 ((equal complete-file '(16))
7022 (setq link (org-make-link
7023 "file:"
7024 (abbreviate-file-name (expand-file-name file)))))
7025 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7026 (setq link (org-make-link "file:" (match-string 1 file))))
7027 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7028 (expand-file-name file))
7029 (setq link (org-make-link
7030 "file:" (match-string 1 (expand-file-name file)))))
7031 (t (setq link (org-make-link "file:" file))))))
7033 ;; Read link, with completion for stored links.
7034 (with-output-to-temp-buffer "*Org Links*"
7035 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7036 (when org-stored-links
7037 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7038 (princ (mapconcat
7039 (lambda (x)
7040 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7041 (reverse org-stored-links) "\n"))))
7042 (let ((cw (selected-window)))
7043 (select-window (get-buffer-window "*Org Links*"))
7044 (setq truncate-lines t)
7045 (org-fit-window-to-buffer)
7046 (select-window cw))
7047 ;; Fake a link history, containing the stored links.
7048 (setq tmphist (append (mapcar 'car org-stored-links)
7049 org-insert-link-history))
7050 (unwind-protect
7051 (setq link
7052 (let ((org-completion-use-ido nil))
7053 (org-completing-read
7054 "Link: "
7055 (append
7056 (mapcar (lambda (x) (list (concat (car x) ":")))
7057 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7058 (mapcar (lambda (x) (list (concat x ":")))
7059 org-link-types))
7060 nil nil nil
7061 'tmphist
7062 (or (car (car org-stored-links))))))
7063 (set-window-configuration wcf)
7064 (kill-buffer "*Org Links*"))
7065 (setq entry (assoc link org-stored-links))
7066 (or entry (push link org-insert-link-history))
7067 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7068 (not org-keep-stored-link-after-insertion))
7069 (setq org-stored-links (delq (assoc link org-stored-links)
7070 org-stored-links)))
7071 (setq desc (or desc (nth 1 entry)))))
7073 (if (string-match org-plain-link-re link)
7074 ;; URL-like link, normalize the use of angular brackets.
7075 (setq link (org-make-link (org-remove-angle-brackets link))))
7077 ;; Check if we are linking to the current file with a search option
7078 ;; If yes, simplify the link by using only the search option.
7079 (when (and buffer-file-name
7080 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7081 (let* ((path (match-string 1 link))
7082 (case-fold-search nil)
7083 (search (match-string 2 link)))
7084 (save-match-data
7085 (if (equal (file-truename buffer-file-name) (file-truename path))
7086 ;; We are linking to this same file, with a search option
7087 (setq link search)))))
7089 ;; Check if we can/should use a relative path. If yes, simplify the link
7090 (when (string-match "^file:\\(.*\\)" link)
7091 (let* ((path (match-string 1 link))
7092 (origpath path)
7093 (case-fold-search nil))
7094 (cond
7095 ((or (eq org-link-file-path-type 'absolute)
7096 (equal complete-file '(16)))
7097 (setq path (abbreviate-file-name (expand-file-name path))))
7098 ((eq org-link-file-path-type 'noabbrev)
7099 (setq path (expand-file-name path)))
7100 ((eq org-link-file-path-type 'relative)
7101 (setq path (file-relative-name path)))
7103 (save-match-data
7104 (if (string-match (concat "^" (regexp-quote
7105 (file-name-as-directory
7106 (expand-file-name "."))))
7107 (expand-file-name path))
7108 ;; We are linking a file with relative path name.
7109 (setq path (substring (expand-file-name path)
7110 (match-end 0)))
7111 (setq path (abbreviate-file-name (expand-file-name path)))))))
7112 (setq link (concat "file:" path))
7113 (if (equal desc origpath)
7114 (setq desc path))))
7116 (if org-make-link-description-function
7117 (setq desc (funcall org-make-link-description-function link desc)))
7119 (setq desc (read-string "Description: " desc))
7120 (unless (string-match "\\S-" desc) (setq desc nil))
7121 (if remove (apply 'delete-region remove))
7122 (insert (org-make-link-string link desc))))
7124 (defun org-completing-read (&rest args)
7125 "Completing-read with SPACE being a normal character."
7126 (let ((minibuffer-local-completion-map
7127 (copy-keymap minibuffer-local-completion-map)))
7128 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7129 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7130 (apply 'org-ido-completing-read args)))
7132 (defun org-completing-read-no-ido (&rest args)
7133 (let (org-completion-use-ido)
7134 (apply 'org-completing-read args)))
7136 (defun org-ido-completing-read (&rest args)
7137 "Completing-read using `ido-mode' speedups if available"
7138 (if (and org-completion-use-ido
7139 (fboundp 'ido-completing-read)
7140 (boundp 'ido-mode) ido-mode
7141 (listp (second args)))
7142 (let ((ido-enter-matching-directory nil))
7143 (apply 'ido-completing-read (concat (car args))
7144 (mapcar (lambda (x) (car x)) (nth 1 args))
7145 (cddr args)))
7146 (apply 'completing-read args)))
7149 (defun org-extract-attributes (s)
7150 "Extract the attributes cookie from a string and set as text property."
7151 (let (a attr (start 0) key value)
7152 (save-match-data
7153 (when (string-match "{{\\([^}]+\\)}}$" s)
7154 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7155 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7156 (setq key (match-string 1 a) value (match-string 2 a)
7157 start (match-end 0)
7158 attr (plist-put attr (intern key) value))))
7159 (org-add-props s nil 'org-attr attr))
7162 (defun org-attributes-to-string (plist)
7163 "Format a property list into an HTML attribute list."
7164 (let ((s "") key value)
7165 (while plist
7166 (setq key (pop plist) value (pop plist))
7167 (and value
7168 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7171 ;;; Opening/following a link
7173 (defvar org-link-search-failed nil)
7175 (defun org-next-link ()
7176 "Move forward to the next link.
7177 If the link is in hidden text, expose it."
7178 (interactive)
7179 (when (and org-link-search-failed (eq this-command last-command))
7180 (goto-char (point-min))
7181 (message "Link search wrapped back to beginning of buffer"))
7182 (setq org-link-search-failed nil)
7183 (let* ((pos (point))
7184 (ct (org-context))
7185 (a (assoc :link ct)))
7186 (if a (goto-char (nth 2 a)))
7187 (if (re-search-forward org-any-link-re nil t)
7188 (progn
7189 (goto-char (match-beginning 0))
7190 (if (org-invisible-p) (org-show-context)))
7191 (goto-char pos)
7192 (setq org-link-search-failed t)
7193 (error "No further link found"))))
7195 (defun org-previous-link ()
7196 "Move backward to the previous link.
7197 If the link is in hidden text, expose it."
7198 (interactive)
7199 (when (and org-link-search-failed (eq this-command last-command))
7200 (goto-char (point-max))
7201 (message "Link search wrapped back to end of buffer"))
7202 (setq org-link-search-failed nil)
7203 (let* ((pos (point))
7204 (ct (org-context))
7205 (a (assoc :link ct)))
7206 (if a (goto-char (nth 1 a)))
7207 (if (re-search-backward org-any-link-re nil t)
7208 (progn
7209 (goto-char (match-beginning 0))
7210 (if (org-invisible-p) (org-show-context)))
7211 (goto-char pos)
7212 (setq org-link-search-failed t)
7213 (error "No further link found"))))
7215 (defun org-translate-link (s)
7216 "Translate a link string if a translation function has been defined."
7217 (if (and org-link-translation-function
7218 (fboundp org-link-translation-function)
7219 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7220 (progn
7221 (setq s (funcall org-link-translation-function
7222 (match-string 1) (match-string 2)))
7223 (concat (car s) ":" (cdr s)))
7226 (defun org-translate-link-from-planner (type path)
7227 "Translate a link from Emacs Planner syntax so that Org can follow it.
7228 This is still an experimental function, your mileage may vary."
7229 (cond
7230 ((member type '("http" "https" "news" "ftp"))
7231 ;; standard Internet links are the same.
7232 nil)
7233 ((and (equal type "irc") (string-match "^//" path))
7234 ;; Planner has two / at the beginning of an irc link, we have 1.
7235 ;; We should have zero, actually....
7236 (setq path (substring path 1)))
7237 ((and (equal type "lisp") (string-match "^/" path))
7238 ;; Planner has a slash, we do not.
7239 (setq type "elisp" path (substring path 1)))
7240 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7241 ;; A typical message link. Planner has the id after the fina slash,
7242 ;; we separate it with a hash mark
7243 (setq path (concat (match-string 1 path) "#"
7244 (org-remove-angle-brackets (match-string 2 path)))))
7246 (cons type path))
7248 (defun org-find-file-at-mouse (ev)
7249 "Open file link or URL at mouse."
7250 (interactive "e")
7251 (mouse-set-point ev)
7252 (org-open-at-point 'in-emacs))
7254 (defun org-open-at-mouse (ev)
7255 "Open file link or URL at mouse."
7256 (interactive "e")
7257 (mouse-set-point ev)
7258 (if (eq major-mode 'org-agenda-mode)
7259 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7260 (org-open-at-point))
7262 (defvar org-window-config-before-follow-link nil
7263 "The window configuration before following a link.
7264 This is saved in case the need arises to restore it.")
7266 (defvar org-open-link-marker (make-marker)
7267 "Marker pointing to the location where `org-open-at-point; was called.")
7269 ;;;###autoload
7270 (defun org-open-at-point-global ()
7271 "Follow a link like Org-mode does.
7272 This command can be called in any mode to follow a link that has
7273 Org-mode syntax."
7274 (interactive)
7275 (org-run-like-in-org-mode 'org-open-at-point))
7277 ;;;###autoload
7278 (defun org-open-link-from-string (s &optional arg)
7279 "Open a link in the string S, as if it was in Org-mode."
7280 (interactive "sLink: \nP")
7281 (with-temp-buffer
7282 (let ((org-inhibit-startup t))
7283 (org-mode)
7284 (insert s)
7285 (goto-char (point-min))
7286 (org-open-at-point arg))))
7288 (defun org-open-at-point (&optional in-emacs)
7289 "Open link at or after point.
7290 If there is no link at point, this function will search forward up to
7291 the end of the current subtree.
7292 Normally, files will be opened by an appropriate application. If the
7293 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7294 With a double prefix argument, try to open outside of Emacs, in the
7295 application the system uses for this file type."
7296 (interactive "P")
7297 (org-load-modules-maybe)
7298 (move-marker org-open-link-marker (point))
7299 (setq org-window-config-before-follow-link (current-window-configuration))
7300 (org-remove-occur-highlights nil nil t)
7301 (cond
7302 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7303 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7304 (org-footnote-action))
7306 (let (type path link line search (pos (point)))
7307 (catch 'match
7308 (save-excursion
7309 (skip-chars-forward "^]\n\r")
7310 (when (org-in-regexp org-bracket-link-regexp)
7311 (setq link (org-extract-attributes
7312 (org-link-unescape (org-match-string-no-properties 1))))
7313 (while (string-match " *\n *" link)
7314 (setq link (replace-match " " t t link)))
7315 (setq link (org-link-expand-abbrev link))
7316 (cond
7317 ((or (file-name-absolute-p link)
7318 (string-match "^\\.\\.?/" link))
7319 (setq type "file" path link))
7320 ((string-match org-link-re-with-space3 link)
7321 (setq type (match-string 1 link) path (match-string 2 link)))
7322 (t (setq type "thisfile" path link)))
7323 (throw 'match t)))
7325 (when (get-text-property (point) 'org-linked-text)
7326 (setq type "thisfile"
7327 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7328 (1+ (point)) (point))
7329 path (buffer-substring
7330 (previous-single-property-change pos 'org-linked-text)
7331 (next-single-property-change pos 'org-linked-text)))
7332 (throw 'match t))
7334 (save-excursion
7335 (when (or (org-in-regexp org-angle-link-re)
7336 (org-in-regexp org-plain-link-re))
7337 (setq type (match-string 1) path (match-string 2))
7338 (throw 'match t)))
7339 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7340 (setq type "tree-match"
7341 path (match-string 1))
7342 (throw 'match t))
7343 (save-excursion
7344 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7345 (setq type "tags"
7346 path (match-string 1))
7347 (while (string-match ":" path)
7348 (setq path (replace-match "+" t t path)))
7349 (throw 'match t))))
7350 (unless path
7351 (error "No link found"))
7352 ;; Remove any trailing spaces in path
7353 (if (string-match " +\\'" path)
7354 (setq path (replace-match "" t t path)))
7355 (if (and org-link-translation-function
7356 (fboundp org-link-translation-function))
7357 ;; Check if we need to translate the link
7358 (let ((tmp (funcall org-link-translation-function type path)))
7359 (setq type (car tmp) path (cdr tmp))))
7361 (cond
7363 ((assoc type org-link-protocols)
7364 (funcall (nth 1 (assoc type org-link-protocols)) path))
7366 ((equal type "mailto")
7367 (let ((cmd (car org-link-mailto-program))
7368 (args (cdr org-link-mailto-program)) args1
7369 (address path) (subject "") a)
7370 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7371 (setq address (match-string 1 path)
7372 subject (org-link-escape (match-string 2 path))))
7373 (while args
7374 (cond
7375 ((not (stringp (car args))) (push (pop args) args1))
7376 (t (setq a (pop args))
7377 (if (string-match "%a" a)
7378 (setq a (replace-match address t t a)))
7379 (if (string-match "%s" a)
7380 (setq a (replace-match subject t t a)))
7381 (push a args1))))
7382 (apply cmd (nreverse args1))))
7384 ((member type '("http" "https" "ftp" "news"))
7385 (browse-url (concat type ":" (org-link-escape
7386 path org-link-escape-chars-browser))))
7388 ((member type '("message"))
7389 (browse-url (concat type ":" path)))
7391 ((string= type "tags")
7392 (org-tags-view in-emacs path))
7393 ((string= type "thisfile")
7394 (if in-emacs
7395 (switch-to-buffer-other-window
7396 (org-get-buffer-for-internal-link (current-buffer)))
7397 (org-mark-ring-push))
7398 (let ((cmd `(org-link-search
7399 ,path
7400 ,(cond ((equal in-emacs '(4)) 'occur)
7401 ((equal in-emacs '(16)) 'org-occur)
7402 (t nil))
7403 ,pos)))
7404 (condition-case nil (eval cmd)
7405 (error (progn (widen) (eval cmd))))))
7407 ((string= type "tree-match")
7408 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7410 ((string= type "file")
7411 (if (string-match "::\\([0-9]+\\)\\'" path)
7412 (setq line (string-to-number (match-string 1 path))
7413 path (substring path 0 (match-beginning 0)))
7414 (if (string-match "::\\(.+\\)\\'" path)
7415 (setq search (match-string 1 path)
7416 path (substring path 0 (match-beginning 0)))))
7417 (if (string-match "[*?{]" (file-name-nondirectory path))
7418 (dired path)
7419 (org-open-file path in-emacs line search)))
7421 ((string= type "news")
7422 (require 'org-gnus)
7423 (org-gnus-follow-link path))
7425 ((string= type "shell")
7426 (let ((cmd path))
7427 (if (or (not org-confirm-shell-link-function)
7428 (funcall org-confirm-shell-link-function
7429 (format "Execute \"%s\" in shell? "
7430 (org-add-props cmd nil
7431 'face 'org-warning))))
7432 (progn
7433 (message "Executing %s" cmd)
7434 (shell-command cmd))
7435 (error "Abort"))))
7437 ((string= type "elisp")
7438 (let ((cmd path))
7439 (if (or (not org-confirm-elisp-link-function)
7440 (funcall org-confirm-elisp-link-function
7441 (format "Execute \"%s\" as elisp? "
7442 (org-add-props cmd nil
7443 'face 'org-warning))))
7444 (message "%s => %s" cmd
7445 (if (equal (string-to-char cmd) ?\()
7446 (eval (read cmd))
7447 (call-interactively (read cmd))))
7448 (error "Abort"))))
7451 (browse-url-at-point))))))
7452 (move-marker org-open-link-marker nil)
7453 (run-hook-with-args 'org-follow-link-hook))
7455 ;;;; Time estimates
7457 (defun org-get-effort (&optional pom)
7458 "Get the effort estimate for the current entry."
7459 (org-entry-get pom org-effort-property))
7461 ;;; File search
7463 (defvar org-create-file-search-functions nil
7464 "List of functions to construct the right search string for a file link.
7465 These functions are called in turn with point at the location to
7466 which the link should point.
7468 A function in the hook should first test if it would like to
7469 handle this file type, for example by checking the major-mode or
7470 the file extension. If it decides not to handle this file, it
7471 should just return nil to give other functions a chance. If it
7472 does handle the file, it must return the search string to be used
7473 when following the link. The search string will be part of the
7474 file link, given after a double colon, and `org-open-at-point'
7475 will automatically search for it. If special measures must be
7476 taken to make the search successful, another function should be
7477 added to the companion hook `org-execute-file-search-functions',
7478 which see.
7480 A function in this hook may also use `setq' to set the variable
7481 `description' to provide a suggestion for the descriptive text to
7482 be used for this link when it gets inserted into an Org-mode
7483 buffer with \\[org-insert-link].")
7485 (defvar org-execute-file-search-functions nil
7486 "List of functions to execute a file search triggered by a link.
7488 Functions added to this hook must accept a single argument, the
7489 search string that was part of the file link, the part after the
7490 double colon. The function must first check if it would like to
7491 handle this search, for example by checking the major-mode or the
7492 file extension. If it decides not to handle this search, it
7493 should just return nil to give other functions a chance. If it
7494 does handle the search, it must return a non-nil value to keep
7495 other functions from trying.
7497 Each function can access the current prefix argument through the
7498 variable `current-prefix-argument'. Note that a single prefix is
7499 used to force opening a link in Emacs, so it may be good to only
7500 use a numeric or double prefix to guide the search function.
7502 In case this is needed, a function in this hook can also restore
7503 the window configuration before `org-open-at-point' was called using:
7505 (set-window-configuration org-window-config-before-follow-link)")
7507 (defun org-link-search (s &optional type avoid-pos)
7508 "Search for a link search option.
7509 If S is surrounded by forward slashes, it is interpreted as a
7510 regular expression. In org-mode files, this will create an `org-occur'
7511 sparse tree. In ordinary files, `occur' will be used to list matches.
7512 If the current buffer is in `dired-mode', grep will be used to search
7513 in all files. If AVOID-POS is given, ignore matches near that position."
7514 (let ((case-fold-search t)
7515 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7516 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7517 (append '(("") (" ") ("\t") ("\n"))
7518 org-emphasis-alist)
7519 "\\|") "\\)"))
7520 (pos (point))
7521 (pre nil) (post nil)
7522 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7523 (cond
7524 ;; First check if there are any special
7525 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7526 ;; Now try the builtin stuff
7527 ((save-excursion
7528 (goto-char (point-min))
7529 (and
7530 (re-search-forward
7531 (concat "<<" (regexp-quote s0) ">>") nil t)
7532 (setq type 'dedicated
7533 pos (match-beginning 0))))
7534 ;; There is an exact target for this
7535 (goto-char pos))
7536 ((and (string-match "^(\\(.*\\))$" s0)
7537 (save-excursion
7538 (goto-char (point-min))
7539 (and
7540 (re-search-forward
7541 (concat "[^[]" (regexp-quote
7542 (format org-coderef-label-format
7543 (match-string 1 s0))))
7544 nil t)
7545 (setq type 'dedicated
7546 pos (1+ (match-beginning 0))))))
7547 ;; There is a coderef target for this
7548 (goto-char pos))
7549 ((string-match "^/\\(.*\\)/$" s)
7550 ;; A regular expression
7551 (cond
7552 ((org-mode-p)
7553 (org-occur (match-string 1 s)))
7554 ;;((eq major-mode 'dired-mode)
7555 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7556 (t (org-do-occur (match-string 1 s)))))
7558 ;; A normal search strings
7559 (when (equal (string-to-char s) ?*)
7560 ;; Anchor on headlines, post may include tags.
7561 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7562 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7563 s (substring s 1)))
7564 (remove-text-properties
7565 0 (length s)
7566 '(face nil mouse-face nil keymap nil fontified nil) s)
7567 ;; Make a series of regular expressions to find a match
7568 (setq words (org-split-string s "[ \n\r\t]+")
7570 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7571 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7572 "\\)" markers)
7573 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7574 re2a (concat "[ \t\r\n]" re2a_)
7575 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7576 re4 (concat "[^a-zA-Z_]" re4_)
7578 re1 (concat pre re2 post)
7579 re3 (concat pre (if pre re4_ re4) post)
7580 re5 (concat pre ".*" re4)
7581 re2 (concat pre re2)
7582 re2a (concat pre (if pre re2a_ re2a))
7583 re4 (concat pre (if pre re4_ re4))
7584 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7585 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7586 re5 "\\)"
7588 (cond
7589 ((eq type 'org-occur) (org-occur reall))
7590 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7591 (t (goto-char (point-min))
7592 (setq type 'fuzzy)
7593 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7594 (org-search-not-self 1 re1 nil t)
7595 (org-search-not-self 1 re2 nil t)
7596 (org-search-not-self 1 re2a nil t)
7597 (org-search-not-self 1 re3 nil t)
7598 (org-search-not-self 1 re4 nil t)
7599 (org-search-not-self 1 re5 nil t)
7601 (goto-char (match-beginning 1))
7602 (goto-char pos)
7603 (error "No match")))))
7605 ;; Normal string-search
7606 (goto-char (point-min))
7607 (if (search-forward s nil t)
7608 (goto-char (match-beginning 0))
7609 (error "No match"))))
7610 (and (org-mode-p) (org-show-context 'link-search))
7611 type))
7613 (defun org-search-not-self (group &rest args)
7614 "Execute `re-search-forward', but only accept matches that do not
7615 enclose the position of `org-open-link-marker'."
7616 (let ((m org-open-link-marker))
7617 (catch 'exit
7618 (while (apply 're-search-forward args)
7619 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7620 (goto-char (match-end group))
7621 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7622 (> (match-beginning 0) (marker-position m))
7623 (< (match-end 0) (marker-position m)))
7624 (save-match-data
7625 (or (not (org-in-regexp
7626 org-bracket-link-analytic-regexp 1))
7627 (not (match-end 4)) ; no description
7628 (and (<= (match-beginning 4) (point))
7629 (>= (match-end 4) (point))))))
7630 (throw 'exit (point))))))))
7632 (defun org-get-buffer-for-internal-link (buffer)
7633 "Return a buffer to be used for displaying the link target of internal links."
7634 (cond
7635 ((not org-display-internal-link-with-indirect-buffer)
7636 buffer)
7637 ((string-match "(Clone)$" (buffer-name buffer))
7638 (message "Buffer is already a clone, not making another one")
7639 ;; we also do not modify visibility in this case
7640 buffer)
7641 (t ; make a new indirect buffer for displaying the link
7642 (let* ((bn (buffer-name buffer))
7643 (ibn (concat bn "(Clone)"))
7644 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7645 (with-current-buffer ib (org-overview))
7646 ib))))
7648 (defun org-do-occur (regexp &optional cleanup)
7649 "Call the Emacs command `occur'.
7650 If CLEANUP is non-nil, remove the printout of the regular expression
7651 in the *Occur* buffer. This is useful if the regex is long and not useful
7652 to read."
7653 (occur regexp)
7654 (when cleanup
7655 (let ((cwin (selected-window)) win beg end)
7656 (when (setq win (get-buffer-window "*Occur*"))
7657 (select-window win))
7658 (goto-char (point-min))
7659 (when (re-search-forward "match[a-z]+" nil t)
7660 (setq beg (match-end 0))
7661 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7662 (setq end (1- (match-beginning 0)))))
7663 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7664 (goto-char (point-min))
7665 (select-window cwin))))
7667 ;;; The mark ring for links jumps
7669 (defvar org-mark-ring nil
7670 "Mark ring for positions before jumps in Org-mode.")
7671 (defvar org-mark-ring-last-goto nil
7672 "Last position in the mark ring used to go back.")
7673 ;; Fill and close the ring
7674 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7675 (loop for i from 1 to org-mark-ring-length do
7676 (push (make-marker) org-mark-ring))
7677 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7678 org-mark-ring)
7680 (defun org-mark-ring-push (&optional pos buffer)
7681 "Put the current position or POS into the mark ring and rotate it."
7682 (interactive)
7683 (setq pos (or pos (point)))
7684 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7685 (move-marker (car org-mark-ring)
7686 (or pos (point))
7687 (or buffer (current-buffer)))
7688 (message "%s"
7689 (substitute-command-keys
7690 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7692 (defun org-mark-ring-goto (&optional n)
7693 "Jump to the previous position in the mark ring.
7694 With prefix arg N, jump back that many stored positions. When
7695 called several times in succession, walk through the entire ring.
7696 Org-mode commands jumping to a different position in the current file,
7697 or to another Org-mode file, automatically push the old position
7698 onto the ring."
7699 (interactive "p")
7700 (let (p m)
7701 (if (eq last-command this-command)
7702 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7703 (setq p org-mark-ring))
7704 (setq org-mark-ring-last-goto p)
7705 (setq m (car p))
7706 (switch-to-buffer (marker-buffer m))
7707 (goto-char m)
7708 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7710 (defun org-remove-angle-brackets (s)
7711 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7712 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7714 (defun org-add-angle-brackets (s)
7715 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7716 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7718 (defun org-remove-double-quotes (s)
7719 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7720 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7723 ;;; Following specific links
7725 (defun org-follow-timestamp-link ()
7726 (cond
7727 ((org-at-date-range-p t)
7728 (let ((org-agenda-start-on-weekday)
7729 (t1 (match-string 1))
7730 (t2 (match-string 2)))
7731 (setq t1 (time-to-days (org-time-string-to-time t1))
7732 t2 (time-to-days (org-time-string-to-time t2)))
7733 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7734 ((org-at-timestamp-p t)
7735 (org-agenda-list nil (time-to-days (org-time-string-to-time
7736 (substring (match-string 1) 0 10)))
7738 (t (error "This should not happen"))))
7741 ;;; Following file links
7742 (defvar org-wait nil)
7743 (defun org-open-file (path &optional in-emacs line search)
7744 "Open the file at PATH.
7745 First, this expands any special file name abbreviations. Then the
7746 configuration variable `org-file-apps' is checked if it contains an
7747 entry for this file type, and if yes, the corresponding command is launched.
7749 If no application is found, Emacs simply visits the file.
7751 With optional prefix argument IN-EMACS, Emacs will visit the file.
7752 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7753 and o use an external application to visit the file.
7755 Optional LINE specifies a line to go to, optional SEARCH a string to
7756 search for. If LINE or SEARCH is given, the file will always be
7757 opened in Emacs.
7758 If the file does not exist, an error is thrown."
7759 (setq in-emacs (or in-emacs line search))
7760 (let* ((file (if (equal path "")
7761 buffer-file-name
7762 (substitute-in-file-name (expand-file-name path))))
7763 (apps (append org-file-apps (org-default-apps)))
7764 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7765 (dirp (if remp nil (file-directory-p file)))
7766 (file (if (and dirp org-open-directory-means-index-dot-org)
7767 (concat (file-name-as-directory file) "index.org")
7768 file))
7769 (a-m-a-p (assq 'auto-mode apps))
7770 (dfile (downcase file))
7771 (old-buffer (current-buffer))
7772 (old-pos (point))
7773 (old-mode major-mode)
7774 ext cmd)
7775 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7776 (setq ext (match-string 1 dfile))
7777 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7778 (setq ext (match-string 1 dfile))))
7779 (cond
7780 ((equal in-emacs '(16))
7781 (setq cmd (cdr (assoc 'system apps))))
7782 (in-emacs (setq cmd 'emacs))
7784 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7785 (and dirp (cdr (assoc 'directory apps)))
7786 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7787 'string-match)
7788 (cdr (assoc ext apps))
7789 (cdr (assoc t apps))))))
7790 (when (eq cmd 'system)
7791 (setq cmd (cdr (assoc 'system apps))))
7792 (when (eq cmd 'default)
7793 (setq cmd (cdr (assoc t apps))))
7794 (when (eq cmd 'mailcap)
7795 (require 'mailcap)
7796 (mailcap-parse-mailcaps)
7797 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7798 (command (mailcap-mime-info mime-type)))
7799 (if (stringp command)
7800 (setq cmd command)
7801 (setq cmd 'emacs))))
7802 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7803 (not (file-exists-p file))
7804 (not org-open-non-existing-files))
7805 (error "No such file: %s" file))
7806 (cond
7807 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7808 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7809 (while (string-match "['\"]%s['\"]" cmd)
7810 (setq cmd (replace-match "%s" t t cmd)))
7811 (while (string-match "%s" cmd)
7812 (setq cmd (replace-match
7813 (save-match-data
7814 (shell-quote-argument
7815 (convert-standard-filename file)))
7816 t t cmd)))
7817 (save-window-excursion
7818 (start-process-shell-command cmd nil cmd)
7819 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7821 ((or (stringp cmd)
7822 (eq cmd 'emacs))
7823 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7824 (widen)
7825 (if line (goto-line line)
7826 (if search (org-link-search search))))
7827 ((consp cmd)
7828 (let ((file (convert-standard-filename file)))
7829 (eval cmd)))
7830 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7831 (and (org-mode-p) (eq old-mode 'org-mode)
7832 (or (not (equal old-buffer (current-buffer)))
7833 (not (equal old-pos (point))))
7834 (org-mark-ring-push old-pos old-buffer))))
7836 (defun org-default-apps ()
7837 "Return the default applications for this operating system."
7838 (cond
7839 ((eq system-type 'darwin)
7840 org-file-apps-defaults-macosx)
7841 ((eq system-type 'windows-nt)
7842 org-file-apps-defaults-windowsnt)
7843 (t org-file-apps-defaults-gnu)))
7845 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7846 "Convert extensions to regular expressions in the cars of LIST.
7847 Also, weed out any non-string entries, because the return value is used
7848 only for regexp matching.
7849 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7850 point to the symbol `emacs', indicating that the file should
7851 be opened in Emacs."
7852 (append
7853 (delq nil
7854 (mapcar (lambda (x)
7855 (if (not (stringp (car x)))
7857 (if (string-match "\\W" (car x))
7859 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7860 list))
7861 (if add-auto-mode
7862 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7864 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7865 (defun org-file-remote-p (file)
7866 "Test whether FILE specifies a location on a remote system.
7867 Return non-nil if the location is indeed remote.
7869 For example, the filename \"/user@host:/foo\" specifies a location
7870 on the system \"/user@host:\"."
7871 (cond ((fboundp 'file-remote-p)
7872 (file-remote-p file))
7873 ((fboundp 'tramp-handle-file-remote-p)
7874 (tramp-handle-file-remote-p file))
7875 ((and (boundp 'ange-ftp-name-format)
7876 (string-match (car ange-ftp-name-format) file))
7878 (t nil)))
7881 ;;;; Refiling
7883 (defun org-get-org-file ()
7884 "Read a filename, with default directory `org-directory'."
7885 (let ((default (or org-default-notes-file remember-data-file)))
7886 (read-file-name (format "File name [%s]: " default)
7887 (file-name-as-directory org-directory)
7888 default)))
7890 (defun org-notes-order-reversed-p ()
7891 "Check if the current file should receive notes in reversed order."
7892 (cond
7893 ((not org-reverse-note-order) nil)
7894 ((eq t org-reverse-note-order) t)
7895 ((not (listp org-reverse-note-order)) nil)
7896 (t (catch 'exit
7897 (let ((all org-reverse-note-order)
7898 entry)
7899 (while (setq entry (pop all))
7900 (if (string-match (car entry) buffer-file-name)
7901 (throw 'exit (cdr entry))))
7902 nil)))))
7904 (defvar org-refile-target-table nil
7905 "The list of refile targets, created by `org-refile'.")
7907 (defvar org-agenda-new-buffers nil
7908 "Buffers created to visit agenda files.")
7910 (defun org-get-refile-targets (&optional default-buffer)
7911 "Produce a table with refile targets."
7912 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7913 targets txt re files f desc descre fast-path-p level)
7914 (message "Getting targets...")
7915 (with-current-buffer (or default-buffer (current-buffer))
7916 (while (setq entry (pop entries))
7917 (setq files (car entry) desc (cdr entry))
7918 (setq fast-path-p nil)
7919 (cond
7920 ((null files) (setq files (list (current-buffer))))
7921 ((eq files 'org-agenda-files)
7922 (setq files (org-agenda-files 'unrestricted)))
7923 ((and (symbolp files) (fboundp files))
7924 (setq files (funcall files)))
7925 ((and (symbolp files) (boundp files))
7926 (setq files (symbol-value files))))
7927 (if (stringp files) (setq files (list files)))
7928 (cond
7929 ((eq (car desc) :tag)
7930 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7931 ((eq (car desc) :todo)
7932 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7933 ((eq (car desc) :regexp)
7934 (setq descre (cdr desc)))
7935 ((eq (car desc) :level)
7936 (setq descre (concat "^\\*\\{" (number-to-string
7937 (if org-odd-levels-only
7938 (1- (* 2 (cdr desc)))
7939 (cdr desc)))
7940 "\\}[ \t]")))
7941 ((eq (car desc) :maxlevel)
7942 (setq fast-path-p t)
7943 (setq descre (concat "^\\*\\{1," (number-to-string
7944 (if org-odd-levels-only
7945 (1- (* 2 (cdr desc)))
7946 (cdr desc)))
7947 "\\}[ \t]")))
7948 (t (error "Bad refiling target description %s" desc)))
7949 (while (setq f (pop files))
7950 (save-excursion
7951 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7952 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7953 (setq f (expand-file-name f))
7954 (save-excursion
7955 (save-restriction
7956 (widen)
7957 (goto-char (point-min))
7958 (while (re-search-forward descre nil t)
7959 (goto-char (point-at-bol))
7960 (when (looking-at org-complex-heading-regexp)
7961 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7962 txt (org-link-display-format (match-string 4))
7963 re (concat "^" (regexp-quote
7964 (buffer-substring (match-beginning 1)
7965 (match-end 4)))))
7966 (if (match-end 5) (setq re (concat re "[ \t]+"
7967 (regexp-quote
7968 (match-string 5)))))
7969 (setq re (concat re "[ \t]*$"))
7970 (when org-refile-use-outline-path
7971 (setq txt (mapconcat 'org-protect-slash
7972 (append
7973 (if (eq org-refile-use-outline-path 'file)
7974 (list (file-name-nondirectory
7975 (buffer-file-name (buffer-base-buffer))))
7976 (if (eq org-refile-use-outline-path 'full-file-path)
7977 (list (buffer-file-name (buffer-base-buffer)))))
7978 (org-get-outline-path fast-path-p level txt)
7979 (list txt))
7980 "/")))
7981 (push (list txt f re (point)) targets))
7982 (goto-char (point-at-eol))))))))
7983 (message "Getting targets...done")
7984 (nreverse targets))))
7986 (defun org-protect-slash (s)
7987 (while (string-match "/" s)
7988 (setq s (replace-match "\\" t t s)))
7991 (defvar org-olpa (make-vector 20 nil))
7993 (defun org-get-outline-path (&optional fastp level heading)
7994 "Return the outline path to the current entry, as a list."
7995 (if fastp
7996 (progn
7997 (if (> level 19)
7998 (error "Outline path failure, more than 19 levels."))
7999 (loop for i from level upto 19 do
8000 (aset org-olpa i nil))
8001 (prog1
8002 (delq nil (append org-olpa nil))
8003 (aset org-olpa level heading)))
8004 (let (rtn)
8005 (save-excursion
8006 (while (org-up-heading-safe)
8007 (when (looking-at org-complex-heading-regexp)
8008 (push (org-match-string-no-properties 4) rtn)))
8009 rtn))))
8011 (defvar org-refile-history nil
8012 "History for refiling operations.")
8014 (defun org-refile (&optional goto default-buffer)
8015 "Move the entry at point to another heading.
8016 The list of target headings is compiled using the information in
8017 `org-refile-targets', which see. This list is created before each use
8018 and will therefore always be up-to-date.
8020 At the target location, the entry is filed as a subitem of the target heading.
8021 Depending on `org-reverse-note-order', the new subitem will either be the
8022 first or the last subitem.
8024 If there is an active region, all entries in that region will be moved.
8025 However, the region must fulfil the requirement that the first heading
8026 is the first one sets the top-level of the moved text - at most siblings
8027 below it are allowed.
8029 With prefix arg GOTO, the command will only visit the target location,
8030 not actually move anything.
8031 With a double prefix `C-u C-u', go to the location where the last refiling
8032 operation has put the subtree."
8033 (interactive "P")
8034 (let* ((cbuf (current-buffer))
8035 (regionp (org-region-active-p))
8036 (region-start (and regionp (region-beginning)))
8037 (region-end (and regionp (region-end)))
8038 (region-length (and regionp (- region-end region-start)))
8039 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8040 pos it nbuf file re level reversed)
8041 (when regionp (goto-char region-start)
8042 (unless (org-kill-is-subtree-p
8043 (buffer-substring region-start region-end))
8044 (error "The region is not a (sequence of) subtree(s)")))
8045 (if (equal goto '(16))
8046 (org-refile-goto-last-stored)
8047 (when (setq it (org-refile-get-location
8048 (if goto "Goto: " "Refile to: ") default-buffer))
8049 (setq file (nth 1 it)
8050 re (nth 2 it)
8051 pos (nth 3 it))
8052 (if (and (equal (buffer-file-name) file)
8053 (if regionp
8054 (and (>= pos region-start)
8055 (<= pos region-end))
8056 (and (>= pos (point))
8057 (< pos (save-excursion
8058 (org-end-of-subtree t t))))))
8059 (error "Cannot refile to position inside the tree or region"))
8061 (setq nbuf (or (find-buffer-visiting file)
8062 (find-file-noselect file)))
8063 (if goto
8064 (progn
8065 (switch-to-buffer nbuf)
8066 (goto-char pos)
8067 (org-show-context 'org-goto))
8068 (if regionp
8069 (progn
8070 (kill-new (buffer-substring region-start region-end))
8071 (org-save-markers-in-region region-start region-end))
8072 (org-copy-subtree 1 nil t))
8073 (save-excursion
8074 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8075 (find-file-noselect file))))
8076 (setq reversed (org-notes-order-reversed-p))
8077 (save-excursion
8078 (save-restriction
8079 (widen)
8080 (goto-char pos)
8081 (looking-at outline-regexp)
8082 (setq level (org-get-valid-level (funcall outline-level) 1))
8083 (goto-char
8084 (if reversed
8085 (or (outline-next-heading) (point-max))
8086 (or (save-excursion (outline-get-next-sibling))
8087 (org-end-of-subtree t t)
8088 (point-max))))
8089 (if (not (bolp)) (newline))
8090 (bookmark-set "org-refile-last-stored")
8091 (org-paste-subtree level))))
8092 (if regionp
8093 (delete-region (point) (+ (point) region-length))
8094 (org-cut-subtree))
8095 (setq org-markers-to-move nil)
8096 (message "Refiled to \"%s\"" (car it)))))))
8098 (defun org-refile-goto-last-stored ()
8099 "Go to the location where the last refile was stored."
8100 (interactive)
8101 (bookmark-jump "org-refile-last-stored")
8102 (message "This is the location of the last refile"))
8104 (defun org-refile-get-location (&optional prompt default-buffer)
8105 "Prompt the user for a refile location, using PROMPT."
8106 (let ((org-refile-targets org-refile-targets)
8107 (org-refile-use-outline-path org-refile-use-outline-path))
8108 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8109 (unless org-refile-target-table
8110 (error "No refile targets"))
8111 (let* ((cbuf (current-buffer))
8112 (partial-completion-mode nil)
8113 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8114 (cfunc (if (and org-refile-use-outline-path
8115 org-outline-path-complete-in-steps)
8116 'org-olpath-completing-read
8117 'org-ido-completing-read))
8118 (extra (if org-refile-use-outline-path "/" ""))
8119 (filename (and cfn (expand-file-name cfn)))
8120 (tbl (mapcar
8121 (lambda (x)
8122 (if (not (equal filename (nth 1 x)))
8123 (cons (concat (car x) extra " ("
8124 (file-name-nondirectory (nth 1 x)) ")")
8125 (cdr x))
8126 (cons (concat (car x) extra) (cdr x))))
8127 org-refile-target-table))
8128 (completion-ignore-case t))
8129 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8130 tbl)))
8132 (defun org-olpath-completing-read (prompt collection &rest args)
8133 "Read an outline path like a file name."
8134 (let ((thetable collection)
8135 (org-completion-use-ido nil)) ; does not work with ido.
8136 (apply
8137 'org-ido-completing-read prompt
8138 (lambda (string predicate &optional flag)
8139 (let (rtn r f (l (length string)))
8140 (cond
8141 ((eq flag nil)
8142 ;; try completion
8143 (try-completion string thetable))
8144 ((eq flag t)
8145 ;; all-completions
8146 (setq rtn (all-completions string thetable predicate))
8147 (mapcar
8148 (lambda (x)
8149 (setq r (substring x l))
8150 (if (string-match " ([^)]*)$" x)
8151 (setq f (match-string 0 x))
8152 (setq f ""))
8153 (if (string-match "/" r)
8154 (concat string (substring r 0 (match-end 0)) f)
8156 rtn))
8157 ((eq flag 'lambda)
8158 ;; exact match?
8159 (assoc string thetable)))
8161 args)))
8163 ;;;; Dynamic blocks
8165 (defun org-find-dblock (name)
8166 "Find the first dynamic block with name NAME in the buffer.
8167 If not found, stay at current position and return nil."
8168 (let (pos)
8169 (save-excursion
8170 (goto-char (point-min))
8171 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8172 nil t)
8173 (match-beginning 0))))
8174 (if pos (goto-char pos))
8175 pos))
8177 (defconst org-dblock-start-re
8178 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8179 "Matches the startline of a dynamic block, with parameters.")
8181 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8182 "Matches the end of a dynamic block.")
8184 (defun org-create-dblock (plist)
8185 "Create a dynamic block section, with parameters taken from PLIST.
8186 PLIST must contain a :name entry which is used as name of the block."
8187 (unless (bolp) (newline))
8188 (let ((name (plist-get plist :name)))
8189 (insert "#+BEGIN: " name)
8190 (while plist
8191 (if (eq (car plist) :name)
8192 (setq plist (cddr plist))
8193 (insert " " (prin1-to-string (pop plist)))))
8194 (insert "\n\n#+END:\n")
8195 (beginning-of-line -2)))
8197 (defun org-prepare-dblock ()
8198 "Prepare dynamic block for refresh.
8199 This empties the block, puts the cursor at the insert position and returns
8200 the property list including an extra property :name with the block name."
8201 (unless (looking-at org-dblock-start-re)
8202 (error "Not at a dynamic block"))
8203 (let* ((begdel (1+ (match-end 0)))
8204 (name (org-no-properties (match-string 1)))
8205 (params (append (list :name name)
8206 (read (concat "(" (match-string 3) ")")))))
8207 (unless (re-search-forward org-dblock-end-re nil t)
8208 (error "Dynamic block not terminated"))
8209 (setq params
8210 (append params
8211 (list :content (buffer-substring
8212 begdel (match-beginning 0)))))
8213 (delete-region begdel (match-beginning 0))
8214 (goto-char begdel)
8215 (open-line 1)
8216 params))
8218 (defun org-map-dblocks (&optional command)
8219 "Apply COMMAND to all dynamic blocks in the current buffer.
8220 If COMMAND is not given, use `org-update-dblock'."
8221 (let ((cmd (or command 'org-update-dblock))
8222 pos)
8223 (save-excursion
8224 (goto-char (point-min))
8225 (while (re-search-forward org-dblock-start-re nil t)
8226 (goto-char (setq pos (match-beginning 0)))
8227 (condition-case nil
8228 (funcall cmd)
8229 (error (message "Error during update of dynamic block")))
8230 (goto-char pos)
8231 (unless (re-search-forward org-dblock-end-re nil t)
8232 (error "Dynamic block not terminated"))))))
8234 (defun org-dblock-update (&optional arg)
8235 "User command for updating dynamic blocks.
8236 Update the dynamic block at point. With prefix ARG, update all dynamic
8237 blocks in the buffer."
8238 (interactive "P")
8239 (if arg
8240 (org-update-all-dblocks)
8241 (or (looking-at org-dblock-start-re)
8242 (org-beginning-of-dblock))
8243 (org-update-dblock)))
8245 (defun org-update-dblock ()
8246 "Update the dynamic block at point
8247 This means to empty the block, parse for parameters and then call
8248 the correct writing function."
8249 (save-window-excursion
8250 (let* ((pos (point))
8251 (line (org-current-line))
8252 (params (org-prepare-dblock))
8253 (name (plist-get params :name))
8254 (cmd (intern (concat "org-dblock-write:" name))))
8255 (message "Updating dynamic block `%s' at line %d..." name line)
8256 (funcall cmd params)
8257 (message "Updating dynamic block `%s' at line %d...done" name line)
8258 (goto-char pos))))
8260 (defun org-beginning-of-dblock ()
8261 "Find the beginning of the dynamic block at point.
8262 Error if there is no such block at point."
8263 (let ((pos (point))
8264 beg)
8265 (end-of-line 1)
8266 (if (and (re-search-backward org-dblock-start-re nil t)
8267 (setq beg (match-beginning 0))
8268 (re-search-forward org-dblock-end-re nil t)
8269 (> (match-end 0) pos))
8270 (goto-char beg)
8271 (goto-char pos)
8272 (error "Not in a dynamic block"))))
8274 (defun org-update-all-dblocks ()
8275 "Update all dynamic blocks in the buffer.
8276 This function can be used in a hook."
8277 (when (org-mode-p)
8278 (org-map-dblocks 'org-update-dblock)))
8281 ;;;; Completion
8283 (defconst org-additional-option-like-keywords
8284 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8285 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8286 "BEGIN_EXAMPLE" "END_EXAMPLE"
8287 "BEGIN_QUOTE" "END_QUOTE"
8288 "BEGIN_VERSE" "END_VERSE"
8289 "BEGIN_SRC" "END_SRC"
8290 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8292 (defcustom org-structure-template-alist
8294 ("s" "#+begin_src ?\n\n#+end_src"
8295 "<src lang=\"?\">\n\n</src>")
8296 ("e" "#+begin_example\n?\n#+end_example"
8297 "<example>\n?\n</example>")
8298 ("q" "#+begin_quote\n?\n#+end_quote"
8299 "<quote>\n?\n</quote>")
8300 ("v" "#+begin_verse\n?\n#+end_verse"
8301 "<verse>\n?\n/verse>")
8302 ("l" "#+begin_latex\n?\n#+end_latex"
8303 "<literal style=\"latex\">\n?\n</literal>")
8304 ("L" "#+latex: "
8305 "<literal style=\"latex\">?</literal>")
8306 ("h" "#+begin_html\n?\n#+end_html"
8307 "<literal style=\"html\">\n?\n</literal>")
8308 ("H" "#+html: "
8309 "<literal style=\"html\">?</literal>")
8310 ("a" "#+begin_ascii\n?\n#+end_ascii")
8311 ("A" "#+ascii: ")
8312 ("i" "#+include %file ?"
8313 "<include file=%file markup=\"?\">")
8315 "Structure completion elements.
8316 This is a list of abbreviation keys and values. The value gets inserted
8317 it you type @samp{.} followed by the key and then the completion key,
8318 usually `M-TAB'. %file will be replaced by a file name after prompting
8319 for the file using completion.
8320 There are two templates for each key, the first uses the original Org syntax,
8321 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8322 the default when the /org-mtags.el/ module has been loaded. See also the
8323 variable `org-mtags-prefer-muse-templates'.
8324 This is an experimental feature, it is undecided if it is going to stay in."
8325 :group 'org-completion
8326 :type '(repeat
8327 (string :tag "Key")
8328 (string :tag "Template")
8329 (string :tag "Muse Template")))
8331 (defun org-try-structure-completion ()
8332 "Try to complete a structure template before point.
8333 This looks for strings like \"<e\" on an otherwise empty line and
8334 expands them."
8335 (let ((l (buffer-substring (point-at-bol) (point)))
8337 (when (and (looking-at "[ \t]*$")
8338 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8339 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8340 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8341 (match-beginning 1)) a)
8342 t)))
8344 (defun org-complete-expand-structure-template (start cell)
8345 "Expand a structure template."
8346 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8347 (rpl (nth (if musep 2 1) cell)))
8348 (delete-region start (point))
8349 (when (string-match "\\`#\\+" rpl)
8350 (cond
8351 ((bolp))
8352 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8353 (delete-region (point-at-bol) (point)))
8354 (t (newline))))
8355 (setq start (point))
8356 (if (string-match "%file" rpl)
8357 (setq rpl (replace-match
8358 (concat
8359 "\""
8360 (save-match-data
8361 (abbreviate-file-name (read-file-name "Include file: ")))
8362 "\"")
8363 t t rpl)))
8364 (insert rpl)
8365 (if (re-search-backward "\\?" start t) (delete-char 1))))
8368 (defun org-complete (&optional arg)
8369 "Perform completion on word at point.
8370 At the beginning of a headline, this completes TODO keywords as given in
8371 `org-todo-keywords'.
8372 If the current word is preceded by a backslash, completes the TeX symbols
8373 that are supported for HTML support.
8374 If the current word is preceded by \"#+\", completes special words for
8375 setting file options.
8376 In the line after \"#+STARTUP:, complete valid keywords.\"
8377 At all other locations, this simply calls the value of
8378 `org-completion-fallback-command'."
8379 (interactive "P")
8380 (org-without-partial-completion
8381 (catch 'exit
8382 (let* ((a nil)
8383 (end (point))
8384 (beg1 (save-excursion
8385 (skip-chars-backward (org-re "[:alnum:]_@"))
8386 (point)))
8387 (beg (save-excursion
8388 (skip-chars-backward "a-zA-Z0-9_:$")
8389 (point)))
8390 (confirm (lambda (x) (stringp (car x))))
8391 (searchhead (equal (char-before beg) ?*))
8392 (struct
8393 (when (and (member (char-before beg1) '(?. ?<))
8394 (setq a (assoc (buffer-substring beg1 (point))
8395 org-structure-template-alist)))
8396 (org-complete-expand-structure-template (1- beg1) a)
8397 (throw 'exit t)))
8398 (tag (and (equal (char-before beg1) ?:)
8399 (equal (char-after (point-at-bol)) ?*)))
8400 (prop (and (equal (char-before beg1) ?:)
8401 (not (equal (char-after (point-at-bol)) ?*))))
8402 (texp (equal (char-before beg) ?\\))
8403 (link (equal (char-before beg) ?\[))
8404 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8405 beg)
8406 "#+"))
8407 (startup (string-match "^#\\+STARTUP:.*"
8408 (buffer-substring (point-at-bol) (point))))
8409 (completion-ignore-case opt)
8410 (type nil)
8411 (tbl nil)
8412 (table (cond
8413 (opt
8414 (setq type :opt)
8415 (require 'org-exp)
8416 (append
8417 (mapcar
8418 (lambda (x)
8419 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8420 (cons (match-string 2 x) (match-string 1 x)))
8421 (org-split-string (org-get-current-options) "\n"))
8422 (mapcar 'list org-additional-option-like-keywords)))
8423 (startup
8424 (setq type :startup)
8425 org-startup-options)
8426 (link (append org-link-abbrev-alist-local
8427 org-link-abbrev-alist))
8428 (texp
8429 (setq type :tex)
8430 org-html-entities)
8431 ((string-match "\\`\\*+[ \t]+\\'"
8432 (buffer-substring (point-at-bol) beg))
8433 (setq type :todo)
8434 (mapcar 'list org-todo-keywords-1))
8435 (searchhead
8436 (setq type :searchhead)
8437 (save-excursion
8438 (goto-char (point-min))
8439 (while (re-search-forward org-todo-line-regexp nil t)
8440 (push (list
8441 (org-make-org-heading-search-string
8442 (match-string 3) t))
8443 tbl)))
8444 tbl)
8445 (tag (setq type :tag beg beg1)
8446 (or org-tag-alist (org-get-buffer-tags)))
8447 (prop (setq type :prop beg beg1)
8448 (mapcar 'list (org-buffer-property-keys nil t t)))
8449 (t (progn
8450 (call-interactively org-completion-fallback-command)
8451 (throw 'exit nil)))))
8452 (pattern (buffer-substring-no-properties beg end))
8453 (completion (try-completion pattern table confirm)))
8454 (cond ((eq completion t)
8455 (if (not (assoc (upcase pattern) table))
8456 (message "Already complete")
8457 (if (and (equal type :opt)
8458 (not (member (car (assoc (upcase pattern) table))
8459 org-additional-option-like-keywords)))
8460 (insert (substring (cdr (assoc (upcase pattern) table))
8461 (length pattern)))
8462 (if (memq type '(:tag :prop)) (insert ":")))))
8463 ((null completion)
8464 (message "Can't find completion for \"%s\"" pattern)
8465 (ding))
8466 ((not (string= pattern completion))
8467 (delete-region beg end)
8468 (if (string-match " +$" completion)
8469 (setq completion (replace-match "" t t completion)))
8470 (insert completion)
8471 (if (get-buffer-window "*Completions*")
8472 (delete-window (get-buffer-window "*Completions*")))
8473 (if (assoc completion table)
8474 (if (eq type :todo) (insert " ")
8475 (if (memq type '(:tag :prop)) (insert ":"))))
8476 (if (and (equal type :opt) (assoc completion table))
8477 (message "%s" (substitute-command-keys
8478 "Press \\[org-complete] again to insert example settings"))))
8480 (message "Making completion list...")
8481 (let ((list (sort (all-completions pattern table confirm)
8482 'string<)))
8483 (with-output-to-temp-buffer "*Completions*"
8484 (condition-case nil
8485 ;; Protection needed for XEmacs and emacs 21
8486 (display-completion-list list pattern)
8487 (error (display-completion-list list)))))
8488 (message "Making completion list...%s" "done")))))))
8490 ;;;; TODO, DEADLINE, Comments
8492 (defun org-toggle-comment ()
8493 "Change the COMMENT state of an entry."
8494 (interactive)
8495 (save-excursion
8496 (org-back-to-heading)
8497 (let (case-fold-search)
8498 (if (looking-at (concat outline-regexp
8499 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8500 (replace-match "" t t nil 1)
8501 (if (looking-at outline-regexp)
8502 (progn
8503 (goto-char (match-end 0))
8504 (insert org-comment-string " ")))))))
8506 (defvar org-last-todo-state-is-todo nil
8507 "This is non-nil when the last TODO state change led to a TODO state.
8508 If the last change removed the TODO tag or switched to DONE, then
8509 this is nil.")
8511 (defvar org-setting-tags nil) ; dynamically skipped
8513 (defun org-parse-local-options (string var)
8514 "Parse STRING for startup setting relevant for variable VAR."
8515 (let ((rtn (symbol-value var))
8516 e opts)
8517 (save-match-data
8518 (if (or (not string) (not (string-match "\\S-" string)))
8520 (setq opts (delq nil (mapcar (lambda (x)
8521 (setq e (assoc x org-startup-options))
8522 (if (eq (nth 1 e) var) e nil))
8523 (org-split-string string "[ \t]+"))))
8524 (if (not opts)
8526 (setq rtn nil)
8527 (while (setq e (pop opts))
8528 (if (not (nth 3 e))
8529 (setq rtn (nth 2 e))
8530 (if (not (listp rtn)) (setq rtn nil))
8531 (push (nth 2 e) rtn)))
8532 rtn)))))
8534 (defvar org-todo-setup-filter-hook nil
8535 "Hook for functions that pre-filter todo specs.
8537 Each function takes a todo spec and returns either `nil' or the spec
8538 transformed into canonical form." )
8540 (defvar org-todo-get-default-hook nil
8541 "Hook for functions that get a default item for todo.
8543 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8544 `nil' or a string to be used for the todo mark." )
8546 (defvar org-agenda-headline-snapshot-before-repeat)
8547 (defun org-todo (&optional arg)
8548 "Change the TODO state of an item.
8549 The state of an item is given by a keyword at the start of the heading,
8550 like
8551 *** TODO Write paper
8552 *** DONE Call mom
8554 The different keywords are specified in the variable `org-todo-keywords'.
8555 By default the available states are \"TODO\" and \"DONE\".
8556 So for this example: when the item starts with TODO, it is changed to DONE.
8557 When it starts with DONE, the DONE is removed. And when neither TODO nor
8558 DONE are present, add TODO at the beginning of the heading.
8560 With C-u prefix arg, use completion to determine the new state.
8561 With numeric prefix arg, switch to that state.
8562 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8563 With a tripple C-u prefix, circumvent any state blocking.
8565 For calling through lisp, arg is also interpreted in the following way:
8566 'none -> empty state
8567 \"\"(empty string) -> switch to empty state
8568 'done -> switch to DONE
8569 'nextset -> switch to the next set of keywords
8570 'previousset -> switch to the previous set of keywords
8571 \"WAITING\" -> switch to the specified keyword, but only if it
8572 really is a member of `org-todo-keywords'."
8573 (interactive "P")
8574 (if (equal arg '(16)) (setq arg 'nextset))
8575 (let ((org-blocker-hook org-blocker-hook))
8576 (when (equal arg '(64))
8577 (setq arg nil org-blocker-hook nil))
8578 (save-excursion
8579 (catch 'exit
8580 (org-back-to-heading)
8581 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8582 (or (looking-at (concat " +" org-todo-regexp " *"))
8583 (looking-at " *"))
8584 (let* ((match-data (match-data))
8585 (startpos (point-at-bol))
8586 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8587 (org-log-done org-log-done)
8588 (org-log-repeat org-log-repeat)
8589 (org-todo-log-states org-todo-log-states)
8590 (this (match-string 1))
8591 (hl-pos (match-beginning 0))
8592 (head (org-get-todo-sequence-head this))
8593 (ass (assoc head org-todo-kwd-alist))
8594 (interpret (nth 1 ass))
8595 (done-word (nth 3 ass))
8596 (final-done-word (nth 4 ass))
8597 (last-state (or this ""))
8598 (completion-ignore-case t)
8599 (member (member this org-todo-keywords-1))
8600 (tail (cdr member))
8601 (state (cond
8602 ((and org-todo-key-trigger
8603 (or (and (equal arg '(4))
8604 (eq org-use-fast-todo-selection 'prefix))
8605 (and (not arg) org-use-fast-todo-selection
8606 (not (eq org-use-fast-todo-selection
8607 'prefix)))))
8608 ;; Use fast selection
8609 (org-fast-todo-selection))
8610 ((and (equal arg '(4))
8611 (or (not org-use-fast-todo-selection)
8612 (not org-todo-key-trigger)))
8613 ;; Read a state with completion
8614 (org-ido-completing-read
8615 "State: " (mapcar (lambda(x) (list x))
8616 org-todo-keywords-1)
8617 nil t))
8618 ((eq arg 'right)
8619 (if this
8620 (if tail (car tail) nil)
8621 (car org-todo-keywords-1)))
8622 ((eq arg 'left)
8623 (if (equal member org-todo-keywords-1)
8625 (if this
8626 (nth (- (length org-todo-keywords-1)
8627 (length tail) 2)
8628 org-todo-keywords-1)
8629 (org-last org-todo-keywords-1))))
8630 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8631 (setq arg nil))) ; hack to fall back to cycling
8632 (arg
8633 ;; user or caller requests a specific state
8634 (cond
8635 ((equal arg "") nil)
8636 ((eq arg 'none) nil)
8637 ((eq arg 'done) (or done-word (car org-done-keywords)))
8638 ((eq arg 'nextset)
8639 (or (car (cdr (member head org-todo-heads)))
8640 (car org-todo-heads)))
8641 ((eq arg 'previousset)
8642 (let ((org-todo-heads (reverse org-todo-heads)))
8643 (or (car (cdr (member head org-todo-heads)))
8644 (car org-todo-heads))))
8645 ((car (member arg org-todo-keywords-1)))
8646 ((nth (1- (prefix-numeric-value arg))
8647 org-todo-keywords-1))))
8648 ((null member) (or head (car org-todo-keywords-1)))
8649 ((equal this final-done-word) nil) ;; -> make empty
8650 ((null tail) nil) ;; -> first entry
8651 ((memq interpret '(type priority))
8652 (if (eq this-command last-command)
8653 (car tail)
8654 (if (> (length tail) 0)
8655 (or done-word (car org-done-keywords))
8656 nil)))
8658 (car tail))))
8659 (state (or
8660 (run-hook-with-args-until-success
8661 'org-todo-get-default-hook state last-state)
8662 state))
8663 (next (if state (concat " " state " ") " "))
8664 (change-plist (list :type 'todo-state-change :from this :to state
8665 :position startpos))
8666 dolog now-done-p)
8667 (when org-blocker-hook
8668 (setq org-last-todo-state-is-todo
8669 (not (member this org-done-keywords)))
8670 (unless (save-excursion
8671 (save-match-data
8672 (run-hook-with-args-until-failure
8673 'org-blocker-hook change-plist)))
8674 (if (interactive-p)
8675 (error "TODO state change from %s to %s blocked" this state)
8676 ;; fail silently
8677 (message "TODO state change from %s to %s blocked" this state)
8678 (throw 'exit nil))))
8679 (store-match-data match-data)
8680 (replace-match next t t)
8681 (unless (pos-visible-in-window-p hl-pos)
8682 (message "TODO state changed to %s" (org-trim next)))
8683 (unless head
8684 (setq head (org-get-todo-sequence-head state)
8685 ass (assoc head org-todo-kwd-alist)
8686 interpret (nth 1 ass)
8687 done-word (nth 3 ass)
8688 final-done-word (nth 4 ass)))
8689 (when (memq arg '(nextset previousset))
8690 (message "Keyword-Set %d/%d: %s"
8691 (- (length org-todo-sets) -1
8692 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8693 (length org-todo-sets)
8694 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8695 (setq org-last-todo-state-is-todo
8696 (not (member state org-done-keywords)))
8697 (setq now-done-p (and (member state org-done-keywords)
8698 (not (member this org-done-keywords))))
8699 (and logging (org-local-logging logging))
8700 (when (and (or org-todo-log-states org-log-done)
8701 (not (memq arg '(nextset previousset))))
8702 ;; we need to look at recording a time and note
8703 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8704 (nth 2 (assoc this org-todo-log-states))))
8705 (when (and state
8706 (member state org-not-done-keywords)
8707 (not (member this org-not-done-keywords)))
8708 ;; This is now a todo state and was not one before
8709 ;; If there was a CLOSED time stamp, get rid of it.
8710 (org-add-planning-info nil nil 'closed))
8711 (when (and now-done-p org-log-done)
8712 ;; It is now done, and it was not done before
8713 (org-add-planning-info 'closed (org-current-time))
8714 (if (and (not dolog) (eq 'note org-log-done))
8715 (org-add-log-setup 'done state this 'findpos 'note)))
8716 (when (and state dolog)
8717 ;; This is a non-nil state, and we need to log it
8718 (org-add-log-setup 'state state this 'findpos dolog)))
8719 ;; Fixup tag positioning
8720 (org-todo-trigger-tag-changes state)
8721 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8722 (when org-provide-todo-statistics
8723 (org-update-parent-todo-statistics))
8724 (run-hooks 'org-after-todo-state-change-hook)
8725 (if (and arg (not (member state org-done-keywords)))
8726 (setq head (org-get-todo-sequence-head state)))
8727 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8728 ;; Do we need to trigger a repeat?
8729 (when now-done-p
8730 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8731 ;; This is for the agenda, take a snapshot of the headline.
8732 (save-match-data
8733 (setq org-agenda-headline-snapshot-before-repeat
8734 (org-get-heading))))
8735 (org-auto-repeat-maybe state))
8736 ;; Fixup cursor location if close to the keyword
8737 (if (and (outline-on-heading-p)
8738 (not (bolp))
8739 (save-excursion (beginning-of-line 1)
8740 (looking-at org-todo-line-regexp))
8741 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8742 (progn
8743 (goto-char (or (match-end 2) (match-end 1)))
8744 (just-one-space)))
8745 (when org-trigger-hook
8746 (save-excursion
8747 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8749 (defun org-block-todo-from-children-or-siblings (change-plist)
8750 "Block turning an entry into a TODO, using the hierarchy.
8751 This checks whether the current task should be blocked from state
8752 changes. Such blocking occurs when:
8754 1. The task has children which are not all in a completed state.
8756 2. A task has a parent with the property :ORDERED:, and there
8757 are siblings prior to the current task with incomplete
8758 status."
8759 (catch 'dont-block
8760 ;; If this is not a todo state change, or if this entry is already DONE,
8761 ;; do not block
8762 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8763 (member (plist-get change-plist :from)
8764 (cons 'done org-done-keywords))
8765 (member (plist-get change-plist :to)
8766 (cons 'todo org-not-done-keywords)))
8767 (throw 'dont-block t))
8768 ;; If this task has children, and any are undone, it's blocked
8769 (save-excursion
8770 (org-back-to-heading t)
8771 (let ((this-level (funcall outline-level)))
8772 (outline-next-heading)
8773 (let ((child-level (funcall outline-level)))
8774 (while (and (not (eobp))
8775 (> child-level this-level))
8776 ;; this todo has children, check whether they are all
8777 ;; completed
8778 (if (and (not (org-entry-is-done-p))
8779 (org-entry-is-todo-p))
8780 (throw 'dont-block nil))
8781 (outline-next-heading)
8782 (setq child-level (funcall outline-level))))))
8783 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8784 ;; any previous siblings are undone, it's blocked
8785 (save-excursion
8786 (org-back-to-heading t)
8787 (when (save-excursion
8788 (ignore-errors
8789 (org-up-heading-all 1)
8790 (org-entry-get (point) "ORDERED")))
8791 (let* ((this-level (funcall outline-level))
8792 (current-level this-level))
8793 (while (and (not (bobp))
8794 (= current-level this-level))
8795 (outline-previous-heading)
8796 (setq current-level (funcall outline-level))
8797 (if (= current-level this-level)
8798 ;; this todo has children, check whether they are all
8799 ;; completed
8800 (if (and (not (org-entry-is-done-p))
8801 (org-entry-is-todo-p))
8802 (throw 'dont-block nil)))))))
8803 t)) ; don't block
8805 (defcustom org-track-ordered-property-with-tag nil
8806 "Should the ORDERED property also be shown as a tag?
8807 The ORDERED property decides if an entry should require subtasks to be
8808 completed in sequence. Since a property is not very visible, setting
8809 this option means that toggling the ORDERED property with the command
8810 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
8811 not relevant for the behavior, but it makes things more visible.
8813 Note that toggling the tag with tags commands will not change the property
8814 and therefore not influence behavior!
8816 This can be t, meaning the tag ORDERED should be used, It can also be a
8817 string to select a different tag for this task."
8818 :group 'org-todo
8819 :type '(choice
8820 (const :tag "No tracking" nil)
8821 (const :tag "Track with ORDERED tag" t)
8822 (string :tag "Use other tag")))
8824 (defun org-toggle-ordered-property ()
8825 "Toggle the ORDERED property of the current entry.
8826 For better visibility, you can track the value of this property with a tag.
8827 See variable `org-track-ordered-property-with-tag'."
8828 (interactive)
8829 (let* ((t1 org-track-ordered-property-with-tag)
8830 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
8831 (save-excursion
8832 (org-back-to-heading)
8833 (if (org-entry-get nil "ORDERED")
8834 (progn
8835 (org-delete-property "ORDERED")
8836 (and tag (org-toggle-tag tag 'off))
8837 (message "Subtasks can be completed in arbitrary order"))
8838 (org-entry-put nil "ORDERED" "t")
8839 (and tag (org-toggle-tag tag 'on))
8840 (message "Subtasks must be completed in sequence")))))
8842 (defvar org-blocked-by-checkboxes) ; dynamically scoped
8843 (defun org-block-todo-from-checkboxes (change-plist)
8844 "Block turning an entry into a TODO, using checkboxes.
8845 This checks whether the current task should be blocked from state
8846 changes because there are uncheckd boxes in this entry."
8847 (catch 'dont-block
8848 ;; If this is not a todo state change, or if this entry is already DONE,
8849 ;; do not block
8850 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8851 (member (plist-get change-plist :from)
8852 (cons 'done org-done-keywords))
8853 (member (plist-get change-plist :to)
8854 (cons 'todo org-not-done-keywords)))
8855 (throw 'dont-block t))
8856 ;; If this task has checkboxes that are not checked, it's blocked
8857 (save-excursion
8858 (org-back-to-heading t)
8859 (let ((beg (point)) end)
8860 (outline-next-heading)
8861 (setq end (point))
8862 (goto-char beg)
8863 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8864 end t)
8865 (progn
8866 (if (boundp 'org-blocked-by-checkboxes)
8867 (setq org-blocked-by-checkboxes t))
8868 (throw 'dont-block nil)))))
8869 t)) ; do not block
8871 (defun org-update-parent-todo-statistics ()
8872 "Update any statistics cookie in the parent of the current headline."
8873 (interactive)
8874 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8875 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
8876 (catch 'exit
8877 (save-excursion
8878 (setq level (org-up-heading-safe))
8879 (unless level
8880 (throw 'exit nil))
8881 (while (re-search-forward box-re (point-at-eol) t)
8882 (setq cnt-all 0 cnt-done 0 cookie-present t)
8883 (setq is-percent (match-end 2))
8884 (save-match-data
8885 (unless (outline-next-heading) (throw 'exit nil))
8886 (while (looking-at org-todo-line-regexp)
8887 (setq kwd (match-string 2))
8888 (and kwd (setq cnt-all (1+ cnt-all)))
8889 (and (member kwd org-done-keywords)
8890 (setq cnt-done (1+ cnt-done)))
8891 (condition-case nil
8892 (org-forward-same-level 1)
8893 (error (end-of-line 1)))))
8894 (replace-match
8895 (if is-percent
8896 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8897 (format "[%d/%d]" cnt-done cnt-all))))
8898 (when cookie-present
8899 (run-hook-with-args 'org-after-todo-statistics-hook
8900 cnt-done (- cnt-all cnt-done)))))))
8902 (defvar org-after-todo-statistics-hook nil
8903 "Hook that is called after a TODO statistics cookie has been updated.
8904 Each function is called with two arguments: the number of not-done entries
8905 and the number of done entries.
8907 For example, the following function, when added to this hook, will switch
8908 an entry to DONE when all children are done, and back to TODO when new
8909 entries are set to a TODO status. Note that this hook is only called
8910 when there is a statistics cookie in the headline!
8912 (defun org-summary-todo (n-done n-not-done)
8913 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8914 (let (org-log-done org-log-states) ; turn off logging
8915 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8918 (defun org-todo-trigger-tag-changes (state)
8919 "Apply the changes defined in `org-todo-state-tags-triggers'."
8920 (let ((l org-todo-state-tags-triggers)
8921 changes)
8922 (when (or (not state) (equal state ""))
8923 (setq changes (append changes (cdr (assoc "" l)))))
8924 (when (and (stringp state) (> (length state) 0))
8925 (setq changes (append changes (cdr (assoc state l)))))
8926 (when (member state org-not-done-keywords)
8927 (setq changes (append changes (cdr (assoc 'todo l)))))
8928 (when (member state org-done-keywords)
8929 (setq changes (append changes (cdr (assoc 'done l)))))
8930 (dolist (c changes)
8931 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8933 (defun org-local-logging (value)
8934 "Get logging settings from a property VALUE."
8935 (let* (words w a)
8936 ;; directly set the variables, they are already local.
8937 (setq org-log-done nil
8938 org-log-repeat nil
8939 org-todo-log-states nil)
8940 (setq words (org-split-string value))
8941 (while (setq w (pop words))
8942 (cond
8943 ((setq a (assoc w org-startup-options))
8944 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8945 (set (nth 1 a) (nth 2 a))))
8946 ((setq a (org-extract-log-state-settings w))
8947 (and (member (car a) org-todo-keywords-1)
8948 (push a org-todo-log-states)))))))
8950 (defun org-get-todo-sequence-head (kwd)
8951 "Return the head of the TODO sequence to which KWD belongs.
8952 If KWD is not set, check if there is a text property remembering the
8953 right sequence."
8954 (let (p)
8955 (cond
8956 ((not kwd)
8957 (or (get-text-property (point-at-bol) 'org-todo-head)
8958 (progn
8959 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8960 nil (point-at-eol)))
8961 (get-text-property p 'org-todo-head))))
8962 ((not (member kwd org-todo-keywords-1))
8963 (car org-todo-keywords-1))
8964 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8966 (defun org-fast-todo-selection ()
8967 "Fast TODO keyword selection with single keys.
8968 Returns the new TODO keyword, or nil if no state change should occur."
8969 (let* ((fulltable org-todo-key-alist)
8970 (done-keywords org-done-keywords) ;; needed for the faces.
8971 (maxlen (apply 'max (mapcar
8972 (lambda (x)
8973 (if (stringp (car x)) (string-width (car x)) 0))
8974 fulltable)))
8975 (expert nil)
8976 (fwidth (+ maxlen 3 1 3))
8977 (ncol (/ (- (window-width) 4) fwidth))
8978 tg cnt e c tbl
8979 groups ingroup)
8980 (save-excursion
8981 (save-window-excursion
8982 (if expert
8983 (set-buffer (get-buffer-create " *Org todo*"))
8984 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8985 (erase-buffer)
8986 (org-set-local 'org-done-keywords done-keywords)
8987 (setq tbl fulltable cnt 0)
8988 (while (setq e (pop tbl))
8989 (cond
8990 ((equal e '(:startgroup))
8991 (push '() groups) (setq ingroup t)
8992 (when (not (= cnt 0))
8993 (setq cnt 0)
8994 (insert "\n"))
8995 (insert "{ "))
8996 ((equal e '(:endgroup))
8997 (setq ingroup nil cnt 0)
8998 (insert "}\n"))
8999 ((equal e '(:newline))
9000 (when (not (= cnt 0))
9001 (setq cnt 0)
9002 (insert "\n")
9003 (setq e (car tbl))
9004 (while (equal (car tbl) '(:newline))
9005 (insert "\n")
9006 (setq tbl (cdr tbl)))))
9008 (setq tg (car e) c (cdr e))
9009 (if ingroup (push tg (car groups)))
9010 (setq tg (org-add-props tg nil 'face
9011 (org-get-todo-face tg)))
9012 (if (and (= cnt 0) (not ingroup)) (insert " "))
9013 (insert "[" c "] " tg (make-string
9014 (- fwidth 4 (length tg)) ?\ ))
9015 (when (= (setq cnt (1+ cnt)) ncol)
9016 (insert "\n")
9017 (if ingroup (insert " "))
9018 (setq cnt 0)))))
9019 (insert "\n")
9020 (goto-char (point-min))
9021 (if (not expert) (org-fit-window-to-buffer))
9022 (message "[a-z..]:Set [SPC]:clear")
9023 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9024 (cond
9025 ((or (= c ?\C-g)
9026 (and (= c ?q) (not (rassoc c fulltable))))
9027 (setq quit-flag t))
9028 ((= c ?\ ) nil)
9029 ((setq e (rassoc c fulltable) tg (car e))
9031 (t (setq quit-flag t)))))))
9033 (defun org-entry-is-todo-p ()
9034 (member (org-get-todo-state) org-not-done-keywords))
9036 (defun org-entry-is-done-p ()
9037 (member (org-get-todo-state) org-done-keywords))
9039 (defun org-get-todo-state ()
9040 (save-excursion
9041 (org-back-to-heading t)
9042 (and (looking-at org-todo-line-regexp)
9043 (match-end 2)
9044 (match-string 2))))
9046 (defun org-at-date-range-p (&optional inactive-ok)
9047 "Is the cursor inside a date range?"
9048 (interactive)
9049 (save-excursion
9050 (catch 'exit
9051 (let ((pos (point)))
9052 (skip-chars-backward "^[<\r\n")
9053 (skip-chars-backward "<[")
9054 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9055 (>= (match-end 0) pos)
9056 (throw 'exit t))
9057 (skip-chars-backward "^<[\r\n")
9058 (skip-chars-backward "<[")
9059 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9060 (>= (match-end 0) pos)
9061 (throw 'exit t)))
9062 nil)))
9064 (defun org-get-repeat ()
9065 "Check if there is a deadline/schedule with repeater in this entry."
9066 (save-match-data
9067 (save-excursion
9068 (org-back-to-heading t)
9069 (if (re-search-forward
9070 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9071 (match-string 1)))))
9073 (defvar org-last-changed-timestamp)
9074 (defvar org-last-inserted-timestamp)
9075 (defvar org-log-post-message)
9076 (defvar org-log-note-purpose)
9077 (defvar org-log-note-how)
9078 (defvar org-log-note-extra)
9079 (defun org-auto-repeat-maybe (done-word)
9080 "Check if the current headline contains a repeated deadline/schedule.
9081 If yes, set TODO state back to what it was and change the base date
9082 of repeating deadline/scheduled time stamps to new date.
9083 This function is run automatically after each state change to a DONE state."
9084 ;; last-state is dynamically scoped into this function
9085 (let* ((repeat (org-get-repeat))
9086 (aa (assoc last-state org-todo-kwd-alist))
9087 (interpret (nth 1 aa))
9088 (head (nth 2 aa))
9089 (whata '(("d" . day) ("m" . month) ("y" . year)))
9090 (msg "Entry repeats: ")
9091 (org-log-done nil)
9092 (org-todo-log-states nil)
9093 (nshiftmax 10) (nshift 0)
9094 re type n what ts time)
9095 (when repeat
9096 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9097 (org-todo (if (eq interpret 'type) last-state head))
9098 (when org-log-repeat
9099 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9100 (memq 'org-add-log-note post-command-hook))
9101 ;; OK, we are already setup for some record
9102 (if (eq org-log-repeat 'note)
9103 ;; make sure we take a note, not only a time stamp
9104 (setq org-log-note-how 'note))
9105 ;; Set up for taking a record
9106 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9107 last-state
9108 'findpos org-log-repeat)))
9109 (org-back-to-heading t)
9110 (org-add-planning-info nil nil 'closed)
9111 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9112 org-deadline-time-regexp "\\)\\|\\("
9113 org-ts-regexp "\\)"))
9114 (while (re-search-forward
9115 re (save-excursion (outline-next-heading) (point)) t)
9116 (setq type (if (match-end 1) org-scheduled-string
9117 (if (match-end 3) org-deadline-string "Plain:"))
9118 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9119 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9120 (setq n (string-to-number (match-string 2 ts))
9121 what (match-string 3 ts))
9122 (if (equal what "w") (setq n (* n 7) what "d"))
9123 ;; Preparation, see if we need to modify the start date for the change
9124 (when (match-end 1)
9125 (setq time (save-match-data (org-time-string-to-time ts)))
9126 (cond
9127 ((equal (match-string 1 ts) ".")
9128 ;; Shift starting date to today
9129 (org-timestamp-change
9130 (- (time-to-days (current-time)) (time-to-days time))
9131 'day))
9132 ((equal (match-string 1 ts) "+")
9133 (while (or (= nshift 0)
9134 (<= (time-to-days time) (time-to-days (current-time))))
9135 (when (= (incf nshift) nshiftmax)
9136 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9137 (error "Abort")))
9138 (org-timestamp-change n (cdr (assoc what whata)))
9139 (org-at-timestamp-p t)
9140 (setq ts (match-string 1))
9141 (setq time (save-match-data (org-time-string-to-time ts))))
9142 (org-timestamp-change (- n) (cdr (assoc what whata)))
9143 ;; rematch, so that we have everything in place for the real shift
9144 (org-at-timestamp-p t)
9145 (setq ts (match-string 1))
9146 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9147 (org-timestamp-change n (cdr (assoc what whata)))
9148 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9149 (setq org-log-post-message msg)
9150 (message "%s" msg))))
9152 (defun org-show-todo-tree (arg)
9153 "Make a compact tree which shows all headlines marked with TODO.
9154 The tree will show the lines where the regexp matches, and all higher
9155 headlines above the match.
9156 With a \\[universal-argument] prefix, also show the DONE entries.
9157 With a numeric prefix N, construct a sparse tree for the Nth element
9158 of `org-todo-keywords-1'."
9159 (interactive "P")
9160 (let ((case-fold-search nil)
9161 (kwd-re
9162 (cond ((null arg) org-not-done-regexp)
9163 ((equal arg '(4))
9164 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9165 (mapcar 'list org-todo-keywords-1))))
9166 (concat "\\("
9167 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9168 "\\)\\>")))
9169 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9170 (regexp-quote (nth (1- (prefix-numeric-value arg))
9171 org-todo-keywords-1)))
9172 (t (error "Invalid prefix argument: %s" arg)))))
9173 (message "%d TODO entries found"
9174 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9176 (defun org-deadline (&optional remove time)
9177 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9178 With argument REMOVE, remove any deadline from the item.
9179 When TIME is set, it should be an internal time specification, and the
9180 scheduling will use the corresponding date."
9181 (interactive "P")
9182 (if remove
9183 (progn
9184 (org-remove-timestamp-with-keyword org-deadline-string)
9185 (message "Item no longer has a deadline."))
9186 (if (org-get-repeat)
9187 (error "Cannot change deadline on task with repeater, please do that by hand")
9188 (org-add-planning-info 'deadline time 'closed)
9189 (message "Deadline on %s" org-last-inserted-timestamp))))
9191 (defun org-schedule (&optional remove time)
9192 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9193 With argument REMOVE, remove any scheduling date from the item.
9194 When TIME is set, it should be an internal time specification, and the
9195 scheduling will use the corresponding date."
9196 (interactive "P")
9197 (if remove
9198 (progn
9199 (org-remove-timestamp-with-keyword org-scheduled-string)
9200 (message "Item is no longer scheduled."))
9201 (if (org-get-repeat)
9202 (error "Cannot reschedule task with repeater, please do that by hand")
9203 (org-add-planning-info 'scheduled time 'closed)
9204 (message "Scheduled to %s" org-last-inserted-timestamp))))
9206 (defun org-get-scheduled-time (pom &optional inherit)
9207 "Get the scheduled time as a time tuple, of a format suitable
9208 for calling org-schedule with, or if there is no scheduling,
9209 returns nil."
9210 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9211 (when time
9212 (apply 'encode-time (org-parse-time-string time)))))
9214 (defun org-get-deadline-time (pom &optional inherit)
9215 "Get the deadine as a time tuple, of a format suitable for
9216 calling org-deadlin with, or if there is no scheduling, returns
9217 nil."
9218 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9219 (when time
9220 (apply 'encode-time (org-parse-time-string time)))))
9222 (defun org-remove-timestamp-with-keyword (keyword)
9223 "Remove all time stamps with KEYWORD in the current entry."
9224 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9225 beg)
9226 (save-excursion
9227 (org-back-to-heading t)
9228 (setq beg (point))
9229 (org-end-of-subtree t t)
9230 (while (re-search-backward re beg t)
9231 (replace-match "")
9232 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9233 (equal (char-before) ?\ ))
9234 (backward-delete-char 1)
9235 (if (string-match "^[ \t]*$" (buffer-substring
9236 (point-at-bol) (point-at-eol)))
9237 (delete-region (point-at-bol)
9238 (min (point-max) (1+ (point-at-eol))))))))))
9240 (defun org-add-planning-info (what &optional time &rest remove)
9241 "Insert new timestamp with keyword in the line directly after the headline.
9242 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9243 If non is given, the user is prompted for a date.
9244 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9245 be removed."
9246 (interactive)
9247 (let (org-time-was-given org-end-time-was-given ts
9248 end default-time default-input)
9250 (catch 'exit
9251 (when (and (not time) (memq what '(scheduled deadline)))
9252 ;; Try to get a default date/time from existing timestamp
9253 (save-excursion
9254 (org-back-to-heading t)
9255 (setq end (save-excursion (outline-next-heading) (point)))
9256 (when (re-search-forward (if (eq what 'scheduled)
9257 org-scheduled-time-regexp
9258 org-deadline-time-regexp)
9259 end t)
9260 (setq ts (match-string 1)
9261 default-time
9262 (apply 'encode-time (org-parse-time-string ts))
9263 default-input (and ts (org-get-compact-tod ts))))))
9264 (when what
9265 ;; If necessary, get the time from the user
9266 (setq time (or time (org-read-date nil 'to-time nil nil
9267 default-time default-input))))
9269 (when (and org-insert-labeled-timestamps-at-point
9270 (member what '(scheduled deadline)))
9271 (insert
9272 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9273 (org-insert-time-stamp time org-time-was-given
9274 nil nil nil (list org-end-time-was-given))
9275 (setq what nil))
9276 (save-excursion
9277 (save-restriction
9278 (let (col list elt ts buffer-invisibility-spec)
9279 (org-back-to-heading t)
9280 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9281 (goto-char (match-end 1))
9282 (setq col (current-column))
9283 (goto-char (match-end 0))
9284 (if (eobp) (insert "\n") (forward-char 1))
9285 (when (and (not what)
9286 (not (looking-at org-keyword-time-not-clock-regexp)))
9287 ;; Nothing to add, nothing to remove...... :-)
9288 (throw 'exit nil))
9289 (if (and (not (looking-at outline-regexp))
9290 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9291 "[^\r\n]*"))
9292 (not (equal (match-string 1) org-clock-string)))
9293 (narrow-to-region (match-beginning 0) (match-end 0))
9294 (insert-before-markers "\n")
9295 (backward-char 1)
9296 (narrow-to-region (point) (point))
9297 (and org-adapt-indentation (org-indent-to-column col)))
9298 ;; Check if we have to remove something.
9299 (setq list (cons what remove))
9300 (while list
9301 (setq elt (pop list))
9302 (goto-char (point-min))
9303 (when (or (and (eq elt 'scheduled)
9304 (re-search-forward org-scheduled-time-regexp nil t))
9305 (and (eq elt 'deadline)
9306 (re-search-forward org-deadline-time-regexp nil t))
9307 (and (eq elt 'closed)
9308 (re-search-forward org-closed-time-regexp nil t)))
9309 (replace-match "")
9310 (if (looking-at "--+<[^>]+>") (replace-match ""))
9311 (if (looking-at " +") (replace-match ""))))
9312 (goto-char (point-max))
9313 (when what
9314 (insert
9315 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9316 (cond ((eq what 'scheduled) org-scheduled-string)
9317 ((eq what 'deadline) org-deadline-string)
9318 ((eq what 'closed) org-closed-string))
9319 " ")
9320 (setq ts (org-insert-time-stamp
9321 time
9322 (or org-time-was-given
9323 (and (eq what 'closed) org-log-done-with-time))
9324 (eq what 'closed)
9325 nil nil (list org-end-time-was-given)))
9326 (end-of-line 1))
9327 (goto-char (point-min))
9328 (widen)
9329 (if (and (looking-at "[ \t]+\n")
9330 (equal (char-before) ?\n))
9331 (delete-region (1- (point)) (point-at-eol)))
9332 ts))))))
9334 (defvar org-log-note-marker (make-marker))
9335 (defvar org-log-note-purpose nil)
9336 (defvar org-log-note-state nil)
9337 (defvar org-log-note-previous-state nil)
9338 (defvar org-log-note-how nil)
9339 (defvar org-log-note-extra nil)
9340 (defvar org-log-note-window-configuration nil)
9341 (defvar org-log-note-return-to (make-marker))
9342 (defvar org-log-post-message nil
9343 "Message to be displayed after a log note has been stored.
9344 The auto-repeater uses this.")
9346 (defun org-add-note ()
9347 "Add a note to the current entry.
9348 This is done in the same way as adding a state change note."
9349 (interactive)
9350 (org-add-log-setup 'note nil nil 'findpos nil))
9352 (defvar org-property-end-re)
9353 (defun org-add-log-setup (&optional purpose state prev-state
9354 findpos how &optional extra)
9355 "Set up the post command hook to take a note.
9356 If this is about to TODO state change, the new state is expected in STATE.
9357 When FINDPOS is non-nil, find the correct position for the note in
9358 the current entry. If not, assume that it can be inserted at point.
9359 HOW is an indicator what kind of note should be created.
9360 EXTRA is additional text that will be inserted into the notes buffer."
9361 (let ((drawer (cond ((stringp org-log-into-drawer)
9362 org-log-into-drawer)
9363 (org-log-into-drawer "LOGBOOK")
9364 (t nil))))
9365 (save-restriction
9366 (save-excursion
9367 (when findpos
9368 (org-back-to-heading t)
9369 (narrow-to-region (point) (save-excursion
9370 (outline-next-heading) (point)))
9371 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9372 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9373 "[^\r\n]*\\)?"))
9374 (goto-char (match-end 0))
9375 (cond
9376 (drawer
9377 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9378 nil t)
9379 (progn
9380 (goto-char (match-end 0))
9381 (or org-log-states-order-reversed
9382 (and (re-search-forward org-property-end-re nil t)
9383 (goto-char (1- (match-beginning 0))))))
9384 (insert "\n:" drawer ":\n:END:")
9385 (beginning-of-line 0)
9386 (org-indent-line-function)
9387 (beginning-of-line 2)
9388 (org-indent-line-function)
9389 (end-of-line 0)))
9390 ((and org-log-state-notes-insert-after-drawers
9391 (save-excursion
9392 (forward-line) (looking-at org-drawer-regexp)))
9393 (forward-line)
9394 (while (looking-at org-drawer-regexp)
9395 (goto-char (match-end 0))
9396 (re-search-forward org-property-end-re (point-max) t)
9397 (forward-line))
9398 (forward-line -1)))
9399 (unless org-log-states-order-reversed
9400 (and (= (char-after) ?\n) (forward-char 1))
9401 (org-skip-over-state-notes)
9402 (skip-chars-backward " \t\n\r")))
9403 (move-marker org-log-note-marker (point))
9404 (setq org-log-note-purpose purpose
9405 org-log-note-state state
9406 org-log-note-previous-state prev-state
9407 org-log-note-how how
9408 org-log-note-extra extra)
9409 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9411 (defun org-skip-over-state-notes ()
9412 "Skip past the list of State notes in an entry."
9413 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9414 (while (looking-at "[ \t]*- State")
9415 (condition-case nil
9416 (org-next-item)
9417 (error (org-end-of-item)))))
9419 (defun org-add-log-note (&optional purpose)
9420 "Pop up a window for taking a note, and add this note later at point."
9421 (remove-hook 'post-command-hook 'org-add-log-note)
9422 (setq org-log-note-window-configuration (current-window-configuration))
9423 (delete-other-windows)
9424 (move-marker org-log-note-return-to (point))
9425 (switch-to-buffer (marker-buffer org-log-note-marker))
9426 (goto-char org-log-note-marker)
9427 (org-switch-to-buffer-other-window "*Org Note*")
9428 (erase-buffer)
9429 (if (memq org-log-note-how '(time state))
9430 (let (current-prefix-arg) (org-store-log-note))
9431 (let ((org-inhibit-startup t)) (org-mode))
9432 (insert (format "# Insert note for %s.
9433 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9434 (cond
9435 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9436 ((eq org-log-note-purpose 'done) "closed todo item")
9437 ((eq org-log-note-purpose 'state)
9438 (format "state change from \"%s\" to \"%s\""
9439 (or org-log-note-previous-state "")
9440 (or org-log-note-state "")))
9441 ((eq org-log-note-purpose 'note)
9442 "this entry")
9443 (t (error "This should not happen")))))
9444 (if org-log-note-extra (insert org-log-note-extra))
9445 (org-set-local 'org-finish-function 'org-store-log-note)))
9447 (defvar org-note-abort nil) ; dynamically scoped
9448 (defun org-store-log-note ()
9449 "Finish taking a log note, and insert it to where it belongs."
9450 (let ((txt (buffer-string))
9451 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9452 lines ind)
9453 (kill-buffer (current-buffer))
9454 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9455 (setq txt (replace-match "" t t txt)))
9456 (if (string-match "\\s-+\\'" txt)
9457 (setq txt (replace-match "" t t txt)))
9458 (setq lines (org-split-string txt "\n"))
9459 (when (and note (string-match "\\S-" note))
9460 (setq note
9461 (org-replace-escapes
9462 note
9463 (list (cons "%u" (user-login-name))
9464 (cons "%U" user-full-name)
9465 (cons "%t" (format-time-string
9466 (org-time-stamp-format 'long 'inactive)
9467 (current-time)))
9468 (cons "%s" (if org-log-note-state
9469 (concat "\"" org-log-note-state "\"")
9470 ""))
9471 (cons "%S" (if org-log-note-previous-state
9472 (concat "\"" org-log-note-previous-state "\"")
9473 "\"\"")))))
9474 (if lines (setq note (concat note " \\\\")))
9475 (push note lines))
9476 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9477 (when lines
9478 (save-excursion
9479 (set-buffer (marker-buffer org-log-note-marker))
9480 (save-excursion
9481 (goto-char org-log-note-marker)
9482 (move-marker org-log-note-marker nil)
9483 (end-of-line 1)
9484 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9485 (insert "- " (pop lines))
9486 (org-indent-line-function)
9487 (beginning-of-line 1)
9488 (looking-at "[ \t]*")
9489 (setq ind (concat (match-string 0) " "))
9490 (end-of-line 1)
9491 (while lines (insert "\n" ind (pop lines)))
9492 (message "Note stored")
9493 (org-back-to-heading t)
9494 (org-cycle-hide-drawers 'children)))))
9495 (set-window-configuration org-log-note-window-configuration)
9496 (with-current-buffer (marker-buffer org-log-note-return-to)
9497 (goto-char org-log-note-return-to))
9498 (move-marker org-log-note-return-to nil)
9499 (and org-log-post-message (message "%s" org-log-post-message)))
9501 (defun org-sparse-tree (&optional arg)
9502 "Create a sparse tree, prompt for the details.
9503 This command can create sparse trees. You first need to select the type
9504 of match used to create the tree:
9506 t Show entries with a specific TODO keyword.
9507 T Show entries selected by a tags match.
9508 p Enter a property name and its value (both with completion on existing
9509 names/values) and show entries with that property.
9510 r Show entries matching a regular expression
9511 d Show deadlines due within `org-deadline-warning-days'."
9512 (interactive "P")
9513 (let (ans kwd value)
9514 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9515 (setq ans (read-char-exclusive))
9516 (cond
9517 ((equal ans ?d)
9518 (call-interactively 'org-check-deadlines))
9519 ((equal ans ?b)
9520 (call-interactively 'org-check-before-date))
9521 ((equal ans ?t)
9522 (org-show-todo-tree '(4)))
9523 ((equal ans ?T)
9524 (call-interactively 'org-tags-sparse-tree))
9525 ((member ans '(?p ?P))
9526 (setq kwd (org-ido-completing-read "Property: "
9527 (mapcar 'list (org-buffer-property-keys))))
9528 (setq value (org-ido-completing-read "Value: "
9529 (mapcar 'list (org-property-values kwd))))
9530 (unless (string-match "\\`{.*}\\'" value)
9531 (setq value (concat "\"" value "\"")))
9532 (org-tags-sparse-tree arg (concat kwd "=" value)))
9533 ((member ans '(?r ?R ?/))
9534 (call-interactively 'org-occur))
9535 (t (error "No such sparse tree command \"%c\"" ans)))))
9537 (defvar org-occur-highlights nil
9538 "List of overlays used for occur matches.")
9539 (make-variable-buffer-local 'org-occur-highlights)
9540 (defvar org-occur-parameters nil
9541 "Parameters of the active org-occur calls.
9542 This is a list, each call to org-occur pushes as cons cell,
9543 containing the regular expression and the callback, onto the list.
9544 The list can contain several entries if `org-occur' has been called
9545 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9546 will only contain one set of parameters. When the highlights are
9547 removed (for example with `C-c C-c', or with the next edit (depending
9548 on `org-remove-highlights-with-change'), this variable is emptied
9549 as well.")
9550 (make-variable-buffer-local 'org-occur-parameters)
9552 (defun org-occur (regexp &optional keep-previous callback)
9553 "Make a compact tree which shows all matches of REGEXP.
9554 The tree will show the lines where the regexp matches, and all higher
9555 headlines above the match. It will also show the heading after the match,
9556 to make sure editing the matching entry is easy.
9557 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9558 call to `org-occur' will be kept, to allow stacking of calls to this
9559 command.
9560 If CALLBACK is non-nil, it is a function which is called to confirm
9561 that the match should indeed be shown."
9562 (interactive "sRegexp: \nP")
9563 (unless keep-previous
9564 (org-remove-occur-highlights nil nil t))
9565 (push (cons regexp callback) org-occur-parameters)
9566 (let ((cnt 0))
9567 (save-excursion
9568 (goto-char (point-min))
9569 (if (or (not keep-previous) ; do not want to keep
9570 (not org-occur-highlights)) ; no previous matches
9571 ;; hide everything
9572 (org-overview))
9573 (while (re-search-forward regexp nil t)
9574 (when (or (not callback)
9575 (save-match-data (funcall callback)))
9576 (setq cnt (1+ cnt))
9577 (when org-highlight-sparse-tree-matches
9578 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9579 (org-show-context 'occur-tree))))
9580 (when org-remove-highlights-with-change
9581 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9582 nil 'local))
9583 (unless org-sparse-tree-open-archived-trees
9584 (org-hide-archived-subtrees (point-min) (point-max)))
9585 (run-hooks 'org-occur-hook)
9586 (if (interactive-p)
9587 (message "%d match(es) for regexp %s" cnt regexp))
9588 cnt))
9590 (defun org-show-context (&optional key)
9591 "Make sure point and context and visible.
9592 How much context is shown depends upon the variables
9593 `org-show-hierarchy-above', `org-show-following-heading'. and
9594 `org-show-siblings'."
9595 (let ((heading-p (org-on-heading-p t))
9596 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9597 (following-p (org-get-alist-option org-show-following-heading key))
9598 (entry-p (org-get-alist-option org-show-entry-below key))
9599 (siblings-p (org-get-alist-option org-show-siblings key)))
9600 (catch 'exit
9601 ;; Show heading or entry text
9602 (if (and heading-p (not entry-p))
9603 (org-flag-heading nil) ; only show the heading
9604 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9605 (org-show-hidden-entry))) ; show entire entry
9606 (when following-p
9607 ;; Show next sibling, or heading below text
9608 (save-excursion
9609 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9610 (org-flag-heading nil))))
9611 (when siblings-p (org-show-siblings))
9612 (when hierarchy-p
9613 ;; show all higher headings, possibly with siblings
9614 (save-excursion
9615 (while (and (condition-case nil
9616 (progn (org-up-heading-all 1) t)
9617 (error nil))
9618 (not (bobp)))
9619 (org-flag-heading nil)
9620 (when siblings-p (org-show-siblings))))))))
9622 (defun org-reveal (&optional siblings)
9623 "Show current entry, hierarchy above it, and the following headline.
9624 This can be used to show a consistent set of context around locations
9625 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9626 not t for the search context.
9628 With optional argument SIBLINGS, on each level of the hierarchy all
9629 siblings are shown. This repairs the tree structure to what it would
9630 look like when opened with hierarchical calls to `org-cycle'."
9631 (interactive "P")
9632 (let ((org-show-hierarchy-above t)
9633 (org-show-following-heading t)
9634 (org-show-siblings (if siblings t org-show-siblings)))
9635 (org-show-context nil)))
9637 (defun org-highlight-new-match (beg end)
9638 "Highlight from BEG to END and mark the highlight is an occur headline."
9639 (let ((ov (org-make-overlay beg end)))
9640 (org-overlay-put ov 'face 'secondary-selection)
9641 (push ov org-occur-highlights)))
9643 (defun org-remove-occur-highlights (&optional beg end noremove)
9644 "Remove the occur highlights from the buffer.
9645 BEG and END are ignored. If NOREMOVE is nil, remove this function
9646 from the `before-change-functions' in the current buffer."
9647 (interactive)
9648 (unless org-inhibit-highlight-removal
9649 (mapc 'org-delete-overlay org-occur-highlights)
9650 (setq org-occur-highlights nil)
9651 (setq org-occur-parameters nil)
9652 (unless noremove
9653 (remove-hook 'before-change-functions
9654 'org-remove-occur-highlights 'local))))
9656 ;;;; Priorities
9658 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9659 "Regular expression matching the priority indicator.")
9661 (defvar org-remove-priority-next-time nil)
9663 (defun org-priority-up ()
9664 "Increase the priority of the current item."
9665 (interactive)
9666 (org-priority 'up))
9668 (defun org-priority-down ()
9669 "Decrease the priority of the current item."
9670 (interactive)
9671 (org-priority 'down))
9673 (defun org-priority (&optional action)
9674 "Change the priority of an item by ARG.
9675 ACTION can be `set', `up', `down', or a character."
9676 (interactive)
9677 (setq action (or action 'set))
9678 (let (current new news have remove)
9679 (save-excursion
9680 (org-back-to-heading t)
9681 (if (looking-at org-priority-regexp)
9682 (setq current (string-to-char (match-string 2))
9683 have t)
9684 (setq current org-default-priority))
9685 (cond
9686 ((or (eq action 'set)
9687 (if (featurep 'xemacs) (characterp action) (integerp action)))
9688 (if (not (eq action 'set))
9689 (setq new action)
9690 (message "Priority %c-%c, SPC to remove: "
9691 org-highest-priority org-lowest-priority)
9692 (setq new (read-char-exclusive)))
9693 (if (and (= (upcase org-highest-priority) org-highest-priority)
9694 (= (upcase org-lowest-priority) org-lowest-priority))
9695 (setq new (upcase new)))
9696 (cond ((equal new ?\ ) (setq remove t))
9697 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9698 (error "Priority must be between `%c' and `%c'"
9699 org-highest-priority org-lowest-priority))))
9700 ((eq action 'up)
9701 (if (and (not have) (eq last-command this-command))
9702 (setq new org-lowest-priority)
9703 (setq new (if (and org-priority-start-cycle-with-default (not have))
9704 org-default-priority (1- current)))))
9705 ((eq action 'down)
9706 (if (and (not have) (eq last-command this-command))
9707 (setq new org-highest-priority)
9708 (setq new (if (and org-priority-start-cycle-with-default (not have))
9709 org-default-priority (1+ current)))))
9710 (t (error "Invalid action")))
9711 (if (or (< (upcase new) org-highest-priority)
9712 (> (upcase new) org-lowest-priority))
9713 (setq remove t))
9714 (setq news (format "%c" new))
9715 (if have
9716 (if remove
9717 (replace-match "" t t nil 1)
9718 (replace-match news t t nil 2))
9719 (if remove
9720 (error "No priority cookie found in line")
9721 (looking-at org-todo-line-regexp)
9722 (if (match-end 2)
9723 (progn
9724 (goto-char (match-end 2))
9725 (insert " [#" news "]"))
9726 (goto-char (match-beginning 3))
9727 (insert "[#" news "] ")))))
9728 (org-preserve-lc (org-set-tags nil 'align))
9729 (if remove
9730 (message "Priority removed")
9731 (message "Priority of current item set to %s" news))))
9734 (defun org-get-priority (s)
9735 "Find priority cookie and return priority."
9736 (save-match-data
9737 (if (not (string-match org-priority-regexp s))
9738 (* 1000 (- org-lowest-priority org-default-priority))
9739 (* 1000 (- org-lowest-priority
9740 (string-to-char (match-string 2 s)))))))
9742 ;;;; Tags
9744 (defvar org-agenda-archives-mode)
9745 (defun org-scan-tags (action matcher &optional todo-only)
9746 "Scan headline tags with inheritance and produce output ACTION.
9748 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9749 or `agenda' to produce an entry list for an agenda view. It can also be
9750 a Lisp form or a function that should be called at each matched headline, in
9751 this case the return value is a list of all return values from these calls.
9753 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9754 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9755 only lines with a TODO keyword are included in the output."
9756 (require 'org-agenda)
9757 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9758 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9759 (org-re
9760 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9761 (props (list 'face 'default
9762 'done-face 'org-done
9763 'undone-face 'default
9764 'mouse-face 'highlight
9765 'org-not-done-regexp org-not-done-regexp
9766 'org-todo-regexp org-todo-regexp
9767 'keymap org-agenda-keymap
9768 'help-echo
9769 (format "mouse-2 or RET jump to org file %s"
9770 (abbreviate-file-name
9771 (or (buffer-file-name (buffer-base-buffer))
9772 (buffer-name (buffer-base-buffer)))))))
9773 (case-fold-search nil)
9774 lspos tags tags-list
9775 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9776 (llast 0) rtn rtn1 level category i txt
9777 todo marker entry priority)
9778 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9779 (setq action (list 'lambda nil action)))
9780 (save-excursion
9781 (goto-char (point-min))
9782 (when (eq action 'sparse-tree)
9783 (org-overview)
9784 (org-remove-occur-highlights))
9785 (while (re-search-forward re nil t)
9786 (catch :skip
9787 (setq todo (if (match-end 1) (match-string 2))
9788 tags (if (match-end 4) (match-string 4)))
9789 (goto-char (setq lspos (1+ (match-beginning 0))))
9790 (setq level (org-reduced-level (funcall outline-level))
9791 category (org-get-category))
9792 (setq i llast llast level)
9793 ;; remove tag lists from same and sublevels
9794 (while (>= i level)
9795 (when (setq entry (assoc i tags-alist))
9796 (setq tags-alist (delete entry tags-alist)))
9797 (setq i (1- i)))
9798 ;; add the next tags
9799 (when tags
9800 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9801 tags-alist
9802 (cons (cons level tags) tags-alist)))
9803 ;; compile tags for current headline
9804 (setq tags-list
9805 (if org-use-tag-inheritance
9806 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9807 tags))
9808 (when org-use-tag-inheritance
9809 (setcdr (car tags-alist)
9810 (mapcar (lambda (x)
9811 (setq x (copy-sequence x))
9812 (org-add-prop-inherited x))
9813 (cdar tags-alist))))
9814 (when (and tags org-use-tag-inheritance
9815 (not (eq t org-use-tag-inheritance)))
9816 ;; selective inheritance, remove uninherited ones
9817 (setcdr (car tags-alist)
9818 (org-remove-uniherited-tags (cdar tags-alist))))
9819 (when (and (or (not todo-only)
9820 (and (member todo org-not-done-keywords)
9821 (or (not org-agenda-tags-todo-honor-ignore-options)
9822 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9823 (let ((case-fold-search t)) (eval matcher))
9825 (not (member org-archive-tag tags-list))
9826 ;; we have an archive tag, should we use this anyway?
9827 (or (not org-agenda-skip-archived-trees)
9828 (and (eq action 'agenda) org-agenda-archives-mode))))
9829 (unless (eq action 'sparse-tree) (org-agenda-skip))
9831 ;; select this headline
9833 (cond
9834 ((eq action 'sparse-tree)
9835 (and org-highlight-sparse-tree-matches
9836 (org-get-heading) (match-end 0)
9837 (org-highlight-new-match
9838 (match-beginning 0) (match-beginning 1)))
9839 (org-show-context 'tags-tree))
9840 ((eq action 'agenda)
9841 (setq txt (org-format-agenda-item
9843 (concat
9844 (if org-tags-match-list-sublevels
9845 (make-string (1- level) ?.) "")
9846 (org-get-heading))
9847 category (org-get-tags-at))
9848 priority (org-get-priority txt))
9849 (goto-char lspos)
9850 (setq marker (org-agenda-new-marker))
9851 (org-add-props txt props
9852 'org-marker marker 'org-hd-marker marker 'org-category category
9853 'todo-state todo
9854 'priority priority 'type "tagsmatch")
9855 (push txt rtn))
9856 ((functionp action)
9857 (save-excursion
9858 (setq rtn1 (funcall action))
9859 (push rtn1 rtn))
9860 (goto-char (point-at-eol)))
9861 (t (error "Invalid action")))
9863 ;; if we are to skip sublevels, jump to end of subtree
9864 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9865 (when (and (eq action 'sparse-tree)
9866 (not org-sparse-tree-open-archived-trees))
9867 (org-hide-archived-subtrees (point-min) (point-max)))
9868 (nreverse rtn)))
9870 (defun org-remove-uniherited-tags (tags)
9871 "Remove all tags that are not inherited from the list TAGS."
9872 (cond
9873 ((eq org-use-tag-inheritance t)
9874 (if org-tags-exclude-from-inheritance
9875 (org-delete-all org-tags-exclude-from-inheritance tags)
9876 tags))
9877 ((not org-use-tag-inheritance) nil)
9878 ((stringp org-use-tag-inheritance)
9879 (delq nil (mapcar
9880 (lambda (x)
9881 (if (and (string-match org-use-tag-inheritance x)
9882 (not (member x org-tags-exclude-from-inheritance)))
9883 x nil))
9884 tags)))
9885 ((listp org-use-tag-inheritance)
9886 (delq nil (mapcar
9887 (lambda (x)
9888 (if (member x org-use-tag-inheritance) x nil))
9889 tags)))))
9891 (defvar todo-only) ;; dynamically scoped
9893 (defun org-tags-sparse-tree (&optional todo-only match)
9894 "Create a sparse tree according to tags string MATCH.
9895 MATCH can contain positive and negative selection of tags, like
9896 \"+WORK+URGENT-WITHBOSS\".
9897 If optional argument TODO-ONLY is non-nil, only select lines that are
9898 also TODO lines."
9899 (interactive "P")
9900 (org-prepare-agenda-buffers (list (current-buffer)))
9901 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9903 (defvar org-cached-props nil)
9904 (defun org-cached-entry-get (pom property)
9905 (if (or (eq t org-use-property-inheritance)
9906 (and (stringp org-use-property-inheritance)
9907 (string-match org-use-property-inheritance property))
9908 (and (listp org-use-property-inheritance)
9909 (member property org-use-property-inheritance)))
9910 ;; Caching is not possible, check it directly
9911 (org-entry-get pom property 'inherit)
9912 ;; Get all properties, so that we can do complicated checks easily
9913 (cdr (assoc property (or org-cached-props
9914 (setq org-cached-props
9915 (org-entry-properties pom)))))))
9917 (defun org-global-tags-completion-table (&optional files)
9918 "Return the list of all tags in all agenda buffer/files."
9919 (save-excursion
9920 (org-uniquify
9921 (delq nil
9922 (apply 'append
9923 (mapcar
9924 (lambda (file)
9925 (set-buffer (find-file-noselect file))
9926 (append (org-get-buffer-tags)
9927 (mapcar (lambda (x) (if (stringp (car-safe x))
9928 (list (car-safe x)) nil))
9929 org-tag-alist)))
9930 (if (and files (car files))
9931 files
9932 (org-agenda-files))))))))
9934 (defun org-make-tags-matcher (match)
9935 "Create the TAGS//TODO matcher form for the selection string MATCH."
9936 ;; todo-only is scoped dynamically into this function, and the function
9937 ;; may change it if the matcher asks for it.
9938 (unless match
9939 ;; Get a new match request, with completion
9940 (let ((org-last-tags-completion-table
9941 (org-global-tags-completion-table)))
9942 (setq match (org-completing-read-no-ido
9943 "Match: " 'org-tags-completion-function nil nil nil
9944 'org-tags-history))))
9946 ;; Parse the string and create a lisp form
9947 (let ((match0 match)
9948 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9949 minus tag mm
9950 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9951 orterms term orlist re-p str-p level-p level-op time-p
9952 prop-p pn pv po cat-p gv rest)
9953 (if (string-match "/+" match)
9954 ;; match contains also a todo-matching request
9955 (progn
9956 (setq tagsmatch (substring match 0 (match-beginning 0))
9957 todomatch (substring match (match-end 0)))
9958 (if (string-match "^!" todomatch)
9959 (setq todo-only t todomatch (substring todomatch 1)))
9960 (if (string-match "^\\s-*$" todomatch)
9961 (setq todomatch nil)))
9962 ;; only matching tags
9963 (setq tagsmatch match todomatch nil))
9965 ;; Make the tags matcher
9966 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9967 (setq tagsmatcher t)
9968 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9969 (while (setq term (pop orterms))
9970 (while (and (equal (substring term -1) "\\") orterms)
9971 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9972 (while (string-match re term)
9973 (setq rest (substring term (match-end 0))
9974 minus (and (match-end 1)
9975 (equal (match-string 1 term) "-"))
9976 tag (match-string 2 term)
9977 re-p (equal (string-to-char tag) ?{)
9978 level-p (match-end 4)
9979 prop-p (match-end 5)
9980 mm (cond
9981 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9982 (level-p
9983 (setq level-op (org-op-to-function (match-string 3 term)))
9984 `(,level-op level ,(string-to-number
9985 (match-string 4 term))))
9986 (prop-p
9987 (setq pn (match-string 5 term)
9988 po (match-string 6 term)
9989 pv (match-string 7 term)
9990 cat-p (equal pn "CATEGORY")
9991 re-p (equal (string-to-char pv) ?{)
9992 str-p (equal (string-to-char pv) ?\")
9993 time-p (save-match-data
9994 (string-match "^\"[[<].*[]>]\"$" pv))
9995 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9996 (if time-p (setq pv (org-matcher-time pv)))
9997 (setq po (org-op-to-function po (if time-p 'time str-p)))
9998 (cond
9999 ((equal pn "CATEGORY")
10000 (setq gv '(get-text-property (point) 'org-category)))
10001 ((equal pn "TODO")
10002 (setq gv 'todo))
10004 (setq gv `(org-cached-entry-get nil ,pn))))
10005 (if re-p
10006 (if (eq po 'org<>)
10007 `(not (string-match ,pv (or ,gv "")))
10008 `(string-match ,pv (or ,gv "")))
10009 (if str-p
10010 `(,po (or ,gv "") ,pv)
10011 `(,po (string-to-number (or ,gv ""))
10012 ,(string-to-number pv) ))))
10013 (t `(member ,(downcase tag) tags-list)))
10014 mm (if minus (list 'not mm) mm)
10015 term rest)
10016 (push mm tagsmatcher))
10017 (push (if (> (length tagsmatcher) 1)
10018 (cons 'and tagsmatcher)
10019 (car tagsmatcher))
10020 orlist)
10021 (setq tagsmatcher nil))
10022 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10023 (setq tagsmatcher
10024 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10025 ;; Make the todo matcher
10026 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10027 (setq todomatcher t)
10028 (setq orterms (org-split-string todomatch "|") orlist nil)
10029 (while (setq term (pop orterms))
10030 (while (string-match re term)
10031 (setq minus (and (match-end 1)
10032 (equal (match-string 1 term) "-"))
10033 kwd (match-string 2 term)
10034 re-p (equal (string-to-char kwd) ?{)
10035 term (substring term (match-end 0))
10036 mm (if re-p
10037 `(string-match ,(substring kwd 1 -1) todo)
10038 (list 'equal 'todo kwd))
10039 mm (if minus (list 'not mm) mm))
10040 (push mm todomatcher))
10041 (push (if (> (length todomatcher) 1)
10042 (cons 'and todomatcher)
10043 (car todomatcher))
10044 orlist)
10045 (setq todomatcher nil))
10046 (setq todomatcher (if (> (length orlist) 1)
10047 (cons 'or orlist) (car orlist))))
10049 ;; Return the string and lisp forms of the matcher
10050 (setq matcher (if todomatcher
10051 (list 'and tagsmatcher todomatcher)
10052 tagsmatcher))
10053 (cons match0 matcher)))
10055 (defun org-op-to-function (op &optional stringp)
10056 "Turn an operator into the appropriate function."
10057 (setq op
10058 (cond
10059 ((equal op "<" ) '(< string< org-time<))
10060 ((equal op ">" ) '(> org-string> org-time>))
10061 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10062 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10063 ((member op '("=" "==")) '(= string= org-time=))
10064 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10065 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10067 (defun org<> (a b) (not (= a b)))
10068 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10069 (defun org-string>= (a b) (not (string< a b)))
10070 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10071 (defun org-string<> (a b) (not (string= a b)))
10072 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10073 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10074 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10075 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10076 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10077 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10078 (defun org-2ft (s)
10079 "Convert S to a floating point time.
10080 If S is already a number, just return it. If it is a string, parse
10081 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10082 (cond
10083 ((numberp s) s)
10084 ((stringp s)
10085 (condition-case nil
10086 (float-time (apply 'encode-time (org-parse-time-string s)))
10087 (error 0.)))
10088 (t 0.)))
10090 (defun org-time-today ()
10091 "Time in seconds today at 0:00.
10092 Returns the float number of seconds since the beginning of the
10093 epoch to the beginning of today (00:00)."
10094 (float-time (apply 'encode-time
10095 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10097 (defun org-matcher-time (s)
10098 "Interpret a time comparison value."
10099 (save-match-data
10100 (cond
10101 ((string= s "<now>") (float-time))
10102 ((string= s "<today>") (org-time-today))
10103 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10104 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10105 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10106 (+ (org-time-today)
10107 (* (string-to-number (match-string 1 s))
10108 (cdr (assoc (match-string 2 s)
10109 '(("d" . 86400.0) ("w" . 604800.0)
10110 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10111 (t (org-2ft s)))))
10113 (defun org-match-any-p (re list)
10114 "Does re match any element of list?"
10115 (setq list (mapcar (lambda (x) (string-match re x)) list))
10116 (delq nil list))
10118 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10119 (defvar org-tags-overlay (org-make-overlay 1 1))
10120 (org-detach-overlay org-tags-overlay)
10122 (defun org-get-local-tags-at (&optional pos)
10123 "Get a list of tags defined in the current headline."
10124 (org-get-tags-at pos 'local))
10126 (defun org-get-local-tags ()
10127 "Get a list of tags defined in the current headline."
10128 (org-get-tags-at nil 'local))
10130 (defun org-get-tags-at (&optional pos local)
10131 "Get a list of all headline tags applicable at POS.
10132 POS defaults to point. If tags are inherited, the list contains
10133 the targets in the same sequence as the headlines appear, i.e.
10134 the tags of the current headline come last.
10135 When LOCAL is non-nil, only return tags from the current headline,
10136 ignore inherited ones."
10137 (interactive)
10138 (let (tags ltags lastpos parent)
10139 (save-excursion
10140 (save-restriction
10141 (widen)
10142 (goto-char (or pos (point)))
10143 (save-match-data
10144 (catch 'done
10145 (condition-case nil
10146 (progn
10147 (org-back-to-heading t)
10148 (while (not (equal lastpos (point)))
10149 (setq lastpos (point))
10150 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10151 (setq ltags (org-split-string
10152 (org-match-string-no-properties 1) ":"))
10153 (when parent
10154 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10155 (setq tags (append
10156 (if parent
10157 (org-remove-uniherited-tags ltags)
10158 ltags)
10159 tags)))
10160 (or org-use-tag-inheritance (throw 'done t))
10161 (if local (throw 'done t))
10162 (org-up-heading-all 1)
10163 (setq parent t)))
10164 (error nil)))))
10165 (append (org-remove-uniherited-tags org-file-tags) tags))))
10167 (defun org-add-prop-inherited (s)
10168 (add-text-properties 0 (length s) '(inherited t) s)
10171 (defun org-toggle-tag (tag &optional onoff)
10172 "Toggle the tag TAG for the current line.
10173 If ONOFF is `on' or `off', don't toggle but set to this state."
10174 (let (res current)
10175 (save-excursion
10176 (org-back-to-heading t)
10177 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10178 (point-at-eol) t)
10179 (progn
10180 (setq current (match-string 1))
10181 (replace-match ""))
10182 (setq current ""))
10183 (setq current (nreverse (org-split-string current ":")))
10184 (cond
10185 ((eq onoff 'on)
10186 (setq res t)
10187 (or (member tag current) (push tag current)))
10188 ((eq onoff 'off)
10189 (or (not (member tag current)) (setq current (delete tag current))))
10190 (t (if (member tag current)
10191 (setq current (delete tag current))
10192 (setq res t)
10193 (push tag current))))
10194 (end-of-line 1)
10195 (if current
10196 (progn
10197 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10198 (org-set-tags nil t))
10199 (delete-horizontal-space))
10200 (run-hooks 'org-after-tags-change-hook))
10201 res))
10203 (defun org-align-tags-here (to-col)
10204 ;; Assumes that this is a headline
10205 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10206 (beginning-of-line 1)
10207 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10208 (< pos (match-beginning 2)))
10209 (progn
10210 (setq tags-l (- (match-end 2) (match-beginning 2)))
10211 (goto-char (match-beginning 1))
10212 (insert " ")
10213 (delete-region (point) (1+ (match-beginning 2)))
10214 (setq ncol (max (1+ (current-column))
10215 (1+ col)
10216 (if (> to-col 0)
10217 to-col
10218 (- (abs to-col) tags-l))))
10219 (setq p (point))
10220 (insert (make-string (- ncol (current-column)) ?\ ))
10221 (setq ncol (current-column))
10222 (when indent-tabs-mode (tabify p (point-at-eol)))
10223 (org-move-to-column (min ncol col) t))
10224 (goto-char pos))))
10226 (defun org-set-tags-command (&optional arg just-align)
10227 "Call the set-tags command for the current entry."
10228 (interactive "P")
10229 (if (org-on-heading-p)
10230 (org-set-tags arg just-align)
10231 (save-excursion
10232 (org-back-to-heading t)
10233 (org-set-tags arg just-align))))
10235 (defun org-set-tags (&optional arg just-align)
10236 "Set the tags for the current headline.
10237 With prefix ARG, realign all tags in headings in the current buffer."
10238 (interactive "P")
10239 (let* ((re (concat "^" outline-regexp))
10240 (current (org-get-tags-string))
10241 (col (current-column))
10242 (org-setting-tags t)
10243 table current-tags inherited-tags ; computed below when needed
10244 tags p0 c0 c1 rpl)
10245 (if arg
10246 (save-excursion
10247 (goto-char (point-min))
10248 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10249 (while (re-search-forward re nil t)
10250 (org-set-tags nil t)
10251 (end-of-line 1)))
10252 (message "All tags realigned to column %d" org-tags-column))
10253 (if just-align
10254 (setq tags current)
10255 ;; Get a new set of tags from the user
10256 (save-excursion
10257 (setq table (append org-tag-persistent-alist
10258 (or org-tag-alist (org-get-buffer-tags)))
10259 org-last-tags-completion-table table
10260 current-tags (org-split-string current ":")
10261 inherited-tags (nreverse
10262 (nthcdr (length current-tags)
10263 (nreverse (org-get-tags-at))))
10264 tags
10265 (if (or (eq t org-use-fast-tag-selection)
10266 (and org-use-fast-tag-selection
10267 (delq nil (mapcar 'cdr table))))
10268 (org-fast-tag-selection
10269 current-tags inherited-tags table
10270 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10271 (let ((org-add-colon-after-tag-completion t))
10272 (org-trim
10273 (org-without-partial-completion
10274 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10275 nil nil current 'org-tags-history)))))))
10276 (while (string-match "[-+&]+" tags)
10277 ;; No boolean logic, just a list
10278 (setq tags (replace-match ":" t t tags))))
10280 (if (string-match "\\`[\t ]*\\'" tags)
10281 (setq tags "")
10282 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10283 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10285 ;; Insert new tags at the correct column
10286 (beginning-of-line 1)
10287 (cond
10288 ((and (equal current "") (equal tags "")))
10289 ((re-search-forward
10290 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10291 (point-at-eol) t)
10292 (if (equal tags "")
10293 (setq rpl "")
10294 (goto-char (match-beginning 0))
10295 (setq c0 (current-column) p0 (point)
10296 c1 (max (1+ c0) (if (> org-tags-column 0)
10297 org-tags-column
10298 (- (- org-tags-column) (length tags))))
10299 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10300 (replace-match rpl t t)
10301 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10302 tags)
10303 (t (error "Tags alignment failed")))
10304 (org-move-to-column col)
10305 (unless just-align
10306 (run-hooks 'org-after-tags-change-hook)))))
10308 (defun org-change-tag-in-region (beg end tag off)
10309 "Add or remove TAG for each entry in the region.
10310 This works in the agenda, and also in an org-mode buffer."
10311 (interactive
10312 (list (region-beginning) (region-end)
10313 (let ((org-last-tags-completion-table
10314 (if (org-mode-p)
10315 (org-get-buffer-tags)
10316 (org-global-tags-completion-table))))
10317 (org-ido-completing-read
10318 "Tag: " 'org-tags-completion-function nil nil nil
10319 'org-tags-history))
10320 (progn
10321 (message "[s]et or [r]emove? ")
10322 (equal (read-char-exclusive) ?r))))
10323 (if (fboundp 'deactivate-mark) (deactivate-mark))
10324 (let ((agendap (equal major-mode 'org-agenda-mode))
10325 l1 l2 m buf pos newhead (cnt 0))
10326 (goto-char end)
10327 (setq l2 (1- (org-current-line)))
10328 (goto-char beg)
10329 (setq l1 (org-current-line))
10330 (loop for l from l1 to l2 do
10331 (goto-line l)
10332 (setq m (get-text-property (point) 'org-hd-marker))
10333 (when (or (and (org-mode-p) (org-on-heading-p))
10334 (and agendap m))
10335 (setq buf (if agendap (marker-buffer m) (current-buffer))
10336 pos (if agendap m (point)))
10337 (with-current-buffer buf
10338 (save-excursion
10339 (save-restriction
10340 (goto-char pos)
10341 (setq cnt (1+ cnt))
10342 (org-toggle-tag tag (if off 'off 'on))
10343 (setq newhead (org-get-heading)))))
10344 (and agendap (org-agenda-change-all-lines newhead m))))
10345 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10347 (defun org-tags-completion-function (string predicate &optional flag)
10348 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10349 (confirm (lambda (x) (stringp (car x)))))
10350 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10351 (setq s1 (match-string 1 string)
10352 s2 (match-string 2 string))
10353 (setq s1 "" s2 string))
10354 (cond
10355 ((eq flag nil)
10356 ;; try completion
10357 (setq rtn (try-completion s2 ctable confirm))
10358 (if (stringp rtn)
10359 (setq rtn
10360 (concat s1 s2 (substring rtn (length s2))
10361 (if (and org-add-colon-after-tag-completion
10362 (assoc rtn ctable))
10363 ":" ""))))
10364 rtn)
10365 ((eq flag t)
10366 ;; all-completions
10367 (all-completions s2 ctable confirm)
10369 ((eq flag 'lambda)
10370 ;; exact match?
10371 (assoc s2 ctable)))
10374 (defun org-fast-tag-insert (kwd tags face &optional end)
10375 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10376 (insert (format "%-12s" (concat kwd ":"))
10377 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10378 (or end "")))
10380 (defun org-fast-tag-show-exit (flag)
10381 (save-excursion
10382 (goto-line 3)
10383 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10384 (replace-match ""))
10385 (when flag
10386 (end-of-line 1)
10387 (org-move-to-column (- (window-width) 19) t)
10388 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10390 (defun org-set-current-tags-overlay (current prefix)
10391 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10392 (if (featurep 'xemacs)
10393 (org-overlay-display org-tags-overlay (concat prefix s)
10394 'secondary-selection)
10395 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10396 (org-overlay-display org-tags-overlay (concat prefix s)))))
10398 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10399 "Fast tag selection with single keys.
10400 CURRENT is the current list of tags in the headline, INHERITED is the
10401 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10402 possibly with grouping information. TODO-TABLE is a similar table with
10403 TODO keywords, should these have keys assigned to them.
10404 If the keys are nil, a-z are automatically assigned.
10405 Returns the new tags string, or nil to not change the current settings."
10406 (let* ((fulltable (append table todo-table))
10407 (maxlen (apply 'max (mapcar
10408 (lambda (x)
10409 (if (stringp (car x)) (string-width (car x)) 0))
10410 fulltable)))
10411 (buf (current-buffer))
10412 (expert (eq org-fast-tag-selection-single-key 'expert))
10413 (buffer-tags nil)
10414 (fwidth (+ maxlen 3 1 3))
10415 (ncol (/ (- (window-width) 4) fwidth))
10416 (i-face 'org-done)
10417 (c-face 'org-todo)
10418 tg cnt e c char c1 c2 ntable tbl rtn
10419 ov-start ov-end ov-prefix
10420 (exit-after-next org-fast-tag-selection-single-key)
10421 (done-keywords org-done-keywords)
10422 groups ingroup)
10423 (save-excursion
10424 (beginning-of-line 1)
10425 (if (looking-at
10426 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10427 (setq ov-start (match-beginning 1)
10428 ov-end (match-end 1)
10429 ov-prefix "")
10430 (setq ov-start (1- (point-at-eol))
10431 ov-end (1+ ov-start))
10432 (skip-chars-forward "^\n\r")
10433 (setq ov-prefix
10434 (concat
10435 (buffer-substring (1- (point)) (point))
10436 (if (> (current-column) org-tags-column)
10438 (make-string (- org-tags-column (current-column)) ?\ ))))))
10439 (org-move-overlay org-tags-overlay ov-start ov-end)
10440 (save-window-excursion
10441 (if expert
10442 (set-buffer (get-buffer-create " *Org tags*"))
10443 (delete-other-windows)
10444 (split-window-vertically)
10445 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10446 (erase-buffer)
10447 (org-set-local 'org-done-keywords done-keywords)
10448 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10449 (org-fast-tag-insert "Current" current c-face "\n\n")
10450 (org-fast-tag-show-exit exit-after-next)
10451 (org-set-current-tags-overlay current ov-prefix)
10452 (setq tbl fulltable char ?a cnt 0)
10453 (while (setq e (pop tbl))
10454 (cond
10455 ((equal e '(:startgroup))
10456 (push '() groups) (setq ingroup t)
10457 (when (not (= cnt 0))
10458 (setq cnt 0)
10459 (insert "\n"))
10460 (insert "{ "))
10461 ((equal e '(:endgroup))
10462 (setq ingroup nil cnt 0)
10463 (insert "}\n"))
10464 ((equal e '(:newline))
10465 (when (not (= cnt 0))
10466 (setq cnt 0)
10467 (insert "\n")
10468 (setq e (car tbl))
10469 (while (equal (car tbl) '(:newline))
10470 (insert "\n")
10471 (setq tbl (cdr tbl)))))
10473 (setq tg (car e) c2 nil)
10474 (if (cdr e)
10475 (setq c (cdr e))
10476 ;; automatically assign a character.
10477 (setq c1 (string-to-char
10478 (downcase (substring
10479 tg (if (= (string-to-char tg) ?@) 1 0)))))
10480 (if (or (rassoc c1 ntable) (rassoc c1 table))
10481 (while (or (rassoc char ntable) (rassoc char table))
10482 (setq char (1+ char)))
10483 (setq c2 c1))
10484 (setq c (or c2 char)))
10485 (if ingroup (push tg (car groups)))
10486 (setq tg (org-add-props tg nil 'face
10487 (cond
10488 ((not (assoc tg table))
10489 (org-get-todo-face tg))
10490 ((member tg current) c-face)
10491 ((member tg inherited) i-face)
10492 (t nil))))
10493 (if (and (= cnt 0) (not ingroup)) (insert " "))
10494 (insert "[" c "] " tg (make-string
10495 (- fwidth 4 (length tg)) ?\ ))
10496 (push (cons tg c) ntable)
10497 (when (= (setq cnt (1+ cnt)) ncol)
10498 (insert "\n")
10499 (if ingroup (insert " "))
10500 (setq cnt 0)))))
10501 (setq ntable (nreverse ntable))
10502 (insert "\n")
10503 (goto-char (point-min))
10504 (if (not expert) (org-fit-window-to-buffer))
10505 (setq rtn
10506 (catch 'exit
10507 (while t
10508 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10509 (if groups " [!] no groups" " [!]groups")
10510 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10511 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10512 (cond
10513 ((= c ?\r) (throw 'exit t))
10514 ((= c ?!)
10515 (setq groups (not groups))
10516 (goto-char (point-min))
10517 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10518 ((= c ?\C-c)
10519 (if (not expert)
10520 (org-fast-tag-show-exit
10521 (setq exit-after-next (not exit-after-next)))
10522 (setq expert nil)
10523 (delete-other-windows)
10524 (split-window-vertically)
10525 (org-switch-to-buffer-other-window " *Org tags*")
10526 (org-fit-window-to-buffer)))
10527 ((or (= c ?\C-g)
10528 (and (= c ?q) (not (rassoc c ntable))))
10529 (org-detach-overlay org-tags-overlay)
10530 (setq quit-flag t))
10531 ((= c ?\ )
10532 (setq current nil)
10533 (if exit-after-next (setq exit-after-next 'now)))
10534 ((= c ?\t)
10535 (condition-case nil
10536 (setq tg (org-ido-completing-read
10537 "Tag: "
10538 (or buffer-tags
10539 (with-current-buffer buf
10540 (org-get-buffer-tags)))))
10541 (quit (setq tg "")))
10542 (when (string-match "\\S-" tg)
10543 (add-to-list 'buffer-tags (list tg))
10544 (if (member tg current)
10545 (setq current (delete tg current))
10546 (push tg current)))
10547 (if exit-after-next (setq exit-after-next 'now)))
10548 ((setq e (rassoc c todo-table) tg (car e))
10549 (with-current-buffer buf
10550 (save-excursion (org-todo tg)))
10551 (if exit-after-next (setq exit-after-next 'now)))
10552 ((setq e (rassoc c ntable) tg (car e))
10553 (if (member tg current)
10554 (setq current (delete tg current))
10555 (loop for g in groups do
10556 (if (member tg g)
10557 (mapc (lambda (x)
10558 (setq current (delete x current)))
10559 g)))
10560 (push tg current))
10561 (if exit-after-next (setq exit-after-next 'now))))
10563 ;; Create a sorted list
10564 (setq current
10565 (sort current
10566 (lambda (a b)
10567 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10568 (if (eq exit-after-next 'now) (throw 'exit t))
10569 (goto-char (point-min))
10570 (beginning-of-line 2)
10571 (delete-region (point) (point-at-eol))
10572 (org-fast-tag-insert "Current" current c-face)
10573 (org-set-current-tags-overlay current ov-prefix)
10574 (while (re-search-forward
10575 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10576 (setq tg (match-string 1))
10577 (add-text-properties
10578 (match-beginning 1) (match-end 1)
10579 (list 'face
10580 (cond
10581 ((member tg current) c-face)
10582 ((member tg inherited) i-face)
10583 (t (get-text-property (match-beginning 1) 'face))))))
10584 (goto-char (point-min)))))
10585 (org-detach-overlay org-tags-overlay)
10586 (if rtn
10587 (mapconcat 'identity current ":")
10588 nil))))
10590 (defun org-get-tags-string ()
10591 "Get the TAGS string in the current headline."
10592 (unless (org-on-heading-p t)
10593 (error "Not on a heading"))
10594 (save-excursion
10595 (beginning-of-line 1)
10596 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10597 (org-match-string-no-properties 1)
10598 "")))
10600 (defun org-get-tags ()
10601 "Get the list of tags specified in the current headline."
10602 (org-split-string (org-get-tags-string) ":"))
10604 (defun org-get-buffer-tags ()
10605 "Get a table of all tags used in the buffer, for completion."
10606 (let (tags)
10607 (save-excursion
10608 (goto-char (point-min))
10609 (while (re-search-forward
10610 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10611 (when (equal (char-after (point-at-bol 0)) ?*)
10612 (mapc (lambda (x) (add-to-list 'tags x))
10613 (org-split-string (org-match-string-no-properties 1) ":")))))
10614 (mapcar 'list tags)))
10616 ;;;; The mapping API
10618 ;;;###autoload
10619 (defun org-map-entries (func &optional match scope &rest skip)
10620 "Call FUNC at each headline selected by MATCH in SCOPE.
10622 FUNC is a function or a lisp form. The function will be called without
10623 arguments, with the cursor positioned at the beginning of the headline.
10624 The return values of all calls to the function will be collected and
10625 returned as a list.
10627 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10628 Only headlines that are matched by this query will be considered during
10629 the iteration. When MATCH is nil or t, all headlines will be
10630 visited by the iteration.
10632 SCOPE determines the scope of this command. It can be any of:
10634 nil The current buffer, respecting the restriction if any
10635 tree The subtree started with the entry at point
10636 file The current buffer, without restriction
10637 file-with-archives
10638 The current buffer, and any archives associated with it
10639 agenda All agenda files
10640 agenda-with-archives
10641 All agenda files with any archive files associated with them
10642 \(file1 file2 ...)
10643 If this is a list, all files in the list will be scanned
10645 The remaining args are treated as settings for the skipping facilities of
10646 the scanner. The following items can be given here:
10648 archive skip trees with the archive tag.
10649 comment skip trees with the COMMENT keyword
10650 function or Emacs Lisp form:
10651 will be used as value for `org-agenda-skip-function', so whenever
10652 the the function returns t, FUNC will not be called for that
10653 entry and search will continue from the point where the
10654 function leaves it."
10655 (let* ((org-agenda-archives-mode nil) ; just to make sure
10656 (org-agenda-skip-archived-trees (memq 'archive skip))
10657 (org-agenda-skip-comment-trees (memq 'comment skip))
10658 (org-agenda-skip-function
10659 (car (org-delete-all '(comment archive) skip)))
10660 (org-tags-match-list-sublevels t)
10661 matcher file res
10662 org-todo-keywords-for-agenda
10663 org-done-keywords-for-agenda
10664 org-todo-keyword-alist-for-agenda
10665 org-tag-alist-for-agenda)
10667 (cond
10668 ((eq match t) (setq matcher t))
10669 ((eq match nil) (setq matcher t))
10670 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10672 (save-excursion
10673 (save-restriction
10674 (when (eq scope 'tree)
10675 (org-back-to-heading t)
10676 (org-narrow-to-subtree)
10677 (setq scope nil))
10679 (if (not scope)
10680 (progn
10681 (org-prepare-agenda-buffers
10682 (list (buffer-file-name (current-buffer))))
10683 (setq res (org-scan-tags func matcher)))
10684 ;; Get the right scope
10685 (cond
10686 ((and scope (listp scope) (symbolp (car scope)))
10687 (setq scope (eval scope)))
10688 ((eq scope 'agenda)
10689 (setq scope (org-agenda-files t)))
10690 ((eq scope 'agenda-with-archives)
10691 (setq scope (org-agenda-files t))
10692 (setq scope (org-add-archive-files scope)))
10693 ((eq scope 'file)
10694 (setq scope (list (buffer-file-name))))
10695 ((eq scope 'file-with-archives)
10696 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10697 (org-prepare-agenda-buffers scope)
10698 (while (setq file (pop scope))
10699 (with-current-buffer (org-find-base-buffer-visiting file)
10700 (save-excursion
10701 (save-restriction
10702 (widen)
10703 (goto-char (point-min))
10704 (setq res (append res (org-scan-tags func matcher))))))))))
10705 res))
10707 ;;;; Properties
10709 ;;; Setting and retrieving properties
10711 (defconst org-special-properties
10712 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10713 "TIMESTAMP" "TIMESTAMP_IA")
10714 "The special properties valid in Org-mode.
10716 These are properties that are not defined in the property drawer,
10717 but in some other way.")
10719 (defconst org-default-properties
10720 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10721 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10722 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10723 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10724 "Some properties that are used by Org-mode for various purposes.
10725 Being in this list makes sure that they are offered for completion.")
10727 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10728 "Regular expression matching the first line of a property drawer.")
10730 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10731 "Regular expression matching the first line of a property drawer.")
10733 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10734 "Regular expression matching the first line of a property drawer.")
10736 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10737 "Regular expression matching the first line of a property drawer.")
10739 (defconst org-property-drawer-re
10740 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10741 org-property-end-re "\\)\n?")
10742 "Matches an entire property drawer.")
10744 (defconst org-clock-drawer-re
10745 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10746 org-property-end-re "\\)\n?")
10747 "Matches an entire clock drawer.")
10749 (defun org-property-action ()
10750 "Do an action on properties."
10751 (interactive)
10752 (let (c)
10753 (org-at-property-p)
10754 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10755 (setq c (read-char-exclusive))
10756 (cond
10757 ((equal c ?s)
10758 (call-interactively 'org-set-property))
10759 ((equal c ?d)
10760 (call-interactively 'org-delete-property))
10761 ((equal c ?D)
10762 (call-interactively 'org-delete-property-globally))
10763 ((equal c ?c)
10764 (call-interactively 'org-compute-property-at-point))
10765 (t (error "No such property action %c" c)))))
10767 (defun org-at-property-p ()
10768 "Is the cursor in a property line?"
10769 ;; FIXME: Does not check if we are actually in the drawer.
10770 ;; FIXME: also returns true on any drawers.....
10771 ;; This is used by C-c C-c for property action.
10772 (save-excursion
10773 (beginning-of-line 1)
10774 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10776 (defun org-get-property-block (&optional beg end force)
10777 "Return the (beg . end) range of the body of the property drawer.
10778 BEG and END can be beginning and end of subtree, if not given
10779 they will be found.
10780 If the drawer does not exist and FORCE is non-nil, create the drawer."
10781 (catch 'exit
10782 (save-excursion
10783 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10784 (end (or end (progn (outline-next-heading) (point)))))
10785 (goto-char beg)
10786 (if (re-search-forward org-property-start-re end t)
10787 (setq beg (1+ (match-end 0)))
10788 (if force
10789 (save-excursion
10790 (org-insert-property-drawer)
10791 (setq end (progn (outline-next-heading) (point))))
10792 (throw 'exit nil))
10793 (goto-char beg)
10794 (if (re-search-forward org-property-start-re end t)
10795 (setq beg (1+ (match-end 0)))))
10796 (if (re-search-forward org-property-end-re end t)
10797 (setq end (match-beginning 0))
10798 (or force (throw 'exit nil))
10799 (goto-char beg)
10800 (setq end beg)
10801 (org-indent-line-function)
10802 (insert ":END:\n"))
10803 (cons beg end)))))
10805 (defun org-entry-properties (&optional pom which)
10806 "Get all properties of the entry at point-or-marker POM.
10807 This includes the TODO keyword, the tags, time strings for deadline,
10808 scheduled, and clocking, and any additional properties defined in the
10809 entry. The return value is an alist, keys may occur multiple times
10810 if the property key was used several times.
10811 POM may also be nil, in which case the current entry is used.
10812 If WHICH is nil or `all', get all properties. If WHICH is
10813 `special' or `standard', only get that subclass."
10814 (setq which (or which 'all))
10815 (org-with-point-at pom
10816 (let ((clockstr (substring org-clock-string 0 -1))
10817 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10818 beg end range props sum-props key value string clocksum)
10819 (save-excursion
10820 (when (condition-case nil
10821 (and (org-mode-p) (org-back-to-heading t))
10822 (error nil))
10823 (setq beg (point))
10824 (setq sum-props (get-text-property (point) 'org-summaries))
10825 (setq clocksum (get-text-property (point) :org-clock-minutes))
10826 (outline-next-heading)
10827 (setq end (point))
10828 (when (memq which '(all special))
10829 ;; Get the special properties, like TODO and tags
10830 (goto-char beg)
10831 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10832 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10833 (when (looking-at org-priority-regexp)
10834 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10835 (when (and (setq value (org-get-tags-string))
10836 (string-match "\\S-" value))
10837 (push (cons "TAGS" value) props))
10838 (when (setq value (org-get-tags-at))
10839 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10840 props))
10841 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10842 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10843 string (if (equal key clockstr)
10844 (org-no-properties
10845 (org-trim
10846 (buffer-substring
10847 (match-beginning 3) (goto-char (point-at-eol)))))
10848 (substring (org-match-string-no-properties 3) 1 -1)))
10849 (unless key
10850 (if (= (char-after (match-beginning 3)) ?\[)
10851 (setq key "TIMESTAMP_IA")
10852 (setq key "TIMESTAMP")))
10853 (when (or (equal key clockstr) (not (assoc key props)))
10854 (push (cons key string) props)))
10858 (when (memq which '(all standard))
10859 ;; Get the standard properties, like :PORP: ...
10860 (setq range (org-get-property-block beg end))
10861 (when range
10862 (goto-char (car range))
10863 (while (re-search-forward
10864 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10865 (cdr range) t)
10866 (setq key (org-match-string-no-properties 1)
10867 value (org-trim (or (org-match-string-no-properties 2) "")))
10868 (unless (member key excluded)
10869 (push (cons key (or value "")) props)))))
10870 (if clocksum
10871 (push (cons "CLOCKSUM"
10872 (org-columns-number-to-string (/ (float clocksum) 60.)
10873 'add_times))
10874 props))
10875 (unless (assoc "CATEGORY" props)
10876 (setq value (or (org-get-category)
10877 (progn (org-refresh-category-properties)
10878 (org-get-category))))
10879 (push (cons "CATEGORY" value) props))
10880 (append sum-props (nreverse props)))))))
10882 (defun org-entry-get (pom property &optional inherit)
10883 "Get value of PROPERTY for entry at point-or-marker POM.
10884 If INHERIT is non-nil and the entry does not have the property,
10885 then also check higher levels of the hierarchy.
10886 If INHERIT is the symbol `selective', use inheritance only if the setting
10887 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10888 If the property is present but empty, the return value is the empty string.
10889 If the property is not present at all, nil is returned."
10890 (org-with-point-at pom
10891 (if (and inherit (if (eq inherit 'selective)
10892 (org-property-inherit-p property)
10894 (org-entry-get-with-inheritance property)
10895 (if (member property org-special-properties)
10896 ;; We need a special property. Use brute force, get all properties.
10897 (cdr (assoc property (org-entry-properties nil 'special)))
10898 (let ((range (org-get-property-block)))
10899 (if (and range
10900 (goto-char (car range))
10901 (re-search-forward
10902 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10903 (cdr range) t))
10904 ;; Found the property, return it.
10905 (if (match-end 1)
10906 (org-match-string-no-properties 1)
10907 "")))))))
10909 (defun org-property-or-variable-value (var &optional inherit)
10910 "Check if there is a property fixing the value of VAR.
10911 If yes, return this value. If not, return the current value of the variable."
10912 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10913 (if (and prop (stringp prop) (string-match "\\S-" prop))
10914 (read prop)
10915 (symbol-value var))))
10917 (defun org-entry-delete (pom property)
10918 "Delete the property PROPERTY from entry at point-or-marker POM."
10919 (org-with-point-at pom
10920 (if (member property org-special-properties)
10921 nil ; cannot delete these properties.
10922 (let ((range (org-get-property-block)))
10923 (if (and range
10924 (goto-char (car range))
10925 (re-search-forward
10926 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10927 (cdr range) t))
10928 (progn
10929 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10931 nil)))))
10933 ;; Multi-values properties are properties that contain multiple values
10934 ;; These values are assumed to be single words, separated by whitespace.
10935 (defun org-entry-add-to-multivalued-property (pom property value)
10936 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10937 (let* ((old (org-entry-get pom property))
10938 (values (and old (org-split-string old "[ \t]"))))
10939 (setq value (org-entry-protect-space value))
10940 (unless (member value values)
10941 (setq values (cons value values))
10942 (org-entry-put pom property
10943 (mapconcat 'identity values " ")))))
10945 (defun org-entry-remove-from-multivalued-property (pom property value)
10946 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10947 (let* ((old (org-entry-get pom property))
10948 (values (and old (org-split-string old "[ \t]"))))
10949 (setq value (org-entry-protect-space value))
10950 (when (member value values)
10951 (setq values (delete value values))
10952 (org-entry-put pom property
10953 (mapconcat 'identity values " ")))))
10955 (defun org-entry-member-in-multivalued-property (pom property value)
10956 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10957 (let* ((old (org-entry-get pom property))
10958 (values (and old (org-split-string old "[ \t]"))))
10959 (setq value (org-entry-protect-space value))
10960 (member value values)))
10962 (defun org-entry-get-multivalued-property (pom property)
10963 "Return a list of values in a multivalued property."
10964 (let* ((value (org-entry-get pom property))
10965 (values (and value (org-split-string value "[ \t]"))))
10966 (mapcar 'org-entry-restore-space values)))
10968 (defun org-entry-put-multivalued-property (pom property &rest values)
10969 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10970 VALUES should be a list of strings. Spaces will be protected."
10971 (org-entry-put pom property
10972 (mapconcat 'org-entry-protect-space values " "))
10973 (let* ((value (org-entry-get pom property))
10974 (values (and value (org-split-string value "[ \t]"))))
10975 (mapcar 'org-entry-restore-space values)))
10977 (defun org-entry-protect-space (s)
10978 "Protect spaces and newline in string S."
10979 (while (string-match " " s)
10980 (setq s (replace-match "%20" t t s)))
10981 (while (string-match "\n" s)
10982 (setq s (replace-match "%0A" t t s)))
10985 (defun org-entry-restore-space (s)
10986 "Restore spaces and newline in string S."
10987 (while (string-match "%20" s)
10988 (setq s (replace-match " " t t s)))
10989 (while (string-match "%0A" s)
10990 (setq s (replace-match "\n" t t s)))
10993 (defvar org-entry-property-inherited-from (make-marker)
10994 "Marker pointing to the entry from where a property was inherited.
10995 Each call to `org-entry-get-with-inheritance' will set this marker to the
10996 location of the entry where the inheritance search matched. If there was
10997 no match, the marker will point nowhere.
10998 Note that also `org-entry-get' calls this function, if the INHERIT flag
10999 is set.")
11001 (defun org-entry-get-with-inheritance (property)
11002 "Get entry property, and search higher levels if not present."
11003 (move-marker org-entry-property-inherited-from nil)
11004 (let (tmp)
11005 (save-excursion
11006 (save-restriction
11007 (widen)
11008 (catch 'ex
11009 (while t
11010 (when (setq tmp (org-entry-get nil property))
11011 (org-back-to-heading t)
11012 (move-marker org-entry-property-inherited-from (point))
11013 (throw 'ex tmp))
11014 (or (org-up-heading-safe) (throw 'ex nil)))))
11015 (or tmp
11016 (cdr (assoc property org-file-properties))
11017 (cdr (assoc property org-global-properties))
11018 (cdr (assoc property org-global-properties-fixed))))))
11020 (defun org-entry-put (pom property value)
11021 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11022 (org-with-point-at pom
11023 (org-back-to-heading t)
11024 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11025 range)
11026 (cond
11027 ((equal property "TODO")
11028 (when (and (stringp value) (string-match "\\S-" value)
11029 (not (member value org-todo-keywords-1)))
11030 (error "\"%s\" is not a valid TODO state" value))
11031 (if (or (not value)
11032 (not (string-match "\\S-" value)))
11033 (setq value 'none))
11034 (org-todo value)
11035 (org-set-tags nil 'align))
11036 ((equal property "PRIORITY")
11037 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11038 (string-to-char value) ?\ ))
11039 (org-set-tags nil 'align))
11040 ((equal property "SCHEDULED")
11041 (if (re-search-forward org-scheduled-time-regexp end t)
11042 (cond
11043 ((eq value 'earlier) (org-timestamp-change -1 'day))
11044 ((eq value 'later) (org-timestamp-change 1 'day))
11045 (t (call-interactively 'org-schedule)))
11046 (call-interactively 'org-schedule)))
11047 ((equal property "DEADLINE")
11048 (if (re-search-forward org-deadline-time-regexp end t)
11049 (cond
11050 ((eq value 'earlier) (org-timestamp-change -1 'day))
11051 ((eq value 'later) (org-timestamp-change 1 'day))
11052 (t (call-interactively 'org-deadline)))
11053 (call-interactively 'org-deadline)))
11054 ((member property org-special-properties)
11055 (error "The %s property can not yet be set with `org-entry-put'"
11056 property))
11057 (t ; a non-special property
11058 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11059 (setq range (org-get-property-block beg end 'force))
11060 (goto-char (car range))
11061 (if (re-search-forward
11062 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11063 (progn
11064 (delete-region (match-beginning 1) (match-end 1))
11065 (goto-char (match-beginning 1)))
11066 (goto-char (cdr range))
11067 (insert "\n")
11068 (backward-char 1)
11069 (org-indent-line-function)
11070 (insert ":" property ":"))
11071 (and value (insert " " value))
11072 (org-indent-line-function)))))))
11074 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11075 "Get all property keys in the current buffer.
11076 With INCLUDE-SPECIALS, also list the special properties that reflect things
11077 like tags and TODO state.
11078 With INCLUDE-DEFAULTS, also include properties that has special meaning
11079 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11080 With INCLUDE-COLUMNS, also include property names given in COLUMN
11081 formats in the current buffer."
11082 (let (rtn range cfmt s p)
11083 (save-excursion
11084 (save-restriction
11085 (widen)
11086 (goto-char (point-min))
11087 (while (re-search-forward org-property-start-re nil t)
11088 (setq range (org-get-property-block))
11089 (goto-char (car range))
11090 (while (re-search-forward
11091 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11092 (cdr range) t)
11093 (add-to-list 'rtn (org-match-string-no-properties 1)))
11094 (outline-next-heading))))
11096 (when include-specials
11097 (setq rtn (append org-special-properties rtn)))
11099 (when include-defaults
11100 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11102 (when include-columns
11103 (save-excursion
11104 (save-restriction
11105 (widen)
11106 (goto-char (point-min))
11107 (while (re-search-forward
11108 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11109 nil t)
11110 (setq cfmt (match-string 2) s 0)
11111 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11112 cfmt s)
11113 (setq s (match-end 0)
11114 p (match-string 1 cfmt))
11115 (unless (or (equal p "ITEM")
11116 (member p org-special-properties))
11117 (add-to-list 'rtn (match-string 1 cfmt))))))))
11119 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11121 (defun org-property-values (key)
11122 "Return a list of all values of property KEY."
11123 (save-excursion
11124 (save-restriction
11125 (widen)
11126 (goto-char (point-min))
11127 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11128 values)
11129 (while (re-search-forward re nil t)
11130 (add-to-list 'values (org-trim (match-string 1))))
11131 (delete "" values)))))
11133 (defun org-insert-property-drawer ()
11134 "Insert a property drawer into the current entry."
11135 (interactive)
11136 (org-back-to-heading t)
11137 (looking-at outline-regexp)
11138 (let ((indent (- (match-end 0)(match-beginning 0)))
11139 (beg (point))
11140 (re (concat "^[ \t]*" org-keyword-time-regexp))
11141 end hiddenp)
11142 (outline-next-heading)
11143 (setq end (point))
11144 (goto-char beg)
11145 (while (re-search-forward re end t))
11146 (setq hiddenp (org-invisible-p))
11147 (end-of-line 1)
11148 (and (equal (char-after) ?\n) (forward-char 1))
11149 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11150 (if (member (match-string 1) '("CLOCK:" ":END:"))
11151 ;; just skip this line
11152 (beginning-of-line 2)
11153 ;; Drawer start, find the end
11154 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11155 (beginning-of-line 1)))
11156 (org-skip-over-state-notes)
11157 (skip-chars-backward " \t\n\r")
11158 (if (eq (char-before) ?*) (forward-char 1))
11159 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11160 (beginning-of-line 0)
11161 (org-indent-to-column indent)
11162 (beginning-of-line 2)
11163 (org-indent-to-column indent)
11164 (beginning-of-line 0)
11165 (if hiddenp
11166 (save-excursion
11167 (org-back-to-heading t)
11168 (hide-entry))
11169 (org-flag-drawer t))))
11171 (defun org-set-property (property value)
11172 "In the current entry, set PROPERTY to VALUE.
11173 When called interactively, this will prompt for a property name, offering
11174 completion on existing and default properties. And then it will prompt
11175 for a value, offering completion either on allowed values (via an inherited
11176 xxx_ALL property) or on existing values in other instances of this property
11177 in the current file."
11178 (interactive
11179 (let* ((completion-ignore-case t)
11180 (keys (org-buffer-property-keys nil t t))
11181 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11182 (prop (if (member prop0 keys)
11183 prop0
11184 (or (cdr (assoc (downcase prop0)
11185 (mapcar (lambda (x) (cons (downcase x) x))
11186 keys)))
11187 prop0)))
11188 (cur (org-entry-get nil prop))
11189 (allowed (org-property-get-allowed-values nil prop 'table))
11190 (existing (mapcar 'list (org-property-values prop)))
11191 (val (if allowed
11192 (org-completing-read "Value: " allowed nil 'req-match)
11193 (let (org-completion-use-ido)
11194 (org-completing-read
11195 (concat "Value" (if (and cur (string-match "\\S-" cur))
11196 (concat "[" cur "]") "")
11197 ": ")
11198 existing nil nil "" nil cur)))))
11199 (list prop (if (equal val "") cur val))))
11200 (unless (equal (org-entry-get nil property) value)
11201 (org-entry-put nil property value)))
11203 (defun org-delete-property (property)
11204 "In the current entry, delete PROPERTY."
11205 (interactive
11206 (let* ((completion-ignore-case t)
11207 (prop (org-ido-completing-read
11208 "Property: " (org-entry-properties nil 'standard))))
11209 (list prop)))
11210 (message "Property %s %s" property
11211 (if (org-entry-delete nil property)
11212 "deleted"
11213 "was not present in the entry")))
11215 (defun org-delete-property-globally (property)
11216 "Remove PROPERTY globally, from all entries."
11217 (interactive
11218 (let* ((completion-ignore-case t)
11219 (prop (org-ido-completing-read
11220 "Globally remove property: "
11221 (mapcar 'list (org-buffer-property-keys)))))
11222 (list prop)))
11223 (save-excursion
11224 (save-restriction
11225 (widen)
11226 (goto-char (point-min))
11227 (let ((cnt 0))
11228 (while (re-search-forward
11229 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11230 nil t)
11231 (setq cnt (1+ cnt))
11232 (replace-match ""))
11233 (message "Property \"%s\" removed from %d entries" property cnt)))))
11235 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11237 (defun org-compute-property-at-point ()
11238 "Compute the property at point.
11239 This looks for an enclosing column format, extracts the operator and
11240 then applies it to the property in the column format's scope."
11241 (interactive)
11242 (unless (org-at-property-p)
11243 (error "Not at a property"))
11244 (let ((prop (org-match-string-no-properties 2)))
11245 (org-columns-get-format-and-top-level)
11246 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11247 (error "No operator defined for property %s" prop))
11248 (org-columns-compute prop)))
11250 (defun org-property-get-allowed-values (pom property &optional table)
11251 "Get allowed values for the property PROPERTY.
11252 When TABLE is non-nil, return an alist that can directly be used for
11253 completion."
11254 (let (vals)
11255 (cond
11256 ((equal property "TODO")
11257 (setq vals (org-with-point-at pom
11258 (append org-todo-keywords-1 '("")))))
11259 ((equal property "PRIORITY")
11260 (let ((n org-lowest-priority))
11261 (while (>= n org-highest-priority)
11262 (push (char-to-string n) vals)
11263 (setq n (1- n)))))
11264 ((member property org-special-properties))
11266 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11268 (when (and vals (string-match "\\S-" vals))
11269 (setq vals (car (read-from-string (concat "(" vals ")"))))
11270 (setq vals (mapcar (lambda (x)
11271 (cond ((stringp x) x)
11272 ((numberp x) (number-to-string x))
11273 ((symbolp x) (symbol-name x))
11274 (t "???")))
11275 vals)))))
11276 (if table (mapcar 'list vals) vals)))
11278 (defun org-property-previous-allowed-value (&optional previous)
11279 "Switch to the next allowed value for this property."
11280 (interactive)
11281 (org-property-next-allowed-value t))
11283 (defun org-property-next-allowed-value (&optional previous)
11284 "Switch to the next allowed value for this property."
11285 (interactive)
11286 (unless (org-at-property-p)
11287 (error "Not at a property"))
11288 (let* ((key (match-string 2))
11289 (value (match-string 3))
11290 (allowed (or (org-property-get-allowed-values (point) key)
11291 (and (member value '("[ ]" "[-]" "[X]"))
11292 '("[ ]" "[X]"))))
11293 nval)
11294 (unless allowed
11295 (error "Allowed values for this property have not been defined"))
11296 (if previous (setq allowed (reverse allowed)))
11297 (if (member value allowed)
11298 (setq nval (car (cdr (member value allowed)))))
11299 (setq nval (or nval (car allowed)))
11300 (if (equal nval value)
11301 (error "Only one allowed value for this property"))
11302 (org-at-property-p)
11303 (replace-match (concat " :" key ": " nval) t t)
11304 (org-indent-line-function)
11305 (beginning-of-line 1)
11306 (skip-chars-forward " \t")))
11308 (defun org-find-entry-with-id (ident)
11309 "Locate the entry that contains the ID property with exact value IDENT.
11310 IDENT can be a string, a symbol or a number, this function will search for
11311 the string representation of it.
11312 Return the position where this entry starts, or nil if there is no such entry."
11313 (interactive "sID: ")
11314 (let ((id (cond
11315 ((stringp ident) ident)
11316 ((symbol-name ident) (symbol-name ident))
11317 ((numberp ident) (number-to-string ident))
11318 (t (error "IDENT %s must be a string, symbol or number" ident))))
11319 (case-fold-search nil))
11320 (save-excursion
11321 (save-restriction
11322 (widen)
11323 (goto-char (point-min))
11324 (when (re-search-forward
11325 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11326 nil t)
11327 (org-back-to-heading)
11328 (point))))))
11330 ;;;; Timestamps
11332 (defvar org-last-changed-timestamp nil)
11333 (defvar org-last-inserted-timestamp nil
11334 "The last time stamp inserted with `org-insert-time-stamp'.")
11335 (defvar org-time-was-given) ; dynamically scoped parameter
11336 (defvar org-end-time-was-given) ; dynamically scoped parameter
11337 (defvar org-ts-what) ; dynamically scoped parameter
11339 (defun org-time-stamp (arg &optional inactive)
11340 "Prompt for a date/time and insert a time stamp.
11341 If the user specifies a time like HH:MM, or if this command is called
11342 with a prefix argument, the time stamp will contain date and time.
11343 Otherwise, only the date will be included. All parts of a date not
11344 specified by the user will be filled in from the current date/time.
11345 So if you press just return without typing anything, the time stamp
11346 will represent the current date/time. If there is already a timestamp
11347 at the cursor, it will be modified."
11348 (interactive "P")
11349 (let* ((ts nil)
11350 (default-time
11351 ;; Default time is either today, or, when entering a range,
11352 ;; the range start.
11353 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11354 (save-excursion
11355 (re-search-backward
11356 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11357 (- (point) 20) t)))
11358 (apply 'encode-time (org-parse-time-string (match-string 1)))
11359 (current-time)))
11360 (default-input (and ts (org-get-compact-tod ts)))
11361 org-time-was-given org-end-time-was-given time)
11362 (cond
11363 ((and (org-at-timestamp-p t)
11364 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11365 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11366 (insert "--")
11367 (setq time (let ((this-command this-command))
11368 (org-read-date arg 'totime nil nil
11369 default-time default-input)))
11370 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11371 ((org-at-timestamp-p t)
11372 (setq time (let ((this-command this-command))
11373 (org-read-date arg 'totime nil nil default-time default-input)))
11374 (when (org-at-timestamp-p t) ; just to get the match data
11375 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11376 (replace-match "")
11377 (setq org-last-changed-timestamp
11378 (org-insert-time-stamp
11379 time (or org-time-was-given arg)
11380 inactive nil nil (list org-end-time-was-given))))
11381 (message "Timestamp updated"))
11383 (setq time (let ((this-command this-command))
11384 (org-read-date arg 'totime nil nil default-time default-input)))
11385 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11386 nil nil (list org-end-time-was-given))))))
11388 ;; FIXME: can we use this for something else, like computing time differences?
11389 (defun org-get-compact-tod (s)
11390 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11391 (let* ((t1 (match-string 1 s))
11392 (h1 (string-to-number (match-string 2 s)))
11393 (m1 (string-to-number (match-string 3 s)))
11394 (t2 (and (match-end 4) (match-string 5 s)))
11395 (h2 (and t2 (string-to-number (match-string 6 s))))
11396 (m2 (and t2 (string-to-number (match-string 7 s))))
11397 dh dm)
11398 (if (not t2)
11400 (setq dh (- h2 h1) dm (- m2 m1))
11401 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11402 (concat t1 "+" (number-to-string dh)
11403 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11405 (defun org-time-stamp-inactive (&optional arg)
11406 "Insert an inactive time stamp.
11407 An inactive time stamp is enclosed in square brackets instead of angle
11408 brackets. It is inactive in the sense that it does not trigger agenda entries,
11409 does not link to the calendar and cannot be changed with the S-cursor keys.
11410 So these are more for recording a certain time/date."
11411 (interactive "P")
11412 (org-time-stamp arg 'inactive))
11414 (defvar org-date-ovl (org-make-overlay 1 1))
11415 (org-overlay-put org-date-ovl 'face 'org-warning)
11416 (org-detach-overlay org-date-ovl)
11418 (defvar org-ans1) ; dynamically scoped parameter
11419 (defvar org-ans2) ; dynamically scoped parameter
11421 (defvar org-plain-time-of-day-regexp) ; defined below
11423 (defvar org-overriding-default-time nil) ; dynamically scoped
11424 (defvar org-read-date-overlay nil)
11425 (defvar org-dcst nil) ; dynamically scoped
11427 (defun org-read-date (&optional with-time to-time from-string prompt
11428 default-time default-input)
11429 "Read a date, possibly a time, and make things smooth for the user.
11430 The prompt will suggest to enter an ISO date, but you can also enter anything
11431 which will at least partially be understood by `parse-time-string'.
11432 Unrecognized parts of the date will default to the current day, month, year,
11433 hour and minute. If this command is called to replace a timestamp at point,
11434 of to enter the second timestamp of a range, the default time is taken from the
11435 existing stamp. For example,
11436 3-2-5 --> 2003-02-05
11437 feb 15 --> currentyear-02-15
11438 sep 12 9 --> 2009-09-12
11439 12:45 --> today 12:45
11440 22 sept 0:34 --> currentyear-09-22 0:34
11441 12 --> currentyear-currentmonth-12
11442 Fri --> nearest Friday (today or later)
11443 etc.
11445 Furthermore you can specify a relative date by giving, as the *first* thing
11446 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11447 change in days weeks, months, years.
11448 With a single plus or minus, the date is relative to today. With a double
11449 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11450 +4d --> four days from today
11451 +4 --> same as above
11452 +2w --> two weeks from today
11453 ++5 --> five days from default date
11455 The function understands only English month and weekday abbreviations,
11456 but this can be configured with the variables `parse-time-months' and
11457 `parse-time-weekdays'.
11459 While prompting, a calendar is popped up - you can also select the
11460 date with the mouse (button 1). The calendar shows a period of three
11461 months. To scroll it to other months, use the keys `>' and `<'.
11462 If you don't like the calendar, turn it off with
11463 \(setq org-read-date-popup-calendar nil)
11465 With optional argument TO-TIME, the date will immediately be converted
11466 to an internal time.
11467 With an optional argument WITH-TIME, the prompt will suggest to also
11468 insert a time. Note that when WITH-TIME is not set, you can still
11469 enter a time, and this function will inform the calling routine about
11470 this change. The calling routine may then choose to change the format
11471 used to insert the time stamp into the buffer to include the time.
11472 With optional argument FROM-STRING, read from this string instead from
11473 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11474 the time/date that is used for everything that is not specified by the
11475 user."
11476 (require 'parse-time)
11477 (let* ((org-time-stamp-rounding-minutes
11478 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11479 (org-dcst org-display-custom-times)
11480 (ct (org-current-time))
11481 (def (or org-overriding-default-time default-time ct))
11482 (defdecode (decode-time def))
11483 (dummy (progn
11484 (when (< (nth 2 defdecode) org-extend-today-until)
11485 (setcar (nthcdr 2 defdecode) -1)
11486 (setcar (nthcdr 1 defdecode) 59)
11487 (setq def (apply 'encode-time defdecode)
11488 defdecode (decode-time def)))))
11489 (calendar-move-hook nil)
11490 (calendar-view-diary-initially-flag nil)
11491 (view-diary-entries-initially nil)
11492 (calendar-view-holidays-initially-flag nil)
11493 (view-calendar-holidays-initially nil)
11494 (timestr (format-time-string
11495 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11496 (prompt (concat (if prompt (concat prompt " ") "")
11497 (format "Date+time [%s]: " timestr)))
11498 ans (org-ans0 "") org-ans1 org-ans2 final)
11500 (cond
11501 (from-string (setq ans from-string))
11502 (org-read-date-popup-calendar
11503 (save-excursion
11504 (save-window-excursion
11505 (calendar)
11506 (calendar-forward-day (- (time-to-days def)
11507 (calendar-absolute-from-gregorian
11508 (calendar-current-date))))
11509 (org-eval-in-calendar nil t)
11510 (let* ((old-map (current-local-map))
11511 (map (copy-keymap calendar-mode-map))
11512 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11513 (org-defkey map (kbd "RET") 'org-calendar-select)
11514 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11515 'org-calendar-select-mouse)
11516 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11517 'org-calendar-select-mouse)
11518 (org-defkey minibuffer-local-map [(meta shift left)]
11519 (lambda () (interactive)
11520 (org-eval-in-calendar '(calendar-backward-month 1))))
11521 (org-defkey minibuffer-local-map [(meta shift right)]
11522 (lambda () (interactive)
11523 (org-eval-in-calendar '(calendar-forward-month 1))))
11524 (org-defkey minibuffer-local-map [(meta shift up)]
11525 (lambda () (interactive)
11526 (org-eval-in-calendar '(calendar-backward-year 1))))
11527 (org-defkey minibuffer-local-map [(meta shift down)]
11528 (lambda () (interactive)
11529 (org-eval-in-calendar '(calendar-forward-year 1))))
11530 (org-defkey minibuffer-local-map [(shift up)]
11531 (lambda () (interactive)
11532 (org-eval-in-calendar '(calendar-backward-week 1))))
11533 (org-defkey minibuffer-local-map [(shift down)]
11534 (lambda () (interactive)
11535 (org-eval-in-calendar '(calendar-forward-week 1))))
11536 (org-defkey minibuffer-local-map [(shift left)]
11537 (lambda () (interactive)
11538 (org-eval-in-calendar '(calendar-backward-day 1))))
11539 (org-defkey minibuffer-local-map [(shift right)]
11540 (lambda () (interactive)
11541 (org-eval-in-calendar '(calendar-forward-day 1))))
11542 (org-defkey minibuffer-local-map ">"
11543 (lambda () (interactive)
11544 (org-eval-in-calendar '(scroll-calendar-left 1))))
11545 (org-defkey minibuffer-local-map "<"
11546 (lambda () (interactive)
11547 (org-eval-in-calendar '(scroll-calendar-right 1))))
11548 (unwind-protect
11549 (progn
11550 (use-local-map map)
11551 (add-hook 'post-command-hook 'org-read-date-display)
11552 (setq org-ans0 (read-string prompt default-input nil nil))
11553 ;; org-ans0: from prompt
11554 ;; org-ans1: from mouse click
11555 ;; org-ans2: from calendar motion
11556 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11557 (remove-hook 'post-command-hook 'org-read-date-display)
11558 (use-local-map old-map)
11559 (when org-read-date-overlay
11560 (org-delete-overlay org-read-date-overlay)
11561 (setq org-read-date-overlay nil)))))))
11563 (t ; Naked prompt only
11564 (unwind-protect
11565 (setq ans (read-string prompt default-input nil timestr))
11566 (when org-read-date-overlay
11567 (org-delete-overlay org-read-date-overlay)
11568 (setq org-read-date-overlay nil)))))
11570 (setq final (org-read-date-analyze ans def defdecode))
11572 (if to-time
11573 (apply 'encode-time final)
11574 (if (and (boundp 'org-time-was-given) org-time-was-given)
11575 (format "%04d-%02d-%02d %02d:%02d"
11576 (nth 5 final) (nth 4 final) (nth 3 final)
11577 (nth 2 final) (nth 1 final))
11578 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11579 (defvar def)
11580 (defvar defdecode)
11581 (defvar with-time)
11582 (defun org-read-date-display ()
11583 "Display the current date prompt interpretation in the minibuffer."
11584 (when org-read-date-display-live
11585 (when org-read-date-overlay
11586 (org-delete-overlay org-read-date-overlay))
11587 (let ((p (point)))
11588 (end-of-line 1)
11589 (while (not (equal (buffer-substring
11590 (max (point-min) (- (point) 4)) (point))
11591 " "))
11592 (insert " "))
11593 (goto-char p))
11594 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11595 " " (or org-ans1 org-ans2)))
11596 (org-end-time-was-given nil)
11597 (f (org-read-date-analyze ans def defdecode))
11598 (fmts (if org-dcst
11599 org-time-stamp-custom-formats
11600 org-time-stamp-formats))
11601 (fmt (if (or with-time
11602 (and (boundp 'org-time-was-given) org-time-was-given))
11603 (cdr fmts)
11604 (car fmts)))
11605 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11606 (when (and org-end-time-was-given
11607 (string-match org-plain-time-of-day-regexp txt))
11608 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11609 org-end-time-was-given
11610 (substring txt (match-end 0)))))
11611 (setq org-read-date-overlay
11612 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11613 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11615 (defun org-read-date-analyze (ans def defdecode)
11616 "Analyse the combined answer of the date prompt."
11617 ;; FIXME: cleanup and comment
11618 (let (delta deltan deltaw deltadef year month day
11619 hour minute second wday pm h2 m2 tl wday1
11620 iso-year iso-weekday iso-week iso-year iso-date)
11622 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11623 (setq ans "+0"))
11625 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11626 (setq ans (replace-match "" t t ans)
11627 deltan (car delta)
11628 deltaw (nth 1 delta)
11629 deltadef (nth 2 delta)))
11631 ;; Check if there is an iso week date in there
11632 ;; If yes, sore the info and postpone interpreting it until the rest
11633 ;; of the parsing is done
11634 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11635 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11636 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11637 iso-week (string-to-number (match-string 2 ans)))
11638 (setq ans (replace-match "" t t ans)))
11640 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11641 (when (string-match
11642 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11643 (setq year (if (match-end 2)
11644 (string-to-number (match-string 2 ans))
11645 (string-to-number (format-time-string "%Y")))
11646 month (string-to-number (match-string 3 ans))
11647 day (string-to-number (match-string 4 ans)))
11648 (if (< year 100) (setq year (+ 2000 year)))
11649 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11650 t nil ans)))
11651 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11652 ;; If there is a time with am/pm, and *no* time without it, we convert
11653 ;; so that matching will be successful.
11654 (loop for i from 1 to 2 do ; twice, for end time as well
11655 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11656 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11657 (setq hour (string-to-number (match-string 1 ans))
11658 minute (if (match-end 3)
11659 (string-to-number (match-string 3 ans))
11661 pm (equal ?p
11662 (string-to-char (downcase (match-string 4 ans)))))
11663 (if (and (= hour 12) (not pm))
11664 (setq hour 0)
11665 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11666 (setq ans (replace-match (format "%02d:%02d" hour minute)
11667 t t ans))))
11669 ;; Check if a time range is given as a duration
11670 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11671 (setq hour (string-to-number (match-string 1 ans))
11672 h2 (+ hour (string-to-number (match-string 3 ans)))
11673 minute (string-to-number (match-string 2 ans))
11674 m2 (+ minute (if (match-end 5) (string-to-number
11675 (match-string 5 ans))0)))
11676 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11677 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11678 t t ans)))
11680 ;; Check if there is a time range
11681 (when (boundp 'org-end-time-was-given)
11682 (setq org-time-was-given nil)
11683 (when (and (string-match org-plain-time-of-day-regexp ans)
11684 (match-end 8))
11685 (setq org-end-time-was-given (match-string 8 ans))
11686 (setq ans (concat (substring ans 0 (match-beginning 7))
11687 (substring ans (match-end 7))))))
11689 (setq tl (parse-time-string ans)
11690 day (or (nth 3 tl) (nth 3 defdecode))
11691 month (or (nth 4 tl)
11692 (if (and org-read-date-prefer-future
11693 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11694 (1+ (nth 4 defdecode))
11695 (nth 4 defdecode)))
11696 year (or (nth 5 tl)
11697 (if (and org-read-date-prefer-future
11698 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11699 (1+ (nth 5 defdecode))
11700 (nth 5 defdecode)))
11701 hour (or (nth 2 tl) (nth 2 defdecode))
11702 minute (or (nth 1 tl) (nth 1 defdecode))
11703 second (or (nth 0 tl) 0)
11704 wday (nth 6 tl))
11706 ;; Special date definitions below
11707 (cond
11708 (iso-week
11709 ;; There was an iso week
11710 (setq year (or iso-year year)
11711 day (or iso-weekday wday 1)
11712 wday nil ; to make sure that the trigger below does not match
11713 iso-date (calendar-gregorian-from-absolute
11714 (calendar-absolute-from-iso
11715 (list iso-week day year))))
11716 ; FIXME: Should we also push ISO weeks into the future?
11717 ; (when (and org-read-date-prefer-future
11718 ; (not iso-year)
11719 ; (< (calendar-absolute-from-gregorian iso-date)
11720 ; (time-to-days (current-time))))
11721 ; (setq year (1+ year)
11722 ; iso-date (calendar-gregorian-from-absolute
11723 ; (calendar-absolute-from-iso
11724 ; (list iso-week day year)))))
11725 (setq month (car iso-date)
11726 year (nth 2 iso-date)
11727 day (nth 1 iso-date)))
11728 (deltan
11729 (unless deltadef
11730 (let ((now (decode-time (current-time))))
11731 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11732 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11733 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11734 ((equal deltaw "m") (setq month (+ month deltan)))
11735 ((equal deltaw "y") (setq year (+ year deltan)))))
11736 ((and wday (not (nth 3 tl)))
11737 ;; Weekday was given, but no day, so pick that day in the week
11738 ;; on or after the derived date.
11739 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11740 (unless (equal wday wday1)
11741 (setq day (+ day (% (- wday wday1 -7) 7))))))
11742 (if (and (boundp 'org-time-was-given)
11743 (nth 2 tl))
11744 (setq org-time-was-given t))
11745 (if (< year 100) (setq year (+ 2000 year)))
11746 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11747 (list second minute hour day month year)))
11749 (defvar parse-time-weekdays)
11751 (defun org-read-date-get-relative (s today default)
11752 "Check string S for special relative date string.
11753 TODAY and DEFAULT are internal times, for today and for a default.
11754 Return shift list (N what def-flag)
11755 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11756 N is the number of WHATs to shift.
11757 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11758 the DEFAULT date rather than TODAY."
11759 (when (and
11760 (string-match
11761 (concat
11762 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11763 "\\([0-9]+\\)?"
11764 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11765 "\\([ \t]\\|$\\)") s)
11766 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11767 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11768 (string-to-char (substring (match-string 1 s) -1))
11769 ?+))
11770 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11771 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11772 (what (if (match-end 3) (match-string 3 s) "d"))
11773 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11774 (date (if rel default today))
11775 (wday (nth 6 (decode-time date)))
11776 delta)
11777 (if wday1
11778 (progn
11779 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11780 (if (= dir ?-) (setq delta (- delta 7)))
11781 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11782 (list delta "d" rel))
11783 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11785 (defun org-eval-in-calendar (form &optional keepdate)
11786 "Eval FORM in the calendar window and return to current window.
11787 Also, store the cursor date in variable org-ans2."
11788 (let ((sw (selected-window)))
11789 (select-window (get-buffer-window "*Calendar*"))
11790 (eval form)
11791 (when (and (not keepdate) (calendar-cursor-to-date))
11792 (let* ((date (calendar-cursor-to-date))
11793 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11794 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11795 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11796 (select-window sw)))
11798 (defun org-calendar-select ()
11799 "Return to `org-read-date' with the date currently selected.
11800 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11801 (interactive)
11802 (when (calendar-cursor-to-date)
11803 (let* ((date (calendar-cursor-to-date))
11804 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11805 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11806 (if (active-minibuffer-window) (exit-minibuffer))))
11808 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11809 "Insert a date stamp for the date given by the internal TIME.
11810 WITH-HM means, use the stamp format that includes the time of the day.
11811 INACTIVE means use square brackets instead of angular ones, so that the
11812 stamp will not contribute to the agenda.
11813 PRE and POST are optional strings to be inserted before and after the
11814 stamp.
11815 The command returns the inserted time stamp."
11816 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11817 stamp)
11818 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11819 (insert-before-markers (or pre ""))
11820 (insert-before-markers (setq stamp (format-time-string fmt time)))
11821 (when (listp extra)
11822 (setq extra (car extra))
11823 (if (and (stringp extra)
11824 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11825 (setq extra (format "-%02d:%02d"
11826 (string-to-number (match-string 1 extra))
11827 (string-to-number (match-string 2 extra))))
11828 (setq extra nil)))
11829 (when extra
11830 (backward-char 1)
11831 (insert-before-markers extra)
11832 (forward-char 1))
11833 (insert-before-markers (or post ""))
11834 (setq org-last-inserted-timestamp stamp)))
11836 (defun org-toggle-time-stamp-overlays ()
11837 "Toggle the use of custom time stamp formats."
11838 (interactive)
11839 (setq org-display-custom-times (not org-display-custom-times))
11840 (unless org-display-custom-times
11841 (let ((p (point-min)) (bmp (buffer-modified-p)))
11842 (while (setq p (next-single-property-change p 'display))
11843 (if (and (get-text-property p 'display)
11844 (eq (get-text-property p 'face) 'org-date))
11845 (remove-text-properties
11846 p (setq p (next-single-property-change p 'display))
11847 '(display t))))
11848 (set-buffer-modified-p bmp)))
11849 (if (featurep 'xemacs)
11850 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11851 (org-restart-font-lock)
11852 (setq org-table-may-need-update t)
11853 (if org-display-custom-times
11854 (message "Time stamps are overlayed with custom format")
11855 (message "Time stamp overlays removed")))
11857 (defun org-display-custom-time (beg end)
11858 "Overlay modified time stamp format over timestamp between BEG and END."
11859 (let* ((ts (buffer-substring beg end))
11860 t1 w1 with-hm tf time str w2 (off 0))
11861 (save-match-data
11862 (setq t1 (org-parse-time-string ts t))
11863 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11864 (setq off (- (match-end 0) (match-beginning 0)))))
11865 (setq end (- end off))
11866 (setq w1 (- end beg)
11867 with-hm (and (nth 1 t1) (nth 2 t1))
11868 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11869 time (org-fix-decoded-time t1)
11870 str (org-add-props
11871 (format-time-string
11872 (substring tf 1 -1) (apply 'encode-time time))
11873 nil 'mouse-face 'highlight)
11874 w2 (length str))
11875 (if (not (= w2 w1))
11876 (add-text-properties (1+ beg) (+ 2 beg)
11877 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11878 (if (featurep 'xemacs)
11879 (progn
11880 (put-text-property beg end 'invisible t)
11881 (put-text-property beg end 'end-glyph (make-glyph str)))
11882 (put-text-property beg end 'display str))))
11884 (defun org-translate-time (string)
11885 "Translate all timestamps in STRING to custom format.
11886 But do this only if the variable `org-display-custom-times' is set."
11887 (when org-display-custom-times
11888 (save-match-data
11889 (let* ((start 0)
11890 (re org-ts-regexp-both)
11891 t1 with-hm inactive tf time str beg end)
11892 (while (setq start (string-match re string start))
11893 (setq beg (match-beginning 0)
11894 end (match-end 0)
11895 t1 (save-match-data
11896 (org-parse-time-string (substring string beg end) t))
11897 with-hm (and (nth 1 t1) (nth 2 t1))
11898 inactive (equal (substring string beg (1+ beg)) "[")
11899 tf (funcall (if with-hm 'cdr 'car)
11900 org-time-stamp-custom-formats)
11901 time (org-fix-decoded-time t1)
11902 str (format-time-string
11903 (concat
11904 (if inactive "[" "<") (substring tf 1 -1)
11905 (if inactive "]" ">"))
11906 (apply 'encode-time time))
11907 string (replace-match str t t string)
11908 start (+ start (length str)))))))
11909 string)
11911 (defun org-fix-decoded-time (time)
11912 "Set 0 instead of nil for the first 6 elements of time.
11913 Don't touch the rest."
11914 (let ((n 0))
11915 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11917 (defun org-days-to-time (timestamp-string)
11918 "Difference between TIMESTAMP-STRING and now in days."
11919 (- (time-to-days (org-time-string-to-time timestamp-string))
11920 (time-to-days (current-time))))
11922 (defun org-deadline-close (timestamp-string &optional ndays)
11923 "Is the time in TIMESTAMP-STRING close to the current date?"
11924 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11925 (and (< (org-days-to-time timestamp-string) ndays)
11926 (not (org-entry-is-done-p))))
11928 (defun org-get-wdays (ts)
11929 "Get the deadline lead time appropriate for timestring TS."
11930 (cond
11931 ((<= org-deadline-warning-days 0)
11932 ;; 0 or negative, enforce this value no matter what
11933 (- org-deadline-warning-days))
11934 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
11935 ;; lead time is specified.
11936 (floor (* (string-to-number (match-string 1 ts))
11937 (cdr (assoc (match-string 2 ts)
11938 '(("d" . 1) ("w" . 7)
11939 ("m" . 30.4) ("y" . 365.25)))))))
11940 ;; go for the default.
11941 (t org-deadline-warning-days)))
11943 (defun org-calendar-select-mouse (ev)
11944 "Return to `org-read-date' with the date currently selected.
11945 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11946 (interactive "e")
11947 (mouse-set-point ev)
11948 (when (calendar-cursor-to-date)
11949 (let* ((date (calendar-cursor-to-date))
11950 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11951 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11952 (if (active-minibuffer-window) (exit-minibuffer))))
11954 (defun org-check-deadlines (ndays)
11955 "Check if there are any deadlines due or past due.
11956 A deadline is considered due if it happens within `org-deadline-warning-days'
11957 days from today's date. If the deadline appears in an entry marked DONE,
11958 it is not shown. The prefix arg NDAYS can be used to test that many
11959 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11960 (interactive "P")
11961 (let* ((org-warn-days
11962 (cond
11963 ((equal ndays '(4)) 100000)
11964 (ndays (prefix-numeric-value ndays))
11965 (t (abs org-deadline-warning-days))))
11966 (case-fold-search nil)
11967 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11968 (callback
11969 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11971 (message "%d deadlines past-due or due within %d days"
11972 (org-occur regexp nil callback)
11973 org-warn-days)))
11975 (defun org-check-before-date (date)
11976 "Check if there are deadlines or scheduled entries before DATE."
11977 (interactive (list (org-read-date)))
11978 (let ((case-fold-search nil)
11979 (regexp (concat "\\<\\(" org-deadline-string
11980 "\\|" org-scheduled-string
11981 "\\) *<\\([^>]+\\)>"))
11982 (callback
11983 (lambda () (time-less-p
11984 (org-time-string-to-time (match-string 2))
11985 (org-time-string-to-time date)))))
11986 (message "%d entries before %s"
11987 (org-occur regexp nil callback) date)))
11989 (defun org-evaluate-time-range (&optional to-buffer)
11990 "Evaluate a time range by computing the difference between start and end.
11991 Normally the result is just printed in the echo area, but with prefix arg
11992 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11993 If the time range is actually in a table, the result is inserted into the
11994 next column.
11995 For time difference computation, a year is assumed to be exactly 365
11996 days in order to avoid rounding problems."
11997 (interactive "P")
11999 (org-clock-update-time-maybe)
12000 (save-excursion
12001 (unless (org-at-date-range-p t)
12002 (goto-char (point-at-bol))
12003 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12004 (if (not (org-at-date-range-p t))
12005 (error "Not at a time-stamp range, and none found in current line")))
12006 (let* ((ts1 (match-string 1))
12007 (ts2 (match-string 2))
12008 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12009 (match-end (match-end 0))
12010 (time1 (org-time-string-to-time ts1))
12011 (time2 (org-time-string-to-time ts2))
12012 (t1 (time-to-seconds time1))
12013 (t2 (time-to-seconds time2))
12014 (diff (abs (- t2 t1)))
12015 (negative (< (- t2 t1) 0))
12016 ;; (ys (floor (* 365 24 60 60)))
12017 (ds (* 24 60 60))
12018 (hs (* 60 60))
12019 (fy "%dy %dd %02d:%02d")
12020 (fy1 "%dy %dd")
12021 (fd "%dd %02d:%02d")
12022 (fd1 "%dd")
12023 (fh "%02d:%02d")
12024 y d h m align)
12025 (if havetime
12026 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12028 d (floor (/ diff ds)) diff (mod diff ds)
12029 h (floor (/ diff hs)) diff (mod diff hs)
12030 m (floor (/ diff 60)))
12031 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12033 d (floor (+ (/ diff ds) 0.5))
12034 h 0 m 0))
12035 (if (not to-buffer)
12036 (message "%s" (org-make-tdiff-string y d h m))
12037 (if (org-at-table-p)
12038 (progn
12039 (goto-char match-end)
12040 (setq align t)
12041 (and (looking-at " *|") (goto-char (match-end 0))))
12042 (goto-char match-end))
12043 (if (looking-at
12044 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12045 (replace-match ""))
12046 (if negative (insert " -"))
12047 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12048 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12049 (insert " " (format fh h m))))
12050 (if align (org-table-align))
12051 (message "Time difference inserted")))))
12053 (defun org-make-tdiff-string (y d h m)
12054 (let ((fmt "")
12055 (l nil))
12056 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12057 l (push y l)))
12058 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12059 l (push d l)))
12060 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12061 l (push h l)))
12062 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12063 l (push m l)))
12064 (apply 'format fmt (nreverse l))))
12066 (defun org-time-string-to-time (s)
12067 (apply 'encode-time (org-parse-time-string s)))
12069 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12070 "Convert a time stamp to an absolute day number.
12071 If there is a specifyer for a cyclic time stamp, get the closest date to
12072 DAYNR.
12073 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12074 (cond
12075 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12076 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12077 daynr
12078 (+ daynr 1000)))
12079 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12080 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12081 (time-to-days (current-time))) (match-string 0 s)
12082 prefer show-all))
12083 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12085 (defun org-days-to-iso-week (days)
12086 "Return the iso week number."
12087 (require 'cal-iso)
12088 (car (calendar-iso-from-absolute days)))
12090 (defun org-small-year-to-year (year)
12091 "Convert 2-digit years into 4-digit years.
12092 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12093 The year 2000 cannot be abbreviated. Any year larger than 99
12094 is returned unchanged."
12095 (if (< year 38)
12096 (setq year (+ 2000 year))
12097 (if (< year 100)
12098 (setq year (+ 1900 year))))
12099 year)
12101 (defun org-time-from-absolute (d)
12102 "Return the time corresponding to date D.
12103 D may be an absolute day number, or a calendar-type list (month day year)."
12104 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12105 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12107 (defun org-calendar-holiday ()
12108 "List of holidays, for Diary display in Org-mode."
12109 (require 'holidays)
12110 (let ((hl (funcall
12111 (if (fboundp 'calendar-check-holidays)
12112 'calendar-check-holidays 'check-calendar-holidays) date)))
12113 (if hl (mapconcat 'identity hl "; "))))
12115 (defun org-diary-sexp-entry (sexp entry date)
12116 "Process a SEXP diary ENTRY for DATE."
12117 (require 'diary-lib)
12118 (let ((result (if calendar-debug-sexp
12119 (let ((stack-trace-on-error t))
12120 (eval (car (read-from-string sexp))))
12121 (condition-case nil
12122 (eval (car (read-from-string sexp)))
12123 (error
12124 (beep)
12125 (message "Bad sexp at line %d in %s: %s"
12126 (org-current-line)
12127 (buffer-file-name) sexp)
12128 (sleep-for 2))))))
12129 (cond ((stringp result) result)
12130 ((and (consp result)
12131 (stringp (cdr result))) (cdr result))
12132 (result entry)
12133 (t nil))))
12135 (defun org-diary-to-ical-string (frombuf)
12136 "Get iCalendar entries from diary entries in buffer FROMBUF.
12137 This uses the icalendar.el library."
12138 (let* ((tmpdir (if (featurep 'xemacs)
12139 (temp-directory)
12140 temporary-file-directory))
12141 (tmpfile (make-temp-name
12142 (expand-file-name "orgics" tmpdir)))
12143 buf rtn b e)
12144 (save-excursion
12145 (set-buffer frombuf)
12146 (icalendar-export-region (point-min) (point-max) tmpfile)
12147 (setq buf (find-buffer-visiting tmpfile))
12148 (set-buffer buf)
12149 (goto-char (point-min))
12150 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12151 (setq b (match-beginning 0)))
12152 (goto-char (point-max))
12153 (if (re-search-backward "^END:VEVENT" nil t)
12154 (setq e (match-end 0)))
12155 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12156 (kill-buffer buf)
12157 (delete-file tmpfile)
12158 rtn))
12160 (defun org-closest-date (start current change prefer show-all)
12161 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12162 When PREFER is `past' return a date that is either CURRENT or past.
12163 When PREFER is `future', return a date that is either CURRENT or future.
12164 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12165 ;; Make the proper lists from the dates
12166 (catch 'exit
12167 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12168 dn dw sday cday n1 n2 n0
12169 d m y y1 y2 date1 date2 nmonths nm ny m2)
12171 (setq start (org-date-to-gregorian start)
12172 current (org-date-to-gregorian
12173 (if show-all
12174 current
12175 (time-to-days (current-time))))
12176 sday (calendar-absolute-from-gregorian start)
12177 cday (calendar-absolute-from-gregorian current))
12179 (if (<= cday sday) (throw 'exit sday))
12181 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12182 (setq dn (string-to-number (match-string 1 change))
12183 dw (cdr (assoc (match-string 2 change) a1)))
12184 (error "Invalid change specifyer: %s" change))
12185 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12186 (cond
12187 ((eq dw 'day)
12188 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12189 n2 (+ n1 dn)))
12190 ((eq dw 'year)
12191 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12192 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12193 (setq date1 (list m d y1)
12194 n1 (calendar-absolute-from-gregorian date1)
12195 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12196 n2 (calendar-absolute-from-gregorian date2)))
12197 ((eq dw 'month)
12198 ;; approx number of month between the two dates
12199 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12200 ;; How often does dn fit in there?
12201 (setq d (nth 1 start) m (car start) y (nth 2 start)
12202 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12203 m (+ m nm)
12204 ny (floor (/ m 12))
12205 y (+ y ny)
12206 m (- m (* ny 12)))
12207 (while (> m 12) (setq m (- m 12) y (1+ y)))
12208 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12209 (setq m2 (+ m dn) y2 y)
12210 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12211 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12212 (while (<= n2 cday)
12213 (setq n1 n2 m m2 y y2)
12214 (setq m2 (+ m dn) y2 y)
12215 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12216 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12217 ;; Make sure n1 is the earlier date
12218 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12219 (if show-all
12220 (cond
12221 ((eq prefer 'past) n1)
12222 ((eq prefer 'future) (if (= cday n1) n1 n2))
12223 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12224 (cond
12225 ((eq prefer 'past) n1)
12226 ((eq prefer 'future) (if (= cday n1) n1 n2))
12227 (t (if (= cday n1) n1 n2)))))))
12229 (defun org-date-to-gregorian (date)
12230 "Turn any specification of DATE into a gregorian date for the calendar."
12231 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12232 ((and (listp date) (= (length date) 3)) date)
12233 ((stringp date)
12234 (setq date (org-parse-time-string date))
12235 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12236 ((listp date)
12237 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12239 (defun org-parse-time-string (s &optional nodefault)
12240 "Parse the standard Org-mode time string.
12241 This should be a lot faster than the normal `parse-time-string'.
12242 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12243 hour and minute fields will be nil if not given."
12244 (if (string-match org-ts-regexp0 s)
12245 (list 0
12246 (if (or (match-beginning 8) (not nodefault))
12247 (string-to-number (or (match-string 8 s) "0")))
12248 (if (or (match-beginning 7) (not nodefault))
12249 (string-to-number (or (match-string 7 s) "0")))
12250 (string-to-number (match-string 4 s))
12251 (string-to-number (match-string 3 s))
12252 (string-to-number (match-string 2 s))
12253 nil nil nil)
12254 (make-list 9 0)))
12256 (defun org-timestamp-up (&optional arg)
12257 "Increase the date item at the cursor by one.
12258 If the cursor is on the year, change the year. If it is on the month or
12259 the day, change that.
12260 With prefix ARG, change by that many units."
12261 (interactive "p")
12262 (org-timestamp-change (prefix-numeric-value arg)))
12264 (defun org-timestamp-down (&optional arg)
12265 "Decrease the date item at the cursor by one.
12266 If the cursor is on the year, change the year. If it is on the month or
12267 the day, change that.
12268 With prefix ARG, change by that many units."
12269 (interactive "p")
12270 (org-timestamp-change (- (prefix-numeric-value arg))))
12272 (defun org-timestamp-up-day (&optional arg)
12273 "Increase the date in the time stamp by one day.
12274 With prefix ARG, change that many days."
12275 (interactive "p")
12276 (if (and (not (org-at-timestamp-p t))
12277 (org-on-heading-p))
12278 (org-todo 'up)
12279 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12281 (defun org-timestamp-down-day (&optional arg)
12282 "Decrease the date in the time stamp by one day.
12283 With prefix ARG, change that many days."
12284 (interactive "p")
12285 (if (and (not (org-at-timestamp-p t))
12286 (org-on-heading-p))
12287 (org-todo 'down)
12288 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12290 (defun org-at-timestamp-p (&optional inactive-ok)
12291 "Determine if the cursor is in or at a timestamp."
12292 (interactive)
12293 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12294 (pos (point))
12295 (ans (or (looking-at tsr)
12296 (save-excursion
12297 (skip-chars-backward "^[<\n\r\t")
12298 (if (> (point) (point-min)) (backward-char 1))
12299 (and (looking-at tsr)
12300 (> (- (match-end 0) pos) -1))))))
12301 (and ans
12302 (boundp 'org-ts-what)
12303 (setq org-ts-what
12304 (cond
12305 ((= pos (match-beginning 0)) 'bracket)
12306 ((= pos (1- (match-end 0))) 'bracket)
12307 ((org-pos-in-match-range pos 2) 'year)
12308 ((org-pos-in-match-range pos 3) 'month)
12309 ((org-pos-in-match-range pos 7) 'hour)
12310 ((org-pos-in-match-range pos 8) 'minute)
12311 ((or (org-pos-in-match-range pos 4)
12312 (org-pos-in-match-range pos 5)) 'day)
12313 ((and (> pos (or (match-end 8) (match-end 5)))
12314 (< pos (match-end 0)))
12315 (- pos (or (match-end 8) (match-end 5))))
12316 (t 'day))))
12317 ans))
12319 (defun org-toggle-timestamp-type ()
12320 "Toggle the type (<active> or [inactive]) of a time stamp."
12321 (interactive)
12322 (when (org-at-timestamp-p t)
12323 (let ((beg (match-beginning 0)) (end (match-end 0))
12324 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12325 (save-excursion
12326 (goto-char beg)
12327 (while (re-search-forward "[][<>]" end t)
12328 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12329 t t)))
12330 (message "Timestamp is now %sactive"
12331 (if (equal (char-after beg) ?<) "" "in")))))
12333 (defun org-timestamp-change (n &optional what)
12334 "Change the date in the time stamp at point.
12335 The date will be changed by N times WHAT. WHAT can be `day', `month',
12336 `year', `minute', `second'. If WHAT is not given, the cursor position
12337 in the timestamp determines what will be changed."
12338 (let ((pos (point))
12339 with-hm inactive
12340 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12341 org-ts-what
12342 extra rem
12343 ts time time0)
12344 (if (not (org-at-timestamp-p t))
12345 (error "Not at a timestamp"))
12346 (if (and (not what) (eq org-ts-what 'bracket))
12347 (org-toggle-timestamp-type)
12348 (if (and (not what) (not (eq org-ts-what 'day))
12349 org-display-custom-times
12350 (get-text-property (point) 'display)
12351 (not (get-text-property (1- (point)) 'display)))
12352 (setq org-ts-what 'day))
12353 (setq org-ts-what (or what org-ts-what)
12354 inactive (= (char-after (match-beginning 0)) ?\[)
12355 ts (match-string 0))
12356 (replace-match "")
12357 (if (string-match
12358 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12360 (setq extra (match-string 1 ts)))
12361 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12362 (setq with-hm t))
12363 (setq time0 (org-parse-time-string ts))
12364 (when (and (eq org-ts-what 'minute)
12365 (eq current-prefix-arg nil))
12366 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12367 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12368 (setcar (cdr time0) (+ (nth 1 time0)
12369 (if (> n 0) (- rem) (- dm rem))))))
12370 (setq time
12371 (encode-time (or (car time0) 0)
12372 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12373 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12374 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12375 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12376 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12377 (nthcdr 6 time0)))
12378 (when (integerp org-ts-what)
12379 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12380 (if (eq what 'calendar)
12381 (let ((cal-date (org-get-date-from-calendar)))
12382 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12383 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12384 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12385 (setcar time0 (or (car time0) 0))
12386 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12387 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12388 (setq time (apply 'encode-time time0))))
12389 (setq org-last-changed-timestamp
12390 (org-insert-time-stamp time with-hm inactive nil nil extra))
12391 (org-clock-update-time-maybe)
12392 (goto-char pos)
12393 ;; Try to recenter the calendar window, if any
12394 (if (and org-calendar-follow-timestamp-change
12395 (get-buffer-window "*Calendar*" t)
12396 (memq org-ts-what '(day month year)))
12397 (org-recenter-calendar (time-to-days time))))))
12399 (defun org-modify-ts-extra (s pos n dm)
12400 "Change the different parts of the lead-time and repeat fields in timestamp."
12401 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12402 ng h m new rem)
12403 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12404 (cond
12405 ((or (org-pos-in-match-range pos 2)
12406 (org-pos-in-match-range pos 3))
12407 (setq m (string-to-number (match-string 3 s))
12408 h (string-to-number (match-string 2 s)))
12409 (if (org-pos-in-match-range pos 2)
12410 (setq h (+ h n))
12411 (setq n (* dm (org-no-warnings (signum n))))
12412 (when (not (= 0 (setq rem (% m dm))))
12413 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12414 (setq m (+ m n)))
12415 (if (< m 0) (setq m (+ m 60) h (1- h)))
12416 (if (> m 59) (setq m (- m 60) h (1+ h)))
12417 (setq h (min 24 (max 0 h)))
12418 (setq ng 1 new (format "-%02d:%02d" h m)))
12419 ((org-pos-in-match-range pos 6)
12420 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12421 ((org-pos-in-match-range pos 5)
12422 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12424 ((org-pos-in-match-range pos 9)
12425 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12426 ((org-pos-in-match-range pos 8)
12427 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12429 (when ng
12430 (setq s (concat
12431 (substring s 0 (match-beginning ng))
12433 (substring s (match-end ng))))))
12436 (defun org-recenter-calendar (date)
12437 "If the calendar is visible, recenter it to DATE."
12438 (let* ((win (selected-window))
12439 (cwin (get-buffer-window "*Calendar*" t))
12440 (calendar-move-hook nil))
12441 (when cwin
12442 (select-window cwin)
12443 (calendar-goto-date (if (listp date) date
12444 (calendar-gregorian-from-absolute date)))
12445 (select-window win))))
12447 (defun org-goto-calendar (&optional arg)
12448 "Go to the Emacs calendar at the current date.
12449 If there is a time stamp in the current line, go to that date.
12450 A prefix ARG can be used to force the current date."
12451 (interactive "P")
12452 (let ((tsr org-ts-regexp) diff
12453 (calendar-move-hook nil)
12454 (calendar-view-holidays-initially-flag nil)
12455 (view-calendar-holidays-initially nil)
12456 (calendar-view-diary-initially-flag nil)
12457 (view-diary-entries-initially nil))
12458 (if (or (org-at-timestamp-p)
12459 (save-excursion
12460 (beginning-of-line 1)
12461 (looking-at (concat ".*" tsr))))
12462 (let ((d1 (time-to-days (current-time)))
12463 (d2 (time-to-days
12464 (org-time-string-to-time (match-string 1)))))
12465 (setq diff (- d2 d1))))
12466 (calendar)
12467 (calendar-goto-today)
12468 (if (and diff (not arg)) (calendar-forward-day diff))))
12470 (defun org-get-date-from-calendar ()
12471 "Return a list (month day year) of date at point in calendar."
12472 (with-current-buffer "*Calendar*"
12473 (save-match-data
12474 (calendar-cursor-to-date))))
12476 (defun org-date-from-calendar ()
12477 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12478 If there is already a time stamp at the cursor position, update it."
12479 (interactive)
12480 (if (org-at-timestamp-p t)
12481 (org-timestamp-change 0 'calendar)
12482 (let ((cal-date (org-get-date-from-calendar)))
12483 (org-insert-time-stamp
12484 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12486 (defun org-minutes-to-hh:mm-string (m)
12487 "Compute H:MM from a number of minutes."
12488 (let ((h (/ m 60)))
12489 (setq m (- m (* 60 h)))
12490 (format org-time-clocksum-format h m)))
12492 (defun org-hh:mm-string-to-minutes (s)
12493 "Convert a string H:MM to a number of minutes."
12494 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12495 (+ (* (string-to-number (match-string 1 s)) 60)
12496 (string-to-number (match-string 2 s)))
12499 ;;;; Files
12501 (defun org-save-all-org-buffers ()
12502 "Save all Org-mode buffers without user confirmation."
12503 (interactive)
12504 (message "Saving all Org-mode buffers...")
12505 (save-some-buffers t 'org-mode-p)
12506 (when (featurep 'org-id) (org-id-locations-save))
12507 (message "Saving all Org-mode buffers... done"))
12509 (defun org-revert-all-org-buffers ()
12510 "Revert all Org-mode buffers.
12511 Prompt for confirmation when there are unsaved changes.
12512 Be sure you know what you are doing before letting this function
12513 overwrite your changes.
12515 This function is useful in a setup where one tracks org files
12516 with a version control system, to revert on one machine after pulling
12517 changes from another. I believe the procedure must be like this:
12519 1. M-x org-save-all-org-buffers
12520 2. Pull changes from the other machine, resolve conflicts
12521 3. M-x org-revert-all-org-buffers"
12522 (interactive)
12523 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12524 (error "Abort"))
12525 (save-excursion
12526 (save-window-excursion
12527 (mapc
12528 (lambda (b)
12529 (when (and (with-current-buffer b (org-mode-p))
12530 (with-current-buffer b buffer-file-name))
12531 (switch-to-buffer b)
12532 (revert-buffer t 'no-confirm)))
12533 (buffer-list))
12534 (when (and (featurep 'org-id) org-id-track-globally)
12535 (org-id-locations-load)))))
12537 ;;;; Agenda files
12539 ;;;###autoload
12540 (defun org-iswitchb (&optional arg)
12541 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12542 With a prefix argument, restrict available to files.
12543 With two prefix arguments, restrict available buffers to agenda files.
12545 Due to some yet unresolved reason, the global function
12546 `iswitchb-mode' needs to be active for this function to work."
12547 (interactive "P")
12548 (require 'iswitchb)
12549 (let ((enabled iswitchb-mode) blist)
12550 (or enabled (iswitchb-mode 1))
12551 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12552 ((equal arg '(16)) (org-buffer-list 'agenda))
12553 (t (org-buffer-list))))
12554 (unwind-protect
12555 (let ((iswitchb-make-buflist-hook
12556 (lambda ()
12557 (setq iswitchb-temp-buflist
12558 (mapcar 'buffer-name blist)))))
12559 (switch-to-buffer
12560 (iswitchb-read-buffer
12561 "Switch-to: " nil t))
12562 (or enabled (iswitchb-mode -1))))))
12564 ;;;###autoload
12565 (defun org-ido-switchb (&optional arg)
12566 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12567 With a prefix argument, restrict available to files.
12568 With two prefix arguments, restrict available buffers to agenda files."
12569 (interactive "P")
12570 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12571 ((equal arg '(16)) (org-buffer-list 'agenda))
12572 (t (org-buffer-list)))))
12573 (switch-to-buffer
12574 (org-ido-completing-read "Org buffer: "
12575 (mapcar 'buffer-name blist)
12576 nil t))))
12578 (defun org-buffer-list (&optional predicate exclude-tmp)
12579 "Return a list of Org buffers.
12580 PREDICATE can be `export', `files' or `agenda'.
12582 export restrict the list to Export buffers.
12583 files restrict the list to buffers visiting Org files.
12584 agenda restrict the list to buffers visiting agenda files.
12586 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12587 (let* ((bfn nil)
12588 (agenda-files (and (eq predicate 'agenda)
12589 (mapcar 'file-truename (org-agenda-files t))))
12590 (filter
12591 (cond
12592 ((eq predicate 'files)
12593 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12594 ((eq predicate 'export)
12595 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12596 ((eq predicate 'agenda)
12597 (lambda (b)
12598 (with-current-buffer b
12599 (and (eq major-mode 'org-mode)
12600 (setq bfn (buffer-file-name b))
12601 (member (file-truename bfn) agenda-files)))))
12602 (t (lambda (b) (with-current-buffer b
12603 (or (eq major-mode 'org-mode)
12604 (string-match "\*Org .*Export"
12605 (buffer-name b)))))))))
12606 (delq nil
12607 (mapcar
12608 (lambda(b)
12609 (if (and (funcall filter b)
12610 (or (not exclude-tmp)
12611 (not (string-match "tmp" (buffer-name b)))))
12613 nil))
12614 (buffer-list)))))
12616 (defun org-agenda-files (&optional unrestricted archives)
12617 "Get the list of agenda files.
12618 Optional UNRESTRICTED means return the full list even if a restriction
12619 is currently in place.
12620 When ARCHIVES is t, include all archive files hat are really being
12621 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12622 `org-agenda-archives-mode' is t."
12623 (let ((files
12624 (cond
12625 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12626 ((stringp org-agenda-files) (org-read-agenda-file-list))
12627 ((listp org-agenda-files) org-agenda-files)
12628 (t (error "Invalid value of `org-agenda-files'")))))
12629 (setq files (apply 'append
12630 (mapcar (lambda (f)
12631 (if (file-directory-p f)
12632 (directory-files
12633 f t org-agenda-file-regexp)
12634 (list f)))
12635 files)))
12636 (when org-agenda-skip-unavailable-files
12637 (setq files (delq nil
12638 (mapcar (function
12639 (lambda (file)
12640 (and (file-readable-p file) file)))
12641 files))))
12642 (when (or (eq archives t)
12643 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12644 (setq files (org-add-archive-files files)))
12645 files))
12647 (defun org-edit-agenda-file-list ()
12648 "Edit the list of agenda files.
12649 Depending on setup, this either uses customize to edit the variable
12650 `org-agenda-files', or it visits the file that is holding the list. In the
12651 latter case, the buffer is set up in a way that saving it automatically kills
12652 the buffer and restores the previous window configuration."
12653 (interactive)
12654 (if (stringp org-agenda-files)
12655 (let ((cw (current-window-configuration)))
12656 (find-file org-agenda-files)
12657 (org-set-local 'org-window-configuration cw)
12658 (org-add-hook 'after-save-hook
12659 (lambda ()
12660 (set-window-configuration
12661 (prog1 org-window-configuration
12662 (kill-buffer (current-buffer))))
12663 (org-install-agenda-files-menu)
12664 (message "New agenda file list installed"))
12665 nil 'local)
12666 (message "%s" (substitute-command-keys
12667 "Edit list and finish with \\[save-buffer]")))
12668 (customize-variable 'org-agenda-files)))
12670 (defun org-store-new-agenda-file-list (list)
12671 "Set new value for the agenda file list and save it correctly."
12672 (if (stringp org-agenda-files)
12673 (let ((f org-agenda-files) b)
12674 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12675 (with-temp-file f
12676 (insert (mapconcat 'identity list "\n") "\n")))
12677 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12678 (setq org-agenda-files list)
12679 (customize-save-variable 'org-agenda-files org-agenda-files))))
12681 (defun org-read-agenda-file-list ()
12682 "Read the list of agenda files from a file."
12683 (when (file-directory-p org-agenda-files)
12684 (error "`org-agenda-files' cannot be a single directory"))
12685 (when (stringp org-agenda-files)
12686 (with-temp-buffer
12687 (insert-file-contents org-agenda-files)
12688 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12691 ;;;###autoload
12692 (defun org-cycle-agenda-files ()
12693 "Cycle through the files in `org-agenda-files'.
12694 If the current buffer visits an agenda file, find the next one in the list.
12695 If the current buffer does not, find the first agenda file."
12696 (interactive)
12697 (let* ((fs (org-agenda-files t))
12698 (files (append fs (list (car fs))))
12699 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12700 file)
12701 (unless files (error "No agenda files"))
12702 (catch 'exit
12703 (while (setq file (pop files))
12704 (if (equal (file-truename file) tcf)
12705 (when (car files)
12706 (find-file (car files))
12707 (throw 'exit t))))
12708 (find-file (car fs)))
12709 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12711 (defun org-agenda-file-to-front (&optional to-end)
12712 "Move/add the current file to the top of the agenda file list.
12713 If the file is not present in the list, it is added to the front. If it is
12714 present, it is moved there. With optional argument TO-END, add/move to the
12715 end of the list."
12716 (interactive "P")
12717 (let ((org-agenda-skip-unavailable-files nil)
12718 (file-alist (mapcar (lambda (x)
12719 (cons (file-truename x) x))
12720 (org-agenda-files t)))
12721 (ctf (file-truename buffer-file-name))
12722 x had)
12723 (setq x (assoc ctf file-alist) had x)
12725 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12726 (if to-end
12727 (setq file-alist (append (delq x file-alist) (list x)))
12728 (setq file-alist (cons x (delq x file-alist))))
12729 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12730 (org-install-agenda-files-menu)
12731 (message "File %s to %s of agenda file list"
12732 (if had "moved" "added") (if to-end "end" "front"))))
12734 (defun org-remove-file (&optional file)
12735 "Remove current file from the list of files in variable `org-agenda-files'.
12736 These are the files which are being checked for agenda entries.
12737 Optional argument FILE means, use this file instead of the current."
12738 (interactive)
12739 (let* ((org-agenda-skip-unavailable-files nil)
12740 (file (or file buffer-file-name))
12741 (true-file (file-truename file))
12742 (afile (abbreviate-file-name file))
12743 (files (delq nil (mapcar
12744 (lambda (x)
12745 (if (equal true-file
12746 (file-truename x))
12747 nil x))
12748 (org-agenda-files t)))))
12749 (if (not (= (length files) (length (org-agenda-files t))))
12750 (progn
12751 (org-store-new-agenda-file-list files)
12752 (org-install-agenda-files-menu)
12753 (message "Removed file: %s" afile))
12754 (message "File was not in list: %s (not removed)" afile))))
12756 (defun org-file-menu-entry (file)
12757 (vector file (list 'find-file file) t))
12759 (defun org-check-agenda-file (file)
12760 "Make sure FILE exists. If not, ask user what to do."
12761 (when (not (file-exists-p file))
12762 (message "non-existent file %s. [R]emove from list or [A]bort?"
12763 (abbreviate-file-name file))
12764 (let ((r (downcase (read-char-exclusive))))
12765 (cond
12766 ((equal r ?r)
12767 (org-remove-file file)
12768 (throw 'nextfile t))
12769 (t (error "Abort"))))))
12771 (defun org-get-agenda-file-buffer (file)
12772 "Get a buffer visiting FILE. If the buffer needs to be created, add
12773 it to the list of buffers which might be released later."
12774 (let ((buf (org-find-base-buffer-visiting file)))
12775 (if buf
12776 buf ; just return it
12777 ;; Make a new buffer and remember it
12778 (setq buf (find-file-noselect file))
12779 (if buf (push buf org-agenda-new-buffers))
12780 buf)))
12782 (defun org-release-buffers (blist)
12783 "Release all buffers in list, asking the user for confirmation when needed.
12784 When a buffer is unmodified, it is just killed. When modified, it is saved
12785 \(if the user agrees) and then killed."
12786 (let (buf file)
12787 (while (setq buf (pop blist))
12788 (setq file (buffer-file-name buf))
12789 (when (and (buffer-modified-p buf)
12790 file
12791 (y-or-n-p (format "Save file %s? " file)))
12792 (with-current-buffer buf (save-buffer)))
12793 (kill-buffer buf))))
12795 (defun org-prepare-agenda-buffers (files)
12796 "Create buffers for all agenda files, protect archived trees and comments."
12797 (interactive)
12798 (let ((pa '(:org-archived t))
12799 (pc '(:org-comment t))
12800 (pall '(:org-archived t :org-comment t))
12801 (inhibit-read-only t)
12802 (rea (concat ":" org-archive-tag ":"))
12803 bmp file re)
12804 (save-excursion
12805 (save-restriction
12806 (while (setq file (pop files))
12807 (if (bufferp file)
12808 (set-buffer file)
12809 (org-check-agenda-file file)
12810 (set-buffer (org-get-agenda-file-buffer file)))
12811 (widen)
12812 (setq bmp (buffer-modified-p))
12813 (org-refresh-category-properties)
12814 (setq org-todo-keywords-for-agenda
12815 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12816 (setq org-done-keywords-for-agenda
12817 (append org-done-keywords-for-agenda org-done-keywords))
12818 (setq org-todo-keyword-alist-for-agenda
12819 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12820 (setq org-tag-alist-for-agenda
12821 (append org-tag-alist-for-agenda org-tag-alist))
12823 (save-excursion
12824 (remove-text-properties (point-min) (point-max) pall)
12825 (when org-agenda-skip-archived-trees
12826 (goto-char (point-min))
12827 (while (re-search-forward rea nil t)
12828 (if (org-on-heading-p t)
12829 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12830 (goto-char (point-min))
12831 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12832 (while (re-search-forward re nil t)
12833 (add-text-properties
12834 (match-beginning 0) (org-end-of-subtree t) pc)))
12835 (set-buffer-modified-p bmp))))
12836 (setq org-todo-keyword-alist-for-agenda
12837 (org-uniquify org-todo-keyword-alist-for-agenda)
12838 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12840 ;;;; Embedded LaTeX
12842 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12843 "Keymap for the minor `org-cdlatex-mode'.")
12845 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12846 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12847 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12848 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12849 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12851 (defvar org-cdlatex-texmathp-advice-is-done nil
12852 "Flag remembering if we have applied the advice to texmathp already.")
12854 (define-minor-mode org-cdlatex-mode
12855 "Toggle the minor `org-cdlatex-mode'.
12856 This mode supports entering LaTeX environment and math in LaTeX fragments
12857 in Org-mode.
12858 \\{org-cdlatex-mode-map}"
12859 nil " OCDL" nil
12860 (when org-cdlatex-mode (require 'cdlatex))
12861 (unless org-cdlatex-texmathp-advice-is-done
12862 (setq org-cdlatex-texmathp-advice-is-done t)
12863 (defadvice texmathp (around org-math-always-on activate)
12864 "Always return t in org-mode buffers.
12865 This is because we want to insert math symbols without dollars even outside
12866 the LaTeX math segments. If Orgmode thinks that point is actually inside
12867 an embedded LaTeX fragment, let texmathp do its job.
12868 \\[org-cdlatex-mode-map]"
12869 (interactive)
12870 (let (p)
12871 (cond
12872 ((not (org-mode-p)) ad-do-it)
12873 ((eq this-command 'cdlatex-math-symbol)
12874 (setq ad-return-value t
12875 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12877 (let ((p (org-inside-LaTeX-fragment-p)))
12878 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12879 (setq ad-return-value t
12880 texmathp-why '("Org-mode embedded math" . 0))
12881 (if p ad-do-it)))))))))
12883 (defun turn-on-org-cdlatex ()
12884 "Unconditionally turn on `org-cdlatex-mode'."
12885 (org-cdlatex-mode 1))
12887 (defun org-inside-LaTeX-fragment-p ()
12888 "Test if point is inside a LaTeX fragment.
12889 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12890 sequence appearing also before point.
12891 Even though the matchers for math are configurable, this function assumes
12892 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12893 delimiters are skipped when they have been removed by customization.
12894 The return value is nil, or a cons cell with the delimiter and
12895 and the position of this delimiter.
12897 This function does a reasonably good job, but can locally be fooled by
12898 for example currency specifications. For example it will assume being in
12899 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12900 fragments that are properly closed, but during editing, we have to live
12901 with the uncertainty caused by missing closing delimiters. This function
12902 looks only before point, not after."
12903 (catch 'exit
12904 (let ((pos (point))
12905 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12906 (lim (progn
12907 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12908 (point)))
12909 dd-on str (start 0) m re)
12910 (goto-char pos)
12911 (when dodollar
12912 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12913 re (nth 1 (assoc "$" org-latex-regexps)))
12914 (while (string-match re str start)
12915 (cond
12916 ((= (match-end 0) (length str))
12917 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12918 ((= (match-end 0) (- (length str) 5))
12919 (throw 'exit nil))
12920 (t (setq start (match-end 0))))))
12921 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12922 (goto-char pos)
12923 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12924 (and (match-beginning 2) (throw 'exit nil))
12925 ;; count $$
12926 (while (re-search-backward "\\$\\$" lim t)
12927 (setq dd-on (not dd-on)))
12928 (goto-char pos)
12929 (if dd-on (cons "$$" m))))))
12932 (defun org-try-cdlatex-tab ()
12933 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12934 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12935 - inside a LaTeX fragment, or
12936 - after the first word in a line, where an abbreviation expansion could
12937 insert a LaTeX environment."
12938 (when org-cdlatex-mode
12939 (cond
12940 ((save-excursion
12941 (skip-chars-backward "a-zA-Z0-9*")
12942 (skip-chars-backward " \t")
12943 (bolp))
12944 (cdlatex-tab) t)
12945 ((org-inside-LaTeX-fragment-p)
12946 (cdlatex-tab) t)
12947 (t nil))))
12949 (defun org-cdlatex-underscore-caret (&optional arg)
12950 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12951 Revert to the normal definition outside of these fragments."
12952 (interactive "P")
12953 (if (org-inside-LaTeX-fragment-p)
12954 (call-interactively 'cdlatex-sub-superscript)
12955 (let (org-cdlatex-mode)
12956 (call-interactively (key-binding (vector last-input-event))))))
12958 (defun org-cdlatex-math-modify (&optional arg)
12959 "Execute `cdlatex-math-modify' in LaTeX fragments.
12960 Revert to the normal definition outside of these fragments."
12961 (interactive "P")
12962 (if (org-inside-LaTeX-fragment-p)
12963 (call-interactively 'cdlatex-math-modify)
12964 (let (org-cdlatex-mode)
12965 (call-interactively (key-binding (vector last-input-event))))))
12967 (defvar org-latex-fragment-image-overlays nil
12968 "List of overlays carrying the images of latex fragments.")
12969 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12971 (defun org-remove-latex-fragment-image-overlays ()
12972 "Remove all overlays with LaTeX fragment images in current buffer."
12973 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12974 (setq org-latex-fragment-image-overlays nil))
12976 (defun org-preview-latex-fragment (&optional subtree)
12977 "Preview the LaTeX fragment at point, or all locally or globally.
12978 If the cursor is in a LaTeX fragment, create the image and overlay
12979 it over the source code. If there is no fragment at point, display
12980 all fragments in the current text, from one headline to the next. With
12981 prefix SUBTREE, display all fragments in the current subtree. With a
12982 double prefix `C-u C-u', or when the cursor is before the first headline,
12983 display all fragments in the buffer.
12984 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12985 (interactive "P")
12986 (org-remove-latex-fragment-image-overlays)
12987 (save-excursion
12988 (save-restriction
12989 (let (beg end at msg)
12990 (cond
12991 ((or (equal subtree '(16))
12992 (not (save-excursion
12993 (re-search-backward (concat "^" outline-regexp) nil t))))
12994 (setq beg (point-min) end (point-max)
12995 msg "Creating images for buffer...%s"))
12996 ((equal subtree '(4))
12997 (org-back-to-heading)
12998 (setq beg (point) end (org-end-of-subtree t)
12999 msg "Creating images for subtree...%s"))
13001 (if (setq at (org-inside-LaTeX-fragment-p))
13002 (goto-char (max (point-min) (- (cdr at) 2)))
13003 (org-back-to-heading))
13004 (setq beg (point) end (progn (outline-next-heading) (point))
13005 msg (if at "Creating image...%s"
13006 "Creating images for entry...%s"))))
13007 (message msg "")
13008 (narrow-to-region beg end)
13009 (goto-char beg)
13010 (org-format-latex
13011 (concat "ltxpng/" (file-name-sans-extension
13012 (file-name-nondirectory
13013 buffer-file-name)))
13014 default-directory 'overlays msg at 'forbuffer)
13015 (message msg "done. Use `C-c C-c' to remove images.")))))
13017 (defvar org-latex-regexps
13018 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13019 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13020 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13021 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13022 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13023 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13024 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13025 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13026 "Regular expressions for matching embedded LaTeX.")
13028 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13029 "Replace LaTeX fragments with links to an image, and produce images."
13030 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13031 (let* ((prefixnodir (file-name-nondirectory prefix))
13032 (absprefix (expand-file-name prefix dir))
13033 (todir (file-name-directory absprefix))
13034 (opt org-format-latex-options)
13035 (matchers (plist-get opt :matchers))
13036 (re-list org-latex-regexps)
13037 (cnt 0) txt link beg end re e checkdir
13038 m n block linkfile movefile ov)
13039 ;; Check if there are old images files with this prefix, and remove them
13040 (when (file-directory-p todir)
13041 (mapc 'delete-file
13042 (directory-files
13043 todir 'full
13044 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13045 ;; Check the different regular expressions
13046 (while (setq e (pop re-list))
13047 (setq m (car e) re (nth 1 e) n (nth 2 e)
13048 block (if (nth 3 e) "\n\n" ""))
13049 (when (member m matchers)
13050 (goto-char (point-min))
13051 (while (re-search-forward re nil t)
13052 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13053 (not (get-text-property (match-beginning n)
13054 'org-protected)))
13055 (setq txt (match-string n)
13056 beg (match-beginning n) end (match-end n)
13057 cnt (1+ cnt)
13058 linkfile (format "%s_%04d.png" prefix cnt)
13059 movefile (format "%s_%04d.png" absprefix cnt)
13060 link (concat block "[[file:" linkfile "]]" block))
13061 (if msg (message msg cnt))
13062 (goto-char beg)
13063 (unless checkdir ; make sure the directory exists
13064 (setq checkdir t)
13065 (or (file-directory-p todir) (make-directory todir)))
13066 (org-create-formula-image
13067 txt movefile opt forbuffer)
13068 (if overlays
13069 (progn
13070 (setq ov (org-make-overlay beg end))
13071 (if (featurep 'xemacs)
13072 (progn
13073 (org-overlay-put ov 'invisible t)
13074 (org-overlay-put
13075 ov 'end-glyph
13076 (make-glyph (vector 'png :file movefile))))
13077 (org-overlay-put
13078 ov 'display
13079 (list 'image :type 'png :file movefile :ascent 'center)))
13080 (push ov org-latex-fragment-image-overlays)
13081 (goto-char end))
13082 (delete-region beg end)
13083 (insert link))))))))
13085 ;; This function borrows from Ganesh Swami's latex2png.el
13086 (defun org-create-formula-image (string tofile options buffer)
13087 (let* ((tmpdir (if (featurep 'xemacs)
13088 (temp-directory)
13089 temporary-file-directory))
13090 (texfilebase (make-temp-name
13091 (expand-file-name "orgtex" tmpdir)))
13092 (texfile (concat texfilebase ".tex"))
13093 (dvifile (concat texfilebase ".dvi"))
13094 (pngfile (concat texfilebase ".png"))
13095 (fnh (if (featurep 'xemacs)
13096 (font-height (get-face-font 'default))
13097 (face-attribute 'default :height nil)))
13098 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13099 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13100 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13101 "Black"))
13102 (bg (or (plist-get options (if buffer :background :html-background))
13103 "Transparent")))
13104 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13105 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13106 (with-temp-file texfile
13107 (insert org-format-latex-header
13108 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13109 (let ((dir default-directory))
13110 (condition-case nil
13111 (progn
13112 (cd tmpdir)
13113 (call-process "latex" nil nil nil texfile))
13114 (error nil))
13115 (cd dir))
13116 (if (not (file-exists-p dvifile))
13117 (progn (message "Failed to create dvi file from %s" texfile) nil)
13118 (condition-case nil
13119 (call-process "dvipng" nil nil nil
13120 "-E" "-fg" fg "-bg" bg
13121 "-D" dpi
13122 ;;"-x" scale "-y" scale
13123 "-T" "tight"
13124 "-o" pngfile
13125 dvifile)
13126 (error nil))
13127 (if (not (file-exists-p pngfile))
13128 (progn (message "Failed to create png file from %s" texfile) nil)
13129 ;; Use the requested file name and clean up
13130 (copy-file pngfile tofile 'replace)
13131 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13132 (delete-file (concat texfilebase e)))
13133 pngfile))))
13135 (defun org-dvipng-color (attr)
13136 "Return an rgb color specification for dvipng."
13137 (apply 'format "rgb %s %s %s"
13138 (mapcar 'org-normalize-color
13139 (color-values (face-attribute 'default attr nil)))))
13141 (defun org-normalize-color (value)
13142 "Return string to be used as color value for an RGB component."
13143 (format "%g" (/ value 65535.0)))
13145 ;;;; Key bindings
13147 ;; Make `C-c C-x' a prefix key
13148 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13150 ;; TAB key with modifiers
13151 (org-defkey org-mode-map "\C-i" 'org-cycle)
13152 (org-defkey org-mode-map [(tab)] 'org-cycle)
13153 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13154 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13155 (org-defkey org-mode-map "\M-\t" 'org-complete)
13156 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13157 ;; The following line is necessary under Suse GNU/Linux
13158 (unless (featurep 'xemacs)
13159 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13160 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13161 (define-key org-mode-map [backtab] 'org-shifttab)
13163 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13164 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13165 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13167 ;; Cursor keys with modifiers
13168 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13169 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13170 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13171 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13173 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13174 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13175 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13176 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13178 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13179 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13180 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13181 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13183 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13184 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13186 ;;; Extra keys for tty access.
13187 ;; We only set them when really needed because otherwise the
13188 ;; menus don't show the simple keys
13190 (when (or org-use-extra-keys
13191 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13192 (not window-system))
13193 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13194 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13195 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13196 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13197 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13198 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13199 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13200 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13201 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13202 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13203 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13204 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13205 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13206 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13207 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13208 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13209 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13210 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13211 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13212 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13213 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13214 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13216 ;; All the other keys
13218 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13219 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13220 (if (boundp 'narrow-map)
13221 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13222 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13223 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13224 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13225 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13226 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13227 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13228 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13229 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13230 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13231 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13232 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13233 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13234 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13235 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13236 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13237 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13238 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
13239 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13240 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13241 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13242 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13243 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13244 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13245 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13246 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13247 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13248 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13249 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13250 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13251 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13252 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13253 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13254 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13255 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13256 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13257 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13258 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13259 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13260 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13261 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13262 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13263 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13264 (org-defkey org-mode-map "\C-c^" 'org-sort)
13265 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13266 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13267 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13268 (org-defkey org-mode-map "\C-m" 'org-return)
13269 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13270 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13271 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13272 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13273 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13274 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13275 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13276 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13277 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13278 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13279 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13280 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13281 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13282 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13283 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13284 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13285 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13287 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13288 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13289 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13290 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13292 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13293 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13294 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13295 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13296 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13297 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13298 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13299 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13300 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13301 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13302 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13303 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13304 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13306 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13307 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13308 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13309 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13311 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13313 (define-key org-mode-map "\C-c\C-xr" 'org-reload)
13315 (when (featurep 'xemacs)
13316 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13319 (defvar org-self-insert-command-undo-counter 0)
13321 (defvar org-table-auto-blank-field) ; defined in org-table.el
13322 (defun org-self-insert-command (N)
13323 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13324 If the cursor is in a table looking at whitespace, the whitespace is
13325 overwritten, and the table is not marked as requiring realignment."
13326 (interactive "p")
13327 (if (and
13328 (org-table-p)
13329 (progn
13330 ;; check if we blank the field, and if that triggers align
13331 (and (featurep 'org-table) org-table-auto-blank-field
13332 (member last-command
13333 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13334 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13335 ;; got extra space, this field does not determine column width
13336 (let (org-table-may-need-update) (org-table-blank-field))
13337 ;; no extra space, this field may determine column width
13338 (org-table-blank-field)))
13340 (eq N 1)
13341 (looking-at "[^|\n]* |"))
13342 (let (org-table-may-need-update)
13343 (goto-char (1- (match-end 0)))
13344 (delete-backward-char 1)
13345 (goto-char (match-beginning 0))
13346 (self-insert-command N))
13347 (setq org-table-may-need-update t)
13348 (self-insert-command N)
13349 (org-fix-tags-on-the-fly)
13350 (if org-self-insert-cluster-for-undo
13351 (if (not (eq last-command 'org-self-insert-command))
13352 (setq org-self-insert-command-undo-counter 1)
13353 (if (>= org-self-insert-command-undo-counter 20)
13354 (setq org-self-insert-command-undo-counter 1)
13355 (and (> org-self-insert-command-undo-counter 0)
13356 buffer-undo-list
13357 (not (cadr buffer-undo-list)) ; remove nil entry
13358 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13359 (setq org-self-insert-command-undo-counter
13360 (1+ org-self-insert-command-undo-counter)))))))
13362 (defun org-fix-tags-on-the-fly ()
13363 (when (and (equal (char-after (point-at-bol)) ?*)
13364 (org-on-heading-p))
13365 (org-align-tags-here org-tags-column)))
13367 (defun org-delete-backward-char (N)
13368 "Like `delete-backward-char', insert whitespace at field end in tables.
13369 When deleting backwards, in tables this function will insert whitespace in
13370 front of the next \"|\" separator, to keep the table aligned. The table will
13371 still be marked for re-alignment if the field did fill the entire column,
13372 because, in this case the deletion might narrow the column."
13373 (interactive "p")
13374 (if (and (org-table-p)
13375 (eq N 1)
13376 (string-match "|" (buffer-substring (point-at-bol) (point)))
13377 (looking-at ".*?|"))
13378 (let ((pos (point))
13379 (noalign (looking-at "[^|\n\r]* |"))
13380 (c org-table-may-need-update))
13381 (backward-delete-char N)
13382 (skip-chars-forward "^|")
13383 (insert " ")
13384 (goto-char (1- pos))
13385 ;; noalign: if there were two spaces at the end, this field
13386 ;; does not determine the width of the column.
13387 (if noalign (setq org-table-may-need-update c)))
13388 (backward-delete-char N)
13389 (org-fix-tags-on-the-fly)))
13391 (defun org-delete-char (N)
13392 "Like `delete-char', but insert whitespace at field end in tables.
13393 When deleting characters, in tables this function will insert whitespace in
13394 front of the next \"|\" separator, to keep the table aligned. The table will
13395 still be marked for re-alignment if the field did fill the entire column,
13396 because, in this case the deletion might narrow the column."
13397 (interactive "p")
13398 (if (and (org-table-p)
13399 (not (bolp))
13400 (not (= (char-after) ?|))
13401 (eq N 1))
13402 (if (looking-at ".*?|")
13403 (let ((pos (point))
13404 (noalign (looking-at "[^|\n\r]* |"))
13405 (c org-table-may-need-update))
13406 (replace-match (concat
13407 (substring (match-string 0) 1 -1)
13408 " |"))
13409 (goto-char pos)
13410 ;; noalign: if there were two spaces at the end, this field
13411 ;; does not determine the width of the column.
13412 (if noalign (setq org-table-may-need-update c)))
13413 (delete-char N))
13414 (delete-char N)
13415 (org-fix-tags-on-the-fly)))
13417 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13418 (put 'org-self-insert-command 'delete-selection t)
13419 (put 'orgtbl-self-insert-command 'delete-selection t)
13420 (put 'org-delete-char 'delete-selection 'supersede)
13421 (put 'org-delete-backward-char 'delete-selection 'supersede)
13422 (put 'org-yank 'delete-selection 'yank)
13424 ;; Make `flyspell-mode' delay after some commands
13425 (put 'org-self-insert-command 'flyspell-delayed t)
13426 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13427 (put 'org-delete-char 'flyspell-delayed t)
13428 (put 'org-delete-backward-char 'flyspell-delayed t)
13430 ;; Make pabbrev-mode expand after org-mode commands
13431 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13432 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13434 ;; How to do this: Measure non-white length of current string
13435 ;; If equal to column width, we should realign.
13437 (defun org-remap (map &rest commands)
13438 "In MAP, remap the functions given in COMMANDS.
13439 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13440 (let (new old)
13441 (while commands
13442 (setq old (pop commands) new (pop commands))
13443 (if (fboundp 'command-remapping)
13444 (org-defkey map (vector 'remap old) new)
13445 (substitute-key-definition old new map global-map)))))
13447 (when (eq org-enable-table-editor 'optimized)
13448 ;; If the user wants maximum table support, we need to hijack
13449 ;; some standard editing functions
13450 (org-remap org-mode-map
13451 'self-insert-command 'org-self-insert-command
13452 'delete-char 'org-delete-char
13453 'delete-backward-char 'org-delete-backward-char)
13454 (org-defkey org-mode-map "|" 'org-force-self-insert))
13456 (defvar org-ctrl-c-ctrl-c-hook nil
13457 "Hook for functions attaching themselves to `C-c C-c'.
13458 This can be used to add additional functionality to the C-c C-c key which
13459 executes context-dependent commands.
13460 Each function will be called with no arguments. The function must check
13461 if the context is appropriate for it to act. If yes, it should do its
13462 thing and then return a non-nil value. If the context is wrong,
13463 just do nothing.")
13465 (defvar org-metaleft-hook nil
13466 "Hook for functions attaching themselves to `M-left'.
13467 See `org-ctrl-c-ctrl-c-hook' for more information.")
13468 (defvar org-metaright-hook nil
13469 "Hook for functions attaching themselves to `M-right'.
13470 See `org-ctrl-c-ctrl-c-hook' for more information.")
13471 (defvar org-metaup-hook nil
13472 "Hook for functions attaching themselves to `M-up'.
13473 See `org-ctrl-c-ctrl-c-hook' for more information.")
13474 (defvar org-metadown-hook nil
13475 "Hook for functions attaching themselves to `M-down'.
13476 See `org-ctrl-c-ctrl-c-hook' for more information.")
13477 (defvar org-shiftmetaleft-hook nil
13478 "Hook for functions attaching themselves to `M-S-left'.
13479 See `org-ctrl-c-ctrl-c-hook' for more information.")
13480 (defvar org-shiftmetaright-hook nil
13481 "Hook for functions attaching themselves to `M-S-right'.
13482 See `org-ctrl-c-ctrl-c-hook' for more information.")
13483 (defvar org-shiftmetaup-hook nil
13484 "Hook for functions attaching themselves to `M-S-up'.
13485 See `org-ctrl-c-ctrl-c-hook' for more information.")
13486 (defvar org-shiftmetadown-hook nil
13487 "Hook for functions attaching themselves to `M-S-down'.
13488 See `org-ctrl-c-ctrl-c-hook' for more information.")
13489 (defvar org-metareturn-hook nil
13490 "Hook for functions attaching themselves to `M-RET'.
13491 See `org-ctrl-c-ctrl-c-hook' for more information.")
13493 (defun org-modifier-cursor-error ()
13494 "Throw an error, a modified cursor command was applied in wrong context."
13495 (error "This command is active in special context like tables, headlines or items"))
13497 (defun org-shiftselect-error ()
13498 "Throw an error because Shift-Cursor command was applied in wrong context."
13499 (if (and (boundp 'shift-select-mode) shift-select-mode)
13500 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13501 (error "This command works only in special context like headlines or timestamps.")))
13503 (defun org-call-for-shift-select (cmd)
13504 (let ((this-command-keys-shift-translated t))
13505 (call-interactively cmd)))
13507 (defun org-shifttab (&optional arg)
13508 "Global visibility cycling or move to previous table field.
13509 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13510 on context.
13511 See the individual commands for more information."
13512 (interactive "P")
13513 (cond
13514 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13515 ((integerp arg)
13516 (message "Content view to level: %d" arg)
13517 (org-content (prefix-numeric-value arg))
13518 (setq org-cycle-global-status 'overview))
13519 (t (call-interactively 'org-global-cycle))))
13521 (defun org-shiftmetaleft ()
13522 "Promote subtree or delete table column.
13523 Calls `org-promote-subtree', `org-outdent-item',
13524 or `org-table-delete-column', depending on context.
13525 See the individual commands for more information."
13526 (interactive)
13527 (cond
13528 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13529 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13530 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13531 ((org-at-item-p) (call-interactively 'org-outdent-item))
13532 (t (org-modifier-cursor-error))))
13534 (defun org-shiftmetaright ()
13535 "Demote subtree or insert table column.
13536 Calls `org-demote-subtree', `org-indent-item',
13537 or `org-table-insert-column', depending on context.
13538 See the individual commands for more information."
13539 (interactive)
13540 (cond
13541 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13542 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13543 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13544 ((org-at-item-p) (call-interactively 'org-indent-item))
13545 (t (org-modifier-cursor-error))))
13547 (defun org-shiftmetaup (&optional arg)
13548 "Move subtree up or kill table row.
13549 Calls `org-move-subtree-up' or `org-table-kill-row' or
13550 `org-move-item-up' depending on context. See the individual commands
13551 for more information."
13552 (interactive "P")
13553 (cond
13554 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13555 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13556 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13557 ((org-at-item-p) (call-interactively 'org-move-item-up))
13558 (t (org-modifier-cursor-error))))
13560 (defun org-shiftmetadown (&optional arg)
13561 "Move subtree down or insert table row.
13562 Calls `org-move-subtree-down' or `org-table-insert-row' or
13563 `org-move-item-down', depending on context. See the individual
13564 commands for more information."
13565 (interactive "P")
13566 (cond
13567 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13568 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13569 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13570 ((org-at-item-p) (call-interactively 'org-move-item-down))
13571 (t (org-modifier-cursor-error))))
13573 (defun org-metaleft (&optional arg)
13574 "Promote heading or move table column to left.
13575 Calls `org-do-promote' or `org-table-move-column', depending on context.
13576 With no specific context, calls the Emacs default `backward-word'.
13577 See the individual commands for more information."
13578 (interactive "P")
13579 (cond
13580 ((run-hook-with-args-until-success 'org-metaleft-hook))
13581 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13582 ((or (org-on-heading-p)
13583 (and (org-region-active-p)
13584 (save-excursion
13585 (goto-char (region-beginning))
13586 (org-on-heading-p))))
13587 (call-interactively 'org-do-promote))
13588 ((or (org-at-item-p)
13589 (and (org-region-active-p)
13590 (save-excursion
13591 (goto-char (region-beginning))
13592 (org-at-item-p))))
13593 (call-interactively 'org-outdent-item))
13594 (t (call-interactively 'backward-word))))
13596 (defun org-metaright (&optional arg)
13597 "Demote subtree or move table column to right.
13598 Calls `org-do-demote' or `org-table-move-column', depending on context.
13599 With no specific context, calls the Emacs default `forward-word'.
13600 See the individual commands for more information."
13601 (interactive "P")
13602 (cond
13603 ((run-hook-with-args-until-success 'org-metaright-hook))
13604 ((org-at-table-p) (call-interactively 'org-table-move-column))
13605 ((or (org-on-heading-p)
13606 (and (org-region-active-p)
13607 (save-excursion
13608 (goto-char (region-beginning))
13609 (org-on-heading-p))))
13610 (call-interactively 'org-do-demote))
13611 ((or (org-at-item-p)
13612 (and (org-region-active-p)
13613 (save-excursion
13614 (goto-char (region-beginning))
13615 (org-at-item-p))))
13616 (call-interactively 'org-indent-item))
13617 (t (call-interactively 'forward-word))))
13619 (defun org-metaup (&optional arg)
13620 "Move subtree up or move table row up.
13621 Calls `org-move-subtree-up' or `org-table-move-row' or
13622 `org-move-item-up', depending on context. See the individual commands
13623 for more information."
13624 (interactive "P")
13625 (cond
13626 ((run-hook-with-args-until-success 'org-metaup-hook))
13627 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13628 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13629 ((org-at-item-p) (call-interactively 'org-move-item-up))
13630 (t (transpose-lines 1) (beginning-of-line -1))))
13632 (defun org-metadown (&optional arg)
13633 "Move subtree down or move table row down.
13634 Calls `org-move-subtree-down' or `org-table-move-row' or
13635 `org-move-item-down', depending on context. See the individual
13636 commands for more information."
13637 (interactive "P")
13638 (cond
13639 ((run-hook-with-args-until-success 'org-metadown-hook))
13640 ((org-at-table-p) (call-interactively 'org-table-move-row))
13641 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13642 ((org-at-item-p) (call-interactively 'org-move-item-down))
13643 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13645 (defun org-shiftup (&optional arg)
13646 "Increase item in timestamp or increase priority of current headline.
13647 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13648 depending on context. See the individual commands for more information."
13649 (interactive "P")
13650 (cond
13651 ((and org-support-shift-select (org-region-active-p))
13652 (org-call-for-shift-select 'previous-line))
13653 ((org-at-timestamp-p t)
13654 (call-interactively (if org-edit-timestamp-down-means-later
13655 'org-timestamp-down 'org-timestamp-up)))
13656 ((and (not (eq org-support-shift-select 'always))
13657 (org-on-heading-p))
13658 (call-interactively 'org-priority-up))
13659 ((and (not org-support-shift-select) (org-at-item-p))
13660 (call-interactively 'org-previous-item))
13661 ((org-clocktable-try-shift 'up arg))
13662 (org-support-shift-select
13663 (org-call-for-shift-select 'previous-line))
13664 (t (org-shiftselect-error))))
13666 (defun org-shiftdown (&optional arg)
13667 "Decrease item in timestamp or decrease priority of current headline.
13668 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13669 depending on context. See the individual commands for more information."
13670 (interactive "P")
13671 (cond
13672 ((and org-support-shift-select (org-region-active-p))
13673 (org-call-for-shift-select 'next-line))
13674 ((org-at-timestamp-p t)
13675 (call-interactively (if org-edit-timestamp-down-means-later
13676 'org-timestamp-up 'org-timestamp-down)))
13677 ((and (not (eq org-support-shift-select 'always))
13678 (org-on-heading-p))
13679 (call-interactively 'org-priority-down))
13680 ((and (not org-support-shift-select) (org-at-item-p))
13681 (call-interactively 'org-next-item))
13682 ((org-clocktable-try-shift 'down arg))
13683 (org-support-shift-select
13684 (org-call-for-shift-select 'next-line))
13685 (t (org-shiftselect-error))))
13687 (defun org-shiftright (&optional arg)
13688 "Cycle the thing at point or in the current line, depending on context.
13689 Depending on context, this does one of the following:
13691 - switch a timestamp at point one day into the future
13692 - on a headline, switch to the next TODO keyword.
13693 - on an item, switch entire list to the next bullet type
13694 - on a property line, switch to the next allowed value
13695 - on a clocktable definition line, move time block into the future"
13696 (interactive "P")
13697 (cond
13698 ((and org-support-shift-select (org-region-active-p))
13699 (org-call-for-shift-select 'forward-char))
13700 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13701 ((and (not (eq org-support-shift-select 'always))
13702 (org-on-heading-p))
13703 (org-call-with-arg 'org-todo 'right))
13704 ((or (and org-support-shift-select
13705 (not (eq org-support-shift-select 'always))
13706 (org-at-item-bullet-p))
13707 (and (not org-support-shift-select) (org-at-item-p)))
13708 (org-call-with-arg 'org-cycle-list-bullet nil))
13709 ((and (not (eq org-support-shift-select 'always))
13710 (org-at-property-p))
13711 (call-interactively 'org-property-next-allowed-value))
13712 ((org-clocktable-try-shift 'right arg))
13713 (org-support-shift-select
13714 (org-call-for-shift-select 'forward-char))
13715 (t (org-shiftselect-error))))
13717 (defun org-shiftleft (&optional arg)
13718 "Cycle the thing at point or in the current line, depending on context.
13719 Depending on context, this does one of the following:
13721 - switch a timestamp at point one day into the past
13722 - on a headline, switch to the previous TODO keyword.
13723 - on an item, switch entire list to the previous bullet type
13724 - on a property line, switch to the previous allowed value
13725 - on a clocktable definition line, move time block into the past"
13726 (interactive "P")
13727 (cond
13728 ((and org-support-shift-select (org-region-active-p))
13729 (org-call-for-shift-select 'backward-char))
13730 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13731 ((and (not (eq org-support-shift-select 'always))
13732 (org-on-heading-p))
13733 (org-call-with-arg 'org-todo 'left))
13734 ((or (and org-support-shift-select
13735 (not (eq org-support-shift-select 'always))
13736 (org-at-item-bullet-p))
13737 (and (not org-support-shift-select) (org-at-item-p)))
13738 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13739 ((and (not (eq org-support-shift-select 'always))
13740 (org-at-property-p))
13741 (call-interactively 'org-property-previous-allowed-value))
13742 ((org-clocktable-try-shift 'left arg))
13743 (org-support-shift-select
13744 (org-call-for-shift-select 'backward-char))
13745 (t (org-shiftselect-error))))
13747 (defun org-shiftcontrolright ()
13748 "Switch to next TODO set."
13749 (interactive)
13750 (cond
13751 ((and org-support-shift-select (org-region-active-p))
13752 (org-call-for-shift-select 'forward-word))
13753 ((and (not (eq org-support-shift-select 'always))
13754 (org-on-heading-p))
13755 (org-call-with-arg 'org-todo 'nextset))
13756 (org-support-shift-select
13757 (org-call-for-shift-select 'forward-word))
13758 (t (org-shiftselect-error))))
13760 (defun org-shiftcontrolleft ()
13761 "Switch to previous TODO set."
13762 (interactive)
13763 (cond
13764 ((and org-support-shift-select (org-region-active-p))
13765 (org-call-for-shift-select 'backward-word))
13766 ((and (not (eq org-support-shift-select 'always))
13767 (org-on-heading-p))
13768 (org-call-with-arg 'org-todo 'previousset))
13769 (org-support-shift-select
13770 (org-call-for-shift-select 'backward-word))
13771 (t (org-shiftselect-error))))
13773 (defun org-ctrl-c-ret ()
13774 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13775 (interactive)
13776 (cond
13777 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13778 (t (call-interactively 'org-insert-heading))))
13780 (defun org-copy-special ()
13781 "Copy region in table or copy current subtree.
13782 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13783 See the individual commands for more information."
13784 (interactive)
13785 (call-interactively
13786 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13788 (defun org-cut-special ()
13789 "Cut region in table or cut current subtree.
13790 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13791 See the individual commands for more information."
13792 (interactive)
13793 (call-interactively
13794 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13796 (defun org-paste-special (arg)
13797 "Paste rectangular region into table, or past subtree relative to level.
13798 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13799 See the individual commands for more information."
13800 (interactive "P")
13801 (if (org-at-table-p)
13802 (org-table-paste-rectangle)
13803 (org-paste-subtree arg)))
13805 (defun org-edit-special ()
13806 "Call a special editor for the stuff at point.
13807 When at a table, call the formula editor with `org-table-edit-formulas'.
13808 When at the first line of an src example, call `org-edit-src-code'.
13809 When in an #+include line, visit the include file. Otherwise call
13810 `ffap' to visit the file at point."
13811 (interactive)
13812 (cond
13813 ((org-at-table-p)
13814 (call-interactively 'org-table-edit-formulas))
13815 ((save-excursion
13816 (beginning-of-line 1)
13817 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13818 (find-file (org-trim (match-string 1))))
13819 ((org-edit-src-code))
13820 ((org-edit-fixed-width-region))
13821 (t (call-interactively 'ffap))))
13824 (defun org-ctrl-c-ctrl-c (&optional arg)
13825 "Set tags in headline, or update according to changed information at point.
13827 This command does many different things, depending on context:
13829 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
13830 this is what we do.
13832 - If the cursor is in a headline, prompt for tags and insert them
13833 into the current line, aligned to `org-tags-column'. When called
13834 with prefix arg, realign all tags in the current buffer.
13836 - If the cursor is in one of the special #+KEYWORD lines, this
13837 triggers scanning the buffer for these lines and updating the
13838 information.
13840 - If the cursor is inside a table, realign the table. This command
13841 works even if the automatic table editor has been turned off.
13843 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13844 the entire table.
13846 - If the cursor is at a footnote reference or definition, jump to
13847 the corresponding definition or references, respectively.
13849 - If the cursor is a the beginning of a dynamic block, update it.
13851 - If the cursor is inside a table created by the table.el package,
13852 activate that table.
13854 - If the current buffer is a remember buffer, close note and file
13855 it. A prefix argument of 1 files to the default location
13856 without further interaction. A prefix argument of 2 files to
13857 the currently clocking task.
13859 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13860 links in this buffer.
13862 - If the cursor is on a numbered item in a plain list, renumber the
13863 ordered list.
13865 - If the cursor is on a checkbox, toggle it."
13866 (interactive "P")
13867 (let ((org-enable-table-editor t))
13868 (cond
13869 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13870 org-occur-highlights
13871 org-latex-fragment-image-overlays)
13872 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13873 (org-remove-occur-highlights)
13874 (org-remove-latex-fragment-image-overlays)
13875 (message "Temporary highlights/overlays removed from current buffer"))
13876 ((and (local-variable-p 'org-finish-function (current-buffer))
13877 (fboundp org-finish-function))
13878 (funcall org-finish-function))
13879 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
13880 ((org-at-property-p)
13881 (call-interactively 'org-property-action))
13882 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13883 ((org-on-heading-p) (call-interactively 'org-set-tags))
13884 ((org-at-table.el-p)
13885 (require 'table)
13886 (beginning-of-line 1)
13887 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13888 (call-interactively 'table-recognize-table))
13889 ((org-at-table-p)
13890 (org-table-maybe-eval-formula)
13891 (if arg
13892 (call-interactively 'org-table-recalculate)
13893 (org-table-maybe-recalculate-line))
13894 (call-interactively 'org-table-align))
13895 ((or (org-footnote-at-reference-p)
13896 (org-footnote-at-definition-p))
13897 (call-interactively 'org-footnote-action))
13898 ((org-at-item-checkbox-p)
13899 (call-interactively 'org-toggle-checkbox))
13900 ((org-at-item-p)
13901 (if arg
13902 (call-interactively 'org-toggle-checkbox)
13903 (call-interactively 'org-maybe-renumber-ordered-list)))
13904 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13905 ;; Dynamic block
13906 (beginning-of-line 1)
13907 (save-excursion (org-update-dblock)))
13908 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13909 (cond
13910 ((equal (match-string 1) "TBLFM")
13911 ;; Recalculate the table before this line
13912 (save-excursion
13913 (beginning-of-line 1)
13914 (skip-chars-backward " \r\n\t")
13915 (if (org-at-table-p)
13916 (org-call-with-arg 'org-table-recalculate t))))
13918 ; (org-set-regexps-and-options)
13919 ; (org-restart-font-lock)
13920 (let ((org-inhibit-startup t)) (org-mode-restart))
13921 (message "Local setup has been refreshed"))))
13922 (t (error "C-c C-c can do nothing useful at this location.")))))
13924 (defun org-mode-restart ()
13925 "Restart Org-mode, to scan again for special lines.
13926 Also updates the keyword regular expressions."
13927 (interactive)
13928 (org-mode)
13929 (message "Org-mode restarted"))
13931 (defun org-kill-note-or-show-branches ()
13932 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13933 (interactive)
13934 (if (not org-finish-function)
13935 (call-interactively 'show-branches)
13936 (let ((org-note-abort t))
13937 (funcall org-finish-function))))
13939 (defun org-return (&optional indent)
13940 "Goto next table row or insert a newline.
13941 Calls `org-table-next-row' or `newline', depending on context.
13942 See the individual commands for more information."
13943 (interactive)
13944 (cond
13945 ((bobp) (if indent (newline-and-indent) (newline)))
13946 ((org-at-table-p)
13947 (org-table-justify-field-maybe)
13948 (call-interactively 'org-table-next-row))
13949 ((and org-return-follows-link
13950 (eq (get-text-property (point) 'face) 'org-link))
13951 (call-interactively 'org-open-at-point))
13952 ((and (org-at-heading-p)
13953 (looking-at
13954 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13955 (org-show-entry)
13956 (end-of-line 1)
13957 (newline))
13958 (t (if indent (newline-and-indent) (newline)))))
13960 (defun org-return-indent ()
13961 "Goto next table row or insert a newline and indent.
13962 Calls `org-table-next-row' or `newline-and-indent', depending on
13963 context. See the individual commands for more information."
13964 (interactive)
13965 (org-return t))
13967 (defun org-ctrl-c-star ()
13968 "Compute table, or change heading status of lines.
13969 Calls `org-table-recalculate' or `org-toggle-heading',
13970 depending on context."
13971 (interactive)
13972 (cond
13973 ((org-at-table-p)
13974 (call-interactively 'org-table-recalculate))
13976 ;; Convert all lines in region to list items
13977 (call-interactively 'org-toggle-heading))))
13979 (defun org-ctrl-c-minus ()
13980 "Insert separator line in table or modify bullet status of line.
13981 Also turns a plain line or a region of lines into list items.
13982 Calls `org-table-insert-hline', `org-toggle-item', or
13983 `org-cycle-list-bullet', depending on context."
13984 (interactive)
13985 (cond
13986 ((org-at-table-p)
13987 (call-interactively 'org-table-insert-hline))
13988 ((org-region-active-p)
13989 (call-interactively 'org-toggle-item))
13990 ((org-in-item-p)
13991 (call-interactively 'org-cycle-list-bullet))
13993 (call-interactively 'org-toggle-item))))
13995 (defun org-toggle-item ()
13996 "Convert headings or normal lines to items, items to normal lines.
13997 If there is no active region, only the current line is considered.
13999 If the first line in the region is a headline, convert all headlines to items.
14001 If the first line in the region is an item, convert all items to normal lines.
14003 If the first line is normal text, add an item bullet to each line."
14004 (interactive)
14005 (let (l2 l beg end)
14006 (if (org-region-active-p)
14007 (setq beg (region-beginning) end (region-end))
14008 (setq beg (point-at-bol)
14009 end (min (1+ (point-at-eol)) (point-max))))
14010 (save-excursion
14011 (goto-char end)
14012 (setq l2 (org-current-line))
14013 (goto-char beg)
14014 (beginning-of-line 1)
14015 (setq l (1- (org-current-line)))
14016 (if (org-at-item-p)
14017 ;; We already have items, de-itemize
14018 (while (< (setq l (1+ l)) l2)
14019 (when (org-at-item-p)
14020 (goto-char (match-beginning 2))
14021 (delete-region (match-beginning 2) (match-end 2))
14022 (and (looking-at "[ \t]+") (replace-match "")))
14023 (beginning-of-line 2))
14024 (if (org-on-heading-p)
14025 ;; Headings, convert to items
14026 (while (< (setq l (1+ l)) l2)
14027 (if (looking-at org-outline-regexp)
14028 (replace-match "- " t t))
14029 (beginning-of-line 2))
14030 ;; normal lines, turn them into items
14031 (while (< (setq l (1+ l)) l2)
14032 (unless (org-at-item-p)
14033 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14034 (replace-match "\\1- \\2")))
14035 (beginning-of-line 2)))))))
14037 (defun org-toggle-heading (&optional nstars)
14038 "Convert headings to normal text, or items or text to headings.
14039 If there is no active region, only the current line is considered.
14041 If the first line is a heading, remove the stars from all headlines
14042 in the region.
14044 If the first line is a plain list item, turn all plain list items into
14045 headings.
14047 If the first line is a normal line, turn each and every line in the region
14048 into a heading.
14050 When converting a line into a heading, the number of stars is chosen
14051 such that the lines become children of the current entry. However, when
14052 a prefix argument is given, its value determines the number of stars to add."
14053 (interactive "P")
14054 (let (l2 l itemp beg end)
14055 (if (org-region-active-p)
14056 (setq beg (region-beginning) end (region-end))
14057 (setq beg (point-at-bol)
14058 end (min (1+ (point-at-eol)) (point-max))))
14059 (save-excursion
14060 (goto-char end)
14061 (setq l2 (org-current-line))
14062 (goto-char beg)
14063 (beginning-of-line 1)
14064 (setq l (1- (org-current-line)))
14065 (if (org-on-heading-p)
14066 ;; We already have headlines, de-star them
14067 (while (< (setq l (1+ l)) l2)
14068 (when (org-on-heading-p t)
14069 (and (looking-at outline-regexp) (replace-match "")))
14070 (beginning-of-line 2))
14071 (setq itemp (org-at-item-p))
14072 (let* ((stars
14073 (if nstars
14074 (make-string (prefix-numeric-value current-prefix-arg)
14076 (save-excursion
14077 (re-search-backward org-complex-heading-regexp nil t)
14078 (or (match-string 1) "*"))))
14079 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
14080 (rpl (concat stars add-stars " ")))
14081 (while (< (setq l (1+ l)) l2)
14082 (if itemp
14083 (and (org-at-item-p) (replace-match rpl t t))
14084 (unless (org-on-heading-p)
14085 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14086 (replace-match (concat rpl (match-string 2))))))
14087 (beginning-of-line 2)))))))
14089 (defun org-meta-return (&optional arg)
14090 "Insert a new heading or wrap a region in a table.
14091 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14092 See the individual commands for more information."
14093 (interactive "P")
14094 (cond
14095 ((run-hook-with-args-until-success 'org-metareturn-hook))
14096 ((org-at-table-p)
14097 (call-interactively 'org-table-wrap-region))
14098 (t (call-interactively 'org-insert-heading))))
14100 ;;; Menu entries
14102 ;; Define the Org-mode menus
14103 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14104 '("Tbl"
14105 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14106 ["Next Field" org-cycle (org-at-table-p)]
14107 ["Previous Field" org-shifttab (org-at-table-p)]
14108 ["Next Row" org-return (org-at-table-p)]
14109 "--"
14110 ["Blank Field" org-table-blank-field (org-at-table-p)]
14111 ["Edit Field" org-table-edit-field (org-at-table-p)]
14112 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14113 "--"
14114 ("Column"
14115 ["Move Column Left" org-metaleft (org-at-table-p)]
14116 ["Move Column Right" org-metaright (org-at-table-p)]
14117 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14118 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14119 ("Row"
14120 ["Move Row Up" org-metaup (org-at-table-p)]
14121 ["Move Row Down" org-metadown (org-at-table-p)]
14122 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14123 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14124 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14125 "--"
14126 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14127 ("Rectangle"
14128 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14129 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14130 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14131 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14132 "--"
14133 ("Calculate"
14134 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14135 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14136 ["Edit Formulas" org-edit-special (org-at-table-p)]
14137 "--"
14138 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14139 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14140 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14141 "--"
14142 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14143 "--"
14144 ["Sum Column/Rectangle" org-table-sum
14145 (or (org-at-table-p) (org-region-active-p))]
14146 ["Which Column?" org-table-current-column (org-at-table-p)])
14147 ["Debug Formulas"
14148 org-table-toggle-formula-debugger
14149 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14150 ["Show Col/Row Numbers"
14151 org-table-toggle-coordinate-overlays
14152 :style toggle
14153 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14154 "--"
14155 ["Create" org-table-create (and (not (org-at-table-p))
14156 org-enable-table-editor)]
14157 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14158 ["Import from File" org-table-import (not (org-at-table-p))]
14159 ["Export to File" org-table-export (org-at-table-p)]
14160 "--"
14161 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14163 (easy-menu-define org-org-menu org-mode-map "Org menu"
14164 '("Org"
14165 ("Show/Hide"
14166 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14167 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14168 ["Sparse Tree..." org-sparse-tree t]
14169 ["Reveal Context" org-reveal t]
14170 ["Show All" show-all t]
14171 "--"
14172 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14173 "--"
14174 ["New Heading" org-insert-heading t]
14175 ("Navigate Headings"
14176 ["Up" outline-up-heading t]
14177 ["Next" outline-next-visible-heading t]
14178 ["Previous" outline-previous-visible-heading t]
14179 ["Next Same Level" outline-forward-same-level t]
14180 ["Previous Same Level" outline-backward-same-level t]
14181 "--"
14182 ["Jump" org-goto t])
14183 ("Edit Structure"
14184 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14185 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14186 "--"
14187 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14188 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14189 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14190 "--"
14191 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14192 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14193 ["Demote Heading" org-metaright (not (org-at-table-p))]
14194 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14195 "--"
14196 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14197 "--"
14198 ["Convert to odd levels" org-convert-to-odd-levels t]
14199 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14200 ("Editing"
14201 ["Emphasis..." org-emphasize t]
14202 ["Edit Source Example" org-edit-special t]
14203 "--"
14204 ["Footnote new/jump" org-footnote-action t]
14205 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14206 ("Archive"
14207 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14208 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14209 ; :active t :keys "C-u C-c C-x C-a"]
14210 ["Sparse trees open ARCHIVE trees"
14211 (setq org-sparse-tree-open-archived-trees
14212 (not org-sparse-tree-open-archived-trees))
14213 :style toggle :selected org-sparse-tree-open-archived-trees]
14214 ["Cycling opens ARCHIVE trees"
14215 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14216 :style toggle :selected org-cycle-open-archived-trees]
14217 "--"
14218 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14219 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14220 ; ["Check and Move Children" (org-archive-subtree '(4))
14221 ; :active t :keys "C-u C-c C-x C-s"]
14223 "--"
14224 ("TODO Lists"
14225 ["TODO/DONE/-" org-todo t]
14226 ("Select keyword"
14227 ["Next keyword" org-shiftright (org-on-heading-p)]
14228 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14229 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14230 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14231 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14232 ["Show TODO Tree" org-show-todo-tree t]
14233 ["Global TODO list" org-todo-list t]
14234 "--"
14235 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14236 :selected org-enforce-todo-dependencies :style toggle :active t]
14237 "Settings for tree at point"
14238 ["Do Children sequentially" org-toggle-ordered-property :style radio
14239 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14240 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14241 ["Do Children parallel" org-toggle-ordered-property :style radio
14242 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14243 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14244 "--"
14245 ["Set Priority" org-priority t]
14246 ["Priority Up" org-shiftup t]
14247 ["Priority Down" org-shiftdown t])
14248 ("TAGS and Properties"
14249 ["Set Tags" org-set-tags-command t]
14250 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14251 "--"
14252 ["Set property" org-set-property t]
14253 ["Column view of properties" org-columns t]
14254 ["Insert Column View DBlock" org-insert-columns-dblock t])
14255 ("Dates and Scheduling"
14256 ["Timestamp" org-time-stamp t]
14257 ["Timestamp (inactive)" org-time-stamp-inactive t]
14258 ("Change Date"
14259 ["1 Day Later" org-shiftright t]
14260 ["1 Day Earlier" org-shiftleft t]
14261 ["1 ... Later" org-shiftup t]
14262 ["1 ... Earlier" org-shiftdown t])
14263 ["Compute Time Range" org-evaluate-time-range t]
14264 ["Schedule Item" org-schedule t]
14265 ["Deadline" org-deadline t]
14266 "--"
14267 ["Custom time format" org-toggle-time-stamp-overlays
14268 :style radio :selected org-display-custom-times]
14269 "--"
14270 ["Goto Calendar" org-goto-calendar t]
14271 ["Date from Calendar" org-date-from-calendar t]
14272 "--"
14273 ["Start/Restart Timer" org-timer-start t]
14274 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14275 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14276 ["Insert Timer String" org-timer t]
14277 ["Insert Timer Item" org-timer-item t])
14278 ("Logging work"
14279 ["Clock in" org-clock-in t]
14280 ["Clock out" org-clock-out t]
14281 ["Clock cancel" org-clock-cancel t]
14282 ["Goto running clock" org-clock-goto t]
14283 ["Display times" org-clock-display t]
14284 ["Create clock table" org-clock-report t]
14285 "--"
14286 ["Record DONE time"
14287 (progn (setq org-log-done (not org-log-done))
14288 (message "Switching to %s will %s record a timestamp"
14289 (car org-done-keywords)
14290 (if org-log-done "automatically" "not")))
14291 :style toggle :selected org-log-done])
14292 "--"
14293 ["Agenda Command..." org-agenda t]
14294 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14295 ("File List for Agenda")
14296 ("Special views current file"
14297 ["TODO Tree" org-show-todo-tree t]
14298 ["Check Deadlines" org-check-deadlines t]
14299 ["Timeline" org-timeline t]
14300 ["Tags Tree" org-tags-sparse-tree t])
14301 "--"
14302 ("Hyperlinks"
14303 ["Store Link (Global)" org-store-link t]
14304 ["Insert Link" org-insert-link t]
14305 ["Follow Link" org-open-at-point t]
14306 "--"
14307 ["Next link" org-next-link t]
14308 ["Previous link" org-previous-link t]
14309 "--"
14310 ["Descriptive Links"
14311 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14312 :style radio
14313 :selected (member '(org-link) buffer-invisibility-spec)]
14314 ["Literal Links"
14315 (progn
14316 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14317 :style radio
14318 :selected (not (member '(org-link) buffer-invisibility-spec))])
14319 "--"
14320 ["Export/Publish..." org-export t]
14321 ("LaTeX"
14322 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14323 :selected org-cdlatex-mode]
14324 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14325 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14326 ["Modify math symbol" org-cdlatex-math-modify
14327 (org-inside-LaTeX-fragment-p)]
14328 ["Export LaTeX fragments as images"
14329 (if (featurep 'org-exp)
14330 (setq org-export-with-LaTeX-fragments
14331 (not org-export-with-LaTeX-fragments))
14332 (require 'org-exp))
14333 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14334 org-export-with-LaTeX-fragments)])
14335 "--"
14336 ("Documentation"
14337 ["Show Version" org-version t]
14338 ["Info Documentation" org-info t])
14339 ("Customize"
14340 ["Browse Org Group" org-customize t]
14341 "--"
14342 ["Expand This Menu" org-create-customize-menu
14343 (fboundp 'customize-menu-create)])
14344 "--"
14345 ("Refresh/Reload"
14346 ["Refresh setup current buffer" org-mode-restart t]
14347 ["Reload Org (after update)" org-reload t]
14348 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14351 (defun org-info (&optional node)
14352 "Read documentation for Org-mode in the info system.
14353 With optional NODE, go directly to that node."
14354 (interactive)
14355 (info (format "(org)%s" (or node ""))))
14357 (defun org-install-agenda-files-menu ()
14358 (let ((bl (buffer-list)))
14359 (save-excursion
14360 (while bl
14361 (set-buffer (pop bl))
14362 (if (org-mode-p) (setq bl nil)))
14363 (when (org-mode-p)
14364 (easy-menu-change
14365 '("Org") "File List for Agenda"
14366 (append
14367 (list
14368 ["Edit File List" (org-edit-agenda-file-list) t]
14369 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14370 ["Remove Current File from List" org-remove-file t]
14371 ["Cycle through agenda files" org-cycle-agenda-files t]
14372 ["Occur in all agenda files" org-occur-in-agenda-files t]
14373 "--")
14374 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14376 ;;;; Documentation
14378 ;;;###autoload
14379 (defun org-require-autoloaded-modules ()
14380 (interactive)
14381 (mapc 'require
14382 '(org-agenda org-archive org-attach org-clock org-colview
14383 org-exp org-id org-export-latex org-publish
14384 org-remember org-table org-timer)))
14386 ;;;###autoload
14387 (defun org-reload (&optional uncompiled)
14388 "Reload all org lisp files.
14389 With prefix arg UNCOMPILED, load the uncompiled versions."
14390 (interactive "P")
14391 (require 'find-func)
14392 (let* ((dir (file-name-directory (find-library-name "org")))
14393 (files (directory-files dir t "\\.el\\'"))
14394 (remove-re (concat (if (featurep 'xemacs)
14395 "org-colview" "org-colview-xemacs")
14396 "\\'")))
14397 (setq files (mapcar 'file-name-sans-extension files))
14398 (setq files (mapcar
14399 (lambda (x) (if (string-match remove-re x) nil x))
14400 files))
14401 (setq files (delq nil files))
14402 (mapc
14403 (lambda (f)
14404 (if (and (not uncompiled)
14405 (file-exists-p (concat f ".elc")))
14406 (load (concat f ".elc") nil nil t)
14407 (load (concat f ".el") nil nil t)))
14408 files)))
14410 ;;;###autoload
14411 (defun org-customize ()
14412 "Call the customize function with org as argument."
14413 (interactive)
14414 (org-load-modules-maybe)
14415 (org-require-autoloaded-modules)
14416 (customize-browse 'org))
14418 (defun org-create-customize-menu ()
14419 "Create a full customization menu for Org-mode, insert it into the menu."
14420 (interactive)
14421 (org-load-modules-maybe)
14422 (org-require-autoloaded-modules)
14423 (if (fboundp 'customize-menu-create)
14424 (progn
14425 (easy-menu-change
14426 '("Org") "Customize"
14427 `(["Browse Org group" org-customize t]
14428 "--"
14429 ,(customize-menu-create 'org)
14430 ["Set" Custom-set t]
14431 ["Save" Custom-save t]
14432 ["Reset to Current" Custom-reset-current t]
14433 ["Reset to Saved" Custom-reset-saved t]
14434 ["Reset to Standard Settings" Custom-reset-standard t]))
14435 (message "\"Org\"-menu now contains full customization menu"))
14436 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14438 ;;;; Miscellaneous stuff
14440 ;;; Generally useful functions
14442 (defun org-find-text-property-in-string (prop s)
14443 "Return the first non-nil value of property PROP in string S."
14444 (or (get-text-property 0 prop s)
14445 (get-text-property (or (next-single-property-change 0 prop s) 0)
14446 prop s)))
14448 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14449 "Display the given MESSAGE as a warning."
14450 (if (fboundp 'display-warning)
14451 (display-warning 'org message
14452 (if (featurep 'xemacs)
14453 'warning
14454 :warning))
14455 (let ((buf (get-buffer-create "*Org warnings*")))
14456 (with-current-buffer buf
14457 (goto-char (point-max))
14458 (insert "Warning (Org): " message)
14459 (unless (bolp)
14460 (newline)))
14461 (display-buffer buf)
14462 (sit-for 0))))
14464 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14465 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14466 (if (and marker (marker-buffer marker)
14467 (buffer-live-p (marker-buffer marker)))
14468 (progn
14469 (switch-to-buffer (marker-buffer marker))
14470 (if (or (> marker (point-max)) (< marker (point-min)))
14471 (widen))
14472 (goto-char marker)
14473 (org-show-context 'org-goto))
14474 (if bookmark
14475 (bookmark-jump bookmark)
14476 (error "Cannot find location"))))
14478 (defun org-quote-csv-field (s)
14479 "Quote field for inclusion in CSV material."
14480 (if (string-match "[\",]" s)
14481 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14484 (defun org-plist-delete (plist property)
14485 "Delete PROPERTY from PLIST.
14486 This is in contrast to merely setting it to 0."
14487 (let (p)
14488 (while plist
14489 (if (not (eq property (car plist)))
14490 (setq p (plist-put p (car plist) (nth 1 plist))))
14491 (setq plist (cddr plist)))
14494 (defun org-force-self-insert (N)
14495 "Needed to enforce self-insert under remapping."
14496 (interactive "p")
14497 (self-insert-command N))
14499 (defun org-string-width (s)
14500 "Compute width of string, ignoring invisible characters.
14501 This ignores character with invisibility property `org-link', and also
14502 characters with property `org-cwidth', because these will become invisible
14503 upon the next fontification round."
14504 (let (b l)
14505 (when (or (eq t buffer-invisibility-spec)
14506 (assq 'org-link buffer-invisibility-spec))
14507 (while (setq b (text-property-any 0 (length s)
14508 'invisible 'org-link s))
14509 (setq s (concat (substring s 0 b)
14510 (substring s (or (next-single-property-change
14511 b 'invisible s) (length s)))))))
14512 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14513 (setq s (concat (substring s 0 b)
14514 (substring s (or (next-single-property-change
14515 b 'org-cwidth s) (length s))))))
14516 (setq l (string-width s) b -1)
14517 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14518 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14521 (defun org-get-indentation (&optional line)
14522 "Get the indentation of the current line, interpreting tabs.
14523 When LINE is given, assume it represents a line and compute its indentation."
14524 (if line
14525 (if (string-match "^ *" (org-remove-tabs line))
14526 (match-end 0))
14527 (save-excursion
14528 (beginning-of-line 1)
14529 (skip-chars-forward " \t")
14530 (current-column))))
14532 (defun org-remove-tabs (s &optional width)
14533 "Replace tabulators in S with spaces.
14534 Assumes that s is a single line, starting in column 0."
14535 (setq width (or width tab-width))
14536 (while (string-match "\t" s)
14537 (setq s (replace-match
14538 (make-string
14539 (- (* width (/ (+ (match-beginning 0) width) width))
14540 (match-beginning 0)) ?\ )
14541 t t s)))
14544 (defun org-fix-indentation (line ind)
14545 "Fix indentation in LINE.
14546 IND is a cons cell with target and minimum indentation.
14547 If the current indentation in LINE is smaller than the minimum,
14548 leave it alone. If it is larger than ind, set it to the target."
14549 (let* ((l (org-remove-tabs line))
14550 (i (org-get-indentation l))
14551 (i1 (car ind)) (i2 (cdr ind)))
14552 (if (>= i i2) (setq l (substring line i2)))
14553 (if (> i1 0)
14554 (concat (make-string i1 ?\ ) l)
14555 l)))
14557 (defun org-base-buffer (buffer)
14558 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14559 (if (not buffer)
14560 buffer
14561 (or (buffer-base-buffer buffer)
14562 buffer)))
14564 (defun org-trim (s)
14565 "Remove whitespace at beginning and end of string."
14566 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14567 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14570 (defun org-wrap (string &optional width lines)
14571 "Wrap string to either a number of lines, or a width in characters.
14572 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14573 that costs. If there is a word longer than WIDTH, the text is actually
14574 wrapped to the length of that word.
14575 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14576 many lines, whatever width that takes.
14577 The return value is a list of lines, without newlines at the end."
14578 (let* ((words (org-split-string string "[ \t\n]+"))
14579 (maxword (apply 'max (mapcar 'org-string-width words)))
14580 w ll)
14581 (cond (width
14582 (org-do-wrap words (max maxword width)))
14583 (lines
14584 (setq w maxword)
14585 (setq ll (org-do-wrap words maxword))
14586 (if (<= (length ll) lines)
14588 (setq ll words)
14589 (while (> (length ll) lines)
14590 (setq w (1+ w))
14591 (setq ll (org-do-wrap words w)))
14592 ll))
14593 (t (error "Cannot wrap this")))))
14595 (defun org-do-wrap (words width)
14596 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14597 (let (lines line)
14598 (while words
14599 (setq line (pop words))
14600 (while (and words (< (+ (length line) (length (car words))) width))
14601 (setq line (concat line " " (pop words))))
14602 (setq lines (push line lines)))
14603 (nreverse lines)))
14605 (defun org-split-string (string &optional separators)
14606 "Splits STRING into substrings at SEPARATORS.
14607 No empty strings are returned if there are matches at the beginning
14608 and end of string."
14609 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14610 (start 0)
14611 notfirst
14612 (list nil))
14613 (while (and (string-match rexp string
14614 (if (and notfirst
14615 (= start (match-beginning 0))
14616 (< start (length string)))
14617 (1+ start) start))
14618 (< (match-beginning 0) (length string)))
14619 (setq notfirst t)
14620 (or (eq (match-beginning 0) 0)
14621 (and (eq (match-beginning 0) (match-end 0))
14622 (eq (match-beginning 0) start))
14623 (setq list
14624 (cons (substring string start (match-beginning 0))
14625 list)))
14626 (setq start (match-end 0)))
14627 (or (eq start (length string))
14628 (setq list
14629 (cons (substring string start)
14630 list)))
14631 (nreverse list)))
14633 (defun org-context ()
14634 "Return a list of contexts of the current cursor position.
14635 If several contexts apply, all are returned.
14636 Each context entry is a list with a symbol naming the context, and
14637 two positions indicating start and end of the context. Possible
14638 contexts are:
14640 :headline anywhere in a headline
14641 :headline-stars on the leading stars in a headline
14642 :todo-keyword on a TODO keyword (including DONE) in a headline
14643 :tags on the TAGS in a headline
14644 :priority on the priority cookie in a headline
14645 :item on the first line of a plain list item
14646 :item-bullet on the bullet/number of a plain list item
14647 :checkbox on the checkbox in a plain list item
14648 :table in an org-mode table
14649 :table-special on a special filed in a table
14650 :table-table in a table.el table
14651 :link on a hyperlink
14652 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14653 :target on a <<target>>
14654 :radio-target on a <<<radio-target>>>
14655 :latex-fragment on a LaTeX fragment
14656 :latex-preview on a LaTeX fragment with overlayed preview image
14658 This function expects the position to be visible because it uses font-lock
14659 faces as a help to recognize the following contexts: :table-special, :link,
14660 and :keyword."
14661 (let* ((f (get-text-property (point) 'face))
14662 (faces (if (listp f) f (list f)))
14663 (p (point)) clist o)
14664 ;; First the large context
14665 (cond
14666 ((org-on-heading-p t)
14667 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14668 (when (progn
14669 (beginning-of-line 1)
14670 (looking-at org-todo-line-tags-regexp))
14671 (push (org-point-in-group p 1 :headline-stars) clist)
14672 (push (org-point-in-group p 2 :todo-keyword) clist)
14673 (push (org-point-in-group p 4 :tags) clist))
14674 (goto-char p)
14675 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14676 (if (looking-at "\\[#[A-Z0-9]\\]")
14677 (push (org-point-in-group p 0 :priority) clist)))
14679 ((org-at-item-p)
14680 (push (org-point-in-group p 2 :item-bullet) clist)
14681 (push (list :item (point-at-bol)
14682 (save-excursion (org-end-of-item) (point)))
14683 clist)
14684 (and (org-at-item-checkbox-p)
14685 (push (org-point-in-group p 0 :checkbox) clist)))
14687 ((org-at-table-p)
14688 (push (list :table (org-table-begin) (org-table-end)) clist)
14689 (if (memq 'org-formula faces)
14690 (push (list :table-special
14691 (previous-single-property-change p 'face)
14692 (next-single-property-change p 'face)) clist)))
14693 ((org-at-table-p 'any)
14694 (push (list :table-table) clist)))
14695 (goto-char p)
14697 ;; Now the small context
14698 (cond
14699 ((org-at-timestamp-p)
14700 (push (org-point-in-group p 0 :timestamp) clist))
14701 ((memq 'org-link faces)
14702 (push (list :link
14703 (previous-single-property-change p 'face)
14704 (next-single-property-change p 'face)) clist))
14705 ((memq 'org-special-keyword faces)
14706 (push (list :keyword
14707 (previous-single-property-change p 'face)
14708 (next-single-property-change p 'face)) clist))
14709 ((org-on-target-p)
14710 (push (org-point-in-group p 0 :target) clist)
14711 (goto-char (1- (match-beginning 0)))
14712 (if (looking-at org-radio-target-regexp)
14713 (push (org-point-in-group p 0 :radio-target) clist))
14714 (goto-char p))
14715 ((setq o (car (delq nil
14716 (mapcar
14717 (lambda (x)
14718 (if (memq x org-latex-fragment-image-overlays) x))
14719 (org-overlays-at (point))))))
14720 (push (list :latex-fragment
14721 (org-overlay-start o) (org-overlay-end o)) clist)
14722 (push (list :latex-preview
14723 (org-overlay-start o) (org-overlay-end o)) clist))
14724 ((org-inside-LaTeX-fragment-p)
14725 ;; FIXME: positions wrong.
14726 (push (list :latex-fragment (point) (point)) clist)))
14728 (setq clist (nreverse (delq nil clist)))
14729 clist))
14731 ;; FIXME: Compare with at-regexp-p Do we need both?
14732 (defun org-in-regexp (re &optional nlines visually)
14733 "Check if point is inside a match of regexp.
14734 Normally only the current line is checked, but you can include NLINES extra
14735 lines both before and after point into the search.
14736 If VISUALLY is set, require that the cursor is not after the match but
14737 really on, so that the block visually is on the match."
14738 (catch 'exit
14739 (let ((pos (point))
14740 (eol (point-at-eol (+ 1 (or nlines 0))))
14741 (inc (if visually 1 0)))
14742 (save-excursion
14743 (beginning-of-line (- 1 (or nlines 0)))
14744 (while (re-search-forward re eol t)
14745 (if (and (<= (match-beginning 0) pos)
14746 (>= (+ inc (match-end 0)) pos))
14747 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14749 (defun org-at-regexp-p (regexp)
14750 "Is point inside a match of REGEXP in the current line?"
14751 (catch 'exit
14752 (save-excursion
14753 (let ((pos (point)) (end (point-at-eol)))
14754 (beginning-of-line 1)
14755 (while (re-search-forward regexp end t)
14756 (if (and (<= (match-beginning 0) pos)
14757 (>= (match-end 0) pos))
14758 (throw 'exit t)))
14759 nil))))
14761 (defun org-occur-in-agenda-files (regexp &optional nlines)
14762 "Call `multi-occur' with buffers for all agenda files."
14763 (interactive "sOrg-files matching: \np")
14764 (let* ((files (org-agenda-files))
14765 (tnames (mapcar 'file-truename files))
14766 (extra org-agenda-text-search-extra-files)
14768 (when (eq (car extra) 'agenda-archives)
14769 (setq extra (cdr extra))
14770 (setq files (org-add-archive-files files)))
14771 (while (setq f (pop extra))
14772 (unless (member (file-truename f) tnames)
14773 (add-to-list 'files f 'append)
14774 (add-to-list 'tnames (file-truename f) 'append)))
14775 (multi-occur
14776 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14777 regexp)))
14779 (if (boundp 'occur-mode-find-occurrence-hook)
14780 ;; Emacs 23
14781 (add-hook 'occur-mode-find-occurrence-hook
14782 (lambda ()
14783 (when (org-mode-p)
14784 (org-reveal))))
14785 ;; Emacs 22
14786 (defadvice occur-mode-goto-occurrence
14787 (after org-occur-reveal activate)
14788 (and (org-mode-p) (org-reveal)))
14789 (defadvice occur-mode-goto-occurrence-other-window
14790 (after org-occur-reveal activate)
14791 (and (org-mode-p) (org-reveal)))
14792 (defadvice occur-mode-display-occurrence
14793 (after org-occur-reveal activate)
14794 (when (org-mode-p)
14795 (let ((pos (occur-mode-find-occurrence)))
14796 (with-current-buffer (marker-buffer pos)
14797 (save-excursion
14798 (goto-char pos)
14799 (org-reveal)))))))
14801 (defun org-uniquify (list)
14802 "Remove duplicate elements from LIST."
14803 (let (res)
14804 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14805 res))
14807 (defun org-delete-all (elts list)
14808 "Remove all elements in ELTS from LIST."
14809 (while elts
14810 (setq list (delete (pop elts) list)))
14811 list)
14813 (defun org-back-over-empty-lines ()
14814 "Move backwards over whitespace, to the beginning of the first empty line.
14815 Returns the number of empty lines passed."
14816 (let ((pos (point)))
14817 (skip-chars-backward " \t\n\r")
14818 (beginning-of-line 2)
14819 (goto-char (min (point) pos))
14820 (count-lines (point) pos)))
14822 (defun org-skip-whitespace ()
14823 (skip-chars-forward " \t\n\r"))
14825 (defun org-point-in-group (point group &optional context)
14826 "Check if POINT is in match-group GROUP.
14827 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14828 match. If the match group does ot exist or point is not inside it,
14829 return nil."
14830 (and (match-beginning group)
14831 (>= point (match-beginning group))
14832 (<= point (match-end group))
14833 (if context
14834 (list context (match-beginning group) (match-end group))
14835 t)))
14837 (defun org-switch-to-buffer-other-window (&rest args)
14838 "Switch to buffer in a second window on the current frame.
14839 In particular, do not allow pop-up frames."
14840 (let (pop-up-frames special-display-buffer-names special-display-regexps
14841 special-display-function)
14842 (apply 'switch-to-buffer-other-window args)))
14844 (defun org-combine-plists (&rest plists)
14845 "Create a single property list from all plists in PLISTS.
14846 The process starts by copying the first list, and then setting properties
14847 from the other lists. Settings in the last list are the most significant
14848 ones and overrule settings in the other lists."
14849 (let ((rtn (copy-sequence (pop plists)))
14850 p v ls)
14851 (while plists
14852 (setq ls (pop plists))
14853 (while ls
14854 (setq p (pop ls) v (pop ls))
14855 (setq rtn (plist-put rtn p v))))
14856 rtn))
14858 (defun org-move-line-down (arg)
14859 "Move the current line down. With prefix argument, move it past ARG lines."
14860 (interactive "p")
14861 (let ((col (current-column))
14862 beg end pos)
14863 (beginning-of-line 1) (setq beg (point))
14864 (beginning-of-line 2) (setq end (point))
14865 (beginning-of-line (+ 1 arg))
14866 (setq pos (move-marker (make-marker) (point)))
14867 (insert (delete-and-extract-region beg end))
14868 (goto-char pos)
14869 (org-move-to-column col)))
14871 (defun org-move-line-up (arg)
14872 "Move the current line up. With prefix argument, move it past ARG lines."
14873 (interactive "p")
14874 (let ((col (current-column))
14875 beg end pos)
14876 (beginning-of-line 1) (setq beg (point))
14877 (beginning-of-line 2) (setq end (point))
14878 (beginning-of-line (- arg))
14879 (setq pos (move-marker (make-marker) (point)))
14880 (insert (delete-and-extract-region beg end))
14881 (goto-char pos)
14882 (org-move-to-column col)))
14884 (defun org-replace-escapes (string table)
14885 "Replace %-escapes in STRING with values in TABLE.
14886 TABLE is an association list with keys like \"%a\" and string values.
14887 The sequences in STRING may contain normal field width and padding information,
14888 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14889 so values can contain further %-escapes if they are define later in TABLE."
14890 (let ((case-fold-search nil)
14891 e re rpl)
14892 (while (setq e (pop table))
14893 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14894 (while (string-match re string)
14895 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14896 (cdr e)))
14897 (setq string (replace-match rpl t t string))))
14898 string))
14901 (defun org-sublist (list start end)
14902 "Return a section of LIST, from START to END.
14903 Counting starts at 1."
14904 (let (rtn (c start))
14905 (setq list (nthcdr (1- start) list))
14906 (while (and list (<= c end))
14907 (push (pop list) rtn)
14908 (setq c (1+ c)))
14909 (nreverse rtn)))
14911 (defun org-find-base-buffer-visiting (file)
14912 "Like `find-buffer-visiting' but alway return the base buffer and
14913 not an indirect buffer."
14914 (let ((buf (find-buffer-visiting file)))
14915 (if buf
14916 (or (buffer-base-buffer buf) buf)
14917 nil)))
14919 (defun org-image-file-name-regexp (&optional extensions)
14920 "Return regexp matching the file names of images.
14921 If EXTENSIONS is given, only match these."
14922 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14923 (image-file-name-regexp)
14924 (let ((image-file-name-extensions
14925 (or extensions
14926 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14927 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14928 (concat "\\."
14929 (regexp-opt (nconc (mapcar 'upcase
14930 image-file-name-extensions)
14931 image-file-name-extensions)
14933 "\\'"))))
14935 (defun org-file-image-p (file &optional extensions)
14936 "Return non-nil if FILE is an image."
14937 (save-match-data
14938 (string-match (org-image-file-name-regexp extensions) file)))
14940 (defun org-get-cursor-date ()
14941 "Return the date at cursor in as a time.
14942 This works in the calendar and in the agenda, anywhere else it just
14943 returns the current time."
14944 (let (date day defd)
14945 (cond
14946 ((eq major-mode 'calendar-mode)
14947 (setq date (calendar-cursor-to-date)
14948 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14949 ((eq major-mode 'org-agenda-mode)
14950 (setq day (get-text-property (point) 'day))
14951 (if day
14952 (setq date (calendar-gregorian-from-absolute day)
14953 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14954 (nth 2 date))))))
14955 (or defd (current-time))))
14957 (defvar org-agenda-action-marker (make-marker)
14958 "Marker pointing to the entry for the next agenda action.")
14960 (defun org-mark-entry-for-agenda-action ()
14961 "Mark the current entry as target of an agenda action.
14962 Agenda actions are actions executed from the agenda with the key `k',
14963 which make use of the date at the cursor."
14964 (interactive)
14965 (move-marker org-agenda-action-marker
14966 (save-excursion (org-back-to-heading t) (point))
14967 (current-buffer))
14968 (message
14969 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14971 ;;; Paragraph filling stuff.
14972 ;; We want this to be just right, so use the full arsenal.
14974 (defun org-indent-line-function ()
14975 "Indent line like previous, but further if previous was headline or item."
14976 (interactive)
14977 (let* ((pos (point))
14978 (itemp (org-at-item-p))
14979 (org-drawer-regexp (or org-drawer-regexp "\000"))
14980 column bpos bcol tpos tcol bullet btype bullet-type)
14981 ;; Find the previous relevant line
14982 (beginning-of-line 1)
14983 (cond
14984 ((looking-at "#") (setq column 0))
14985 ((looking-at "\\*+ ") (setq column 0))
14986 ((and (looking-at "[ \t]*:END:")
14987 (save-excursion (re-search-backward org-drawer-regexp nil t)))
14988 (save-excursion
14989 (goto-char (1- (match-beginning 1)))
14990 (setq column (current-column))))
14992 (beginning-of-line 0)
14993 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
14994 (not (looking-at "[ \t]*:END:"))
14995 (not (looking-at org-drawer-regexp)))
14996 (beginning-of-line 0))
14997 (cond
14998 ((looking-at "\\*+[ \t]+")
14999 (if (not org-adapt-indentation)
15000 (setq column 0)
15001 (goto-char (match-end 0))
15002 (setq column (current-column))))
15003 ((looking-at org-drawer-regexp)
15004 (goto-char (1- (match-beginning 1)))
15005 (setq column (current-column)))
15006 ((looking-at "\\([ \t]*\\):END:")
15007 (goto-char (match-end 1))
15008 (setq column (current-column)))
15009 ((org-in-item-p)
15010 (org-beginning-of-item)
15011 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15012 (setq bpos (match-beginning 1) tpos (match-end 0)
15013 bcol (progn (goto-char bpos) (current-column))
15014 tcol (progn (goto-char tpos) (current-column))
15015 bullet (match-string 1)
15016 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15017 (if (> tcol (+ bcol org-description-max-indent))
15018 (setq tcol (+ bcol 5)))
15019 (if (not itemp)
15020 (setq column tcol)
15021 (goto-char pos)
15022 (beginning-of-line 1)
15023 (if (looking-at "\\S-")
15024 (progn
15025 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15026 (setq bullet (match-string 1)
15027 btype (if (string-match "[0-9]" bullet) "n" bullet))
15028 (setq column (if (equal btype bullet-type) bcol tcol)))
15029 (setq column (org-get-indentation)))))
15030 (t (setq column (org-get-indentation))))))
15031 (goto-char pos)
15032 (if (<= (current-column) (current-indentation))
15033 (org-indent-line-to column)
15034 (save-excursion (org-indent-line-to column)))
15035 (setq column (current-column))
15036 (beginning-of-line 1)
15037 (if (looking-at
15038 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15039 (replace-match (concat "\\1" (format org-property-format
15040 (match-string 2) (match-string 3)))
15041 t nil))
15042 (org-move-to-column column)))
15044 (defun org-set-autofill-regexps ()
15045 (interactive)
15046 ;; In the paragraph separator we include headlines, because filling
15047 ;; text in a line directly attached to a headline would otherwise
15048 ;; fill the headline as well.
15049 (org-set-local 'comment-start-skip "^#+[ \t]*")
15050 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15051 ;; The paragraph starter includes hand-formatted lists.
15052 (org-set-local 'paragraph-start
15053 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15054 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15055 ;; But only if the user has not turned off tables or fixed-width regions
15056 (org-set-local
15057 'auto-fill-inhibit-regexp
15058 (concat "\\*+ \\|#\\+"
15059 "\\|[ \t]*" org-keyword-time-regexp
15060 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15061 (concat
15062 "\\|[ \t]*["
15063 (if org-enable-table-editor "|" "")
15064 (if org-enable-fixed-width-editor ":" "")
15065 "]"))))
15066 ;; We use our own fill-paragraph function, to make sure that tables
15067 ;; and fixed-width regions are not wrapped. That function will pass
15068 ;; through to `fill-paragraph' when appropriate.
15069 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15070 ; Adaptive filling: To get full control, first make sure that
15071 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15072 (org-set-local 'adaptive-fill-regexp "\000")
15073 (org-set-local 'adaptive-fill-function
15074 'org-adaptive-fill-function)
15075 (org-set-local
15076 'align-mode-rules-list
15077 '((org-in-buffer-settings
15078 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15079 (modes . '(org-mode))))))
15081 (defun org-fill-paragraph (&optional justify)
15082 "Re-align a table, pass through to fill-paragraph if no table."
15083 (let ((table-p (org-at-table-p))
15084 (table.el-p (org-at-table.el-p)))
15085 (cond ((and (equal (char-after (point-at-bol)) ?*)
15086 (save-excursion (goto-char (point-at-bol))
15087 (looking-at outline-regexp)))
15088 t) ; skip headlines
15089 (table.el-p t) ; skip table.el tables
15090 (table-p (org-table-align) t) ; align org-mode tables
15091 (t nil)))) ; call paragraph-fill
15093 ;; For reference, this is the default value of adaptive-fill-regexp
15094 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15096 (defun org-adaptive-fill-function ()
15097 "Return a fill prefix for org-mode files.
15098 In particular, this makes sure hanging paragraphs for hand-formatted lists
15099 work correctly."
15100 (cond ((looking-at "#[ \t]+")
15101 (match-string 0))
15102 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15103 (save-excursion
15104 (if (> (match-end 1) (+ (match-beginning 1)
15105 org-description-max-indent))
15106 (goto-char (+ (match-beginning 1) 5))
15107 (goto-char (match-end 0)))
15108 (make-string (current-column) ?\ )))
15109 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15110 (save-excursion
15111 (goto-char (match-end 0))
15112 (make-string (current-column) ?\ )))
15113 (t nil)))
15115 ;;; Other stuff.
15117 (defun org-toggle-fixed-width-section (arg)
15118 "Toggle the fixed-width export.
15119 If there is no active region, the QUOTE keyword at the current headline is
15120 inserted or removed. When present, it causes the text between this headline
15121 and the next to be exported as fixed-width text, and unmodified.
15122 If there is an active region, this command adds or removes a colon as the
15123 first character of this line. If the first character of a line is a colon,
15124 this line is also exported in fixed-width font."
15125 (interactive "P")
15126 (let* ((cc 0)
15127 (regionp (org-region-active-p))
15128 (beg (if regionp (region-beginning) (point)))
15129 (end (if regionp (region-end)))
15130 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15131 (case-fold-search nil)
15132 (re "[ \t]*\\(:\\)")
15133 off)
15134 (if regionp
15135 (save-excursion
15136 (goto-char beg)
15137 (setq cc (current-column))
15138 (beginning-of-line 1)
15139 (setq off (looking-at re))
15140 (while (> nlines 0)
15141 (setq nlines (1- nlines))
15142 (beginning-of-line 1)
15143 (cond
15144 (arg
15145 (org-move-to-column cc t)
15146 (insert ":\n")
15147 (forward-line -1))
15148 ((and off (looking-at re))
15149 (replace-match "" t t nil 1))
15150 ((not off) (org-move-to-column cc t) (insert ":")))
15151 (forward-line 1)))
15152 (save-excursion
15153 (org-back-to-heading)
15154 (if (looking-at (concat outline-regexp
15155 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15156 (replace-match "" t t nil 1)
15157 (if (looking-at outline-regexp)
15158 (progn
15159 (goto-char (match-end 0))
15160 (insert org-quote-string " "))))))))
15162 ;;;; Functions extending outline functionality
15164 (defun org-beginning-of-line (&optional arg)
15165 "Go to the beginning of the current line. If that is invisible, continue
15166 to a visible line beginning. This makes the function of C-a more intuitive.
15167 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15168 first attempt, and only move to after the tags when the cursor is already
15169 beyond the end of the headline."
15170 (interactive "P")
15171 (let ((pos (point))
15172 (special (if (consp org-special-ctrl-a/e)
15173 (car org-special-ctrl-a/e)
15174 org-special-ctrl-a/e))
15175 refpos)
15176 (beginning-of-line 1)
15177 (if (and arg (fboundp 'move-beginning-of-line))
15178 (call-interactively 'move-beginning-of-line)
15179 (if (bobp)
15181 (backward-char 1)
15182 (if (org-invisible-p)
15183 (while (and (not (bobp)) (org-invisible-p))
15184 (backward-char 1)
15185 (beginning-of-line 1))
15186 (forward-char 1))))
15187 (when special
15188 (cond
15189 ((and (looking-at org-complex-heading-regexp)
15190 (= (char-after (match-end 1)) ?\ ))
15191 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15192 (point-at-eol)))
15193 (goto-char
15194 (if (eq special t)
15195 (cond ((> pos refpos) refpos)
15196 ((= pos (point)) refpos)
15197 (t (point)))
15198 (cond ((> pos (point)) (point))
15199 ((not (eq last-command this-command)) (point))
15200 (t refpos)))))
15201 ((org-at-item-p)
15202 (goto-char
15203 (if (eq special t)
15204 (cond ((> pos (match-end 4)) (match-end 4))
15205 ((= pos (point)) (match-end 4))
15206 (t (point)))
15207 (cond ((> pos (point)) (point))
15208 ((not (eq last-command this-command)) (point))
15209 (t (match-end 4))))))))
15210 (org-no-warnings
15211 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15213 (defun org-end-of-line (&optional arg)
15214 "Go to the end of the line.
15215 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15216 first attempt, and only move to after the tags when the cursor is already
15217 beyond the end of the headline."
15218 (interactive "P")
15219 (let ((special (if (consp org-special-ctrl-a/e)
15220 (cdr org-special-ctrl-a/e)
15221 org-special-ctrl-a/e)))
15222 (if (or (not special)
15223 (not (org-on-heading-p))
15224 arg)
15225 (call-interactively (if (fboundp 'move-end-of-line)
15226 'move-end-of-line
15227 'end-of-line))
15228 (let ((pos (point)))
15229 (beginning-of-line 1)
15230 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15231 (if (eq special t)
15232 (if (or (< pos (match-beginning 1))
15233 (= pos (match-end 0)))
15234 (goto-char (match-beginning 1))
15235 (goto-char (match-end 0)))
15236 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15237 (goto-char (match-end 0))
15238 (goto-char (match-beginning 1))))
15239 (call-interactively (if (fboundp 'move-end-of-line)
15240 'move-end-of-line
15241 'end-of-line)))))
15242 (org-no-warnings
15243 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15245 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15246 (define-key org-mode-map "\C-e" 'org-end-of-line)
15248 (defun org-kill-line (&optional arg)
15249 "Kill line, to tags or end of line."
15250 (interactive "P")
15251 (cond
15252 ((or (not org-special-ctrl-k)
15253 (bolp)
15254 (not (org-on-heading-p)))
15255 (call-interactively 'kill-line))
15256 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15257 (kill-region (point) (match-beginning 1))
15258 (org-set-tags nil t))
15259 (t (kill-region (point) (point-at-eol)))))
15261 (define-key org-mode-map "\C-k" 'org-kill-line)
15263 (defun org-yank (&optional arg)
15264 "Yank. If the kill is a subtree, treat it specially.
15265 This command will look at the current kill and check if is a single
15266 subtree, or a series of subtrees[1]. If it passes the test, and if the
15267 cursor is at the beginning of a line or after the stars of a currently
15268 empty headline, then the yank is handled specially. How exactly depends
15269 on the value of the following variables, both set by default.
15271 org-yank-folded-subtrees
15272 When set, the subtree(s) will be folded after insertion, but only
15273 if doing so would now swallow text after the yanked text.
15275 org-yank-adjusted-subtrees
15276 When set, the subtree will be promoted or demoted in order to
15277 fit into the local outline tree structure, which means that the level
15278 will be adjusted so that it becomes the smaller one of the two
15279 *visible* surrounding headings.
15281 Any prefix to this command will cause `yank' to be called directly with
15282 no special treatment. In particular, a simple `C-u' prefix will just
15283 plainly yank the text as it is.
15285 \[1] Basically, the test checks if the first non-white line is a heading
15286 and if there are no other headings with fewer stars."
15287 (interactive "P")
15288 (setq this-command 'yank)
15289 (if arg
15290 (call-interactively 'yank)
15291 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15292 (and (org-kill-is-subtree-p)
15293 (or (bolp)
15294 (and (looking-at "[ \t]*$")
15295 (string-match
15296 "\\`\\*+\\'"
15297 (buffer-substring (point-at-bol) (point)))))))
15298 swallowp)
15299 (cond
15300 ((and subtreep org-yank-folded-subtrees)
15301 (let ((beg (point))
15302 end)
15303 (if (and subtreep org-yank-adjusted-subtrees)
15304 (org-paste-subtree nil nil 'for-yank)
15305 (call-interactively 'yank))
15306 (setq end (point))
15307 (goto-char beg)
15308 (when (and (bolp) subtreep
15309 (not (setq swallowp
15310 (org-yank-folding-would-swallow-text beg end))))
15311 (or (looking-at outline-regexp)
15312 (re-search-forward (concat "^" outline-regexp) end t))
15313 (while (and (< (point) end) (looking-at outline-regexp))
15314 (hide-subtree)
15315 (org-cycle-show-empty-lines 'folded)
15316 (condition-case nil
15317 (outline-forward-same-level 1)
15318 (error (goto-char end)))))
15319 (when swallowp
15320 (message
15321 "Yanked text not folded because that would swallow text"))
15322 (goto-char end)
15323 (skip-chars-forward " \t\n\r")
15324 (beginning-of-line 1)
15325 (push-mark beg 'nomsg)))
15326 ((and subtreep org-yank-adjusted-subtrees)
15327 (let ((beg (point-at-bol)))
15328 (org-paste-subtree nil nil 'for-yank)
15329 (push-mark beg 'nomsg)))
15331 (call-interactively 'yank))))))
15333 (defun org-yank-folding-would-swallow-text (beg end)
15334 "Would hide-subtree at BEG swallow any text after END?"
15335 (let (level)
15336 (save-excursion
15337 (goto-char beg)
15338 (when (or (looking-at outline-regexp)
15339 (re-search-forward (concat "^" outline-regexp) end t))
15340 (setq level (org-outline-level)))
15341 (goto-char end)
15342 (skip-chars-forward " \t\r\n\v\f")
15343 (if (or (eobp)
15344 (and (bolp) (looking-at org-outline-regexp)
15345 (<= (org-outline-level) level)))
15346 nil ; Nothing would be swallowed
15347 t)))) ; something would swallow
15349 (define-key org-mode-map "\C-y" 'org-yank)
15351 (defun org-invisible-p ()
15352 "Check if point is at a character currently not visible."
15353 ;; Early versions of noutline don't have `outline-invisible-p'.
15354 (if (fboundp 'outline-invisible-p)
15355 (outline-invisible-p)
15356 (get-char-property (point) 'invisible)))
15358 (defun org-invisible-p2 ()
15359 "Check if point is at a character currently not visible."
15360 (save-excursion
15361 (if (and (eolp) (not (bobp))) (backward-char 1))
15362 ;; Early versions of noutline don't have `outline-invisible-p'.
15363 (if (fboundp 'outline-invisible-p)
15364 (outline-invisible-p)
15365 (get-char-property (point) 'invisible))))
15367 (defun org-back-to-heading (&optional invisible-ok)
15368 "Call `outline-back-to-heading', but provide a better error message."
15369 (condition-case nil
15370 (outline-back-to-heading invisible-ok)
15371 (error (error "Before first headline at position %d in buffer %s"
15372 (point) (current-buffer)))))
15374 (defun org-before-first-heading-p ()
15375 "Before first heading?"
15376 (save-excursion
15377 (null (re-search-backward "^\\*+ " nil t))))
15379 (defalias 'org-on-heading-p 'outline-on-heading-p)
15380 (defalias 'org-at-heading-p 'outline-on-heading-p)
15381 (defun org-at-heading-or-item-p ()
15382 (or (org-on-heading-p) (org-at-item-p)))
15384 (defun org-on-target-p ()
15385 (or (org-in-regexp org-radio-target-regexp)
15386 (org-in-regexp org-target-regexp)))
15388 (defun org-up-heading-all (arg)
15389 "Move to the heading line of which the present line is a subheading.
15390 This function considers both visible and invisible heading lines.
15391 With argument, move up ARG levels."
15392 (if (fboundp 'outline-up-heading-all)
15393 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15394 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15396 (defun org-up-heading-safe ()
15397 "Move to the heading line of which the present line is a subheading.
15398 This version will not throw an error. It will return the level of the
15399 headline found, or nil if no higher level is found."
15400 (let (start-level re)
15401 (org-back-to-heading t)
15402 (setq start-level (funcall outline-level))
15403 (if (equal start-level 1)
15405 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15406 (if (re-search-backward re nil t)
15407 (funcall outline-level)))))
15409 (defun org-first-sibling-p ()
15410 "Is this heading the first child of its parents?"
15411 (interactive)
15412 (let ((re (concat "^" outline-regexp))
15413 level l)
15414 (unless (org-at-heading-p t)
15415 (error "Not at a heading"))
15416 (setq level (funcall outline-level))
15417 (save-excursion
15418 (if (not (re-search-backward re nil t))
15420 (setq l (funcall outline-level))
15421 (< l level)))))
15423 (defun org-goto-sibling (&optional previous)
15424 "Goto the next sibling, even if it is invisible.
15425 When PREVIOUS is set, go to the previous sibling instead. Returns t
15426 when a sibling was found. When none is found, return nil and don't
15427 move point."
15428 (let ((fun (if previous 're-search-backward 're-search-forward))
15429 (pos (point))
15430 (re (concat "^" outline-regexp))
15431 level l)
15432 (when (condition-case nil (org-back-to-heading t) (error nil))
15433 (setq level (funcall outline-level))
15434 (catch 'exit
15435 (or previous (forward-char 1))
15436 (while (funcall fun re nil t)
15437 (setq l (funcall outline-level))
15438 (when (< l level) (goto-char pos) (throw 'exit nil))
15439 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15440 (goto-char pos)
15441 nil))))
15443 (defun org-show-siblings ()
15444 "Show all siblings of the current headline."
15445 (save-excursion
15446 (while (org-goto-sibling) (org-flag-heading nil)))
15447 (save-excursion
15448 (while (org-goto-sibling 'previous)
15449 (org-flag-heading nil))))
15451 (defun org-show-hidden-entry ()
15452 "Show an entry where even the heading is hidden."
15453 (save-excursion
15454 (org-show-entry)))
15456 (defun org-flag-heading (flag &optional entry)
15457 "Flag the current heading. FLAG non-nil means make invisible.
15458 When ENTRY is non-nil, show the entire entry."
15459 (save-excursion
15460 (org-back-to-heading t)
15461 ;; Check if we should show the entire entry
15462 (if entry
15463 (progn
15464 (org-show-entry)
15465 (save-excursion
15466 (and (outline-next-heading)
15467 (org-flag-heading nil))))
15468 (outline-flag-region (max (point-min) (1- (point)))
15469 (save-excursion (outline-end-of-heading) (point))
15470 flag))))
15472 (defun org-forward-same-level (arg)
15473 "Move forward to the ARG'th subheading at same level as this one.
15474 Stop at the first and last subheadings of a superior heading.
15475 This is like outline-forward-same-level, but invisible headings are ok."
15476 (interactive "p")
15477 (org-back-to-heading t)
15478 (while (> arg 0)
15479 (let ((point-to-move-to (save-excursion
15480 (org-get-next-sibling))))
15481 (if point-to-move-to
15482 (progn
15483 (goto-char point-to-move-to)
15484 (setq arg (1- arg)))
15485 (progn
15486 (setq arg 0)
15487 (error "No following same-level heading"))))))
15489 (defun org-get-next-sibling ()
15490 "Move to next heading of the same level, and return point.
15491 If there is no such heading, return nil.
15492 This is like outline-next-sibling, but invisible headings are ok."
15493 (let ((level (funcall outline-level)))
15494 (outline-next-heading)
15495 (while (and (not (eobp)) (> (funcall outline-level) level))
15496 (outline-next-heading))
15497 (if (or (eobp) (< (funcall outline-level) level))
15499 (point))))
15501 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15502 ;; This is an exact copy of the original function, but it uses
15503 ;; `org-back-to-heading', to make it work also in invisible
15504 ;; trees. And is uses an invisible-OK argument.
15505 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15506 (org-back-to-heading invisible-OK)
15507 (let ((first t)
15508 (level (funcall outline-level)))
15509 (while (and (not (eobp))
15510 (or first (> (funcall outline-level) level)))
15511 (setq first nil)
15512 (outline-next-heading))
15513 (unless to-heading
15514 (if (memq (preceding-char) '(?\n ?\^M))
15515 (progn
15516 ;; Go to end of line before heading
15517 (forward-char -1)
15518 (if (memq (preceding-char) '(?\n ?\^M))
15519 ;; leave blank line before heading
15520 (forward-char -1))))))
15521 (point))
15523 (defun org-show-subtree ()
15524 "Show everything after this heading at deeper levels."
15525 (outline-flag-region
15526 (point)
15527 (save-excursion
15528 (outline-end-of-subtree) (outline-next-heading) (point))
15529 nil))
15531 (defun org-show-entry ()
15532 "Show the body directly following this heading.
15533 Show the heading too, if it is currently invisible."
15534 (interactive)
15535 (save-excursion
15536 (condition-case nil
15537 (progn
15538 (org-back-to-heading t)
15539 (outline-flag-region
15540 (max (point-min) (1- (point)))
15541 (save-excursion
15542 (if (re-search-forward
15543 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15544 (match-beginning 1)
15545 (point-max)))
15546 nil))
15547 (error nil))))
15549 (defun org-make-options-regexp (kwds &optional extra)
15550 "Make a regular expression for keyword lines."
15551 (concat
15553 "#?[ \t]*\\+\\("
15554 (mapconcat 'regexp-quote kwds "\\|")
15555 (if extra (concat "\\|" extra))
15556 "\\):[ \t]*"
15557 "\\(.+\\)"))
15559 ;; Make isearch reveal the necessary context
15560 (defun org-isearch-end ()
15561 "Reveal context after isearch exits."
15562 (when isearch-success ; only if search was successful
15563 (if (featurep 'xemacs)
15564 ;; Under XEmacs, the hook is run in the correct place,
15565 ;; we directly show the context.
15566 (org-show-context 'isearch)
15567 ;; In Emacs the hook runs *before* restoring the overlays.
15568 ;; So we have to use a one-time post-command-hook to do this.
15569 ;; (Emacs 22 has a special variable, see function `org-mode')
15570 (unless (and (boundp 'isearch-mode-end-hook-quit)
15571 isearch-mode-end-hook-quit)
15572 ;; Only when the isearch was not quitted.
15573 (org-add-hook 'post-command-hook 'org-isearch-post-command
15574 'append 'local)))))
15576 (defun org-isearch-post-command ()
15577 "Remove self from hook, and show context."
15578 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15579 (org-show-context 'isearch))
15582 ;;;; Integration with and fixes for other packages
15584 ;;; Imenu support
15586 (defvar org-imenu-markers nil
15587 "All markers currently used by Imenu.")
15588 (make-variable-buffer-local 'org-imenu-markers)
15590 (defun org-imenu-new-marker (&optional pos)
15591 "Return a new marker for use by Imenu, and remember the marker."
15592 (let ((m (make-marker)))
15593 (move-marker m (or pos (point)))
15594 (push m org-imenu-markers)
15597 (defun org-imenu-get-tree ()
15598 "Produce the index for Imenu."
15599 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15600 (setq org-imenu-markers nil)
15601 (let* ((n org-imenu-depth)
15602 (re (concat "^" outline-regexp))
15603 (subs (make-vector (1+ n) nil))
15604 (last-level 0)
15605 m level head)
15606 (save-excursion
15607 (save-restriction
15608 (widen)
15609 (goto-char (point-max))
15610 (while (re-search-backward re nil t)
15611 (setq level (org-reduced-level (funcall outline-level)))
15612 (when (<= level n)
15613 (looking-at org-complex-heading-regexp)
15614 (setq head (org-link-display-format
15615 (org-match-string-no-properties 4))
15616 m (org-imenu-new-marker))
15617 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15618 (if (>= level last-level)
15619 (push (cons head m) (aref subs level))
15620 (push (cons head (aref subs (1+ level))) (aref subs level))
15621 (loop for i from (1+ level) to n do (aset subs i nil)))
15622 (setq last-level level)))))
15623 (aref subs 1)))
15625 (eval-after-load "imenu"
15626 '(progn
15627 (add-hook 'imenu-after-jump-hook
15628 (lambda ()
15629 (if (eq major-mode 'org-mode)
15630 (org-show-context 'org-goto))))))
15632 (defun org-link-display-format (link)
15633 "Replace a link with either the description, or the link target
15634 if no description is present"
15635 (save-match-data
15636 (if (string-match org-bracket-link-analytic-regexp link)
15637 (replace-match (or (match-string 5 link)
15638 (concat (match-string 1 link)
15639 (match-string 3 link)))
15640 nil nil link)
15641 link)))
15643 ;; Speedbar support
15645 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15646 "Overlay marking the agenda restriction line in speedbar.")
15647 (org-overlay-put org-speedbar-restriction-lock-overlay
15648 'face 'org-agenda-restriction-lock)
15649 (org-overlay-put org-speedbar-restriction-lock-overlay
15650 'help-echo "Agendas are currently limited to this item.")
15651 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15653 (defun org-speedbar-set-agenda-restriction ()
15654 "Restrict future agenda commands to the location at point in speedbar.
15655 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15656 (interactive)
15657 (require 'org-agenda)
15658 (let (p m tp np dir txt)
15659 (cond
15660 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15661 'org-imenu t))
15662 (setq m (get-text-property p 'org-imenu-marker))
15663 (save-excursion
15664 (save-restriction
15665 (set-buffer (marker-buffer m))
15666 (goto-char m)
15667 (org-agenda-set-restriction-lock 'subtree))))
15668 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15669 'speedbar-function 'speedbar-find-file))
15670 (setq tp (previous-single-property-change
15671 (1+ p) 'speedbar-function)
15672 np (next-single-property-change
15673 tp 'speedbar-function)
15674 dir (speedbar-line-directory)
15675 txt (buffer-substring-no-properties (or tp (point-min))
15676 (or np (point-max))))
15677 (save-excursion
15678 (save-restriction
15679 (set-buffer (find-file-noselect
15680 (let ((default-directory dir))
15681 (expand-file-name txt))))
15682 (unless (org-mode-p)
15683 (error "Cannot restrict to non-Org-mode file"))
15684 (org-agenda-set-restriction-lock 'file))))
15685 (t (error "Don't know how to restrict Org-mode's agenda")))
15686 (org-move-overlay org-speedbar-restriction-lock-overlay
15687 (point-at-bol) (point-at-eol))
15688 (setq current-prefix-arg nil)
15689 (org-agenda-maybe-redo)))
15691 (eval-after-load "speedbar"
15692 '(progn
15693 (speedbar-add-supported-extension ".org")
15694 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15695 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15696 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15697 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15698 (add-hook 'speedbar-visiting-tag-hook
15699 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15702 ;;; Fixes and Hacks for problems with other packages
15704 ;; Make flyspell not check words in links, to not mess up our keymap
15705 (defun org-mode-flyspell-verify ()
15706 "Don't let flyspell put overlays at active buttons."
15707 (not (get-text-property (point) 'keymap)))
15709 ;; Make `bookmark-jump' show the jump location if it was hidden.
15710 (eval-after-load "bookmark"
15711 '(if (boundp 'bookmark-after-jump-hook)
15712 ;; We can use the hook
15713 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15714 ;; Hook not available, use advice
15715 (defadvice bookmark-jump (after org-make-visible activate)
15716 "Make the position visible."
15717 (org-bookmark-jump-unhide))))
15719 ;; Make sure saveplace show the location if it was hidden
15720 (eval-after-load "saveplace"
15721 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15722 "Make the position visible."
15723 (org-bookmark-jump-unhide)))
15725 (defun org-bookmark-jump-unhide ()
15726 "Unhide the current position, to show the bookmark location."
15727 (and (org-mode-p)
15728 (or (org-invisible-p)
15729 (save-excursion (goto-char (max (point-min) (1- (point))))
15730 (org-invisible-p)))
15731 (org-show-context 'bookmark-jump)))
15733 ;; Make session.el ignore our circular variable
15734 (eval-after-load "session"
15735 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15737 ;;;; Experimental code
15739 (defun org-closed-in-range ()
15740 "Sparse tree of items closed in a certain time range.
15741 Still experimental, may disappear in the future."
15742 (interactive)
15743 ;; Get the time interval from the user.
15744 (let* ((time1 (time-to-seconds
15745 (org-read-date nil 'to-time nil "Starting date: ")))
15746 (time2 (time-to-seconds
15747 (org-read-date nil 'to-time nil "End date:")))
15748 ;; callback function
15749 (callback (lambda ()
15750 (let ((time
15751 (time-to-seconds
15752 (apply 'encode-time
15753 (org-parse-time-string
15754 (match-string 1))))))
15755 ;; check if time in interval
15756 (and (>= time time1) (<= time time2))))))
15757 ;; make tree, check each match with the callback
15758 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15761 ;;;; Finish up
15763 (provide 'org)
15765 (run-hooks 'org-load-hook)
15767 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15769 ;;; org.el ends here