Fix bug in `org-toggle-fixed-width-section'.
[org-mode.git] / lisp / org.el
blob75e42a912358c1a80649940a2d764e326c4b4a6e
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.24trans
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.24trans"
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 collector: Collect properties into tables" org-collector)
186 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
187 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
188 (const :tag "C eval: Include command output as text" org-eval)
189 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
190 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
191 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
192 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
193 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
194 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
195 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
196 (const :tag "C mtags: Support for muse-like tags" org-mtags)
197 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
198 (const :tag "C R: Computation using the R language" org-R)
199 (const :tag "C registry: A registry for Org links" org-registry)
200 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
201 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
202 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
203 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
204 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
206 (defcustom org-support-shift-select nil
207 "Non-nil means, make shift-cursor commands select text when possible.
209 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
210 selecting a region, or enlarge thusly regions started in this way.
211 In Org-mode, in special contexts, these same keys are used for other
212 purposes, important enough to compete with shift selection. Org tries
213 to balance these needs by supporting `shift-select-mode' outside these
214 special contexts, under control of this variable.
216 The default of this variable is nil, to avoid confusing behavior. Shifted
217 cursor keys will then execute Org commands in the following contexts:
218 - on a headline, changing TODO state (left/right) and priority (up/down)
219 - on a time stamp, changing the time
220 - in a plain list item, changing the bullet type
221 - in a property definition line, switching between allowed values
222 - in the BEGIN line of a clock table (changing the time block).
223 Outside these contexts, the commands will throw an error.
225 When this variable is t and the cursor is not in a special context,
226 Org-mode will support shift-selection for making and enlarging regions.
227 To make this more effective, the bullet cycling will no longer happen
228 anywhere in an item line, but only if the cursor is exactly on the bullet.
230 If you set this variable to the symbol `always', then the keys
231 will not be special in headlines, property lines, and item lines, to make
232 shift selection work there as well. If this is what you want, you can
233 use the following alternative commands: `C-c C-t' and `C-c ,' to
234 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
235 TODO sets, `C-c -' to cycle item bullet types, and properties can be
236 edited by hand or in column view.
238 However, when the cursor is on a timestamp, shift-cursor commands
239 will still edit the time stamp - this is just too good to give up.
241 XEmacs user should have this variable set to nil, because shift-select-mode
242 is Emacs 23 only."
243 :group 'org
244 :type '(choice
245 (const :tag "Never" nil)
246 (const :tag "When outside special context" t)
247 (const :tag "Everywhere except timestamps" always)))
249 (defgroup org-startup nil
250 "Options concerning startup of Org-mode."
251 :tag "Org Startup"
252 :group 'org)
254 (defcustom org-startup-folded t
255 "Non-nil means, entering Org-mode will switch to OVERVIEW.
256 This can also be configured on a per-file basis by adding one of
257 the following lines anywhere in the buffer:
259 #+STARTUP: fold
260 #+STARTUP: nofold
261 #+STARTUP: content"
262 :group 'org-startup
263 :type '(choice
264 (const :tag "nofold: show all" nil)
265 (const :tag "fold: overview" t)
266 (const :tag "content: all headlines" content)))
268 (defcustom org-startup-truncated t
269 "Non-nil means, entering Org-mode will set `truncate-lines'.
270 This is useful since some lines containing links can be very long and
271 uninteresting. Also tables look terrible when wrapped."
272 :group 'org-startup
273 :type 'boolean)
275 (defcustom org-startup-align-all-tables nil
276 "Non-nil means, align all tables when visiting a file.
277 This is useful when the column width in tables is forced with <N> cookies
278 in table fields. Such tables will look correct only after the first re-align.
279 This can also be configured on a per-file basis by adding one of
280 the following lines anywhere in the buffer:
281 #+STARTUP: align
282 #+STARTUP: noalign"
283 :group 'org-startup
284 :type 'boolean)
286 (defcustom org-insert-mode-line-in-empty-file nil
287 "Non-nil means insert the first line setting Org-mode in empty files.
288 When the function `org-mode' is called interactively in an empty file, this
289 normally means that the file name does not automatically trigger Org-mode.
290 To ensure that the file will always be in Org-mode in the future, a
291 line enforcing Org-mode will be inserted into the buffer, if this option
292 has been set."
293 :group 'org-startup
294 :type 'boolean)
296 (defcustom org-replace-disputed-keys nil
297 "Non-nil means use alternative key bindings for some keys.
298 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
299 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
300 If you want to use Org-mode together with one of these other modes,
301 or more generally if you would like to move some Org-mode commands to
302 other keys, set this variable and configure the keys with the variable
303 `org-disputed-keys'.
305 This option is only relevant at load-time of Org-mode, and must be set
306 *before* org.el is loaded. Changing it requires a restart of Emacs to
307 become effective."
308 :group 'org-startup
309 :type 'boolean)
311 (defcustom org-use-extra-keys nil
312 "Non-nil means use extra key sequence definitions for certain
313 commands. This happens automatically if you run XEmacs or if
314 window-system is nil. This variable lets you do the same
315 manually. You must set it before loading org.
317 Example: on Carbon Emacs 22 running graphically, with an external
318 keyboard on a Powerbook, the default way of setting M-left might
319 not work for either Alt or ESC. Setting this variable will make
320 it work for ESC."
321 :group 'org-startup
322 :type 'boolean)
324 (if (fboundp 'defvaralias)
325 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
327 (defcustom org-disputed-keys
328 '(([(shift up)] . [(meta p)])
329 ([(shift down)] . [(meta n)])
330 ([(shift left)] . [(meta -)])
331 ([(shift right)] . [(meta +)])
332 ([(control shift right)] . [(meta shift +)])
333 ([(control shift left)] . [(meta shift -)]))
334 "Keys for which Org-mode and other modes compete.
335 This is an alist, cars are the default keys, second element specifies
336 the alternative to use when `org-replace-disputed-keys' is t.
338 Keys can be specified in any syntax supported by `define-key'.
339 The value of this option takes effect only at Org-mode's startup,
340 therefore you'll have to restart Emacs to apply it after changing."
341 :group 'org-startup
342 :type 'alist)
344 (defun org-key (key)
345 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
346 Or return the original if not disputed."
347 (if org-replace-disputed-keys
348 (let* ((nkey (key-description key))
349 (x (org-find-if (lambda (x)
350 (equal (key-description (car x)) nkey))
351 org-disputed-keys)))
352 (if x (cdr x) key))
353 key))
355 (defun org-find-if (predicate seq)
356 (catch 'exit
357 (while seq
358 (if (funcall predicate (car seq))
359 (throw 'exit (car seq))
360 (pop seq)))))
362 (defun org-defkey (keymap key def)
363 "Define a key, possibly translated, as returned by `org-key'."
364 (define-key keymap (org-key key) def))
366 (defcustom org-ellipsis nil
367 "The ellipsis to use in the Org-mode outline.
368 When nil, just use the standard three dots. When a string, use that instead,
369 When a face, use the standard 3 dots, but with the specified face.
370 The change affects only Org-mode (which will then use its own display table).
371 Changing this requires executing `M-x org-mode' in a buffer to become
372 effective."
373 :group 'org-startup
374 :type '(choice (const :tag "Default" nil)
375 (face :tag "Face" :value org-warning)
376 (string :tag "String" :value "...#")))
378 (defvar org-display-table nil
379 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
381 (defgroup org-keywords nil
382 "Keywords in Org-mode."
383 :tag "Org Keywords"
384 :group 'org)
386 (defcustom org-deadline-string "DEADLINE:"
387 "String to mark deadline entries.
388 A deadline is this string, followed by a time stamp. Should be a word,
389 terminated by a colon. You can insert a schedule keyword and
390 a timestamp with \\[org-deadline].
391 Changes become only effective after restarting Emacs."
392 :group 'org-keywords
393 :type 'string)
395 (defcustom org-scheduled-string "SCHEDULED:"
396 "String to mark scheduled TODO entries.
397 A schedule is this string, followed by a time stamp. Should be a word,
398 terminated by a colon. You can insert a schedule keyword and
399 a timestamp with \\[org-schedule].
400 Changes become only effective after restarting Emacs."
401 :group 'org-keywords
402 :type 'string)
404 (defcustom org-closed-string "CLOSED:"
405 "String used as the prefix for timestamps logging closing a TODO entry."
406 :group 'org-keywords
407 :type 'string)
409 (defcustom org-clock-string "CLOCK:"
410 "String used as prefix for timestamps clocking work hours on an item."
411 :group 'org-keywords
412 :type 'string)
414 (defcustom org-comment-string "COMMENT"
415 "Entries starting with this keyword will never be exported.
416 An entry can be toggled between COMMENT and normal with
417 \\[org-toggle-comment].
418 Changes become only effective after restarting Emacs."
419 :group 'org-keywords
420 :type 'string)
422 (defcustom org-quote-string "QUOTE"
423 "Entries starting with this keyword will be exported in fixed-width font.
424 Quoting applies only to the text in the entry following the headline, and does
425 not extend beyond the next headline, even if that is lower level.
426 An entry can be toggled between QUOTE and normal with
427 \\[org-toggle-fixed-width-section]."
428 :group 'org-keywords
429 :type 'string)
431 (defconst org-repeat-re
432 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
433 "Regular expression for specifying repeated events.
434 After a match, group 1 contains the repeat expression.")
436 (defgroup org-structure nil
437 "Options concerning the general structure of Org-mode files."
438 :tag "Org Structure"
439 :group 'org)
441 (defgroup org-reveal-location nil
442 "Options about how to make context of a location visible."
443 :tag "Org Reveal Location"
444 :group 'org-structure)
446 (defconst org-context-choice
447 '(choice
448 (const :tag "Always" t)
449 (const :tag "Never" nil)
450 (repeat :greedy t :tag "Individual contexts"
451 (cons
452 (choice :tag "Context"
453 (const agenda)
454 (const org-goto)
455 (const occur-tree)
456 (const tags-tree)
457 (const link-search)
458 (const mark-goto)
459 (const bookmark-jump)
460 (const isearch)
461 (const default))
462 (boolean))))
463 "Contexts for the reveal options.")
465 (defcustom org-show-hierarchy-above '((default . t))
466 "Non-nil means, show full hierarchy when revealing a location.
467 Org-mode often shows locations in an org-mode file which might have
468 been invisible before. When this is set, the hierarchy of headings
469 above the exposed location is shown.
470 Turning this off for example for sparse trees makes them very compact.
471 Instead of t, this can also be an alist specifying this option for different
472 contexts. Valid contexts are
473 agenda when exposing an entry from the agenda
474 org-goto when using the command `org-goto' on key C-c C-j
475 occur-tree when using the command `org-occur' on key C-c /
476 tags-tree when constructing a sparse tree based on tags matches
477 link-search when exposing search matches associated with a link
478 mark-goto when exposing the jump goal of a mark
479 bookmark-jump when exposing a bookmark location
480 isearch when exiting from an incremental search
481 default default for all contexts not set explicitly"
482 :group 'org-reveal-location
483 :type org-context-choice)
485 (defcustom org-show-following-heading '((default . nil))
486 "Non-nil means, show following heading when revealing a location.
487 Org-mode often shows locations in an org-mode file which might have
488 been invisible before. When this is set, the heading following the
489 match is shown.
490 Turning this off for example for sparse trees makes them very compact,
491 but makes it harder to edit the location of the match. In such a case,
492 use the command \\[org-reveal] to show more context.
493 Instead of t, this can also be an alist specifying this option for different
494 contexts. See `org-show-hierarchy-above' for valid contexts."
495 :group 'org-reveal-location
496 :type org-context-choice)
498 (defcustom org-show-siblings '((default . nil) (isearch t))
499 "Non-nil means, show all sibling heading when revealing a location.
500 Org-mode often shows locations in an org-mode file which might have
501 been invisible before. When this is set, the sibling of the current entry
502 heading are all made visible. If `org-show-hierarchy-above' is t,
503 the same happens on each level of the hierarchy above the current entry.
505 By default this is on for the isearch context, off for all other contexts.
506 Turning this off for example for sparse trees makes them very compact,
507 but makes it harder to edit the location of the match. In such a case,
508 use the command \\[org-reveal] to show more context.
509 Instead of t, this can also be an alist specifying this option for different
510 contexts. See `org-show-hierarchy-above' for valid contexts."
511 :group 'org-reveal-location
512 :type org-context-choice)
514 (defcustom org-show-entry-below '((default . nil))
515 "Non-nil means, show the entry below a headline when revealing a location.
516 Org-mode often shows locations in an org-mode file which might have
517 been invisible before. When this is set, the text below the headline that is
518 exposed is also shown.
520 By default this is off for all contexts.
521 Instead of t, this can also be an alist specifying this option for different
522 contexts. See `org-show-hierarchy-above' for valid contexts."
523 :group 'org-reveal-location
524 :type org-context-choice)
526 (defcustom org-indirect-buffer-display 'other-window
527 "How should indirect tree buffers be displayed?
528 This applies to indirect buffers created with the commands
529 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
530 Valid values are:
531 current-window Display in the current window
532 other-window Just display in another window.
533 dedicated-frame Create one new frame, and re-use it each time.
534 new-frame Make a new frame each time. Note that in this case
535 previously-made indirect buffers are kept, and you need to
536 kill these buffers yourself."
537 :group 'org-structure
538 :group 'org-agenda-windows
539 :type '(choice
540 (const :tag "In current window" current-window)
541 (const :tag "In current frame, other window" other-window)
542 (const :tag "Each time a new frame" new-frame)
543 (const :tag "One dedicated frame" dedicated-frame)))
545 (defgroup org-cycle nil
546 "Options concerning visibility cycling in Org-mode."
547 :tag "Org Cycle"
548 :group 'org-structure)
550 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
551 "Names of drawers. Drawers are not opened by cycling on the headline above.
552 Drawers only open with a TAB on the drawer line itself. A drawer looks like
553 this:
554 :DRAWERNAME:
555 .....
556 :END:
557 The drawer \"PROPERTIES\" is special for capturing properties through
558 the property API.
560 Drawers can be defined on the per-file basis with a line like:
562 #+DRAWERS: HIDDEN STATE PROPERTIES"
563 :group 'org-structure
564 :type '(repeat (string :tag "Drawer Name")))
566 (defcustom org-cycle-global-at-bob nil
567 "Cycle globally if cursor is at beginning of buffer and not at a headline.
568 This makes it possible to do global cycling without having to use S-TAB or
569 C-u TAB. For this special case to work, the first line of the buffer
570 must not be a headline - it may be empty or some other text. When used in
571 this way, `org-cycle-hook' is disables temporarily, to make sure the
572 cursor stays at the beginning of the buffer.
573 When this option is nil, don't do anything special at the beginning
574 of the buffer."
575 :group 'org-cycle
576 :type 'boolean)
578 (defcustom org-cycle-emulate-tab t
579 "Where should `org-cycle' emulate TAB.
580 nil Never
581 white Only in completely white lines
582 whitestart Only at the beginning of lines, before the first non-white char
583 t Everywhere except in headlines
584 exc-hl-bol Everywhere except at the start of a headline
585 If TAB is used in a place where it does not emulate TAB, the current subtree
586 visibility is cycled."
587 :group 'org-cycle
588 :type '(choice (const :tag "Never" nil)
589 (const :tag "Only in completely white lines" white)
590 (const :tag "Before first char in a line" whitestart)
591 (const :tag "Everywhere except in headlines" t)
592 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
595 (defcustom org-cycle-separator-lines 2
596 "Number of empty lines needed to keep an empty line between collapsed trees.
597 If you leave an empty line between the end of a subtree and the following
598 headline, this empty line is hidden when the subtree is folded.
599 Org-mode will leave (exactly) one empty line visible if the number of
600 empty lines is equal or larger to the number given in this variable.
601 So the default 2 means, at least 2 empty lines after the end of a subtree
602 are needed to produce free space between a collapsed subtree and the
603 following headline.
605 Special case: when 0, never leave empty lines in collapsed view."
606 :group 'org-cycle
607 :type 'integer)
608 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
610 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
611 org-cycle-hide-drawers
612 org-cycle-show-empty-lines
613 org-optimize-window-after-visibility-change)
614 "Hook that is run after `org-cycle' has changed the buffer visibility.
615 The function(s) in this hook must accept a single argument which indicates
616 the new state that was set by the most recent `org-cycle' command. The
617 argument is a symbol. After a global state change, it can have the values
618 `overview', `content', or `all'. After a local state change, it can have
619 the values `folded', `children', or `subtree'."
620 :group 'org-cycle
621 :type 'hook)
623 (defgroup org-edit-structure nil
624 "Options concerning structure editing in Org-mode."
625 :tag "Org Edit Structure"
626 :group 'org-structure)
628 (defcustom org-odd-levels-only nil
629 "Non-nil means, skip even levels and only use odd levels for the outline.
630 This has the effect that two stars are being added/taken away in
631 promotion/demotion commands. It also influences how levels are
632 handled by the exporters.
633 Changing it requires restart of `font-lock-mode' to become effective
634 for fontification also in regions already fontified.
635 You may also set this on a per-file basis by adding one of the following
636 lines to the buffer:
638 #+STARTUP: odd
639 #+STARTUP: oddeven"
640 :group 'org-edit-structure
641 :group 'org-font-lock
642 :type 'boolean)
644 (defcustom org-adapt-indentation t
645 "Non-nil means, adapt indentation when promoting and demoting.
646 When this is set and the *entire* text in an entry is indented, the
647 indentation is increased by one space in a demotion command, and
648 decreased by one in a promotion command. If any line in the entry
649 body starts at column 0, indentation is not changed at all."
650 :group 'org-edit-structure
651 :type 'boolean)
653 (defcustom org-special-ctrl-a/e nil
654 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
656 When t, `C-a' will bring back the cursor to the beginning of the
657 headline text, i.e. after the stars and after a possible TODO keyword.
658 In an item, this will be the position after the bullet.
659 When the cursor is already at that position, another `C-a' will bring
660 it to the beginning of the line.
662 `C-e' will jump to the end of the headline, ignoring the presence of tags
663 in the headline. A second `C-e' will then jump to the true end of the
664 line, after any tags.
666 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
667 and only a directly following, identical keypress will bring the cursor
668 to the special positions.
670 This may also be a cons cell where the behavior for `C-a' and `C-e' is
671 set separately."
672 :group 'org-edit-structure
673 :type '(choice
674 (const :tag "off" nil)
675 (const :tag "after stars/bullet and before tags first" t)
676 (const :tag "true line boundary first" reversed)
677 (cons :tag "Set C-a and C-e separately"
678 (choice :tag "Special C-a"
679 (const :tag "off" nil)
680 (const :tag "after stars/bullet first" t)
681 (const :tag "before stars/bullet first" reversed))
682 (choice :tag "Special C-e"
683 (const :tag "off" nil)
684 (const :tag "before tags first" t)
685 (const :tag "after tags first" reversed)))))
686 (if (fboundp 'defvaralias)
687 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
689 (defcustom org-special-ctrl-k nil
690 "Non-nil means `C-k' will behave specially in headlines.
691 When nil, `C-k' will call the default `kill-line' command.
692 When t, the following will happen while the cursor is in the headline:
694 - When the cursor is at the beginning of a headline, kill the entire
695 line and possible the folded subtree below the line.
696 - When in the middle of the headline text, kill the headline up to the tags.
697 - When after the headline text, kill the tags."
698 :group 'org-edit-structure
699 :type 'boolean)
701 (defcustom org-yank-folded-subtrees t
702 "Non-nil means, when yanking subtrees, fold them.
703 If the kill is a single subtree, or a sequence of subtrees, i.e. if
704 it starts with a heading and all other headings in it are either children
705 or siblings, then fold all the subtrees. However, do this only if no
706 text after the yank would be swallowed into a folded tree by this action."
707 :group 'org-edit-structure
708 :type 'boolean)
710 (defcustom org-yank-adjusted-subtrees nil
711 "Non-nil means, when yanking subtrees, adjust the level.
712 With this setting, `org-paste-subtree' is used to insert the subtree, see
713 this function for details."
714 :group 'org-edit-structure
715 :type 'boolean)
717 (defcustom org-M-RET-may-split-line '((default . t))
718 "Non-nil means, M-RET will split the line at the cursor position.
719 When nil, it will go to the end of the line before making a
720 new line.
721 You may also set this option in a different way for different
722 contexts. Valid contexts are:
724 headline when creating a new headline
725 item when creating a new item
726 table in a table field
727 default the value to be used for all contexts not explicitly
728 customized"
729 :group 'org-structure
730 :group 'org-table
731 :type '(choice
732 (const :tag "Always" t)
733 (const :tag "Never" nil)
734 (repeat :greedy t :tag "Individual contexts"
735 (cons
736 (choice :tag "Context"
737 (const headline)
738 (const item)
739 (const table)
740 (const default))
741 (boolean)))))
744 (defcustom org-insert-heading-respect-content nil
745 "Non-nil means, insert new headings after the current subtree.
746 When nil, the new heading is created directly after the current line.
747 The commands \\[org-insert-heading-respect-content] and
748 \\[org-insert-todo-heading-respect-content] turn this variable on
749 for the duration of the command."
750 :group 'org-structure
751 :type 'boolean)
753 (defcustom org-blank-before-new-entry '((heading . auto)
754 (plain-list-item . auto))
755 "Should `org-insert-heading' leave a blank line before new heading/item?
756 The value is an alist, with `heading' and `plain-list-item' as car,
757 and a boolean flag as cdr. For plain lists, if the variable
758 `org-empty-line-terminates-plain-lists' is set, the setting here
759 is ignored and no empty line is inserted, to keep the list in tact."
760 :group 'org-edit-structure
761 :type '(list
762 (cons (const heading)
763 (choice (const :tag "Never" nil)
764 (const :tag "Always" t)
765 (const :tag "Auto" auto)))
766 (cons (const plain-list-item)
767 (choice (const :tag "Never" nil)
768 (const :tag "Always" t)
769 (const :tag "Auto" auto)))))
771 (defcustom org-insert-heading-hook nil
772 "Hook being run after inserting a new heading."
773 :group 'org-edit-structure
774 :type 'hook)
776 (defcustom org-enable-fixed-width-editor t
777 "Non-nil means, lines starting with \":\" are treated as fixed-width.
778 This currently only means, they are never auto-wrapped.
779 When nil, such lines will be treated like ordinary lines.
780 See also the QUOTE keyword."
781 :group 'org-edit-structure
782 :type 'boolean)
784 (defcustom org-edit-src-region-extra nil
785 "Additional regexps to identify regions for editing with `org-edit-src-code'.
786 For examples see the function `org-edit-src-find-region-and-lang'.
787 The regular expression identifying the begin marker should end with a newline,
788 and the regexp marking the end line should start with a newline, to make sure
789 there are kept outside the narrowed region."
790 :group 'org-edit-structure
791 :type '(repeat
792 (list
793 (regexp :tag "begin regexp")
794 (regexp :tag "end regexp")
795 (choice :tag "language"
796 (string :tag "specify")
797 (integer :tag "from match group")
798 (const :tag "from `lang' element")
799 (const :tag "from `style' element")))))
801 (defcustom org-coderef-label-format "(ref:%s)"
802 "The default coderef format.
803 This format string will be used to search for coderef labels in literal
804 examples (EXAMPLE and SRC blocks). The format can be overwritten
805 an individual literal example with the -f option, like
807 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
809 #+END_SRC
811 If you want to use this for HTML export, make sure that the format does
812 not introduce special font-locking, and avoid the HTML special
813 characters `<', `>', and `&'. The reason for this restriction is that
814 the labels are searched for only after htmlize has done its job."
815 :group 'org-edit-structure ; FIXME this is not in the right group
816 :type 'string)
818 (defcustom org-edit-fixed-width-region-mode 'artist-mode
819 "The mode that should be used to edit fixed-width regions.
820 These are the regions where each line starts with a colon."
821 :group 'org-edit-structure
822 :type '(choice
823 (const artist-mode)
824 (const picture-mode)
825 (const fundamental-mode)
826 (function :tag "Other (specify)")))
828 (defcustom org-goto-auto-isearch t
829 "Non-nil means, typing characters in org-goto starts incremental search."
830 :group 'org-edit-structure
831 :type 'boolean)
833 (defgroup org-sparse-trees nil
834 "Options concerning sparse trees in Org-mode."
835 :tag "Org Sparse Trees"
836 :group 'org-structure)
838 (defcustom org-highlight-sparse-tree-matches t
839 "Non-nil means, highlight all matches that define a sparse tree.
840 The highlights will automatically disappear the next time the buffer is
841 changed by an edit command."
842 :group 'org-sparse-trees
843 :type 'boolean)
845 (defcustom org-remove-highlights-with-change t
846 "Non-nil means, any change to the buffer will remove temporary highlights.
847 Such highlights are created by `org-occur' and `org-clock-display'.
848 When nil, `C-c C-c needs to be used to get rid of the highlights.
849 The highlights created by `org-preview-latex-fragment' always need
850 `C-c C-c' to be removed."
851 :group 'org-sparse-trees
852 :group 'org-time
853 :type 'boolean)
856 (defcustom org-occur-hook '(org-first-headline-recenter)
857 "Hook that is run after `org-occur' has constructed a sparse tree.
858 This can be used to recenter the window to show as much of the structure
859 as possible."
860 :group 'org-sparse-trees
861 :type 'hook)
863 (defgroup org-imenu-and-speedbar nil
864 "Options concerning imenu and speedbar in Org-mode."
865 :tag "Org Imenu and Speedbar"
866 :group 'org-structure)
868 (defcustom org-imenu-depth 2
869 "The maximum level for Imenu access to Org-mode headlines.
870 This also applied for speedbar access."
871 :group 'org-imenu-and-speedbar
872 :type 'number)
874 (defgroup org-table nil
875 "Options concerning tables in Org-mode."
876 :tag "Org Table"
877 :group 'org)
879 (defcustom org-enable-table-editor 'optimized
880 "Non-nil means, lines starting with \"|\" are handled by the table editor.
881 When nil, such lines will be treated like ordinary lines.
883 When equal to the symbol `optimized', the table editor will be optimized to
884 do the following:
885 - Automatic overwrite mode in front of whitespace in table fields.
886 This makes the structure of the table stay in tact as long as the edited
887 field does not exceed the column width.
888 - Minimize the number of realigns. Normally, the table is aligned each time
889 TAB or RET are pressed to move to another field. With optimization this
890 happens only if changes to a field might have changed the column width.
891 Optimization requires replacing the functions `self-insert-command',
892 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
893 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
894 very good at guessing when a re-align will be necessary, but you can always
895 force one with \\[org-ctrl-c-ctrl-c].
897 If you would like to use the optimized version in Org-mode, but the
898 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
900 This variable can be used to turn on and off the table editor during a session,
901 but in order to toggle optimization, a restart is required.
903 See also the variable `org-table-auto-blank-field'."
904 :group 'org-table
905 :type '(choice
906 (const :tag "off" nil)
907 (const :tag "on" t)
908 (const :tag "on, optimized" optimized)))
910 (defcustom org-self-insert-cluster-for-undo t
911 "Non-nil means cluster self-insert commands for undo when possible.
912 If this is set, then, like in the Emacs command loop, 20 consequtive
913 characters will be undone together.
914 This is configurable, because there is some impact on typing performance."
915 :group 'org-table
916 :type 'boolean)
918 (defcustom org-table-tab-recognizes-table.el t
919 "Non-nil means, TAB will automatically notice a table.el table.
920 When it sees such a table, it moves point into it and - if necessary -
921 calls `table-recognize-table'."
922 :group 'org-table-editing
923 :type 'boolean)
925 (defgroup org-link nil
926 "Options concerning links in Org-mode."
927 :tag "Org Link"
928 :group 'org)
930 (defvar org-link-abbrev-alist-local nil
931 "Buffer-local version of `org-link-abbrev-alist', which see.
932 The value of this is taken from the #+LINK lines.")
933 (make-variable-buffer-local 'org-link-abbrev-alist-local)
935 (defcustom org-link-abbrev-alist nil
936 "Alist of link abbreviations.
937 The car of each element is a string, to be replaced at the start of a link.
938 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
939 links in Org-mode buffers can have an optional tag after a double colon, e.g.
941 [[linkkey:tag][description]]
943 The 'linkkey' must be a word word, starting with a letter, followed
944 by letters, numbers, '-' or '_'.
946 If REPLACE is a string, the tag will simply be appended to create the link.
947 If the string contains \"%s\", the tag will be inserted there. Alternatively,
948 the placeholder \"%h\" will cause a url-encoded version of the tag to
949 be inserted at that point (see the function `url-hexify-string').
951 REPLACE may also be a function that will be called with the tag as the
952 only argument to create the link, which should be returned as a string.
954 See the manual for examples."
955 :group 'org-link
956 :type '(repeat
957 (cons
958 (string :tag "Protocol")
959 (choice
960 (string :tag "Format")
961 (function)))))
963 (defcustom org-descriptive-links t
964 "Non-nil means, hide link part and only show description of bracket links.
965 Bracket links are like [[link][description]]. This variable sets the initial
966 state in new org-mode buffers. The setting can then be toggled on a
967 per-buffer basis from the Org->Hyperlinks menu."
968 :group 'org-link
969 :type 'boolean)
971 (defcustom org-link-file-path-type 'adaptive
972 "How the path name in file links should be stored.
973 Valid values are:
975 relative Relative to the current directory, i.e. the directory of the file
976 into which the link is being inserted.
977 absolute Absolute path, if possible with ~ for home directory.
978 noabbrev Absolute path, no abbreviation of home directory.
979 adaptive Use relative path for files in the current directory and sub-
980 directories of it. For other files, use an absolute path."
981 :group 'org-link
982 :type '(choice
983 (const relative)
984 (const absolute)
985 (const noabbrev)
986 (const adaptive)))
988 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
989 "Types of links that should be activated in Org-mode files.
990 This is a list of symbols, each leading to the activation of a certain link
991 type. In principle, it does not hurt to turn on most link types - there may
992 be a small gain when turning off unused link types. The types are:
994 bracket The recommended [[link][description]] or [[link]] links with hiding.
995 angular Links in angular brackets that may contain whitespace like
996 <bbdb:Carsten Dominik>.
997 plain Plain links in normal text, no whitespace, like http://google.com.
998 radio Text that is matched by a radio target, see manual for details.
999 tag Tag settings in a headline (link to tag search).
1000 date Time stamps (link to calendar).
1001 footnote Footnote labels.
1003 Changing this variable requires a restart of Emacs to become effective."
1004 :group 'org-link
1005 :type '(set :greedy t
1006 (const :tag "Double bracket links (new style)" bracket)
1007 (const :tag "Angular bracket links (old style)" angular)
1008 (const :tag "Plain text links" plain)
1009 (const :tag "Radio target matches" radio)
1010 (const :tag "Tags" tag)
1011 (const :tag "Timestamps" date)
1012 (const :tag "Footnotes" footnote)))
1014 (defcustom org-make-link-description-function nil
1015 "Function to use to generate link descriptions from links. If
1016 nil the link location will be used. This function must take two
1017 parameters; the first is the link and the second the description
1018 org-insert-link has generated, and should return the description
1019 to use."
1020 :group 'org-link
1021 :type 'function)
1023 (defgroup org-link-store nil
1024 "Options concerning storing links in Org-mode."
1025 :tag "Org Store Link"
1026 :group 'org-link)
1028 (defcustom org-email-link-description-format "Email %c: %.30s"
1029 "Format of the description part of a link to an email or usenet message.
1030 The following %-escapes will be replaced by corresponding information:
1032 %F full \"From\" field
1033 %f name, taken from \"From\" field, address if no name
1034 %T full \"To\" field
1035 %t first name in \"To\" field, address if no name
1036 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1037 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1038 %s subject
1039 %m message-id.
1041 You may use normal field width specification between the % and the letter.
1042 This is for example useful to limit the length of the subject.
1044 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1045 :group 'org-link-store
1046 :type 'string)
1048 (defcustom org-from-is-user-regexp
1049 (let (r1 r2)
1050 (when (and user-mail-address (not (string= user-mail-address "")))
1051 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1052 (when (and user-full-name (not (string= user-full-name "")))
1053 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1054 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1055 "Regexp matched against the \"From:\" header of an email or usenet message.
1056 It should match if the message is from the user him/herself."
1057 :group 'org-link-store
1058 :type 'regexp)
1060 (defcustom org-link-to-org-use-id 'create-if-interactive
1061 "Non-nil means, storing a link to an Org file will use entry IDs.
1063 Note that before this variable is even considered, org-id must be loaded,
1064 to please customize `org-modules' and turn it on.
1066 The variable can have the following values:
1068 t Create an ID if needed to make a link to the current entry.
1070 create-if-interactive
1071 If `org-store-link' is called directly (interactively, as a user
1072 command), do create an ID to support the link. But when doing the
1073 job for remember, only use the ID if it already exists. The
1074 purpose of this setting is to avoid proliferation of unwanted
1075 IDs, just because you happen to be in an Org file when you
1076 call `org-remember' that automatically and preemptively
1077 creates a link. If you do want to get an ID link in a remember
1078 template to an entry not having an ID, create it first by
1079 explicitly creating a link to it, using `C-c C-l' first.
1081 use-existing
1082 Use existing ID, do not create one.
1084 nil Never use an ID to make a link, instead link using a text search for
1085 the headline text."
1086 :group 'org-link-store
1087 :type '(choice
1088 (const :tag "Create ID to make link" t)
1089 (const :tag "Create if string link interactively"
1090 'create-if-interactive)
1091 (const :tag "Only use existing" 'use-existing)
1092 (const :tag "Do not use ID to create link" nil)))
1094 (defcustom org-context-in-file-links t
1095 "Non-nil means, file links from `org-store-link' contain context.
1096 A search string will be added to the file name with :: as separator and
1097 used to find the context when the link is activated by the command
1098 `org-open-at-point'.
1099 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1100 negates this setting for the duration of the command."
1101 :group 'org-link-store
1102 :type 'boolean)
1104 (defcustom org-keep-stored-link-after-insertion nil
1105 "Non-nil means, keep link in list for entire session.
1107 The command `org-store-link' adds a link pointing to the current
1108 location to an internal list. These links accumulate during a session.
1109 The command `org-insert-link' can be used to insert links into any
1110 Org-mode file (offering completion for all stored links). When this
1111 option is nil, every link which has been inserted once using \\[org-insert-link]
1112 will be removed from the list, to make completing the unused links
1113 more efficient."
1114 :group 'org-link-store
1115 :type 'boolean)
1117 (defgroup org-link-follow nil
1118 "Options concerning following links in Org-mode."
1119 :tag "Org Follow Link"
1120 :group 'org-link)
1122 (defcustom org-link-translation-function nil
1123 "Function to translate links with different syntax to Org syntax.
1124 This can be used to translate links created for example by the Planner
1125 or emacs-wiki packages to Org syntax.
1126 The function must accept two parameters, a TYPE containing the link
1127 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1128 which is everything after the link protocol. It should return a cons
1129 with possibly modified values of type and path.
1130 Org contains a function for this, so if you set this variable to
1131 `org-translate-link-from-planner', you should be able follow many
1132 links created by planner."
1133 :group 'org-link-follow
1134 :type 'function)
1136 (defcustom org-follow-link-hook nil
1137 "Hook that is run after a link has been followed."
1138 :group 'org-link-follow
1139 :type 'hook)
1141 (defcustom org-tab-follows-link nil
1142 "Non-nil means, on links TAB will follow the link.
1143 Needs to be set before org.el is loaded.
1144 This really should not be used, it does not make sense, and the
1145 implementation is bad."
1146 :group 'org-link-follow
1147 :type 'boolean)
1149 (defcustom org-return-follows-link nil
1150 "Non-nil means, on links RET will follow the link.
1151 Needs to be set before org.el is loaded."
1152 :group 'org-link-follow
1153 :type 'boolean)
1155 (defcustom org-mouse-1-follows-link
1156 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1157 "Non-nil means, mouse-1 on a link will follow the link.
1158 A longer mouse click will still set point. Does not work on XEmacs.
1159 Needs to be set before org.el is loaded."
1160 :group 'org-link-follow
1161 :type 'boolean)
1163 (defcustom org-mark-ring-length 4
1164 "Number of different positions to be recorded in the ring
1165 Changing this requires a restart of Emacs to work correctly."
1166 :group 'org-link-follow
1167 :type 'integer)
1169 (defcustom org-link-frame-setup
1170 '((vm . vm-visit-folder-other-frame)
1171 (gnus . gnus-other-frame)
1172 (file . find-file-other-window))
1173 "Setup the frame configuration for following links.
1174 When following a link with Emacs, it may often be useful to display
1175 this link in another window or frame. This variable can be used to
1176 set this up for the different types of links.
1177 For VM, use any of
1178 `vm-visit-folder'
1179 `vm-visit-folder-other-frame'
1180 For Gnus, use any of
1181 `gnus'
1182 `gnus-other-frame'
1183 `org-gnus-no-new-news'
1184 For FILE, use any of
1185 `find-file'
1186 `find-file-other-window'
1187 `find-file-other-frame'
1188 For the calendar, use the variable `calendar-setup'.
1189 For BBDB, it is currently only possible to display the matches in
1190 another window."
1191 :group 'org-link-follow
1192 :type '(list
1193 (cons (const vm)
1194 (choice
1195 (const vm-visit-folder)
1196 (const vm-visit-folder-other-window)
1197 (const vm-visit-folder-other-frame)))
1198 (cons (const gnus)
1199 (choice
1200 (const gnus)
1201 (const gnus-other-frame)
1202 (const org-gnus-no-new-news)))
1203 (cons (const file)
1204 (choice
1205 (const find-file)
1206 (const find-file-other-window)
1207 (const find-file-other-frame)))))
1209 (defcustom org-display-internal-link-with-indirect-buffer nil
1210 "Non-nil means, use indirect buffer to display infile links.
1211 Activating internal links (from one location in a file to another location
1212 in the same file) normally just jumps to the location. When the link is
1213 activated with a C-u prefix (or with mouse-3), the link is displayed in
1214 another window. When this option is set, the other window actually displays
1215 an indirect buffer clone of the current buffer, to avoid any visibility
1216 changes to the current buffer."
1217 :group 'org-link-follow
1218 :type 'boolean)
1220 (defcustom org-open-non-existing-files nil
1221 "Non-nil means, `org-open-file' will open non-existing files.
1222 When nil, an error will be generated."
1223 :group 'org-link-follow
1224 :type 'boolean)
1226 (defcustom org-open-directory-means-index-dot-org nil
1227 "Non-nil means, a link to a directory really means to index.org.
1228 When nil, following a directory link will run dired or open a finder/explorer
1229 window on that directory."
1230 :group 'org-link-follow
1231 :type 'boolean)
1233 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1234 "Function and arguments to call for following mailto links.
1235 This is a list with the first element being a lisp function, and the
1236 remaining elements being arguments to the function. In string arguments,
1237 %a will be replaced by the address, and %s will be replaced by the subject
1238 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1239 :group 'org-link-follow
1240 :type '(choice
1241 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1242 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1243 (const :tag "message-mail" (message-mail "%a" "%s"))
1244 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1246 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1247 "Non-nil means, ask for confirmation before executing shell links.
1248 Shell links can be dangerous: just think about a link
1250 [[shell:rm -rf ~/*][Google Search]]
1252 This link would show up in your Org-mode document as \"Google Search\",
1253 but really it would remove your entire home directory.
1254 Therefore we advise against setting this variable to nil.
1255 Just change it to `y-or-n-p' of you want to confirm with a
1256 single keystroke rather than having to type \"yes\"."
1257 :group 'org-link-follow
1258 :type '(choice
1259 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1260 (const :tag "with y-or-n (faster)" y-or-n-p)
1261 (const :tag "no confirmation (dangerous)" nil)))
1263 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1264 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1265 Elisp links can be dangerous: just think about a link
1267 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1269 This link would show up in your Org-mode document as \"Google Search\",
1270 but really it would remove your entire home directory.
1271 Therefore we advise against setting this variable to nil.
1272 Just change it to `y-or-n-p' of you want to confirm with a
1273 single keystroke rather than having to type \"yes\"."
1274 :group 'org-link-follow
1275 :type '(choice
1276 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1277 (const :tag "with y-or-n (faster)" y-or-n-p)
1278 (const :tag "no confirmation (dangerous)" nil)))
1280 (defconst org-file-apps-defaults-gnu
1281 '((remote . emacs)
1282 (system . mailcap)
1283 (t . mailcap))
1284 "Default file applications on a UNIX or GNU/Linux system.
1285 See `org-file-apps'.")
1287 (defconst org-file-apps-defaults-macosx
1288 '((remote . emacs)
1289 (t . "open %s")
1290 (system . "open %s")
1291 ("ps.gz" . "gv %s")
1292 ("eps.gz" . "gv %s")
1293 ("dvi" . "xdvi %s")
1294 ("fig" . "xfig %s"))
1295 "Default file applications on a MacOS X system.
1296 The system \"open\" is known as a default, but we use X11 applications
1297 for some files for which the OS does not have a good default.
1298 See `org-file-apps'.")
1300 (defconst org-file-apps-defaults-windowsnt
1301 (list
1302 '(remote . emacs)
1303 (cons t
1304 (list (if (featurep 'xemacs)
1305 'mswindows-shell-execute
1306 'w32-shell-execute)
1307 "open" 'file))
1308 (cons 'system
1309 (list (if (featurep 'xemacs)
1310 'mswindows-shell-execute
1311 'w32-shell-execute)
1312 "open" 'file)))
1313 "Default file applications on a Windows NT system.
1314 The system \"open\" is used for most files.
1315 See `org-file-apps'.")
1317 (defcustom org-file-apps
1319 (auto-mode . emacs)
1320 ("\\.x?html?\\'" . default)
1321 ("\\.pdf\\'" . default)
1323 "External applications for opening `file:path' items in a document.
1324 Org-mode uses system defaults for different file types, but
1325 you can use this variable to set the application for a given file
1326 extension. The entries in this list are cons cells where the car identifies
1327 files and the cdr the corresponding command. Possible values for the
1328 file identifier are
1329 \"regex\" Regular expression matched against the file name. For backward
1330 compatibility, this can also be a string with only alphanumeric
1331 characters, which is then interpreted as an extension.
1332 `directory' Matches a directory
1333 `remote' Matches a remote file, accessible through tramp or efs.
1334 Remote files most likely should be visited through Emacs
1335 because external applications cannot handle such paths.
1336 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1337 so all files Emacs knows how to handle. Using this with
1338 command `emacs' will open most files in Emacs. Beware that this
1339 will also open html files inside Emacs, unless you add
1340 (\"html\" . default) to the list as well.
1341 t Default for files not matched by any of the other options.
1342 `system' The system command to open files, like `open' on Windows
1343 and Mac OS X, and mailcap under GNU/Linux. This is the command
1344 that will be selected if you call `C-c C-o' with a double
1345 `C-u C-u' prefix.
1347 Possible values for the command are:
1348 `emacs' The file will be visited by the current Emacs process.
1349 `default' Use the default application for this file type, which is the
1350 association for t in the list, most likely in the system-specific
1351 part.
1352 This can be used to overrule an unwanted setting in the
1353 system-specific variable.
1354 `system' Use the system command for opening files, like \"open\".
1355 This command is specified by the entry whose car is `system'.
1356 Most likely, the system-specific version of this variable
1357 does define this command, but you can overrule/replace it
1358 here.
1359 string A command to be executed by a shell; %s will be replaced
1360 by the path to the file.
1361 sexp A Lisp form which will be evaluated. The file path will
1362 be available in the Lisp variable `file'.
1363 For more examples, see the system specific constants
1364 `org-file-apps-defaults-macosx'
1365 `org-file-apps-defaults-windowsnt'
1366 `org-file-apps-defaults-gnu'."
1367 :group 'org-link-follow
1368 :type '(repeat
1369 (cons (choice :value ""
1370 (string :tag "Extension")
1371 (const :tag "System command to open files" system)
1372 (const :tag "Default for unrecognized files" t)
1373 (const :tag "Remote file" remote)
1374 (const :tag "Links to a directory" directory)
1375 (const :tag "Any files that have Emacs modes"
1376 auto-mode))
1377 (choice :value ""
1378 (const :tag "Visit with Emacs" emacs)
1379 (const :tag "Use default" default)
1380 (const :tag "Use the system command" system)
1381 (string :tag "Command")
1382 (sexp :tag "Lisp form")))))
1384 (defgroup org-refile nil
1385 "Options concerning refiling entries in Org-mode."
1386 :tag "Org Refile"
1387 :group 'org)
1389 (defcustom org-directory "~/org"
1390 "Directory with org files.
1391 This is just a default location to look for Org files. There is no need
1392 at all to put your files into this directory. It is only used in the
1393 following situations:
1395 1. When a remember template specifies a target file that is not an
1396 absolute path. The path will then be interpreted relative to
1397 `org-directory'
1398 2. When a remember note is filed away in an interactive way (when exiting the
1399 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1400 with `org-directory' as the default path."
1401 :group 'org-refile
1402 :group 'org-remember
1403 :type 'directory)
1405 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1406 "Default target for storing notes.
1407 Used by the hooks for remember.el. This can be a string, or nil to mean
1408 the value of `remember-data-file'.
1409 You can set this on a per-template basis with the variable
1410 `org-remember-templates'."
1411 :group 'org-refile
1412 :group 'org-remember
1413 :type '(choice
1414 (const :tag "Default from remember-data-file" nil)
1415 file))
1417 (defcustom org-goto-interface 'outline
1418 "The default interface to be used for `org-goto'.
1419 Allowed values are:
1420 outline The interface shows an outline of the relevant file
1421 and the correct heading is found by moving through
1422 the outline or by searching with incremental search.
1423 outline-path-completion Headlines in the current buffer are offered via
1424 completion. This is the interface also used by
1425 the refile command."
1426 :group 'org-refile
1427 :type '(choice
1428 (const :tag "Outline" outline)
1429 (const :tag "Outline-path-completion" outline-path-completion)))
1431 (defcustom org-goto-max-level 5
1432 "Maximum level to be considered when running org-goto with refile interface."
1433 :group 'org-refile
1434 :type 'number)
1436 (defcustom org-reverse-note-order nil
1437 "Non-nil means, store new notes at the beginning of a file or entry.
1438 When nil, new notes will be filed to the end of a file or entry.
1439 This can also be a list with cons cells of regular expressions that
1440 are matched against file names, and values."
1441 :group 'org-remember
1442 :group 'org-refile
1443 :type '(choice
1444 (const :tag "Reverse always" t)
1445 (const :tag "Reverse never" nil)
1446 (repeat :tag "By file name regexp"
1447 (cons regexp boolean))))
1449 (defcustom org-refile-targets nil
1450 "Targets for refiling entries with \\[org-refile].
1451 This is list of cons cells. Each cell contains:
1452 - a specification of the files to be considered, either a list of files,
1453 or a symbol whose function or variable value will be used to retrieve
1454 a file name or a list of file names. If you use `org-agenda-files' for
1455 that, all agenda files will be scanned for targets. Nil means, consider
1456 headings in the current buffer.
1457 - A specification of how to find candidate refile targets. This may be
1458 any of:
1459 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1460 This tag has to be present in all target headlines, inheritance will
1461 not be considered.
1462 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1463 todo keyword.
1464 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1465 headlines that are refiling targets.
1466 - a cons cell (:level . N). Any headline of level N is considered a target.
1467 Note that, when `org-odd-levels-only' is set, level corresponds to
1468 order in hierarchy, not to the number of stars.
1469 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1470 Note that, when `org-odd-levels-only' is set, level corresponds to
1471 order in hierarchy, not to the number of stars.
1473 When this variable is nil, all top-level headlines in the current buffer
1474 are used, equivalent to the value `((nil . (:level . 1))'."
1475 :group 'org-refile
1476 :type '(repeat
1477 (cons
1478 (choice :value org-agenda-files
1479 (const :tag "All agenda files" org-agenda-files)
1480 (const :tag "Current buffer" nil)
1481 (function) (variable) (file))
1482 (choice :tag "Identify target headline by"
1483 (cons :tag "Specific tag" (const :value :tag) (string))
1484 (cons :tag "TODO keyword" (const :value :todo) (string))
1485 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1486 (cons :tag "Level number" (const :value :level) (integer))
1487 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1489 (defcustom org-refile-use-outline-path nil
1490 "Non-nil means, provide refile targets as paths.
1491 So a level 3 headline will be available as level1/level2/level3.
1492 When the value is `file', also include the file name (without directory)
1493 into the path. When `full-file-path', include the full file path."
1494 :group 'org-refile
1495 :type '(choice
1496 (const :tag "Not" nil)
1497 (const :tag "Yes" t)
1498 (const :tag "Start with file name" file)
1499 (const :tag "Start with full file path" full-file-path)))
1501 (defcustom org-outline-path-complete-in-steps t
1502 "Non-nil means, complete the outline path in hierarchical steps.
1503 When Org-mode uses the refile interface to select an outline path
1504 \(see variable `org-refile-use-outline-path'), the completion of
1505 the path can be done is a single go, or if can be done in steps down
1506 the headline hierarchy. Going in steps is probably the best if you
1507 do not use a special completion package like `ido' or `icicles'.
1508 However, when using these packages, going in one step can be very
1509 fast, while still showing the whole path to the entry."
1510 :group 'org-refile
1511 :type 'boolean)
1513 (defgroup org-todo nil
1514 "Options concerning TODO items in Org-mode."
1515 :tag "Org TODO"
1516 :group 'org)
1518 (defgroup org-progress nil
1519 "Options concerning Progress logging in Org-mode."
1520 :tag "Org Progress"
1521 :group 'org-time)
1523 (defvar org-todo-interpretation-widgets
1525 (:tag "Sequence (cycling hits every state)" sequence)
1526 (:tag "Type (cycling directly to DONE)" type))
1527 "The available interpretation symbols for customizing
1528 `org-todo-keywords'.
1529 Interested libraries should add to this list.")
1531 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1532 "List of TODO entry keyword sequences and their interpretation.
1533 \\<org-mode-map>This is a list of sequences.
1535 Each sequence starts with a symbol, either `sequence' or `type',
1536 indicating if the keywords should be interpreted as a sequence of
1537 action steps, or as different types of TODO items. The first
1538 keywords are states requiring action - these states will select a headline
1539 for inclusion into the global TODO list Org-mode produces. If one of
1540 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1541 signify that no further action is necessary. If \"|\" is not found,
1542 the last keyword is treated as the only DONE state of the sequence.
1544 The command \\[org-todo] cycles an entry through these states, and one
1545 additional state where no keyword is present. For details about this
1546 cycling, see the manual.
1548 TODO keywords and interpretation can also be set on a per-file basis with
1549 the special #+SEQ_TODO and #+TYP_TODO lines.
1551 Each keyword can optionally specify a character for fast state selection
1552 \(in combination with the variable `org-use-fast-todo-selection')
1553 and specifiers for state change logging, using the same syntax
1554 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1555 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1556 indicates to record a time stamp each time this state is selected.
1558 Each keyword may also specify if a timestamp or a note should be
1559 recorded when entering or leaving the state, by adding additional
1560 characters in the parenthesis after the keyword. This looks like this:
1561 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1562 record only the time of the state change. With X and Y being either
1563 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1564 Y when leaving the state if and only if the *target* state does not
1565 define X. You may omit any of the fast-selection key or X or /Y,
1566 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1568 For backward compatibility, this variable may also be just a list
1569 of keywords - in this case the interpretation (sequence or type) will be
1570 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1571 :group 'org-todo
1572 :group 'org-keywords
1573 :type '(choice
1574 (repeat :tag "Old syntax, just keywords"
1575 (string :tag "Keyword"))
1576 (repeat :tag "New syntax"
1577 (cons
1578 (choice
1579 :tag "Interpretation"
1580 ;;Quick and dirty way to see
1581 ;;`org-todo-interpretations'. This takes the
1582 ;;place of item arguments
1583 :convert-widget
1584 (lambda (widget)
1585 (widget-put widget
1586 :args (mapcar
1587 #'(lambda (x)
1588 (widget-convert
1589 (cons 'const x)))
1590 org-todo-interpretation-widgets))
1591 widget))
1592 (repeat
1593 (string :tag "Keyword"))))))
1595 (defvar org-todo-keywords-1 nil
1596 "All TODO and DONE keywords active in a buffer.")
1597 (make-variable-buffer-local 'org-todo-keywords-1)
1598 (defvar org-todo-keywords-for-agenda nil)
1599 (defvar org-done-keywords-for-agenda nil)
1600 (defvar org-todo-keyword-alist-for-agenda nil)
1601 (defvar org-tag-alist-for-agenda nil)
1602 (defvar org-agenda-contributing-files nil)
1603 (defvar org-not-done-keywords nil)
1604 (make-variable-buffer-local 'org-not-done-keywords)
1605 (defvar org-done-keywords nil)
1606 (make-variable-buffer-local 'org-done-keywords)
1607 (defvar org-todo-heads nil)
1608 (make-variable-buffer-local 'org-todo-heads)
1609 (defvar org-todo-sets nil)
1610 (make-variable-buffer-local 'org-todo-sets)
1611 (defvar org-todo-log-states nil)
1612 (make-variable-buffer-local 'org-todo-log-states)
1613 (defvar org-todo-kwd-alist nil)
1614 (make-variable-buffer-local 'org-todo-kwd-alist)
1615 (defvar org-todo-key-alist nil)
1616 (make-variable-buffer-local 'org-todo-key-alist)
1617 (defvar org-todo-key-trigger nil)
1618 (make-variable-buffer-local 'org-todo-key-trigger)
1620 (defcustom org-todo-interpretation 'sequence
1621 "Controls how TODO keywords are interpreted.
1622 This variable is in principle obsolete and is only used for
1623 backward compatibility, if the interpretation of todo keywords is
1624 not given already in `org-todo-keywords'. See that variable for
1625 more information."
1626 :group 'org-todo
1627 :group 'org-keywords
1628 :type '(choice (const sequence)
1629 (const type)))
1631 (defcustom org-use-fast-todo-selection t
1632 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1633 This variable describes if and under what circumstances the cycling
1634 mechanism for TODO keywords will be replaced by a single-key, direct
1635 selection scheme.
1637 When nil, fast selection is never used.
1639 When the symbol `prefix', it will be used when `org-todo' is called with
1640 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1641 in an agenda buffer.
1643 When t, fast selection is used by default. In this case, the prefix
1644 argument forces cycling instead.
1646 In all cases, the special interface is only used if access keys have actually
1647 been assigned by the user, i.e. if keywords in the configuration are followed
1648 by a letter in parenthesis, like TODO(t)."
1649 :group 'org-todo
1650 :type '(choice
1651 (const :tag "Never" nil)
1652 (const :tag "By default" t)
1653 (const :tag "Only with C-u C-c C-t" prefix)))
1655 (defcustom org-provide-todo-statistics t
1656 "Non-nil means, update todo statistics after insert and toggle.
1657 When this is set, todo statistics is updated in the parent of the current
1658 entry each time a todo state is changed."
1659 :group 'org-todo
1660 :type 'boolean)
1662 (defcustom org-after-todo-state-change-hook nil
1663 "Hook which is run after the state of a TODO item was changed.
1664 The new state (a string with a TODO keyword, or nil) is available in the
1665 Lisp variable `state'."
1666 :group 'org-todo
1667 :type 'hook)
1669 (defvar org-blocker-hook nil
1670 "Hook for functions that are allowed to block a state change.
1672 Each function gets as its single argument a property list, see
1673 `org-trigger-hook' for more information about this list.
1675 If any of the functions in this hook returns nil, the state change
1676 is blocked.")
1678 (defvar org-trigger-hook nil
1679 "Hook for functions that are triggered by a state change.
1681 Each function gets as its single argument a property list with at least
1682 the following elements:
1684 (:type type-of-change :position pos-at-entry-start
1685 :from old-state :to new-state)
1687 Depending on the type, more properties may be present.
1689 This mechanism is currently implemented for:
1691 TODO state changes
1692 ------------------
1693 :type todo-state-change
1694 :from previous state (keyword as a string), or nil, or a symbol
1695 'todo' or 'done', to indicate the general type of state.
1696 :to new state, like in :from")
1698 (defcustom org-enforce-todo-dependencies nil
1699 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1700 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1701 be blocked if any prior sibling is not yet done.
1702 This variable needs to be set before org.el is loaded, and you need to
1703 restart Emacs after a change to make the change effective. The only way
1704 to change is while Emacs is running is through the customize interface."
1705 :set (lambda (var val)
1706 (set var val)
1707 (if val
1708 (add-hook 'org-blocker-hook
1709 'org-block-todo-from-children-or-siblings)
1710 (remove-hook 'org-blocker-hook
1711 'org-block-todo-from-children-or-siblings)))
1712 :group 'org-todo
1713 :type 'boolean)
1715 (defcustom org-enforce-todo-checkbox-dependencies nil
1716 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1717 When this is nil, checkboxes have no influence on switching TODO states.
1718 When non-nil, you first need to check off all check boxes before the TODO
1719 entry can be switched to DONE.
1720 This variable needs to be set before org.el is loaded, and you need to
1721 restart Emacs after a change to make the change effective. The only way
1722 to change is while Emacs is running is through the customize interface."
1723 :set (lambda (var val)
1724 (set var val)
1725 (if val
1726 (add-hook 'org-blocker-hook
1727 'org-block-todo-from-checkboxes)
1728 (remove-hook 'org-blocker-hook
1729 'org-block-todo-from-checkboxes)))
1730 :group 'org-todo
1731 :type 'boolean)
1733 (defcustom org-todo-state-tags-triggers nil
1734 "Tag changes that should be triggered by TODO state changes.
1735 This is a list. Each entry is
1737 (state-change (tag . flag) .......)
1739 State-change can be a string with a state, and empty string to indicate the
1740 state that has no TODO keyword, or it can be one of the symbols `todo'
1741 or `done', meaning any not-done or done state, respectively."
1742 :group 'org-todo
1743 :group 'org-tags
1744 :type '(repeat
1745 (cons (choice :tag "When changing to"
1746 (const :tag "Not-done state" todo)
1747 (const :tag "Done state" done)
1748 (string :tag "State"))
1749 (repeat
1750 (cons :tag "Tag action"
1751 (string :tag "Tag")
1752 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1754 (defcustom org-log-done nil
1755 "Information to record when a task moves to the DONE state.
1757 Possible values are:
1759 nil Don't add anything, just change the keyword
1760 time Add a time stamp to the task
1761 note Prompt a closing note and add it with template `org-log-note-headings'
1763 This option can also be set with on a per-file-basis with
1765 #+STARTUP: nologdone
1766 #+STARTUP: logdone
1767 #+STARTUP: lognotedone
1769 You can have local logging settings for a subtree by setting the LOGGING
1770 property to one or more of these keywords."
1771 :group 'org-todo
1772 :group 'org-progress
1773 :type '(choice
1774 (const :tag "No logging" nil)
1775 (const :tag "Record CLOSED timestamp" time)
1776 (const :tag "Record CLOSED timestamp with closing note." note)))
1778 ;; Normalize old uses of org-log-done.
1779 (cond
1780 ((eq org-log-done t) (setq org-log-done 'time))
1781 ((and (listp org-log-done) (memq 'done org-log-done))
1782 (setq org-log-done 'note)))
1784 (defcustom org-log-note-clock-out nil
1785 "Non-nil means, record a note when clocking out of an item.
1786 This can also be configured on a per-file basis by adding one of
1787 the following lines anywhere in the buffer:
1789 #+STARTUP: lognoteclock-out
1790 #+STARTUP: nolognoteclock-out"
1791 :group 'org-todo
1792 :group 'org-progress
1793 :type 'boolean)
1795 (defcustom org-log-done-with-time t
1796 "Non-nil means, the CLOSED time stamp will contain date and time.
1797 When nil, only the date will be recorded."
1798 :group 'org-progress
1799 :type 'boolean)
1801 (defcustom org-log-note-headings
1802 '((done . "CLOSING NOTE %t")
1803 (state . "State %-12s from %-12S %t")
1804 (note . "Note taken on %t")
1805 (clock-out . ""))
1806 "Headings for notes added to entries.
1807 The value is an alist, with the car being a symbol indicating the note
1808 context, and the cdr is the heading to be used. The heading may also be the
1809 empty string.
1810 %t in the heading will be replaced by a time stamp.
1811 %s will be replaced by the new TODO state, in double quotes.
1812 %S will be replaced by the old TODO state, in double quotes.
1813 %u will be replaced by the user name.
1814 %U will be replaced by the full user name."
1815 :group 'org-todo
1816 :group 'org-progress
1817 :type '(list :greedy t
1818 (cons (const :tag "Heading when closing an item" done) string)
1819 (cons (const :tag
1820 "Heading when changing todo state (todo sequence only)"
1821 state) string)
1822 (cons (const :tag "Heading when just taking a note" note) string)
1823 (cons (const :tag "Heading when clocking out" clock-out) string)))
1825 (unless (assq 'note org-log-note-headings)
1826 (push '(note . "%t") org-log-note-headings))
1828 (defcustom org-log-into-drawer nil
1829 "Non-nil means, insert state change notes and time stamps into a drawer.
1830 When nil, state changes notes will be inserted after the headline and
1831 any scheduling and clock lines, but not inside a drawer.
1833 The value of this variable should be the name of the drawer to use.
1834 LOGBOOK is proposed at the default drawer for this purpose, you can
1835 also set this to a string to define the drawer of your choice.
1837 A value of t is also allowed, representing \"LOGBOOK\".
1839 If this variable is set, `org-log-state-notes-insert-after-drawers'
1840 will be ignored."
1841 :group 'org-todo
1842 :group 'org-progress
1843 :type '(choice
1844 (const :tag "Not into a drawer" nil)
1845 (const :tag "LOGBOOK" t)
1846 (string :tag "Other")))
1848 (if (fboundp 'defvaralias)
1849 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1851 (defcustom org-log-state-notes-insert-after-drawers nil
1852 "Non-nil means, insert state change notes after any drawers in entry.
1853 Only the drawers that *immediately* follow the headline and the
1854 deadline/scheduled line are skipped.
1855 When nil, insert notes right after the heading and perhaps the line
1856 with deadline/scheduling if present.
1858 This variable will have no effect if `org-log-into-drawer' is
1859 set."
1860 :group 'org-todo
1861 :group 'org-progress
1862 :type 'boolean)
1864 (defcustom org-log-states-order-reversed t
1865 "Non-nil means, the latest state change note will be directly after heading.
1866 When nil, the notes will be orderer according to time."
1867 :group 'org-todo
1868 :group 'org-progress
1869 :type 'boolean)
1871 (defcustom org-log-repeat 'time
1872 "Non-nil means, record moving through the DONE state when triggering repeat.
1873 An auto-repeating tasks is immediately switched back to TODO when marked
1874 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1875 the TODO keyword definition, or recording a closing note by setting
1876 `org-log-done', there will be no record of the task moving through DONE.
1877 This variable forces taking a note anyway. Possible values are:
1879 nil Don't force a record
1880 time Record a time stamp
1881 note Record a note
1883 This option can also be set with on a per-file-basis with
1885 #+STARTUP: logrepeat
1886 #+STARTUP: lognoterepeat
1887 #+STARTUP: nologrepeat
1889 You can have local logging settings for a subtree by setting the LOGGING
1890 property to one or more of these keywords."
1891 :group 'org-todo
1892 :group 'org-progress
1893 :type '(choice
1894 (const :tag "Don't force a record" nil)
1895 (const :tag "Force recording the DONE state" time)
1896 (const :tag "Force recording a note with the DONE state" note)))
1899 (defgroup org-priorities nil
1900 "Priorities in Org-mode."
1901 :tag "Org Priorities"
1902 :group 'org-todo)
1904 (defcustom org-highest-priority ?A
1905 "The highest priority of TODO items. A character like ?A, ?B etc.
1906 Must have a smaller ASCII number than `org-lowest-priority'."
1907 :group 'org-priorities
1908 :type 'character)
1910 (defcustom org-lowest-priority ?C
1911 "The lowest priority of TODO items. A character like ?A, ?B etc.
1912 Must have a larger ASCII number than `org-highest-priority'."
1913 :group 'org-priorities
1914 :type 'character)
1916 (defcustom org-default-priority ?B
1917 "The default priority of TODO items.
1918 This is the priority an item get if no explicit priority is given."
1919 :group 'org-priorities
1920 :type 'character)
1922 (defcustom org-priority-start-cycle-with-default t
1923 "Non-nil means, start with default priority when starting to cycle.
1924 When this is nil, the first step in the cycle will be (depending on the
1925 command used) one higher or lower that the default priority."
1926 :group 'org-priorities
1927 :type 'boolean)
1929 (defgroup org-time nil
1930 "Options concerning time stamps and deadlines in Org-mode."
1931 :tag "Org Time"
1932 :group 'org)
1934 (defcustom org-insert-labeled-timestamps-at-point nil
1935 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1936 When nil, these labeled time stamps are forces into the second line of an
1937 entry, just after the headline. When scheduling from the global TODO list,
1938 the time stamp will always be forced into the second line."
1939 :group 'org-time
1940 :type 'boolean)
1942 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1943 "Formats for `format-time-string' which are used for time stamps.
1944 It is not recommended to change this constant.")
1946 (defcustom org-time-stamp-rounding-minutes '(0 5)
1947 "Number of minutes to round time stamps to.
1948 These are two values, the first applies when first creating a time stamp.
1949 The second applies when changing it with the commands `S-up' and `S-down'.
1950 When changing the time stamp, this means that it will change in steps
1951 of N minutes, as given by the second value.
1953 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1954 numbers should be factors of 60, so for example 5, 10, 15.
1956 When this is larger than 1, you can still force an exact time-stamp by using
1957 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1958 and by using a prefix arg to `S-up/down' to specify the exact number
1959 of minutes to shift."
1960 :group 'org-time
1961 :get '(lambda (var) ; Make sure all entries have 5 elements
1962 (if (integerp (default-value var))
1963 (list (default-value var) 5)
1964 (default-value var)))
1965 :type '(list
1966 (integer :tag "when inserting times")
1967 (integer :tag "when modifying times")))
1969 ;; Normalize old customizations of this variable.
1970 (when (integerp org-time-stamp-rounding-minutes)
1971 (setq org-time-stamp-rounding-minutes
1972 (list org-time-stamp-rounding-minutes
1973 org-time-stamp-rounding-minutes)))
1975 (defcustom org-display-custom-times nil
1976 "Non-nil means, overlay custom formats over all time stamps.
1977 The formats are defined through the variable `org-time-stamp-custom-formats'.
1978 To turn this on on a per-file basis, insert anywhere in the file:
1979 #+STARTUP: customtime"
1980 :group 'org-time
1981 :set 'set-default
1982 :type 'sexp)
1983 (make-variable-buffer-local 'org-display-custom-times)
1985 (defcustom org-time-stamp-custom-formats
1986 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1987 "Custom formats for time stamps. See `format-time-string' for the syntax.
1988 These are overlayed over the default ISO format if the variable
1989 `org-display-custom-times' is set. Time like %H:%M should be at the
1990 end of the second format."
1991 :group 'org-time
1992 :type 'sexp)
1994 (defun org-time-stamp-format (&optional long inactive)
1995 "Get the right format for a time string."
1996 (let ((f (if long (cdr org-time-stamp-formats)
1997 (car org-time-stamp-formats))))
1998 (if inactive
1999 (concat "[" (substring f 1 -1) "]")
2000 f)))
2002 (defcustom org-time-clocksum-format "%d:%02d"
2003 "The format string used when creating CLOCKSUM lines, or when
2004 org-mode generates a time duration."
2005 :group 'org-time
2006 :type 'string)
2008 (defcustom org-deadline-warning-days 14
2009 "No. of days before expiration during which a deadline becomes active.
2010 This variable governs the display in sparse trees and in the agenda.
2011 When 0 or negative, it means use this number (the absolute value of it)
2012 even if a deadline has a different individual lead time specified.
2014 Custom commands can set this variable in the options section."
2015 :group 'org-time
2016 :group 'org-agenda-daily/weekly
2017 :type 'number)
2019 (defcustom org-read-date-prefer-future t
2020 "Non-nil means, assume future for incomplete date input from user.
2021 This affects the following situations:
2022 1. The user gives a day, but no month.
2023 For example, if today is the 15th, and you enter \"3\", Org-mode will
2024 read this as the third of *next* month. However, if you enter \"17\",
2025 it will be considered as *this* month.
2026 2. The user gives a month but not a year.
2027 For example, if it is april and you enter \"feb 2\", this will be read
2028 as feb 2, *next* year. \"May 5\", however, will be this year.
2030 Currently this does not work for ISO week specifications.
2032 When this option is nil, the current month and year will always be used
2033 as defaults."
2034 :group 'org-time
2035 :type 'boolean)
2037 (defcustom org-read-date-display-live t
2038 "Non-nil means, display current interpretation of date prompt live.
2039 This display will be in an overlay, in the minibuffer."
2040 :group 'org-time
2041 :type 'boolean)
2043 (defcustom org-read-date-popup-calendar t
2044 "Non-nil means, pop up a calendar when prompting for a date.
2045 In the calendar, the date can be selected with mouse-1. However, the
2046 minibuffer will also be active, and you can simply enter the date as well.
2047 When nil, only the minibuffer will be available."
2048 :group 'org-time
2049 :type 'boolean)
2050 (if (fboundp 'defvaralias)
2051 (defvaralias 'org-popup-calendar-for-date-prompt
2052 'org-read-date-popup-calendar))
2054 (defcustom org-extend-today-until 0
2055 "The hour when your day really ends. Must be an integer.
2056 This has influence for the following applications:
2057 - When switching the agenda to \"today\". It it is still earlier than
2058 the time given here, the day recognized as TODAY is actually yesterday.
2059 - When a date is read from the user and it is still before the time given
2060 here, the current date and time will be assumed to be yesterday, 23:59.
2061 Also, timestamps inserted in remember templates follow this rule.
2063 IMPORTANT: This is a feature whose implementation is and likely will
2064 remain incomplete. Really, it is only here because past midnight seems to
2065 be the favorite working time of John Wiegley :-)"
2066 :group 'org-time
2067 :type 'number)
2069 (defcustom org-edit-timestamp-down-means-later nil
2070 "Non-nil means, S-down will increase the time in a time stamp.
2071 When nil, S-up will increase."
2072 :group 'org-time
2073 :type 'boolean)
2075 (defcustom org-calendar-follow-timestamp-change t
2076 "Non-nil means, make the calendar window follow timestamp changes.
2077 When a timestamp is modified and the calendar window is visible, it will be
2078 moved to the new date."
2079 :group 'org-time
2080 :type 'boolean)
2082 (defgroup org-tags nil
2083 "Options concerning tags in Org-mode."
2084 :tag "Org Tags"
2085 :group 'org)
2087 (defcustom org-tag-alist nil
2088 "List of tags allowed in Org-mode files.
2089 When this list is nil, Org-mode will base TAG input on what is already in the
2090 buffer.
2091 The value of this variable is an alist, the car of each entry must be a
2092 keyword as a string, the cdr may be a character that is used to select
2093 that tag through the fast-tag-selection interface.
2094 See the manual for details."
2095 :group 'org-tags
2096 :type '(repeat
2097 (choice
2098 (cons (string :tag "Tag name")
2099 (character :tag "Access char"))
2100 (const :tag "Start radio group" (:startgroup))
2101 (const :tag "End radio group" (:endgroup))
2102 (const :tag "New line" (:newline)))))
2104 (defcustom org-tag-persistent-alist nil
2105 "List of tags that will always appear in all Org-mode files.
2106 This is in addition to any in buffer settings or customizations
2107 of `org-tag-alist'.
2108 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2109 The value of this variable is an alist, the car of each entry must be a
2110 keyword as a string, the cdr may be a character that is used to select
2111 that tag through the fast-tag-selection interface.
2112 See the manual for details.
2113 To disable these tags on a per-file basis, insert anywhere in the file:
2114 #+STARTUP: noptag"
2115 :group 'org-tags
2116 :type '(repeat
2117 (choice
2118 (cons (string :tag "Tag name")
2119 (character :tag "Access char"))
2120 (const :tag "Start radio group" (:startgroup))
2121 (const :tag "End radio group" (:endgroup))
2122 (const :tag "New line" (:newline)))))
2124 (defvar org-file-tags nil
2125 "List of tags that can be inherited by all entries in the file.
2126 The tags will be inherited if the variable `org-use-tag-inheritance'
2127 says they should be.
2128 This variable is populated from #+TAG lines.")
2130 (defcustom org-use-fast-tag-selection 'auto
2131 "Non-nil means, use fast tag selection scheme.
2132 This is a special interface to select and deselect tags with single keys.
2133 When nil, fast selection is never used.
2134 When the symbol `auto', fast selection is used if and only if selection
2135 characters for tags have been configured, either through the variable
2136 `org-tag-alist' or through a #+TAGS line in the buffer.
2137 When t, fast selection is always used and selection keys are assigned
2138 automatically if necessary."
2139 :group 'org-tags
2140 :type '(choice
2141 (const :tag "Always" t)
2142 (const :tag "Never" nil)
2143 (const :tag "When selection characters are configured" 'auto)))
2145 (defcustom org-fast-tag-selection-single-key nil
2146 "Non-nil means, fast tag selection exits after first change.
2147 When nil, you have to press RET to exit it.
2148 During fast tag selection, you can toggle this flag with `C-c'.
2149 This variable can also have the value `expert'. In this case, the window
2150 displaying the tags menu is not even shown, until you press C-c again."
2151 :group 'org-tags
2152 :type '(choice
2153 (const :tag "No" nil)
2154 (const :tag "Yes" t)
2155 (const :tag "Expert" expert)))
2157 (defvar org-fast-tag-selection-include-todo nil
2158 "Non-nil means, fast tags selection interface will also offer TODO states.
2159 This is an undocumented feature, you should not rely on it.")
2161 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2162 "The column to which tags should be indented in a headline.
2163 If this number is positive, it specifies the column. If it is negative,
2164 it means that the tags should be flushright to that column. For example,
2165 -80 works well for a normal 80 character screen."
2166 :group 'org-tags
2167 :type 'integer)
2169 (defcustom org-auto-align-tags t
2170 "Non-nil means, realign tags after pro/demotion of TODO state change.
2171 These operations change the length of a headline and therefore shift
2172 the tags around. With this options turned on, after each such operation
2173 the tags are again aligned to `org-tags-column'."
2174 :group 'org-tags
2175 :type 'boolean)
2177 (defcustom org-use-tag-inheritance t
2178 "Non-nil means, tags in levels apply also for sublevels.
2179 When nil, only the tags directly given in a specific line apply there.
2180 This may also be a list of tags that should be inherited, or a regexp that
2181 matches tags that should be inherited. Additional control is possible
2182 with the variable `org-tags-exclude-from-inheritance' which gives an
2183 explicit list of tags to be excluded from inheritance., even if the value of
2184 `org-use-tag-inheritance' would select it for inheritance.
2186 If this option is t, a match early-on in a tree can lead to a large
2187 number of matches in the subtree when constructing the agenda or creating
2188 a sparse tree. If you only want to see the first match in a tree during
2189 a search, check out the variable `org-tags-match-list-sublevels'."
2190 :group 'org-tags
2191 :type '(choice
2192 (const :tag "Not" nil)
2193 (const :tag "Always" t)
2194 (repeat :tag "Specific tags" (string :tag "Tag"))
2195 (regexp :tag "Tags matched by regexp")))
2197 (defcustom org-tags-exclude-from-inheritance nil
2198 "List of tags that should never be inherited.
2199 This is a way to exclude a few tags from inheritance. For way to do
2200 the opposite, to actively allow inheritance for selected tags,
2201 see the variable `org-use-tag-inheritance'."
2202 :group 'org-tags
2203 :type '(repeat (string :tag "Tag")))
2205 (defun org-tag-inherit-p (tag)
2206 "Check if TAG is one that should be inherited."
2207 (cond
2208 ((member tag org-tags-exclude-from-inheritance) nil)
2209 ((eq org-use-tag-inheritance t) t)
2210 ((not org-use-tag-inheritance) nil)
2211 ((stringp org-use-tag-inheritance)
2212 (string-match org-use-tag-inheritance tag))
2213 ((listp org-use-tag-inheritance)
2214 (member tag org-use-tag-inheritance))
2215 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2217 (defcustom org-tags-match-list-sublevels t
2218 "Non-nil means list also sublevels of headlines matching tag search.
2219 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2220 the sublevels of a headline matching a tag search often also match
2221 the same search. Listing all of them can create very long lists.
2222 Setting this variable to nil causes subtrees of a match to be skipped.
2223 This option is off by default, because inheritance in on. If you turn
2224 inheritance off, you very likely want to turn this option on.
2226 As a special case, if the tag search is restricted to TODO items, the
2227 value of this variable is ignored and sublevels are always checked, to
2228 make sure all corresponding TODO items find their way into the list.
2230 This variable is semi-obsolete and probably should always be true. It
2231 is better to limit inheritance to certain tags using the variables
2232 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2233 :group 'org-tags
2234 :type 'boolean)
2236 (defvar org-tags-history nil
2237 "History of minibuffer reads for tags.")
2238 (defvar org-last-tags-completion-table nil
2239 "The last used completion table for tags.")
2240 (defvar org-after-tags-change-hook nil
2241 "Hook that is run after the tags in a line have changed.")
2243 (defgroup org-properties nil
2244 "Options concerning properties in Org-mode."
2245 :tag "Org Properties"
2246 :group 'org)
2248 (defcustom org-property-format "%-10s %s"
2249 "How property key/value pairs should be formatted by `indent-line'.
2250 When `indent-line' hits a property definition, it will format the line
2251 according to this format, mainly to make sure that the values are
2252 lined-up with respect to each other."
2253 :group 'org-properties
2254 :type 'string)
2256 (defcustom org-use-property-inheritance nil
2257 "Non-nil means, properties apply also for sublevels.
2259 This setting is chiefly used during property searches. Turning it on can
2260 cause significant overhead when doing a search, which is why it is not
2261 on by default.
2263 When nil, only the properties directly given in the current entry count.
2264 When t, every property is inherited. The value may also be a list of
2265 properties that should have inheritance, or a regular expression matching
2266 properties that should be inherited.
2268 However, note that some special properties use inheritance under special
2269 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2270 and the properties ending in \"_ALL\" when they are used as descriptor
2271 for valid values of a property.
2273 Note for programmers:
2274 When querying an entry with `org-entry-get', you can control if inheritance
2275 should be used. By default, `org-entry-get' looks only at the local
2276 properties. You can request inheritance by setting the inherit argument
2277 to t (to force inheritance) or to `selective' (to respect the setting
2278 in this variable)."
2279 :group 'org-properties
2280 :type '(choice
2281 (const :tag "Not" nil)
2282 (const :tag "Always" t)
2283 (repeat :tag "Specific properties" (string :tag "Property"))
2284 (regexp :tag "Properties matched by regexp")))
2286 (defun org-property-inherit-p (property)
2287 "Check if PROPERTY is one that should be inherited."
2288 (cond
2289 ((eq org-use-property-inheritance t) t)
2290 ((not org-use-property-inheritance) nil)
2291 ((stringp org-use-property-inheritance)
2292 (string-match org-use-property-inheritance property))
2293 ((listp org-use-property-inheritance)
2294 (member property org-use-property-inheritance))
2295 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2297 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2298 "The default column format, if no other format has been defined.
2299 This variable can be set on the per-file basis by inserting a line
2301 #+COLUMNS: %25ITEM ....."
2302 :group 'org-properties
2303 :type 'string)
2305 (defcustom org-columns-ellipses ".."
2306 "The ellipses to be used when a field in column view is truncated.
2307 When this is the empty string, as many characters as possible are shown,
2308 but then there will be no visual indication that the field has been truncated.
2309 When this is a string of length N, the last N characters of a truncated
2310 field are replaced by this string. If the column is narrower than the
2311 ellipses string, only part of the ellipses string will be shown."
2312 :group 'org-properties
2313 :type 'string)
2315 (defcustom org-columns-modify-value-for-display-function nil
2316 "Function that modifies values for display in column view.
2317 For example, it can be used to cut out a certain part from a time stamp.
2318 The function must take 2 arguments:
2320 column-title The title of the column (*not* the property name)
2321 value The value that should be modified.
2323 The function should return the value that should be displayed,
2324 or nil if the normal value should be used."
2325 :group 'org-properties
2326 :type 'function)
2328 (defcustom org-effort-property "Effort"
2329 "The property that is being used to keep track of effort estimates.
2330 Effort estimates given in this property need to have the format H:MM."
2331 :group 'org-properties
2332 :group 'org-progress
2333 :type '(string :tag "Property"))
2335 (defconst org-global-properties-fixed
2336 '(("VISIBILITY_ALL" . "folded children content all"))
2337 "List of property/value pairs that can be inherited by any entry.
2339 These are fixed values, for the preset properties. The user variable
2340 that can be used to add to this list is `org-global-properties'.
2342 The entries in this list are cons cells where the car is a property
2343 name and cdr is a string with the value. If the value represents
2344 multiple items like an \"_ALL\" property, separate the items by
2345 spaces.")
2347 (defcustom org-global-properties nil
2348 "List of property/value pairs that can be inherited by any entry.
2350 This list will be combined with the constant `org-global-properties-fixed'.
2352 The entries in this list are cons cells where the car is a property
2353 name and cdr is a string with the value.
2355 You can set buffer-local values for the same purpose in the variable
2356 `org-file-properties' this by adding lines like
2358 #+PROPERTY: NAME VALUE"
2359 :group 'org-properties
2360 :type '(repeat
2361 (cons (string :tag "Property")
2362 (string :tag "Value"))))
2364 (defvar org-file-properties nil
2365 "List of property/value pairs that can be inherited by any entry.
2366 Valid for the current buffer.
2367 This variable is populated from #+PROPERTY lines.")
2368 (make-variable-buffer-local 'org-file-properties)
2370 (defgroup org-agenda nil
2371 "Options concerning agenda views in Org-mode."
2372 :tag "Org Agenda"
2373 :group 'org)
2375 (defvar org-category nil
2376 "Variable used by org files to set a category for agenda display.
2377 Such files should use a file variable to set it, for example
2379 # -*- mode: org; org-category: \"ELisp\"
2381 or contain a special line
2383 #+CATEGORY: ELisp
2385 If the file does not specify a category, then file's base name
2386 is used instead.")
2387 (make-variable-buffer-local 'org-category)
2388 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2390 (defcustom org-agenda-files nil
2391 "The files to be used for agenda display.
2392 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2393 \\[org-remove-file]. You can also use customize to edit the list.
2395 If an entry is a directory, all files in that directory that are matched by
2396 `org-agenda-file-regexp' will be part of the file list.
2398 If the value of the variable is not a list but a single file name, then
2399 the list of agenda files is actually stored and maintained in that file, one
2400 agenda file per line."
2401 :group 'org-agenda
2402 :type '(choice
2403 (repeat :tag "List of files and directories" file)
2404 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2406 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2407 "Regular expression to match files for `org-agenda-files'.
2408 If any element in the list in that variable contains a directory instead
2409 of a normal file, all files in that directory that are matched by this
2410 regular expression will be included."
2411 :group 'org-agenda
2412 :type 'regexp)
2414 (defcustom org-agenda-text-search-extra-files nil
2415 "List of extra files to be searched by text search commands.
2416 These files will be search in addition to the agenda files by the
2417 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2418 Note that these files will only be searched for text search commands,
2419 not for the other agenda views like todo lists, tag searches or the weekly
2420 agenda. This variable is intended to list notes and possibly archive files
2421 that should also be searched by these two commands.
2422 In fact, if the first element in the list is the symbol `agenda-archives',
2423 than all archive files of all agenda files will be added to the search
2424 scope."
2425 :group 'org-agenda
2426 :type '(set :greedy t
2427 (const :tag "Agenda Archives" agenda-archives)
2428 (repeat :inline t (file))))
2430 (if (fboundp 'defvaralias)
2431 (defvaralias 'org-agenda-multi-occur-extra-files
2432 'org-agenda-text-search-extra-files))
2434 (defcustom org-agenda-skip-unavailable-files nil
2435 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2436 A nil value means to remove them, after a query, from the list."
2437 :group 'org-agenda
2438 :type 'boolean)
2440 (defcustom org-calendar-to-agenda-key [?c]
2441 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2442 The command `org-calendar-goto-agenda' will be bound to this key. The
2443 default is the character `c' because then `c' can be used to switch back and
2444 forth between agenda and calendar."
2445 :group 'org-agenda
2446 :type 'sexp)
2448 (defcustom org-calendar-agenda-action-key [?k]
2449 "The key to be installed in `calendar-mode-map' for agenda-action.
2450 The command `org-agenda-action' will be bound to this key. The
2451 default is the character `k' because we use the same key in the agenda."
2452 :group 'org-agenda
2453 :type 'sexp)
2455 (eval-after-load "calendar"
2456 '(progn
2457 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2458 'org-calendar-goto-agenda)
2459 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2460 'org-agenda-action)))
2462 (defgroup org-latex nil
2463 "Options for embedding LaTeX code into Org-mode."
2464 :tag "Org LaTeX"
2465 :group 'org)
2467 (defcustom org-format-latex-options
2468 '(:foreground default :background default :scale 1.0
2469 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2470 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2471 "Options for creating images from LaTeX fragments.
2472 This is a property list with the following properties:
2473 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2474 `default' means use the foreground of the default face.
2475 :background the background color, or \"Transparent\".
2476 `default' means use the background of the default face.
2477 :scale a scaling factor for the size of the images.
2478 :html-foreground, :html-background, :html-scale
2479 the same numbers for HTML export.
2480 :matchers a list indicating which matchers should be used to
2481 find LaTeX fragments. Valid members of this list are:
2482 \"begin\" find environments
2483 \"$1\" find single characters surrounded by $.$
2484 \"$\" find math expressions surrounded by $...$
2485 \"$$\" find math expressions surrounded by $$....$$
2486 \"\\(\" find math expressions surrounded by \\(...\\)
2487 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2488 :group 'org-latex
2489 :type 'plist)
2491 (defcustom org-format-latex-header "\\documentclass{article}
2492 \\usepackage{fullpage} % do not remove
2493 \\usepackage{amssymb}
2494 \\usepackage[usenames]{color}
2495 \\usepackage{amsmath}
2496 \\usepackage{latexsym}
2497 \\usepackage[mathscr]{eucal}
2498 \\pagestyle{empty} % do not remove"
2499 "The document header used for processing LaTeX fragments."
2500 :group 'org-latex
2501 :type 'string)
2504 (defgroup org-font-lock nil
2505 "Font-lock settings for highlighting in Org-mode."
2506 :tag "Org Font Lock"
2507 :group 'org)
2509 (defcustom org-level-color-stars-only nil
2510 "Non-nil means fontify only the stars in each headline.
2511 When nil, the entire headline is fontified.
2512 Changing it requires restart of `font-lock-mode' to become effective
2513 also in regions already fontified."
2514 :group 'org-font-lock
2515 :type 'boolean)
2517 (defcustom org-hide-leading-stars nil
2518 "Non-nil means, hide the first N-1 stars in a headline.
2519 This works by using the face `org-hide' for these stars. This
2520 face is white for a light background, and black for a dark
2521 background. You may have to customize the face `org-hide' to
2522 make this work.
2523 Changing it requires restart of `font-lock-mode' to become effective
2524 also in regions already fontified.
2525 You may also set this on a per-file basis by adding one of the following
2526 lines to the buffer:
2528 #+STARTUP: hidestars
2529 #+STARTUP: showstars"
2530 :group 'org-font-lock
2531 :type 'boolean)
2533 (defcustom org-fontify-done-headline nil
2534 "Non-nil means, change the face of a headline if it is marked DONE.
2535 Normally, only the TODO/DONE keyword indicates the state of a headline.
2536 When this is non-nil, the headline after the keyword is set to the
2537 `org-headline-done' as an additional indication."
2538 :group 'org-font-lock
2539 :type 'boolean)
2541 (defcustom org-fontify-emphasized-text t
2542 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2543 Changing this variable requires a restart of Emacs to take effect."
2544 :group 'org-font-lock
2545 :type 'boolean)
2547 (defcustom org-highlight-latex-fragments-and-specials nil
2548 "Non-nil means, fontify what is treated specially by the exporters."
2549 :group 'org-font-lock
2550 :type 'boolean)
2552 (defcustom org-hide-emphasis-markers nil
2553 "Non-nil mean font-lock should hide the emphasis marker characters."
2554 :group 'org-font-lock
2555 :type 'boolean)
2557 (defvar org-emph-re nil
2558 "Regular expression for matching emphasis.")
2559 (defvar org-verbatim-re nil
2560 "Regular expression for matching verbatim text.")
2561 (defvar org-emphasis-regexp-components) ; defined just below
2562 (defvar org-emphasis-alist) ; defined just below
2563 (defun org-set-emph-re (var val)
2564 "Set variable and compute the emphasis regular expression."
2565 (set var val)
2566 (when (and (boundp 'org-emphasis-alist)
2567 (boundp 'org-emphasis-regexp-components)
2568 org-emphasis-alist org-emphasis-regexp-components)
2569 (let* ((e org-emphasis-regexp-components)
2570 (pre (car e))
2571 (post (nth 1 e))
2572 (border (nth 2 e))
2573 (body (nth 3 e))
2574 (nl (nth 4 e))
2575 (body1 (concat body "*?"))
2576 (markers (mapconcat 'car org-emphasis-alist ""))
2577 (vmarkers (mapconcat
2578 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2579 org-emphasis-alist "")))
2580 ;; make sure special characters appear at the right position in the class
2581 (if (string-match "\\^" markers)
2582 (setq markers (concat (replace-match "" t t markers) "^")))
2583 (if (string-match "-" markers)
2584 (setq markers (concat (replace-match "" t t markers) "-")))
2585 (if (string-match "\\^" vmarkers)
2586 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2587 (if (string-match "-" vmarkers)
2588 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2589 (if (> nl 0)
2590 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2591 (int-to-string nl) "\\}")))
2592 ;; Make the regexp
2593 (setq org-emph-re
2594 (concat "\\([" pre "]\\|^\\)"
2595 "\\("
2596 "\\([" markers "]\\)"
2597 "\\("
2598 "[^" border "]\\|"
2599 "[^" border "]"
2600 body1
2601 "[^" border "]"
2602 "\\)"
2603 "\\3\\)"
2604 "\\([" post "]\\|$\\)"))
2605 (setq org-verbatim-re
2606 (concat "\\([" pre "]\\|^\\)"
2607 "\\("
2608 "\\([" vmarkers "]\\)"
2609 "\\("
2610 "[^" border "]\\|"
2611 "[^" border "]"
2612 body1
2613 "[^" border "]"
2614 "\\)"
2615 "\\3\\)"
2616 "\\([" post "]\\|$\\)")))))
2618 (defcustom org-emphasis-regexp-components
2619 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2620 "Components used to build the regular expression for emphasis.
2621 This is a list with 6 entries. Terminology: In an emphasis string
2622 like \" *strong word* \", we call the initial space PREMATCH, the final
2623 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2624 and \"trong wor\" is the body. The different components in this variable
2625 specify what is allowed/forbidden in each part:
2627 pre Chars allowed as prematch. Beginning of line will be allowed too.
2628 post Chars allowed as postmatch. End of line will be allowed too.
2629 border The chars *forbidden* as border characters.
2630 body-regexp A regexp like \".\" to match a body character. Don't use
2631 non-shy groups here, and don't allow newline here.
2632 newline The maximum number of newlines allowed in an emphasis exp.
2634 Use customize to modify this, or restart Emacs after changing it."
2635 :group 'org-font-lock
2636 :set 'org-set-emph-re
2637 :type '(list
2638 (sexp :tag "Allowed chars in pre ")
2639 (sexp :tag "Allowed chars in post ")
2640 (sexp :tag "Forbidden chars in border ")
2641 (sexp :tag "Regexp for body ")
2642 (integer :tag "number of newlines allowed")
2643 (option (boolean :tag "Please ignore this button"))))
2645 (defcustom org-emphasis-alist
2646 `(("*" bold "<b>" "</b>")
2647 ("/" italic "<i>" "</i>")
2648 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2649 ("=" org-code "<code>" "</code>" verbatim)
2650 ("~" org-verbatim "<code>" "</code>" verbatim)
2651 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2652 "<del>" "</del>")
2654 "Special syntax for emphasized text.
2655 Text starting and ending with a special character will be emphasized, for
2656 example *bold*, _underlined_ and /italic/. This variable sets the marker
2657 characters, the face to be used by font-lock for highlighting in Org-mode
2658 Emacs buffers, and the HTML tags to be used for this.
2659 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2660 Use customize to modify this, or restart Emacs after changing it."
2661 :group 'org-font-lock
2662 :set 'org-set-emph-re
2663 :type '(repeat
2664 (list
2665 (string :tag "Marker character")
2666 (choice
2667 (face :tag "Font-lock-face")
2668 (plist :tag "Face property list"))
2669 (string :tag "HTML start tag")
2670 (string :tag "HTML end tag")
2671 (option (const verbatim)))))
2673 ;;; Miscellaneous options
2675 (defgroup org-completion nil
2676 "Completion in Org-mode."
2677 :tag "Org Completion"
2678 :group 'org)
2680 (defcustom org-completion-use-ido nil
2681 "Non-nil means, use ido completion wherever possible.
2682 Note that `ido-mode' must be active for this variable to be relevant.
2683 If you decide to turn this variable on, you might well want to turn off
2684 `org-outline-path-complete-in-steps'."
2685 :group 'org-completion
2686 :type 'boolean)
2688 (defcustom org-completion-fallback-command 'hippie-expand
2689 "The expansion command called by \\[org-complete] in normal context.
2690 Normal means, no org-mode-specific context."
2691 :group 'org-completion
2692 :type 'function)
2694 ;;; Functions and variables from ther packages
2695 ;; Declared here to avoid compiler warnings
2697 ;; XEmacs only
2698 (defvar outline-mode-menu-heading)
2699 (defvar outline-mode-menu-show)
2700 (defvar outline-mode-menu-hide)
2701 (defvar zmacs-regions) ; XEmacs regions
2703 ;; Emacs only
2704 (defvar mark-active)
2706 ;; Various packages
2707 (declare-function find-library-name "find-func" (library))
2708 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2709 (declare-function calendar-forward-day "cal-move" (arg))
2710 (declare-function calendar-goto-date "cal-move" (date))
2711 (declare-function calendar-goto-today "cal-move" ())
2712 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2713 (defvar calc-embedded-close-formula)
2714 (defvar calc-embedded-open-formula)
2715 (declare-function cdlatex-tab "ext:cdlatex" ())
2716 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2717 (defvar font-lock-unfontify-region-function)
2718 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2719 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2720 (defvar iswitchb-temp-buflist)
2721 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2722 (defvar org-agenda-tags-todo-honor-ignore-options)
2723 (declare-function org-agenda-skip "org-agenda" ())
2724 (declare-function org-format-agenda-item "org-agenda"
2725 (extra txt &optional category tags dotime noprefix remove-re))
2726 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2727 (declare-function org-agenda-change-all-lines "org-agenda"
2728 (newhead hdmarker &optional fixface just-this))
2729 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2730 (declare-function org-agenda-maybe-redo "org-agenda" ())
2731 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2732 (beg end))
2733 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2734 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2735 "org-agenda" (&optional end))
2737 (declare-function parse-time-string "parse-time" (string))
2738 (declare-function remember "remember" (&optional initial))
2739 (declare-function remember-buffer-desc "remember" ())
2740 (declare-function remember-finalize "remember" ())
2741 (defvar remember-save-after-remembering)
2742 (defvar remember-data-file)
2743 (defvar remember-register)
2744 (defvar remember-buffer)
2745 (defvar remember-handler-functions)
2746 (defvar remember-annotation-functions)
2747 (defvar texmathp-why)
2748 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2749 (declare-function table--at-cell-p "table" (position &optional object at-column))
2751 (defvar w3m-current-url)
2752 (defvar w3m-current-title)
2754 (defvar org-latex-regexps)
2756 ;;; Autoload and prepare some org modules
2758 ;; Some table stuff that needs to be defined here, because it is used
2759 ;; by the functions setting up org-mode or checking for table context.
2761 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2762 "Detects an org-type or table-type table.")
2763 (defconst org-table-line-regexp "^[ \t]*|"
2764 "Detects an org-type table line.")
2765 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2766 "Detects an org-type table line.")
2767 (defconst org-table-hline-regexp "^[ \t]*|-"
2768 "Detects an org-type table hline.")
2769 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2770 "Detects a table-type table hline.")
2771 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2772 "Searching from within a table (any type) this finds the first line
2773 outside the table.")
2775 ;; Autoload the functions in org-table.el that are needed by functions here.
2777 (eval-and-compile
2778 (org-autoload "org-table"
2779 '(org-table-align org-table-begin org-table-blank-field
2780 org-table-convert org-table-convert-region org-table-copy-down
2781 org-table-copy-region org-table-create
2782 org-table-create-or-convert-from-region
2783 org-table-create-with-table.el org-table-current-dline
2784 org-table-cut-region org-table-delete-column org-table-edit-field
2785 org-table-edit-formulas org-table-end org-table-eval-formula
2786 org-table-export org-table-field-info
2787 org-table-get-stored-formulas org-table-goto-column
2788 org-table-hline-and-move org-table-import org-table-insert-column
2789 org-table-insert-hline org-table-insert-row org-table-iterate
2790 org-table-justify-field-maybe org-table-kill-row
2791 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2792 org-table-move-column org-table-move-column-left
2793 org-table-move-column-right org-table-move-row
2794 org-table-move-row-down org-table-move-row-up
2795 org-table-next-field org-table-next-row org-table-paste-rectangle
2796 org-table-previous-field org-table-recalculate
2797 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2798 org-table-toggle-coordinate-overlays
2799 org-table-toggle-formula-debugger org-table-wrap-region
2800 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2802 (defun org-at-table-p (&optional table-type)
2803 "Return t if the cursor is inside an org-type table.
2804 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2805 (if org-enable-table-editor
2806 (save-excursion
2807 (beginning-of-line 1)
2808 (looking-at (if table-type org-table-any-line-regexp
2809 org-table-line-regexp)))
2810 nil))
2811 (defsubst org-table-p () (org-at-table-p))
2813 (defun org-at-table.el-p ()
2814 "Return t if and only if we are at a table.el table."
2815 (and (org-at-table-p 'any)
2816 (save-excursion
2817 (goto-char (org-table-begin 'any))
2818 (looking-at org-table1-hline-regexp))))
2819 (defun org-table-recognize-table.el ()
2820 "If there is a table.el table nearby, recognize it and move into it."
2821 (if org-table-tab-recognizes-table.el
2822 (if (org-at-table.el-p)
2823 (progn
2824 (beginning-of-line 1)
2825 (if (looking-at org-table-dataline-regexp)
2827 (if (looking-at org-table1-hline-regexp)
2828 (progn
2829 (beginning-of-line 2)
2830 (if (looking-at org-table-any-border-regexp)
2831 (beginning-of-line -1)))))
2832 (if (re-search-forward "|" (org-table-end t) t)
2833 (progn
2834 (require 'table)
2835 (if (table--at-cell-p (point))
2837 (message "recognizing table.el table...")
2838 (table-recognize-table)
2839 (message "recognizing table.el table...done")))
2840 (error "This should not happen..."))
2842 nil)
2843 nil))
2845 (defun org-at-table-hline-p ()
2846 "Return t if the cursor is inside a hline in a table."
2847 (if org-enable-table-editor
2848 (save-excursion
2849 (beginning-of-line 1)
2850 (looking-at org-table-hline-regexp))
2851 nil))
2853 (defvar org-table-clean-did-remove-column nil)
2855 (defun org-table-map-tables (function)
2856 "Apply FUNCTION to the start of all tables in the buffer."
2857 (save-excursion
2858 (save-restriction
2859 (widen)
2860 (goto-char (point-min))
2861 (while (re-search-forward org-table-any-line-regexp nil t)
2862 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2863 (beginning-of-line 1)
2864 (if (looking-at org-table-line-regexp)
2865 (save-excursion (funcall function)))
2866 (re-search-forward org-table-any-border-regexp nil 1))))
2867 (message "Mapping tables: done"))
2869 ;; Declare and autoload functions from org-exp.el
2871 (declare-function org-default-export-plist "org-exp")
2872 (declare-function org-infile-export-plist "org-exp")
2873 (declare-function org-get-current-options "org-exp")
2874 (eval-and-compile
2875 (org-autoload "org-exp"
2876 '(org-export org-export-as-ascii org-export-visible
2877 org-insert-export-options-template org-export-as-html-and-open
2878 org-export-as-html-batch org-export-as-html-to-buffer
2879 org-replace-region-by-html org-export-region-as-html
2880 org-export-as-html org-export-icalendar-this-file
2881 org-export-icalendar-all-agenda-files
2882 org-table-clean-before-export
2883 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2885 ;; Declare and autoload functions from org-agenda.el
2887 (eval-and-compile
2888 (org-autoload "org-agenda"
2889 '(org-agenda org-agenda-list org-search-view
2890 org-todo-list org-tags-view org-agenda-list-stuck-projects
2891 org-diary org-agenda-to-appt
2892 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2894 ;; Autoload org-remember
2896 (eval-and-compile
2897 (org-autoload "org-remember"
2898 '(org-remember-insinuate org-remember-annotation
2899 org-remember-apply-template org-remember org-remember-handler)))
2901 ;; Autoload org-clock.el
2904 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2905 (beg end))
2906 (declare-function org-clock-update-mode-line "org-clock" ())
2907 (defvar org-clock-start-time)
2908 (defvar org-clock-marker (make-marker)
2909 "Marker recording the last clock-in.")
2911 (eval-and-compile
2912 (org-autoload
2913 "org-clock"
2914 '(org-clock-in org-clock-out org-clock-cancel
2915 org-clock-goto org-clock-sum org-clock-display
2916 org-clock-remove-overlays org-clock-report
2917 org-clocktable-shift org-dblock-write:clocktable
2918 org-get-clocktable)))
2920 (defun org-clock-update-time-maybe ()
2921 "If this is a CLOCK line, update it and return t.
2922 Otherwise, return nil."
2923 (interactive)
2924 (save-excursion
2925 (beginning-of-line 1)
2926 (skip-chars-forward " \t")
2927 (when (looking-at org-clock-string)
2928 (let ((re (concat "[ \t]*" org-clock-string
2929 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2930 "\\([ \t]*=>.*\\)?\\)?"))
2931 ts te h m s neg)
2932 (cond
2933 ((not (looking-at re))
2934 nil)
2935 ((not (match-end 2))
2936 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2937 (> org-clock-marker (point))
2938 (<= org-clock-marker (point-at-eol)))
2939 ;; The clock is running here
2940 (setq org-clock-start-time
2941 (apply 'encode-time
2942 (org-parse-time-string (match-string 1))))
2943 (org-clock-update-mode-line)))
2945 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2946 (end-of-line 1)
2947 (setq ts (match-string 1)
2948 te (match-string 3))
2949 (setq s (- (time-to-seconds
2950 (apply 'encode-time (org-parse-time-string te)))
2951 (time-to-seconds
2952 (apply 'encode-time (org-parse-time-string ts))))
2953 neg (< s 0)
2954 s (abs s)
2955 h (floor (/ s 3600))
2956 s (- s (* 3600 h))
2957 m (floor (/ s 60))
2958 s (- s (* 60 s)))
2959 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2960 t))))))
2962 (defun org-check-running-clock ()
2963 "Check if the current buffer contains the running clock.
2964 If yes, offer to stop it and to save the buffer with the changes."
2965 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2966 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2967 (buffer-name))))
2968 (org-clock-out)
2969 (when (y-or-n-p "Save changed buffer?")
2970 (save-buffer))))
2972 (defun org-clocktable-try-shift (dir n)
2973 "Check if this line starts a clock table, if yes, shift the time block."
2974 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2975 (org-clocktable-shift dir n)))
2977 ;; Autoload org-timer.el
2979 ;(declare-function org-timer "org-timer")
2981 (eval-and-compile
2982 (org-autoload
2983 "org-timer"
2984 '(org-timer-start org-timer org-timer-item
2985 org-timer-change-times-in-region)))
2988 ;; Autoload archiving code
2989 ;; The stuff that is needed for cycling and tags has to be defined here.
2991 (defgroup org-archive nil
2992 "Options concerning archiving in Org-mode."
2993 :tag "Org Archive"
2994 :group 'org-structure)
2996 (defcustom org-archive-location "%s_archive::"
2997 "The location where subtrees should be archived.
2999 The value of this variable is a string, consisting of two parts,
3000 separated by a double-colon. The first part is a filename and
3001 the second part is a headline.
3003 When the filename is omitted, archiving happens in the same file.
3004 %s in the filename will be replaced by the current file
3005 name (without the directory part). Archiving to a different file
3006 is useful to keep archived entries from contributing to the
3007 Org-mode Agenda.
3009 The archived entries will be filed as subtrees of the specified
3010 headline. When the headline is omitted, the subtrees are simply
3011 filed away at the end of the file, as top-level entries. Also in
3012 the heading you can use %s to represent the file name, this can be
3013 useful when using the same archive for a number of different files.
3015 Here are a few examples:
3016 \"%s_archive::\"
3017 If the current file is Projects.org, archive in file
3018 Projects.org_archive, as top-level trees. This is the default.
3020 \"::* Archived Tasks\"
3021 Archive in the current file, under the top-level headline
3022 \"* Archived Tasks\".
3024 \"~/org/archive.org::\"
3025 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3027 \"~/org/archive.org::From %s\"
3028 Archive in file ~/org/archive.org (absolute path), und headlines
3029 \"From FILENAME\" where file name is the current file name.
3031 \"basement::** Finished Tasks\"
3032 Archive in file ./basement (relative path), as level 3 trees
3033 below the level 2 heading \"** Finished Tasks\".
3035 You may set this option on a per-file basis by adding to the buffer a
3036 line like
3038 #+ARCHIVE: basement::** Finished Tasks
3040 You may also define it locally for a subtree by setting an ARCHIVE property
3041 in the entry. If such a property is found in an entry, or anywhere up
3042 the hierarchy, it will be used."
3043 :group 'org-archive
3044 :type 'string)
3046 (defcustom org-archive-tag "ARCHIVE"
3047 "The tag that marks a subtree as archived.
3048 An archived subtree does not open during visibility cycling, and does
3049 not contribute to the agenda listings.
3050 After changing this, font-lock must be restarted in the relevant buffers to
3051 get the proper fontification."
3052 :group 'org-archive
3053 :group 'org-keywords
3054 :type 'string)
3056 (defcustom org-agenda-skip-archived-trees t
3057 "Non-nil means, the agenda will skip any items located in archived trees.
3058 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3059 variable is no longer recommended, you should leave it at the value t.
3060 Instead, use the key `v' to cycle the archives-mode in the agenda."
3061 :group 'org-archive
3062 :group 'org-agenda-skip
3063 :type 'boolean)
3065 (defcustom org-cycle-open-archived-trees nil
3066 "Non-nil means, `org-cycle' will open archived trees.
3067 An archived tree is a tree marked with the tag ARCHIVE.
3068 When nil, archived trees will stay folded. You can still open them with
3069 normal outline commands like `show-all', but not with the cycling commands."
3070 :group 'org-archive
3071 :group 'org-cycle
3072 :type 'boolean)
3074 (defcustom org-sparse-tree-open-archived-trees nil
3075 "Non-nil means sparse tree construction shows matches in archived trees.
3076 When nil, matches in these trees are highlighted, but the trees are kept in
3077 collapsed state."
3078 :group 'org-archive
3079 :group 'org-sparse-trees
3080 :type 'boolean)
3082 (defun org-cycle-hide-archived-subtrees (state)
3083 "Re-hide all archived subtrees after a visibility state change."
3084 (when (and (not org-cycle-open-archived-trees)
3085 (not (memq state '(overview folded))))
3086 (save-excursion
3087 (let* ((globalp (memq state '(contents all)))
3088 (beg (if globalp (point-min) (point)))
3089 (end (if globalp (point-max) (org-end-of-subtree t))))
3090 (org-hide-archived-subtrees beg end)
3091 (goto-char beg)
3092 (if (looking-at (concat ".*:" org-archive-tag ":"))
3093 (message "%s" (substitute-command-keys
3094 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3096 (defun org-force-cycle-archived ()
3097 "Cycle subtree even if it is archived."
3098 (interactive)
3099 (setq this-command 'org-cycle)
3100 (let ((org-cycle-open-archived-trees t))
3101 (call-interactively 'org-cycle)))
3103 (defun org-hide-archived-subtrees (beg end)
3104 "Re-hide all archived subtrees after a visibility state change."
3105 (save-excursion
3106 (let* ((re (concat ":" org-archive-tag ":")))
3107 (goto-char beg)
3108 (while (re-search-forward re end t)
3109 (and (org-on-heading-p) (hide-subtree))
3110 (org-end-of-subtree t)))))
3112 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3114 (eval-and-compile
3115 (org-autoload "org-archive"
3116 '(org-add-archive-files org-archive-subtree
3117 org-archive-to-archive-sibling org-toggle-archive-tag)))
3119 ;; Autoload Column View Code
3121 (declare-function org-columns-number-to-string "org-colview")
3122 (declare-function org-columns-get-format-and-top-level "org-colview")
3123 (declare-function org-columns-compute "org-colview")
3125 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3126 '(org-columns-number-to-string org-columns-get-format-and-top-level
3127 org-columns-compute org-agenda-columns org-columns-remove-overlays
3128 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3130 ;; Autoload ID code
3132 (declare-function org-id-store-link "org-id")
3133 (declare-function org-id-locations-load "org-id")
3134 (declare-function org-id-locations-save "org-id")
3135 (defvar org-id-track-globally)
3136 (org-autoload "org-id"
3137 '(org-id-get-create org-id-new org-id-copy org-id-get
3138 org-id-get-with-outline-path-completion
3139 org-id-get-with-outline-drilling
3140 org-id-goto org-id-find org-id-store-link))
3142 ;; Autoload Plotting Code
3144 (org-autoload "org-plot"
3145 '(org-plot/gnuplot))
3147 ;;; Variables for pre-computed regular expressions, all buffer local
3149 (defvar org-drawer-regexp nil
3150 "Matches first line of a hidden block.")
3151 (make-variable-buffer-local 'org-drawer-regexp)
3152 (defvar org-todo-regexp nil
3153 "Matches any of the TODO state keywords.")
3154 (make-variable-buffer-local 'org-todo-regexp)
3155 (defvar org-not-done-regexp nil
3156 "Matches any of the TODO state keywords except the last one.")
3157 (make-variable-buffer-local 'org-not-done-regexp)
3158 (defvar org-todo-line-regexp nil
3159 "Matches a headline and puts TODO state into group 2 if present.")
3160 (make-variable-buffer-local 'org-todo-line-regexp)
3161 (defvar org-complex-heading-regexp nil
3162 "Matches a headline and puts everything into groups:
3163 group 1: the stars
3164 group 2: The todo keyword, maybe
3165 group 3: Priority cookie
3166 group 4: True headline
3167 group 5: Tags")
3168 (make-variable-buffer-local 'org-complex-heading-regexp)
3169 (defvar org-todo-line-tags-regexp nil
3170 "Matches a headline and puts TODO state into group 2 if present.
3171 Also put tags into group 4 if tags are present.")
3172 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3173 (defvar org-nl-done-regexp nil
3174 "Matches newline followed by a headline with the DONE keyword.")
3175 (make-variable-buffer-local 'org-nl-done-regexp)
3176 (defvar org-looking-at-done-regexp nil
3177 "Matches the DONE keyword a point.")
3178 (make-variable-buffer-local 'org-looking-at-done-regexp)
3179 (defvar org-ds-keyword-length 12
3180 "Maximum length of the Deadline and SCHEDULED keywords.")
3181 (make-variable-buffer-local 'org-ds-keyword-length)
3182 (defvar org-deadline-regexp nil
3183 "Matches the DEADLINE keyword.")
3184 (make-variable-buffer-local 'org-deadline-regexp)
3185 (defvar org-deadline-time-regexp nil
3186 "Matches the DEADLINE keyword together with a time stamp.")
3187 (make-variable-buffer-local 'org-deadline-time-regexp)
3188 (defvar org-deadline-line-regexp nil
3189 "Matches the DEADLINE keyword and the rest of the line.")
3190 (make-variable-buffer-local 'org-deadline-line-regexp)
3191 (defvar org-scheduled-regexp nil
3192 "Matches the SCHEDULED keyword.")
3193 (make-variable-buffer-local 'org-scheduled-regexp)
3194 (defvar org-scheduled-time-regexp nil
3195 "Matches the SCHEDULED keyword together with a time stamp.")
3196 (make-variable-buffer-local 'org-scheduled-time-regexp)
3197 (defvar org-closed-time-regexp nil
3198 "Matches the CLOSED keyword together with a time stamp.")
3199 (make-variable-buffer-local 'org-closed-time-regexp)
3201 (defvar org-keyword-time-regexp nil
3202 "Matches any of the 4 keywords, together with the time stamp.")
3203 (make-variable-buffer-local 'org-keyword-time-regexp)
3204 (defvar org-keyword-time-not-clock-regexp nil
3205 "Matches any of the 3 keywords, together with the time stamp.")
3206 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3207 (defvar org-maybe-keyword-time-regexp nil
3208 "Matches a timestamp, possibly preceeded by a keyword.")
3209 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3210 (defvar org-planning-or-clock-line-re nil
3211 "Matches a line with planning or clock info.")
3212 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3214 (defconst org-plain-time-of-day-regexp
3215 (concat
3216 "\\(\\<[012]?[0-9]"
3217 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3218 "\\(--?"
3219 "\\(\\<[012]?[0-9]"
3220 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3221 "\\)?")
3222 "Regular expression to match a plain time or time range.
3223 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3224 groups carry important information:
3225 0 the full match
3226 1 the first time, range or not
3227 8 the second time, if it is a range.")
3229 (defconst org-plain-time-extension-regexp
3230 (concat
3231 "\\(\\<[012]?[0-9]"
3232 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3233 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3234 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3235 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3236 groups carry important information:
3237 0 the full match
3238 7 hours of duration
3239 9 minutes of duration")
3241 (defconst org-stamp-time-of-day-regexp
3242 (concat
3243 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3244 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3245 "\\(--?"
3246 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3247 "Regular expression to match a timestamp time or time range.
3248 After a match, the following groups carry important information:
3249 0 the full match
3250 1 date plus weekday, for backreferencing to make sure both times on same day
3251 2 the first time, range or not
3252 4 the second time, if it is a range.")
3254 (defconst org-startup-options
3255 '(("fold" org-startup-folded t)
3256 ("overview" org-startup-folded t)
3257 ("nofold" org-startup-folded nil)
3258 ("showall" org-startup-folded nil)
3259 ("content" org-startup-folded content)
3260 ("hidestars" org-hide-leading-stars t)
3261 ("showstars" org-hide-leading-stars nil)
3262 ("odd" org-odd-levels-only t)
3263 ("oddeven" org-odd-levels-only nil)
3264 ("align" org-startup-align-all-tables t)
3265 ("noalign" org-startup-align-all-tables nil)
3266 ("customtime" org-display-custom-times t)
3267 ("logdone" org-log-done time)
3268 ("lognotedone" org-log-done note)
3269 ("nologdone" org-log-done nil)
3270 ("lognoteclock-out" org-log-note-clock-out t)
3271 ("nolognoteclock-out" org-log-note-clock-out nil)
3272 ("logrepeat" org-log-repeat state)
3273 ("lognoterepeat" org-log-repeat note)
3274 ("nologrepeat" org-log-repeat nil)
3275 ("fninline" org-footnote-define-inline t)
3276 ("nofninline" org-footnote-define-inline nil)
3277 ("fnlocal" org-footnote-section nil)
3278 ("fnauto" org-footnote-auto-label t)
3279 ("fnprompt" org-footnote-auto-label nil)
3280 ("fnconfirm" org-footnote-auto-label confirm)
3281 ("fnplain" org-footnote-auto-label plain)
3282 ("constcgs" constants-unit-system cgs)
3283 ("constSI" constants-unit-system SI)
3284 ("noptag" org-tag-persistent-alist nil))
3285 "Variable associated with STARTUP options for org-mode.
3286 Each element is a list of three items: The startup options as written
3287 in the #+STARTUP line, the corresponding variable, and the value to
3288 set this variable to if the option is found. An optional forth element PUSH
3289 means to push this value onto the list in the variable.")
3291 (defun org-set-regexps-and-options ()
3292 "Precompute regular expressions for current buffer."
3293 (when (org-mode-p)
3294 (org-set-local 'org-todo-kwd-alist nil)
3295 (org-set-local 'org-todo-key-alist nil)
3296 (org-set-local 'org-todo-key-trigger nil)
3297 (org-set-local 'org-todo-keywords-1 nil)
3298 (org-set-local 'org-done-keywords nil)
3299 (org-set-local 'org-todo-heads nil)
3300 (org-set-local 'org-todo-sets nil)
3301 (org-set-local 'org-todo-log-states nil)
3302 (org-set-local 'org-file-properties nil)
3303 (org-set-local 'org-file-tags nil)
3304 (let ((re (org-make-options-regexp
3305 '("CATEGORY" "TODO" "COLUMNS"
3306 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3307 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3308 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3309 (splitre "[ \t]+")
3310 kwds kws0 kwsa key log value cat arch tags const links hw dws
3311 tail sep kws1 prio props ftags drawers
3312 ext-setup-or-nil setup-contents (start 0))
3313 (save-excursion
3314 (save-restriction
3315 (widen)
3316 (goto-char (point-min))
3317 (while (or (and ext-setup-or-nil
3318 (string-match re ext-setup-or-nil start)
3319 (setq start (match-end 0)))
3320 (and (setq ext-setup-or-nil nil start 0)
3321 (re-search-forward re nil t)))
3322 (setq key (upcase (match-string 1 ext-setup-or-nil))
3323 value (org-match-string-no-properties 2 ext-setup-or-nil))
3324 (cond
3325 ((equal key "CATEGORY")
3326 (if (string-match "[ \t]+$" value)
3327 (setq value (replace-match "" t t value)))
3328 (setq cat value))
3329 ((member key '("SEQ_TODO" "TODO"))
3330 (push (cons 'sequence (org-split-string value splitre)) kwds))
3331 ((equal key "TYP_TODO")
3332 (push (cons 'type (org-split-string value splitre)) kwds))
3333 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3334 ;; general TODO-like setup
3335 (push (cons (intern (downcase (match-string 1 key)))
3336 (org-split-string value splitre)) kwds))
3337 ((equal key "TAGS")
3338 (setq tags (append tags (if tags '("\\n") nil)
3339 (org-split-string value splitre))))
3340 ((equal key "COLUMNS")
3341 (org-set-local 'org-columns-default-format value))
3342 ((equal key "LINK")
3343 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3344 (push (cons (match-string 1 value)
3345 (org-trim (match-string 2 value)))
3346 links)))
3347 ((equal key "PRIORITIES")
3348 (setq prio (org-split-string value " +")))
3349 ((equal key "PROPERTY")
3350 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3351 (push (cons (match-string 1 value) (match-string 2 value))
3352 props)))
3353 ((equal key "FILETAGS")
3354 (when (string-match "\\S-" value)
3355 (setq ftags
3356 (append
3357 ftags
3358 (apply 'append
3359 (mapcar (lambda (x) (org-split-string x ":"))
3360 (org-split-string value)))))))
3361 ((equal key "DRAWERS")
3362 (setq drawers (org-split-string value splitre)))
3363 ((equal key "CONSTANTS")
3364 (setq const (append const (org-split-string value splitre))))
3365 ((equal key "STARTUP")
3366 (let ((opts (org-split-string value splitre))
3367 l var val)
3368 (while (setq l (pop opts))
3369 (when (setq l (assoc l org-startup-options))
3370 (setq var (nth 1 l) val (nth 2 l))
3371 (if (not (nth 3 l))
3372 (set (make-local-variable var) val)
3373 (if (not (listp (symbol-value var)))
3374 (set (make-local-variable var) nil))
3375 (set (make-local-variable var) (symbol-value var))
3376 (add-to-list var val))))))
3377 ((equal key "ARCHIVE")
3378 (string-match " *$" value)
3379 (setq arch (replace-match "" t t value))
3380 (remove-text-properties 0 (length arch)
3381 '(face t fontified t) arch))
3382 ((equal key "SETUPFILE")
3383 (setq setup-contents (org-file-contents
3384 (expand-file-name
3385 (org-remove-double-quotes value))
3386 'noerror))
3387 (if (not ext-setup-or-nil)
3388 (setq ext-setup-or-nil setup-contents start 0)
3389 (setq ext-setup-or-nil
3390 (concat (substring ext-setup-or-nil 0 start)
3391 "\n" setup-contents "\n"
3392 (substring ext-setup-or-nil start)))))
3393 ))))
3394 (when cat
3395 (org-set-local 'org-category (intern cat))
3396 (push (cons "CATEGORY" cat) props))
3397 (when prio
3398 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3399 (setq prio (mapcar 'string-to-char prio))
3400 (org-set-local 'org-highest-priority (nth 0 prio))
3401 (org-set-local 'org-lowest-priority (nth 1 prio))
3402 (org-set-local 'org-default-priority (nth 2 prio)))
3403 (and props (org-set-local 'org-file-properties (nreverse props)))
3404 (and ftags (org-set-local 'org-file-tags ftags))
3405 (and drawers (org-set-local 'org-drawers drawers))
3406 (and arch (org-set-local 'org-archive-location arch))
3407 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3408 ;; Process the TODO keywords
3409 (unless kwds
3410 ;; Use the global values as if they had been given locally.
3411 (setq kwds (default-value 'org-todo-keywords))
3412 (if (stringp (car kwds))
3413 (setq kwds (list (cons org-todo-interpretation
3414 (default-value 'org-todo-keywords)))))
3415 (setq kwds (reverse kwds)))
3416 (setq kwds (nreverse kwds))
3417 (let (inter kws kw)
3418 (while (setq kws (pop kwds))
3419 (let ((kws (or
3420 (run-hook-with-args-until-success
3421 'org-todo-setup-filter-hook kws)
3422 kws)))
3423 (setq inter (pop kws) sep (member "|" kws)
3424 kws0 (delete "|" (copy-sequence kws))
3425 kwsa nil
3426 kws1 (mapcar
3427 (lambda (x)
3428 ;; 1 2
3429 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3430 (progn
3431 (setq kw (match-string 1 x)
3432 key (and (match-end 2) (match-string 2 x))
3433 log (org-extract-log-state-settings x))
3434 (push (cons kw (and key (string-to-char key))) kwsa)
3435 (and log (push log org-todo-log-states))
3437 (error "Invalid TODO keyword %s" x)))
3438 kws0)
3439 kwsa (if kwsa (append '((:startgroup))
3440 (nreverse kwsa)
3441 '((:endgroup))))
3442 hw (car kws1)
3443 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3444 tail (list inter hw (car dws) (org-last dws))))
3445 (add-to-list 'org-todo-heads hw 'append)
3446 (push kws1 org-todo-sets)
3447 (setq org-done-keywords (append org-done-keywords dws nil))
3448 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3449 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3450 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3451 (setq org-todo-sets (nreverse org-todo-sets)
3452 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3453 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3454 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3455 ;; Process the constants
3456 (when const
3457 (let (e cst)
3458 (while (setq e (pop const))
3459 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3460 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3461 (setq org-table-formula-constants-local cst)))
3463 ;; Process the tags.
3464 (when tags
3465 (let (e tgs)
3466 (while (setq e (pop tags))
3467 (cond
3468 ((equal e "{") (push '(:startgroup) tgs))
3469 ((equal e "}") (push '(:endgroup) tgs))
3470 ((equal e "\\n") (push '(:newline) tgs))
3471 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3472 (push (cons (match-string 1 e)
3473 (string-to-char (match-string 2 e)))
3474 tgs))
3475 (t (push (list e) tgs))))
3476 (org-set-local 'org-tag-alist nil)
3477 (while (setq e (pop tgs))
3478 (or (and (stringp (car e))
3479 (assoc (car e) org-tag-alist))
3480 (push e org-tag-alist)))))
3482 ;; Compute the regular expressions and other local variables
3483 (if (not org-done-keywords)
3484 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3485 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3486 (length org-scheduled-string)
3487 (length org-clock-string)
3488 (length org-closed-string)))
3489 org-drawer-regexp
3490 (concat "^[ \t]*:\\("
3491 (mapconcat 'regexp-quote org-drawers "\\|")
3492 "\\):[ \t]*$")
3493 org-not-done-keywords
3494 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3495 org-todo-regexp
3496 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3497 "\\|") "\\)\\>")
3498 org-not-done-regexp
3499 (concat "\\<\\("
3500 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3501 "\\)\\>")
3502 org-todo-line-regexp
3503 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3504 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3505 "\\)\\>\\)?[ \t]*\\(.*\\)")
3506 org-complex-heading-regexp
3507 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3508 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3509 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3510 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3511 org-nl-done-regexp
3512 (concat "\n\\*+[ \t]+"
3513 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3514 "\\)" "\\>")
3515 org-todo-line-tags-regexp
3516 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3517 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3518 (org-re
3519 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3520 org-looking-at-done-regexp
3521 (concat "^" "\\(?:"
3522 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3523 "\\>")
3524 org-deadline-regexp (concat "\\<" org-deadline-string)
3525 org-deadline-time-regexp
3526 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3527 org-deadline-line-regexp
3528 (concat "\\<\\(" org-deadline-string "\\).*")
3529 org-scheduled-regexp
3530 (concat "\\<" org-scheduled-string)
3531 org-scheduled-time-regexp
3532 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3533 org-closed-time-regexp
3534 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3535 org-keyword-time-regexp
3536 (concat "\\<\\(" org-scheduled-string
3537 "\\|" org-deadline-string
3538 "\\|" org-closed-string
3539 "\\|" org-clock-string "\\)"
3540 " *[[<]\\([^]>]+\\)[]>]")
3541 org-keyword-time-not-clock-regexp
3542 (concat "\\<\\(" org-scheduled-string
3543 "\\|" org-deadline-string
3544 "\\|" org-closed-string
3545 "\\)"
3546 " *[[<]\\([^]>]+\\)[]>]")
3547 org-maybe-keyword-time-regexp
3548 (concat "\\(\\<\\(" org-scheduled-string
3549 "\\|" org-deadline-string
3550 "\\|" org-closed-string
3551 "\\|" org-clock-string "\\)\\)?"
3552 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3553 org-planning-or-clock-line-re
3554 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3555 "\\|" org-deadline-string
3556 "\\|" org-closed-string "\\|" org-clock-string
3557 "\\)\\>\\)")
3559 (org-compute-latex-and-specials-regexp)
3560 (org-set-font-lock-defaults))))
3562 (defun org-file-contents (file &optional noerror)
3563 "Return the contents of FILE, as a string."
3564 (if (or (not file)
3565 (not (file-readable-p file)))
3566 (if noerror
3567 (progn
3568 (message "Cannot read file %s" file)
3569 (ding) (sit-for 2)
3571 (error "Cannot read file %s" file))
3572 (with-temp-buffer
3573 (insert-file-contents file)
3574 (buffer-string))))
3576 (defun org-extract-log-state-settings (x)
3577 "Extract the log state setting from a TODO keyword string.
3578 This will extract info from a string like \"WAIT(w@/!)\"."
3579 (let (kw key log1 log2)
3580 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3581 (setq kw (match-string 1 x)
3582 key (and (match-end 2) (match-string 2 x))
3583 log1 (and (match-end 3) (match-string 3 x))
3584 log2 (and (match-end 4) (match-string 4 x)))
3585 (and (or log1 log2)
3586 (list kw
3587 (and log1 (if (equal log1 "!") 'time 'note))
3588 (and log2 (if (equal log2 "!") 'time 'note)))))))
3590 (defun org-remove-keyword-keys (list)
3591 "Remove a pair of parenthesis at the end of each string in LIST."
3592 (mapcar (lambda (x)
3593 (if (string-match "(.*)$" x)
3594 (substring x 0 (match-beginning 0))
3596 list))
3598 ;; FIXME: this could be done much better, using second characters etc.
3599 (defun org-assign-fast-keys (alist)
3600 "Assign fast keys to a keyword-key alist.
3601 Respect keys that are already there."
3602 (let (new e k c c1 c2 (char ?a))
3603 (while (setq e (pop alist))
3604 (cond
3605 ((equal e '(:startgroup)) (push e new))
3606 ((equal e '(:endgroup)) (push e new))
3607 ((equal e '(:newline)) (push e new))
3609 (setq k (car e) c2 nil)
3610 (if (cdr e)
3611 (setq c (cdr e))
3612 ;; automatically assign a character.
3613 (setq c1 (string-to-char
3614 (downcase (substring
3615 k (if (= (string-to-char k) ?@) 1 0)))))
3616 (if (or (rassoc c1 new) (rassoc c1 alist))
3617 (while (or (rassoc char new) (rassoc char alist))
3618 (setq char (1+ char)))
3619 (setq c2 c1))
3620 (setq c (or c2 char)))
3621 (push (cons k c) new))))
3622 (nreverse new)))
3624 ;;; Some variables used in various places
3626 (defvar org-window-configuration nil
3627 "Used in various places to store a window configuration.")
3628 (defvar org-finish-function nil
3629 "Function to be called when `C-c C-c' is used.
3630 This is for getting out of special buffers like remember.")
3633 ;; FIXME: Occasionally check by commenting these, to make sure
3634 ;; no other functions uses these, forgetting to let-bind them.
3635 (defvar entry)
3636 (defvar state)
3637 (defvar last-state)
3638 (defvar date)
3639 (defvar description)
3641 ;; Defined somewhere in this file, but used before definition.
3642 (defvar org-html-entities)
3643 (defvar org-struct-menu)
3644 (defvar org-org-menu)
3645 (defvar org-tbl-menu)
3646 (defvar org-agenda-keymap)
3648 ;;;; Define the Org-mode
3650 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3651 (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."))
3654 ;; We use a before-change function to check if a table might need
3655 ;; an update.
3656 (defvar org-table-may-need-update t
3657 "Indicates that a table might need an update.
3658 This variable is set by `org-before-change-function'.
3659 `org-table-align' sets it back to nil.")
3660 (defun org-before-change-function (beg end)
3661 "Every change indicates that a table might need an update."
3662 (setq org-table-may-need-update t))
3663 (defvar org-mode-map)
3664 (defvar org-mode-hook nil
3665 "Mode hook for Org-mode, run after the mode was turned on.")
3666 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3667 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3668 (defvar org-table-buffer-is-an nil)
3669 (defconst org-outline-regexp "\\*+ ")
3671 ;;;###autoload
3672 (define-derived-mode org-mode outline-mode "Org"
3673 "Outline-based notes management and organizer, alias
3674 \"Carsten's outline-mode for keeping track of everything.\"
3676 Org-mode develops organizational tasks around a NOTES file which
3677 contains information about projects as plain text. Org-mode is
3678 implemented on top of outline-mode, which is ideal to keep the content
3679 of large files well structured. It supports ToDo items, deadlines and
3680 time stamps, which magically appear in the diary listing of the Emacs
3681 calendar. Tables are easily created with a built-in table editor.
3682 Plain text URL-like links connect to websites, emails (VM), Usenet
3683 messages (Gnus), BBDB entries, and any files related to the project.
3684 For printing and sharing of notes, an Org-mode file (or a part of it)
3685 can be exported as a structured ASCII or HTML file.
3687 The following commands are available:
3689 \\{org-mode-map}"
3691 ;; Get rid of Outline menus, they are not needed
3692 ;; Need to do this here because define-derived-mode sets up
3693 ;; the keymap so late. Still, it is a waste to call this each time
3694 ;; we switch another buffer into org-mode.
3695 (if (featurep 'xemacs)
3696 (when (boundp 'outline-mode-menu-heading)
3697 ;; Assume this is Greg's port, it used easymenu
3698 (easy-menu-remove outline-mode-menu-heading)
3699 (easy-menu-remove outline-mode-menu-show)
3700 (easy-menu-remove outline-mode-menu-hide))
3701 (define-key org-mode-map [menu-bar headings] 'undefined)
3702 (define-key org-mode-map [menu-bar hide] 'undefined)
3703 (define-key org-mode-map [menu-bar show] 'undefined))
3705 (org-load-modules-maybe)
3706 (easy-menu-add org-org-menu)
3707 (easy-menu-add org-tbl-menu)
3708 (org-install-agenda-files-menu)
3709 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3710 (org-add-to-invisibility-spec '(org-cwidth))
3711 (when (featurep 'xemacs)
3712 (org-set-local 'line-move-ignore-invisible t))
3713 (org-set-local 'outline-regexp org-outline-regexp)
3714 (org-set-local 'outline-level 'org-outline-level)
3715 (when (and org-ellipsis
3716 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3717 (fboundp 'make-glyph-code))
3718 (unless org-display-table
3719 (setq org-display-table (make-display-table)))
3720 (set-display-table-slot
3721 org-display-table 4
3722 (vconcat (mapcar
3723 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3724 org-ellipsis)))
3725 (if (stringp org-ellipsis) org-ellipsis "..."))))
3726 (setq buffer-display-table org-display-table))
3727 (org-set-regexps-and-options)
3728 (when (and org-tag-faces (not org-tags-special-faces-re))
3729 ;; tag faces set outside customize.... force initialization.
3730 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3731 ;; Calc embedded
3732 (org-set-local 'calc-embedded-open-mode "# ")
3733 (modify-syntax-entry ?# "<")
3734 (modify-syntax-entry ?@ "w")
3735 (if org-startup-truncated (setq truncate-lines t))
3736 (org-set-local 'font-lock-unfontify-region-function
3737 'org-unfontify-region)
3738 ;; Activate before-change-function
3739 (org-set-local 'org-table-may-need-update t)
3740 (org-add-hook 'before-change-functions 'org-before-change-function nil
3741 'local)
3742 ;; Check for running clock before killing a buffer
3743 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3744 ;; Paragraphs and auto-filling
3745 (org-set-autofill-regexps)
3746 (setq indent-line-function 'org-indent-line-function)
3747 (org-update-radio-target-regexp)
3748 ;; Make sure dependence stuff works reliably, even for users who set it
3749 ;; too late :-(
3750 (if org-enforce-todo-dependencies
3751 (add-hook 'org-blocker-hook
3752 'org-block-todo-from-children-or-siblings)
3753 (remove-hook 'org-blocker-hook
3754 'org-block-todo-from-children-or-siblings))
3755 (if org-enforce-todo-checkbox-dependencies
3756 (add-hook 'org-blocker-hook
3757 'org-block-todo-from-checkboxes)
3758 (remove-hook 'org-blocker-hook
3759 'org-block-todo-from-checkboxes))
3761 ;; Comment characters
3762 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3763 (org-set-local 'comment-padding " ")
3765 ;; Align options lines
3766 (org-set-local
3767 'align-mode-rules-list
3768 '((org-in-buffer-settings
3769 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3770 (modes . '(org-mode)))))
3772 ;; Imenu
3773 (org-set-local 'imenu-create-index-function
3774 'org-imenu-get-tree)
3776 ;; Make isearch reveal context
3777 (if (or (featurep 'xemacs)
3778 (not (boundp 'outline-isearch-open-invisible-function)))
3779 ;; Emacs 21 and XEmacs make use of the hook
3780 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3781 ;; Emacs 22 deals with this through a special variable
3782 (org-set-local 'outline-isearch-open-invisible-function
3783 (lambda (&rest ignore) (org-show-context 'isearch))))
3785 ;; If empty file that did not turn on org-mode automatically, make it to.
3786 (if (and org-insert-mode-line-in-empty-file
3787 (interactive-p)
3788 (= (point-min) (point-max)))
3789 (insert "# -*- mode: org -*-\n\n"))
3791 (unless org-inhibit-startup
3792 (when org-startup-align-all-tables
3793 (let ((bmp (buffer-modified-p)))
3794 (org-table-map-tables 'org-table-align)
3795 (set-buffer-modified-p bmp)))
3796 (org-set-startup-visibility)))
3798 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3800 (defun org-current-time ()
3801 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3802 (if (> (car org-time-stamp-rounding-minutes) 1)
3803 (let ((r (car org-time-stamp-rounding-minutes))
3804 (time (decode-time)))
3805 (apply 'encode-time
3806 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3807 (nthcdr 2 time))))
3808 (current-time)))
3810 ;;;; Font-Lock stuff, including the activators
3812 (defvar org-mouse-map (make-sparse-keymap))
3813 (org-defkey org-mouse-map
3814 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3815 (org-defkey org-mouse-map
3816 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3817 (when org-mouse-1-follows-link
3818 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3819 (when org-tab-follows-link
3820 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3821 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3823 (require 'font-lock)
3825 (defconst org-non-link-chars "]\t\n\r<>")
3826 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3827 "shell" "elisp"))
3828 (defvar org-link-types-re nil
3829 "Matches a link that has a url-like prefix like \"http:\"")
3830 (defvar org-link-re-with-space nil
3831 "Matches a link with spaces, optional angular brackets around it.")
3832 (defvar org-link-re-with-space2 nil
3833 "Matches a link with spaces, optional angular brackets around it.")
3834 (defvar org-link-re-with-space3 nil
3835 "Matches a link with spaces, only for internal part in bracket links.")
3836 (defvar org-angle-link-re nil
3837 "Matches link with angular brackets, spaces are allowed.")
3838 (defvar org-plain-link-re nil
3839 "Matches plain link, without spaces.")
3840 (defvar org-bracket-link-regexp nil
3841 "Matches a link in double brackets.")
3842 (defvar org-bracket-link-analytic-regexp nil
3843 "Regular expression used to analyze links.
3844 Here is what the match groups contain after a match:
3845 1: http:
3846 2: http
3847 3: path
3848 4: [desc]
3849 5: desc")
3850 (defvar org-bracket-link-analytic-regexp++ nil
3851 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3852 (defvar org-any-link-re nil
3853 "Regular expression matching any link.")
3855 (defun org-make-link-regexps ()
3856 "Update the link regular expressions.
3857 This should be called after the variable `org-link-types' has changed."
3858 (setq org-link-types-re
3859 (concat
3860 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3861 org-link-re-with-space
3862 (concat
3863 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3864 "\\([^" org-non-link-chars " ]"
3865 "[^" org-non-link-chars "]*"
3866 "[^" org-non-link-chars " ]\\)>?")
3867 org-link-re-with-space2
3868 (concat
3869 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3870 "\\([^" org-non-link-chars " ]"
3871 "[^\t\n\r]*"
3872 "[^" org-non-link-chars " ]\\)>?")
3873 org-link-re-with-space3
3874 (concat
3875 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3876 "\\([^" org-non-link-chars " ]"
3877 "[^\t\n\r]*\\)")
3878 org-angle-link-re
3879 (concat
3880 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3881 "\\([^" org-non-link-chars " ]"
3882 "[^" org-non-link-chars "]*"
3883 "\\)>")
3884 org-plain-link-re
3885 (concat
3886 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3887 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3888 org-bracket-link-regexp
3889 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3890 org-bracket-link-analytic-regexp
3891 (concat
3892 "\\[\\["
3893 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3894 "\\([^]]+\\)"
3895 "\\]"
3896 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3897 "\\]")
3898 org-bracket-link-analytic-regexp++
3899 (concat
3900 "\\[\\["
3901 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3902 "\\([^]]+\\)"
3903 "\\]"
3904 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3905 "\\]")
3906 org-any-link-re
3907 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3908 org-angle-link-re "\\)\\|\\("
3909 org-plain-link-re "\\)")))
3911 (org-make-link-regexps)
3913 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3914 "Regular expression for fast time stamp matching.")
3915 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3916 "Regular expression for fast time stamp matching.")
3917 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3918 "Regular expression matching time strings for analysis.
3919 This one does not require the space after the date, so it can be used
3920 on a string that terminates immediately after the date.")
3921 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3922 "Regular expression matching time strings for analysis.")
3923 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3924 "Regular expression matching time stamps, with groups.")
3925 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3926 "Regular expression matching time stamps (also [..]), with groups.")
3927 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3928 "Regular expression matching a time stamp range.")
3929 (defconst org-tr-regexp-both
3930 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3931 "Regular expression matching a time stamp range.")
3932 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3933 org-ts-regexp "\\)?")
3934 "Regular expression matching a time stamp or time stamp range.")
3935 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3936 org-ts-regexp-both "\\)?")
3937 "Regular expression matching a time stamp or time stamp range.
3938 The time stamps may be either active or inactive.")
3940 (defvar org-emph-face nil)
3942 (defun org-do-emphasis-faces (limit)
3943 "Run through the buffer and add overlays to links."
3944 (let (rtn)
3945 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3946 (if (not (= (char-after (match-beginning 3))
3947 (char-after (match-beginning 4))))
3948 (progn
3949 (setq rtn t)
3950 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3951 'face
3952 (nth 1 (assoc (match-string 3)
3953 org-emphasis-alist)))
3954 (add-text-properties (match-beginning 2) (match-end 2)
3955 '(font-lock-multiline t))
3956 (when org-hide-emphasis-markers
3957 (add-text-properties (match-end 4) (match-beginning 5)
3958 '(invisible org-link))
3959 (add-text-properties (match-beginning 3) (match-end 3)
3960 '(invisible org-link)))))
3961 (backward-char 1))
3962 rtn))
3964 (defun org-emphasize (&optional char)
3965 "Insert or change an emphasis, i.e. a font like bold or italic.
3966 If there is an active region, change that region to a new emphasis.
3967 If there is no region, just insert the marker characters and position
3968 the cursor between them.
3969 CHAR should be either the marker character, or the first character of the
3970 HTML tag associated with that emphasis. If CHAR is a space, the means
3971 to remove the emphasis of the selected region.
3972 If char is not given (for example in an interactive call) it
3973 will be prompted for."
3974 (interactive)
3975 (let ((eal org-emphasis-alist) e det
3976 (erc org-emphasis-regexp-components)
3977 (prompt "")
3978 (string "") beg end move tag c s)
3979 (if (org-region-active-p)
3980 (setq beg (region-beginning) end (region-end)
3981 string (buffer-substring beg end))
3982 (setq move t))
3984 (while (setq e (pop eal))
3985 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3986 c (aref tag 0))
3987 (push (cons c (string-to-char (car e))) det)
3988 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3989 (substring tag 1)))))
3990 (setq det (nreverse det))
3991 (unless char
3992 (message "%s" (concat "Emphasis marker or tag:" prompt))
3993 (setq char (read-char-exclusive)))
3994 (setq char (or (cdr (assoc char det)) char))
3995 (if (equal char ?\ )
3996 (setq s "" move nil)
3997 (unless (assoc (char-to-string char) org-emphasis-alist)
3998 (error "No such emphasis marker: \"%c\"" char))
3999 (setq s (char-to-string char)))
4000 (while (and (> (length string) 1)
4001 (equal (substring string 0 1) (substring string -1))
4002 (assoc (substring string 0 1) org-emphasis-alist))
4003 (setq string (substring string 1 -1)))
4004 (setq string (concat s string s))
4005 (if beg (delete-region beg end))
4006 (unless (or (bolp)
4007 (string-match (concat "[" (nth 0 erc) "\n]")
4008 (char-to-string (char-before (point)))))
4009 (insert " "))
4010 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4011 (char-to-string (char-after (point))))
4012 (insert " ") (backward-char 1))
4013 (insert string)
4014 (and move (backward-char 1))))
4016 (defconst org-nonsticky-props
4017 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4020 (defun org-activate-plain-links (limit)
4021 "Run through the buffer and add overlays to links."
4022 (catch 'exit
4023 (let (f)
4024 (while (re-search-forward org-plain-link-re limit t)
4025 (setq f (get-text-property (match-beginning 0) 'face))
4026 (if (or (eq f 'org-tag)
4027 (and (listp f) (memq 'org-tag f)))
4029 (add-text-properties (match-beginning 0) (match-end 0)
4030 (list 'mouse-face 'highlight
4031 'rear-nonsticky org-nonsticky-props
4032 'keymap org-mouse-map
4034 (throw 'exit t))))))
4036 (defun org-activate-code (limit)
4037 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4038 (progn
4039 (remove-text-properties (match-beginning 0) (match-end 0)
4040 '(display t invisible t intangible t))
4041 t)))
4043 (defun org-activate-angle-links (limit)
4044 "Run through the buffer and add overlays to links."
4045 (if (re-search-forward org-angle-link-re limit t)
4046 (progn
4047 (add-text-properties (match-beginning 0) (match-end 0)
4048 (list 'mouse-face 'highlight
4049 'rear-nonsticky org-nonsticky-props
4050 'keymap org-mouse-map
4052 t)))
4054 (defun org-activate-footnote-links (limit)
4055 "Run through the buffer and add overlays to links."
4056 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4057 limit t)
4058 (progn
4059 (add-text-properties (match-beginning 2) (match-end 2)
4060 (list 'mouse-face 'highlight
4061 'rear-nonsticky org-nonsticky-props
4062 'keymap org-mouse-map
4063 'help-echo
4064 (if (= (point-at-bol) (match-beginning 2))
4065 "Footnote definition"
4066 "Footnote reference")
4068 t)))
4070 (defun org-activate-bracket-links (limit)
4071 "Run through the buffer and add overlays to bracketed links."
4072 (if (re-search-forward org-bracket-link-regexp limit t)
4073 (let* ((help (concat "LINK: "
4074 (org-match-string-no-properties 1)))
4075 ;; FIXME: above we should remove the escapes.
4076 ;; but that requires another match, protecting match data,
4077 ;; a lot of overhead for font-lock.
4078 (ip (org-maybe-intangible
4079 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4080 'keymap org-mouse-map 'mouse-face 'highlight
4081 'font-lock-multiline t 'help-echo help)))
4082 (vp (list 'rear-nonsticky org-nonsticky-props
4083 'keymap org-mouse-map 'mouse-face 'highlight
4084 'font-lock-multiline t 'help-echo help)))
4085 ;; We need to remove the invisible property here. Table narrowing
4086 ;; may have made some of this invisible.
4087 (remove-text-properties (match-beginning 0) (match-end 0)
4088 '(invisible nil))
4089 (if (match-end 3)
4090 (progn
4091 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4092 (add-text-properties (match-beginning 3) (match-end 3) vp)
4093 (add-text-properties (match-end 3) (match-end 0) ip))
4094 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4095 (add-text-properties (match-beginning 1) (match-end 1) vp)
4096 (add-text-properties (match-end 1) (match-end 0) ip))
4097 t)))
4099 (defun org-activate-dates (limit)
4100 "Run through the buffer and add overlays to dates."
4101 (if (re-search-forward org-tsr-regexp-both limit t)
4102 (progn
4103 (add-text-properties (match-beginning 0) (match-end 0)
4104 (list 'mouse-face 'highlight
4105 'rear-nonsticky org-nonsticky-props
4106 'keymap org-mouse-map))
4107 (when org-display-custom-times
4108 (if (match-end 3)
4109 (org-display-custom-time (match-beginning 3) (match-end 3)))
4110 (org-display-custom-time (match-beginning 1) (match-end 1)))
4111 t)))
4113 (defvar org-target-link-regexp nil
4114 "Regular expression matching radio targets in plain text.")
4115 (make-variable-buffer-local 'org-target-link-regexp)
4116 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4117 "Regular expression matching a link target.")
4118 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4119 "Regular expression matching a radio target.")
4120 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4121 "Regular expression matching any target.")
4123 (defun org-activate-target-links (limit)
4124 "Run through the buffer and add overlays to target matches."
4125 (when org-target-link-regexp
4126 (let ((case-fold-search t))
4127 (if (re-search-forward org-target-link-regexp limit t)
4128 (progn
4129 (add-text-properties (match-beginning 0) (match-end 0)
4130 (list 'mouse-face 'highlight
4131 'rear-nonsticky org-nonsticky-props
4132 'keymap org-mouse-map
4133 'help-echo "Radio target link"
4134 'org-linked-text t))
4135 t)))))
4137 (defun org-update-radio-target-regexp ()
4138 "Find all radio targets in this file and update the regular expression."
4139 (interactive)
4140 (when (memq 'radio org-activate-links)
4141 (setq org-target-link-regexp
4142 (org-make-target-link-regexp (org-all-targets 'radio)))
4143 (org-restart-font-lock)))
4145 (defun org-hide-wide-columns (limit)
4146 (let (s e)
4147 (setq s (text-property-any (point) (or limit (point-max))
4148 'org-cwidth t))
4149 (when s
4150 (setq e (next-single-property-change s 'org-cwidth))
4151 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4152 (goto-char e)
4153 t)))
4155 (defvar org-latex-and-specials-regexp nil
4156 "Regular expression for highlighting export special stuff.")
4157 (defvar org-match-substring-regexp)
4158 (defvar org-match-substring-with-braces-regexp)
4159 (defvar org-export-html-special-string-regexps)
4161 (defun org-compute-latex-and-specials-regexp ()
4162 "Compute regular expression for stuff treated specially by exporters."
4163 (if (not org-highlight-latex-fragments-and-specials)
4164 (org-set-local 'org-latex-and-specials-regexp nil)
4165 (require 'org-exp)
4166 (let*
4167 ((matchers (plist-get org-format-latex-options :matchers))
4168 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4169 org-latex-regexps)))
4170 (options (org-combine-plists (org-default-export-plist)
4171 (org-infile-export-plist)))
4172 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4173 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4174 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4175 (org-export-html-expand (plist-get options :expand-quoted-html))
4176 (org-export-with-special-strings (plist-get options :special-strings))
4177 (re-sub
4178 (cond
4179 ((equal org-export-with-sub-superscripts '{})
4180 (list org-match-substring-with-braces-regexp))
4181 (org-export-with-sub-superscripts
4182 (list org-match-substring-regexp))
4183 (t nil)))
4184 (re-latex
4185 (if org-export-with-LaTeX-fragments
4186 (mapcar (lambda (x) (nth 1 x)) latexs)))
4187 (re-macros
4188 (if org-export-with-TeX-macros
4189 (list (concat "\\\\"
4190 (regexp-opt
4191 (append (mapcar 'car org-html-entities)
4192 (if (boundp 'org-latex-entities)
4193 org-latex-entities nil))
4194 'words))) ; FIXME
4196 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4197 (re-special (if org-export-with-special-strings
4198 (mapcar (lambda (x) (car x))
4199 org-export-html-special-string-regexps)))
4200 (re-rest
4201 (delq nil
4202 (list
4203 (if org-export-html-expand "@<[^>\n]+>")
4204 ))))
4205 (org-set-local
4206 'org-latex-and-specials-regexp
4207 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4208 re-rest) "\\|")))))
4210 (defun org-do-latex-and-special-faces (limit)
4211 "Run through the buffer and add overlays to links."
4212 (when org-latex-and-specials-regexp
4213 (let (rtn d)
4214 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4215 limit t))
4216 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4217 'face))
4218 '(org-code org-verbatim underline)))
4219 (progn
4220 (setq rtn t
4221 d (cond ((member (char-after (1+ (match-beginning 0)))
4222 '(?_ ?^)) 1)
4223 (t 0)))
4224 (font-lock-prepend-text-property
4225 (+ d (match-beginning 0)) (match-end 0)
4226 'face 'org-latex-and-export-specials)
4227 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4228 '(font-lock-multiline t)))))
4229 rtn)))
4231 (defun org-restart-font-lock ()
4232 "Restart font-lock-mode, to force refontification."
4233 (when (and (boundp 'font-lock-mode) font-lock-mode)
4234 (font-lock-mode -1)
4235 (font-lock-mode 1)))
4237 (defun org-all-targets (&optional radio)
4238 "Return a list of all targets in this file.
4239 With optional argument RADIO, only find radio targets."
4240 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4241 rtn)
4242 (save-excursion
4243 (goto-char (point-min))
4244 (while (re-search-forward re nil t)
4245 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4246 rtn)))
4248 (defun org-make-target-link-regexp (targets)
4249 "Make regular expression matching all strings in TARGETS.
4250 The regular expression finds the targets also if there is a line break
4251 between words."
4252 (and targets
4253 (concat
4254 "\\<\\("
4255 (mapconcat
4256 (lambda (x)
4257 (while (string-match " +" x)
4258 (setq x (replace-match "\\s-+" t t x)))
4260 targets
4261 "\\|")
4262 "\\)\\>")))
4264 (defun org-activate-tags (limit)
4265 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4266 (progn
4267 (add-text-properties (match-beginning 1) (match-end 1)
4268 (list 'mouse-face 'highlight
4269 'rear-nonsticky org-nonsticky-props
4270 'keymap org-mouse-map))
4271 t)))
4273 (defun org-outline-level ()
4274 (save-excursion
4275 (looking-at outline-regexp)
4276 (if (match-beginning 1)
4277 (+ (org-get-string-indentation (match-string 1)) 1000)
4278 (1- (- (match-end 0) (match-beginning 0))))))
4280 (defvar org-font-lock-keywords nil)
4282 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4283 "Regular expression matching a property line.")
4285 (defvar org-font-lock-hook nil
4286 "Functions to be called for special font lock stuff.")
4288 (defun org-font-lock-hook (limit)
4289 (run-hook-with-args 'org-font-lock-hook limit))
4291 (defun org-set-font-lock-defaults ()
4292 (let* ((em org-fontify-emphasized-text)
4293 (lk org-activate-links)
4294 (org-font-lock-extra-keywords
4295 (list
4296 ;; Call the hook
4297 '(org-font-lock-hook)
4298 ;; Headlines
4299 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4300 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4301 ;; Table lines
4302 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4303 (1 'org-table t))
4304 ;; Table internals
4305 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4306 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4307 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4308 ;; Drawers
4309 (list org-drawer-regexp '(0 'org-special-keyword t))
4310 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4311 ;; Properties
4312 (list org-property-re
4313 '(1 'org-special-keyword t)
4314 '(3 'org-property-value t))
4315 (if org-format-transports-properties-p
4316 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4317 ;; Links
4318 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4319 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4320 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4321 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4322 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4323 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4324 (if (memq 'footnote lk) '(org-activate-footnote-links
4325 (2 'org-footnote t)))
4326 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4327 '(org-hide-wide-columns (0 nil append))
4328 ;; TODO lines
4329 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4330 '(1 (org-get-todo-face 1) t))
4331 ;; DONE
4332 (if org-fontify-done-headline
4333 (list (concat "^[*]+ +\\<\\("
4334 (mapconcat 'regexp-quote org-done-keywords "\\|")
4335 "\\)\\(.*\\)")
4336 '(2 'org-headline-done t))
4337 nil)
4338 ;; Priorities
4339 '(org-font-lock-add-priority-faces)
4340 ;; Tags
4341 '(org-font-lock-add-tag-faces)
4342 ;; Special keywords
4343 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4344 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4345 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4346 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4347 ;; Emphasis
4348 (if em
4349 (if (featurep 'xemacs)
4350 '(org-do-emphasis-faces (0 nil append))
4351 '(org-do-emphasis-faces)))
4352 ;; Checkboxes
4353 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4354 2 'bold prepend)
4355 (if org-provide-checkbox-statistics
4356 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4357 (0 (org-get-checkbox-statistics-face) t)))
4358 ;; Description list items
4359 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4360 2 'bold prepend)
4361 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4362 '(1 'org-archived prepend))
4363 ;; Specials
4364 '(org-do-latex-and-special-faces)
4365 ;; Code
4366 '(org-activate-code (1 'org-code t))
4367 ;; COMMENT
4368 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4369 "\\|" org-quote-string "\\)\\>")
4370 '(1 'org-special-keyword t))
4371 '("^#.*" (0 'font-lock-comment-face t))
4373 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4374 ;; Now set the full font-lock-keywords
4375 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4376 (org-set-local 'font-lock-defaults
4377 '(org-font-lock-keywords t nil nil backward-paragraph))
4378 (kill-local-variable 'font-lock-keywords) nil))
4380 (defvar org-m nil)
4381 (defvar org-l nil)
4382 (defvar org-f nil)
4383 (defun org-get-level-face (n)
4384 "Get the right face for match N in font-lock matching of headlines."
4385 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4386 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4387 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4388 (cond
4389 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4390 ((eq n 2) org-f)
4391 (t (if org-level-color-stars-only nil org-f))))
4393 (defun org-get-todo-face (kwd)
4394 "Get the right face for a TODO keyword KWD.
4395 If KWD is a number, get the corresponding match group."
4396 (if (numberp kwd) (setq kwd (match-string kwd)))
4397 (or (cdr (assoc kwd org-todo-keyword-faces))
4398 (and (member kwd org-done-keywords) 'org-done)
4399 'org-todo))
4401 (defun org-font-lock-add-tag-faces (limit)
4402 "Add the special tag faces."
4403 (when (and org-tag-faces org-tags-special-faces-re)
4404 (while (re-search-forward org-tags-special-faces-re limit t)
4405 (add-text-properties (match-beginning 1) (match-end 1)
4406 (list 'face (org-get-tag-face 1)
4407 'font-lock-fontified t))
4408 (backward-char 1))))
4410 (defun org-font-lock-add-priority-faces (limit)
4411 "Add the special priority faces."
4412 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4413 (add-text-properties
4414 (match-beginning 0) (match-end 0)
4415 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4416 org-priority-faces))
4417 'org-special-keyword)
4418 'font-lock-fontified t))))
4420 (defun org-get-tag-face (kwd)
4421 "Get the right face for a TODO keyword KWD.
4422 If KWD is a number, get the corresponding match group."
4423 (if (numberp kwd) (setq kwd (match-string kwd)))
4424 (or (cdr (assoc kwd org-tag-faces))
4425 'org-tag))
4427 (defun org-unfontify-region (beg end &optional maybe_loudly)
4428 "Remove fontification and activation overlays from links."
4429 (font-lock-default-unfontify-region beg end)
4430 (let* ((buffer-undo-list t)
4431 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4432 (inhibit-modification-hooks t)
4433 deactivate-mark buffer-file-name buffer-file-truename)
4434 (remove-text-properties beg end
4435 '(mouse-face t keymap t org-linked-text t
4436 invisible t intangible t))))
4438 ;;;; Visibility cycling, including org-goto and indirect buffer
4440 ;;; Cycling
4442 (defvar org-cycle-global-status nil)
4443 (make-variable-buffer-local 'org-cycle-global-status)
4444 (defvar org-cycle-subtree-status nil)
4445 (make-variable-buffer-local 'org-cycle-subtree-status)
4447 ;;;###autoload
4448 (defun org-cycle (&optional arg)
4449 "Visibility cycling for Org-mode.
4451 - When this function is called with a prefix argument, rotate the entire
4452 buffer through 3 states (global cycling)
4453 1. OVERVIEW: Show only top-level headlines.
4454 2. CONTENTS: Show all headlines of all levels, but no body text.
4455 3. SHOW ALL: Show everything.
4456 When called with two C-u C-u prefixes, switch to the startup visibility,
4457 determined by the variable `org-startup-folded', and by any VISIBILITY
4458 properties in the buffer.
4459 When called with three C-u C-u C-u prefixed, show the entire buffer,
4460 including drawers.
4462 - When point is at the beginning of a headline, rotate the subtree started
4463 by this line through 3 different states (local cycling)
4464 1. FOLDED: Only the main headline is shown.
4465 2. CHILDREN: The main headline and the direct children are shown.
4466 From this state, you can move to one of the children
4467 and zoom in further.
4468 3. SUBTREE: Show the entire subtree, including body text.
4470 - When there is a numeric prefix, go up to a heading with level ARG, do
4471 a `show-subtree' and return to the previous cursor position. If ARG
4472 is negative, go up that many levels.
4474 - When point is not at the beginning of a headline, execute the global
4475 binding for TAB, which is re-indenting the line. See the option
4476 `org-cycle-emulate-tab' for details.
4478 - Special case: if point is at the beginning of the buffer and there is
4479 no headline in line 1, this function will act as if called with prefix arg.
4480 But only if also the variable `org-cycle-global-at-bob' is t."
4481 (interactive "P")
4482 (org-load-modules-maybe)
4483 (let* ((outline-regexp
4484 (if (and (org-mode-p) org-cycle-include-plain-lists)
4485 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4486 outline-regexp))
4487 (bob-special (and org-cycle-global-at-bob (bobp)
4488 (not (looking-at outline-regexp))))
4489 (org-cycle-hook
4490 (if bob-special
4491 (delq 'org-optimize-window-after-visibility-change
4492 (copy-sequence org-cycle-hook))
4493 org-cycle-hook))
4494 (pos (point)))
4496 (if (or bob-special (equal arg '(4)))
4497 ;; special case: use global cycling
4498 (setq arg t))
4500 (cond
4502 ((equal arg '(16))
4503 (org-set-startup-visibility)
4504 (message "Startup visibility, plus VISIBILITY properties"))
4506 ((equal arg '(64))
4507 (show-all)
4508 (message "Entire buffer visible, including drawers"))
4510 ((org-at-table-p 'any)
4511 ;; Enter the table or move to the next field in the table
4512 (or (org-table-recognize-table.el)
4513 (progn
4514 (if arg (org-table-edit-field t)
4515 (org-table-justify-field-maybe)
4516 (call-interactively 'org-table-next-field)))))
4518 ((eq arg t) ;; Global cycling
4520 (cond
4521 ((and (eq last-command this-command)
4522 (eq org-cycle-global-status 'overview))
4523 ;; We just created the overview - now do table of contents
4524 ;; This can be slow in very large buffers, so indicate action
4525 (message "CONTENTS...")
4526 (org-content)
4527 (message "CONTENTS...done")
4528 (setq org-cycle-global-status 'contents)
4529 (run-hook-with-args 'org-cycle-hook 'contents))
4531 ((and (eq last-command this-command)
4532 (eq org-cycle-global-status 'contents))
4533 ;; We just showed the table of contents - now show everything
4534 (show-all)
4535 (message "SHOW ALL")
4536 (setq org-cycle-global-status 'all)
4537 (run-hook-with-args 'org-cycle-hook 'all))
4540 ;; Default action: go to overview
4541 (org-overview)
4542 (message "OVERVIEW")
4543 (setq org-cycle-global-status 'overview)
4544 (run-hook-with-args 'org-cycle-hook 'overview))))
4546 ((and org-drawers org-drawer-regexp
4547 (save-excursion
4548 (beginning-of-line 1)
4549 (looking-at org-drawer-regexp)))
4550 ;; Toggle block visibility
4551 (org-flag-drawer
4552 (not (get-char-property (match-end 0) 'invisible))))
4554 ((integerp arg)
4555 ;; Show-subtree, ARG levels up from here.
4556 (save-excursion
4557 (org-back-to-heading)
4558 (outline-up-heading (if (< arg 0) (- arg)
4559 (- (funcall outline-level) arg)))
4560 (org-show-subtree)))
4562 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4563 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4564 ;; At a heading: rotate between three different views
4565 (org-back-to-heading)
4566 (let ((goal-column 0) eoh eol eos)
4567 ;; First, some boundaries
4568 (save-excursion
4569 (org-back-to-heading)
4570 (save-excursion
4571 (beginning-of-line 2)
4572 (while (and (not (eobp)) ;; this is like `next-line'
4573 (get-char-property (1- (point)) 'invisible))
4574 (beginning-of-line 2)) (setq eol (point)))
4575 (outline-end-of-heading) (setq eoh (point))
4576 (org-end-of-subtree t)
4577 (unless (eobp)
4578 (skip-chars-forward " \t\n")
4579 (beginning-of-line 1) ; in case this is an item
4581 (setq eos (1- (point))))
4582 ;; Find out what to do next and set `this-command'
4583 (cond
4584 ((= eos eoh)
4585 ;; Nothing is hidden behind this heading
4586 (message "EMPTY ENTRY")
4587 (setq org-cycle-subtree-status nil)
4588 (save-excursion
4589 (goto-char eos)
4590 (outline-next-heading)
4591 (if (org-invisible-p) (org-flag-heading nil))))
4592 ((or (>= eol eos)
4593 (not (string-match "\\S-" (buffer-substring eol eos))))
4594 ;; Entire subtree is hidden in one line: open it
4595 (org-show-entry)
4596 (show-children)
4597 (message "CHILDREN")
4598 (save-excursion
4599 (goto-char eos)
4600 (outline-next-heading)
4601 (if (org-invisible-p) (org-flag-heading nil)))
4602 (setq org-cycle-subtree-status 'children)
4603 (run-hook-with-args 'org-cycle-hook 'children))
4604 ((and (eq last-command this-command)
4605 (eq org-cycle-subtree-status 'children))
4606 ;; We just showed the children, now show everything.
4607 (org-show-subtree)
4608 (message "SUBTREE")
4609 (setq org-cycle-subtree-status 'subtree)
4610 (run-hook-with-args 'org-cycle-hook 'subtree))
4612 ;; Default action: hide the subtree.
4613 (hide-subtree)
4614 (message "FOLDED")
4615 (setq org-cycle-subtree-status 'folded)
4616 (run-hook-with-args 'org-cycle-hook 'folded)))))
4618 ;; TAB emulation and template completion
4619 (buffer-read-only (org-back-to-heading))
4621 ((org-try-structure-completion))
4623 ((org-try-cdlatex-tab))
4625 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4626 (or (not (bolp))
4627 (not (looking-at outline-regexp))))
4628 (call-interactively (global-key-binding "\t")))
4630 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4631 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4632 (or (and (eq org-cycle-emulate-tab 'white)
4633 (= (match-end 0) (point-at-eol)))
4634 (and (eq org-cycle-emulate-tab 'whitestart)
4635 (>= (match-end 0) pos))))
4637 (eq org-cycle-emulate-tab t))
4638 (call-interactively (global-key-binding "\t")))
4640 (t (save-excursion
4641 (org-back-to-heading)
4642 (org-cycle))))))
4644 ;;;###autoload
4645 (defun org-global-cycle (&optional arg)
4646 "Cycle the global visibility. For details see `org-cycle'.
4647 With C-u prefix arg, switch to startup visibility.
4648 With a numeric prefix, show all headlines up to that level."
4649 (interactive "P")
4650 (let ((org-cycle-include-plain-lists
4651 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4652 (cond
4653 ((integerp arg)
4654 (show-all)
4655 (hide-sublevels arg)
4656 (setq org-cycle-global-status 'contents))
4657 ((equal arg '(4))
4658 (org-set-startup-visibility)
4659 (message "Startup visibility, plus VISIBILITY properties."))
4661 (org-cycle '(4))))))
4663 (defun org-set-startup-visibility ()
4664 "Set the visibility required by startup options and properties."
4665 (cond
4666 ((eq org-startup-folded t)
4667 (org-cycle '(4)))
4668 ((eq org-startup-folded 'content)
4669 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4670 (org-cycle '(4)) (org-cycle '(4)))))
4671 (org-set-visibility-according-to-property 'no-cleanup)
4672 (org-cycle-hide-archived-subtrees 'all)
4673 (org-cycle-hide-drawers 'all)
4674 (org-cycle-show-empty-lines 'all))
4676 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4677 "Switch subtree visibilities according to :VISIBILITY: property."
4678 (interactive)
4679 (let (org-show-entry-below state)
4680 (save-excursion
4681 (goto-char (point-min))
4682 (while (re-search-forward
4683 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4684 nil t)
4685 (setq state (match-string 1))
4686 (save-excursion
4687 (org-back-to-heading t)
4688 (hide-subtree)
4689 (org-reveal)
4690 (cond
4691 ((equal state '("fold" "folded"))
4692 (hide-subtree))
4693 ((equal state "children")
4694 (org-show-hidden-entry)
4695 (show-children))
4696 ((equal state "content")
4697 (save-excursion
4698 (save-restriction
4699 (org-narrow-to-subtree)
4700 (org-content))))
4701 ((member state '("all" "showall"))
4702 (show-subtree)))))
4703 (unless no-cleanup
4704 (org-cycle-hide-archived-subtrees 'all)
4705 (org-cycle-hide-drawers 'all)
4706 (org-cycle-show-empty-lines 'all)))))
4708 (defun org-overview ()
4709 "Switch to overview mode, showing only top-level headlines.
4710 Really, this shows all headlines with level equal or greater than the level
4711 of the first headline in the buffer. This is important, because if the
4712 first headline is not level one, then (hide-sublevels 1) gives confusing
4713 results."
4714 (interactive)
4715 (let ((level (save-excursion
4716 (goto-char (point-min))
4717 (if (re-search-forward (concat "^" outline-regexp) nil t)
4718 (progn
4719 (goto-char (match-beginning 0))
4720 (funcall outline-level))))))
4721 (and level (hide-sublevels level))))
4723 (defun org-content (&optional arg)
4724 "Show all headlines in the buffer, like a table of contents.
4725 With numerical argument N, show content up to level N."
4726 (interactive "P")
4727 (save-excursion
4728 ;; Visit all headings and show their offspring
4729 (and (integerp arg) (org-overview))
4730 (goto-char (point-max))
4731 (catch 'exit
4732 (while (and (progn (condition-case nil
4733 (outline-previous-visible-heading 1)
4734 (error (goto-char (point-min))))
4736 (looking-at outline-regexp))
4737 (if (integerp arg)
4738 (show-children (1- arg))
4739 (show-branches))
4740 (if (bobp) (throw 'exit nil))))))
4743 (defun org-optimize-window-after-visibility-change (state)
4744 "Adjust the window after a change in outline visibility.
4745 This function is the default value of the hook `org-cycle-hook'."
4746 (when (get-buffer-window (current-buffer))
4747 (cond
4748 ((eq state 'content) nil)
4749 ((eq state 'all) nil)
4750 ((eq state 'folded) nil)
4751 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4752 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4754 (defun org-compact-display-after-subtree-move ()
4755 "Show a compacter version of the tree of the entry's parent."
4756 (save-excursion
4757 (if (org-up-heading-safe)
4758 (progn
4759 (hide-subtree)
4760 (show-entry)
4761 (show-children)
4762 (org-cycle-show-empty-lines 'children)
4763 (org-cycle-hide-drawers 'children))
4764 (org-overview))))
4766 (defun org-cycle-show-empty-lines (state)
4767 "Show empty lines above all visible headlines.
4768 The region to be covered depends on STATE when called through
4769 `org-cycle-hook'. Lisp program can use t for STATE to get the
4770 entire buffer covered. Note that an empty line is only shown if there
4771 are at least `org-cycle-separator-lines' empty lines before the headline."
4772 (when (> org-cycle-separator-lines 0)
4773 (save-excursion
4774 (let* ((n org-cycle-separator-lines)
4775 (re (cond
4776 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4777 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4778 (t (let ((ns (number-to-string (- n 2))))
4779 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4780 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4781 beg end)
4782 (cond
4783 ((memq state '(overview contents t))
4784 (setq beg (point-min) end (point-max)))
4785 ((memq state '(children folded))
4786 (setq beg (point) end (progn (org-end-of-subtree t t)
4787 (beginning-of-line 2)
4788 (point)))))
4789 (when beg
4790 (goto-char beg)
4791 (while (re-search-forward re end t)
4792 (if (not (get-char-property (match-end 1) 'invisible))
4793 (outline-flag-region
4794 (match-beginning 1) (match-end 1) nil)))))))
4795 ;; Never hide empty lines at the end of the file.
4796 (save-excursion
4797 (goto-char (point-max))
4798 (outline-previous-heading)
4799 (outline-end-of-heading)
4800 (if (and (looking-at "[ \t\n]+")
4801 (= (match-end 0) (point-max)))
4802 (outline-flag-region (point) (match-end 0) nil))))
4804 (defun org-show-empty-lines-in-parent ()
4805 "Move to the parent and re-show empty lines before visible headlines."
4806 (save-excursion
4807 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4808 (org-cycle-show-empty-lines context))))
4810 (defun org-cycle-hide-drawers (state)
4811 "Re-hide all drawers after a visibility state change."
4812 (when (and (org-mode-p)
4813 (not (memq state '(overview folded))))
4814 (save-excursion
4815 (let* ((globalp (memq state '(contents all)))
4816 (beg (if globalp (point-min) (point)))
4817 (end (if globalp (point-max) (org-end-of-subtree t))))
4818 (goto-char beg)
4819 (while (re-search-forward org-drawer-regexp end t)
4820 (org-flag-drawer t))))))
4822 (defun org-flag-drawer (flag)
4823 (save-excursion
4824 (beginning-of-line 1)
4825 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4826 (let ((b (match-end 0))
4827 (outline-regexp org-outline-regexp))
4828 (if (re-search-forward
4829 "^[ \t]*:END:"
4830 (save-excursion (outline-next-heading) (point)) t)
4831 (outline-flag-region b (point-at-eol) flag)
4832 (error ":END: line missing"))))))
4834 (defun org-subtree-end-visible-p ()
4835 "Is the end of the current subtree visible?"
4836 (pos-visible-in-window-p
4837 (save-excursion (org-end-of-subtree t) (point))))
4839 (defun org-first-headline-recenter (&optional N)
4840 "Move cursor to the first headline and recenter the headline.
4841 Optional argument N means, put the headline into the Nth line of the window."
4842 (goto-char (point-min))
4843 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4844 (beginning-of-line)
4845 (recenter (prefix-numeric-value N))))
4847 ;;; Org-goto
4849 (defvar org-goto-window-configuration nil)
4850 (defvar org-goto-marker nil)
4851 (defvar org-goto-map
4852 (let ((map (make-sparse-keymap)))
4853 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4854 (while (setq cmd (pop cmds))
4855 (substitute-key-definition cmd cmd map global-map)))
4856 (suppress-keymap map)
4857 (org-defkey map "\C-m" 'org-goto-ret)
4858 (org-defkey map [(return)] 'org-goto-ret)
4859 (org-defkey map [(left)] 'org-goto-left)
4860 (org-defkey map [(right)] 'org-goto-right)
4861 (org-defkey map [(control ?g)] 'org-goto-quit)
4862 (org-defkey map "\C-i" 'org-cycle)
4863 (org-defkey map [(tab)] 'org-cycle)
4864 (org-defkey map [(down)] 'outline-next-visible-heading)
4865 (org-defkey map [(up)] 'outline-previous-visible-heading)
4866 (if org-goto-auto-isearch
4867 (if (fboundp 'define-key-after)
4868 (define-key-after map [t] 'org-goto-local-auto-isearch)
4869 nil)
4870 (org-defkey map "q" 'org-goto-quit)
4871 (org-defkey map "n" 'outline-next-visible-heading)
4872 (org-defkey map "p" 'outline-previous-visible-heading)
4873 (org-defkey map "f" 'outline-forward-same-level)
4874 (org-defkey map "b" 'outline-backward-same-level)
4875 (org-defkey map "u" 'outline-up-heading))
4876 (org-defkey map "/" 'org-occur)
4877 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4878 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4879 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4880 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4881 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4882 map))
4884 (defconst org-goto-help
4885 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4886 RET=jump to location [Q]uit and return to previous location
4887 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4889 (defvar org-goto-start-pos) ; dynamically scoped parameter
4891 ;; FIXME: Docstring doe not mention both interfaces
4892 (defun org-goto (&optional alternative-interface)
4893 "Look up a different location in the current file, keeping current visibility.
4895 When you want look-up or go to a different location in a document, the
4896 fastest way is often to fold the entire buffer and then dive into the tree.
4897 This method has the disadvantage, that the previous location will be folded,
4898 which may not be what you want.
4900 This command works around this by showing a copy of the current buffer
4901 in an indirect buffer, in overview mode. You can dive into the tree in
4902 that copy, use org-occur and incremental search to find a location.
4903 When pressing RET or `Q', the command returns to the original buffer in
4904 which the visibility is still unchanged. After RET is will also jump to
4905 the location selected in the indirect buffer and expose the
4906 the headline hierarchy above."
4907 (interactive "P")
4908 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4909 (org-refile-use-outline-path t)
4910 (interface
4911 (if (not alternative-interface)
4912 org-goto-interface
4913 (if (eq org-goto-interface 'outline)
4914 'outline-path-completion
4915 'outline)))
4916 (org-goto-start-pos (point))
4917 (selected-point
4918 (if (eq interface 'outline)
4919 (car (org-get-location (current-buffer) org-goto-help))
4920 (nth 3 (org-refile-get-location "Goto: ")))))
4921 (if selected-point
4922 (progn
4923 (org-mark-ring-push org-goto-start-pos)
4924 (goto-char selected-point)
4925 (if (or (org-invisible-p) (org-invisible-p2))
4926 (org-show-context 'org-goto)))
4927 (message "Quit"))))
4929 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4930 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4931 (defvar org-goto-local-auto-isearch-map) ; defined below
4933 (defun org-get-location (buf help)
4934 "Let the user select a location in the Org-mode buffer BUF.
4935 This function uses a recursive edit. It returns the selected position
4936 or nil."
4937 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4938 (isearch-hide-immediately nil)
4939 (isearch-search-fun-function
4940 (lambda () 'org-goto-local-search-headings))
4941 (org-goto-selected-point org-goto-exit-command))
4942 (save-excursion
4943 (save-window-excursion
4944 (delete-other-windows)
4945 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4946 (switch-to-buffer
4947 (condition-case nil
4948 (make-indirect-buffer (current-buffer) "*org-goto*")
4949 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4950 (with-output-to-temp-buffer "*Help*"
4951 (princ help))
4952 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4953 (setq buffer-read-only nil)
4954 (let ((org-startup-truncated t)
4955 (org-startup-folded nil)
4956 (org-startup-align-all-tables nil))
4957 (org-mode)
4958 (org-overview))
4959 (setq buffer-read-only t)
4960 (if (and (boundp 'org-goto-start-pos)
4961 (integer-or-marker-p org-goto-start-pos))
4962 (let ((org-show-hierarchy-above t)
4963 (org-show-siblings t)
4964 (org-show-following-heading t))
4965 (goto-char org-goto-start-pos)
4966 (and (org-invisible-p) (org-show-context)))
4967 (goto-char (point-min)))
4968 (let (org-special-ctrl-a/e) (org-beginning-of-line))
4969 (message "Select location and press RET")
4970 (use-local-map org-goto-map)
4971 (recursive-edit)
4973 (kill-buffer "*org-goto*")
4974 (cons org-goto-selected-point org-goto-exit-command)))
4976 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4977 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4978 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4979 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4981 (defun org-goto-local-search-headings (string bound noerror)
4982 "Search and make sure that any matches are in headlines."
4983 (catch 'return
4984 (while (if isearch-forward
4985 (search-forward string bound noerror)
4986 (search-backward string bound noerror))
4987 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4988 (and (member :headline context)
4989 (not (member :tags context))))
4990 (throw 'return (point))))))
4992 (defun org-goto-local-auto-isearch ()
4993 "Start isearch."
4994 (interactive)
4995 (goto-char (point-min))
4996 (let ((keys (this-command-keys)))
4997 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4998 (isearch-mode t)
4999 (isearch-process-search-char (string-to-char keys)))))
5001 (defun org-goto-ret (&optional arg)
5002 "Finish `org-goto' by going to the new location."
5003 (interactive "P")
5004 (setq org-goto-selected-point (point)
5005 org-goto-exit-command 'return)
5006 (throw 'exit nil))
5008 (defun org-goto-left ()
5009 "Finish `org-goto' by going to the new location."
5010 (interactive)
5011 (if (org-on-heading-p)
5012 (progn
5013 (beginning-of-line 1)
5014 (setq org-goto-selected-point (point)
5015 org-goto-exit-command 'left)
5016 (throw 'exit nil))
5017 (error "Not on a heading")))
5019 (defun org-goto-right ()
5020 "Finish `org-goto' by going to the new location."
5021 (interactive)
5022 (if (org-on-heading-p)
5023 (progn
5024 (setq org-goto-selected-point (point)
5025 org-goto-exit-command 'right)
5026 (throw 'exit nil))
5027 (error "Not on a heading")))
5029 (defun org-goto-quit ()
5030 "Finish `org-goto' without cursor motion."
5031 (interactive)
5032 (setq org-goto-selected-point nil)
5033 (setq org-goto-exit-command 'quit)
5034 (throw 'exit nil))
5036 ;;; Indirect buffer display of subtrees
5038 (defvar org-indirect-dedicated-frame nil
5039 "This is the frame being used for indirect tree display.")
5040 (defvar org-last-indirect-buffer nil)
5042 (defun org-tree-to-indirect-buffer (&optional arg)
5043 "Create indirect buffer and narrow it to current subtree.
5044 With numerical prefix ARG, go up to this level and then take that tree.
5045 If ARG is negative, go up that many levels.
5046 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5047 indirect buffer previously made with this command, to avoid proliferation of
5048 indirect buffers. However, when you call the command with a `C-u' prefix, or
5049 when `org-indirect-buffer-display' is `new-frame', the last buffer
5050 is kept so that you can work with several indirect buffers at the same time.
5051 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5052 requests that a new frame be made for the new buffer, so that the dedicated
5053 frame is not changed."
5054 (interactive "P")
5055 (let ((cbuf (current-buffer))
5056 (cwin (selected-window))
5057 (pos (point))
5058 beg end level heading ibuf)
5059 (save-excursion
5060 (org-back-to-heading t)
5061 (when (numberp arg)
5062 (setq level (org-outline-level))
5063 (if (< arg 0) (setq arg (+ level arg)))
5064 (while (> (setq level (org-outline-level)) arg)
5065 (outline-up-heading 1 t)))
5066 (setq beg (point)
5067 heading (org-get-heading))
5068 (org-end-of-subtree t) (setq end (point)))
5069 (if (and (buffer-live-p org-last-indirect-buffer)
5070 (not (eq org-indirect-buffer-display 'new-frame))
5071 (not arg))
5072 (kill-buffer org-last-indirect-buffer))
5073 (setq ibuf (org-get-indirect-buffer cbuf)
5074 org-last-indirect-buffer ibuf)
5075 (cond
5076 ((or (eq org-indirect-buffer-display 'new-frame)
5077 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5078 (select-frame (make-frame))
5079 (delete-other-windows)
5080 (switch-to-buffer ibuf)
5081 (org-set-frame-title heading))
5082 ((eq org-indirect-buffer-display 'dedicated-frame)
5083 (raise-frame
5084 (select-frame (or (and org-indirect-dedicated-frame
5085 (frame-live-p org-indirect-dedicated-frame)
5086 org-indirect-dedicated-frame)
5087 (setq org-indirect-dedicated-frame (make-frame)))))
5088 (delete-other-windows)
5089 (switch-to-buffer ibuf)
5090 (org-set-frame-title (concat "Indirect: " heading)))
5091 ((eq org-indirect-buffer-display 'current-window)
5092 (switch-to-buffer ibuf))
5093 ((eq org-indirect-buffer-display 'other-window)
5094 (pop-to-buffer ibuf))
5095 (t (error "Invalid value.")))
5096 (if (featurep 'xemacs)
5097 (save-excursion (org-mode) (turn-on-font-lock)))
5098 (narrow-to-region beg end)
5099 (show-all)
5100 (goto-char pos)
5101 (and (window-live-p cwin) (select-window cwin))))
5103 (defun org-get-indirect-buffer (&optional buffer)
5104 (setq buffer (or buffer (current-buffer)))
5105 (let ((n 1) (base (buffer-name buffer)) bname)
5106 (while (buffer-live-p
5107 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5108 (setq n (1+ n)))
5109 (condition-case nil
5110 (make-indirect-buffer buffer bname 'clone)
5111 (error (make-indirect-buffer buffer bname)))))
5113 (defun org-set-frame-title (title)
5114 "Set the title of the current frame to the string TITLE."
5115 ;; FIXME: how to name a single frame in XEmacs???
5116 (unless (featurep 'xemacs)
5117 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5119 ;;;; Structure editing
5121 ;;; Inserting headlines
5123 (defun org-previous-line-empty-p ()
5124 (save-excursion
5125 (and (not (bobp))
5126 (or (beginning-of-line 0) t)
5127 (save-match-data
5128 (looking-at "[ \t]*$")))))
5130 (defun org-insert-heading (&optional force-heading)
5131 "Insert a new heading or item with same depth at point.
5132 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5133 If point is at the beginning of a headline, insert a sibling before the
5134 current headline. If point is not at the beginning, do not split the line,
5135 but create the new headline after the current line."
5136 (interactive "P")
5137 (if (= (buffer-size) 0)
5138 (insert "\n* ")
5139 (when (or force-heading (not (org-insert-item)))
5140 (let* ((empty-line-p nil)
5141 (head (save-excursion
5142 (condition-case nil
5143 (progn
5144 (org-back-to-heading)
5145 (setq empty-line-p (org-previous-line-empty-p))
5146 (match-string 0))
5147 (error "*"))))
5148 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5149 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5150 pos hide-previous previous-pos)
5151 (cond
5152 ((and (org-on-heading-p) (bolp)
5153 (or (bobp)
5154 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5155 ;; insert before the current line
5156 (open-line (if blank 2 1)))
5157 ((and (bolp)
5158 (or (bobp)
5159 (save-excursion
5160 (backward-char 1) (not (org-invisible-p)))))
5161 ;; insert right here
5162 nil)
5164 ;; somewhere in the line
5165 (save-excursion
5166 (setq previous-pos (point-at-bol))
5167 (end-of-line)
5168 (setq hide-previous (org-invisible-p)))
5169 (and org-insert-heading-respect-content (org-show-subtree))
5170 (let ((split
5171 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5172 (save-excursion
5173 (let ((p (point)))
5174 (goto-char (point-at-bol))
5175 (and (looking-at org-complex-heading-regexp)
5176 (> p (match-beginning 4)))))))
5177 tags pos)
5178 (cond
5179 (org-insert-heading-respect-content
5180 (org-end-of-subtree nil t)
5181 (or (bolp) (newline))
5182 (or (org-previous-line-empty-p)
5183 (and blank (newline)))
5184 (open-line 1))
5185 ((org-on-heading-p)
5186 (when hide-previous
5187 (show-children)
5188 (org-show-entry))
5189 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5190 (setq tags (and (match-end 2) (match-string 2)))
5191 (and (match-end 1)
5192 (delete-region (match-beginning 1) (match-end 1)))
5193 (setq pos (point-at-bol))
5194 (or split (end-of-line 1))
5195 (delete-horizontal-space)
5196 (newline (if blank 2 1))
5197 (when tags
5198 (save-excursion
5199 (goto-char pos)
5200 (end-of-line 1)
5201 (insert " " tags)
5202 (org-set-tags nil 'align))))
5204 (or split (end-of-line 1))
5205 (newline (if blank 2 1)))))))
5206 (insert head) (just-one-space)
5207 (setq pos (point))
5208 (end-of-line 1)
5209 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5210 (when (and org-insert-heading-respect-content hide-previous)
5211 (save-excursion
5212 (goto-char previous-pos)
5213 (hide-subtree)))
5214 (run-hooks 'org-insert-heading-hook)))))
5216 (defun org-get-heading (&optional no-tags)
5217 "Return the heading of the current entry, without the stars."
5218 (save-excursion
5219 (org-back-to-heading t)
5220 (if (looking-at
5221 (if no-tags
5222 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5223 "\\*+[ \t]+\\([^\r\n]*\\)"))
5224 (match-string 1) "")))
5226 (defun org-heading-components ()
5227 "Return the components of the current heading.
5228 This is a list with the following elements:
5229 - the level as an integer
5230 - the reduced level, different if `org-odd-levels-only' is set.
5231 - the TODO keyword, or nil
5232 - the priority character, like ?A, or nil if no priority is given
5233 - the headline text itself, or the tags string if no headline text
5234 - the tags string, or nil."
5235 (save-excursion
5236 (org-back-to-heading t)
5237 (if (looking-at org-complex-heading-regexp)
5238 (list (length (match-string 1))
5239 (org-reduced-level (length (match-string 1)))
5240 (org-match-string-no-properties 2)
5241 (and (match-end 3) (aref (match-string 3) 2))
5242 (org-match-string-no-properties 4)
5243 (org-match-string-no-properties 5)))))
5245 (defun org-insert-heading-after-current ()
5246 "Insert a new heading with same level as current, after current subtree."
5247 (interactive)
5248 (org-back-to-heading)
5249 (org-insert-heading)
5250 (org-move-subtree-down)
5251 (end-of-line 1))
5253 (defun org-insert-heading-respect-content ()
5254 (interactive)
5255 (let ((org-insert-heading-respect-content t))
5256 (org-insert-heading t)))
5258 (defun org-insert-todo-heading-respect-content (&optional force-state)
5259 (interactive "P")
5260 (let ((org-insert-heading-respect-content t))
5261 (org-insert-todo-heading force-state t)))
5263 (defun org-insert-todo-heading (arg &optional force-heading)
5264 "Insert a new heading with the same level and TODO state as current heading.
5265 If the heading has no TODO state, or if the state is DONE, use the first
5266 state (TODO by default). Also with prefix arg, force first state."
5267 (interactive "P")
5268 (when (or force-heading (not (org-insert-item 'checkbox)))
5269 (org-insert-heading force-heading)
5270 (save-excursion
5271 (org-back-to-heading)
5272 (outline-previous-heading)
5273 (looking-at org-todo-line-regexp))
5274 (let*
5275 ((new-mark-x
5276 (if (or arg
5277 (not (match-beginning 2))
5278 (member (match-string 2) org-done-keywords))
5279 (car org-todo-keywords-1)
5280 (match-string 2)))
5281 (new-mark
5283 (run-hook-with-args-until-success
5284 'org-todo-get-default-hook new-mark-x nil)
5285 new-mark-x)))
5286 (beginning-of-line 1)
5287 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5288 (insert new-mark " ")))
5289 (when org-provide-todo-statistics
5290 (org-update-parent-todo-statistics))))
5292 (defun org-insert-subheading (arg)
5293 "Insert a new subheading and demote it.
5294 Works for outline headings and for plain lists alike."
5295 (interactive "P")
5296 (org-insert-heading arg)
5297 (cond
5298 ((org-on-heading-p) (org-do-demote))
5299 ((org-at-item-p) (org-indent-item 1))))
5301 (defun org-insert-todo-subheading (arg)
5302 "Insert a new subheading with TODO keyword or checkbox and demote it.
5303 Works for outline headings and for plain lists alike."
5304 (interactive "P")
5305 (org-insert-todo-heading arg)
5306 (cond
5307 ((org-on-heading-p) (org-do-demote))
5308 ((org-at-item-p) (org-indent-item 1))))
5310 ;;; Promotion and Demotion
5312 (defun org-promote-subtree ()
5313 "Promote the entire subtree.
5314 See also `org-promote'."
5315 (interactive)
5316 (save-excursion
5317 (org-map-tree 'org-promote))
5318 (org-fix-position-after-promote))
5320 (defun org-demote-subtree ()
5321 "Demote the entire subtree. See `org-demote'.
5322 See also `org-promote'."
5323 (interactive)
5324 (save-excursion
5325 (org-map-tree 'org-demote))
5326 (org-fix-position-after-promote))
5329 (defun org-do-promote ()
5330 "Promote the current heading higher up the tree.
5331 If the region is active in `transient-mark-mode', promote all headings
5332 in the region."
5333 (interactive)
5334 (save-excursion
5335 (if (org-region-active-p)
5336 (org-map-region 'org-promote (region-beginning) (region-end))
5337 (org-promote)))
5338 (org-fix-position-after-promote))
5340 (defun org-do-demote ()
5341 "Demote the current heading lower down the tree.
5342 If the region is active in `transient-mark-mode', demote all headings
5343 in the region."
5344 (interactive)
5345 (save-excursion
5346 (if (org-region-active-p)
5347 (org-map-region 'org-demote (region-beginning) (region-end))
5348 (org-demote)))
5349 (org-fix-position-after-promote))
5351 (defun org-fix-position-after-promote ()
5352 "Make sure that after pro/demotion cursor position is right."
5353 (let ((pos (point)))
5354 (when (save-excursion
5355 (beginning-of-line 1)
5356 (looking-at org-todo-line-regexp)
5357 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5358 (cond ((eobp) (insert " "))
5359 ((eolp) (insert " "))
5360 ((equal (char-after) ?\ ) (forward-char 1))))))
5362 (defun org-reduced-level (l)
5363 "Compute the effective level of a heading.
5364 This takes into account the setting of `org-odd-levels-only'."
5365 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5367 (defun org-get-valid-level (level &optional change)
5368 "Rectify a level change under the influence of `org-odd-levels-only'
5369 LEVEL is a current level, CHANGE is by how much the level should be
5370 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5371 even level numbers will become the next higher odd number."
5372 (if org-odd-levels-only
5373 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5374 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5375 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5376 (max 1 (+ level (or change 0)))))
5378 (if (boundp 'define-obsolete-function-alias)
5379 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5380 (define-obsolete-function-alias 'org-get-legal-level
5381 'org-get-valid-level)
5382 (define-obsolete-function-alias 'org-get-legal-level
5383 'org-get-valid-level "23.1")))
5385 (defun org-promote ()
5386 "Promote the current heading higher up the tree.
5387 If the region is active in `transient-mark-mode', promote all headings
5388 in the region."
5389 (org-back-to-heading t)
5390 (let* ((level (save-match-data (funcall outline-level)))
5391 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5392 (diff (abs (- level (length up-head) -1))))
5393 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5394 (replace-match up-head nil t)
5395 ;; Fixup tag positioning
5396 (and org-auto-align-tags (org-set-tags nil t))
5397 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5399 (defun org-demote ()
5400 "Demote the current heading lower down the tree.
5401 If the region is active in `transient-mark-mode', demote all headings
5402 in the region."
5403 (org-back-to-heading t)
5404 (let* ((level (save-match-data (funcall outline-level)))
5405 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5406 (diff (abs (- level (length down-head) -1))))
5407 (replace-match down-head nil t)
5408 ;; Fixup tag positioning
5409 (and org-auto-align-tags (org-set-tags nil t))
5410 (if org-adapt-indentation (org-fixup-indentation diff))))
5412 (defun org-map-tree (fun)
5413 "Call FUN for every heading underneath the current one."
5414 (org-back-to-heading)
5415 (let ((level (funcall outline-level)))
5416 (save-excursion
5417 (funcall fun)
5418 (while (and (progn
5419 (outline-next-heading)
5420 (> (funcall outline-level) level))
5421 (not (eobp)))
5422 (funcall fun)))))
5424 (defun org-map-region (fun beg end)
5425 "Call FUN for every heading between BEG and END."
5426 (let ((org-ignore-region t))
5427 (save-excursion
5428 (setq end (copy-marker end))
5429 (goto-char beg)
5430 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5431 (< (point) end))
5432 (funcall fun))
5433 (while (and (progn
5434 (outline-next-heading)
5435 (< (point) end))
5436 (not (eobp)))
5437 (funcall fun)))))
5439 (defun org-fixup-indentation (diff)
5440 "Change the indentation in the current entry by DIFF
5441 However, if any line in the current entry has no indentation, or if it
5442 would end up with no indentation after the change, nothing at all is done."
5443 (save-excursion
5444 (let ((end (save-excursion (outline-next-heading)
5445 (point-marker)))
5446 (prohibit (if (> diff 0)
5447 "^\\S-"
5448 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5449 col)
5450 (unless (save-excursion (end-of-line 1)
5451 (re-search-forward prohibit end t))
5452 (while (and (< (point) end)
5453 (re-search-forward "^[ \t]+" end t))
5454 (goto-char (match-end 0))
5455 (setq col (current-column))
5456 (if (< diff 0) (replace-match ""))
5457 (org-indent-to-column (+ diff col))))
5458 (move-marker end nil))))
5460 (defun org-convert-to-odd-levels ()
5461 "Convert an org-mode file with all levels allowed to one with odd levels.
5462 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5463 level 5 etc."
5464 (interactive)
5465 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5466 (let ((org-odd-levels-only nil) n)
5467 (save-excursion
5468 (goto-char (point-min))
5469 (while (re-search-forward "^\\*\\*+ " nil t)
5470 (setq n (- (length (match-string 0)) 2))
5471 (while (>= (setq n (1- n)) 0)
5472 (org-demote))
5473 (end-of-line 1))))))
5476 (defun org-convert-to-oddeven-levels ()
5477 "Convert an org-mode file with only odd levels to one with odd and even levels.
5478 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5479 section with an even level, conversion would destroy the structure of the file. An error
5480 is signaled in this case."
5481 (interactive)
5482 (goto-char (point-min))
5483 ;; First check if there are no even levels
5484 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5485 (org-show-context t)
5486 (error "Not all levels are odd in this file. Conversion not possible."))
5487 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5488 (let ((org-odd-levels-only nil) n)
5489 (save-excursion
5490 (goto-char (point-min))
5491 (while (re-search-forward "^\\*\\*+ " nil t)
5492 (setq n (/ (1- (length (match-string 0))) 2))
5493 (while (>= (setq n (1- n)) 0)
5494 (org-promote))
5495 (end-of-line 1))))))
5497 (defun org-tr-level (n)
5498 "Make N odd if required."
5499 (if org-odd-levels-only (1+ (/ n 2)) n))
5501 ;;; Vertical tree motion, cutting and pasting of subtrees
5503 (defun org-move-subtree-up (&optional arg)
5504 "Move the current subtree up past ARG headlines of the same level."
5505 (interactive "p")
5506 (org-move-subtree-down (- (prefix-numeric-value arg))))
5508 (defun org-move-subtree-down (&optional arg)
5509 "Move the current subtree down past ARG headlines of the same level."
5510 (interactive "p")
5511 (setq arg (prefix-numeric-value arg))
5512 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5513 'outline-get-last-sibling))
5514 (ins-point (make-marker))
5515 (cnt (abs arg))
5516 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5517 ;; Select the tree
5518 (org-back-to-heading)
5519 (setq beg0 (point))
5520 (save-excursion
5521 (setq ne-beg (org-back-over-empty-lines))
5522 (setq beg (point)))
5523 (save-match-data
5524 (save-excursion (outline-end-of-heading)
5525 (setq folded (org-invisible-p)))
5526 (outline-end-of-subtree))
5527 (outline-next-heading)
5528 (setq ne-end (org-back-over-empty-lines))
5529 (setq end (point))
5530 (goto-char beg0)
5531 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5532 ;; include less whitespace
5533 (save-excursion
5534 (goto-char beg)
5535 (forward-line (- ne-beg ne-end))
5536 (setq beg (point))))
5537 ;; Find insertion point, with error handling
5538 (while (> cnt 0)
5539 (or (and (funcall movfunc) (looking-at outline-regexp))
5540 (progn (goto-char beg0)
5541 (error "Cannot move past superior level or buffer limit")))
5542 (setq cnt (1- cnt)))
5543 (if (> arg 0)
5544 ;; Moving forward - still need to move over subtree
5545 (progn (org-end-of-subtree t t)
5546 (save-excursion
5547 (org-back-over-empty-lines)
5548 (or (bolp) (newline)))))
5549 (setq ne-ins (org-back-over-empty-lines))
5550 (move-marker ins-point (point))
5551 (setq txt (buffer-substring beg end))
5552 (org-save-markers-in-region beg end)
5553 (delete-region beg end)
5554 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5555 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5556 (let ((bbb (point)))
5557 (insert-before-markers txt)
5558 (org-reinstall-markers-in-region bbb)
5559 (move-marker ins-point bbb))
5560 (or (bolp) (insert "\n"))
5561 (setq ins-end (point))
5562 (goto-char ins-point)
5563 (org-skip-whitespace)
5564 (when (and (< arg 0)
5565 (org-first-sibling-p)
5566 (> ne-ins ne-beg))
5567 ;; Move whitespace back to beginning
5568 (save-excursion
5569 (goto-char ins-end)
5570 (let ((kill-whole-line t))
5571 (kill-line (- ne-ins ne-beg)) (point)))
5572 (insert (make-string (- ne-ins ne-beg) ?\n)))
5573 (move-marker ins-point nil)
5574 (org-compact-display-after-subtree-move)
5575 (org-show-empty-lines-in-parent)
5576 (unless folded
5577 (org-show-entry)
5578 (show-children)
5579 (org-cycle-hide-drawers 'children))))
5581 (defvar org-subtree-clip ""
5582 "Clipboard for cut and paste of subtrees.
5583 This is actually only a copy of the kill, because we use the normal kill
5584 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5586 (defvar org-subtree-clip-folded nil
5587 "Was the last copied subtree folded?
5588 This is used to fold the tree back after pasting.")
5590 (defun org-cut-subtree (&optional n)
5591 "Cut the current subtree into the clipboard.
5592 With prefix arg N, cut this many sequential subtrees.
5593 This is a short-hand for marking the subtree and then cutting it."
5594 (interactive "p")
5595 (org-copy-subtree n 'cut))
5597 (defun org-copy-subtree (&optional n cut force-store-markers)
5598 "Cut the current subtree into the clipboard.
5599 With prefix arg N, cut this many sequential subtrees.
5600 This is a short-hand for marking the subtree and then copying it.
5601 If CUT is non-nil, actually cut the subtree.
5602 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5603 of some markers in the region, even if CUT is non-nil. This is
5604 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5605 (interactive "p")
5606 (let (beg end folded (beg0 (point)))
5607 (if (interactive-p)
5608 (org-back-to-heading nil) ; take what looks like a subtree
5609 (org-back-to-heading t)) ; take what is really there
5610 (org-back-over-empty-lines)
5611 (setq beg (point))
5612 (skip-chars-forward " \t\r\n")
5613 (save-match-data
5614 (save-excursion (outline-end-of-heading)
5615 (setq folded (org-invisible-p)))
5616 (condition-case nil
5617 (outline-forward-same-level (1- n))
5618 (error nil))
5619 (org-end-of-subtree t t))
5620 (org-back-over-empty-lines)
5621 (setq end (point))
5622 (goto-char beg0)
5623 (when (> end beg)
5624 (setq org-subtree-clip-folded folded)
5625 (when (or cut force-store-markers)
5626 (org-save-markers-in-region beg end))
5627 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5628 (setq org-subtree-clip (current-kill 0))
5629 (message "%s: Subtree(s) with %d characters"
5630 (if cut "Cut" "Copied")
5631 (length org-subtree-clip)))))
5633 (defun org-paste-subtree (&optional level tree for-yank)
5634 "Paste the clipboard as a subtree, with modification of headline level.
5635 The entire subtree is promoted or demoted in order to match a new headline
5636 level.
5638 If the cursor is at the beginning of a headline, the same level as
5639 that headline is used to paste the tree
5641 If not, the new level is derived from the *visible* headings
5642 before and after the insertion point, and taken to be the inferior headline
5643 level of the two. So if the previous visible heading is level 3 and the
5644 next is level 4 (or vice versa), level 4 will be used for insertion.
5645 This makes sure that the subtree remains an independent subtree and does
5646 not swallow low level entries.
5648 You can also force a different level, either by using a numeric prefix
5649 argument, or by inserting the heading marker by hand. For example, if the
5650 cursor is after \"*****\", then the tree will be shifted to level 5.
5652 If optional TREE is given, use this text instead of the kill ring.
5654 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5655 move back over whitespace before inserting, and move point to the end of
5656 the inserted text when done."
5657 (interactive "P")
5658 (unless (org-kill-is-subtree-p tree)
5659 (error "%s"
5660 (substitute-command-keys
5661 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5662 (let* ((visp (not (org-invisible-p)))
5663 (txt (or tree (and kill-ring (current-kill 0))))
5664 (^re (concat "^\\(" outline-regexp "\\)"))
5665 (re (concat "\\(" outline-regexp "\\)"))
5666 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5668 (old-level (if (string-match ^re txt)
5669 (- (match-end 0) (match-beginning 0) 1)
5670 -1))
5671 (force-level (cond (level (prefix-numeric-value level))
5672 ((and (looking-at "[ \t]*$")
5673 (string-match
5674 ^re_ (buffer-substring
5675 (point-at-bol) (point))))
5676 (- (match-end 1) (match-beginning 1)))
5677 ((and (bolp)
5678 (looking-at org-outline-regexp))
5679 (- (match-end 0) (point) 1))
5680 (t nil)))
5681 (previous-level (save-excursion
5682 (condition-case nil
5683 (progn
5684 (outline-previous-visible-heading 1)
5685 (if (looking-at re)
5686 (- (match-end 0) (match-beginning 0) 1)
5688 (error 1))))
5689 (next-level (save-excursion
5690 (condition-case nil
5691 (progn
5692 (or (looking-at outline-regexp)
5693 (outline-next-visible-heading 1))
5694 (if (looking-at re)
5695 (- (match-end 0) (match-beginning 0) 1)
5697 (error 1))))
5698 (new-level (or force-level (max previous-level next-level)))
5699 (shift (if (or (= old-level -1)
5700 (= new-level -1)
5701 (= old-level new-level))
5703 (- new-level old-level)))
5704 (delta (if (> shift 0) -1 1))
5705 (func (if (> shift 0) 'org-demote 'org-promote))
5706 (org-odd-levels-only nil)
5707 beg end newend)
5708 ;; Remove the forced level indicator
5709 (if force-level
5710 (delete-region (point-at-bol) (point)))
5711 ;; Paste
5712 (beginning-of-line 1)
5713 (unless for-yank (org-back-over-empty-lines))
5714 (setq beg (point))
5715 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5716 (insert-before-markers txt)
5717 (unless (string-match "\n\\'" txt) (insert "\n"))
5718 (setq newend (point))
5719 (org-reinstall-markers-in-region beg)
5720 (setq end (point))
5721 (goto-char beg)
5722 (skip-chars-forward " \t\n\r")
5723 (setq beg (point))
5724 (if (and (org-invisible-p) visp)
5725 (save-excursion (outline-show-heading)))
5726 ;; Shift if necessary
5727 (unless (= shift 0)
5728 (save-restriction
5729 (narrow-to-region beg end)
5730 (while (not (= shift 0))
5731 (org-map-region func (point-min) (point-max))
5732 (setq shift (+ delta shift)))
5733 (goto-char (point-min))
5734 (setq newend (point-max))))
5735 (when (or (interactive-p) for-yank)
5736 (message "Clipboard pasted as level %d subtree" new-level))
5737 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5738 kill-ring
5739 (eq org-subtree-clip (current-kill 0))
5740 org-subtree-clip-folded)
5741 ;; The tree was folded before it was killed/copied
5742 (hide-subtree))
5743 (and for-yank (goto-char newend))))
5745 (defun org-kill-is-subtree-p (&optional txt)
5746 "Check if the current kill is an outline subtree, or a set of trees.
5747 Returns nil if kill does not start with a headline, or if the first
5748 headline level is not the largest headline level in the tree.
5749 So this will actually accept several entries of equal levels as well,
5750 which is OK for `org-paste-subtree'.
5751 If optional TXT is given, check this string instead of the current kill."
5752 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5753 (start-level (and kill
5754 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5755 org-outline-regexp "\\)")
5756 kill)
5757 (- (match-end 2) (match-beginning 2) 1)))
5758 (re (concat "^" org-outline-regexp))
5759 (start (1+ (or (match-beginning 2) -1))))
5760 (if (not start-level)
5761 (progn
5762 nil) ;; does not even start with a heading
5763 (catch 'exit
5764 (while (setq start (string-match re kill (1+ start)))
5765 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5766 (throw 'exit nil)))
5767 t))))
5769 (defvar org-markers-to-move nil
5770 "Markers that should be moved with a cut-and-paste operation.
5771 Those markers are stored together with their positions relative to
5772 the start of the region.")
5774 (defun org-save-markers-in-region (beg end)
5775 "Check markers in region.
5776 If these markers are between BEG and END, record their position relative
5777 to BEG, so that after moving the block of text, we can put the markers back
5778 into place.
5779 This function gets called just before an entry or tree gets cut from the
5780 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5781 called immediately, to move the markers with the entries."
5782 (setq org-markers-to-move nil)
5783 (when (featurep 'org-clock)
5784 (org-clock-save-markers-for-cut-and-paste beg end))
5785 (when (featurep 'org-agenda)
5786 (org-agenda-save-markers-for-cut-and-paste beg end)))
5788 (defun org-check-and-save-marker (marker beg end)
5789 "Check if MARKER is between BEG and END.
5790 If yes, remember the marker and the distance to BEG."
5791 (when (and (marker-buffer marker)
5792 (equal (marker-buffer marker) (current-buffer)))
5793 (if (and (>= marker beg) (< marker end))
5794 (push (cons marker (- marker beg)) org-markers-to-move))))
5796 (defun org-reinstall-markers-in-region (beg)
5797 "Move all remembered markers to their position relative to BEG."
5798 (mapc (lambda (x)
5799 (move-marker (car x) (+ beg (cdr x))))
5800 org-markers-to-move)
5801 (setq org-markers-to-move nil))
5803 (defun org-narrow-to-subtree ()
5804 "Narrow buffer to the current subtree."
5805 (interactive)
5806 (save-excursion
5807 (save-match-data
5808 (narrow-to-region
5809 (progn (org-back-to-heading) (point))
5810 (progn (org-end-of-subtree t) (point))))))
5812 (defun org-clone-subtree-with-time-shift (n &optional shift)
5813 "Clone the task (subtree) at point N times.
5814 The clones will be inserted as siblings.
5816 In interactive use, the user will be prompted for the number of clones
5817 to be produced, and for a time SHIFT, which may be a repeater as used
5818 in time stamps, for example `+3d'.
5820 When a valid repeater is given and the entry contains any time stamps,
5821 the clones will become a sequence in time, with time stamps in the
5822 subtree shifted for each clone produced. If SHIFT is nil or the
5823 empty string, time stamps will be left alone.
5825 If the original subtree did contain time stamps with a repeater,
5826 the following will happen:
5827 - the repeater will be removed in each clone
5828 - an additional clone will be produced, with the current, unshifted
5829 date(s) in the entry.
5830 - the original entry will be placed *after* all the clones, with
5831 repeater intact.
5832 - the start days in the repeater in the original entry will be shifted
5833 to past the last clone.
5834 I this way you can spell out a number of instances of a repeating task,
5835 and still retain the repeater to cover future instances of the task."
5836 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
5837 (let (beg end template task
5838 shift-n shift-what doshift nmin nmax (n-no-remove -1))
5839 (if (not (and (integerp n) (> n 0)))
5840 (error "Invalid number of replications %s" n))
5841 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
5842 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
5843 shift)))
5844 (error "Invalid shift specification %s" shift))
5845 (when doshift
5846 (setq shift-n (string-to-number (match-string 1 shift))
5847 shift-what (cdr (assoc (match-string 2 shift)
5848 '(("d" . day) ("w" . week)
5849 ("m" . month) ("y" . year))))))
5850 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
5851 (setq nmin 1 nmax n)
5852 (org-back-to-heading t)
5853 (setq beg (point))
5854 (org-end-of-subtree t t)
5855 (setq end (point))
5856 (setq template (buffer-substring beg end))
5857 (when (and doshift
5858 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
5859 (delete-region beg end)
5860 (setq end beg)
5861 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
5862 (goto-char end)
5863 (loop for n from nmin to nmax do
5864 (if (not doshift)
5865 (setq task template)
5866 (with-temp-buffer
5867 (insert template)
5868 (org-mode)
5869 (goto-char (point-min))
5870 (while (re-search-forward org-ts-regexp nil t)
5871 (org-timestamp-change (* n shift-n) shift-what))
5872 (unless (= n n-no-remove)
5873 (goto-char (point-min))
5874 (while (re-search-forward org-ts-regexp nil t)
5875 (save-excursion
5876 (goto-char (match-beginning 0))
5877 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
5878 (delete-region (match-beginning 1) (match-end 1))))))
5879 (setq task (buffer-string))))
5880 (insert task))
5881 (goto-char beg)))
5883 ;;; Outline Sorting
5885 (defun org-sort (with-case)
5886 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5887 Optional argument WITH-CASE means sort case-sensitively.
5888 With a double prefix argument, also remove duplicate entries."
5889 (interactive "P")
5890 (if (org-at-table-p)
5891 (org-call-with-arg 'org-table-sort-lines with-case)
5892 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5894 (defun org-sort-remove-invisible (s)
5895 (remove-text-properties 0 (length s) org-rm-props s)
5896 (while (string-match org-bracket-link-regexp s)
5897 (setq s (replace-match (if (match-end 2)
5898 (match-string 3 s)
5899 (match-string 1 s)) t t s)))
5902 (defvar org-priority-regexp) ; defined later in the file
5904 (defun org-sort-entries-or-items
5905 (&optional with-case sorting-type getkey-func compare-func property)
5906 "Sort entries on a certain level of an outline tree.
5907 If there is an active region, the entries in the region are sorted.
5908 Else, if the cursor is before the first entry, sort the top-level items.
5909 Else, the children of the entry at point are sorted.
5911 Sorting can be alphabetically, numerically, and by date/time as given by
5912 the first time stamp in the entry. The command prompts for the sorting
5913 type unless it has been given to the function through the SORTING-TYPE
5914 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5915 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5916 called with point at the beginning of the record. It must return either
5917 a string or a number that should serve as the sorting key for that record.
5919 Comparing entries ignores case by default. However, with an optional argument
5920 WITH-CASE, the sorting considers case as well."
5921 (interactive "P")
5922 (let ((case-func (if with-case 'identity 'downcase))
5923 start beg end stars re re2
5924 txt what tmp plain-list-p)
5925 ;; Find beginning and end of region to sort
5926 (cond
5927 ((org-region-active-p)
5928 ;; we will sort the region
5929 (setq end (region-end)
5930 what "region")
5931 (goto-char (region-beginning))
5932 (if (not (org-on-heading-p)) (outline-next-heading))
5933 (setq start (point)))
5934 ((org-at-item-p)
5935 ;; we will sort this plain list
5936 (org-beginning-of-item-list) (setq start (point))
5937 (org-end-of-item-list) (setq end (point))
5938 (goto-char start)
5939 (setq plain-list-p t
5940 what "plain list"))
5941 ((or (org-on-heading-p)
5942 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5943 ;; we will sort the children of the current headline
5944 (org-back-to-heading)
5945 (setq start (point)
5946 end (progn (org-end-of-subtree t t)
5947 (org-back-over-empty-lines)
5948 (point))
5949 what "children")
5950 (goto-char start)
5951 (show-subtree)
5952 (outline-next-heading))
5954 ;; we will sort the top-level entries in this file
5955 (goto-char (point-min))
5956 (or (org-on-heading-p) (outline-next-heading))
5957 (setq start (point) end (point-max) what "top-level")
5958 (goto-char start)
5959 (show-all)))
5961 (setq beg (point))
5962 (if (>= beg end) (error "Nothing to sort"))
5964 (unless plain-list-p
5965 (looking-at "\\(\\*+\\)")
5966 (setq stars (match-string 1)
5967 re (concat "^" (regexp-quote stars) " +")
5968 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5969 txt (buffer-substring beg end))
5970 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5971 (if (and (not (equal stars "*")) (string-match re2 txt))
5972 (error "Region to sort contains a level above the first entry")))
5974 (unless sorting-type
5975 (message
5976 (if plain-list-p
5977 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5978 "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:")
5979 what)
5980 (setq sorting-type (read-char-exclusive))
5982 (and (= (downcase sorting-type) ?f)
5983 (setq getkey-func
5984 (org-ido-completing-read "Sort using function: "
5985 obarray 'fboundp t nil nil))
5986 (setq getkey-func (intern getkey-func)))
5988 (and (= (downcase sorting-type) ?r)
5989 (setq property
5990 (org-ido-completing-read "Property: "
5991 (mapcar 'list (org-buffer-property-keys t))
5992 nil t))))
5994 (message "Sorting entries...")
5996 (save-restriction
5997 (narrow-to-region start end)
5999 (let ((dcst (downcase sorting-type))
6000 (now (current-time)))
6001 (sort-subr
6002 (/= dcst sorting-type)
6003 ;; This function moves to the beginning character of the "record" to
6004 ;; be sorted.
6005 (if plain-list-p
6006 (lambda nil
6007 (if (org-at-item-p) t (goto-char (point-max))))
6008 (lambda nil
6009 (if (re-search-forward re nil t)
6010 (goto-char (match-beginning 0))
6011 (goto-char (point-max)))))
6012 ;; This function moves to the last character of the "record" being
6013 ;; sorted.
6014 (if plain-list-p
6015 'org-end-of-item
6016 (lambda nil
6017 (save-match-data
6018 (condition-case nil
6019 (outline-forward-same-level 1)
6020 (error
6021 (goto-char (point-max)))))))
6023 ;; This function returns the value that gets sorted against.
6024 (if plain-list-p
6025 (lambda nil
6026 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6027 (cond
6028 ((= dcst ?n)
6029 (string-to-number (buffer-substring (match-end 0)
6030 (point-at-eol))))
6031 ((= dcst ?a)
6032 (buffer-substring (match-end 0) (point-at-eol)))
6033 ((= dcst ?t)
6034 (if (re-search-forward org-ts-regexp
6035 (point-at-eol) t)
6036 (org-time-string-to-time (match-string 0))
6037 now))
6038 ((= dcst ?f)
6039 (if getkey-func
6040 (progn
6041 (setq tmp (funcall getkey-func))
6042 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6043 tmp)
6044 (error "Invalid key function `%s'" getkey-func)))
6045 (t (error "Invalid sorting type `%c'" sorting-type)))))
6046 (lambda nil
6047 (cond
6048 ((= dcst ?n)
6049 (if (looking-at org-complex-heading-regexp)
6050 (string-to-number (match-string 4))
6051 nil))
6052 ((= dcst ?a)
6053 (if (looking-at org-complex-heading-regexp)
6054 (funcall case-func (match-string 4))
6055 nil))
6056 ((= dcst ?t)
6057 (if (re-search-forward org-ts-regexp
6058 (save-excursion
6059 (forward-line 2)
6060 (point)) t)
6061 (org-time-string-to-time (match-string 0))
6062 now))
6063 ((= dcst ?p)
6064 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6065 (string-to-char (match-string 2))
6066 org-default-priority))
6067 ((= dcst ?r)
6068 (or (org-entry-get nil property) ""))
6069 ((= dcst ?o)
6070 (if (looking-at org-complex-heading-regexp)
6071 (- 9999 (length (member (match-string 2)
6072 org-todo-keywords-1)))))
6073 ((= dcst ?f)
6074 (if getkey-func
6075 (progn
6076 (setq tmp (funcall getkey-func))
6077 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6078 tmp)
6079 (error "Invalid key function `%s'" getkey-func)))
6080 (t (error "Invalid sorting type `%c'" sorting-type)))))
6082 (cond
6083 ((= dcst ?a) 'string<)
6084 ((= dcst ?t) 'time-less-p)
6085 ((= dcst ?f) compare-func)
6086 (t nil)))))
6087 (message "Sorting entries...done")))
6089 (defun org-do-sort (table what &optional with-case sorting-type)
6090 "Sort TABLE of WHAT according to SORTING-TYPE.
6091 The user will be prompted for the SORTING-TYPE if the call to this
6092 function does not specify it. WHAT is only for the prompt, to indicate
6093 what is being sorted. The sorting key will be extracted from
6094 the car of the elements of the table.
6095 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6096 (unless sorting-type
6097 (message
6098 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6099 what)
6100 (setq sorting-type (read-char-exclusive)))
6101 (let ((dcst (downcase sorting-type))
6102 extractfun comparefun)
6103 ;; Define the appropriate functions
6104 (cond
6105 ((= dcst ?n)
6106 (setq extractfun 'string-to-number
6107 comparefun (if (= dcst sorting-type) '< '>)))
6108 ((= dcst ?a)
6109 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6110 (lambda(x) (downcase (org-sort-remove-invisible x))))
6111 comparefun (if (= dcst sorting-type)
6112 'string<
6113 (lambda (a b) (and (not (string< a b))
6114 (not (string= a b)))))))
6115 ((= dcst ?t)
6116 (setq extractfun
6117 (lambda (x)
6118 (if (or (string-match org-ts-regexp x)
6119 (string-match org-ts-regexp-both x))
6120 (time-to-seconds
6121 (org-time-string-to-time (match-string 0 x)))
6123 comparefun (if (= dcst sorting-type) '< '>)))
6124 (t (error "Invalid sorting type `%c'" sorting-type)))
6126 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6127 table)
6128 (lambda (a b) (funcall comparefun (car a) (car b))))))
6130 ;;; Editing source examples
6132 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6133 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6134 (defvar org-edit-src-force-single-line nil)
6135 (defvar org-edit-src-from-org-mode nil)
6136 (defvar org-edit-src-picture nil)
6138 (define-minor-mode org-exit-edit-mode
6139 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6141 (defun org-edit-src-code ()
6142 "Edit the source code example at point.
6143 An indirect buffer is created, and that buffer is then narrowed to the
6144 example at point and switched to the correct language mode. When done,
6145 exit by killing the buffer with \\[org-edit-src-exit]."
6146 (interactive)
6147 (let ((line (org-current-line))
6148 (case-fold-search t)
6149 (msg (substitute-command-keys
6150 "Edit, then exit with C-c ' (C-c and single quote)"))
6151 (info (org-edit-src-find-region-and-lang))
6152 (org-mode-p (eq major-mode 'org-mode))
6153 beg end lang lang-f single lfmt)
6154 (if (not info)
6156 (setq beg (nth 0 info)
6157 end (nth 1 info)
6158 lang (nth 2 info)
6159 single (nth 3 info)
6160 lfmt (nth 4 info)
6161 lang-f (intern (concat lang "-mode")))
6162 (unless (functionp lang-f)
6163 (error "No such language mode: %s" lang-f))
6164 (goto-line line)
6165 (if (get-buffer "*Org Edit Src Example*")
6166 (kill-buffer "*Org Edit Src Example*"))
6167 (switch-to-buffer (make-indirect-buffer (current-buffer)
6168 "*Org Edit Src Example*"))
6169 (narrow-to-region beg end)
6170 (remove-text-properties beg end '(display nil invisible nil
6171 intangible nil))
6172 (let ((org-inhibit-startup t))
6173 (funcall lang-f))
6174 (set (make-local-variable 'org-edit-src-force-single-line) single)
6175 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6176 (when lfmt
6177 (set (make-local-variable 'org-coderef-label-format) lfmt))
6178 (when org-mode-p
6179 (goto-char (point-min))
6180 (while (re-search-forward "^," nil t)
6181 (replace-match "")))
6182 (goto-line line)
6183 (org-exit-edit-mode)
6184 (org-set-local 'header-line-format msg)
6185 (message "%s" msg)
6186 t)))
6188 (defun org-edit-fixed-width-region ()
6189 "Edit the fixed-width ascii drawing at point.
6190 This must be a region where each line starts with a colon followed by
6191 a space character.
6192 An indirect buffer is created, and that buffer is then narrowed to the
6193 example at point and switched to artist-mode. When done,
6194 exit by killing the buffer with \\[org-edit-src-exit]."
6195 (interactive)
6196 (let ((line (org-current-line))
6197 (case-fold-search t)
6198 (msg (substitute-command-keys
6199 "Edit, then exit with C-c ' (C-c and single quote)"))
6200 (org-mode-p (eq major-mode 'org-mode))
6201 beg end)
6202 (beginning-of-line 1)
6203 (if (looking-at "[ \t]*[^:\n \t]")
6205 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6206 (setq beg (point) end beg)
6207 (save-excursion
6208 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6209 (setq beg (point-at-bol 2))
6210 (setq beg (point))))
6211 (save-excursion
6212 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6213 (setq end (1- (match-beginning 0)))
6214 (setq end (point))))
6215 (goto-line line))
6216 (if (get-buffer "*Org Edit Picture*")
6217 (kill-buffer "*Org Edit Picture*"))
6218 (switch-to-buffer (make-indirect-buffer (current-buffer)
6219 "*Org Edit Picture*"))
6220 (narrow-to-region beg end)
6221 (remove-text-properties beg end '(display nil invisible nil
6222 intangible nil))
6223 (when (fboundp 'font-lock-unfontify-region)
6224 (font-lock-unfontify-region (point-min) (point-max)))
6225 (cond
6226 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6227 (fundamental-mode)
6228 (artist-mode 1))
6229 (t (funcall org-edit-fixed-width-region-mode)))
6230 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6231 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6232 (set (make-local-variable 'org-edit-src-picture) t)
6233 (goto-char (point-min))
6234 (while (re-search-forward "^[ \t]*: ?" nil t)
6235 (replace-match ""))
6236 (goto-line line)
6237 (org-exit-edit-mode)
6238 (org-set-local 'header-line-format msg)
6239 (message "%s" msg)
6240 t)))
6243 (defun org-edit-src-find-region-and-lang ()
6244 "Find the region and language for a local edit.
6245 Return a list with beginning and end of the region, a string representing
6246 the language, a switch telling of the content should be in a single line."
6247 (let ((re-list
6248 (append
6249 org-edit-src-region-extra
6251 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6252 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6253 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6254 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6255 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6256 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6257 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6258 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6259 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6260 ("^#\\+html:" "\n" "html" single-line)
6261 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6262 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6263 ("^#\\+latex:" "\n" "latex" single-line)
6264 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6265 ("^#\\+ascii:" "\n" "ascii" single-line)
6267 (pos (point))
6268 re1 re2 single beg end lang lfmt match-re1)
6269 (catch 'exit
6270 (while (setq entry (pop re-list))
6271 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6272 single (nth 3 entry))
6273 (save-excursion
6274 (if (or (looking-at re1)
6275 (re-search-backward re1 nil t))
6276 (progn
6277 (setq match-re1 (match-string 0))
6278 (setq beg (match-end 0)
6279 lang (org-edit-src-get-lang lang)
6280 lfmt (org-edit-src-get-label-format match-re1))
6281 (if (and (re-search-forward re2 nil t)
6282 (>= (match-end 0) pos))
6283 (throw 'exit (list beg (match-beginning 0)
6284 lang single lfmt))))
6285 (if (or (looking-at re2)
6286 (re-search-forward re2 nil t))
6287 (progn
6288 (setq end (match-beginning 0))
6289 (if (and (re-search-backward re1 nil t)
6290 (<= (match-beginning 0) pos))
6291 (progn
6292 (setq lfmt (org-edit-src-get-label-format
6293 (match-string 0)))
6294 (throw 'exit
6295 (list (match-end 0) end
6296 (org-edit-src-get-lang lang)
6297 single lfmt))))))))))))
6299 (defun org-edit-src-get-lang (lang)
6300 "Extract the src language."
6301 (let ((m (match-string 0)))
6302 (cond
6303 ((stringp lang) lang)
6304 ((integerp lang) (match-string lang))
6305 ((and (eq lang 'lang)
6306 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6307 (match-string 1 m))
6308 ((and (eq lang 'style)
6309 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6310 (match-string 1 m))
6311 (t "fundamental"))))
6313 (defun org-edit-src-get-label-format (s)
6314 "Extract the label format."
6315 (save-match-data
6316 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6317 (match-string 1 s))))
6319 (defun org-edit-src-exit ()
6320 "Exit special edit and protect problematic lines."
6321 (interactive)
6322 (unless (buffer-base-buffer (current-buffer))
6323 (error "This is not an indirect buffer, something is wrong..."))
6324 (unless (> (point-min) 1)
6325 (error "This buffer is not narrowed, something is wrong..."))
6326 (goto-char (point-min))
6327 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6328 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6329 (when (org-bound-and-true-p org-edit-src-force-single-line)
6330 (goto-char (point-min))
6331 (while (re-search-forward "\n" nil t)
6332 (replace-match " "))
6333 (goto-char (point-min))
6334 (if (looking-at "\\s-*") (replace-match " "))
6335 (if (re-search-forward "\\s-+\\'" nil t)
6336 (replace-match "")))
6337 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6338 (goto-char (point-min))
6339 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6340 (replace-match ",\\1"))
6341 (when font-lock-mode
6342 (font-lock-unfontify-region (point-min) (point-max)))
6343 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6344 (when (org-bound-and-true-p org-edit-src-picture)
6345 (untabify (point-min) (point-max))
6346 (goto-char (point-min))
6347 (while (re-search-forward "^" nil t)
6348 (replace-match ": "))
6349 (when font-lock-mode
6350 (font-lock-unfontify-region (point-min) (point-max)))
6351 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6352 (kill-buffer (current-buffer))
6353 (and (org-mode-p) (org-restart-font-lock)))
6356 ;;; The orgstruct minor mode
6358 ;; Define a minor mode which can be used in other modes in order to
6359 ;; integrate the org-mode structure editing commands.
6361 ;; This is really a hack, because the org-mode structure commands use
6362 ;; keys which normally belong to the major mode. Here is how it
6363 ;; works: The minor mode defines all the keys necessary to operate the
6364 ;; structure commands, but wraps the commands into a function which
6365 ;; tests if the cursor is currently at a headline or a plain list
6366 ;; item. If that is the case, the structure command is used,
6367 ;; temporarily setting many Org-mode variables like regular
6368 ;; expressions for filling etc. However, when any of those keys is
6369 ;; used at a different location, function uses `key-binding' to look
6370 ;; up if the key has an associated command in another currently active
6371 ;; keymap (minor modes, major mode, global), and executes that
6372 ;; command. There might be problems if any of the keys is otherwise
6373 ;; used as a prefix key.
6375 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6376 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6377 ;; addresses this by checking explicitly for both bindings.
6379 (defvar orgstruct-mode-map (make-sparse-keymap)
6380 "Keymap for the minor `orgstruct-mode'.")
6382 (defvar org-local-vars nil
6383 "List of local variables, for use by `orgstruct-mode'")
6385 ;;;###autoload
6386 (define-minor-mode orgstruct-mode
6387 "Toggle the minor more `orgstruct-mode'.
6388 This mode is for using Org-mode structure commands in other modes.
6389 The following key behave as if Org-mode was active, if the cursor
6390 is on a headline, or on a plain list item (both in the definition
6391 of Org-mode).
6393 M-up Move entry/item up
6394 M-down Move entry/item down
6395 M-left Promote
6396 M-right Demote
6397 M-S-up Move entry/item up
6398 M-S-down Move entry/item down
6399 M-S-left Promote subtree
6400 M-S-right Demote subtree
6401 M-q Fill paragraph and items like in Org-mode
6402 C-c ^ Sort entries
6403 C-c - Cycle list bullet
6404 TAB Cycle item visibility
6405 M-RET Insert new heading/item
6406 S-M-RET Insert new TODO heading / Checkbox item
6407 C-c C-c Set tags / toggle checkbox"
6408 nil " OrgStruct" nil
6409 (org-load-modules-maybe)
6410 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6412 ;;;###autoload
6413 (defun turn-on-orgstruct ()
6414 "Unconditionally turn on `orgstruct-mode'."
6415 (orgstruct-mode 1))
6417 (defun orgstruct++-mode (&optional arg)
6418 "Toggle `orgstruct-mode', the enhanced version of it.
6419 In addition to setting orgstruct-mode, this also exports all indentation and
6420 autofilling variables from org-mode into the buffer. It will also
6421 recognize item context in multiline items.
6422 Note that turning off orgstruct-mode will *not* remove the
6423 indentation/paragraph settings. This can only be done by refreshing the
6424 major mode, for example with \[normal-mode]."
6425 (interactive "P")
6426 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6427 (if (< arg 1)
6428 (orgstruct-mode -1)
6429 (orgstruct-mode 1)
6430 (let (var val)
6431 (mapc
6432 (lambda (x)
6433 (when (string-match
6434 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6435 (symbol-name (car x)))
6436 (setq var (car x) val (nth 1 x))
6437 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6438 org-local-vars)
6439 (org-set-local 'orgstruct-is-++ t))))
6441 (defvar orgstruct-is-++ nil
6442 "Is orgstruct-mode in ++ version in the current-buffer?")
6443 (make-variable-buffer-local 'orgstruct-is-++)
6445 ;;;###autoload
6446 (defun turn-on-orgstruct++ ()
6447 "Unconditionally turn on `orgstruct++-mode'."
6448 (orgstruct++-mode 1))
6450 (defun orgstruct-error ()
6451 "Error when there is no default binding for a structure key."
6452 (interactive)
6453 (error "This key has no function outside structure elements"))
6455 (defun orgstruct-setup ()
6456 "Setup orgstruct keymaps."
6457 (let ((nfunc 0)
6458 (bindings
6459 (list
6460 '([(meta up)] org-metaup)
6461 '([(meta down)] org-metadown)
6462 '([(meta left)] org-metaleft)
6463 '([(meta right)] org-metaright)
6464 '([(meta shift up)] org-shiftmetaup)
6465 '([(meta shift down)] org-shiftmetadown)
6466 '([(meta shift left)] org-shiftmetaleft)
6467 '([(meta shift right)] org-shiftmetaright)
6468 '([(shift up)] org-shiftup)
6469 '([(shift down)] org-shiftdown)
6470 '([(shift left)] org-shiftleft)
6471 '([(shift right)] org-shiftright)
6472 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6473 '("\M-q" fill-paragraph)
6474 '("\C-c^" org-sort)
6475 '("\C-c-" org-cycle-list-bullet)))
6476 elt key fun cmd)
6477 (while (setq elt (pop bindings))
6478 (setq nfunc (1+ nfunc))
6479 (setq key (org-key (car elt))
6480 fun (nth 1 elt)
6481 cmd (orgstruct-make-binding fun nfunc key))
6482 (org-defkey orgstruct-mode-map key cmd))
6484 ;; Special treatment needed for TAB and RET
6485 (org-defkey orgstruct-mode-map [(tab)]
6486 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6487 (org-defkey orgstruct-mode-map "\C-i"
6488 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6490 (org-defkey orgstruct-mode-map "\M-\C-m"
6491 (orgstruct-make-binding 'org-insert-heading 105
6492 "\M-\C-m" [(meta return)]))
6493 (org-defkey orgstruct-mode-map [(meta return)]
6494 (orgstruct-make-binding 'org-insert-heading 106
6495 [(meta return)] "\M-\C-m"))
6497 (org-defkey orgstruct-mode-map [(shift meta return)]
6498 (orgstruct-make-binding 'org-insert-todo-heading 107
6499 [(meta return)] "\M-\C-m"))
6501 (unless org-local-vars
6502 (setq org-local-vars (org-get-local-variables)))
6506 (defun orgstruct-make-binding (fun n &rest keys)
6507 "Create a function for binding in the structure minor mode.
6508 FUN is the command to call inside a table. N is used to create a unique
6509 command name. KEYS are keys that should be checked in for a command
6510 to execute outside of tables."
6511 (eval
6512 (list 'defun
6513 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6514 '(arg)
6515 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6516 "Outside of structure, run the binding of `"
6517 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6518 "'.")
6519 '(interactive "p")
6520 (list 'if
6521 `(org-context-p 'headline 'item
6522 (and orgstruct-is-++
6523 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6524 'item-body))
6525 (list 'org-run-like-in-org-mode (list 'quote fun))
6526 (list 'let '(orgstruct-mode)
6527 (list 'call-interactively
6528 (append '(or)
6529 (mapcar (lambda (k)
6530 (list 'key-binding k))
6531 keys)
6532 '('orgstruct-error))))))))
6534 (defun org-context-p (&rest contexts)
6535 "Check if local context is any of CONTEXTS.
6536 Possible values in the list of contexts are `table', `headline', and `item'."
6537 (let ((pos (point)))
6538 (goto-char (point-at-bol))
6539 (prog1 (or (and (memq 'table contexts)
6540 (looking-at "[ \t]*|"))
6541 (and (memq 'headline contexts)
6542 ;;????????? (looking-at "\\*+"))
6543 (looking-at outline-regexp))
6544 (and (memq 'item contexts)
6545 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6546 (and (memq 'item-body contexts)
6547 (org-in-item-p)))
6548 (goto-char pos))))
6550 (defun org-get-local-variables ()
6551 "Return a list of all local variables in an org-mode buffer."
6552 (let (varlist)
6553 (with-current-buffer (get-buffer-create "*Org tmp*")
6554 (erase-buffer)
6555 (org-mode)
6556 (setq varlist (buffer-local-variables)))
6557 (kill-buffer "*Org tmp*")
6558 (delq nil
6559 (mapcar
6560 (lambda (x)
6561 (setq x
6562 (if (symbolp x)
6563 (list x)
6564 (list (car x) (list 'quote (cdr x)))))
6565 (if (string-match
6566 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6567 (symbol-name (car x)))
6568 x nil))
6569 varlist))))
6571 ;;;###autoload
6572 (defun org-run-like-in-org-mode (cmd)
6573 "Run a command, pretending that the current buffer is in Org-mode.
6574 This will temporarily bind local variables that are typically bound in
6575 Org-mode to the values they have in Org-mode, and then interactively
6576 call CMD."
6577 (org-load-modules-maybe)
6578 (unless org-local-vars
6579 (setq org-local-vars (org-get-local-variables)))
6580 (eval (list 'let org-local-vars
6581 (list 'call-interactively (list 'quote cmd)))))
6583 ;;;; Archiving
6585 (defun org-get-category (&optional pos)
6586 "Get the category applying to position POS."
6587 (get-text-property (or pos (point)) 'org-category))
6589 (defun org-refresh-category-properties ()
6590 "Refresh category text properties in the buffer."
6591 (let ((def-cat (cond
6592 ((null org-category)
6593 (if buffer-file-name
6594 (file-name-sans-extension
6595 (file-name-nondirectory buffer-file-name))
6596 "???"))
6597 ((symbolp org-category) (symbol-name org-category))
6598 (t org-category)))
6599 beg end cat pos optionp)
6600 (org-unmodified
6601 (save-excursion
6602 (save-restriction
6603 (widen)
6604 (goto-char (point-min))
6605 (put-text-property (point) (point-max) 'org-category def-cat)
6606 (while (re-search-forward
6607 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6608 (setq pos (match-end 0)
6609 optionp (equal (char-after (match-beginning 0)) ?#)
6610 cat (org-trim (match-string 2)))
6611 (if optionp
6612 (setq beg (point-at-bol) end (point-max))
6613 (org-back-to-heading t)
6614 (setq beg (point) end (org-end-of-subtree t t)))
6615 (put-text-property beg end 'org-category cat)
6616 (goto-char pos)))))))
6619 ;;;; Link Stuff
6621 ;;; Link abbreviations
6623 (defun org-link-expand-abbrev (link)
6624 "Apply replacements as defined in `org-link-abbrev-alist."
6625 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6626 (let* ((key (match-string 1 link))
6627 (as (or (assoc key org-link-abbrev-alist-local)
6628 (assoc key org-link-abbrev-alist)))
6629 (tag (and (match-end 2) (match-string 3 link)))
6630 rpl)
6631 (if (not as)
6632 link
6633 (setq rpl (cdr as))
6634 (cond
6635 ((symbolp rpl) (funcall rpl tag))
6636 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6637 ((string-match "%h" rpl)
6638 (replace-match (url-hexify-string (or tag "")) t t rpl))
6639 (t (concat rpl tag)))))
6640 link))
6642 ;;; Storing and inserting links
6644 (defvar org-insert-link-history nil
6645 "Minibuffer history for links inserted with `org-insert-link'.")
6647 (defvar org-stored-links nil
6648 "Contains the links stored with `org-store-link'.")
6650 (defvar org-store-link-plist nil
6651 "Plist with info about the most recently link created with `org-store-link'.")
6653 (defvar org-link-protocols nil
6654 "Link protocols added to Org-mode using `org-add-link-type'.")
6656 (defvar org-store-link-functions nil
6657 "List of functions that are called to create and store a link.
6658 Each function will be called in turn until one returns a non-nil
6659 value. Each function should check if it is responsible for creating
6660 this link (for example by looking at the major mode).
6661 If not, it must exit and return nil.
6662 If yes, it should return a non-nil value after a calling
6663 `org-store-link-props' with a list of properties and values.
6664 Special properties are:
6666 :type The link prefix. like \"http\". This must be given.
6667 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6668 This is obligatory as well.
6669 :description Optional default description for the second pair
6670 of brackets in an Org-mode link. The user can still change
6671 this when inserting this link into an Org-mode buffer.
6673 In addition to these, any additional properties can be specified
6674 and then used in remember templates.")
6676 (defun org-add-link-type (type &optional follow export)
6677 "Add TYPE to the list of `org-link-types'.
6678 Re-compute all regular expressions depending on `org-link-types'
6680 FOLLOW and EXPORT are two functions.
6682 FOLLOW should take the link path as the single argument and do whatever
6683 is necessary to follow the link, for example find a file or display
6684 a mail message.
6686 EXPORT should format the link path for export to one of the export formats.
6687 It should be a function accepting three arguments:
6689 path the path of the link, the text after the prefix (like \"http:\")
6690 desc the description of the link, if any, nil if there was no description
6691 format the export format, a symbol like `html' or `latex'.
6693 The function may use the FORMAT information to return different values
6694 depending on the format. The return value will be put literally into
6695 the exported file.
6696 Org-mode has a built-in default for exporting links. If you are happy with
6697 this default, there is no need to define an export function for the link
6698 type. For a simple example of an export function, see `org-bbdb.el'."
6699 (add-to-list 'org-link-types type t)
6700 (org-make-link-regexps)
6701 (if (assoc type org-link-protocols)
6702 (setcdr (assoc type org-link-protocols) (list follow export))
6703 (push (list type follow export) org-link-protocols)))
6705 ;;;###autoload
6706 (defun org-store-link (arg)
6707 "\\<org-mode-map>Store an org-link to the current location.
6708 This link is added to `org-stored-links' and can later be inserted
6709 into an org-buffer with \\[org-insert-link].
6711 For some link types, a prefix arg is interpreted:
6712 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6713 For file links, arg negates `org-context-in-file-links'."
6714 (interactive "P")
6715 (org-load-modules-maybe)
6716 (setq org-store-link-plist nil) ; reset
6717 (let (link cpltxt desc description search txt)
6718 (cond
6720 ((run-hook-with-args-until-success 'org-store-link-functions)
6721 (setq link (plist-get org-store-link-plist :link)
6722 desc (or (plist-get org-store-link-plist :description) link)))
6724 ((equal (buffer-name) "*Org Edit Src Example*")
6725 (let (label gc)
6726 (while (or (not label)
6727 (save-excursion
6728 (save-restriction
6729 (widen)
6730 (goto-char (point-min))
6731 (re-search-forward
6732 (regexp-quote (format org-coderef-label-format label))
6733 nil t))))
6734 (when label (message "Label exists already") (sit-for 2))
6735 (setq label (read-string "Code line label: " label)))
6736 (end-of-line 1)
6737 (setq link (format org-coderef-label-format label))
6738 (setq gc (- 79 (length link)))
6739 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6740 (insert link)
6741 (setq link (concat "(" label ")") desc nil)))
6743 ((eq major-mode 'calendar-mode)
6744 (let ((cd (calendar-cursor-to-date)))
6745 (setq link
6746 (format-time-string
6747 (car org-time-stamp-formats)
6748 (apply 'encode-time
6749 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6750 nil nil nil))))
6751 (org-store-link-props :type "calendar" :date cd)))
6753 ((eq major-mode 'w3-mode)
6754 (setq cpltxt (url-view-url t)
6755 link (org-make-link cpltxt))
6756 (org-store-link-props :type "w3" :url (url-view-url t)))
6758 ((eq major-mode 'w3m-mode)
6759 (setq cpltxt (or w3m-current-title w3m-current-url)
6760 link (org-make-link w3m-current-url))
6761 (org-store-link-props :type "w3m" :url (url-view-url t)))
6763 ((setq search (run-hook-with-args-until-success
6764 'org-create-file-search-functions))
6765 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6766 "::" search))
6767 (setq cpltxt (or description link)))
6769 ((eq major-mode 'image-mode)
6770 (setq cpltxt (concat "file:"
6771 (abbreviate-file-name buffer-file-name))
6772 link (org-make-link cpltxt))
6773 (org-store-link-props :type "image" :file buffer-file-name))
6775 ((eq major-mode 'dired-mode)
6776 ;; link to the file in the current line
6777 (setq cpltxt (concat "file:"
6778 (abbreviate-file-name
6779 (expand-file-name
6780 (dired-get-filename nil t))))
6781 link (org-make-link cpltxt)))
6783 ((and buffer-file-name (org-mode-p))
6784 (cond
6785 ((org-in-regexp "<<\\(.*?\\)>>")
6786 (setq cpltxt
6787 (concat "file:"
6788 (abbreviate-file-name buffer-file-name)
6789 "::" (match-string 1))
6790 link (org-make-link cpltxt)))
6791 ((and (featurep 'org-id)
6792 (or (eq org-link-to-org-use-id t)
6793 (and (eq org-link-to-org-use-id 'create-if-interactive)
6794 (interactive-p))
6795 (and org-link-to-org-use-id
6796 (condition-case nil
6797 (org-entry-get nil "ID")
6798 (error nil)))))
6799 ;; We can make a link using the ID.
6800 (setq link (condition-case nil
6801 (prog1 (org-id-store-link)
6802 (setq desc (plist-get org-store-link-plist
6803 :description)))
6804 (error
6805 ;; probably before first headline, link to file only
6806 (concat "file:"
6807 (abbreviate-file-name buffer-file-name))))))
6809 ;; Just link to current headline
6810 (setq cpltxt (concat "file:"
6811 (abbreviate-file-name buffer-file-name)))
6812 ;; Add a context search string
6813 (when (org-xor org-context-in-file-links arg)
6814 (setq txt (cond
6815 ((org-on-heading-p) nil)
6816 ((org-region-active-p)
6817 (buffer-substring (region-beginning) (region-end)))
6818 (t nil)))
6819 (when (or (null txt) (string-match "\\S-" txt))
6820 (setq cpltxt
6821 (concat cpltxt "::"
6822 (condition-case nil
6823 (org-make-org-heading-search-string txt)
6824 (error "")))
6825 desc "NONE")))
6826 (if (string-match "::\\'" cpltxt)
6827 (setq cpltxt (substring cpltxt 0 -2)))
6828 (setq link (org-make-link cpltxt)))))
6830 ((buffer-file-name (buffer-base-buffer))
6831 ;; Just link to this file here.
6832 (setq cpltxt (concat "file:"
6833 (abbreviate-file-name
6834 (buffer-file-name (buffer-base-buffer)))))
6835 ;; Add a context string
6836 (when (org-xor org-context-in-file-links arg)
6837 (setq txt (if (org-region-active-p)
6838 (buffer-substring (region-beginning) (region-end))
6839 (buffer-substring (point-at-bol) (point-at-eol))))
6840 ;; Only use search option if there is some text.
6841 (when (string-match "\\S-" txt)
6842 (setq cpltxt
6843 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6844 desc "NONE")))
6845 (setq link (org-make-link cpltxt)))
6847 ((interactive-p)
6848 (error "Cannot link to a buffer which is not visiting a file"))
6850 (t (setq link nil)))
6852 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6853 (setq link (or link cpltxt)
6854 desc (or desc cpltxt))
6855 (if (equal desc "NONE") (setq desc nil))
6857 (if (and (interactive-p) link)
6858 (progn
6859 (setq org-stored-links
6860 (cons (list link desc) org-stored-links))
6861 (message "Stored: %s" (or desc link)))
6862 (and link (org-make-link-string link desc)))))
6864 (defun org-store-link-props (&rest plist)
6865 "Store link properties, extract names and addresses."
6866 (let (x adr)
6867 (when (setq x (plist-get plist :from))
6868 (setq adr (mail-extract-address-components x))
6869 (setq plist (plist-put plist :fromname (car adr)))
6870 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6871 (when (setq x (plist-get plist :to))
6872 (setq adr (mail-extract-address-components x))
6873 (setq plist (plist-put plist :toname (car adr)))
6874 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6875 (let ((from (plist-get plist :from))
6876 (to (plist-get plist :to)))
6877 (when (and from to org-from-is-user-regexp)
6878 (setq plist
6879 (plist-put plist :fromto
6880 (if (string-match org-from-is-user-regexp from)
6881 (concat "to %t")
6882 (concat "from %f"))))))
6883 (setq org-store-link-plist plist))
6885 (defun org-add-link-props (&rest plist)
6886 "Add these properties to the link property list."
6887 (let (key value)
6888 (while plist
6889 (setq key (pop plist) value (pop plist))
6890 (setq org-store-link-plist
6891 (plist-put org-store-link-plist key value)))))
6893 (defun org-email-link-description (&optional fmt)
6894 "Return the description part of an email link.
6895 This takes information from `org-store-link-plist' and formats it
6896 according to FMT (default from `org-email-link-description-format')."
6897 (setq fmt (or fmt org-email-link-description-format))
6898 (let* ((p org-store-link-plist)
6899 (to (plist-get p :toaddress))
6900 (from (plist-get p :fromaddress))
6901 (table
6902 (list
6903 (cons "%c" (plist-get p :fromto))
6904 (cons "%F" (plist-get p :from))
6905 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6906 (cons "%T" (plist-get p :to))
6907 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6908 (cons "%s" (plist-get p :subject))
6909 (cons "%m" (plist-get p :message-id)))))
6910 (when (string-match "%c" fmt)
6911 ;; Check if the user wrote this message
6912 (if (and org-from-is-user-regexp from to
6913 (save-match-data (string-match org-from-is-user-regexp from)))
6914 (setq fmt (replace-match "to %t" t t fmt))
6915 (setq fmt (replace-match "from %f" t t fmt))))
6916 (org-replace-escapes fmt table)))
6918 (defun org-make-org-heading-search-string (&optional string heading)
6919 "Make search string for STRING or current headline."
6920 (interactive)
6921 (let ((s (or string (org-get-heading))))
6922 (unless (and string (not heading))
6923 ;; We are using a headline, clean up garbage in there.
6924 (if (string-match org-todo-regexp s)
6925 (setq s (replace-match "" t t s)))
6926 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6927 (setq s (replace-match "" t t s)))
6928 (setq s (org-trim s))
6929 (if (string-match (concat "^\\(" org-quote-string "\\|"
6930 org-comment-string "\\)") s)
6931 (setq s (replace-match "" t t s)))
6932 (while (string-match org-ts-regexp s)
6933 (setq s (replace-match "" t t s))))
6934 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6935 (setq s (replace-match " " t t s)))
6936 (or string (setq s (concat "*" s))) ; Add * for headlines
6937 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6939 (defun org-make-link (&rest strings)
6940 "Concatenate STRINGS."
6941 (apply 'concat strings))
6943 (defun org-make-link-string (link &optional description)
6944 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6945 (unless (string-match "\\S-" link)
6946 (error "Empty link"))
6947 (when (stringp description)
6948 ;; Remove brackets from the description, they are fatal.
6949 (while (string-match "\\[" description)
6950 (setq description (replace-match "{" t t description)))
6951 (while (string-match "\\]" description)
6952 (setq description (replace-match "}" t t description))))
6953 (when (equal (org-link-escape link) description)
6954 ;; No description needed, it is identical
6955 (setq description nil))
6956 (when (and (not description)
6957 (not (equal link (org-link-escape link))))
6958 (setq description (org-extract-attributes link)))
6959 (concat "[[" (org-link-escape link) "]"
6960 (if description (concat "[" description "]") "")
6961 "]"))
6963 (defconst org-link-escape-chars
6964 '((?\ . "%20")
6965 (?\[ . "%5B")
6966 (?\] . "%5D")
6967 (?\340 . "%E0") ; `a
6968 (?\342 . "%E2") ; ^a
6969 (?\347 . "%E7") ; ,c
6970 (?\350 . "%E8") ; `e
6971 (?\351 . "%E9") ; 'e
6972 (?\352 . "%EA") ; ^e
6973 (?\356 . "%EE") ; ^i
6974 (?\364 . "%F4") ; ^o
6975 (?\371 . "%F9") ; `u
6976 (?\373 . "%FB") ; ^u
6977 (?\; . "%3B")
6978 (?? . "%3F")
6979 (?= . "%3D")
6980 (?+ . "%2B")
6982 "Association list of escapes for some characters problematic in links.
6983 This is the list that is used for internal purposes.")
6985 (defconst org-link-escape-chars-browser
6986 '((?\ . "%20")) ; 32 for the SPC char
6987 "Association list of escapes for some characters problematic in links.
6988 This is the list that is used before handing over to the browser.")
6990 (defun org-link-escape (text &optional table)
6991 "Escape characters in TEXT that are problematic for links."
6992 (setq table (or table org-link-escape-chars))
6993 (when text
6994 (let ((re (mapconcat (lambda (x) (regexp-quote
6995 (char-to-string (car x))))
6996 table "\\|")))
6997 (while (string-match re text)
6998 (setq text
6999 (replace-match
7000 (cdr (assoc (string-to-char (match-string 0 text))
7001 table))
7002 t t text)))
7003 text)))
7005 (defun org-link-unescape (text &optional table)
7006 "Reverse the action of `org-link-escape'."
7007 (setq table (or table org-link-escape-chars))
7008 (when text
7009 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7010 table "\\|")))
7011 (while (string-match re text)
7012 (setq text
7013 (replace-match
7014 (char-to-string (car (rassoc (match-string 0 text) table)))
7015 t t text)))
7016 text)))
7018 (defun org-xor (a b)
7019 "Exclusive or."
7020 (if a (not b) b))
7022 (defun org-fixup-message-id-for-http (s)
7023 "Replace special characters in a message id, so it can be used in an http query."
7024 (while (string-match "<" s)
7025 (setq s (replace-match "%3C" t t s)))
7026 (while (string-match ">" s)
7027 (setq s (replace-match "%3E" t t s)))
7028 (while (string-match "@" s)
7029 (setq s (replace-match "%40" t t s)))
7032 ;;;###autoload
7033 (defun org-insert-link-global ()
7034 "Insert a link like Org-mode does.
7035 This command can be called in any mode to insert a link in Org-mode syntax."
7036 (interactive)
7037 (org-load-modules-maybe)
7038 (org-run-like-in-org-mode 'org-insert-link))
7040 (defun org-insert-link (&optional complete-file link-location)
7041 "Insert a link. At the prompt, enter the link.
7043 Completion can be used to insert any of the link protocol prefixes like
7044 http or ftp in use.
7046 The history can be used to select a link previously stored with
7047 `org-store-link'. When the empty string is entered (i.e. if you just
7048 press RET at the prompt), the link defaults to the most recently
7049 stored link. As SPC triggers completion in the minibuffer, you need to
7050 use M-SPC or C-q SPC to force the insertion of a space character.
7052 You will also be prompted for a description, and if one is given, it will
7053 be displayed in the buffer instead of the link.
7055 If there is already a link at point, this command will allow you to edit link
7056 and description parts.
7058 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7059 be selected using completion. The path to the file will be relative to the
7060 current directory if the file is in the current directory or a subdirectory.
7061 Otherwise, the link will be the absolute path as completed in the minibuffer
7062 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7063 option `org-link-file-path-type'.
7065 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7066 the current directory or below.
7068 With three \\[universal-argument] prefixes, negate the meaning of
7069 `org-keep-stored-link-after-insertion'.
7071 If `org-make-link-description-function' is non-nil, this function will be
7072 called with the link target, and the result will be the default
7073 link description.
7075 If the LINK-LOCATION parameter is non-nil, this value will be
7076 used as the link location instead of reading one interactively."
7077 (interactive "P")
7078 (let* ((wcf (current-window-configuration))
7079 (region (if (org-region-active-p)
7080 (buffer-substring (region-beginning) (region-end))))
7081 (remove (and region (list (region-beginning) (region-end))))
7082 (desc region)
7083 tmphist ; byte-compile incorrectly complains about this
7084 (link link-location)
7085 entry file)
7086 (cond
7087 (link-location) ; specified by arg, just use it.
7088 ((org-in-regexp org-bracket-link-regexp 1)
7089 ;; We do have a link at point, and we are going to edit it.
7090 (setq remove (list (match-beginning 0) (match-end 0)))
7091 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7092 (setq link (read-string "Link: "
7093 (org-link-unescape
7094 (org-match-string-no-properties 1)))))
7095 ((or (org-in-regexp org-angle-link-re)
7096 (org-in-regexp org-plain-link-re))
7097 ;; Convert to bracket link
7098 (setq remove (list (match-beginning 0) (match-end 0))
7099 link (read-string "Link: "
7100 (org-remove-angle-brackets (match-string 0)))))
7101 ((member complete-file '((4) (16)))
7102 ;; Completing read for file names.
7103 (setq file (read-file-name "File: "))
7104 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7105 (pwd1 (file-name-as-directory (abbreviate-file-name
7106 (expand-file-name ".")))))
7107 (cond
7108 ((equal complete-file '(16))
7109 (setq link (org-make-link
7110 "file:"
7111 (abbreviate-file-name (expand-file-name file)))))
7112 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7113 (setq link (org-make-link "file:" (match-string 1 file))))
7114 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7115 (expand-file-name file))
7116 (setq link (org-make-link
7117 "file:" (match-string 1 (expand-file-name file)))))
7118 (t (setq link (org-make-link "file:" file))))))
7120 ;; Read link, with completion for stored links.
7121 (with-output-to-temp-buffer "*Org Links*"
7122 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7123 (when org-stored-links
7124 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7125 (princ (mapconcat
7126 (lambda (x)
7127 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7128 (reverse org-stored-links) "\n"))))
7129 (let ((cw (selected-window)))
7130 (select-window (get-buffer-window "*Org Links*"))
7131 (setq truncate-lines t)
7132 (org-fit-window-to-buffer)
7133 (select-window cw))
7134 ;; Fake a link history, containing the stored links.
7135 (setq tmphist (append (mapcar 'car org-stored-links)
7136 org-insert-link-history))
7137 (unwind-protect
7138 (setq link
7139 (let ((org-completion-use-ido nil))
7140 (org-completing-read
7141 "Link: "
7142 (append
7143 (mapcar (lambda (x) (list (concat (car x) ":")))
7144 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7145 (mapcar (lambda (x) (list (concat x ":")))
7146 org-link-types))
7147 nil nil nil
7148 'tmphist
7149 (or (car (car org-stored-links))))))
7150 (set-window-configuration wcf)
7151 (kill-buffer "*Org Links*"))
7152 (setq entry (assoc link org-stored-links))
7153 (or entry (push link org-insert-link-history))
7154 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7155 (not org-keep-stored-link-after-insertion))
7156 (setq org-stored-links (delq (assoc link org-stored-links)
7157 org-stored-links)))
7158 (setq desc (or desc (nth 1 entry)))))
7160 (if (string-match org-plain-link-re link)
7161 ;; URL-like link, normalize the use of angular brackets.
7162 (setq link (org-make-link (org-remove-angle-brackets link))))
7164 ;; Check if we are linking to the current file with a search option
7165 ;; If yes, simplify the link by using only the search option.
7166 (when (and buffer-file-name
7167 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7168 (let* ((path (match-string 1 link))
7169 (case-fold-search nil)
7170 (search (match-string 2 link)))
7171 (save-match-data
7172 (if (equal (file-truename buffer-file-name) (file-truename path))
7173 ;; We are linking to this same file, with a search option
7174 (setq link search)))))
7176 ;; Check if we can/should use a relative path. If yes, simplify the link
7177 (when (string-match "^file:\\(.*\\)" link)
7178 (let* ((path (match-string 1 link))
7179 (origpath path)
7180 (case-fold-search nil))
7181 (cond
7182 ((or (eq org-link-file-path-type 'absolute)
7183 (equal complete-file '(16)))
7184 (setq path (abbreviate-file-name (expand-file-name path))))
7185 ((eq org-link-file-path-type 'noabbrev)
7186 (setq path (expand-file-name path)))
7187 ((eq org-link-file-path-type 'relative)
7188 (setq path (file-relative-name path)))
7190 (save-match-data
7191 (if (string-match (concat "^" (regexp-quote
7192 (file-name-as-directory
7193 (expand-file-name "."))))
7194 (expand-file-name path))
7195 ;; We are linking a file with relative path name.
7196 (setq path (substring (expand-file-name path)
7197 (match-end 0)))
7198 (setq path (abbreviate-file-name (expand-file-name path)))))))
7199 (setq link (concat "file:" path))
7200 (if (equal desc origpath)
7201 (setq desc path))))
7203 (if org-make-link-description-function
7204 (setq desc (funcall org-make-link-description-function link desc)))
7206 (setq desc (read-string "Description: " desc))
7207 (unless (string-match "\\S-" desc) (setq desc nil))
7208 (if remove (apply 'delete-region remove))
7209 (insert (org-make-link-string link desc))))
7211 (defun org-completing-read (&rest args)
7212 "Completing-read with SPACE being a normal character."
7213 (let ((minibuffer-local-completion-map
7214 (copy-keymap minibuffer-local-completion-map)))
7215 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7216 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7217 (apply 'org-ido-completing-read args)))
7219 (defun org-completing-read-no-ido (&rest args)
7220 (let (org-completion-use-ido)
7221 (apply 'org-completing-read args)))
7223 (defun org-ido-completing-read (&rest args)
7224 "Completing-read using `ido-mode' speedups if available"
7225 (if (and org-completion-use-ido
7226 (fboundp 'ido-completing-read)
7227 (boundp 'ido-mode) ido-mode
7228 (listp (second args)))
7229 (let ((ido-enter-matching-directory nil))
7230 (apply 'ido-completing-read (concat (car args))
7231 (mapcar (lambda (x) (car x)) (nth 1 args))
7232 (cddr args)))
7233 (apply 'completing-read args)))
7236 (defun org-extract-attributes (s)
7237 "Extract the attributes cookie from a string and set as text property."
7238 (let (a attr (start 0) key value)
7239 (save-match-data
7240 (when (string-match "{{\\([^}]+\\)}}$" s)
7241 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7242 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7243 (setq key (match-string 1 a) value (match-string 2 a)
7244 start (match-end 0)
7245 attr (plist-put attr (intern key) value))))
7246 (org-add-props s nil 'org-attr attr))
7249 (defun org-attributes-to-string (plist)
7250 "Format a property list into an HTML attribute list."
7251 (let ((s "") key value)
7252 (while plist
7253 (setq key (pop plist) value (pop plist))
7254 (and value
7255 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7258 ;;; Opening/following a link
7260 (defvar org-link-search-failed nil)
7262 (defun org-next-link ()
7263 "Move forward to the next link.
7264 If the link is in hidden text, expose it."
7265 (interactive)
7266 (when (and org-link-search-failed (eq this-command last-command))
7267 (goto-char (point-min))
7268 (message "Link search wrapped back to beginning of buffer"))
7269 (setq org-link-search-failed nil)
7270 (let* ((pos (point))
7271 (ct (org-context))
7272 (a (assoc :link ct)))
7273 (if a (goto-char (nth 2 a)))
7274 (if (re-search-forward org-any-link-re nil t)
7275 (progn
7276 (goto-char (match-beginning 0))
7277 (if (org-invisible-p) (org-show-context)))
7278 (goto-char pos)
7279 (setq org-link-search-failed t)
7280 (error "No further link found"))))
7282 (defun org-previous-link ()
7283 "Move backward to the previous link.
7284 If the link is in hidden text, expose it."
7285 (interactive)
7286 (when (and org-link-search-failed (eq this-command last-command))
7287 (goto-char (point-max))
7288 (message "Link search wrapped back to end of buffer"))
7289 (setq org-link-search-failed nil)
7290 (let* ((pos (point))
7291 (ct (org-context))
7292 (a (assoc :link ct)))
7293 (if a (goto-char (nth 1 a)))
7294 (if (re-search-backward org-any-link-re nil t)
7295 (progn
7296 (goto-char (match-beginning 0))
7297 (if (org-invisible-p) (org-show-context)))
7298 (goto-char pos)
7299 (setq org-link-search-failed t)
7300 (error "No further link found"))))
7302 (defun org-translate-link (s)
7303 "Translate a link string if a translation function has been defined."
7304 (if (and org-link-translation-function
7305 (fboundp org-link-translation-function)
7306 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7307 (progn
7308 (setq s (funcall org-link-translation-function
7309 (match-string 1) (match-string 2)))
7310 (concat (car s) ":" (cdr s)))
7313 (defun org-translate-link-from-planner (type path)
7314 "Translate a link from Emacs Planner syntax so that Org can follow it.
7315 This is still an experimental function, your mileage may vary."
7316 (cond
7317 ((member type '("http" "https" "news" "ftp"))
7318 ;; standard Internet links are the same.
7319 nil)
7320 ((and (equal type "irc") (string-match "^//" path))
7321 ;; Planner has two / at the beginning of an irc link, we have 1.
7322 ;; We should have zero, actually....
7323 (setq path (substring path 1)))
7324 ((and (equal type "lisp") (string-match "^/" path))
7325 ;; Planner has a slash, we do not.
7326 (setq type "elisp" path (substring path 1)))
7327 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7328 ;; A typical message link. Planner has the id after the fina slash,
7329 ;; we separate it with a hash mark
7330 (setq path (concat (match-string 1 path) "#"
7331 (org-remove-angle-brackets (match-string 2 path)))))
7333 (cons type path))
7335 (defun org-find-file-at-mouse (ev)
7336 "Open file link or URL at mouse."
7337 (interactive "e")
7338 (mouse-set-point ev)
7339 (org-open-at-point 'in-emacs))
7341 (defun org-open-at-mouse (ev)
7342 "Open file link or URL at mouse."
7343 (interactive "e")
7344 (mouse-set-point ev)
7345 (if (eq major-mode 'org-agenda-mode)
7346 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7347 (org-open-at-point))
7349 (defvar org-window-config-before-follow-link nil
7350 "The window configuration before following a link.
7351 This is saved in case the need arises to restore it.")
7353 (defvar org-open-link-marker (make-marker)
7354 "Marker pointing to the location where `org-open-at-point; was called.")
7356 ;;;###autoload
7357 (defun org-open-at-point-global ()
7358 "Follow a link like Org-mode does.
7359 This command can be called in any mode to follow a link that has
7360 Org-mode syntax."
7361 (interactive)
7362 (org-run-like-in-org-mode 'org-open-at-point))
7364 ;;;###autoload
7365 (defun org-open-link-from-string (s &optional arg)
7366 "Open a link in the string S, as if it was in Org-mode."
7367 (interactive "sLink: \nP")
7368 (with-temp-buffer
7369 (let ((org-inhibit-startup t))
7370 (org-mode)
7371 (insert s)
7372 (goto-char (point-min))
7373 (org-open-at-point arg))))
7375 (defun org-open-at-point (&optional in-emacs)
7376 "Open link at or after point.
7377 If there is no link at point, this function will search forward up to
7378 the end of the current subtree.
7379 Normally, files will be opened by an appropriate application. If the
7380 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7381 With a double prefix argument, try to open outside of Emacs, in the
7382 application the system uses for this file type."
7383 (interactive "P")
7384 (org-load-modules-maybe)
7385 (move-marker org-open-link-marker (point))
7386 (setq org-window-config-before-follow-link (current-window-configuration))
7387 (org-remove-occur-highlights nil nil t)
7388 (cond
7389 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7390 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7391 (org-footnote-action))
7393 (let (type path link line search (pos (point)))
7394 (catch 'match
7395 (save-excursion
7396 (skip-chars-forward "^]\n\r")
7397 (when (org-in-regexp org-bracket-link-regexp)
7398 (setq link (org-extract-attributes
7399 (org-link-unescape (org-match-string-no-properties 1))))
7400 (while (string-match " *\n *" link)
7401 (setq link (replace-match " " t t link)))
7402 (setq link (org-link-expand-abbrev link))
7403 (cond
7404 ((or (file-name-absolute-p link)
7405 (string-match "^\\.\\.?/" link))
7406 (setq type "file" path link))
7407 ((string-match org-link-re-with-space3 link)
7408 (setq type (match-string 1 link) path (match-string 2 link)))
7409 (t (setq type "thisfile" path link)))
7410 (throw 'match t)))
7412 (when (get-text-property (point) 'org-linked-text)
7413 (setq type "thisfile"
7414 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7415 (1+ (point)) (point))
7416 path (buffer-substring
7417 (previous-single-property-change pos 'org-linked-text)
7418 (next-single-property-change pos 'org-linked-text)))
7419 (throw 'match t))
7421 (save-excursion
7422 (when (or (org-in-regexp org-angle-link-re)
7423 (org-in-regexp org-plain-link-re))
7424 (setq type (match-string 1) path (match-string 2))
7425 (throw 'match t)))
7426 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7427 (setq type "tree-match"
7428 path (match-string 1))
7429 (throw 'match t))
7430 (save-excursion
7431 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7432 (setq type "tags"
7433 path (match-string 1))
7434 (while (string-match ":" path)
7435 (setq path (replace-match "+" t t path)))
7436 (throw 'match t))))
7437 (unless path
7438 (error "No link found"))
7439 ;; Remove any trailing spaces in path
7440 (if (string-match " +\\'" path)
7441 (setq path (replace-match "" t t path)))
7442 (if (and org-link-translation-function
7443 (fboundp org-link-translation-function))
7444 ;; Check if we need to translate the link
7445 (let ((tmp (funcall org-link-translation-function type path)))
7446 (setq type (car tmp) path (cdr tmp))))
7448 (cond
7450 ((assoc type org-link-protocols)
7451 (funcall (nth 1 (assoc type org-link-protocols)) path))
7453 ((equal type "mailto")
7454 (let ((cmd (car org-link-mailto-program))
7455 (args (cdr org-link-mailto-program)) args1
7456 (address path) (subject "") a)
7457 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7458 (setq address (match-string 1 path)
7459 subject (org-link-escape (match-string 2 path))))
7460 (while args
7461 (cond
7462 ((not (stringp (car args))) (push (pop args) args1))
7463 (t (setq a (pop args))
7464 (if (string-match "%a" a)
7465 (setq a (replace-match address t t a)))
7466 (if (string-match "%s" a)
7467 (setq a (replace-match subject t t a)))
7468 (push a args1))))
7469 (apply cmd (nreverse args1))))
7471 ((member type '("http" "https" "ftp" "news"))
7472 (browse-url (concat type ":" (org-link-escape
7473 path org-link-escape-chars-browser))))
7475 ((member type '("message"))
7476 (browse-url (concat type ":" path)))
7478 ((string= type "tags")
7479 (org-tags-view in-emacs path))
7480 ((string= type "thisfile")
7481 (if in-emacs
7482 (switch-to-buffer-other-window
7483 (org-get-buffer-for-internal-link (current-buffer)))
7484 (org-mark-ring-push))
7485 (let ((cmd `(org-link-search
7486 ,path
7487 ,(cond ((equal in-emacs '(4)) 'occur)
7488 ((equal in-emacs '(16)) 'org-occur)
7489 (t nil))
7490 ,pos)))
7491 (condition-case nil (eval cmd)
7492 (error (progn (widen) (eval cmd))))))
7494 ((string= type "tree-match")
7495 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7497 ((string= type "file")
7498 (if (string-match "::\\([0-9]+\\)\\'" path)
7499 (setq line (string-to-number (match-string 1 path))
7500 path (substring path 0 (match-beginning 0)))
7501 (if (string-match "::\\(.+\\)\\'" path)
7502 (setq search (match-string 1 path)
7503 path (substring path 0 (match-beginning 0)))))
7504 (if (string-match "[*?{]" (file-name-nondirectory path))
7505 (dired path)
7506 (org-open-file path in-emacs line search)))
7508 ((string= type "news")
7509 (require 'org-gnus)
7510 (org-gnus-follow-link path))
7512 ((string= type "shell")
7513 (let ((cmd path))
7514 (if (or (not org-confirm-shell-link-function)
7515 (funcall org-confirm-shell-link-function
7516 (format "Execute \"%s\" in shell? "
7517 (org-add-props cmd nil
7518 'face 'org-warning))))
7519 (progn
7520 (message "Executing %s" cmd)
7521 (shell-command cmd))
7522 (error "Abort"))))
7524 ((string= type "elisp")
7525 (let ((cmd path))
7526 (if (or (not org-confirm-elisp-link-function)
7527 (funcall org-confirm-elisp-link-function
7528 (format "Execute \"%s\" as elisp? "
7529 (org-add-props cmd nil
7530 'face 'org-warning))))
7531 (message "%s => %s" cmd
7532 (if (equal (string-to-char cmd) ?\()
7533 (eval (read cmd))
7534 (call-interactively (read cmd))))
7535 (error "Abort"))))
7538 (browse-url-at-point))))))
7539 (move-marker org-open-link-marker nil)
7540 (run-hook-with-args 'org-follow-link-hook))
7542 ;;;; Time estimates
7544 (defun org-get-effort (&optional pom)
7545 "Get the effort estimate for the current entry."
7546 (org-entry-get pom org-effort-property))
7548 ;;; File search
7550 (defvar org-create-file-search-functions nil
7551 "List of functions to construct the right search string for a file link.
7552 These functions are called in turn with point at the location to
7553 which the link should point.
7555 A function in the hook should first test if it would like to
7556 handle this file type, for example by checking the major-mode or
7557 the file extension. If it decides not to handle this file, it
7558 should just return nil to give other functions a chance. If it
7559 does handle the file, it must return the search string to be used
7560 when following the link. The search string will be part of the
7561 file link, given after a double colon, and `org-open-at-point'
7562 will automatically search for it. If special measures must be
7563 taken to make the search successful, another function should be
7564 added to the companion hook `org-execute-file-search-functions',
7565 which see.
7567 A function in this hook may also use `setq' to set the variable
7568 `description' to provide a suggestion for the descriptive text to
7569 be used for this link when it gets inserted into an Org-mode
7570 buffer with \\[org-insert-link].")
7572 (defvar org-execute-file-search-functions nil
7573 "List of functions to execute a file search triggered by a link.
7575 Functions added to this hook must accept a single argument, the
7576 search string that was part of the file link, the part after the
7577 double colon. The function must first check if it would like to
7578 handle this search, for example by checking the major-mode or the
7579 file extension. If it decides not to handle this search, it
7580 should just return nil to give other functions a chance. If it
7581 does handle the search, it must return a non-nil value to keep
7582 other functions from trying.
7584 Each function can access the current prefix argument through the
7585 variable `current-prefix-argument'. Note that a single prefix is
7586 used to force opening a link in Emacs, so it may be good to only
7587 use a numeric or double prefix to guide the search function.
7589 In case this is needed, a function in this hook can also restore
7590 the window configuration before `org-open-at-point' was called using:
7592 (set-window-configuration org-window-config-before-follow-link)")
7594 (defun org-link-search (s &optional type avoid-pos)
7595 "Search for a link search option.
7596 If S is surrounded by forward slashes, it is interpreted as a
7597 regular expression. In org-mode files, this will create an `org-occur'
7598 sparse tree. In ordinary files, `occur' will be used to list matches.
7599 If the current buffer is in `dired-mode', grep will be used to search
7600 in all files. If AVOID-POS is given, ignore matches near that position."
7601 (let ((case-fold-search t)
7602 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7603 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7604 (append '(("") (" ") ("\t") ("\n"))
7605 org-emphasis-alist)
7606 "\\|") "\\)"))
7607 (pos (point))
7608 (pre nil) (post nil)
7609 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7610 (cond
7611 ;; First check if there are any special
7612 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7613 ;; Now try the builtin stuff
7614 ((save-excursion
7615 (goto-char (point-min))
7616 (and
7617 (re-search-forward
7618 (concat "<<" (regexp-quote s0) ">>") nil t)
7619 (setq type 'dedicated
7620 pos (match-beginning 0))))
7621 ;; There is an exact target for this
7622 (goto-char pos))
7623 ((and (string-match "^(\\(.*\\))$" s0)
7624 (save-excursion
7625 (goto-char (point-min))
7626 (and
7627 (re-search-forward
7628 (concat "[^[]" (regexp-quote
7629 (format org-coderef-label-format
7630 (match-string 1 s0))))
7631 nil t)
7632 (setq type 'dedicated
7633 pos (1+ (match-beginning 0))))))
7634 ;; There is a coderef target for this
7635 (goto-char pos))
7636 ((string-match "^/\\(.*\\)/$" s)
7637 ;; A regular expression
7638 (cond
7639 ((org-mode-p)
7640 (org-occur (match-string 1 s)))
7641 ;;((eq major-mode 'dired-mode)
7642 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7643 (t (org-do-occur (match-string 1 s)))))
7645 ;; A normal search strings
7646 (when (equal (string-to-char s) ?*)
7647 ;; Anchor on headlines, post may include tags.
7648 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7649 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7650 s (substring s 1)))
7651 (remove-text-properties
7652 0 (length s)
7653 '(face nil mouse-face nil keymap nil fontified nil) s)
7654 ;; Make a series of regular expressions to find a match
7655 (setq words (org-split-string s "[ \n\r\t]+")
7657 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7658 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7659 "\\)" markers)
7660 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7661 re2a (concat "[ \t\r\n]" re2a_)
7662 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7663 re4 (concat "[^a-zA-Z_]" re4_)
7665 re1 (concat pre re2 post)
7666 re3 (concat pre (if pre re4_ re4) post)
7667 re5 (concat pre ".*" re4)
7668 re2 (concat pre re2)
7669 re2a (concat pre (if pre re2a_ re2a))
7670 re4 (concat pre (if pre re4_ re4))
7671 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7672 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7673 re5 "\\)"
7675 (cond
7676 ((eq type 'org-occur) (org-occur reall))
7677 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7678 (t (goto-char (point-min))
7679 (setq type 'fuzzy)
7680 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7681 (org-search-not-self 1 re1 nil t)
7682 (org-search-not-self 1 re2 nil t)
7683 (org-search-not-self 1 re2a nil t)
7684 (org-search-not-self 1 re3 nil t)
7685 (org-search-not-self 1 re4 nil t)
7686 (org-search-not-self 1 re5 nil t)
7688 (goto-char (match-beginning 1))
7689 (goto-char pos)
7690 (error "No match")))))
7692 ;; Normal string-search
7693 (goto-char (point-min))
7694 (if (search-forward s nil t)
7695 (goto-char (match-beginning 0))
7696 (error "No match"))))
7697 (and (org-mode-p) (org-show-context 'link-search))
7698 type))
7700 (defun org-search-not-self (group &rest args)
7701 "Execute `re-search-forward', but only accept matches that do not
7702 enclose the position of `org-open-link-marker'."
7703 (let ((m org-open-link-marker))
7704 (catch 'exit
7705 (while (apply 're-search-forward args)
7706 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7707 (goto-char (match-end group))
7708 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7709 (> (match-beginning 0) (marker-position m))
7710 (< (match-end 0) (marker-position m)))
7711 (save-match-data
7712 (or (not (org-in-regexp
7713 org-bracket-link-analytic-regexp 1))
7714 (not (match-end 4)) ; no description
7715 (and (<= (match-beginning 4) (point))
7716 (>= (match-end 4) (point))))))
7717 (throw 'exit (point))))))))
7719 (defun org-get-buffer-for-internal-link (buffer)
7720 "Return a buffer to be used for displaying the link target of internal links."
7721 (cond
7722 ((not org-display-internal-link-with-indirect-buffer)
7723 buffer)
7724 ((string-match "(Clone)$" (buffer-name buffer))
7725 (message "Buffer is already a clone, not making another one")
7726 ;; we also do not modify visibility in this case
7727 buffer)
7728 (t ; make a new indirect buffer for displaying the link
7729 (let* ((bn (buffer-name buffer))
7730 (ibn (concat bn "(Clone)"))
7731 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7732 (with-current-buffer ib (org-overview))
7733 ib))))
7735 (defun org-do-occur (regexp &optional cleanup)
7736 "Call the Emacs command `occur'.
7737 If CLEANUP is non-nil, remove the printout of the regular expression
7738 in the *Occur* buffer. This is useful if the regex is long and not useful
7739 to read."
7740 (occur regexp)
7741 (when cleanup
7742 (let ((cwin (selected-window)) win beg end)
7743 (when (setq win (get-buffer-window "*Occur*"))
7744 (select-window win))
7745 (goto-char (point-min))
7746 (when (re-search-forward "match[a-z]+" nil t)
7747 (setq beg (match-end 0))
7748 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7749 (setq end (1- (match-beginning 0)))))
7750 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7751 (goto-char (point-min))
7752 (select-window cwin))))
7754 ;;; The mark ring for links jumps
7756 (defvar org-mark-ring nil
7757 "Mark ring for positions before jumps in Org-mode.")
7758 (defvar org-mark-ring-last-goto nil
7759 "Last position in the mark ring used to go back.")
7760 ;; Fill and close the ring
7761 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7762 (loop for i from 1 to org-mark-ring-length do
7763 (push (make-marker) org-mark-ring))
7764 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7765 org-mark-ring)
7767 (defun org-mark-ring-push (&optional pos buffer)
7768 "Put the current position or POS into the mark ring and rotate it."
7769 (interactive)
7770 (setq pos (or pos (point)))
7771 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7772 (move-marker (car org-mark-ring)
7773 (or pos (point))
7774 (or buffer (current-buffer)))
7775 (message "%s"
7776 (substitute-command-keys
7777 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7779 (defun org-mark-ring-goto (&optional n)
7780 "Jump to the previous position in the mark ring.
7781 With prefix arg N, jump back that many stored positions. When
7782 called several times in succession, walk through the entire ring.
7783 Org-mode commands jumping to a different position in the current file,
7784 or to another Org-mode file, automatically push the old position
7785 onto the ring."
7786 (interactive "p")
7787 (let (p m)
7788 (if (eq last-command this-command)
7789 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7790 (setq p org-mark-ring))
7791 (setq org-mark-ring-last-goto p)
7792 (setq m (car p))
7793 (switch-to-buffer (marker-buffer m))
7794 (goto-char m)
7795 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7797 (defun org-remove-angle-brackets (s)
7798 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7799 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7801 (defun org-add-angle-brackets (s)
7802 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7803 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7805 (defun org-remove-double-quotes (s)
7806 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7807 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7810 ;;; Following specific links
7812 (defun org-follow-timestamp-link ()
7813 (cond
7814 ((org-at-date-range-p t)
7815 (let ((org-agenda-start-on-weekday)
7816 (t1 (match-string 1))
7817 (t2 (match-string 2)))
7818 (setq t1 (time-to-days (org-time-string-to-time t1))
7819 t2 (time-to-days (org-time-string-to-time t2)))
7820 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7821 ((org-at-timestamp-p t)
7822 (org-agenda-list nil (time-to-days (org-time-string-to-time
7823 (substring (match-string 1) 0 10)))
7825 (t (error "This should not happen"))))
7828 ;;; Following file links
7829 (defvar org-wait nil)
7830 (defun org-open-file (path &optional in-emacs line search)
7831 "Open the file at PATH.
7832 First, this expands any special file name abbreviations. Then the
7833 configuration variable `org-file-apps' is checked if it contains an
7834 entry for this file type, and if yes, the corresponding command is launched.
7836 If no application is found, Emacs simply visits the file.
7838 With optional prefix argument IN-EMACS, Emacs will visit the file.
7839 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7840 and o use an external application to visit the file.
7842 Optional LINE specifies a line to go to, optional SEARCH a string to
7843 search for. If LINE or SEARCH is given, the file will always be
7844 opened in Emacs.
7845 If the file does not exist, an error is thrown."
7846 (setq in-emacs (or in-emacs line search))
7847 (let* ((file (if (equal path "")
7848 buffer-file-name
7849 (substitute-in-file-name (expand-file-name path))))
7850 (apps (append org-file-apps (org-default-apps)))
7851 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7852 (dirp (if remp nil (file-directory-p file)))
7853 (file (if (and dirp org-open-directory-means-index-dot-org)
7854 (concat (file-name-as-directory file) "index.org")
7855 file))
7856 (a-m-a-p (assq 'auto-mode apps))
7857 (dfile (downcase file))
7858 (old-buffer (current-buffer))
7859 (old-pos (point))
7860 (old-mode major-mode)
7861 ext cmd)
7862 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7863 (setq ext (match-string 1 dfile))
7864 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7865 (setq ext (match-string 1 dfile))))
7866 (cond
7867 ((equal in-emacs '(16))
7868 (setq cmd (cdr (assoc 'system apps))))
7869 (in-emacs (setq cmd 'emacs))
7871 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7872 (and dirp (cdr (assoc 'directory apps)))
7873 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7874 'string-match)
7875 (cdr (assoc ext apps))
7876 (cdr (assoc t apps))))))
7877 (when (eq cmd 'system)
7878 (setq cmd (cdr (assoc 'system apps))))
7879 (when (eq cmd 'default)
7880 (setq cmd (cdr (assoc t apps))))
7881 (when (eq cmd 'mailcap)
7882 (require 'mailcap)
7883 (mailcap-parse-mailcaps)
7884 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7885 (command (mailcap-mime-info mime-type)))
7886 (if (stringp command)
7887 (setq cmd command)
7888 (setq cmd 'emacs))))
7889 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7890 (not (file-exists-p file))
7891 (not org-open-non-existing-files))
7892 (error "No such file: %s" file))
7893 (cond
7894 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7895 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7896 (while (string-match "['\"]%s['\"]" cmd)
7897 (setq cmd (replace-match "%s" t t cmd)))
7898 (while (string-match "%s" cmd)
7899 (setq cmd (replace-match
7900 (save-match-data
7901 (shell-quote-argument
7902 (convert-standard-filename file)))
7903 t t cmd)))
7904 (save-window-excursion
7905 (start-process-shell-command cmd nil cmd)
7906 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7908 ((or (stringp cmd)
7909 (eq cmd 'emacs))
7910 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7911 (widen)
7912 (if line (goto-line line)
7913 (if search (org-link-search search))))
7914 ((consp cmd)
7915 (let ((file (convert-standard-filename file)))
7916 (eval cmd)))
7917 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7918 (and (org-mode-p) (eq old-mode 'org-mode)
7919 (or (not (equal old-buffer (current-buffer)))
7920 (not (equal old-pos (point))))
7921 (org-mark-ring-push old-pos old-buffer))))
7923 (defun org-default-apps ()
7924 "Return the default applications for this operating system."
7925 (cond
7926 ((eq system-type 'darwin)
7927 org-file-apps-defaults-macosx)
7928 ((eq system-type 'windows-nt)
7929 org-file-apps-defaults-windowsnt)
7930 (t org-file-apps-defaults-gnu)))
7932 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7933 "Convert extensions to regular expressions in the cars of LIST.
7934 Also, weed out any non-string entries, because the return value is used
7935 only for regexp matching.
7936 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7937 point to the symbol `emacs', indicating that the file should
7938 be opened in Emacs."
7939 (append
7940 (delq nil
7941 (mapcar (lambda (x)
7942 (if (not (stringp (car x)))
7944 (if (string-match "\\W" (car x))
7946 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7947 list))
7948 (if add-auto-mode
7949 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7951 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7952 (defun org-file-remote-p (file)
7953 "Test whether FILE specifies a location on a remote system.
7954 Return non-nil if the location is indeed remote.
7956 For example, the filename \"/user@host:/foo\" specifies a location
7957 on the system \"/user@host:\"."
7958 (cond ((fboundp 'file-remote-p)
7959 (file-remote-p file))
7960 ((fboundp 'tramp-handle-file-remote-p)
7961 (tramp-handle-file-remote-p file))
7962 ((and (boundp 'ange-ftp-name-format)
7963 (string-match (car ange-ftp-name-format) file))
7965 (t nil)))
7968 ;;;; Refiling
7970 (defun org-get-org-file ()
7971 "Read a filename, with default directory `org-directory'."
7972 (let ((default (or org-default-notes-file remember-data-file)))
7973 (read-file-name (format "File name [%s]: " default)
7974 (file-name-as-directory org-directory)
7975 default)))
7977 (defun org-notes-order-reversed-p ()
7978 "Check if the current file should receive notes in reversed order."
7979 (cond
7980 ((not org-reverse-note-order) nil)
7981 ((eq t org-reverse-note-order) t)
7982 ((not (listp org-reverse-note-order)) nil)
7983 (t (catch 'exit
7984 (let ((all org-reverse-note-order)
7985 entry)
7986 (while (setq entry (pop all))
7987 (if (string-match (car entry) buffer-file-name)
7988 (throw 'exit (cdr entry))))
7989 nil)))))
7991 (defvar org-refile-target-table nil
7992 "The list of refile targets, created by `org-refile'.")
7994 (defvar org-agenda-new-buffers nil
7995 "Buffers created to visit agenda files.")
7997 (defun org-get-refile-targets (&optional default-buffer)
7998 "Produce a table with refile targets."
7999 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8000 targets txt re files f desc descre fast-path-p level)
8001 (message "Getting targets...")
8002 (with-current-buffer (or default-buffer (current-buffer))
8003 (while (setq entry (pop entries))
8004 (setq files (car entry) desc (cdr entry))
8005 (setq fast-path-p nil)
8006 (cond
8007 ((null files) (setq files (list (current-buffer))))
8008 ((eq files 'org-agenda-files)
8009 (setq files (org-agenda-files 'unrestricted)))
8010 ((and (symbolp files) (fboundp files))
8011 (setq files (funcall files)))
8012 ((and (symbolp files) (boundp files))
8013 (setq files (symbol-value files))))
8014 (if (stringp files) (setq files (list files)))
8015 (cond
8016 ((eq (car desc) :tag)
8017 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8018 ((eq (car desc) :todo)
8019 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8020 ((eq (car desc) :regexp)
8021 (setq descre (cdr desc)))
8022 ((eq (car desc) :level)
8023 (setq descre (concat "^\\*\\{" (number-to-string
8024 (if org-odd-levels-only
8025 (1- (* 2 (cdr desc)))
8026 (cdr desc)))
8027 "\\}[ \t]")))
8028 ((eq (car desc) :maxlevel)
8029 (setq fast-path-p t)
8030 (setq descre (concat "^\\*\\{1," (number-to-string
8031 (if org-odd-levels-only
8032 (1- (* 2 (cdr desc)))
8033 (cdr desc)))
8034 "\\}[ \t]")))
8035 (t (error "Bad refiling target description %s" desc)))
8036 (while (setq f (pop files))
8037 (save-excursion
8038 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8039 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8040 (setq f (expand-file-name f))
8041 (save-excursion
8042 (save-restriction
8043 (widen)
8044 (goto-char (point-min))
8045 (while (re-search-forward descre nil t)
8046 (goto-char (point-at-bol))
8047 (when (looking-at org-complex-heading-regexp)
8048 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8049 txt (org-link-display-format (match-string 4))
8050 re (concat "^" (regexp-quote
8051 (buffer-substring (match-beginning 1)
8052 (match-end 4)))))
8053 (if (match-end 5) (setq re (concat re "[ \t]+"
8054 (regexp-quote
8055 (match-string 5)))))
8056 (setq re (concat re "[ \t]*$"))
8057 (when org-refile-use-outline-path
8058 (setq txt (mapconcat 'org-protect-slash
8059 (append
8060 (if (eq org-refile-use-outline-path 'file)
8061 (list (file-name-nondirectory
8062 (buffer-file-name (buffer-base-buffer))))
8063 (if (eq org-refile-use-outline-path 'full-file-path)
8064 (list (buffer-file-name (buffer-base-buffer)))))
8065 (org-get-outline-path fast-path-p level txt)
8066 (list txt))
8067 "/")))
8068 (push (list txt f re (point)) targets))
8069 (goto-char (point-at-eol))))))))
8070 (message "Getting targets...done")
8071 (nreverse targets))))
8073 (defun org-protect-slash (s)
8074 (while (string-match "/" s)
8075 (setq s (replace-match "\\" t t s)))
8078 (defvar org-olpa (make-vector 20 nil))
8080 (defun org-get-outline-path (&optional fastp level heading)
8081 "Return the outline path to the current entry, as a list."
8082 (if fastp
8083 (progn
8084 (if (> level 19)
8085 (error "Outline path failure, more than 19 levels."))
8086 (loop for i from level upto 19 do
8087 (aset org-olpa i nil))
8088 (prog1
8089 (delq nil (append org-olpa nil))
8090 (aset org-olpa level heading)))
8091 (let (rtn)
8092 (save-excursion
8093 (while (org-up-heading-safe)
8094 (when (looking-at org-complex-heading-regexp)
8095 (push (org-match-string-no-properties 4) rtn)))
8096 rtn))))
8098 (defvar org-refile-history nil
8099 "History for refiling operations.")
8101 (defun org-refile (&optional goto default-buffer)
8102 "Move the entry at point to another heading.
8103 The list of target headings is compiled using the information in
8104 `org-refile-targets', which see. This list is created before each use
8105 and will therefore always be up-to-date.
8107 At the target location, the entry is filed as a subitem of the target heading.
8108 Depending on `org-reverse-note-order', the new subitem will either be the
8109 first or the last subitem.
8111 If there is an active region, all entries in that region will be moved.
8112 However, the region must fulfil the requirement that the first heading
8113 is the first one sets the top-level of the moved text - at most siblings
8114 below it are allowed.
8116 With prefix arg GOTO, the command will only visit the target location,
8117 not actually move anything.
8118 With a double prefix `C-u C-u', go to the location where the last refiling
8119 operation has put the subtree."
8120 (interactive "P")
8121 (let* ((cbuf (current-buffer))
8122 (regionp (org-region-active-p))
8123 (region-start (and regionp (region-beginning)))
8124 (region-end (and regionp (region-end)))
8125 (region-length (and regionp (- region-end region-start)))
8126 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8127 pos it nbuf file re level reversed)
8128 (when regionp (goto-char region-start)
8129 (unless (org-kill-is-subtree-p
8130 (buffer-substring region-start region-end))
8131 (error "The region is not a (sequence of) subtree(s)")))
8132 (if (equal goto '(16))
8133 (org-refile-goto-last-stored)
8134 (when (setq it (org-refile-get-location
8135 (if goto "Goto: " "Refile to: ") default-buffer))
8136 (setq file (nth 1 it)
8137 re (nth 2 it)
8138 pos (nth 3 it))
8139 (if (and (equal (buffer-file-name) file)
8140 (if regionp
8141 (and (>= pos region-start)
8142 (<= pos region-end))
8143 (and (>= pos (point))
8144 (< pos (save-excursion
8145 (org-end-of-subtree t t))))))
8146 (error "Cannot refile to position inside the tree or region"))
8148 (setq nbuf (or (find-buffer-visiting file)
8149 (find-file-noselect file)))
8150 (if goto
8151 (progn
8152 (switch-to-buffer nbuf)
8153 (goto-char pos)
8154 (org-show-context 'org-goto))
8155 (if regionp
8156 (progn
8157 (kill-new (buffer-substring region-start region-end))
8158 (org-save-markers-in-region region-start region-end))
8159 (org-copy-subtree 1 nil t))
8160 (save-excursion
8161 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8162 (find-file-noselect file))))
8163 (setq reversed (org-notes-order-reversed-p))
8164 (save-excursion
8165 (save-restriction
8166 (widen)
8167 (goto-char pos)
8168 (looking-at outline-regexp)
8169 (setq level (org-get-valid-level (funcall outline-level) 1))
8170 (goto-char
8171 (if reversed
8172 (or (outline-next-heading) (point-max))
8173 (or (save-excursion (outline-get-next-sibling))
8174 (org-end-of-subtree t t)
8175 (point-max))))
8176 (if (not (bolp)) (newline))
8177 (bookmark-set "org-refile-last-stored")
8178 (org-paste-subtree level))))
8179 (if regionp
8180 (delete-region (point) (+ (point) region-length))
8181 (org-cut-subtree))
8182 (setq org-markers-to-move nil)
8183 (message "Refiled to \"%s\"" (car it)))))))
8185 (defun org-refile-goto-last-stored ()
8186 "Go to the location where the last refile was stored."
8187 (interactive)
8188 (bookmark-jump "org-refile-last-stored")
8189 (message "This is the location of the last refile"))
8191 (defun org-refile-get-location (&optional prompt default-buffer)
8192 "Prompt the user for a refile location, using PROMPT."
8193 (let ((org-refile-targets org-refile-targets)
8194 (org-refile-use-outline-path org-refile-use-outline-path))
8195 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8196 (unless org-refile-target-table
8197 (error "No refile targets"))
8198 (let* ((cbuf (current-buffer))
8199 (partial-completion-mode nil)
8200 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8201 (cfunc (if (and org-refile-use-outline-path
8202 org-outline-path-complete-in-steps)
8203 'org-olpath-completing-read
8204 'org-ido-completing-read))
8205 (extra (if org-refile-use-outline-path "/" ""))
8206 (filename (and cfn (expand-file-name cfn)))
8207 (tbl (mapcar
8208 (lambda (x)
8209 (if (not (equal filename (nth 1 x)))
8210 (cons (concat (car x) extra " ("
8211 (file-name-nondirectory (nth 1 x)) ")")
8212 (cdr x))
8213 (cons (concat (car x) extra) (cdr x))))
8214 org-refile-target-table))
8215 (completion-ignore-case t))
8216 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8217 tbl)))
8219 (defun org-olpath-completing-read (prompt collection &rest args)
8220 "Read an outline path like a file name."
8221 (let ((thetable collection)
8222 (org-completion-use-ido nil)) ; does not work with ido.
8223 (apply
8224 'org-ido-completing-read prompt
8225 (lambda (string predicate &optional flag)
8226 (let (rtn r f (l (length string)))
8227 (cond
8228 ((eq flag nil)
8229 ;; try completion
8230 (try-completion string thetable))
8231 ((eq flag t)
8232 ;; all-completions
8233 (setq rtn (all-completions string thetable predicate))
8234 (mapcar
8235 (lambda (x)
8236 (setq r (substring x l))
8237 (if (string-match " ([^)]*)$" x)
8238 (setq f (match-string 0 x))
8239 (setq f ""))
8240 (if (string-match "/" r)
8241 (concat string (substring r 0 (match-end 0)) f)
8243 rtn))
8244 ((eq flag 'lambda)
8245 ;; exact match?
8246 (assoc string thetable)))
8248 args)))
8250 ;;;; Dynamic blocks
8252 (defun org-find-dblock (name)
8253 "Find the first dynamic block with name NAME in the buffer.
8254 If not found, stay at current position and return nil."
8255 (let (pos)
8256 (save-excursion
8257 (goto-char (point-min))
8258 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8259 nil t)
8260 (match-beginning 0))))
8261 (if pos (goto-char pos))
8262 pos))
8264 (defconst org-dblock-start-re
8265 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8266 "Matches the startline of a dynamic block, with parameters.")
8268 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8269 "Matches the end of a dynamic block.")
8271 (defun org-create-dblock (plist)
8272 "Create a dynamic block section, with parameters taken from PLIST.
8273 PLIST must contain a :name entry which is used as name of the block."
8274 (unless (bolp) (newline))
8275 (let ((name (plist-get plist :name)))
8276 (insert "#+BEGIN: " name)
8277 (while plist
8278 (if (eq (car plist) :name)
8279 (setq plist (cddr plist))
8280 (insert " " (prin1-to-string (pop plist)))))
8281 (insert "\n\n#+END:\n")
8282 (beginning-of-line -2)))
8284 (defun org-prepare-dblock ()
8285 "Prepare dynamic block for refresh.
8286 This empties the block, puts the cursor at the insert position and returns
8287 the property list including an extra property :name with the block name."
8288 (unless (looking-at org-dblock-start-re)
8289 (error "Not at a dynamic block"))
8290 (let* ((begdel (1+ (match-end 0)))
8291 (name (org-no-properties (match-string 1)))
8292 (params (append (list :name name)
8293 (read (concat "(" (match-string 3) ")")))))
8294 (unless (re-search-forward org-dblock-end-re nil t)
8295 (error "Dynamic block not terminated"))
8296 (setq params
8297 (append params
8298 (list :content (buffer-substring
8299 begdel (match-beginning 0)))))
8300 (delete-region begdel (match-beginning 0))
8301 (goto-char begdel)
8302 (open-line 1)
8303 params))
8305 (defun org-map-dblocks (&optional command)
8306 "Apply COMMAND to all dynamic blocks in the current buffer.
8307 If COMMAND is not given, use `org-update-dblock'."
8308 (let ((cmd (or command 'org-update-dblock))
8309 pos)
8310 (save-excursion
8311 (goto-char (point-min))
8312 (while (re-search-forward org-dblock-start-re nil t)
8313 (goto-char (setq pos (match-beginning 0)))
8314 (condition-case nil
8315 (funcall cmd)
8316 (error (message "Error during update of dynamic block")))
8317 (goto-char pos)
8318 (unless (re-search-forward org-dblock-end-re nil t)
8319 (error "Dynamic block not terminated"))))))
8321 (defun org-dblock-update (&optional arg)
8322 "User command for updating dynamic blocks.
8323 Update the dynamic block at point. With prefix ARG, update all dynamic
8324 blocks in the buffer."
8325 (interactive "P")
8326 (if arg
8327 (org-update-all-dblocks)
8328 (or (looking-at org-dblock-start-re)
8329 (org-beginning-of-dblock))
8330 (org-update-dblock)))
8332 (defun org-update-dblock ()
8333 "Update the dynamic block at point
8334 This means to empty the block, parse for parameters and then call
8335 the correct writing function."
8336 (save-window-excursion
8337 (let* ((pos (point))
8338 (line (org-current-line))
8339 (params (org-prepare-dblock))
8340 (name (plist-get params :name))
8341 (cmd (intern (concat "org-dblock-write:" name))))
8342 (message "Updating dynamic block `%s' at line %d..." name line)
8343 (funcall cmd params)
8344 (message "Updating dynamic block `%s' at line %d...done" name line)
8345 (goto-char pos))))
8347 (defun org-beginning-of-dblock ()
8348 "Find the beginning of the dynamic block at point.
8349 Error if there is no such block at point."
8350 (let ((pos (point))
8351 beg)
8352 (end-of-line 1)
8353 (if (and (re-search-backward org-dblock-start-re nil t)
8354 (setq beg (match-beginning 0))
8355 (re-search-forward org-dblock-end-re nil t)
8356 (> (match-end 0) pos))
8357 (goto-char beg)
8358 (goto-char pos)
8359 (error "Not in a dynamic block"))))
8361 (defun org-update-all-dblocks ()
8362 "Update all dynamic blocks in the buffer.
8363 This function can be used in a hook."
8364 (when (org-mode-p)
8365 (org-map-dblocks 'org-update-dblock)))
8368 ;;;; Completion
8370 (defconst org-additional-option-like-keywords
8371 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8372 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8373 "BEGIN_EXAMPLE" "END_EXAMPLE"
8374 "BEGIN_QUOTE" "END_QUOTE"
8375 "BEGIN_VERSE" "END_VERSE"
8376 "BEGIN_SRC" "END_SRC"
8377 "CATEGORY" "COLUMNS"
8378 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8380 (defcustom org-structure-template-alist
8382 ("s" "#+begin_src ?\n\n#+end_src"
8383 "<src lang=\"?\">\n\n</src>")
8384 ("e" "#+begin_example\n?\n#+end_example"
8385 "<example>\n?\n</example>")
8386 ("q" "#+begin_quote\n?\n#+end_quote"
8387 "<quote>\n?\n</quote>")
8388 ("v" "#+begin_verse\n?\n#+end_verse"
8389 "<verse>\n?\n/verse>")
8390 ("l" "#+begin_latex\n?\n#+end_latex"
8391 "<literal style=\"latex\">\n?\n</literal>")
8392 ("L" "#+latex: "
8393 "<literal style=\"latex\">?</literal>")
8394 ("h" "#+begin_html\n?\n#+end_html"
8395 "<literal style=\"html\">\n?\n</literal>")
8396 ("H" "#+html: "
8397 "<literal style=\"html\">?</literal>")
8398 ("a" "#+begin_ascii\n?\n#+end_ascii")
8399 ("A" "#+ascii: ")
8400 ("i" "#+include %file ?"
8401 "<include file=%file markup=\"?\">")
8403 "Structure completion elements.
8404 This is a list of abbreviation keys and values. The value gets inserted
8405 it you type @samp{.} followed by the key and then the completion key,
8406 usually `M-TAB'. %file will be replaced by a file name after prompting
8407 for the file using completion.
8408 There are two templates for each key, the first uses the original Org syntax,
8409 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8410 the default when the /org-mtags.el/ module has been loaded. See also the
8411 variable `org-mtags-prefer-muse-templates'.
8412 This is an experimental feature, it is undecided if it is going to stay in."
8413 :group 'org-completion
8414 :type '(repeat
8415 (string :tag "Key")
8416 (string :tag "Template")
8417 (string :tag "Muse Template")))
8419 (defun org-try-structure-completion ()
8420 "Try to complete a structure template before point.
8421 This looks for strings like \"<e\" on an otherwise empty line and
8422 expands them."
8423 (let ((l (buffer-substring (point-at-bol) (point)))
8425 (when (and (looking-at "[ \t]*$")
8426 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8427 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8428 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8429 (match-beginning 1)) a)
8430 t)))
8432 (defun org-complete-expand-structure-template (start cell)
8433 "Expand a structure template."
8434 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8435 (rpl (nth (if musep 2 1) cell)))
8436 (delete-region start (point))
8437 (when (string-match "\\`#\\+" rpl)
8438 (cond
8439 ((bolp))
8440 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8441 (delete-region (point-at-bol) (point)))
8442 (t (newline))))
8443 (setq start (point))
8444 (if (string-match "%file" rpl)
8445 (setq rpl (replace-match
8446 (concat
8447 "\""
8448 (save-match-data
8449 (abbreviate-file-name (read-file-name "Include file: ")))
8450 "\"")
8451 t t rpl)))
8452 (insert rpl)
8453 (if (re-search-backward "\\?" start t) (delete-char 1))))
8456 (defun org-complete (&optional arg)
8457 "Perform completion on word at point.
8458 At the beginning of a headline, this completes TODO keywords as given in
8459 `org-todo-keywords'.
8460 If the current word is preceded by a backslash, completes the TeX symbols
8461 that are supported for HTML support.
8462 If the current word is preceded by \"#+\", completes special words for
8463 setting file options.
8464 In the line after \"#+STARTUP:, complete valid keywords.\"
8465 At all other locations, this simply calls the value of
8466 `org-completion-fallback-command'."
8467 (interactive "P")
8468 (org-without-partial-completion
8469 (catch 'exit
8470 (let* ((a nil)
8471 (end (point))
8472 (beg1 (save-excursion
8473 (skip-chars-backward (org-re "[:alnum:]_@"))
8474 (point)))
8475 (beg (save-excursion
8476 (skip-chars-backward "a-zA-Z0-9_:$")
8477 (point)))
8478 (confirm (lambda (x) (stringp (car x))))
8479 (searchhead (equal (char-before beg) ?*))
8480 (struct
8481 (when (and (member (char-before beg1) '(?. ?<))
8482 (setq a (assoc (buffer-substring beg1 (point))
8483 org-structure-template-alist)))
8484 (org-complete-expand-structure-template (1- beg1) a)
8485 (throw 'exit t)))
8486 (tag (and (equal (char-before beg1) ?:)
8487 (equal (char-after (point-at-bol)) ?*)))
8488 (prop (and (equal (char-before beg1) ?:)
8489 (not (equal (char-after (point-at-bol)) ?*))))
8490 (texp (equal (char-before beg) ?\\))
8491 (link (equal (char-before beg) ?\[))
8492 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8493 beg)
8494 "#+"))
8495 (startup (string-match "^#\\+STARTUP:.*"
8496 (buffer-substring (point-at-bol) (point))))
8497 (completion-ignore-case opt)
8498 (type nil)
8499 (tbl nil)
8500 (table (cond
8501 (opt
8502 (setq type :opt)
8503 (require 'org-exp)
8504 (append
8505 (mapcar
8506 (lambda (x)
8507 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8508 (cons (match-string 2 x) (match-string 1 x)))
8509 (org-split-string (org-get-current-options) "\n"))
8510 (mapcar 'list org-additional-option-like-keywords)))
8511 (startup
8512 (setq type :startup)
8513 org-startup-options)
8514 (link (append org-link-abbrev-alist-local
8515 org-link-abbrev-alist))
8516 (texp
8517 (setq type :tex)
8518 org-html-entities)
8519 ((string-match "\\`\\*+[ \t]+\\'"
8520 (buffer-substring (point-at-bol) beg))
8521 (setq type :todo)
8522 (mapcar 'list org-todo-keywords-1))
8523 (searchhead
8524 (setq type :searchhead)
8525 (save-excursion
8526 (goto-char (point-min))
8527 (while (re-search-forward org-todo-line-regexp nil t)
8528 (push (list
8529 (org-make-org-heading-search-string
8530 (match-string 3) t))
8531 tbl)))
8532 tbl)
8533 (tag (setq type :tag beg beg1)
8534 (or org-tag-alist (org-get-buffer-tags)))
8535 (prop (setq type :prop beg beg1)
8536 (mapcar 'list (org-buffer-property-keys nil t t)))
8537 (t (progn
8538 (call-interactively org-completion-fallback-command)
8539 (throw 'exit nil)))))
8540 (pattern (buffer-substring-no-properties beg end))
8541 (completion (try-completion pattern table confirm)))
8542 (cond ((eq completion t)
8543 (if (not (assoc (upcase pattern) table))
8544 (message "Already complete")
8545 (if (and (equal type :opt)
8546 (not (member (car (assoc (upcase pattern) table))
8547 org-additional-option-like-keywords)))
8548 (insert (substring (cdr (assoc (upcase pattern) table))
8549 (length pattern)))
8550 (if (memq type '(:tag :prop)) (insert ":")))))
8551 ((null completion)
8552 (message "Can't find completion for \"%s\"" pattern)
8553 (ding))
8554 ((not (string= pattern completion))
8555 (delete-region beg end)
8556 (if (string-match " +$" completion)
8557 (setq completion (replace-match "" t t completion)))
8558 (insert completion)
8559 (if (get-buffer-window "*Completions*")
8560 (delete-window (get-buffer-window "*Completions*")))
8561 (if (assoc completion table)
8562 (if (eq type :todo) (insert " ")
8563 (if (memq type '(:tag :prop)) (insert ":"))))
8564 (if (and (equal type :opt) (assoc completion table))
8565 (message "%s" (substitute-command-keys
8566 "Press \\[org-complete] again to insert example settings"))))
8568 (message "Making completion list...")
8569 (let ((list (sort (all-completions pattern table confirm)
8570 'string<)))
8571 (with-output-to-temp-buffer "*Completions*"
8572 (condition-case nil
8573 ;; Protection needed for XEmacs and emacs 21
8574 (display-completion-list list pattern)
8575 (error (display-completion-list list)))))
8576 (message "Making completion list...%s" "done")))))))
8578 ;;;; TODO, DEADLINE, Comments
8580 (defun org-toggle-comment ()
8581 "Change the COMMENT state of an entry."
8582 (interactive)
8583 (save-excursion
8584 (org-back-to-heading)
8585 (let (case-fold-search)
8586 (if (looking-at (concat outline-regexp
8587 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8588 (replace-match "" t t nil 1)
8589 (if (looking-at outline-regexp)
8590 (progn
8591 (goto-char (match-end 0))
8592 (insert org-comment-string " ")))))))
8594 (defvar org-last-todo-state-is-todo nil
8595 "This is non-nil when the last TODO state change led to a TODO state.
8596 If the last change removed the TODO tag or switched to DONE, then
8597 this is nil.")
8599 (defvar org-setting-tags nil) ; dynamically skipped
8601 (defun org-parse-local-options (string var)
8602 "Parse STRING for startup setting relevant for variable VAR."
8603 (let ((rtn (symbol-value var))
8604 e opts)
8605 (save-match-data
8606 (if (or (not string) (not (string-match "\\S-" string)))
8608 (setq opts (delq nil (mapcar (lambda (x)
8609 (setq e (assoc x org-startup-options))
8610 (if (eq (nth 1 e) var) e nil))
8611 (org-split-string string "[ \t]+"))))
8612 (if (not opts)
8614 (setq rtn nil)
8615 (while (setq e (pop opts))
8616 (if (not (nth 3 e))
8617 (setq rtn (nth 2 e))
8618 (if (not (listp rtn)) (setq rtn nil))
8619 (push (nth 2 e) rtn)))
8620 rtn)))))
8622 (defvar org-todo-setup-filter-hook nil
8623 "Hook for functions that pre-filter todo specs.
8625 Each function takes a todo spec and returns either `nil' or the spec
8626 transformed into canonical form." )
8628 (defvar org-todo-get-default-hook nil
8629 "Hook for functions that get a default item for todo.
8631 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8632 `nil' or a string to be used for the todo mark." )
8634 (defvar org-agenda-headline-snapshot-before-repeat)
8635 (defun org-todo (&optional arg)
8636 "Change the TODO state of an item.
8637 The state of an item is given by a keyword at the start of the heading,
8638 like
8639 *** TODO Write paper
8640 *** DONE Call mom
8642 The different keywords are specified in the variable `org-todo-keywords'.
8643 By default the available states are \"TODO\" and \"DONE\".
8644 So for this example: when the item starts with TODO, it is changed to DONE.
8645 When it starts with DONE, the DONE is removed. And when neither TODO nor
8646 DONE are present, add TODO at the beginning of the heading.
8648 With C-u prefix arg, use completion to determine the new state.
8649 With numeric prefix arg, switch to that state.
8650 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8651 With a tripple C-u prefix, circumvent any state blocking.
8653 For calling through lisp, arg is also interpreted in the following way:
8654 'none -> empty state
8655 \"\"(empty string) -> switch to empty state
8656 'done -> switch to DONE
8657 'nextset -> switch to the next set of keywords
8658 'previousset -> switch to the previous set of keywords
8659 \"WAITING\" -> switch to the specified keyword, but only if it
8660 really is a member of `org-todo-keywords'."
8661 (interactive "P")
8662 (if (equal arg '(16)) (setq arg 'nextset))
8663 (let ((org-blocker-hook org-blocker-hook))
8664 (when (equal arg '(64))
8665 (setq arg nil org-blocker-hook nil))
8666 (save-excursion
8667 (catch 'exit
8668 (org-back-to-heading)
8669 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8670 (or (looking-at (concat " +" org-todo-regexp " *"))
8671 (looking-at " *"))
8672 (let* ((match-data (match-data))
8673 (startpos (point-at-bol))
8674 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8675 (org-log-done org-log-done)
8676 (org-log-repeat org-log-repeat)
8677 (org-todo-log-states org-todo-log-states)
8678 (this (match-string 1))
8679 (hl-pos (match-beginning 0))
8680 (head (org-get-todo-sequence-head this))
8681 (ass (assoc head org-todo-kwd-alist))
8682 (interpret (nth 1 ass))
8683 (done-word (nth 3 ass))
8684 (final-done-word (nth 4 ass))
8685 (last-state (or this ""))
8686 (completion-ignore-case t)
8687 (member (member this org-todo-keywords-1))
8688 (tail (cdr member))
8689 (state (cond
8690 ((and org-todo-key-trigger
8691 (or (and (equal arg '(4))
8692 (eq org-use-fast-todo-selection 'prefix))
8693 (and (not arg) org-use-fast-todo-selection
8694 (not (eq org-use-fast-todo-selection
8695 'prefix)))))
8696 ;; Use fast selection
8697 (org-fast-todo-selection))
8698 ((and (equal arg '(4))
8699 (or (not org-use-fast-todo-selection)
8700 (not org-todo-key-trigger)))
8701 ;; Read a state with completion
8702 (org-ido-completing-read
8703 "State: " (mapcar (lambda(x) (list x))
8704 org-todo-keywords-1)
8705 nil t))
8706 ((eq arg 'right)
8707 (if this
8708 (if tail (car tail) nil)
8709 (car org-todo-keywords-1)))
8710 ((eq arg 'left)
8711 (if (equal member org-todo-keywords-1)
8713 (if this
8714 (nth (- (length org-todo-keywords-1)
8715 (length tail) 2)
8716 org-todo-keywords-1)
8717 (org-last org-todo-keywords-1))))
8718 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8719 (setq arg nil))) ; hack to fall back to cycling
8720 (arg
8721 ;; user or caller requests a specific state
8722 (cond
8723 ((equal arg "") nil)
8724 ((eq arg 'none) nil)
8725 ((eq arg 'done) (or done-word (car org-done-keywords)))
8726 ((eq arg 'nextset)
8727 (or (car (cdr (member head org-todo-heads)))
8728 (car org-todo-heads)))
8729 ((eq arg 'previousset)
8730 (let ((org-todo-heads (reverse org-todo-heads)))
8731 (or (car (cdr (member head org-todo-heads)))
8732 (car org-todo-heads))))
8733 ((car (member arg org-todo-keywords-1)))
8734 ((nth (1- (prefix-numeric-value arg))
8735 org-todo-keywords-1))))
8736 ((null member) (or head (car org-todo-keywords-1)))
8737 ((equal this final-done-word) nil) ;; -> make empty
8738 ((null tail) nil) ;; -> first entry
8739 ((memq interpret '(type priority))
8740 (if (eq this-command last-command)
8741 (car tail)
8742 (if (> (length tail) 0)
8743 (or done-word (car org-done-keywords))
8744 nil)))
8746 (car tail))))
8747 (state (or
8748 (run-hook-with-args-until-success
8749 'org-todo-get-default-hook state last-state)
8750 state))
8751 (next (if state (concat " " state " ") " "))
8752 (change-plist (list :type 'todo-state-change :from this :to state
8753 :position startpos))
8754 dolog now-done-p)
8755 (when org-blocker-hook
8756 (setq org-last-todo-state-is-todo
8757 (not (member this org-done-keywords)))
8758 (unless (save-excursion
8759 (save-match-data
8760 (run-hook-with-args-until-failure
8761 'org-blocker-hook change-plist)))
8762 (if (interactive-p)
8763 (error "TODO state change from %s to %s blocked" this state)
8764 ;; fail silently
8765 (message "TODO state change from %s to %s blocked" this state)
8766 (throw 'exit nil))))
8767 (store-match-data match-data)
8768 (replace-match next t t)
8769 (unless (pos-visible-in-window-p hl-pos)
8770 (message "TODO state changed to %s" (org-trim next)))
8771 (unless head
8772 (setq head (org-get-todo-sequence-head state)
8773 ass (assoc head org-todo-kwd-alist)
8774 interpret (nth 1 ass)
8775 done-word (nth 3 ass)
8776 final-done-word (nth 4 ass)))
8777 (when (memq arg '(nextset previousset))
8778 (message "Keyword-Set %d/%d: %s"
8779 (- (length org-todo-sets) -1
8780 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8781 (length org-todo-sets)
8782 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8783 (setq org-last-todo-state-is-todo
8784 (not (member state org-done-keywords)))
8785 (setq now-done-p (and (member state org-done-keywords)
8786 (not (member this org-done-keywords))))
8787 (and logging (org-local-logging logging))
8788 (when (and (or org-todo-log-states org-log-done)
8789 (not (memq arg '(nextset previousset))))
8790 ;; we need to look at recording a time and note
8791 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8792 (nth 2 (assoc this org-todo-log-states))))
8793 (when (and state
8794 (member state org-not-done-keywords)
8795 (not (member this org-not-done-keywords)))
8796 ;; This is now a todo state and was not one before
8797 ;; If there was a CLOSED time stamp, get rid of it.
8798 (org-add-planning-info nil nil 'closed))
8799 (when (and now-done-p org-log-done)
8800 ;; It is now done, and it was not done before
8801 (org-add-planning-info 'closed (org-current-time))
8802 (if (and (not dolog) (eq 'note org-log-done))
8803 (org-add-log-setup 'done state this 'findpos 'note)))
8804 (when (and state dolog)
8805 ;; This is a non-nil state, and we need to log it
8806 (org-add-log-setup 'state state this 'findpos dolog)))
8807 ;; Fixup tag positioning
8808 (org-todo-trigger-tag-changes state)
8809 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8810 (when org-provide-todo-statistics
8811 (org-update-parent-todo-statistics))
8812 (run-hooks 'org-after-todo-state-change-hook)
8813 (if (and arg (not (member state org-done-keywords)))
8814 (setq head (org-get-todo-sequence-head state)))
8815 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8816 ;; Do we need to trigger a repeat?
8817 (when now-done-p
8818 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8819 ;; This is for the agenda, take a snapshot of the headline.
8820 (save-match-data
8821 (setq org-agenda-headline-snapshot-before-repeat
8822 (org-get-heading))))
8823 (org-auto-repeat-maybe state))
8824 ;; Fixup cursor location if close to the keyword
8825 (if (and (outline-on-heading-p)
8826 (not (bolp))
8827 (save-excursion (beginning-of-line 1)
8828 (looking-at org-todo-line-regexp))
8829 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8830 (progn
8831 (goto-char (or (match-end 2) (match-end 1)))
8832 (just-one-space)))
8833 (when org-trigger-hook
8834 (save-excursion
8835 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8837 (defun org-block-todo-from-children-or-siblings (change-plist)
8838 "Block turning an entry into a TODO, using the hierarchy.
8839 This checks whether the current task should be blocked from state
8840 changes. Such blocking occurs when:
8842 1. The task has children which are not all in a completed state.
8844 2. A task has a parent with the property :ORDERED:, and there
8845 are siblings prior to the current task with incomplete
8846 status."
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 children, and any are undone, it's blocked
8857 (save-excursion
8858 (org-back-to-heading t)
8859 (let ((this-level (funcall outline-level)))
8860 (outline-next-heading)
8861 (let ((child-level (funcall outline-level)))
8862 (while (and (not (eobp))
8863 (> child-level this-level))
8864 ;; this todo has children, check whether they are all
8865 ;; completed
8866 (if (and (not (org-entry-is-done-p))
8867 (org-entry-is-todo-p))
8868 (throw 'dont-block nil))
8869 (outline-next-heading)
8870 (setq child-level (funcall outline-level))))))
8871 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8872 ;; any previous siblings are undone, it's blocked
8873 (save-excursion
8874 (org-back-to-heading t)
8875 (when (save-excursion
8876 (ignore-errors
8877 (org-up-heading-all 1)
8878 (org-entry-get (point) "ORDERED")))
8879 (let* ((this-level (funcall outline-level))
8880 (current-level this-level))
8881 (while (and (not (bobp))
8882 (= current-level this-level))
8883 (outline-previous-heading)
8884 (setq current-level (funcall outline-level))
8885 (if (= current-level this-level)
8886 ;; this todo has children, check whether they are all
8887 ;; completed
8888 (if (and (not (org-entry-is-done-p))
8889 (org-entry-is-todo-p))
8890 (throw 'dont-block nil)))))))
8891 t)) ; don't block
8893 (defcustom org-track-ordered-property-with-tag nil
8894 "Should the ORDERED property also be shown as a tag?
8895 The ORDERED property decides if an entry should require subtasks to be
8896 completed in sequence. Since a property is not very visible, setting
8897 this option means that toggling the ORDERED property with the command
8898 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
8899 not relevant for the behavior, but it makes things more visible.
8901 Note that toggling the tag with tags commands will not change the property
8902 and therefore not influence behavior!
8904 This can be t, meaning the tag ORDERED should be used, It can also be a
8905 string to select a different tag for this task."
8906 :group 'org-todo
8907 :type '(choice
8908 (const :tag "No tracking" nil)
8909 (const :tag "Track with ORDERED tag" t)
8910 (string :tag "Use other tag")))
8912 (defun org-toggle-ordered-property ()
8913 "Toggle the ORDERED property of the current entry.
8914 For better visibility, you can track the value of this property with a tag.
8915 See variable `org-track-ordered-property-with-tag'."
8916 (interactive)
8917 (let* ((t1 org-track-ordered-property-with-tag)
8918 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
8919 (save-excursion
8920 (org-back-to-heading)
8921 (if (org-entry-get nil "ORDERED")
8922 (progn
8923 (org-delete-property "ORDERED")
8924 (and tag (org-toggle-tag tag 'off))
8925 (message "Subtasks can be completed in arbitrary order"))
8926 (org-entry-put nil "ORDERED" "t")
8927 (and tag (org-toggle-tag tag 'on))
8928 (message "Subtasks must be completed in sequence")))))
8930 (defvar org-blocked-by-checkboxes) ; dynamically scoped
8931 (defun org-block-todo-from-checkboxes (change-plist)
8932 "Block turning an entry into a TODO, using checkboxes.
8933 This checks whether the current task should be blocked from state
8934 changes because there are uncheckd boxes in this entry."
8935 (catch 'dont-block
8936 ;; If this is not a todo state change, or if this entry is already DONE,
8937 ;; do not block
8938 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8939 (member (plist-get change-plist :from)
8940 (cons 'done org-done-keywords))
8941 (member (plist-get change-plist :to)
8942 (cons 'todo org-not-done-keywords)))
8943 (throw 'dont-block t))
8944 ;; If this task has checkboxes that are not checked, it's blocked
8945 (save-excursion
8946 (org-back-to-heading t)
8947 (let ((beg (point)) end)
8948 (outline-next-heading)
8949 (setq end (point))
8950 (goto-char beg)
8951 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8952 end t)
8953 (progn
8954 (if (boundp 'org-blocked-by-checkboxes)
8955 (setq org-blocked-by-checkboxes t))
8956 (throw 'dont-block nil)))))
8957 t)) ; do not block
8959 (defun org-update-parent-todo-statistics ()
8960 "Update any statistics cookie in the parent of the current headline."
8961 (interactive)
8962 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8963 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
8964 (catch 'exit
8965 (save-excursion
8966 (setq level (org-up-heading-safe))
8967 (unless level
8968 (throw 'exit nil))
8969 (while (re-search-forward box-re (point-at-eol) t)
8970 (setq cnt-all 0 cnt-done 0 cookie-present t)
8971 (setq is-percent (match-end 2))
8972 (save-match-data
8973 (unless (outline-next-heading) (throw 'exit nil))
8974 (while (looking-at org-todo-line-regexp)
8975 (setq kwd (match-string 2))
8976 (and kwd (setq cnt-all (1+ cnt-all)))
8977 (and (member kwd org-done-keywords)
8978 (setq cnt-done (1+ cnt-done)))
8979 (condition-case nil
8980 (org-forward-same-level 1)
8981 (error (end-of-line 1)))))
8982 (replace-match
8983 (if is-percent
8984 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8985 (format "[%d/%d]" cnt-done cnt-all))))
8986 (when cookie-present
8987 (run-hook-with-args 'org-after-todo-statistics-hook
8988 cnt-done (- cnt-all cnt-done)))))))
8990 (defvar org-after-todo-statistics-hook nil
8991 "Hook that is called after a TODO statistics cookie has been updated.
8992 Each function is called with two arguments: the number of not-done entries
8993 and the number of done entries.
8995 For example, the following function, when added to this hook, will switch
8996 an entry to DONE when all children are done, and back to TODO when new
8997 entries are set to a TODO status. Note that this hook is only called
8998 when there is a statistics cookie in the headline!
9000 (defun org-summary-todo (n-done n-not-done)
9001 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9002 (let (org-log-done org-log-states) ; turn off logging
9003 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9006 (defun org-todo-trigger-tag-changes (state)
9007 "Apply the changes defined in `org-todo-state-tags-triggers'."
9008 (let ((l org-todo-state-tags-triggers)
9009 changes)
9010 (when (or (not state) (equal state ""))
9011 (setq changes (append changes (cdr (assoc "" l)))))
9012 (when (and (stringp state) (> (length state) 0))
9013 (setq changes (append changes (cdr (assoc state l)))))
9014 (when (member state org-not-done-keywords)
9015 (setq changes (append changes (cdr (assoc 'todo l)))))
9016 (when (member state org-done-keywords)
9017 (setq changes (append changes (cdr (assoc 'done l)))))
9018 (dolist (c changes)
9019 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9021 (defun org-local-logging (value)
9022 "Get logging settings from a property VALUE."
9023 (let* (words w a)
9024 ;; directly set the variables, they are already local.
9025 (setq org-log-done nil
9026 org-log-repeat nil
9027 org-todo-log-states nil)
9028 (setq words (org-split-string value))
9029 (while (setq w (pop words))
9030 (cond
9031 ((setq a (assoc w org-startup-options))
9032 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9033 (set (nth 1 a) (nth 2 a))))
9034 ((setq a (org-extract-log-state-settings w))
9035 (and (member (car a) org-todo-keywords-1)
9036 (push a org-todo-log-states)))))))
9038 (defun org-get-todo-sequence-head (kwd)
9039 "Return the head of the TODO sequence to which KWD belongs.
9040 If KWD is not set, check if there is a text property remembering the
9041 right sequence."
9042 (let (p)
9043 (cond
9044 ((not kwd)
9045 (or (get-text-property (point-at-bol) 'org-todo-head)
9046 (progn
9047 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9048 nil (point-at-eol)))
9049 (get-text-property p 'org-todo-head))))
9050 ((not (member kwd org-todo-keywords-1))
9051 (car org-todo-keywords-1))
9052 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9054 (defun org-fast-todo-selection ()
9055 "Fast TODO keyword selection with single keys.
9056 Returns the new TODO keyword, or nil if no state change should occur."
9057 (let* ((fulltable org-todo-key-alist)
9058 (done-keywords org-done-keywords) ;; needed for the faces.
9059 (maxlen (apply 'max (mapcar
9060 (lambda (x)
9061 (if (stringp (car x)) (string-width (car x)) 0))
9062 fulltable)))
9063 (expert nil)
9064 (fwidth (+ maxlen 3 1 3))
9065 (ncol (/ (- (window-width) 4) fwidth))
9066 tg cnt e c tbl
9067 groups ingroup)
9068 (save-excursion
9069 (save-window-excursion
9070 (if expert
9071 (set-buffer (get-buffer-create " *Org todo*"))
9072 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9073 (erase-buffer)
9074 (org-set-local 'org-done-keywords done-keywords)
9075 (setq tbl fulltable cnt 0)
9076 (while (setq e (pop tbl))
9077 (cond
9078 ((equal e '(:startgroup))
9079 (push '() groups) (setq ingroup t)
9080 (when (not (= cnt 0))
9081 (setq cnt 0)
9082 (insert "\n"))
9083 (insert "{ "))
9084 ((equal e '(:endgroup))
9085 (setq ingroup nil cnt 0)
9086 (insert "}\n"))
9087 ((equal e '(:newline))
9088 (when (not (= cnt 0))
9089 (setq cnt 0)
9090 (insert "\n")
9091 (setq e (car tbl))
9092 (while (equal (car tbl) '(:newline))
9093 (insert "\n")
9094 (setq tbl (cdr tbl)))))
9096 (setq tg (car e) c (cdr e))
9097 (if ingroup (push tg (car groups)))
9098 (setq tg (org-add-props tg nil 'face
9099 (org-get-todo-face tg)))
9100 (if (and (= cnt 0) (not ingroup)) (insert " "))
9101 (insert "[" c "] " tg (make-string
9102 (- fwidth 4 (length tg)) ?\ ))
9103 (when (= (setq cnt (1+ cnt)) ncol)
9104 (insert "\n")
9105 (if ingroup (insert " "))
9106 (setq cnt 0)))))
9107 (insert "\n")
9108 (goto-char (point-min))
9109 (if (not expert) (org-fit-window-to-buffer))
9110 (message "[a-z..]:Set [SPC]:clear")
9111 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9112 (cond
9113 ((or (= c ?\C-g)
9114 (and (= c ?q) (not (rassoc c fulltable))))
9115 (setq quit-flag t))
9116 ((= c ?\ ) nil)
9117 ((setq e (rassoc c fulltable) tg (car e))
9119 (t (setq quit-flag t)))))))
9121 (defun org-entry-is-todo-p ()
9122 (member (org-get-todo-state) org-not-done-keywords))
9124 (defun org-entry-is-done-p ()
9125 (member (org-get-todo-state) org-done-keywords))
9127 (defun org-get-todo-state ()
9128 (save-excursion
9129 (org-back-to-heading t)
9130 (and (looking-at org-todo-line-regexp)
9131 (match-end 2)
9132 (match-string 2))))
9134 (defun org-at-date-range-p (&optional inactive-ok)
9135 "Is the cursor inside a date range?"
9136 (interactive)
9137 (save-excursion
9138 (catch 'exit
9139 (let ((pos (point)))
9140 (skip-chars-backward "^[<\r\n")
9141 (skip-chars-backward "<[")
9142 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9143 (>= (match-end 0) pos)
9144 (throw 'exit t))
9145 (skip-chars-backward "^<[\r\n")
9146 (skip-chars-backward "<[")
9147 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9148 (>= (match-end 0) pos)
9149 (throw 'exit t)))
9150 nil)))
9152 (defun org-get-repeat ()
9153 "Check if there is a deadline/schedule with repeater in this entry."
9154 (save-match-data
9155 (save-excursion
9156 (org-back-to-heading t)
9157 (if (re-search-forward
9158 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9159 (match-string 1)))))
9161 (defvar org-last-changed-timestamp)
9162 (defvar org-last-inserted-timestamp)
9163 (defvar org-log-post-message)
9164 (defvar org-log-note-purpose)
9165 (defvar org-log-note-how)
9166 (defvar org-log-note-extra)
9167 (defun org-auto-repeat-maybe (done-word)
9168 "Check if the current headline contains a repeated deadline/schedule.
9169 If yes, set TODO state back to what it was and change the base date
9170 of repeating deadline/scheduled time stamps to new date.
9171 This function is run automatically after each state change to a DONE state."
9172 ;; last-state is dynamically scoped into this function
9173 (let* ((repeat (org-get-repeat))
9174 (aa (assoc last-state org-todo-kwd-alist))
9175 (interpret (nth 1 aa))
9176 (head (nth 2 aa))
9177 (whata '(("d" . day) ("m" . month) ("y" . year)))
9178 (msg "Entry repeats: ")
9179 (org-log-done nil)
9180 (org-todo-log-states nil)
9181 (nshiftmax 10) (nshift 0)
9182 re type n what ts time)
9183 (when repeat
9184 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9185 (org-todo (if (eq interpret 'type) last-state head))
9186 (when org-log-repeat
9187 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9188 (memq 'org-add-log-note post-command-hook))
9189 ;; OK, we are already setup for some record
9190 (if (eq org-log-repeat 'note)
9191 ;; make sure we take a note, not only a time stamp
9192 (setq org-log-note-how 'note))
9193 ;; Set up for taking a record
9194 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9195 last-state
9196 'findpos org-log-repeat)))
9197 (org-back-to-heading t)
9198 (org-add-planning-info nil nil 'closed)
9199 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9200 org-deadline-time-regexp "\\)\\|\\("
9201 org-ts-regexp "\\)"))
9202 (while (re-search-forward
9203 re (save-excursion (outline-next-heading) (point)) t)
9204 (setq type (if (match-end 1) org-scheduled-string
9205 (if (match-end 3) org-deadline-string "Plain:"))
9206 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9207 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9208 (setq n (string-to-number (match-string 2 ts))
9209 what (match-string 3 ts))
9210 (if (equal what "w") (setq n (* n 7) what "d"))
9211 ;; Preparation, see if we need to modify the start date for the change
9212 (when (match-end 1)
9213 (setq time (save-match-data (org-time-string-to-time ts)))
9214 (cond
9215 ((equal (match-string 1 ts) ".")
9216 ;; Shift starting date to today
9217 (org-timestamp-change
9218 (- (time-to-days (current-time)) (time-to-days time))
9219 'day))
9220 ((equal (match-string 1 ts) "+")
9221 (while (or (= nshift 0)
9222 (<= (time-to-days time) (time-to-days (current-time))))
9223 (when (= (incf nshift) nshiftmax)
9224 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9225 (error "Abort")))
9226 (org-timestamp-change n (cdr (assoc what whata)))
9227 (org-at-timestamp-p t)
9228 (setq ts (match-string 1))
9229 (setq time (save-match-data (org-time-string-to-time ts))))
9230 (org-timestamp-change (- n) (cdr (assoc what whata)))
9231 ;; rematch, so that we have everything in place for the real shift
9232 (org-at-timestamp-p t)
9233 (setq ts (match-string 1))
9234 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9235 (org-timestamp-change n (cdr (assoc what whata)))
9236 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9237 (setq org-log-post-message msg)
9238 (message "%s" msg))))
9240 (defun org-show-todo-tree (arg)
9241 "Make a compact tree which shows all headlines marked with TODO.
9242 The tree will show the lines where the regexp matches, and all higher
9243 headlines above the match.
9244 With a \\[universal-argument] prefix, also show the DONE entries.
9245 With a numeric prefix N, construct a sparse tree for the Nth element
9246 of `org-todo-keywords-1'."
9247 (interactive "P")
9248 (let ((case-fold-search nil)
9249 (kwd-re
9250 (cond ((null arg) org-not-done-regexp)
9251 ((equal arg '(4))
9252 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9253 (mapcar 'list org-todo-keywords-1))))
9254 (concat "\\("
9255 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9256 "\\)\\>")))
9257 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9258 (regexp-quote (nth (1- (prefix-numeric-value arg))
9259 org-todo-keywords-1)))
9260 (t (error "Invalid prefix argument: %s" arg)))))
9261 (message "%d TODO entries found"
9262 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9264 (defun org-deadline (&optional remove time)
9265 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9266 With argument REMOVE, remove any deadline from the item.
9267 When TIME is set, it should be an internal time specification, and the
9268 scheduling will use the corresponding date."
9269 (interactive "P")
9270 (if remove
9271 (progn
9272 (org-remove-timestamp-with-keyword org-deadline-string)
9273 (message "Item no longer has a deadline."))
9274 (if (org-get-repeat)
9275 (error "Cannot change deadline on task with repeater, please do that by hand")
9276 (org-add-planning-info 'deadline time 'closed)
9277 (message "Deadline on %s" org-last-inserted-timestamp))))
9279 (defun org-schedule (&optional remove time)
9280 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9281 With argument REMOVE, remove any scheduling date from the item.
9282 When TIME is set, it should be an internal time specification, and the
9283 scheduling will use the corresponding date."
9284 (interactive "P")
9285 (if remove
9286 (progn
9287 (org-remove-timestamp-with-keyword org-scheduled-string)
9288 (message "Item is no longer scheduled."))
9289 (if (org-get-repeat)
9290 (error "Cannot reschedule task with repeater, please do that by hand")
9291 (org-add-planning-info 'scheduled time 'closed)
9292 (message "Scheduled to %s" org-last-inserted-timestamp))))
9294 (defun org-get-scheduled-time (pom &optional inherit)
9295 "Get the scheduled time as a time tuple, of a format suitable
9296 for calling org-schedule with, or if there is no scheduling,
9297 returns nil."
9298 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9299 (when time
9300 (apply 'encode-time (org-parse-time-string time)))))
9302 (defun org-get-deadline-time (pom &optional inherit)
9303 "Get the deadine as a time tuple, of a format suitable for
9304 calling org-deadlin with, or if there is no scheduling, returns
9305 nil."
9306 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9307 (when time
9308 (apply 'encode-time (org-parse-time-string time)))))
9310 (defun org-remove-timestamp-with-keyword (keyword)
9311 "Remove all time stamps with KEYWORD in the current entry."
9312 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9313 beg)
9314 (save-excursion
9315 (org-back-to-heading t)
9316 (setq beg (point))
9317 (org-end-of-subtree t t)
9318 (while (re-search-backward re beg t)
9319 (replace-match "")
9320 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9321 (equal (char-before) ?\ ))
9322 (backward-delete-char 1)
9323 (if (string-match "^[ \t]*$" (buffer-substring
9324 (point-at-bol) (point-at-eol)))
9325 (delete-region (point-at-bol)
9326 (min (point-max) (1+ (point-at-eol))))))))))
9328 (defun org-add-planning-info (what &optional time &rest remove)
9329 "Insert new timestamp with keyword in the line directly after the headline.
9330 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9331 If non is given, the user is prompted for a date.
9332 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9333 be removed."
9334 (interactive)
9335 (let (org-time-was-given org-end-time-was-given ts
9336 end default-time default-input)
9338 (catch 'exit
9339 (when (and (not time) (memq what '(scheduled deadline)))
9340 ;; Try to get a default date/time from existing timestamp
9341 (save-excursion
9342 (org-back-to-heading t)
9343 (setq end (save-excursion (outline-next-heading) (point)))
9344 (when (re-search-forward (if (eq what 'scheduled)
9345 org-scheduled-time-regexp
9346 org-deadline-time-regexp)
9347 end t)
9348 (setq ts (match-string 1)
9349 default-time
9350 (apply 'encode-time (org-parse-time-string ts))
9351 default-input (and ts (org-get-compact-tod ts))))))
9352 (when what
9353 ;; If necessary, get the time from the user
9354 (setq time (or time (org-read-date nil 'to-time nil nil
9355 default-time default-input))))
9357 (when (and org-insert-labeled-timestamps-at-point
9358 (member what '(scheduled deadline)))
9359 (insert
9360 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9361 (org-insert-time-stamp time org-time-was-given
9362 nil nil nil (list org-end-time-was-given))
9363 (setq what nil))
9364 (save-excursion
9365 (save-restriction
9366 (let (col list elt ts buffer-invisibility-spec)
9367 (org-back-to-heading t)
9368 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9369 (goto-char (match-end 1))
9370 (setq col (current-column))
9371 (goto-char (match-end 0))
9372 (if (eobp) (insert "\n") (forward-char 1))
9373 (when (and (not what)
9374 (not (looking-at
9375 (concat "[ \t]*"
9376 org-keyword-time-not-clock-regexp))))
9377 ;; Nothing to add, nothing to remove...... :-)
9378 (throw 'exit nil))
9379 (if (and (not (looking-at outline-regexp))
9380 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9381 "[^\r\n]*"))
9382 (not (equal (match-string 1) org-clock-string)))
9383 (narrow-to-region (match-beginning 0) (match-end 0))
9384 (insert-before-markers "\n")
9385 (backward-char 1)
9386 (narrow-to-region (point) (point))
9387 (and org-adapt-indentation (org-indent-to-column col)))
9388 ;; Check if we have to remove something.
9389 (setq list (cons what remove))
9390 (while list
9391 (setq elt (pop list))
9392 (goto-char (point-min))
9393 (when (or (and (eq elt 'scheduled)
9394 (re-search-forward org-scheduled-time-regexp nil t))
9395 (and (eq elt 'deadline)
9396 (re-search-forward org-deadline-time-regexp nil t))
9397 (and (eq elt 'closed)
9398 (re-search-forward org-closed-time-regexp nil t)))
9399 (replace-match "")
9400 (if (looking-at "--+<[^>]+>") (replace-match ""))
9401 (if (looking-at " +") (replace-match ""))))
9402 (goto-char (point-max))
9403 (when what
9404 (insert
9405 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9406 (cond ((eq what 'scheduled) org-scheduled-string)
9407 ((eq what 'deadline) org-deadline-string)
9408 ((eq what 'closed) org-closed-string))
9409 " ")
9410 (setq ts (org-insert-time-stamp
9411 time
9412 (or org-time-was-given
9413 (and (eq what 'closed) org-log-done-with-time))
9414 (eq what 'closed)
9415 nil nil (list org-end-time-was-given)))
9416 (end-of-line 1))
9417 (goto-char (point-min))
9418 (widen)
9419 (if (and (looking-at "[ \t]+\n")
9420 (equal (char-before) ?\n))
9421 (delete-region (1- (point)) (point-at-eol)))
9422 ts))))))
9424 (defvar org-log-note-marker (make-marker))
9425 (defvar org-log-note-purpose nil)
9426 (defvar org-log-note-state nil)
9427 (defvar org-log-note-previous-state nil)
9428 (defvar org-log-note-how nil)
9429 (defvar org-log-note-extra nil)
9430 (defvar org-log-note-window-configuration nil)
9431 (defvar org-log-note-return-to (make-marker))
9432 (defvar org-log-post-message nil
9433 "Message to be displayed after a log note has been stored.
9434 The auto-repeater uses this.")
9436 (defun org-add-note ()
9437 "Add a note to the current entry.
9438 This is done in the same way as adding a state change note."
9439 (interactive)
9440 (org-add-log-setup 'note nil nil 'findpos nil))
9442 (defvar org-property-end-re)
9443 (defun org-add-log-setup (&optional purpose state prev-state
9444 findpos how &optional extra)
9445 "Set up the post command hook to take a note.
9446 If this is about to TODO state change, the new state is expected in STATE.
9447 When FINDPOS is non-nil, find the correct position for the note in
9448 the current entry. If not, assume that it can be inserted at point.
9449 HOW is an indicator what kind of note should be created.
9450 EXTRA is additional text that will be inserted into the notes buffer."
9451 (let ((drawer (cond ((stringp org-log-into-drawer)
9452 org-log-into-drawer)
9453 (org-log-into-drawer "LOGBOOK")
9454 (t nil))))
9455 (save-restriction
9456 (save-excursion
9457 (when findpos
9458 (org-back-to-heading t)
9459 (narrow-to-region (point) (save-excursion
9460 (outline-next-heading) (point)))
9461 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9462 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9463 "[^\r\n]*\\)?"))
9464 (goto-char (match-end 0))
9465 (cond
9466 (drawer
9467 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9468 nil t)
9469 (progn
9470 (goto-char (match-end 0))
9471 (or org-log-states-order-reversed
9472 (and (re-search-forward org-property-end-re nil t)
9473 (goto-char (1- (match-beginning 0))))))
9474 (insert "\n:" drawer ":\n:END:")
9475 (beginning-of-line 0)
9476 (org-indent-line-function)
9477 (beginning-of-line 2)
9478 (org-indent-line-function)
9479 (end-of-line 0)))
9480 ((and org-log-state-notes-insert-after-drawers
9481 (save-excursion
9482 (forward-line) (looking-at org-drawer-regexp)))
9483 (forward-line)
9484 (while (looking-at org-drawer-regexp)
9485 (goto-char (match-end 0))
9486 (re-search-forward org-property-end-re (point-max) t)
9487 (forward-line))
9488 (forward-line -1)))
9489 (unless org-log-states-order-reversed
9490 (and (= (char-after) ?\n) (forward-char 1))
9491 (org-skip-over-state-notes)
9492 (skip-chars-backward " \t\n\r")))
9493 (move-marker org-log-note-marker (point))
9494 (setq org-log-note-purpose purpose
9495 org-log-note-state state
9496 org-log-note-previous-state prev-state
9497 org-log-note-how how
9498 org-log-note-extra extra)
9499 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9501 (defun org-skip-over-state-notes ()
9502 "Skip past the list of State notes in an entry."
9503 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9504 (while (looking-at "[ \t]*- State")
9505 (condition-case nil
9506 (org-next-item)
9507 (error (org-end-of-item)))))
9509 (defun org-add-log-note (&optional purpose)
9510 "Pop up a window for taking a note, and add this note later at point."
9511 (remove-hook 'post-command-hook 'org-add-log-note)
9512 (setq org-log-note-window-configuration (current-window-configuration))
9513 (delete-other-windows)
9514 (move-marker org-log-note-return-to (point))
9515 (switch-to-buffer (marker-buffer org-log-note-marker))
9516 (goto-char org-log-note-marker)
9517 (org-switch-to-buffer-other-window "*Org Note*")
9518 (erase-buffer)
9519 (if (memq org-log-note-how '(time state))
9520 (let (current-prefix-arg) (org-store-log-note))
9521 (let ((org-inhibit-startup t)) (org-mode))
9522 (insert (format "# Insert note for %s.
9523 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9524 (cond
9525 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9526 ((eq org-log-note-purpose 'done) "closed todo item")
9527 ((eq org-log-note-purpose 'state)
9528 (format "state change from \"%s\" to \"%s\""
9529 (or org-log-note-previous-state "")
9530 (or org-log-note-state "")))
9531 ((eq org-log-note-purpose 'note)
9532 "this entry")
9533 (t (error "This should not happen")))))
9534 (if org-log-note-extra (insert org-log-note-extra))
9535 (org-set-local 'org-finish-function 'org-store-log-note)))
9537 (defvar org-note-abort nil) ; dynamically scoped
9538 (defun org-store-log-note ()
9539 "Finish taking a log note, and insert it to where it belongs."
9540 (let ((txt (buffer-string))
9541 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9542 lines ind)
9543 (kill-buffer (current-buffer))
9544 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9545 (setq txt (replace-match "" t t txt)))
9546 (if (string-match "\\s-+\\'" txt)
9547 (setq txt (replace-match "" t t txt)))
9548 (setq lines (org-split-string txt "\n"))
9549 (when (and note (string-match "\\S-" note))
9550 (setq note
9551 (org-replace-escapes
9552 note
9553 (list (cons "%u" (user-login-name))
9554 (cons "%U" user-full-name)
9555 (cons "%t" (format-time-string
9556 (org-time-stamp-format 'long 'inactive)
9557 (current-time)))
9558 (cons "%s" (if org-log-note-state
9559 (concat "\"" org-log-note-state "\"")
9560 ""))
9561 (cons "%S" (if org-log-note-previous-state
9562 (concat "\"" org-log-note-previous-state "\"")
9563 "\"\"")))))
9564 (if lines (setq note (concat note " \\\\")))
9565 (push note lines))
9566 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9567 (when lines
9568 (save-excursion
9569 (set-buffer (marker-buffer org-log-note-marker))
9570 (save-excursion
9571 (goto-char org-log-note-marker)
9572 (move-marker org-log-note-marker nil)
9573 (end-of-line 1)
9574 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9575 (insert "- " (pop lines))
9576 (org-indent-line-function)
9577 (beginning-of-line 1)
9578 (looking-at "[ \t]*")
9579 (setq ind (concat (match-string 0) " "))
9580 (end-of-line 1)
9581 (while lines (insert "\n" ind (pop lines)))
9582 (message "Note stored")
9583 (org-back-to-heading t)
9584 (org-cycle-hide-drawers 'children)))))
9585 (set-window-configuration org-log-note-window-configuration)
9586 (with-current-buffer (marker-buffer org-log-note-return-to)
9587 (goto-char org-log-note-return-to))
9588 (move-marker org-log-note-return-to nil)
9589 (and org-log-post-message (message "%s" org-log-post-message)))
9591 (defun org-sparse-tree (&optional arg)
9592 "Create a sparse tree, prompt for the details.
9593 This command can create sparse trees. You first need to select the type
9594 of match used to create the tree:
9596 t Show entries with a specific TODO keyword.
9597 m Show entries selected by a tags/property match.
9598 p Enter a property name and its value (both with completion on existing
9599 names/values) and show entries with that property.
9600 r Show entries matching a regular expression
9601 d Show deadlines due within `org-deadline-warning-days'."
9602 (interactive "P")
9603 (let (ans kwd value)
9604 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date")
9605 (setq ans (read-char-exclusive))
9606 (cond
9607 ((equal ans ?d)
9608 (call-interactively 'org-check-deadlines))
9609 ((equal ans ?b)
9610 (call-interactively 'org-check-before-date))
9611 ((equal ans ?t)
9612 (org-show-todo-tree '(4)))
9613 ((member ans '(?T ?m))
9614 (call-interactively 'org-match-sparse-tree))
9615 ((member ans '(?p ?P))
9616 (setq kwd (org-ido-completing-read "Property: "
9617 (mapcar 'list (org-buffer-property-keys))))
9618 (setq value (org-ido-completing-read "Value: "
9619 (mapcar 'list (org-property-values kwd))))
9620 (unless (string-match "\\`{.*}\\'" value)
9621 (setq value (concat "\"" value "\"")))
9622 (org-match-sparse-tree arg (concat kwd "=" value)))
9623 ((member ans '(?r ?R ?/))
9624 (call-interactively 'org-occur))
9625 (t (error "No such sparse tree command \"%c\"" ans)))))
9627 (defvar org-occur-highlights nil
9628 "List of overlays used for occur matches.")
9629 (make-variable-buffer-local 'org-occur-highlights)
9630 (defvar org-occur-parameters nil
9631 "Parameters of the active org-occur calls.
9632 This is a list, each call to org-occur pushes as cons cell,
9633 containing the regular expression and the callback, onto the list.
9634 The list can contain several entries if `org-occur' has been called
9635 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9636 will only contain one set of parameters. When the highlights are
9637 removed (for example with `C-c C-c', or with the next edit (depending
9638 on `org-remove-highlights-with-change'), this variable is emptied
9639 as well.")
9640 (make-variable-buffer-local 'org-occur-parameters)
9642 (defun org-occur (regexp &optional keep-previous callback)
9643 "Make a compact tree which shows all matches of REGEXP.
9644 The tree will show the lines where the regexp matches, and all higher
9645 headlines above the match. It will also show the heading after the match,
9646 to make sure editing the matching entry is easy.
9647 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9648 call to `org-occur' will be kept, to allow stacking of calls to this
9649 command.
9650 If CALLBACK is non-nil, it is a function which is called to confirm
9651 that the match should indeed be shown."
9652 (interactive "sRegexp: \nP")
9653 (unless keep-previous
9654 (org-remove-occur-highlights nil nil t))
9655 (push (cons regexp callback) org-occur-parameters)
9656 (let ((cnt 0))
9657 (save-excursion
9658 (goto-char (point-min))
9659 (if (or (not keep-previous) ; do not want to keep
9660 (not org-occur-highlights)) ; no previous matches
9661 ;; hide everything
9662 (org-overview))
9663 (while (re-search-forward regexp nil t)
9664 (when (or (not callback)
9665 (save-match-data (funcall callback)))
9666 (setq cnt (1+ cnt))
9667 (when org-highlight-sparse-tree-matches
9668 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9669 (org-show-context 'occur-tree))))
9670 (when org-remove-highlights-with-change
9671 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9672 nil 'local))
9673 (unless org-sparse-tree-open-archived-trees
9674 (org-hide-archived-subtrees (point-min) (point-max)))
9675 (run-hooks 'org-occur-hook)
9676 (if (interactive-p)
9677 (message "%d match(es) for regexp %s" cnt regexp))
9678 cnt))
9680 (defun org-show-context (&optional key)
9681 "Make sure point and context and visible.
9682 How much context is shown depends upon the variables
9683 `org-show-hierarchy-above', `org-show-following-heading'. and
9684 `org-show-siblings'."
9685 (let ((heading-p (org-on-heading-p t))
9686 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9687 (following-p (org-get-alist-option org-show-following-heading key))
9688 (entry-p (org-get-alist-option org-show-entry-below key))
9689 (siblings-p (org-get-alist-option org-show-siblings key)))
9690 (catch 'exit
9691 ;; Show heading or entry text
9692 (if (and heading-p (not entry-p))
9693 (org-flag-heading nil) ; only show the heading
9694 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9695 (org-show-hidden-entry))) ; show entire entry
9696 (when following-p
9697 ;; Show next sibling, or heading below text
9698 (save-excursion
9699 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9700 (org-flag-heading nil))))
9701 (when siblings-p (org-show-siblings))
9702 (when hierarchy-p
9703 ;; show all higher headings, possibly with siblings
9704 (save-excursion
9705 (while (and (condition-case nil
9706 (progn (org-up-heading-all 1) t)
9707 (error nil))
9708 (not (bobp)))
9709 (org-flag-heading nil)
9710 (when siblings-p (org-show-siblings))))))))
9712 (defun org-reveal (&optional siblings)
9713 "Show current entry, hierarchy above it, and the following headline.
9714 This can be used to show a consistent set of context around locations
9715 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9716 not t for the search context.
9718 With optional argument SIBLINGS, on each level of the hierarchy all
9719 siblings are shown. This repairs the tree structure to what it would
9720 look like when opened with hierarchical calls to `org-cycle'."
9721 (interactive "P")
9722 (let ((org-show-hierarchy-above t)
9723 (org-show-following-heading t)
9724 (org-show-siblings (if siblings t org-show-siblings)))
9725 (org-show-context nil)))
9727 (defun org-highlight-new-match (beg end)
9728 "Highlight from BEG to END and mark the highlight is an occur headline."
9729 (let ((ov (org-make-overlay beg end)))
9730 (org-overlay-put ov 'face 'secondary-selection)
9731 (push ov org-occur-highlights)))
9733 (defun org-remove-occur-highlights (&optional beg end noremove)
9734 "Remove the occur highlights from the buffer.
9735 BEG and END are ignored. If NOREMOVE is nil, remove this function
9736 from the `before-change-functions' in the current buffer."
9737 (interactive)
9738 (unless org-inhibit-highlight-removal
9739 (mapc 'org-delete-overlay org-occur-highlights)
9740 (setq org-occur-highlights nil)
9741 (setq org-occur-parameters nil)
9742 (unless noremove
9743 (remove-hook 'before-change-functions
9744 'org-remove-occur-highlights 'local))))
9746 ;;;; Priorities
9748 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9749 "Regular expression matching the priority indicator.")
9751 (defvar org-remove-priority-next-time nil)
9753 (defun org-priority-up ()
9754 "Increase the priority of the current item."
9755 (interactive)
9756 (org-priority 'up))
9758 (defun org-priority-down ()
9759 "Decrease the priority of the current item."
9760 (interactive)
9761 (org-priority 'down))
9763 (defun org-priority (&optional action)
9764 "Change the priority of an item by ARG.
9765 ACTION can be `set', `up', `down', or a character."
9766 (interactive)
9767 (setq action (or action 'set))
9768 (let (current new news have remove)
9769 (save-excursion
9770 (org-back-to-heading t)
9771 (if (looking-at org-priority-regexp)
9772 (setq current (string-to-char (match-string 2))
9773 have t)
9774 (setq current org-default-priority))
9775 (cond
9776 ((or (eq action 'set)
9777 (if (featurep 'xemacs) (characterp action) (integerp action)))
9778 (if (not (eq action 'set))
9779 (setq new action)
9780 (message "Priority %c-%c, SPC to remove: "
9781 org-highest-priority org-lowest-priority)
9782 (setq new (read-char-exclusive)))
9783 (if (and (= (upcase org-highest-priority) org-highest-priority)
9784 (= (upcase org-lowest-priority) org-lowest-priority))
9785 (setq new (upcase new)))
9786 (cond ((equal new ?\ ) (setq remove t))
9787 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9788 (error "Priority must be between `%c' and `%c'"
9789 org-highest-priority org-lowest-priority))))
9790 ((eq action 'up)
9791 (if (and (not have) (eq last-command this-command))
9792 (setq new org-lowest-priority)
9793 (setq new (if (and org-priority-start-cycle-with-default (not have))
9794 org-default-priority (1- current)))))
9795 ((eq action 'down)
9796 (if (and (not have) (eq last-command this-command))
9797 (setq new org-highest-priority)
9798 (setq new (if (and org-priority-start-cycle-with-default (not have))
9799 org-default-priority (1+ current)))))
9800 (t (error "Invalid action")))
9801 (if (or (< (upcase new) org-highest-priority)
9802 (> (upcase new) org-lowest-priority))
9803 (setq remove t))
9804 (setq news (format "%c" new))
9805 (if have
9806 (if remove
9807 (replace-match "" t t nil 1)
9808 (replace-match news t t nil 2))
9809 (if remove
9810 (error "No priority cookie found in line")
9811 (looking-at org-todo-line-regexp)
9812 (if (match-end 2)
9813 (progn
9814 (goto-char (match-end 2))
9815 (insert " [#" news "]"))
9816 (goto-char (match-beginning 3))
9817 (insert "[#" news "] ")))))
9818 (org-preserve-lc (org-set-tags nil 'align))
9819 (if remove
9820 (message "Priority removed")
9821 (message "Priority of current item set to %s" news))))
9824 (defun org-get-priority (s)
9825 "Find priority cookie and return priority."
9826 (save-match-data
9827 (if (not (string-match org-priority-regexp s))
9828 (* 1000 (- org-lowest-priority org-default-priority))
9829 (* 1000 (- org-lowest-priority
9830 (string-to-char (match-string 2 s)))))))
9832 ;;;; Tags
9834 (defvar org-agenda-archives-mode)
9835 (defvar org-scanner-tags nil
9836 "The current tag list while the tags scanner is running.")
9837 (defvar org-trust-scanner-tags nil
9838 "Should `org-get-tags-at' use the tags fro the scanner.
9839 This is for internal dynamical scoping only.
9840 When this is non-nil, the function `org-get-tags-at' will return the value
9841 of `org-scanner-tags' instead of building the list by itself. This
9842 can lead to large speed-ups when the tags scanner is used in a file with
9843 many entries, and when the list of tags is retrieved, for example to
9844 obtain a list of properties. Building the tags list for each entry in such
9845 a file becomes an N^2 operation - but with this variable set, it scales
9846 as N.")
9848 (defun org-scan-tags (action matcher &optional todo-only)
9849 "Scan headline tags with inheritance and produce output ACTION.
9851 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9852 or `agenda' to produce an entry list for an agenda view. It can also be
9853 a Lisp form or a function that should be called at each matched headline, in
9854 this case the return value is a list of all return values from these calls.
9856 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9857 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9858 only lines with a TODO keyword are included in the output."
9859 (require 'org-agenda)
9860 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9861 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9862 (org-re
9863 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9864 (props (list 'face 'default
9865 'done-face 'org-done
9866 'undone-face 'default
9867 'mouse-face 'highlight
9868 'org-not-done-regexp org-not-done-regexp
9869 'org-todo-regexp org-todo-regexp
9870 'keymap org-agenda-keymap
9871 'help-echo
9872 (format "mouse-2 or RET jump to org file %s"
9873 (abbreviate-file-name
9874 (or (buffer-file-name (buffer-base-buffer))
9875 (buffer-name (buffer-base-buffer)))))))
9876 (case-fold-search nil)
9877 lspos tags tags-list
9878 (tags-alist (list (cons 0 org-file-tags)))
9879 (llast 0) rtn rtn1 level category i txt
9880 todo marker entry priority)
9881 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9882 (setq action (list 'lambda nil action)))
9883 (save-excursion
9884 (goto-char (point-min))
9885 (when (eq action 'sparse-tree)
9886 (org-overview)
9887 (org-remove-occur-highlights))
9888 (while (re-search-forward re nil t)
9889 (catch :skip
9890 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
9891 tags (if (match-end 4) (org-match-string-no-properties 4)))
9892 (goto-char (setq lspos (1+ (match-beginning 0))))
9893 (setq level (org-reduced-level (funcall outline-level))
9894 category (org-get-category))
9895 (setq i llast llast level)
9896 ;; remove tag lists from same and sublevels
9897 (while (>= i level)
9898 (when (setq entry (assoc i tags-alist))
9899 (setq tags-alist (delete entry tags-alist)))
9900 (setq i (1- i)))
9901 ;; add the next tags
9902 (when tags
9903 (setq tags (org-split-string tags ":")
9904 tags-alist
9905 (cons (cons level tags) tags-alist)))
9906 ;; compile tags for current headline
9907 (setq tags-list
9908 (if org-use-tag-inheritance
9909 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9910 tags)
9911 org-scanner-tags tags-list)
9912 (when org-use-tag-inheritance
9913 (setcdr (car tags-alist)
9914 (mapcar (lambda (x)
9915 (setq x (copy-sequence x))
9916 (org-add-prop-inherited x))
9917 (cdar tags-alist))))
9918 (when (and tags org-use-tag-inheritance
9919 (or (not (eq t org-use-tag-inheritance))
9920 org-tags-exclude-from-inheritance))
9921 ;; selective inheritance, remove uninherited ones
9922 (setcdr (car tags-alist)
9923 (org-remove-uniherited-tags (cdar tags-alist))))
9924 (when (and (or (not todo-only)
9925 (and (member todo org-not-done-keywords)
9926 (or (not org-agenda-tags-todo-honor-ignore-options)
9927 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9928 (let ((case-fold-search t)) (eval matcher))
9930 (not (member org-archive-tag tags-list))
9931 ;; we have an archive tag, should we use this anyway?
9932 (or (not org-agenda-skip-archived-trees)
9933 (and (eq action 'agenda) org-agenda-archives-mode))))
9934 (unless (eq action 'sparse-tree) (org-agenda-skip))
9936 ;; select this headline
9938 (cond
9939 ((eq action 'sparse-tree)
9940 (and org-highlight-sparse-tree-matches
9941 (org-get-heading) (match-end 0)
9942 (org-highlight-new-match
9943 (match-beginning 0) (match-beginning 1)))
9944 (org-show-context 'tags-tree))
9945 ((eq action 'agenda)
9946 (setq txt (org-format-agenda-item
9948 (concat
9949 (if org-tags-match-list-sublevels
9950 (make-string (1- level) ?.) "")
9951 (org-get-heading))
9952 category
9953 ;(org-get-tags-at)
9954 tags-list
9956 priority (org-get-priority txt))
9957 (goto-char lspos)
9958 (setq marker (org-agenda-new-marker))
9959 (org-add-props txt props
9960 'org-marker marker 'org-hd-marker marker 'org-category category
9961 'todo-state todo
9962 'priority priority 'type "tagsmatch")
9963 (push txt rtn))
9964 ((functionp action)
9965 (save-excursion
9966 (setq rtn1 (funcall action))
9967 (push rtn1 rtn))
9968 (goto-char (point-at-eol)))
9969 (t (error "Invalid action")))
9971 ;; if we are to skip sublevels, jump to end of subtree
9972 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9973 (when (and (eq action 'sparse-tree)
9974 (not org-sparse-tree-open-archived-trees))
9975 (org-hide-archived-subtrees (point-min) (point-max)))
9976 (nreverse rtn)))
9978 (defun org-remove-uniherited-tags (tags)
9979 "Remove all tags that are not inherited from the list TAGS."
9980 (cond
9981 ((eq org-use-tag-inheritance t)
9982 (if org-tags-exclude-from-inheritance
9983 (org-delete-all org-tags-exclude-from-inheritance tags)
9984 tags))
9985 ((not org-use-tag-inheritance) nil)
9986 ((stringp org-use-tag-inheritance)
9987 (delq nil (mapcar
9988 (lambda (x)
9989 (if (and (string-match org-use-tag-inheritance x)
9990 (not (member x org-tags-exclude-from-inheritance)))
9991 x nil))
9992 tags)))
9993 ((listp org-use-tag-inheritance)
9994 (delq nil (mapcar
9995 (lambda (x)
9996 (if (member x org-use-tag-inheritance) x nil))
9997 tags)))))
9999 (defvar todo-only) ;; dynamically scoped
10001 (defun org-match-sparse-tree (&optional todo-only match)
10002 "Create a sparse tree according to tags string MATCH.
10003 MATCH can contain positive and negative selection of tags, like
10004 \"+WORK+URGENT-WITHBOSS\".
10005 If optional argument TODO-ONLY is non-nil, only select lines that are
10006 also TODO lines."
10007 (interactive "P")
10008 (org-prepare-agenda-buffers (list (current-buffer)))
10009 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10011 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10013 (defvar org-cached-props nil)
10014 (defun org-cached-entry-get (pom property)
10015 (if (or (eq t org-use-property-inheritance)
10016 (and (stringp org-use-property-inheritance)
10017 (string-match org-use-property-inheritance property))
10018 (and (listp org-use-property-inheritance)
10019 (member property org-use-property-inheritance)))
10020 ;; Caching is not possible, check it directly
10021 (org-entry-get pom property 'inherit)
10022 ;; Get all properties, so that we can do complicated checks easily
10023 (cdr (assoc property (or org-cached-props
10024 (setq org-cached-props
10025 (org-entry-properties pom)))))))
10027 (defun org-global-tags-completion-table (&optional files)
10028 "Return the list of all tags in all agenda buffer/files."
10029 (save-excursion
10030 (org-uniquify
10031 (delq nil
10032 (apply 'append
10033 (mapcar
10034 (lambda (file)
10035 (set-buffer (find-file-noselect file))
10036 (append (org-get-buffer-tags)
10037 (mapcar (lambda (x) (if (stringp (car-safe x))
10038 (list (car-safe x)) nil))
10039 org-tag-alist)))
10040 (if (and files (car files))
10041 files
10042 (org-agenda-files))))))))
10044 (defun org-make-tags-matcher (match)
10045 "Create the TAGS//TODO matcher form for the selection string MATCH."
10046 ;; todo-only is scoped dynamically into this function, and the function
10047 ;; may change it if the matcher asks for it.
10048 (unless match
10049 ;; Get a new match request, with completion
10050 (let ((org-last-tags-completion-table
10051 (org-global-tags-completion-table)))
10052 (setq match (org-completing-read-no-ido
10053 "Match: " 'org-tags-completion-function nil nil nil
10054 'org-tags-history))))
10056 ;; Parse the string and create a lisp form
10057 (let ((match0 match)
10058 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10059 minus tag mm
10060 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10061 orterms term orlist re-p str-p level-p level-op time-p
10062 prop-p pn pv po cat-p gv rest)
10063 (if (string-match "/+" match)
10064 ;; match contains also a todo-matching request
10065 (progn
10066 (setq tagsmatch (substring match 0 (match-beginning 0))
10067 todomatch (substring match (match-end 0)))
10068 (if (string-match "^!" todomatch)
10069 (setq todo-only t todomatch (substring todomatch 1)))
10070 (if (string-match "^\\s-*$" todomatch)
10071 (setq todomatch nil)))
10072 ;; only matching tags
10073 (setq tagsmatch match todomatch nil))
10075 ;; Make the tags matcher
10076 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10077 (setq tagsmatcher t)
10078 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10079 (while (setq term (pop orterms))
10080 (while (and (equal (substring term -1) "\\") orterms)
10081 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10082 (while (string-match re term)
10083 (setq rest (substring term (match-end 0))
10084 minus (and (match-end 1)
10085 (equal (match-string 1 term) "-"))
10086 tag (match-string 2 term)
10087 re-p (equal (string-to-char tag) ?{)
10088 level-p (match-end 4)
10089 prop-p (match-end 5)
10090 mm (cond
10091 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10092 (level-p
10093 (setq level-op (org-op-to-function (match-string 3 term)))
10094 `(,level-op level ,(string-to-number
10095 (match-string 4 term))))
10096 (prop-p
10097 (setq pn (match-string 5 term)
10098 po (match-string 6 term)
10099 pv (match-string 7 term)
10100 cat-p (equal pn "CATEGORY")
10101 re-p (equal (string-to-char pv) ?{)
10102 str-p (equal (string-to-char pv) ?\")
10103 time-p (save-match-data
10104 (string-match "^\"[[<].*[]>]\"$" pv))
10105 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10106 (if time-p (setq pv (org-matcher-time pv)))
10107 (setq po (org-op-to-function po (if time-p 'time str-p)))
10108 (cond
10109 ((equal pn "CATEGORY")
10110 (setq gv '(get-text-property (point) 'org-category)))
10111 ((equal pn "TODO")
10112 (setq gv 'todo))
10114 (setq gv `(org-cached-entry-get nil ,pn))))
10115 (if re-p
10116 (if (eq po 'org<>)
10117 `(not (string-match ,pv (or ,gv "")))
10118 `(string-match ,pv (or ,gv "")))
10119 (if str-p
10120 `(,po (or ,gv "") ,pv)
10121 `(,po (string-to-number (or ,gv ""))
10122 ,(string-to-number pv) ))))
10123 (t `(member ,tag tags-list)))
10124 mm (if minus (list 'not mm) mm)
10125 term rest)
10126 (push mm tagsmatcher))
10127 (push (if (> (length tagsmatcher) 1)
10128 (cons 'and tagsmatcher)
10129 (car tagsmatcher))
10130 orlist)
10131 (setq tagsmatcher nil))
10132 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10133 (setq tagsmatcher
10134 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10135 ;; Make the todo matcher
10136 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10137 (setq todomatcher t)
10138 (setq orterms (org-split-string todomatch "|") orlist nil)
10139 (while (setq term (pop orterms))
10140 (while (string-match re term)
10141 (setq minus (and (match-end 1)
10142 (equal (match-string 1 term) "-"))
10143 kwd (match-string 2 term)
10144 re-p (equal (string-to-char kwd) ?{)
10145 term (substring term (match-end 0))
10146 mm (if re-p
10147 `(string-match ,(substring kwd 1 -1) todo)
10148 (list 'equal 'todo kwd))
10149 mm (if minus (list 'not mm) mm))
10150 (push mm todomatcher))
10151 (push (if (> (length todomatcher) 1)
10152 (cons 'and todomatcher)
10153 (car todomatcher))
10154 orlist)
10155 (setq todomatcher nil))
10156 (setq todomatcher (if (> (length orlist) 1)
10157 (cons 'or orlist) (car orlist))))
10159 ;; Return the string and lisp forms of the matcher
10160 (setq matcher (if todomatcher
10161 (list 'and tagsmatcher todomatcher)
10162 tagsmatcher))
10163 (cons match0 matcher)))
10165 (defun org-op-to-function (op &optional stringp)
10166 "Turn an operator into the appropriate function."
10167 (setq op
10168 (cond
10169 ((equal op "<" ) '(< string< org-time<))
10170 ((equal op ">" ) '(> org-string> org-time>))
10171 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10172 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10173 ((member op '("=" "==")) '(= string= org-time=))
10174 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10175 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10177 (defun org<> (a b) (not (= a b)))
10178 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10179 (defun org-string>= (a b) (not (string< a b)))
10180 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10181 (defun org-string<> (a b) (not (string= a b)))
10182 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10183 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10184 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10185 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10186 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10187 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10188 (defun org-2ft (s)
10189 "Convert S to a floating point time.
10190 If S is already a number, just return it. If it is a string, parse
10191 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10192 (cond
10193 ((numberp s) s)
10194 ((stringp s)
10195 (condition-case nil
10196 (float-time (apply 'encode-time (org-parse-time-string s)))
10197 (error 0.)))
10198 (t 0.)))
10200 (defun org-time-today ()
10201 "Time in seconds today at 0:00.
10202 Returns the float number of seconds since the beginning of the
10203 epoch to the beginning of today (00:00)."
10204 (float-time (apply 'encode-time
10205 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10207 (defun org-matcher-time (s)
10208 "Interpret a time comparison value."
10209 (save-match-data
10210 (cond
10211 ((string= s "<now>") (float-time))
10212 ((string= s "<today>") (org-time-today))
10213 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10214 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10215 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10216 (+ (org-time-today)
10217 (* (string-to-number (match-string 1 s))
10218 (cdr (assoc (match-string 2 s)
10219 '(("d" . 86400.0) ("w" . 604800.0)
10220 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10221 (t (org-2ft s)))))
10223 (defun org-match-any-p (re list)
10224 "Does re match any element of list?"
10225 (setq list (mapcar (lambda (x) (string-match re x)) list))
10226 (delq nil list))
10228 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10229 (defvar org-tags-overlay (org-make-overlay 1 1))
10230 (org-detach-overlay org-tags-overlay)
10232 (defun org-get-local-tags-at (&optional pos)
10233 "Get a list of tags defined in the current headline."
10234 (org-get-tags-at pos 'local))
10236 (defun org-get-local-tags ()
10237 "Get a list of tags defined in the current headline."
10238 (org-get-tags-at nil 'local))
10240 (defun org-get-tags-at (&optional pos local)
10241 "Get a list of all headline tags applicable at POS.
10242 POS defaults to point. If tags are inherited, the list contains
10243 the targets in the same sequence as the headlines appear, i.e.
10244 the tags of the current headline come last.
10245 When LOCAL is non-nil, only return tags from the current headline,
10246 ignore inherited ones."
10247 (interactive)
10248 (if (and org-trust-scanner-tags
10249 (or (not pos) (equal pos (point)))
10250 (not local))
10251 org-scanner-tags
10252 (let (tags ltags lastpos parent)
10253 (save-excursion
10254 (save-restriction
10255 (widen)
10256 (goto-char (or pos (point)))
10257 (save-match-data
10258 (catch 'done
10259 (condition-case nil
10260 (progn
10261 (org-back-to-heading t)
10262 (while (not (equal lastpos (point)))
10263 (setq lastpos (point))
10264 (when (looking-at
10265 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10266 (setq ltags (org-split-string
10267 (org-match-string-no-properties 1) ":"))
10268 (when parent
10269 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10270 (setq tags (append
10271 (if parent
10272 (org-remove-uniherited-tags ltags)
10273 ltags)
10274 tags)))
10275 (or org-use-tag-inheritance (throw 'done t))
10276 (if local (throw 'done t))
10277 (org-up-heading-all 1)
10278 (setq parent t)))
10279 (error nil)))))
10280 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10282 (defun org-add-prop-inherited (s)
10283 (add-text-properties 0 (length s) '(inherited t) s)
10286 (defun org-toggle-tag (tag &optional onoff)
10287 "Toggle the tag TAG for the current line.
10288 If ONOFF is `on' or `off', don't toggle but set to this state."
10289 (let (res current)
10290 (save-excursion
10291 (org-back-to-heading t)
10292 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10293 (point-at-eol) t)
10294 (progn
10295 (setq current (match-string 1))
10296 (replace-match ""))
10297 (setq current ""))
10298 (setq current (nreverse (org-split-string current ":")))
10299 (cond
10300 ((eq onoff 'on)
10301 (setq res t)
10302 (or (member tag current) (push tag current)))
10303 ((eq onoff 'off)
10304 (or (not (member tag current)) (setq current (delete tag current))))
10305 (t (if (member tag current)
10306 (setq current (delete tag current))
10307 (setq res t)
10308 (push tag current))))
10309 (end-of-line 1)
10310 (if current
10311 (progn
10312 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10313 (org-set-tags nil t))
10314 (delete-horizontal-space))
10315 (run-hooks 'org-after-tags-change-hook))
10316 res))
10318 (defun org-align-tags-here (to-col)
10319 ;; Assumes that this is a headline
10320 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10321 (beginning-of-line 1)
10322 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10323 (< pos (match-beginning 2)))
10324 (progn
10325 (setq tags-l (- (match-end 2) (match-beginning 2)))
10326 (goto-char (match-beginning 1))
10327 (insert " ")
10328 (delete-region (point) (1+ (match-beginning 2)))
10329 (setq ncol (max (1+ (current-column))
10330 (1+ col)
10331 (if (> to-col 0)
10332 to-col
10333 (- (abs to-col) tags-l))))
10334 (setq p (point))
10335 (insert (make-string (- ncol (current-column)) ?\ ))
10336 (setq ncol (current-column))
10337 (when indent-tabs-mode (tabify p (point-at-eol)))
10338 (org-move-to-column (min ncol col) t))
10339 (goto-char pos))))
10341 (defun org-set-tags-command (&optional arg just-align)
10342 "Call the set-tags command for the current entry."
10343 (interactive "P")
10344 (if (org-on-heading-p)
10345 (org-set-tags arg just-align)
10346 (save-excursion
10347 (org-back-to-heading t)
10348 (org-set-tags arg just-align))))
10350 (defun org-set-tags (&optional arg just-align)
10351 "Set the tags for the current headline.
10352 With prefix ARG, realign all tags in headings in the current buffer."
10353 (interactive "P")
10354 (let* ((re (concat "^" outline-regexp))
10355 (current (org-get-tags-string))
10356 (col (current-column))
10357 (org-setting-tags t)
10358 table current-tags inherited-tags ; computed below when needed
10359 tags p0 c0 c1 rpl)
10360 (if arg
10361 (save-excursion
10362 (goto-char (point-min))
10363 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10364 (while (re-search-forward re nil t)
10365 (org-set-tags nil t)
10366 (end-of-line 1)))
10367 (message "All tags realigned to column %d" org-tags-column))
10368 (if just-align
10369 (setq tags current)
10370 ;; Get a new set of tags from the user
10371 (save-excursion
10372 (setq table (append org-tag-persistent-alist
10373 (or org-tag-alist (org-get-buffer-tags)))
10374 org-last-tags-completion-table table
10375 current-tags (org-split-string current ":")
10376 inherited-tags (nreverse
10377 (nthcdr (length current-tags)
10378 (nreverse (org-get-tags-at))))
10379 tags
10380 (if (or (eq t org-use-fast-tag-selection)
10381 (and org-use-fast-tag-selection
10382 (delq nil (mapcar 'cdr table))))
10383 (org-fast-tag-selection
10384 current-tags inherited-tags table
10385 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10386 (let ((org-add-colon-after-tag-completion t))
10387 (org-trim
10388 (org-without-partial-completion
10389 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10390 nil nil current 'org-tags-history)))))))
10391 (while (string-match "[-+&]+" tags)
10392 ;; No boolean logic, just a list
10393 (setq tags (replace-match ":" t t tags))))
10395 (if (string-match "\\`[\t ]*\\'" tags)
10396 (setq tags "")
10397 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10398 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10400 ;; Insert new tags at the correct column
10401 (beginning-of-line 1)
10402 (cond
10403 ((and (equal current "") (equal tags "")))
10404 ((re-search-forward
10405 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10406 (point-at-eol) t)
10407 (if (equal tags "")
10408 (setq rpl "")
10409 (goto-char (match-beginning 0))
10410 (setq c0 (current-column) p0 (point)
10411 c1 (max (1+ c0) (if (> org-tags-column 0)
10412 org-tags-column
10413 (- (- org-tags-column) (length tags))))
10414 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10415 (replace-match rpl t t)
10416 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10417 tags)
10418 (t (error "Tags alignment failed")))
10419 (org-move-to-column col)
10420 (unless just-align
10421 (run-hooks 'org-after-tags-change-hook)))))
10423 (defun org-change-tag-in-region (beg end tag off)
10424 "Add or remove TAG for each entry in the region.
10425 This works in the agenda, and also in an org-mode buffer."
10426 (interactive
10427 (list (region-beginning) (region-end)
10428 (let ((org-last-tags-completion-table
10429 (if (org-mode-p)
10430 (org-get-buffer-tags)
10431 (org-global-tags-completion-table))))
10432 (org-ido-completing-read
10433 "Tag: " 'org-tags-completion-function nil nil nil
10434 'org-tags-history))
10435 (progn
10436 (message "[s]et or [r]emove? ")
10437 (equal (read-char-exclusive) ?r))))
10438 (if (fboundp 'deactivate-mark) (deactivate-mark))
10439 (let ((agendap (equal major-mode 'org-agenda-mode))
10440 l1 l2 m buf pos newhead (cnt 0))
10441 (goto-char end)
10442 (setq l2 (1- (org-current-line)))
10443 (goto-char beg)
10444 (setq l1 (org-current-line))
10445 (loop for l from l1 to l2 do
10446 (goto-line l)
10447 (setq m (get-text-property (point) 'org-hd-marker))
10448 (when (or (and (org-mode-p) (org-on-heading-p))
10449 (and agendap m))
10450 (setq buf (if agendap (marker-buffer m) (current-buffer))
10451 pos (if agendap m (point)))
10452 (with-current-buffer buf
10453 (save-excursion
10454 (save-restriction
10455 (goto-char pos)
10456 (setq cnt (1+ cnt))
10457 (org-toggle-tag tag (if off 'off 'on))
10458 (setq newhead (org-get-heading)))))
10459 (and agendap (org-agenda-change-all-lines newhead m))))
10460 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10462 (defun org-tags-completion-function (string predicate &optional flag)
10463 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10464 (confirm (lambda (x) (stringp (car x)))))
10465 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10466 (setq s1 (match-string 1 string)
10467 s2 (match-string 2 string))
10468 (setq s1 "" s2 string))
10469 (cond
10470 ((eq flag nil)
10471 ;; try completion
10472 (setq rtn (try-completion s2 ctable confirm))
10473 (if (stringp rtn)
10474 (setq rtn
10475 (concat s1 s2 (substring rtn (length s2))
10476 (if (and org-add-colon-after-tag-completion
10477 (assoc rtn ctable))
10478 ":" ""))))
10479 rtn)
10480 ((eq flag t)
10481 ;; all-completions
10482 (all-completions s2 ctable confirm)
10484 ((eq flag 'lambda)
10485 ;; exact match?
10486 (assoc s2 ctable)))
10489 (defun org-fast-tag-insert (kwd tags face &optional end)
10490 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10491 (insert (format "%-12s" (concat kwd ":"))
10492 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10493 (or end "")))
10495 (defun org-fast-tag-show-exit (flag)
10496 (save-excursion
10497 (goto-line 3)
10498 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10499 (replace-match ""))
10500 (when flag
10501 (end-of-line 1)
10502 (org-move-to-column (- (window-width) 19) t)
10503 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10505 (defun org-set-current-tags-overlay (current prefix)
10506 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10507 (if (featurep 'xemacs)
10508 (org-overlay-display org-tags-overlay (concat prefix s)
10509 'secondary-selection)
10510 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10511 (org-overlay-display org-tags-overlay (concat prefix s)))))
10513 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10514 "Fast tag selection with single keys.
10515 CURRENT is the current list of tags in the headline, INHERITED is the
10516 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10517 possibly with grouping information. TODO-TABLE is a similar table with
10518 TODO keywords, should these have keys assigned to them.
10519 If the keys are nil, a-z are automatically assigned.
10520 Returns the new tags string, or nil to not change the current settings."
10521 (let* ((fulltable (append table todo-table))
10522 (maxlen (apply 'max (mapcar
10523 (lambda (x)
10524 (if (stringp (car x)) (string-width (car x)) 0))
10525 fulltable)))
10526 (buf (current-buffer))
10527 (expert (eq org-fast-tag-selection-single-key 'expert))
10528 (buffer-tags nil)
10529 (fwidth (+ maxlen 3 1 3))
10530 (ncol (/ (- (window-width) 4) fwidth))
10531 (i-face 'org-done)
10532 (c-face 'org-todo)
10533 tg cnt e c char c1 c2 ntable tbl rtn
10534 ov-start ov-end ov-prefix
10535 (exit-after-next org-fast-tag-selection-single-key)
10536 (done-keywords org-done-keywords)
10537 groups ingroup)
10538 (save-excursion
10539 (beginning-of-line 1)
10540 (if (looking-at
10541 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10542 (setq ov-start (match-beginning 1)
10543 ov-end (match-end 1)
10544 ov-prefix "")
10545 (setq ov-start (1- (point-at-eol))
10546 ov-end (1+ ov-start))
10547 (skip-chars-forward "^\n\r")
10548 (setq ov-prefix
10549 (concat
10550 (buffer-substring (1- (point)) (point))
10551 (if (> (current-column) org-tags-column)
10553 (make-string (- org-tags-column (current-column)) ?\ ))))))
10554 (org-move-overlay org-tags-overlay ov-start ov-end)
10555 (save-window-excursion
10556 (if expert
10557 (set-buffer (get-buffer-create " *Org tags*"))
10558 (delete-other-windows)
10559 (split-window-vertically)
10560 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10561 (erase-buffer)
10562 (org-set-local 'org-done-keywords done-keywords)
10563 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10564 (org-fast-tag-insert "Current" current c-face "\n\n")
10565 (org-fast-tag-show-exit exit-after-next)
10566 (org-set-current-tags-overlay current ov-prefix)
10567 (setq tbl fulltable char ?a cnt 0)
10568 (while (setq e (pop tbl))
10569 (cond
10570 ((equal e '(:startgroup))
10571 (push '() groups) (setq ingroup t)
10572 (when (not (= cnt 0))
10573 (setq cnt 0)
10574 (insert "\n"))
10575 (insert "{ "))
10576 ((equal e '(:endgroup))
10577 (setq ingroup nil cnt 0)
10578 (insert "}\n"))
10579 ((equal e '(:newline))
10580 (when (not (= cnt 0))
10581 (setq cnt 0)
10582 (insert "\n")
10583 (setq e (car tbl))
10584 (while (equal (car tbl) '(:newline))
10585 (insert "\n")
10586 (setq tbl (cdr tbl)))))
10588 (setq tg (car e) c2 nil)
10589 (if (cdr e)
10590 (setq c (cdr e))
10591 ;; automatically assign a character.
10592 (setq c1 (string-to-char
10593 (downcase (substring
10594 tg (if (= (string-to-char tg) ?@) 1 0)))))
10595 (if (or (rassoc c1 ntable) (rassoc c1 table))
10596 (while (or (rassoc char ntable) (rassoc char table))
10597 (setq char (1+ char)))
10598 (setq c2 c1))
10599 (setq c (or c2 char)))
10600 (if ingroup (push tg (car groups)))
10601 (setq tg (org-add-props tg nil 'face
10602 (cond
10603 ((not (assoc tg table))
10604 (org-get-todo-face tg))
10605 ((member tg current) c-face)
10606 ((member tg inherited) i-face)
10607 (t nil))))
10608 (if (and (= cnt 0) (not ingroup)) (insert " "))
10609 (insert "[" c "] " tg (make-string
10610 (- fwidth 4 (length tg)) ?\ ))
10611 (push (cons tg c) ntable)
10612 (when (= (setq cnt (1+ cnt)) ncol)
10613 (insert "\n")
10614 (if ingroup (insert " "))
10615 (setq cnt 0)))))
10616 (setq ntable (nreverse ntable))
10617 (insert "\n")
10618 (goto-char (point-min))
10619 (if (not expert) (org-fit-window-to-buffer))
10620 (setq rtn
10621 (catch 'exit
10622 (while t
10623 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10624 (if groups " [!] no groups" " [!]groups")
10625 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10626 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10627 (cond
10628 ((= c ?\r) (throw 'exit t))
10629 ((= c ?!)
10630 (setq groups (not groups))
10631 (goto-char (point-min))
10632 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10633 ((= c ?\C-c)
10634 (if (not expert)
10635 (org-fast-tag-show-exit
10636 (setq exit-after-next (not exit-after-next)))
10637 (setq expert nil)
10638 (delete-other-windows)
10639 (split-window-vertically)
10640 (org-switch-to-buffer-other-window " *Org tags*")
10641 (org-fit-window-to-buffer)))
10642 ((or (= c ?\C-g)
10643 (and (= c ?q) (not (rassoc c ntable))))
10644 (org-detach-overlay org-tags-overlay)
10645 (setq quit-flag t))
10646 ((= c ?\ )
10647 (setq current nil)
10648 (if exit-after-next (setq exit-after-next 'now)))
10649 ((= c ?\t)
10650 (condition-case nil
10651 (setq tg (org-ido-completing-read
10652 "Tag: "
10653 (or buffer-tags
10654 (with-current-buffer buf
10655 (org-get-buffer-tags)))))
10656 (quit (setq tg "")))
10657 (when (string-match "\\S-" tg)
10658 (add-to-list 'buffer-tags (list tg))
10659 (if (member tg current)
10660 (setq current (delete tg current))
10661 (push tg current)))
10662 (if exit-after-next (setq exit-after-next 'now)))
10663 ((setq e (rassoc c todo-table) tg (car e))
10664 (with-current-buffer buf
10665 (save-excursion (org-todo tg)))
10666 (if exit-after-next (setq exit-after-next 'now)))
10667 ((setq e (rassoc c ntable) tg (car e))
10668 (if (member tg current)
10669 (setq current (delete tg current))
10670 (loop for g in groups do
10671 (if (member tg g)
10672 (mapc (lambda (x)
10673 (setq current (delete x current)))
10674 g)))
10675 (push tg current))
10676 (if exit-after-next (setq exit-after-next 'now))))
10678 ;; Create a sorted list
10679 (setq current
10680 (sort current
10681 (lambda (a b)
10682 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10683 (if (eq exit-after-next 'now) (throw 'exit t))
10684 (goto-char (point-min))
10685 (beginning-of-line 2)
10686 (delete-region (point) (point-at-eol))
10687 (org-fast-tag-insert "Current" current c-face)
10688 (org-set-current-tags-overlay current ov-prefix)
10689 (while (re-search-forward
10690 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10691 (setq tg (match-string 1))
10692 (add-text-properties
10693 (match-beginning 1) (match-end 1)
10694 (list 'face
10695 (cond
10696 ((member tg current) c-face)
10697 ((member tg inherited) i-face)
10698 (t (get-text-property (match-beginning 1) 'face))))))
10699 (goto-char (point-min)))))
10700 (org-detach-overlay org-tags-overlay)
10701 (if rtn
10702 (mapconcat 'identity current ":")
10703 nil))))
10705 (defun org-get-tags-string ()
10706 "Get the TAGS string in the current headline."
10707 (unless (org-on-heading-p t)
10708 (error "Not on a heading"))
10709 (save-excursion
10710 (beginning-of-line 1)
10711 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10712 (org-match-string-no-properties 1)
10713 "")))
10715 (defun org-get-tags ()
10716 "Get the list of tags specified in the current headline."
10717 (org-split-string (org-get-tags-string) ":"))
10719 (defun org-get-buffer-tags ()
10720 "Get a table of all tags used in the buffer, for completion."
10721 (let (tags)
10722 (save-excursion
10723 (goto-char (point-min))
10724 (while (re-search-forward
10725 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10726 (when (equal (char-after (point-at-bol 0)) ?*)
10727 (mapc (lambda (x) (add-to-list 'tags x))
10728 (org-split-string (org-match-string-no-properties 1) ":")))))
10729 (mapcar 'list tags)))
10731 ;;;; The mapping API
10733 ;;;###autoload
10734 (defun org-map-entries (func &optional match scope &rest skip)
10735 "Call FUNC at each headline selected by MATCH in SCOPE.
10737 FUNC is a function or a lisp form. The function will be called without
10738 arguments, with the cursor positioned at the beginning of the headline.
10739 The return values of all calls to the function will be collected and
10740 returned as a list.
10742 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10743 Only headlines that are matched by this query will be considered during
10744 the iteration. When MATCH is nil or t, all headlines will be
10745 visited by the iteration.
10747 SCOPE determines the scope of this command. It can be any of:
10749 nil The current buffer, respecting the restriction if any
10750 tree The subtree started with the entry at point
10751 file The current buffer, without restriction
10752 file-with-archives
10753 The current buffer, and any archives associated with it
10754 agenda All agenda files
10755 agenda-with-archives
10756 All agenda files with any archive files associated with them
10757 \(file1 file2 ...)
10758 If this is a list, all files in the list will be scanned
10760 The remaining args are treated as settings for the skipping facilities of
10761 the scanner. The following items can be given here:
10763 archive skip trees with the archive tag.
10764 comment skip trees with the COMMENT keyword
10765 function or Emacs Lisp form:
10766 will be used as value for `org-agenda-skip-function', so whenever
10767 the the function returns t, FUNC will not be called for that
10768 entry and search will continue from the point where the
10769 function leaves it.
10771 If your function needs to retrieve the tags including inherited tags
10772 at the *current* entry, you can use the value of the variable
10773 `org-scanner-tags' which will be much faster than getting the value
10774 with `org-get-tags-at'. If your function gets properties with
10775 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
10776 to t around the call to `org-entry-properties' to get the same speedup.
10777 Note that if your function moves around to retrieve tags and properties at
10778 a *different* entry, you cannot use these techniques."
10779 (let* ((org-agenda-archives-mode nil) ; just to make sure
10780 (org-agenda-skip-archived-trees (memq 'archive skip))
10781 (org-agenda-skip-comment-trees (memq 'comment skip))
10782 (org-agenda-skip-function
10783 (car (org-delete-all '(comment archive) skip)))
10784 (org-tags-match-list-sublevels t)
10785 matcher file res
10786 org-todo-keywords-for-agenda
10787 org-done-keywords-for-agenda
10788 org-todo-keyword-alist-for-agenda
10789 org-tag-alist-for-agenda)
10791 (cond
10792 ((eq match t) (setq matcher t))
10793 ((eq match nil) (setq matcher t))
10794 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10796 (save-excursion
10797 (save-restriction
10798 (when (eq scope 'tree)
10799 (org-back-to-heading t)
10800 (org-narrow-to-subtree)
10801 (setq scope nil))
10803 (if (not scope)
10804 (progn
10805 (org-prepare-agenda-buffers
10806 (list (buffer-file-name (current-buffer))))
10807 (setq res (org-scan-tags func matcher)))
10808 ;; Get the right scope
10809 (cond
10810 ((and scope (listp scope) (symbolp (car scope)))
10811 (setq scope (eval scope)))
10812 ((eq scope 'agenda)
10813 (setq scope (org-agenda-files t)))
10814 ((eq scope 'agenda-with-archives)
10815 (setq scope (org-agenda-files t))
10816 (setq scope (org-add-archive-files scope)))
10817 ((eq scope 'file)
10818 (setq scope (list (buffer-file-name))))
10819 ((eq scope 'file-with-archives)
10820 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10821 (org-prepare-agenda-buffers scope)
10822 (while (setq file (pop scope))
10823 (with-current-buffer (org-find-base-buffer-visiting file)
10824 (save-excursion
10825 (save-restriction
10826 (widen)
10827 (goto-char (point-min))
10828 (setq res (append res (org-scan-tags func matcher))))))))))
10829 res))
10831 ;;;; Properties
10833 ;;; Setting and retrieving properties
10835 (defconst org-special-properties
10836 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10837 "TIMESTAMP" "TIMESTAMP_IA")
10838 "The special properties valid in Org-mode.
10840 These are properties that are not defined in the property drawer,
10841 but in some other way.")
10843 (defconst org-default-properties
10844 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10845 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10846 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10847 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10848 "Some properties that are used by Org-mode for various purposes.
10849 Being in this list makes sure that they are offered for completion.")
10851 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10852 "Regular expression matching the first line of a property drawer.")
10854 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10855 "Regular expression matching the first line of a property drawer.")
10857 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10858 "Regular expression matching the first line of a property drawer.")
10860 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10861 "Regular expression matching the first line of a property drawer.")
10863 (defconst org-property-drawer-re
10864 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10865 org-property-end-re "\\)\n?")
10866 "Matches an entire property drawer.")
10868 (defconst org-clock-drawer-re
10869 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10870 org-property-end-re "\\)\n?")
10871 "Matches an entire clock drawer.")
10873 (defun org-property-action ()
10874 "Do an action on properties."
10875 (interactive)
10876 (let (c)
10877 (org-at-property-p)
10878 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10879 (setq c (read-char-exclusive))
10880 (cond
10881 ((equal c ?s)
10882 (call-interactively 'org-set-property))
10883 ((equal c ?d)
10884 (call-interactively 'org-delete-property))
10885 ((equal c ?D)
10886 (call-interactively 'org-delete-property-globally))
10887 ((equal c ?c)
10888 (call-interactively 'org-compute-property-at-point))
10889 (t (error "No such property action %c" c)))))
10891 (defun org-at-property-p ()
10892 "Is the cursor in a property line?"
10893 ;; FIXME: Does not check if we are actually in the drawer.
10894 ;; FIXME: also returns true on any drawers.....
10895 ;; This is used by C-c C-c for property action.
10896 (save-excursion
10897 (beginning-of-line 1)
10898 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10900 (defun org-get-property-block (&optional beg end force)
10901 "Return the (beg . end) range of the body of the property drawer.
10902 BEG and END can be beginning and end of subtree, if not given
10903 they will be found.
10904 If the drawer does not exist and FORCE is non-nil, create the drawer."
10905 (catch 'exit
10906 (save-excursion
10907 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10908 (end (or end (progn (outline-next-heading) (point)))))
10909 (goto-char beg)
10910 (if (re-search-forward org-property-start-re end t)
10911 (setq beg (1+ (match-end 0)))
10912 (if force
10913 (save-excursion
10914 (org-insert-property-drawer)
10915 (setq end (progn (outline-next-heading) (point))))
10916 (throw 'exit nil))
10917 (goto-char beg)
10918 (if (re-search-forward org-property-start-re end t)
10919 (setq beg (1+ (match-end 0)))))
10920 (if (re-search-forward org-property-end-re end t)
10921 (setq end (match-beginning 0))
10922 (or force (throw 'exit nil))
10923 (goto-char beg)
10924 (setq end beg)
10925 (org-indent-line-function)
10926 (insert ":END:\n"))
10927 (cons beg end)))))
10929 (defun org-entry-properties (&optional pom which)
10930 "Get all properties of the entry at point-or-marker POM.
10931 This includes the TODO keyword, the tags, time strings for deadline,
10932 scheduled, and clocking, and any additional properties defined in the
10933 entry. The return value is an alist, keys may occur multiple times
10934 if the property key was used several times.
10935 POM may also be nil, in which case the current entry is used.
10936 If WHICH is nil or `all', get all properties. If WHICH is
10937 `special' or `standard', only get that subclass."
10938 (setq which (or which 'all))
10939 (org-with-point-at pom
10940 (let ((clockstr (substring org-clock-string 0 -1))
10941 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10942 beg end range props sum-props key value string clocksum)
10943 (save-excursion
10944 (when (condition-case nil
10945 (and (org-mode-p) (org-back-to-heading t))
10946 (error nil))
10947 (setq beg (point))
10948 (setq sum-props (get-text-property (point) 'org-summaries))
10949 (setq clocksum (get-text-property (point) :org-clock-minutes))
10950 (outline-next-heading)
10951 (setq end (point))
10952 (when (memq which '(all special))
10953 ;; Get the special properties, like TODO and tags
10954 (goto-char beg)
10955 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10956 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10957 (when (looking-at org-priority-regexp)
10958 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10959 (when (and (setq value (org-get-tags-string))
10960 (string-match "\\S-" value))
10961 (push (cons "TAGS" value) props))
10962 (when (setq value (org-get-tags-at))
10963 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10964 props))
10965 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10966 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10967 string (if (equal key clockstr)
10968 (org-no-properties
10969 (org-trim
10970 (buffer-substring
10971 (match-beginning 3) (goto-char (point-at-eol)))))
10972 (substring (org-match-string-no-properties 3) 1 -1)))
10973 (unless key
10974 (if (= (char-after (match-beginning 3)) ?\[)
10975 (setq key "TIMESTAMP_IA")
10976 (setq key "TIMESTAMP")))
10977 (when (or (equal key clockstr) (not (assoc key props)))
10978 (push (cons key string) props)))
10982 (when (memq which '(all standard))
10983 ;; Get the standard properties, like :PROP: ...
10984 (setq range (org-get-property-block beg end))
10985 (when range
10986 (goto-char (car range))
10987 (while (re-search-forward
10988 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10989 (cdr range) t)
10990 (setq key (org-match-string-no-properties 1)
10991 value (org-trim (or (org-match-string-no-properties 2) "")))
10992 (unless (member key excluded)
10993 (push (cons key (or value "")) props)))))
10994 (if clocksum
10995 (push (cons "CLOCKSUM"
10996 (org-columns-number-to-string (/ (float clocksum) 60.)
10997 'add_times))
10998 props))
10999 (unless (assoc "CATEGORY" props)
11000 (setq value (or (org-get-category)
11001 (progn (org-refresh-category-properties)
11002 (org-get-category))))
11003 (push (cons "CATEGORY" value) props))
11004 (append sum-props (nreverse props)))))))
11006 (defun org-entry-get (pom property &optional inherit)
11007 "Get value of PROPERTY for entry at point-or-marker POM.
11008 If INHERIT is non-nil and the entry does not have the property,
11009 then also check higher levels of the hierarchy.
11010 If INHERIT is the symbol `selective', use inheritance only if the setting
11011 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11012 If the property is present but empty, the return value is the empty string.
11013 If the property is not present at all, nil is returned."
11014 (org-with-point-at pom
11015 (if (and inherit (if (eq inherit 'selective)
11016 (org-property-inherit-p property)
11018 (org-entry-get-with-inheritance property)
11019 (if (member property org-special-properties)
11020 ;; We need a special property. Use brute force, get all properties.
11021 (cdr (assoc property (org-entry-properties nil 'special)))
11022 (let ((range (org-get-property-block)))
11023 (if (and range
11024 (goto-char (car range))
11025 (re-search-forward
11026 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11027 (cdr range) t))
11028 ;; Found the property, return it.
11029 (if (match-end 1)
11030 (org-match-string-no-properties 1)
11031 "")))))))
11033 (defun org-property-or-variable-value (var &optional inherit)
11034 "Check if there is a property fixing the value of VAR.
11035 If yes, return this value. If not, return the current value of the variable."
11036 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11037 (if (and prop (stringp prop) (string-match "\\S-" prop))
11038 (read prop)
11039 (symbol-value var))))
11041 (defun org-entry-delete (pom property)
11042 "Delete the property PROPERTY from entry at point-or-marker POM."
11043 (org-with-point-at pom
11044 (if (member property org-special-properties)
11045 nil ; cannot delete these properties.
11046 (let ((range (org-get-property-block)))
11047 (if (and range
11048 (goto-char (car range))
11049 (re-search-forward
11050 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11051 (cdr range) t))
11052 (progn
11053 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11055 nil)))))
11057 ;; Multi-values properties are properties that contain multiple values
11058 ;; These values are assumed to be single words, separated by whitespace.
11059 (defun org-entry-add-to-multivalued-property (pom property value)
11060 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11061 (let* ((old (org-entry-get pom property))
11062 (values (and old (org-split-string old "[ \t]"))))
11063 (setq value (org-entry-protect-space value))
11064 (unless (member value values)
11065 (setq values (cons value values))
11066 (org-entry-put pom property
11067 (mapconcat 'identity values " ")))))
11069 (defun org-entry-remove-from-multivalued-property (pom property value)
11070 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11071 (let* ((old (org-entry-get pom property))
11072 (values (and old (org-split-string old "[ \t]"))))
11073 (setq value (org-entry-protect-space value))
11074 (when (member value values)
11075 (setq values (delete value values))
11076 (org-entry-put pom property
11077 (mapconcat 'identity values " ")))))
11079 (defun org-entry-member-in-multivalued-property (pom property value)
11080 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11081 (let* ((old (org-entry-get pom property))
11082 (values (and old (org-split-string old "[ \t]"))))
11083 (setq value (org-entry-protect-space value))
11084 (member value values)))
11086 (defun org-entry-get-multivalued-property (pom property)
11087 "Return a list of values in a multivalued property."
11088 (let* ((value (org-entry-get pom property))
11089 (values (and value (org-split-string value "[ \t]"))))
11090 (mapcar 'org-entry-restore-space values)))
11092 (defun org-entry-put-multivalued-property (pom property &rest values)
11093 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11094 VALUES should be a list of strings. Spaces will be protected."
11095 (org-entry-put pom property
11096 (mapconcat 'org-entry-protect-space values " "))
11097 (let* ((value (org-entry-get pom property))
11098 (values (and value (org-split-string value "[ \t]"))))
11099 (mapcar 'org-entry-restore-space values)))
11101 (defun org-entry-protect-space (s)
11102 "Protect spaces and newline in string S."
11103 (while (string-match " " s)
11104 (setq s (replace-match "%20" t t s)))
11105 (while (string-match "\n" s)
11106 (setq s (replace-match "%0A" t t s)))
11109 (defun org-entry-restore-space (s)
11110 "Restore spaces and newline in string S."
11111 (while (string-match "%20" s)
11112 (setq s (replace-match " " t t s)))
11113 (while (string-match "%0A" s)
11114 (setq s (replace-match "\n" t t s)))
11117 (defvar org-entry-property-inherited-from (make-marker)
11118 "Marker pointing to the entry from where a property was inherited.
11119 Each call to `org-entry-get-with-inheritance' will set this marker to the
11120 location of the entry where the inheritance search matched. If there was
11121 no match, the marker will point nowhere.
11122 Note that also `org-entry-get' calls this function, if the INHERIT flag
11123 is set.")
11125 (defun org-entry-get-with-inheritance (property)
11126 "Get entry property, and search higher levels if not present."
11127 (move-marker org-entry-property-inherited-from nil)
11128 (let (tmp)
11129 (save-excursion
11130 (save-restriction
11131 (widen)
11132 (catch 'ex
11133 (while t
11134 (when (setq tmp (org-entry-get nil property))
11135 (org-back-to-heading t)
11136 (move-marker org-entry-property-inherited-from (point))
11137 (throw 'ex tmp))
11138 (or (org-up-heading-safe) (throw 'ex nil)))))
11139 (or tmp
11140 (cdr (assoc property org-file-properties))
11141 (cdr (assoc property org-global-properties))
11142 (cdr (assoc property org-global-properties-fixed))))))
11144 (defun org-entry-put (pom property value)
11145 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11146 (org-with-point-at pom
11147 (org-back-to-heading t)
11148 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11149 range)
11150 (cond
11151 ((equal property "TODO")
11152 (when (and (stringp value) (string-match "\\S-" value)
11153 (not (member value org-todo-keywords-1)))
11154 (error "\"%s\" is not a valid TODO state" value))
11155 (if (or (not value)
11156 (not (string-match "\\S-" value)))
11157 (setq value 'none))
11158 (org-todo value)
11159 (org-set-tags nil 'align))
11160 ((equal property "PRIORITY")
11161 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11162 (string-to-char value) ?\ ))
11163 (org-set-tags nil 'align))
11164 ((equal property "SCHEDULED")
11165 (if (re-search-forward org-scheduled-time-regexp end t)
11166 (cond
11167 ((eq value 'earlier) (org-timestamp-change -1 'day))
11168 ((eq value 'later) (org-timestamp-change 1 'day))
11169 (t (call-interactively 'org-schedule)))
11170 (call-interactively 'org-schedule)))
11171 ((equal property "DEADLINE")
11172 (if (re-search-forward org-deadline-time-regexp end t)
11173 (cond
11174 ((eq value 'earlier) (org-timestamp-change -1 'day))
11175 ((eq value 'later) (org-timestamp-change 1 'day))
11176 (t (call-interactively 'org-deadline)))
11177 (call-interactively 'org-deadline)))
11178 ((member property org-special-properties)
11179 (error "The %s property can not yet be set with `org-entry-put'"
11180 property))
11181 (t ; a non-special property
11182 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11183 (setq range (org-get-property-block beg end 'force))
11184 (goto-char (car range))
11185 (if (re-search-forward
11186 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11187 (progn
11188 (delete-region (match-beginning 1) (match-end 1))
11189 (goto-char (match-beginning 1)))
11190 (goto-char (cdr range))
11191 (insert "\n")
11192 (backward-char 1)
11193 (org-indent-line-function)
11194 (insert ":" property ":"))
11195 (and value (insert " " value))
11196 (org-indent-line-function)))))))
11198 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11199 "Get all property keys in the current buffer.
11200 With INCLUDE-SPECIALS, also list the special properties that reflect things
11201 like tags and TODO state.
11202 With INCLUDE-DEFAULTS, also include properties that has special meaning
11203 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11204 With INCLUDE-COLUMNS, also include property names given in COLUMN
11205 formats in the current buffer."
11206 (let (rtn range cfmt s p)
11207 (save-excursion
11208 (save-restriction
11209 (widen)
11210 (goto-char (point-min))
11211 (while (re-search-forward org-property-start-re nil t)
11212 (setq range (org-get-property-block))
11213 (goto-char (car range))
11214 (while (re-search-forward
11215 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11216 (cdr range) t)
11217 (add-to-list 'rtn (org-match-string-no-properties 1)))
11218 (outline-next-heading))))
11220 (when include-specials
11221 (setq rtn (append org-special-properties rtn)))
11223 (when include-defaults
11224 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11226 (when include-columns
11227 (save-excursion
11228 (save-restriction
11229 (widen)
11230 (goto-char (point-min))
11231 (while (re-search-forward
11232 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11233 nil t)
11234 (setq cfmt (match-string 2) s 0)
11235 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11236 cfmt s)
11237 (setq s (match-end 0)
11238 p (match-string 1 cfmt))
11239 (unless (or (equal p "ITEM")
11240 (member p org-special-properties))
11241 (add-to-list 'rtn (match-string 1 cfmt))))))))
11243 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11245 (defun org-property-values (key)
11246 "Return a list of all values of property KEY."
11247 (save-excursion
11248 (save-restriction
11249 (widen)
11250 (goto-char (point-min))
11251 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11252 values)
11253 (while (re-search-forward re nil t)
11254 (add-to-list 'values (org-trim (match-string 1))))
11255 (delete "" values)))))
11257 (defun org-insert-property-drawer ()
11258 "Insert a property drawer into the current entry."
11259 (interactive)
11260 (org-back-to-heading t)
11261 (looking-at outline-regexp)
11262 (let ((indent (- (match-end 0)(match-beginning 0)))
11263 (beg (point))
11264 (re (concat "^[ \t]*" org-keyword-time-regexp))
11265 end hiddenp)
11266 (outline-next-heading)
11267 (setq end (point))
11268 (goto-char beg)
11269 (while (re-search-forward re end t))
11270 (setq hiddenp (org-invisible-p))
11271 (end-of-line 1)
11272 (and (equal (char-after) ?\n) (forward-char 1))
11273 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11274 (if (member (match-string 1) '("CLOCK:" ":END:"))
11275 ;; just skip this line
11276 (beginning-of-line 2)
11277 ;; Drawer start, find the end
11278 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11279 (beginning-of-line 1)))
11280 (org-skip-over-state-notes)
11281 (skip-chars-backward " \t\n\r")
11282 (if (eq (char-before) ?*) (forward-char 1))
11283 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11284 (beginning-of-line 0)
11285 (org-indent-to-column indent)
11286 (beginning-of-line 2)
11287 (org-indent-to-column indent)
11288 (beginning-of-line 0)
11289 (if hiddenp
11290 (save-excursion
11291 (org-back-to-heading t)
11292 (hide-entry))
11293 (org-flag-drawer t))))
11295 (defun org-set-property (property value)
11296 "In the current entry, set PROPERTY to VALUE.
11297 When called interactively, this will prompt for a property name, offering
11298 completion on existing and default properties. And then it will prompt
11299 for a value, offering completion either on allowed values (via an inherited
11300 xxx_ALL property) or on existing values in other instances of this property
11301 in the current file."
11302 (interactive
11303 (let* ((completion-ignore-case t)
11304 (keys (org-buffer-property-keys nil t t))
11305 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11306 (prop (if (member prop0 keys)
11307 prop0
11308 (or (cdr (assoc (downcase prop0)
11309 (mapcar (lambda (x) (cons (downcase x) x))
11310 keys)))
11311 prop0)))
11312 (cur (org-entry-get nil prop))
11313 (allowed (org-property-get-allowed-values nil prop 'table))
11314 (existing (mapcar 'list (org-property-values prop)))
11315 (val (if allowed
11316 (org-completing-read "Value: " allowed nil 'req-match)
11317 (let (org-completion-use-ido)
11318 (org-completing-read
11319 (concat "Value" (if (and cur (string-match "\\S-" cur))
11320 (concat "[" cur "]") "")
11321 ": ")
11322 existing nil nil "" nil cur)))))
11323 (list prop (if (equal val "") cur val))))
11324 (unless (equal (org-entry-get nil property) value)
11325 (org-entry-put nil property value)))
11327 (defun org-delete-property (property)
11328 "In the current entry, delete PROPERTY."
11329 (interactive
11330 (let* ((completion-ignore-case t)
11331 (prop (org-ido-completing-read
11332 "Property: " (org-entry-properties nil 'standard))))
11333 (list prop)))
11334 (message "Property %s %s" property
11335 (if (org-entry-delete nil property)
11336 "deleted"
11337 "was not present in the entry")))
11339 (defun org-delete-property-globally (property)
11340 "Remove PROPERTY globally, from all entries."
11341 (interactive
11342 (let* ((completion-ignore-case t)
11343 (prop (org-ido-completing-read
11344 "Globally remove property: "
11345 (mapcar 'list (org-buffer-property-keys)))))
11346 (list prop)))
11347 (save-excursion
11348 (save-restriction
11349 (widen)
11350 (goto-char (point-min))
11351 (let ((cnt 0))
11352 (while (re-search-forward
11353 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11354 nil t)
11355 (setq cnt (1+ cnt))
11356 (replace-match ""))
11357 (message "Property \"%s\" removed from %d entries" property cnt)))))
11359 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11361 (defun org-compute-property-at-point ()
11362 "Compute the property at point.
11363 This looks for an enclosing column format, extracts the operator and
11364 then applies it to the property in the column format's scope."
11365 (interactive)
11366 (unless (org-at-property-p)
11367 (error "Not at a property"))
11368 (let ((prop (org-match-string-no-properties 2)))
11369 (org-columns-get-format-and-top-level)
11370 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11371 (error "No operator defined for property %s" prop))
11372 (org-columns-compute prop)))
11374 (defun org-property-get-allowed-values (pom property &optional table)
11375 "Get allowed values for the property PROPERTY.
11376 When TABLE is non-nil, return an alist that can directly be used for
11377 completion."
11378 (let (vals)
11379 (cond
11380 ((equal property "TODO")
11381 (setq vals (org-with-point-at pom
11382 (append org-todo-keywords-1 '("")))))
11383 ((equal property "PRIORITY")
11384 (let ((n org-lowest-priority))
11385 (while (>= n org-highest-priority)
11386 (push (char-to-string n) vals)
11387 (setq n (1- n)))))
11388 ((member property org-special-properties))
11390 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11392 (when (and vals (string-match "\\S-" vals))
11393 (setq vals (car (read-from-string (concat "(" vals ")"))))
11394 (setq vals (mapcar (lambda (x)
11395 (cond ((stringp x) x)
11396 ((numberp x) (number-to-string x))
11397 ((symbolp x) (symbol-name x))
11398 (t "???")))
11399 vals)))))
11400 (if table (mapcar 'list vals) vals)))
11402 (defun org-property-previous-allowed-value (&optional previous)
11403 "Switch to the next allowed value for this property."
11404 (interactive)
11405 (org-property-next-allowed-value t))
11407 (defun org-property-next-allowed-value (&optional previous)
11408 "Switch to the next allowed value for this property."
11409 (interactive)
11410 (unless (org-at-property-p)
11411 (error "Not at a property"))
11412 (let* ((key (match-string 2))
11413 (value (match-string 3))
11414 (allowed (or (org-property-get-allowed-values (point) key)
11415 (and (member value '("[ ]" "[-]" "[X]"))
11416 '("[ ]" "[X]"))))
11417 nval)
11418 (unless allowed
11419 (error "Allowed values for this property have not been defined"))
11420 (if previous (setq allowed (reverse allowed)))
11421 (if (member value allowed)
11422 (setq nval (car (cdr (member value allowed)))))
11423 (setq nval (or nval (car allowed)))
11424 (if (equal nval value)
11425 (error "Only one allowed value for this property"))
11426 (org-at-property-p)
11427 (replace-match (concat " :" key ": " nval) t t)
11428 (org-indent-line-function)
11429 (beginning-of-line 1)
11430 (skip-chars-forward " \t")))
11432 (defun org-find-entry-with-id (ident)
11433 "Locate the entry that contains the ID property with exact value IDENT.
11434 IDENT can be a string, a symbol or a number, this function will search for
11435 the string representation of it.
11436 Return the position where this entry starts, or nil if there is no such entry."
11437 (interactive "sID: ")
11438 (let ((id (cond
11439 ((stringp ident) ident)
11440 ((symbol-name ident) (symbol-name ident))
11441 ((numberp ident) (number-to-string ident))
11442 (t (error "IDENT %s must be a string, symbol or number" ident))))
11443 (case-fold-search nil))
11444 (save-excursion
11445 (save-restriction
11446 (widen)
11447 (goto-char (point-min))
11448 (when (re-search-forward
11449 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11450 nil t)
11451 (org-back-to-heading)
11452 (point))))))
11454 ;;;; Timestamps
11456 (defvar org-last-changed-timestamp nil)
11457 (defvar org-last-inserted-timestamp nil
11458 "The last time stamp inserted with `org-insert-time-stamp'.")
11459 (defvar org-time-was-given) ; dynamically scoped parameter
11460 (defvar org-end-time-was-given) ; dynamically scoped parameter
11461 (defvar org-ts-what) ; dynamically scoped parameter
11463 (defun org-time-stamp (arg &optional inactive)
11464 "Prompt for a date/time and insert a time stamp.
11465 If the user specifies a time like HH:MM, or if this command is called
11466 with a prefix argument, the time stamp will contain date and time.
11467 Otherwise, only the date will be included. All parts of a date not
11468 specified by the user will be filled in from the current date/time.
11469 So if you press just return without typing anything, the time stamp
11470 will represent the current date/time. If there is already a timestamp
11471 at the cursor, it will be modified."
11472 (interactive "P")
11473 (let* ((ts nil)
11474 (default-time
11475 ;; Default time is either today, or, when entering a range,
11476 ;; the range start.
11477 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11478 (save-excursion
11479 (re-search-backward
11480 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11481 (- (point) 20) t)))
11482 (apply 'encode-time (org-parse-time-string (match-string 1)))
11483 (current-time)))
11484 (default-input (and ts (org-get-compact-tod ts)))
11485 org-time-was-given org-end-time-was-given time)
11486 (cond
11487 ((and (org-at-timestamp-p t)
11488 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11489 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11490 (insert "--")
11491 (setq time (let ((this-command this-command))
11492 (org-read-date arg 'totime nil nil
11493 default-time default-input)))
11494 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11495 ((org-at-timestamp-p t)
11496 (setq time (let ((this-command this-command))
11497 (org-read-date arg 'totime nil nil default-time default-input)))
11498 (when (org-at-timestamp-p t) ; just to get the match data
11499 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11500 (replace-match "")
11501 (setq org-last-changed-timestamp
11502 (org-insert-time-stamp
11503 time (or org-time-was-given arg)
11504 inactive nil nil (list org-end-time-was-given))))
11505 (message "Timestamp updated"))
11507 (setq time (let ((this-command this-command))
11508 (org-read-date arg 'totime nil nil default-time default-input)))
11509 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11510 nil nil (list org-end-time-was-given))))))
11512 ;; FIXME: can we use this for something else, like computing time differences?
11513 (defun org-get-compact-tod (s)
11514 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11515 (let* ((t1 (match-string 1 s))
11516 (h1 (string-to-number (match-string 2 s)))
11517 (m1 (string-to-number (match-string 3 s)))
11518 (t2 (and (match-end 4) (match-string 5 s)))
11519 (h2 (and t2 (string-to-number (match-string 6 s))))
11520 (m2 (and t2 (string-to-number (match-string 7 s))))
11521 dh dm)
11522 (if (not t2)
11524 (setq dh (- h2 h1) dm (- m2 m1))
11525 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11526 (concat t1 "+" (number-to-string dh)
11527 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11529 (defun org-time-stamp-inactive (&optional arg)
11530 "Insert an inactive time stamp.
11531 An inactive time stamp is enclosed in square brackets instead of angle
11532 brackets. It is inactive in the sense that it does not trigger agenda entries,
11533 does not link to the calendar and cannot be changed with the S-cursor keys.
11534 So these are more for recording a certain time/date."
11535 (interactive "P")
11536 (org-time-stamp arg 'inactive))
11538 (defvar org-date-ovl (org-make-overlay 1 1))
11539 (org-overlay-put org-date-ovl 'face 'org-warning)
11540 (org-detach-overlay org-date-ovl)
11542 (defvar org-ans1) ; dynamically scoped parameter
11543 (defvar org-ans2) ; dynamically scoped parameter
11545 (defvar org-plain-time-of-day-regexp) ; defined below
11547 (defvar org-overriding-default-time nil) ; dynamically scoped
11548 (defvar org-read-date-overlay nil)
11549 (defvar org-dcst nil) ; dynamically scoped
11551 (defun org-read-date (&optional with-time to-time from-string prompt
11552 default-time default-input)
11553 "Read a date, possibly a time, and make things smooth for the user.
11554 The prompt will suggest to enter an ISO date, but you can also enter anything
11555 which will at least partially be understood by `parse-time-string'.
11556 Unrecognized parts of the date will default to the current day, month, year,
11557 hour and minute. If this command is called to replace a timestamp at point,
11558 of to enter the second timestamp of a range, the default time is taken from the
11559 existing stamp. For example,
11560 3-2-5 --> 2003-02-05
11561 feb 15 --> currentyear-02-15
11562 sep 12 9 --> 2009-09-12
11563 12:45 --> today 12:45
11564 22 sept 0:34 --> currentyear-09-22 0:34
11565 12 --> currentyear-currentmonth-12
11566 Fri --> nearest Friday (today or later)
11567 etc.
11569 Furthermore you can specify a relative date by giving, as the *first* thing
11570 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11571 change in days weeks, months, years.
11572 With a single plus or minus, the date is relative to today. With a double
11573 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11574 +4d --> four days from today
11575 +4 --> same as above
11576 +2w --> two weeks from today
11577 ++5 --> five days from default date
11579 The function understands only English month and weekday abbreviations,
11580 but this can be configured with the variables `parse-time-months' and
11581 `parse-time-weekdays'.
11583 While prompting, a calendar is popped up - you can also select the
11584 date with the mouse (button 1). The calendar shows a period of three
11585 months. To scroll it to other months, use the keys `>' and `<'.
11586 If you don't like the calendar, turn it off with
11587 \(setq org-read-date-popup-calendar nil)
11589 With optional argument TO-TIME, the date will immediately be converted
11590 to an internal time.
11591 With an optional argument WITH-TIME, the prompt will suggest to also
11592 insert a time. Note that when WITH-TIME is not set, you can still
11593 enter a time, and this function will inform the calling routine about
11594 this change. The calling routine may then choose to change the format
11595 used to insert the time stamp into the buffer to include the time.
11596 With optional argument FROM-STRING, read from this string instead from
11597 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11598 the time/date that is used for everything that is not specified by the
11599 user."
11600 (require 'parse-time)
11601 (let* ((org-time-stamp-rounding-minutes
11602 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11603 (org-dcst org-display-custom-times)
11604 (ct (org-current-time))
11605 (def (or org-overriding-default-time default-time ct))
11606 (defdecode (decode-time def))
11607 (dummy (progn
11608 (when (< (nth 2 defdecode) org-extend-today-until)
11609 (setcar (nthcdr 2 defdecode) -1)
11610 (setcar (nthcdr 1 defdecode) 59)
11611 (setq def (apply 'encode-time defdecode)
11612 defdecode (decode-time def)))))
11613 (calendar-move-hook nil)
11614 (calendar-view-diary-initially-flag nil)
11615 (view-diary-entries-initially nil)
11616 (calendar-view-holidays-initially-flag nil)
11617 (view-calendar-holidays-initially nil)
11618 (timestr (format-time-string
11619 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11620 (prompt (concat (if prompt (concat prompt " ") "")
11621 (format "Date+time [%s]: " timestr)))
11622 ans (org-ans0 "") org-ans1 org-ans2 final)
11624 (cond
11625 (from-string (setq ans from-string))
11626 (org-read-date-popup-calendar
11627 (save-excursion
11628 (save-window-excursion
11629 (calendar)
11630 (calendar-forward-day (- (time-to-days def)
11631 (calendar-absolute-from-gregorian
11632 (calendar-current-date))))
11633 (org-eval-in-calendar nil t)
11634 (let* ((old-map (current-local-map))
11635 (map (copy-keymap calendar-mode-map))
11636 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11637 (org-defkey map (kbd "RET") 'org-calendar-select)
11638 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11639 'org-calendar-select-mouse)
11640 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11641 'org-calendar-select-mouse)
11642 (org-defkey minibuffer-local-map [(meta shift left)]
11643 (lambda () (interactive)
11644 (org-eval-in-calendar '(calendar-backward-month 1))))
11645 (org-defkey minibuffer-local-map [(meta shift right)]
11646 (lambda () (interactive)
11647 (org-eval-in-calendar '(calendar-forward-month 1))))
11648 (org-defkey minibuffer-local-map [(meta shift up)]
11649 (lambda () (interactive)
11650 (org-eval-in-calendar '(calendar-backward-year 1))))
11651 (org-defkey minibuffer-local-map [(meta shift down)]
11652 (lambda () (interactive)
11653 (org-eval-in-calendar '(calendar-forward-year 1))))
11654 (org-defkey minibuffer-local-map [(shift up)]
11655 (lambda () (interactive)
11656 (org-eval-in-calendar '(calendar-backward-week 1))))
11657 (org-defkey minibuffer-local-map [(shift down)]
11658 (lambda () (interactive)
11659 (org-eval-in-calendar '(calendar-forward-week 1))))
11660 (org-defkey minibuffer-local-map [(shift left)]
11661 (lambda () (interactive)
11662 (org-eval-in-calendar '(calendar-backward-day 1))))
11663 (org-defkey minibuffer-local-map [(shift right)]
11664 (lambda () (interactive)
11665 (org-eval-in-calendar '(calendar-forward-day 1))))
11666 (org-defkey minibuffer-local-map ">"
11667 (lambda () (interactive)
11668 (org-eval-in-calendar '(scroll-calendar-left 1))))
11669 (org-defkey minibuffer-local-map "<"
11670 (lambda () (interactive)
11671 (org-eval-in-calendar '(scroll-calendar-right 1))))
11672 (unwind-protect
11673 (progn
11674 (use-local-map map)
11675 (add-hook 'post-command-hook 'org-read-date-display)
11676 (setq org-ans0 (read-string prompt default-input nil nil))
11677 ;; org-ans0: from prompt
11678 ;; org-ans1: from mouse click
11679 ;; org-ans2: from calendar motion
11680 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11681 (remove-hook 'post-command-hook 'org-read-date-display)
11682 (use-local-map old-map)
11683 (when org-read-date-overlay
11684 (org-delete-overlay org-read-date-overlay)
11685 (setq org-read-date-overlay nil)))))))
11687 (t ; Naked prompt only
11688 (unwind-protect
11689 (setq ans (read-string prompt default-input nil timestr))
11690 (when org-read-date-overlay
11691 (org-delete-overlay org-read-date-overlay)
11692 (setq org-read-date-overlay nil)))))
11694 (setq final (org-read-date-analyze ans def defdecode))
11696 (if to-time
11697 (apply 'encode-time final)
11698 (if (and (boundp 'org-time-was-given) org-time-was-given)
11699 (format "%04d-%02d-%02d %02d:%02d"
11700 (nth 5 final) (nth 4 final) (nth 3 final)
11701 (nth 2 final) (nth 1 final))
11702 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11703 (defvar def)
11704 (defvar defdecode)
11705 (defvar with-time)
11706 (defun org-read-date-display ()
11707 "Display the current date prompt interpretation in the minibuffer."
11708 (when org-read-date-display-live
11709 (when org-read-date-overlay
11710 (org-delete-overlay org-read-date-overlay))
11711 (let ((p (point)))
11712 (end-of-line 1)
11713 (while (not (equal (buffer-substring
11714 (max (point-min) (- (point) 4)) (point))
11715 " "))
11716 (insert " "))
11717 (goto-char p))
11718 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11719 " " (or org-ans1 org-ans2)))
11720 (org-end-time-was-given nil)
11721 (f (org-read-date-analyze ans def defdecode))
11722 (fmts (if org-dcst
11723 org-time-stamp-custom-formats
11724 org-time-stamp-formats))
11725 (fmt (if (or with-time
11726 (and (boundp 'org-time-was-given) org-time-was-given))
11727 (cdr fmts)
11728 (car fmts)))
11729 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11730 (when (and org-end-time-was-given
11731 (string-match org-plain-time-of-day-regexp txt))
11732 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11733 org-end-time-was-given
11734 (substring txt (match-end 0)))))
11735 (setq org-read-date-overlay
11736 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11737 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11739 (defun org-read-date-analyze (ans def defdecode)
11740 "Analyse the combined answer of the date prompt."
11741 ;; FIXME: cleanup and comment
11742 (let (delta deltan deltaw deltadef year month day
11743 hour minute second wday pm h2 m2 tl wday1
11744 iso-year iso-weekday iso-week iso-year iso-date)
11746 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11747 (setq ans "+0"))
11749 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11750 (setq ans (replace-match "" t t ans)
11751 deltan (car delta)
11752 deltaw (nth 1 delta)
11753 deltadef (nth 2 delta)))
11755 ;; Check if there is an iso week date in there
11756 ;; If yes, sore the info and postpone interpreting it until the rest
11757 ;; of the parsing is done
11758 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11759 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11760 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11761 iso-week (string-to-number (match-string 2 ans)))
11762 (setq ans (replace-match "" t t ans)))
11764 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11765 (when (string-match
11766 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11767 (setq year (if (match-end 2)
11768 (string-to-number (match-string 2 ans))
11769 (string-to-number (format-time-string "%Y")))
11770 month (string-to-number (match-string 3 ans))
11771 day (string-to-number (match-string 4 ans)))
11772 (if (< year 100) (setq year (+ 2000 year)))
11773 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11774 t nil ans)))
11775 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11776 ;; If there is a time with am/pm, and *no* time without it, we convert
11777 ;; so that matching will be successful.
11778 (loop for i from 1 to 2 do ; twice, for end time as well
11779 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11780 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11781 (setq hour (string-to-number (match-string 1 ans))
11782 minute (if (match-end 3)
11783 (string-to-number (match-string 3 ans))
11785 pm (equal ?p
11786 (string-to-char (downcase (match-string 4 ans)))))
11787 (if (and (= hour 12) (not pm))
11788 (setq hour 0)
11789 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11790 (setq ans (replace-match (format "%02d:%02d" hour minute)
11791 t t ans))))
11793 ;; Check if a time range is given as a duration
11794 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11795 (setq hour (string-to-number (match-string 1 ans))
11796 h2 (+ hour (string-to-number (match-string 3 ans)))
11797 minute (string-to-number (match-string 2 ans))
11798 m2 (+ minute (if (match-end 5) (string-to-number
11799 (match-string 5 ans))0)))
11800 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11801 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11802 t t ans)))
11804 ;; Check if there is a time range
11805 (when (boundp 'org-end-time-was-given)
11806 (setq org-time-was-given nil)
11807 (when (and (string-match org-plain-time-of-day-regexp ans)
11808 (match-end 8))
11809 (setq org-end-time-was-given (match-string 8 ans))
11810 (setq ans (concat (substring ans 0 (match-beginning 7))
11811 (substring ans (match-end 7))))))
11813 (setq tl (parse-time-string ans)
11814 day (or (nth 3 tl) (nth 3 defdecode))
11815 month (or (nth 4 tl)
11816 (if (and org-read-date-prefer-future
11817 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11818 (1+ (nth 4 defdecode))
11819 (nth 4 defdecode)))
11820 year (or (nth 5 tl)
11821 (if (and org-read-date-prefer-future
11822 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11823 (1+ (nth 5 defdecode))
11824 (nth 5 defdecode)))
11825 hour (or (nth 2 tl) (nth 2 defdecode))
11826 minute (or (nth 1 tl) (nth 1 defdecode))
11827 second (or (nth 0 tl) 0)
11828 wday (nth 6 tl))
11830 ;; Special date definitions below
11831 (cond
11832 (iso-week
11833 ;; There was an iso week
11834 (setq year (or iso-year year)
11835 day (or iso-weekday wday 1)
11836 wday nil ; to make sure that the trigger below does not match
11837 iso-date (calendar-gregorian-from-absolute
11838 (calendar-absolute-from-iso
11839 (list iso-week day year))))
11840 ; FIXME: Should we also push ISO weeks into the future?
11841 ; (when (and org-read-date-prefer-future
11842 ; (not iso-year)
11843 ; (< (calendar-absolute-from-gregorian iso-date)
11844 ; (time-to-days (current-time))))
11845 ; (setq year (1+ year)
11846 ; iso-date (calendar-gregorian-from-absolute
11847 ; (calendar-absolute-from-iso
11848 ; (list iso-week day year)))))
11849 (setq month (car iso-date)
11850 year (nth 2 iso-date)
11851 day (nth 1 iso-date)))
11852 (deltan
11853 (unless deltadef
11854 (let ((now (decode-time (current-time))))
11855 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11856 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11857 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11858 ((equal deltaw "m") (setq month (+ month deltan)))
11859 ((equal deltaw "y") (setq year (+ year deltan)))))
11860 ((and wday (not (nth 3 tl)))
11861 ;; Weekday was given, but no day, so pick that day in the week
11862 ;; on or after the derived date.
11863 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11864 (unless (equal wday wday1)
11865 (setq day (+ day (% (- wday wday1 -7) 7))))))
11866 (if (and (boundp 'org-time-was-given)
11867 (nth 2 tl))
11868 (setq org-time-was-given t))
11869 (if (< year 100) (setq year (+ 2000 year)))
11870 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11871 (list second minute hour day month year)))
11873 (defvar parse-time-weekdays)
11875 (defun org-read-date-get-relative (s today default)
11876 "Check string S for special relative date string.
11877 TODAY and DEFAULT are internal times, for today and for a default.
11878 Return shift list (N what def-flag)
11879 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11880 N is the number of WHATs to shift.
11881 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11882 the DEFAULT date rather than TODAY."
11883 (when (and
11884 (string-match
11885 (concat
11886 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11887 "\\([0-9]+\\)?"
11888 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11889 "\\([ \t]\\|$\\)") s)
11890 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11891 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11892 (string-to-char (substring (match-string 1 s) -1))
11893 ?+))
11894 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11895 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11896 (what (if (match-end 3) (match-string 3 s) "d"))
11897 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11898 (date (if rel default today))
11899 (wday (nth 6 (decode-time date)))
11900 delta)
11901 (if wday1
11902 (progn
11903 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11904 (if (= dir ?-) (setq delta (- delta 7)))
11905 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11906 (list delta "d" rel))
11907 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11909 (defun org-eval-in-calendar (form &optional keepdate)
11910 "Eval FORM in the calendar window and return to current window.
11911 Also, store the cursor date in variable org-ans2."
11912 (let ((sw (selected-window)))
11913 (select-window (get-buffer-window "*Calendar*"))
11914 (eval form)
11915 (when (and (not keepdate) (calendar-cursor-to-date))
11916 (let* ((date (calendar-cursor-to-date))
11917 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11918 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11919 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11920 (select-window sw)))
11922 (defun org-calendar-select ()
11923 "Return to `org-read-date' with the date currently selected.
11924 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11925 (interactive)
11926 (when (calendar-cursor-to-date)
11927 (let* ((date (calendar-cursor-to-date))
11928 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11929 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11930 (if (active-minibuffer-window) (exit-minibuffer))))
11932 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11933 "Insert a date stamp for the date given by the internal TIME.
11934 WITH-HM means, use the stamp format that includes the time of the day.
11935 INACTIVE means use square brackets instead of angular ones, so that the
11936 stamp will not contribute to the agenda.
11937 PRE and POST are optional strings to be inserted before and after the
11938 stamp.
11939 The command returns the inserted time stamp."
11940 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11941 stamp)
11942 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11943 (insert-before-markers (or pre ""))
11944 (insert-before-markers (setq stamp (format-time-string fmt time)))
11945 (when (listp extra)
11946 (setq extra (car extra))
11947 (if (and (stringp extra)
11948 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11949 (setq extra (format "-%02d:%02d"
11950 (string-to-number (match-string 1 extra))
11951 (string-to-number (match-string 2 extra))))
11952 (setq extra nil)))
11953 (when extra
11954 (backward-char 1)
11955 (insert-before-markers extra)
11956 (forward-char 1))
11957 (insert-before-markers (or post ""))
11958 (setq org-last-inserted-timestamp stamp)))
11960 (defun org-toggle-time-stamp-overlays ()
11961 "Toggle the use of custom time stamp formats."
11962 (interactive)
11963 (setq org-display-custom-times (not org-display-custom-times))
11964 (unless org-display-custom-times
11965 (let ((p (point-min)) (bmp (buffer-modified-p)))
11966 (while (setq p (next-single-property-change p 'display))
11967 (if (and (get-text-property p 'display)
11968 (eq (get-text-property p 'face) 'org-date))
11969 (remove-text-properties
11970 p (setq p (next-single-property-change p 'display))
11971 '(display t))))
11972 (set-buffer-modified-p bmp)))
11973 (if (featurep 'xemacs)
11974 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11975 (org-restart-font-lock)
11976 (setq org-table-may-need-update t)
11977 (if org-display-custom-times
11978 (message "Time stamps are overlayed with custom format")
11979 (message "Time stamp overlays removed")))
11981 (defun org-display-custom-time (beg end)
11982 "Overlay modified time stamp format over timestamp between BEG and END."
11983 (let* ((ts (buffer-substring beg end))
11984 t1 w1 with-hm tf time str w2 (off 0))
11985 (save-match-data
11986 (setq t1 (org-parse-time-string ts t))
11987 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11988 (setq off (- (match-end 0) (match-beginning 0)))))
11989 (setq end (- end off))
11990 (setq w1 (- end beg)
11991 with-hm (and (nth 1 t1) (nth 2 t1))
11992 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11993 time (org-fix-decoded-time t1)
11994 str (org-add-props
11995 (format-time-string
11996 (substring tf 1 -1) (apply 'encode-time time))
11997 nil 'mouse-face 'highlight)
11998 w2 (length str))
11999 (if (not (= w2 w1))
12000 (add-text-properties (1+ beg) (+ 2 beg)
12001 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12002 (if (featurep 'xemacs)
12003 (progn
12004 (put-text-property beg end 'invisible t)
12005 (put-text-property beg end 'end-glyph (make-glyph str)))
12006 (put-text-property beg end 'display str))))
12008 (defun org-translate-time (string)
12009 "Translate all timestamps in STRING to custom format.
12010 But do this only if the variable `org-display-custom-times' is set."
12011 (when org-display-custom-times
12012 (save-match-data
12013 (let* ((start 0)
12014 (re org-ts-regexp-both)
12015 t1 with-hm inactive tf time str beg end)
12016 (while (setq start (string-match re string start))
12017 (setq beg (match-beginning 0)
12018 end (match-end 0)
12019 t1 (save-match-data
12020 (org-parse-time-string (substring string beg end) t))
12021 with-hm (and (nth 1 t1) (nth 2 t1))
12022 inactive (equal (substring string beg (1+ beg)) "[")
12023 tf (funcall (if with-hm 'cdr 'car)
12024 org-time-stamp-custom-formats)
12025 time (org-fix-decoded-time t1)
12026 str (format-time-string
12027 (concat
12028 (if inactive "[" "<") (substring tf 1 -1)
12029 (if inactive "]" ">"))
12030 (apply 'encode-time time))
12031 string (replace-match str t t string)
12032 start (+ start (length str)))))))
12033 string)
12035 (defun org-fix-decoded-time (time)
12036 "Set 0 instead of nil for the first 6 elements of time.
12037 Don't touch the rest."
12038 (let ((n 0))
12039 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12041 (defun org-days-to-time (timestamp-string)
12042 "Difference between TIMESTAMP-STRING and now in days."
12043 (- (time-to-days (org-time-string-to-time timestamp-string))
12044 (time-to-days (current-time))))
12046 (defun org-deadline-close (timestamp-string &optional ndays)
12047 "Is the time in TIMESTAMP-STRING close to the current date?"
12048 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12049 (and (< (org-days-to-time timestamp-string) ndays)
12050 (not (org-entry-is-done-p))))
12052 (defun org-get-wdays (ts)
12053 "Get the deadline lead time appropriate for timestring TS."
12054 (cond
12055 ((<= org-deadline-warning-days 0)
12056 ;; 0 or negative, enforce this value no matter what
12057 (- org-deadline-warning-days))
12058 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12059 ;; lead time is specified.
12060 (floor (* (string-to-number (match-string 1 ts))
12061 (cdr (assoc (match-string 2 ts)
12062 '(("d" . 1) ("w" . 7)
12063 ("m" . 30.4) ("y" . 365.25)))))))
12064 ;; go for the default.
12065 (t org-deadline-warning-days)))
12067 (defun org-calendar-select-mouse (ev)
12068 "Return to `org-read-date' with the date currently selected.
12069 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12070 (interactive "e")
12071 (mouse-set-point ev)
12072 (when (calendar-cursor-to-date)
12073 (let* ((date (calendar-cursor-to-date))
12074 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12075 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12076 (if (active-minibuffer-window) (exit-minibuffer))))
12078 (defun org-check-deadlines (ndays)
12079 "Check if there are any deadlines due or past due.
12080 A deadline is considered due if it happens within `org-deadline-warning-days'
12081 days from today's date. If the deadline appears in an entry marked DONE,
12082 it is not shown. The prefix arg NDAYS can be used to test that many
12083 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12084 (interactive "P")
12085 (let* ((org-warn-days
12086 (cond
12087 ((equal ndays '(4)) 100000)
12088 (ndays (prefix-numeric-value ndays))
12089 (t (abs org-deadline-warning-days))))
12090 (case-fold-search nil)
12091 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12092 (callback
12093 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12095 (message "%d deadlines past-due or due within %d days"
12096 (org-occur regexp nil callback)
12097 org-warn-days)))
12099 (defun org-check-before-date (date)
12100 "Check if there are deadlines or scheduled entries before DATE."
12101 (interactive (list (org-read-date)))
12102 (let ((case-fold-search nil)
12103 (regexp (concat "\\<\\(" org-deadline-string
12104 "\\|" org-scheduled-string
12105 "\\) *<\\([^>]+\\)>"))
12106 (callback
12107 (lambda () (time-less-p
12108 (org-time-string-to-time (match-string 2))
12109 (org-time-string-to-time date)))))
12110 (message "%d entries before %s"
12111 (org-occur regexp nil callback) date)))
12113 (defun org-evaluate-time-range (&optional to-buffer)
12114 "Evaluate a time range by computing the difference between start and end.
12115 Normally the result is just printed in the echo area, but with prefix arg
12116 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12117 If the time range is actually in a table, the result is inserted into the
12118 next column.
12119 For time difference computation, a year is assumed to be exactly 365
12120 days in order to avoid rounding problems."
12121 (interactive "P")
12123 (org-clock-update-time-maybe)
12124 (save-excursion
12125 (unless (org-at-date-range-p t)
12126 (goto-char (point-at-bol))
12127 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12128 (if (not (org-at-date-range-p t))
12129 (error "Not at a time-stamp range, and none found in current line")))
12130 (let* ((ts1 (match-string 1))
12131 (ts2 (match-string 2))
12132 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12133 (match-end (match-end 0))
12134 (time1 (org-time-string-to-time ts1))
12135 (time2 (org-time-string-to-time ts2))
12136 (t1 (time-to-seconds time1))
12137 (t2 (time-to-seconds time2))
12138 (diff (abs (- t2 t1)))
12139 (negative (< (- t2 t1) 0))
12140 ;; (ys (floor (* 365 24 60 60)))
12141 (ds (* 24 60 60))
12142 (hs (* 60 60))
12143 (fy "%dy %dd %02d:%02d")
12144 (fy1 "%dy %dd")
12145 (fd "%dd %02d:%02d")
12146 (fd1 "%dd")
12147 (fh "%02d:%02d")
12148 y d h m align)
12149 (if havetime
12150 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12152 d (floor (/ diff ds)) diff (mod diff ds)
12153 h (floor (/ diff hs)) diff (mod diff hs)
12154 m (floor (/ diff 60)))
12155 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12157 d (floor (+ (/ diff ds) 0.5))
12158 h 0 m 0))
12159 (if (not to-buffer)
12160 (message "%s" (org-make-tdiff-string y d h m))
12161 (if (org-at-table-p)
12162 (progn
12163 (goto-char match-end)
12164 (setq align t)
12165 (and (looking-at " *|") (goto-char (match-end 0))))
12166 (goto-char match-end))
12167 (if (looking-at
12168 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12169 (replace-match ""))
12170 (if negative (insert " -"))
12171 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12172 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12173 (insert " " (format fh h m))))
12174 (if align (org-table-align))
12175 (message "Time difference inserted")))))
12177 (defun org-make-tdiff-string (y d h m)
12178 (let ((fmt "")
12179 (l nil))
12180 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12181 l (push y l)))
12182 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12183 l (push d l)))
12184 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12185 l (push h l)))
12186 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12187 l (push m l)))
12188 (apply 'format fmt (nreverse l))))
12190 (defun org-time-string-to-time (s)
12191 (apply 'encode-time (org-parse-time-string s)))
12193 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12194 "Convert a time stamp to an absolute day number.
12195 If there is a specifyer for a cyclic time stamp, get the closest date to
12196 DAYNR.
12197 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12198 (cond
12199 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12200 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12201 daynr
12202 (+ daynr 1000)))
12203 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12204 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12205 (time-to-days (current-time))) (match-string 0 s)
12206 prefer show-all))
12207 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12209 (defun org-days-to-iso-week (days)
12210 "Return the iso week number."
12211 (require 'cal-iso)
12212 (car (calendar-iso-from-absolute days)))
12214 (defun org-small-year-to-year (year)
12215 "Convert 2-digit years into 4-digit years.
12216 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12217 The year 2000 cannot be abbreviated. Any year larger than 99
12218 is returned unchanged."
12219 (if (< year 38)
12220 (setq year (+ 2000 year))
12221 (if (< year 100)
12222 (setq year (+ 1900 year))))
12223 year)
12225 (defun org-time-from-absolute (d)
12226 "Return the time corresponding to date D.
12227 D may be an absolute day number, or a calendar-type list (month day year)."
12228 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12229 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12231 (defun org-calendar-holiday ()
12232 "List of holidays, for Diary display in Org-mode."
12233 (require 'holidays)
12234 (let ((hl (funcall
12235 (if (fboundp 'calendar-check-holidays)
12236 'calendar-check-holidays 'check-calendar-holidays) date)))
12237 (if hl (mapconcat 'identity hl "; "))))
12239 (defun org-diary-sexp-entry (sexp entry date)
12240 "Process a SEXP diary ENTRY for DATE."
12241 (require 'diary-lib)
12242 (let ((result (if calendar-debug-sexp
12243 (let ((stack-trace-on-error t))
12244 (eval (car (read-from-string sexp))))
12245 (condition-case nil
12246 (eval (car (read-from-string sexp)))
12247 (error
12248 (beep)
12249 (message "Bad sexp at line %d in %s: %s"
12250 (org-current-line)
12251 (buffer-file-name) sexp)
12252 (sleep-for 2))))))
12253 (cond ((stringp result) result)
12254 ((and (consp result)
12255 (stringp (cdr result))) (cdr result))
12256 (result entry)
12257 (t nil))))
12259 (defun org-diary-to-ical-string (frombuf)
12260 "Get iCalendar entries from diary entries in buffer FROMBUF.
12261 This uses the icalendar.el library."
12262 (let* ((tmpdir (if (featurep 'xemacs)
12263 (temp-directory)
12264 temporary-file-directory))
12265 (tmpfile (make-temp-name
12266 (expand-file-name "orgics" tmpdir)))
12267 buf rtn b e)
12268 (save-excursion
12269 (set-buffer frombuf)
12270 (icalendar-export-region (point-min) (point-max) tmpfile)
12271 (setq buf (find-buffer-visiting tmpfile))
12272 (set-buffer buf)
12273 (goto-char (point-min))
12274 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12275 (setq b (match-beginning 0)))
12276 (goto-char (point-max))
12277 (if (re-search-backward "^END:VEVENT" nil t)
12278 (setq e (match-end 0)))
12279 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12280 (kill-buffer buf)
12281 (delete-file tmpfile)
12282 rtn))
12284 (defun org-closest-date (start current change prefer show-all)
12285 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12286 When PREFER is `past' return a date that is either CURRENT or past.
12287 When PREFER is `future', return a date that is either CURRENT or future.
12288 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12289 ;; Make the proper lists from the dates
12290 (catch 'exit
12291 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12292 dn dw sday cday n1 n2 n0
12293 d m y y1 y2 date1 date2 nmonths nm ny m2)
12295 (setq start (org-date-to-gregorian start)
12296 current (org-date-to-gregorian
12297 (if show-all
12298 current
12299 (time-to-days (current-time))))
12300 sday (calendar-absolute-from-gregorian start)
12301 cday (calendar-absolute-from-gregorian current))
12303 (if (<= cday sday) (throw 'exit sday))
12305 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12306 (setq dn (string-to-number (match-string 1 change))
12307 dw (cdr (assoc (match-string 2 change) a1)))
12308 (error "Invalid change specifyer: %s" change))
12309 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12310 (cond
12311 ((eq dw 'day)
12312 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12313 n2 (+ n1 dn)))
12314 ((eq dw 'year)
12315 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12316 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12317 (setq date1 (list m d y1)
12318 n1 (calendar-absolute-from-gregorian date1)
12319 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12320 n2 (calendar-absolute-from-gregorian date2)))
12321 ((eq dw 'month)
12322 ;; approx number of month between the two dates
12323 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12324 ;; How often does dn fit in there?
12325 (setq d (nth 1 start) m (car start) y (nth 2 start)
12326 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12327 m (+ m nm)
12328 ny (floor (/ m 12))
12329 y (+ y ny)
12330 m (- m (* ny 12)))
12331 (while (> m 12) (setq m (- m 12) y (1+ y)))
12332 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12333 (setq m2 (+ m dn) y2 y)
12334 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12335 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12336 (while (<= n2 cday)
12337 (setq n1 n2 m m2 y y2)
12338 (setq m2 (+ m dn) y2 y)
12339 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12340 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12341 ;; Make sure n1 is the earlier date
12342 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12343 (if show-all
12344 (cond
12345 ((eq prefer 'past) n1)
12346 ((eq prefer 'future) (if (= cday n1) n1 n2))
12347 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12348 (cond
12349 ((eq prefer 'past) n1)
12350 ((eq prefer 'future) (if (= cday n1) n1 n2))
12351 (t (if (= cday n1) n1 n2)))))))
12353 (defun org-date-to-gregorian (date)
12354 "Turn any specification of DATE into a gregorian date for the calendar."
12355 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12356 ((and (listp date) (= (length date) 3)) date)
12357 ((stringp date)
12358 (setq date (org-parse-time-string date))
12359 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12360 ((listp date)
12361 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12363 (defun org-parse-time-string (s &optional nodefault)
12364 "Parse the standard Org-mode time string.
12365 This should be a lot faster than the normal `parse-time-string'.
12366 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12367 hour and minute fields will be nil if not given."
12368 (if (string-match org-ts-regexp0 s)
12369 (list 0
12370 (if (or (match-beginning 8) (not nodefault))
12371 (string-to-number (or (match-string 8 s) "0")))
12372 (if (or (match-beginning 7) (not nodefault))
12373 (string-to-number (or (match-string 7 s) "0")))
12374 (string-to-number (match-string 4 s))
12375 (string-to-number (match-string 3 s))
12376 (string-to-number (match-string 2 s))
12377 nil nil nil)
12378 (make-list 9 0)))
12380 (defun org-timestamp-up (&optional arg)
12381 "Increase the date item at the cursor by one.
12382 If the cursor is on the year, change the year. If it is on the month or
12383 the day, change that.
12384 With prefix ARG, change by that many units."
12385 (interactive "p")
12386 (org-timestamp-change (prefix-numeric-value arg)))
12388 (defun org-timestamp-down (&optional arg)
12389 "Decrease the date item at the cursor by one.
12390 If the cursor is on the year, change the year. If it is on the month or
12391 the day, change that.
12392 With prefix ARG, change by that many units."
12393 (interactive "p")
12394 (org-timestamp-change (- (prefix-numeric-value arg))))
12396 (defun org-timestamp-up-day (&optional arg)
12397 "Increase the date in the time stamp by one day.
12398 With prefix ARG, change that many days."
12399 (interactive "p")
12400 (if (and (not (org-at-timestamp-p t))
12401 (org-on-heading-p))
12402 (org-todo 'up)
12403 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12405 (defun org-timestamp-down-day (&optional arg)
12406 "Decrease the date in the time stamp by one day.
12407 With prefix ARG, change that many days."
12408 (interactive "p")
12409 (if (and (not (org-at-timestamp-p t))
12410 (org-on-heading-p))
12411 (org-todo 'down)
12412 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12414 (defun org-at-timestamp-p (&optional inactive-ok)
12415 "Determine if the cursor is in or at a timestamp."
12416 (interactive)
12417 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12418 (pos (point))
12419 (ans (or (looking-at tsr)
12420 (save-excursion
12421 (skip-chars-backward "^[<\n\r\t")
12422 (if (> (point) (point-min)) (backward-char 1))
12423 (and (looking-at tsr)
12424 (> (- (match-end 0) pos) -1))))))
12425 (and ans
12426 (boundp 'org-ts-what)
12427 (setq org-ts-what
12428 (cond
12429 ((= pos (match-beginning 0)) 'bracket)
12430 ((= pos (1- (match-end 0))) 'bracket)
12431 ((org-pos-in-match-range pos 2) 'year)
12432 ((org-pos-in-match-range pos 3) 'month)
12433 ((org-pos-in-match-range pos 7) 'hour)
12434 ((org-pos-in-match-range pos 8) 'minute)
12435 ((or (org-pos-in-match-range pos 4)
12436 (org-pos-in-match-range pos 5)) 'day)
12437 ((and (> pos (or (match-end 8) (match-end 5)))
12438 (< pos (match-end 0)))
12439 (- pos (or (match-end 8) (match-end 5))))
12440 (t 'day))))
12441 ans))
12443 (defun org-toggle-timestamp-type ()
12444 "Toggle the type (<active> or [inactive]) of a time stamp."
12445 (interactive)
12446 (when (org-at-timestamp-p t)
12447 (let ((beg (match-beginning 0)) (end (match-end 0))
12448 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12449 (save-excursion
12450 (goto-char beg)
12451 (while (re-search-forward "[][<>]" end t)
12452 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12453 t t)))
12454 (message "Timestamp is now %sactive"
12455 (if (equal (char-after beg) ?<) "" "in")))))
12457 (defun org-timestamp-change (n &optional what)
12458 "Change the date in the time stamp at point.
12459 The date will be changed by N times WHAT. WHAT can be `day', `month',
12460 `year', `minute', `second'. If WHAT is not given, the cursor position
12461 in the timestamp determines what will be changed."
12462 (let ((pos (point))
12463 with-hm inactive
12464 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12465 org-ts-what
12466 extra rem
12467 ts time time0)
12468 (if (not (org-at-timestamp-p t))
12469 (error "Not at a timestamp"))
12470 (if (and (not what) (eq org-ts-what 'bracket))
12471 (org-toggle-timestamp-type)
12472 (if (and (not what) (not (eq org-ts-what 'day))
12473 org-display-custom-times
12474 (get-text-property (point) 'display)
12475 (not (get-text-property (1- (point)) 'display)))
12476 (setq org-ts-what 'day))
12477 (setq org-ts-what (or what org-ts-what)
12478 inactive (= (char-after (match-beginning 0)) ?\[)
12479 ts (match-string 0))
12480 (replace-match "")
12481 (if (string-match
12482 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12484 (setq extra (match-string 1 ts)))
12485 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12486 (setq with-hm t))
12487 (setq time0 (org-parse-time-string ts))
12488 (when (and (eq org-ts-what 'minute)
12489 (eq current-prefix-arg nil))
12490 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12491 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12492 (setcar (cdr time0) (+ (nth 1 time0)
12493 (if (> n 0) (- rem) (- dm rem))))))
12494 (setq time
12495 (encode-time (or (car time0) 0)
12496 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12497 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12498 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12499 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12500 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12501 (nthcdr 6 time0)))
12502 (when (and (member org-ts-what '(hour minute))
12503 extra
12504 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
12505 (setq extra (org-modify-ts-extra
12506 extra
12507 (if (eq org-ts-what 'hour) 2 5)
12508 n dm)))
12509 (when (integerp org-ts-what)
12510 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12511 (if (eq what 'calendar)
12512 (let ((cal-date (org-get-date-from-calendar)))
12513 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12514 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12515 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12516 (setcar time0 (or (car time0) 0))
12517 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12518 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12519 (setq time (apply 'encode-time time0))))
12520 (setq org-last-changed-timestamp
12521 (org-insert-time-stamp time with-hm inactive nil nil extra))
12522 (org-clock-update-time-maybe)
12523 (goto-char pos)
12524 ;; Try to recenter the calendar window, if any
12525 (if (and org-calendar-follow-timestamp-change
12526 (get-buffer-window "*Calendar*" t)
12527 (memq org-ts-what '(day month year)))
12528 (org-recenter-calendar (time-to-days time))))))
12530 (defun org-modify-ts-extra (s pos n dm)
12531 "Change the different parts of the lead-time and repeat fields in timestamp."
12532 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12533 ng h m new rem)
12534 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12535 (cond
12536 ((or (org-pos-in-match-range pos 2)
12537 (org-pos-in-match-range pos 3))
12538 (setq m (string-to-number (match-string 3 s))
12539 h (string-to-number (match-string 2 s)))
12540 (if (org-pos-in-match-range pos 2)
12541 (setq h (+ h n))
12542 (setq n (* dm (org-no-warnings (signum n))))
12543 (when (not (= 0 (setq rem (% m dm))))
12544 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12545 (setq m (+ m n)))
12546 (if (< m 0) (setq m (+ m 60) h (1- h)))
12547 (if (> m 59) (setq m (- m 60) h (1+ h)))
12548 (setq h (min 24 (max 0 h)))
12549 (setq ng 1 new (format "-%02d:%02d" h m)))
12550 ((org-pos-in-match-range pos 6)
12551 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12552 ((org-pos-in-match-range pos 5)
12553 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12555 ((org-pos-in-match-range pos 9)
12556 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12557 ((org-pos-in-match-range pos 8)
12558 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12560 (when ng
12561 (setq s (concat
12562 (substring s 0 (match-beginning ng))
12564 (substring s (match-end ng))))))
12567 (defun org-recenter-calendar (date)
12568 "If the calendar is visible, recenter it to DATE."
12569 (let* ((win (selected-window))
12570 (cwin (get-buffer-window "*Calendar*" t))
12571 (calendar-move-hook nil))
12572 (when cwin
12573 (select-window cwin)
12574 (calendar-goto-date (if (listp date) date
12575 (calendar-gregorian-from-absolute date)))
12576 (select-window win))))
12578 (defun org-goto-calendar (&optional arg)
12579 "Go to the Emacs calendar at the current date.
12580 If there is a time stamp in the current line, go to that date.
12581 A prefix ARG can be used to force the current date."
12582 (interactive "P")
12583 (let ((tsr org-ts-regexp) diff
12584 (calendar-move-hook nil)
12585 (calendar-view-holidays-initially-flag nil)
12586 (view-calendar-holidays-initially nil)
12587 (calendar-view-diary-initially-flag nil)
12588 (view-diary-entries-initially nil))
12589 (if (or (org-at-timestamp-p)
12590 (save-excursion
12591 (beginning-of-line 1)
12592 (looking-at (concat ".*" tsr))))
12593 (let ((d1 (time-to-days (current-time)))
12594 (d2 (time-to-days
12595 (org-time-string-to-time (match-string 1)))))
12596 (setq diff (- d2 d1))))
12597 (calendar)
12598 (calendar-goto-today)
12599 (if (and diff (not arg)) (calendar-forward-day diff))))
12601 (defun org-get-date-from-calendar ()
12602 "Return a list (month day year) of date at point in calendar."
12603 (with-current-buffer "*Calendar*"
12604 (save-match-data
12605 (calendar-cursor-to-date))))
12607 (defun org-date-from-calendar ()
12608 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12609 If there is already a time stamp at the cursor position, update it."
12610 (interactive)
12611 (if (org-at-timestamp-p t)
12612 (org-timestamp-change 0 'calendar)
12613 (let ((cal-date (org-get-date-from-calendar)))
12614 (org-insert-time-stamp
12615 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12617 (defun org-minutes-to-hh:mm-string (m)
12618 "Compute H:MM from a number of minutes."
12619 (let ((h (/ m 60)))
12620 (setq m (- m (* 60 h)))
12621 (format org-time-clocksum-format h m)))
12623 (defun org-hh:mm-string-to-minutes (s)
12624 "Convert a string H:MM to a number of minutes."
12625 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12626 (+ (* (string-to-number (match-string 1 s)) 60)
12627 (string-to-number (match-string 2 s)))
12630 ;;;; Files
12632 (defun org-save-all-org-buffers ()
12633 "Save all Org-mode buffers without user confirmation."
12634 (interactive)
12635 (message "Saving all Org-mode buffers...")
12636 (save-some-buffers t 'org-mode-p)
12637 (when (featurep 'org-id) (org-id-locations-save))
12638 (message "Saving all Org-mode buffers... done"))
12640 (defun org-revert-all-org-buffers ()
12641 "Revert all Org-mode buffers.
12642 Prompt for confirmation when there are unsaved changes.
12643 Be sure you know what you are doing before letting this function
12644 overwrite your changes.
12646 This function is useful in a setup where one tracks org files
12647 with a version control system, to revert on one machine after pulling
12648 changes from another. I believe the procedure must be like this:
12650 1. M-x org-save-all-org-buffers
12651 2. Pull changes from the other machine, resolve conflicts
12652 3. M-x org-revert-all-org-buffers"
12653 (interactive)
12654 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12655 (error "Abort"))
12656 (save-excursion
12657 (save-window-excursion
12658 (mapc
12659 (lambda (b)
12660 (when (and (with-current-buffer b (org-mode-p))
12661 (with-current-buffer b buffer-file-name))
12662 (switch-to-buffer b)
12663 (revert-buffer t 'no-confirm)))
12664 (buffer-list))
12665 (when (and (featurep 'org-id) org-id-track-globally)
12666 (org-id-locations-load)))))
12668 ;;;; Agenda files
12670 ;;;###autoload
12671 (defun org-iswitchb (&optional arg)
12672 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12673 With a prefix argument, restrict available to files.
12674 With two prefix arguments, restrict available buffers to agenda files.
12676 Due to some yet unresolved reason, the global function
12677 `iswitchb-mode' needs to be active for this function to work."
12678 (interactive "P")
12679 (require 'iswitchb)
12680 (let ((enabled iswitchb-mode) blist)
12681 (or enabled (iswitchb-mode 1))
12682 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12683 ((equal arg '(16)) (org-buffer-list 'agenda))
12684 (t (org-buffer-list))))
12685 (unwind-protect
12686 (let ((iswitchb-make-buflist-hook
12687 (lambda ()
12688 (setq iswitchb-temp-buflist
12689 (mapcar 'buffer-name blist)))))
12690 (switch-to-buffer
12691 (iswitchb-read-buffer
12692 "Switch-to: " nil t))
12693 (or enabled (iswitchb-mode -1))))))
12695 ;;;###autoload
12696 (defun org-ido-switchb (&optional arg)
12697 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12698 With a prefix argument, restrict available to files.
12699 With two prefix arguments, restrict available buffers to agenda files."
12700 (interactive "P")
12701 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12702 ((equal arg '(16)) (org-buffer-list 'agenda))
12703 (t (org-buffer-list)))))
12704 (switch-to-buffer
12705 (org-ido-completing-read "Org buffer: "
12706 (mapcar 'buffer-name blist)
12707 nil t))))
12709 (defun org-buffer-list (&optional predicate exclude-tmp)
12710 "Return a list of Org buffers.
12711 PREDICATE can be `export', `files' or `agenda'.
12713 export restrict the list to Export buffers.
12714 files restrict the list to buffers visiting Org files.
12715 agenda restrict the list to buffers visiting agenda files.
12717 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12718 (let* ((bfn nil)
12719 (agenda-files (and (eq predicate 'agenda)
12720 (mapcar 'file-truename (org-agenda-files t))))
12721 (filter
12722 (cond
12723 ((eq predicate 'files)
12724 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12725 ((eq predicate 'export)
12726 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12727 ((eq predicate 'agenda)
12728 (lambda (b)
12729 (with-current-buffer b
12730 (and (eq major-mode 'org-mode)
12731 (setq bfn (buffer-file-name b))
12732 (member (file-truename bfn) agenda-files)))))
12733 (t (lambda (b) (with-current-buffer b
12734 (or (eq major-mode 'org-mode)
12735 (string-match "\*Org .*Export"
12736 (buffer-name b)))))))))
12737 (delq nil
12738 (mapcar
12739 (lambda(b)
12740 (if (and (funcall filter b)
12741 (or (not exclude-tmp)
12742 (not (string-match "tmp" (buffer-name b)))))
12744 nil))
12745 (buffer-list)))))
12747 (defun org-agenda-files (&optional unrestricted archives)
12748 "Get the list of agenda files.
12749 Optional UNRESTRICTED means return the full list even if a restriction
12750 is currently in place.
12751 When ARCHIVES is t, include all archive files hat are really being
12752 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12753 `org-agenda-archives-mode' is t."
12754 (let ((files
12755 (cond
12756 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12757 ((stringp org-agenda-files) (org-read-agenda-file-list))
12758 ((listp org-agenda-files) org-agenda-files)
12759 (t (error "Invalid value of `org-agenda-files'")))))
12760 (setq files (apply 'append
12761 (mapcar (lambda (f)
12762 (if (file-directory-p f)
12763 (directory-files
12764 f t org-agenda-file-regexp)
12765 (list f)))
12766 files)))
12767 (when org-agenda-skip-unavailable-files
12768 (setq files (delq nil
12769 (mapcar (function
12770 (lambda (file)
12771 (and (file-readable-p file) file)))
12772 files))))
12773 (when (or (eq archives t)
12774 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12775 (setq files (org-add-archive-files files)))
12776 files))
12778 (defun org-edit-agenda-file-list ()
12779 "Edit the list of agenda files.
12780 Depending on setup, this either uses customize to edit the variable
12781 `org-agenda-files', or it visits the file that is holding the list. In the
12782 latter case, the buffer is set up in a way that saving it automatically kills
12783 the buffer and restores the previous window configuration."
12784 (interactive)
12785 (if (stringp org-agenda-files)
12786 (let ((cw (current-window-configuration)))
12787 (find-file org-agenda-files)
12788 (org-set-local 'org-window-configuration cw)
12789 (org-add-hook 'after-save-hook
12790 (lambda ()
12791 (set-window-configuration
12792 (prog1 org-window-configuration
12793 (kill-buffer (current-buffer))))
12794 (org-install-agenda-files-menu)
12795 (message "New agenda file list installed"))
12796 nil 'local)
12797 (message "%s" (substitute-command-keys
12798 "Edit list and finish with \\[save-buffer]")))
12799 (customize-variable 'org-agenda-files)))
12801 (defun org-store-new-agenda-file-list (list)
12802 "Set new value for the agenda file list and save it correctly."
12803 (if (stringp org-agenda-files)
12804 (let ((f org-agenda-files) b)
12805 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12806 (with-temp-file f
12807 (insert (mapconcat 'identity list "\n") "\n")))
12808 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12809 (setq org-agenda-files list)
12810 (customize-save-variable 'org-agenda-files org-agenda-files))))
12812 (defun org-read-agenda-file-list ()
12813 "Read the list of agenda files from a file."
12814 (when (file-directory-p org-agenda-files)
12815 (error "`org-agenda-files' cannot be a single directory"))
12816 (when (stringp org-agenda-files)
12817 (with-temp-buffer
12818 (insert-file-contents org-agenda-files)
12819 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12822 ;;;###autoload
12823 (defun org-cycle-agenda-files ()
12824 "Cycle through the files in `org-agenda-files'.
12825 If the current buffer visits an agenda file, find the next one in the list.
12826 If the current buffer does not, find the first agenda file."
12827 (interactive)
12828 (let* ((fs (org-agenda-files t))
12829 (files (append fs (list (car fs))))
12830 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12831 file)
12832 (unless files (error "No agenda files"))
12833 (catch 'exit
12834 (while (setq file (pop files))
12835 (if (equal (file-truename file) tcf)
12836 (when (car files)
12837 (find-file (car files))
12838 (throw 'exit t))))
12839 (find-file (car fs)))
12840 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12842 (defun org-agenda-file-to-front (&optional to-end)
12843 "Move/add the current file to the top of the agenda file list.
12844 If the file is not present in the list, it is added to the front. If it is
12845 present, it is moved there. With optional argument TO-END, add/move to the
12846 end of the list."
12847 (interactive "P")
12848 (let ((org-agenda-skip-unavailable-files nil)
12849 (file-alist (mapcar (lambda (x)
12850 (cons (file-truename x) x))
12851 (org-agenda-files t)))
12852 (ctf (file-truename buffer-file-name))
12853 x had)
12854 (setq x (assoc ctf file-alist) had x)
12856 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12857 (if to-end
12858 (setq file-alist (append (delq x file-alist) (list x)))
12859 (setq file-alist (cons x (delq x file-alist))))
12860 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12861 (org-install-agenda-files-menu)
12862 (message "File %s to %s of agenda file list"
12863 (if had "moved" "added") (if to-end "end" "front"))))
12865 (defun org-remove-file (&optional file)
12866 "Remove current file from the list of files in variable `org-agenda-files'.
12867 These are the files which are being checked for agenda entries.
12868 Optional argument FILE means, use this file instead of the current."
12869 (interactive)
12870 (let* ((org-agenda-skip-unavailable-files nil)
12871 (file (or file buffer-file-name))
12872 (true-file (file-truename file))
12873 (afile (abbreviate-file-name file))
12874 (files (delq nil (mapcar
12875 (lambda (x)
12876 (if (equal true-file
12877 (file-truename x))
12878 nil x))
12879 (org-agenda-files t)))))
12880 (if (not (= (length files) (length (org-agenda-files t))))
12881 (progn
12882 (org-store-new-agenda-file-list files)
12883 (org-install-agenda-files-menu)
12884 (message "Removed file: %s" afile))
12885 (message "File was not in list: %s (not removed)" afile))))
12887 (defun org-file-menu-entry (file)
12888 (vector file (list 'find-file file) t))
12890 (defun org-check-agenda-file (file)
12891 "Make sure FILE exists. If not, ask user what to do."
12892 (when (not (file-exists-p file))
12893 (message "non-existent file %s. [R]emove from list or [A]bort?"
12894 (abbreviate-file-name file))
12895 (let ((r (downcase (read-char-exclusive))))
12896 (cond
12897 ((equal r ?r)
12898 (org-remove-file file)
12899 (throw 'nextfile t))
12900 (t (error "Abort"))))))
12902 (defun org-get-agenda-file-buffer (file)
12903 "Get a buffer visiting FILE. If the buffer needs to be created, add
12904 it to the list of buffers which might be released later."
12905 (let ((buf (org-find-base-buffer-visiting file)))
12906 (if buf
12907 buf ; just return it
12908 ;; Make a new buffer and remember it
12909 (setq buf (find-file-noselect file))
12910 (if buf (push buf org-agenda-new-buffers))
12911 buf)))
12913 (defun org-release-buffers (blist)
12914 "Release all buffers in list, asking the user for confirmation when needed.
12915 When a buffer is unmodified, it is just killed. When modified, it is saved
12916 \(if the user agrees) and then killed."
12917 (let (buf file)
12918 (while (setq buf (pop blist))
12919 (setq file (buffer-file-name buf))
12920 (when (and (buffer-modified-p buf)
12921 file
12922 (y-or-n-p (format "Save file %s? " file)))
12923 (with-current-buffer buf (save-buffer)))
12924 (kill-buffer buf))))
12926 (defun org-prepare-agenda-buffers (files)
12927 "Create buffers for all agenda files, protect archived trees and comments."
12928 (interactive)
12929 (let ((pa '(:org-archived t))
12930 (pc '(:org-comment t))
12931 (pall '(:org-archived t :org-comment t))
12932 (inhibit-read-only t)
12933 (rea (concat ":" org-archive-tag ":"))
12934 bmp file re)
12935 (save-excursion
12936 (save-restriction
12937 (while (setq file (pop files))
12938 (if (bufferp file)
12939 (set-buffer file)
12940 (org-check-agenda-file file)
12941 (set-buffer (org-get-agenda-file-buffer file)))
12942 (widen)
12943 (setq bmp (buffer-modified-p))
12944 (org-refresh-category-properties)
12945 (setq org-todo-keywords-for-agenda
12946 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12947 (setq org-done-keywords-for-agenda
12948 (append org-done-keywords-for-agenda org-done-keywords))
12949 (setq org-todo-keyword-alist-for-agenda
12950 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12951 (setq org-tag-alist-for-agenda
12952 (append org-tag-alist-for-agenda org-tag-alist))
12954 (save-excursion
12955 (remove-text-properties (point-min) (point-max) pall)
12956 (when org-agenda-skip-archived-trees
12957 (goto-char (point-min))
12958 (while (re-search-forward rea nil t)
12959 (if (org-on-heading-p t)
12960 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12961 (goto-char (point-min))
12962 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12963 (while (re-search-forward re nil t)
12964 (add-text-properties
12965 (match-beginning 0) (org-end-of-subtree t) pc)))
12966 (set-buffer-modified-p bmp))))
12967 (setq org-todo-keyword-alist-for-agenda
12968 (org-uniquify org-todo-keyword-alist-for-agenda)
12969 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12971 ;;;; Embedded LaTeX
12973 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12974 "Keymap for the minor `org-cdlatex-mode'.")
12976 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12977 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12978 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12979 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12980 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12982 (defvar org-cdlatex-texmathp-advice-is-done nil
12983 "Flag remembering if we have applied the advice to texmathp already.")
12985 (define-minor-mode org-cdlatex-mode
12986 "Toggle the minor `org-cdlatex-mode'.
12987 This mode supports entering LaTeX environment and math in LaTeX fragments
12988 in Org-mode.
12989 \\{org-cdlatex-mode-map}"
12990 nil " OCDL" nil
12991 (when org-cdlatex-mode (require 'cdlatex))
12992 (unless org-cdlatex-texmathp-advice-is-done
12993 (setq org-cdlatex-texmathp-advice-is-done t)
12994 (defadvice texmathp (around org-math-always-on activate)
12995 "Always return t in org-mode buffers.
12996 This is because we want to insert math symbols without dollars even outside
12997 the LaTeX math segments. If Orgmode thinks that point is actually inside
12998 an embedded LaTeX fragment, let texmathp do its job.
12999 \\[org-cdlatex-mode-map]"
13000 (interactive)
13001 (let (p)
13002 (cond
13003 ((not (org-mode-p)) ad-do-it)
13004 ((eq this-command 'cdlatex-math-symbol)
13005 (setq ad-return-value t
13006 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13008 (let ((p (org-inside-LaTeX-fragment-p)))
13009 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13010 (setq ad-return-value t
13011 texmathp-why '("Org-mode embedded math" . 0))
13012 (if p ad-do-it)))))))))
13014 (defun turn-on-org-cdlatex ()
13015 "Unconditionally turn on `org-cdlatex-mode'."
13016 (org-cdlatex-mode 1))
13018 (defun org-inside-LaTeX-fragment-p ()
13019 "Test if point is inside a LaTeX fragment.
13020 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13021 sequence appearing also before point.
13022 Even though the matchers for math are configurable, this function assumes
13023 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13024 delimiters are skipped when they have been removed by customization.
13025 The return value is nil, or a cons cell with the delimiter and
13026 and the position of this delimiter.
13028 This function does a reasonably good job, but can locally be fooled by
13029 for example currency specifications. For example it will assume being in
13030 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13031 fragments that are properly closed, but during editing, we have to live
13032 with the uncertainty caused by missing closing delimiters. This function
13033 looks only before point, not after."
13034 (catch 'exit
13035 (let ((pos (point))
13036 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13037 (lim (progn
13038 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13039 (point)))
13040 dd-on str (start 0) m re)
13041 (goto-char pos)
13042 (when dodollar
13043 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13044 re (nth 1 (assoc "$" org-latex-regexps)))
13045 (while (string-match re str start)
13046 (cond
13047 ((= (match-end 0) (length str))
13048 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13049 ((= (match-end 0) (- (length str) 5))
13050 (throw 'exit nil))
13051 (t (setq start (match-end 0))))))
13052 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13053 (goto-char pos)
13054 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13055 (and (match-beginning 2) (throw 'exit nil))
13056 ;; count $$
13057 (while (re-search-backward "\\$\\$" lim t)
13058 (setq dd-on (not dd-on)))
13059 (goto-char pos)
13060 (if dd-on (cons "$$" m))))))
13063 (defun org-try-cdlatex-tab ()
13064 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13065 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13066 - inside a LaTeX fragment, or
13067 - after the first word in a line, where an abbreviation expansion could
13068 insert a LaTeX environment."
13069 (when org-cdlatex-mode
13070 (cond
13071 ((save-excursion
13072 (skip-chars-backward "a-zA-Z0-9*")
13073 (skip-chars-backward " \t")
13074 (bolp))
13075 (cdlatex-tab) t)
13076 ((org-inside-LaTeX-fragment-p)
13077 (cdlatex-tab) t)
13078 (t nil))))
13080 (defun org-cdlatex-underscore-caret (&optional arg)
13081 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13082 Revert to the normal definition outside of these fragments."
13083 (interactive "P")
13084 (if (org-inside-LaTeX-fragment-p)
13085 (call-interactively 'cdlatex-sub-superscript)
13086 (let (org-cdlatex-mode)
13087 (call-interactively (key-binding (vector last-input-event))))))
13089 (defun org-cdlatex-math-modify (&optional arg)
13090 "Execute `cdlatex-math-modify' in LaTeX fragments.
13091 Revert to the normal definition outside of these fragments."
13092 (interactive "P")
13093 (if (org-inside-LaTeX-fragment-p)
13094 (call-interactively 'cdlatex-math-modify)
13095 (let (org-cdlatex-mode)
13096 (call-interactively (key-binding (vector last-input-event))))))
13098 (defvar org-latex-fragment-image-overlays nil
13099 "List of overlays carrying the images of latex fragments.")
13100 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13102 (defun org-remove-latex-fragment-image-overlays ()
13103 "Remove all overlays with LaTeX fragment images in current buffer."
13104 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13105 (setq org-latex-fragment-image-overlays nil))
13107 (defun org-preview-latex-fragment (&optional subtree)
13108 "Preview the LaTeX fragment at point, or all locally or globally.
13109 If the cursor is in a LaTeX fragment, create the image and overlay
13110 it over the source code. If there is no fragment at point, display
13111 all fragments in the current text, from one headline to the next. With
13112 prefix SUBTREE, display all fragments in the current subtree. With a
13113 double prefix `C-u C-u', or when the cursor is before the first headline,
13114 display all fragments in the buffer.
13115 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13116 (interactive "P")
13117 (org-remove-latex-fragment-image-overlays)
13118 (save-excursion
13119 (save-restriction
13120 (let (beg end at msg)
13121 (cond
13122 ((or (equal subtree '(16))
13123 (not (save-excursion
13124 (re-search-backward (concat "^" outline-regexp) nil t))))
13125 (setq beg (point-min) end (point-max)
13126 msg "Creating images for buffer...%s"))
13127 ((equal subtree '(4))
13128 (org-back-to-heading)
13129 (setq beg (point) end (org-end-of-subtree t)
13130 msg "Creating images for subtree...%s"))
13132 (if (setq at (org-inside-LaTeX-fragment-p))
13133 (goto-char (max (point-min) (- (cdr at) 2)))
13134 (org-back-to-heading))
13135 (setq beg (point) end (progn (outline-next-heading) (point))
13136 msg (if at "Creating image...%s"
13137 "Creating images for entry...%s"))))
13138 (message msg "")
13139 (narrow-to-region beg end)
13140 (goto-char beg)
13141 (org-format-latex
13142 (concat "ltxpng/" (file-name-sans-extension
13143 (file-name-nondirectory
13144 buffer-file-name)))
13145 default-directory 'overlays msg at 'forbuffer)
13146 (message msg "done. Use `C-c C-c' to remove images.")))))
13148 (defvar org-latex-regexps
13149 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13150 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13151 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13152 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13153 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13154 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13155 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13156 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13157 "Regular expressions for matching embedded LaTeX.")
13159 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13160 "Replace LaTeX fragments with links to an image, and produce images."
13161 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13162 (let* ((prefixnodir (file-name-nondirectory prefix))
13163 (absprefix (expand-file-name prefix dir))
13164 (todir (file-name-directory absprefix))
13165 (opt org-format-latex-options)
13166 (matchers (plist-get opt :matchers))
13167 (re-list org-latex-regexps)
13168 (cnt 0) txt link beg end re e checkdir
13169 m n block linkfile movefile ov)
13170 ;; Check if there are old images files with this prefix, and remove them
13171 (when (file-directory-p todir)
13172 (mapc 'delete-file
13173 (directory-files
13174 todir 'full
13175 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13176 ;; Check the different regular expressions
13177 (while (setq e (pop re-list))
13178 (setq m (car e) re (nth 1 e) n (nth 2 e)
13179 block (if (nth 3 e) "\n\n" ""))
13180 (when (member m matchers)
13181 (goto-char (point-min))
13182 (while (re-search-forward re nil t)
13183 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13184 (not (get-text-property (match-beginning n)
13185 'org-protected)))
13186 (setq txt (match-string n)
13187 beg (match-beginning n) end (match-end n)
13188 cnt (1+ cnt)
13189 linkfile (format "%s_%04d.png" prefix cnt)
13190 movefile (format "%s_%04d.png" absprefix cnt)
13191 link (concat block "[[file:" linkfile "]]" block))
13192 (if msg (message msg cnt))
13193 (goto-char beg)
13194 (unless checkdir ; make sure the directory exists
13195 (setq checkdir t)
13196 (or (file-directory-p todir) (make-directory todir)))
13197 (org-create-formula-image
13198 txt movefile opt forbuffer)
13199 (if overlays
13200 (progn
13201 (setq ov (org-make-overlay beg end))
13202 (if (featurep 'xemacs)
13203 (progn
13204 (org-overlay-put ov 'invisible t)
13205 (org-overlay-put
13206 ov 'end-glyph
13207 (make-glyph (vector 'png :file movefile))))
13208 (org-overlay-put
13209 ov 'display
13210 (list 'image :type 'png :file movefile :ascent 'center)))
13211 (push ov org-latex-fragment-image-overlays)
13212 (goto-char end))
13213 (delete-region beg end)
13214 (insert link))))))))
13216 ;; This function borrows from Ganesh Swami's latex2png.el
13217 (defun org-create-formula-image (string tofile options buffer)
13218 (let* ((tmpdir (if (featurep 'xemacs)
13219 (temp-directory)
13220 temporary-file-directory))
13221 (texfilebase (make-temp-name
13222 (expand-file-name "orgtex" tmpdir)))
13223 (texfile (concat texfilebase ".tex"))
13224 (dvifile (concat texfilebase ".dvi"))
13225 (pngfile (concat texfilebase ".png"))
13226 (fnh (if (featurep 'xemacs)
13227 (font-height (get-face-font 'default))
13228 (face-attribute 'default :height nil)))
13229 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13230 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13231 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13232 "Black"))
13233 (bg (or (plist-get options (if buffer :background :html-background))
13234 "Transparent")))
13235 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13236 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13237 (with-temp-file texfile
13238 (insert org-format-latex-header
13239 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13240 (let ((dir default-directory))
13241 (condition-case nil
13242 (progn
13243 (cd tmpdir)
13244 (call-process "latex" nil nil nil texfile))
13245 (error nil))
13246 (cd dir))
13247 (if (not (file-exists-p dvifile))
13248 (progn (message "Failed to create dvi file from %s" texfile) nil)
13249 (condition-case nil
13250 (call-process "dvipng" nil nil nil
13251 "-E" "-fg" fg "-bg" bg
13252 "-D" dpi
13253 ;;"-x" scale "-y" scale
13254 "-T" "tight"
13255 "-o" pngfile
13256 dvifile)
13257 (error nil))
13258 (if (not (file-exists-p pngfile))
13259 (progn (message "Failed to create png file from %s" texfile) nil)
13260 ;; Use the requested file name and clean up
13261 (copy-file pngfile tofile 'replace)
13262 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13263 (delete-file (concat texfilebase e)))
13264 pngfile))))
13266 (defun org-dvipng-color (attr)
13267 "Return an rgb color specification for dvipng."
13268 (apply 'format "rgb %s %s %s"
13269 (mapcar 'org-normalize-color
13270 (color-values (face-attribute 'default attr nil)))))
13272 (defun org-normalize-color (value)
13273 "Return string to be used as color value for an RGB component."
13274 (format "%g" (/ value 65535.0)))
13276 ;;;; Key bindings
13278 ;; Make `C-c C-x' a prefix key
13279 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13281 ;; TAB key with modifiers
13282 (org-defkey org-mode-map "\C-i" 'org-cycle)
13283 (org-defkey org-mode-map [(tab)] 'org-cycle)
13284 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13285 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13286 (org-defkey org-mode-map "\M-\t" 'org-complete)
13287 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13288 ;; The following line is necessary under Suse GNU/Linux
13289 (unless (featurep 'xemacs)
13290 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13291 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13292 (define-key org-mode-map [backtab] 'org-shifttab)
13294 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13295 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13296 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13298 ;; Cursor keys with modifiers
13299 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13300 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13301 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13302 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13304 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13305 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13306 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13307 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13309 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13310 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13311 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13312 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13314 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13315 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13317 ;;; Extra keys for tty access.
13318 ;; We only set them when really needed because otherwise the
13319 ;; menus don't show the simple keys
13321 (when (or org-use-extra-keys
13322 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13323 (not window-system))
13324 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13325 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13326 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13327 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13328 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13329 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13330 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13331 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13332 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13333 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13334 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13335 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13336 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13337 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13338 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13339 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13340 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13341 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13342 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13343 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13344 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13345 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13347 ;; All the other keys
13349 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13350 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13351 (if (boundp 'narrow-map)
13352 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13353 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13354 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13355 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13356 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13357 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13358 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13359 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13360 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13361 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13362 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13363 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13364 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13365 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13366 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13367 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13368 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13369 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13370 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13371 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13372 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13373 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13374 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13375 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13376 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13377 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13378 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13379 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13380 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13381 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13382 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13383 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13384 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13385 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13386 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13387 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13388 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13389 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13390 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13391 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13392 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13393 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13394 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13395 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13396 (org-defkey org-mode-map "\C-c^" 'org-sort)
13397 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13398 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13399 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13400 (org-defkey org-mode-map "\C-m" 'org-return)
13401 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13402 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13403 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13404 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13405 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13406 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13407 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13408 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13409 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13410 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13411 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13412 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13413 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13414 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13415 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13416 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13417 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13419 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13420 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13421 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13422 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13424 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13425 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13426 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13427 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13428 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13429 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13430 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13431 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13432 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13433 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13434 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13435 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13436 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13438 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13439 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13440 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13441 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13443 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13445 (define-key org-mode-map "\C-c\C-xr" 'org-reload)
13447 (when (featurep 'xemacs)
13448 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13451 (defvar org-self-insert-command-undo-counter 0)
13453 (defvar org-table-auto-blank-field) ; defined in org-table.el
13454 (defun org-self-insert-command (N)
13455 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13456 If the cursor is in a table looking at whitespace, the whitespace is
13457 overwritten, and the table is not marked as requiring realignment."
13458 (interactive "p")
13459 (if (and
13460 (org-table-p)
13461 (progn
13462 ;; check if we blank the field, and if that triggers align
13463 (and (featurep 'org-table) org-table-auto-blank-field
13464 (member last-command
13465 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13466 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13467 ;; got extra space, this field does not determine column width
13468 (let (org-table-may-need-update) (org-table-blank-field))
13469 ;; no extra space, this field may determine column width
13470 (org-table-blank-field)))
13472 (eq N 1)
13473 (looking-at "[^|\n]* |"))
13474 (let (org-table-may-need-update)
13475 (goto-char (1- (match-end 0)))
13476 (delete-backward-char 1)
13477 (goto-char (match-beginning 0))
13478 (self-insert-command N))
13479 (setq org-table-may-need-update t)
13480 (self-insert-command N)
13481 (org-fix-tags-on-the-fly)
13482 (if org-self-insert-cluster-for-undo
13483 (if (not (eq last-command 'org-self-insert-command))
13484 (setq org-self-insert-command-undo-counter 1)
13485 (if (>= org-self-insert-command-undo-counter 20)
13486 (setq org-self-insert-command-undo-counter 1)
13487 (and (> org-self-insert-command-undo-counter 0)
13488 buffer-undo-list
13489 (not (cadr buffer-undo-list)) ; remove nil entry
13490 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13491 (setq org-self-insert-command-undo-counter
13492 (1+ org-self-insert-command-undo-counter)))))))
13494 (defun org-fix-tags-on-the-fly ()
13495 (when (and (equal (char-after (point-at-bol)) ?*)
13496 (org-on-heading-p))
13497 (org-align-tags-here org-tags-column)))
13499 (defun org-delete-backward-char (N)
13500 "Like `delete-backward-char', insert whitespace at field end in tables.
13501 When deleting backwards, in tables this function will insert whitespace in
13502 front of the next \"|\" separator, to keep the table aligned. The table will
13503 still be marked for re-alignment if the field did fill the entire column,
13504 because, in this case the deletion might narrow the column."
13505 (interactive "p")
13506 (if (and (org-table-p)
13507 (eq N 1)
13508 (string-match "|" (buffer-substring (point-at-bol) (point)))
13509 (looking-at ".*?|"))
13510 (let ((pos (point))
13511 (noalign (looking-at "[^|\n\r]* |"))
13512 (c org-table-may-need-update))
13513 (backward-delete-char N)
13514 (skip-chars-forward "^|")
13515 (insert " ")
13516 (goto-char (1- pos))
13517 ;; noalign: if there were two spaces at the end, this field
13518 ;; does not determine the width of the column.
13519 (if noalign (setq org-table-may-need-update c)))
13520 (backward-delete-char N)
13521 (org-fix-tags-on-the-fly)))
13523 (defun org-delete-char (N)
13524 "Like `delete-char', but insert whitespace at field end in tables.
13525 When deleting characters, in tables this function will insert whitespace in
13526 front of the next \"|\" separator, to keep the table aligned. The table will
13527 still be marked for re-alignment if the field did fill the entire column,
13528 because, in this case the deletion might narrow the column."
13529 (interactive "p")
13530 (if (and (org-table-p)
13531 (not (bolp))
13532 (not (= (char-after) ?|))
13533 (eq N 1))
13534 (if (looking-at ".*?|")
13535 (let ((pos (point))
13536 (noalign (looking-at "[^|\n\r]* |"))
13537 (c org-table-may-need-update))
13538 (replace-match (concat
13539 (substring (match-string 0) 1 -1)
13540 " |"))
13541 (goto-char pos)
13542 ;; noalign: if there were two spaces at the end, this field
13543 ;; does not determine the width of the column.
13544 (if noalign (setq org-table-may-need-update c)))
13545 (delete-char N))
13546 (delete-char N)
13547 (org-fix-tags-on-the-fly)))
13549 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13550 (put 'org-self-insert-command 'delete-selection t)
13551 (put 'orgtbl-self-insert-command 'delete-selection t)
13552 (put 'org-delete-char 'delete-selection 'supersede)
13553 (put 'org-delete-backward-char 'delete-selection 'supersede)
13554 (put 'org-yank 'delete-selection 'yank)
13556 ;; Make `flyspell-mode' delay after some commands
13557 (put 'org-self-insert-command 'flyspell-delayed t)
13558 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13559 (put 'org-delete-char 'flyspell-delayed t)
13560 (put 'org-delete-backward-char 'flyspell-delayed t)
13562 ;; Make pabbrev-mode expand after org-mode commands
13563 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13564 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13566 ;; How to do this: Measure non-white length of current string
13567 ;; If equal to column width, we should realign.
13569 (defun org-remap (map &rest commands)
13570 "In MAP, remap the functions given in COMMANDS.
13571 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13572 (let (new old)
13573 (while commands
13574 (setq old (pop commands) new (pop commands))
13575 (if (fboundp 'command-remapping)
13576 (org-defkey map (vector 'remap old) new)
13577 (substitute-key-definition old new map global-map)))))
13579 (when (eq org-enable-table-editor 'optimized)
13580 ;; If the user wants maximum table support, we need to hijack
13581 ;; some standard editing functions
13582 (org-remap org-mode-map
13583 'self-insert-command 'org-self-insert-command
13584 'delete-char 'org-delete-char
13585 'delete-backward-char 'org-delete-backward-char)
13586 (org-defkey org-mode-map "|" 'org-force-self-insert))
13588 (defvar org-ctrl-c-ctrl-c-hook nil
13589 "Hook for functions attaching themselves to `C-c C-c'.
13590 This can be used to add additional functionality to the C-c C-c key which
13591 executes context-dependent commands.
13592 Each function will be called with no arguments. The function must check
13593 if the context is appropriate for it to act. If yes, it should do its
13594 thing and then return a non-nil value. If the context is wrong,
13595 just do nothing.")
13597 (defvar org-metaleft-hook nil
13598 "Hook for functions attaching themselves to `M-left'.
13599 See `org-ctrl-c-ctrl-c-hook' for more information.")
13600 (defvar org-metaright-hook nil
13601 "Hook for functions attaching themselves to `M-right'.
13602 See `org-ctrl-c-ctrl-c-hook' for more information.")
13603 (defvar org-metaup-hook nil
13604 "Hook for functions attaching themselves to `M-up'.
13605 See `org-ctrl-c-ctrl-c-hook' for more information.")
13606 (defvar org-metadown-hook nil
13607 "Hook for functions attaching themselves to `M-down'.
13608 See `org-ctrl-c-ctrl-c-hook' for more information.")
13609 (defvar org-shiftmetaleft-hook nil
13610 "Hook for functions attaching themselves to `M-S-left'.
13611 See `org-ctrl-c-ctrl-c-hook' for more information.")
13612 (defvar org-shiftmetaright-hook nil
13613 "Hook for functions attaching themselves to `M-S-right'.
13614 See `org-ctrl-c-ctrl-c-hook' for more information.")
13615 (defvar org-shiftmetaup-hook nil
13616 "Hook for functions attaching themselves to `M-S-up'.
13617 See `org-ctrl-c-ctrl-c-hook' for more information.")
13618 (defvar org-shiftmetadown-hook nil
13619 "Hook for functions attaching themselves to `M-S-down'.
13620 See `org-ctrl-c-ctrl-c-hook' for more information.")
13621 (defvar org-metareturn-hook nil
13622 "Hook for functions attaching themselves to `M-RET'.
13623 See `org-ctrl-c-ctrl-c-hook' for more information.")
13625 (defun org-modifier-cursor-error ()
13626 "Throw an error, a modified cursor command was applied in wrong context."
13627 (error "This command is active in special context like tables, headlines or items"))
13629 (defun org-shiftselect-error ()
13630 "Throw an error because Shift-Cursor command was applied in wrong context."
13631 (if (and (boundp 'shift-select-mode) shift-select-mode)
13632 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13633 (error "This command works only in special context like headlines or timestamps.")))
13635 (defun org-call-for-shift-select (cmd)
13636 (let ((this-command-keys-shift-translated t))
13637 (call-interactively cmd)))
13639 (defun org-shifttab (&optional arg)
13640 "Global visibility cycling or move to previous table field.
13641 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13642 on context.
13643 See the individual commands for more information."
13644 (interactive "P")
13645 (cond
13646 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13647 ((integerp arg)
13648 (message "Content view to level: %d" arg)
13649 (org-content (prefix-numeric-value arg))
13650 (setq org-cycle-global-status 'overview))
13651 (t (call-interactively 'org-global-cycle))))
13653 (defun org-shiftmetaleft ()
13654 "Promote subtree or delete table column.
13655 Calls `org-promote-subtree', `org-outdent-item',
13656 or `org-table-delete-column', depending on context.
13657 See the individual commands for more information."
13658 (interactive)
13659 (cond
13660 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13661 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13662 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13663 ((org-at-item-p) (call-interactively 'org-outdent-item))
13664 (t (org-modifier-cursor-error))))
13666 (defun org-shiftmetaright ()
13667 "Demote subtree or insert table column.
13668 Calls `org-demote-subtree', `org-indent-item',
13669 or `org-table-insert-column', depending on context.
13670 See the individual commands for more information."
13671 (interactive)
13672 (cond
13673 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13674 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13675 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13676 ((org-at-item-p) (call-interactively 'org-indent-item))
13677 (t (org-modifier-cursor-error))))
13679 (defun org-shiftmetaup (&optional arg)
13680 "Move subtree up or kill table row.
13681 Calls `org-move-subtree-up' or `org-table-kill-row' or
13682 `org-move-item-up' depending on context. See the individual commands
13683 for more information."
13684 (interactive "P")
13685 (cond
13686 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13687 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13688 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13689 ((org-at-item-p) (call-interactively 'org-move-item-up))
13690 (t (org-modifier-cursor-error))))
13692 (defun org-shiftmetadown (&optional arg)
13693 "Move subtree down or insert table row.
13694 Calls `org-move-subtree-down' or `org-table-insert-row' or
13695 `org-move-item-down', depending on context. See the individual
13696 commands for more information."
13697 (interactive "P")
13698 (cond
13699 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13700 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13701 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13702 ((org-at-item-p) (call-interactively 'org-move-item-down))
13703 (t (org-modifier-cursor-error))))
13705 (defun org-metaleft (&optional arg)
13706 "Promote heading or move table column to left.
13707 Calls `org-do-promote' or `org-table-move-column', depending on context.
13708 With no specific context, calls the Emacs default `backward-word'.
13709 See the individual commands for more information."
13710 (interactive "P")
13711 (cond
13712 ((run-hook-with-args-until-success 'org-metaleft-hook))
13713 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13714 ((or (org-on-heading-p)
13715 (and (org-region-active-p)
13716 (save-excursion
13717 (goto-char (region-beginning))
13718 (org-on-heading-p))))
13719 (call-interactively 'org-do-promote))
13720 ((or (org-at-item-p)
13721 (and (org-region-active-p)
13722 (save-excursion
13723 (goto-char (region-beginning))
13724 (org-at-item-p))))
13725 (call-interactively 'org-outdent-item))
13726 (t (call-interactively 'backward-word))))
13728 (defun org-metaright (&optional arg)
13729 "Demote subtree or move table column to right.
13730 Calls `org-do-demote' or `org-table-move-column', depending on context.
13731 With no specific context, calls the Emacs default `forward-word'.
13732 See the individual commands for more information."
13733 (interactive "P")
13734 (cond
13735 ((run-hook-with-args-until-success 'org-metaright-hook))
13736 ((org-at-table-p) (call-interactively 'org-table-move-column))
13737 ((or (org-on-heading-p)
13738 (and (org-region-active-p)
13739 (save-excursion
13740 (goto-char (region-beginning))
13741 (org-on-heading-p))))
13742 (call-interactively 'org-do-demote))
13743 ((or (org-at-item-p)
13744 (and (org-region-active-p)
13745 (save-excursion
13746 (goto-char (region-beginning))
13747 (org-at-item-p))))
13748 (call-interactively 'org-indent-item))
13749 (t (call-interactively 'forward-word))))
13751 (defun org-metaup (&optional arg)
13752 "Move subtree up or move table row up.
13753 Calls `org-move-subtree-up' or `org-table-move-row' or
13754 `org-move-item-up', depending on context. See the individual commands
13755 for more information."
13756 (interactive "P")
13757 (cond
13758 ((run-hook-with-args-until-success 'org-metaup-hook))
13759 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13760 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13761 ((org-at-item-p) (call-interactively 'org-move-item-up))
13762 (t (transpose-lines 1) (beginning-of-line -1))))
13764 (defun org-metadown (&optional arg)
13765 "Move subtree down or move table row down.
13766 Calls `org-move-subtree-down' or `org-table-move-row' or
13767 `org-move-item-down', depending on context. See the individual
13768 commands for more information."
13769 (interactive "P")
13770 (cond
13771 ((run-hook-with-args-until-success 'org-metadown-hook))
13772 ((org-at-table-p) (call-interactively 'org-table-move-row))
13773 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13774 ((org-at-item-p) (call-interactively 'org-move-item-down))
13775 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13777 (defun org-shiftup (&optional arg)
13778 "Increase item in timestamp or increase priority of current headline.
13779 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13780 depending on context. See the individual commands for more information."
13781 (interactive "P")
13782 (cond
13783 ((and org-support-shift-select (org-region-active-p))
13784 (org-call-for-shift-select 'previous-line))
13785 ((org-at-timestamp-p t)
13786 (call-interactively (if org-edit-timestamp-down-means-later
13787 'org-timestamp-down 'org-timestamp-up)))
13788 ((and (not (eq org-support-shift-select 'always))
13789 (org-on-heading-p))
13790 (call-interactively 'org-priority-up))
13791 ((and (not org-support-shift-select) (org-at-item-p))
13792 (call-interactively 'org-previous-item))
13793 ((org-clocktable-try-shift 'up arg))
13794 (org-support-shift-select
13795 (org-call-for-shift-select 'previous-line))
13796 (t (org-shiftselect-error))))
13798 (defun org-shiftdown (&optional arg)
13799 "Decrease item in timestamp or decrease priority of current headline.
13800 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13801 depending on context. See the individual commands for more information."
13802 (interactive "P")
13803 (cond
13804 ((and org-support-shift-select (org-region-active-p))
13805 (org-call-for-shift-select 'next-line))
13806 ((org-at-timestamp-p t)
13807 (call-interactively (if org-edit-timestamp-down-means-later
13808 'org-timestamp-up 'org-timestamp-down)))
13809 ((and (not (eq org-support-shift-select 'always))
13810 (org-on-heading-p))
13811 (call-interactively 'org-priority-down))
13812 ((and (not org-support-shift-select) (org-at-item-p))
13813 (call-interactively 'org-next-item))
13814 ((org-clocktable-try-shift 'down arg))
13815 (org-support-shift-select
13816 (org-call-for-shift-select 'next-line))
13817 (t (org-shiftselect-error))))
13819 (defun org-shiftright (&optional arg)
13820 "Cycle the thing at point or in the current line, depending on context.
13821 Depending on context, this does one of the following:
13823 - switch a timestamp at point one day into the future
13824 - on a headline, switch to the next TODO keyword.
13825 - on an item, switch entire list to the next bullet type
13826 - on a property line, switch to the next allowed value
13827 - on a clocktable definition line, move time block into the future"
13828 (interactive "P")
13829 (cond
13830 ((and org-support-shift-select (org-region-active-p))
13831 (org-call-for-shift-select 'forward-char))
13832 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13833 ((and (not (eq org-support-shift-select 'always))
13834 (org-on-heading-p))
13835 (org-call-with-arg 'org-todo 'right))
13836 ((or (and org-support-shift-select
13837 (not (eq org-support-shift-select 'always))
13838 (org-at-item-bullet-p))
13839 (and (not org-support-shift-select) (org-at-item-p)))
13840 (org-call-with-arg 'org-cycle-list-bullet nil))
13841 ((and (not (eq org-support-shift-select 'always))
13842 (org-at-property-p))
13843 (call-interactively 'org-property-next-allowed-value))
13844 ((org-clocktable-try-shift 'right arg))
13845 (org-support-shift-select
13846 (org-call-for-shift-select 'forward-char))
13847 (t (org-shiftselect-error))))
13849 (defun org-shiftleft (&optional arg)
13850 "Cycle the thing at point or in the current line, depending on context.
13851 Depending on context, this does one of the following:
13853 - switch a timestamp at point one day into the past
13854 - on a headline, switch to the previous TODO keyword.
13855 - on an item, switch entire list to the previous bullet type
13856 - on a property line, switch to the previous allowed value
13857 - on a clocktable definition line, move time block into the past"
13858 (interactive "P")
13859 (cond
13860 ((and org-support-shift-select (org-region-active-p))
13861 (org-call-for-shift-select 'backward-char))
13862 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13863 ((and (not (eq org-support-shift-select 'always))
13864 (org-on-heading-p))
13865 (org-call-with-arg 'org-todo 'left))
13866 ((or (and org-support-shift-select
13867 (not (eq org-support-shift-select 'always))
13868 (org-at-item-bullet-p))
13869 (and (not org-support-shift-select) (org-at-item-p)))
13870 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13871 ((and (not (eq org-support-shift-select 'always))
13872 (org-at-property-p))
13873 (call-interactively 'org-property-previous-allowed-value))
13874 ((org-clocktable-try-shift 'left arg))
13875 (org-support-shift-select
13876 (org-call-for-shift-select 'backward-char))
13877 (t (org-shiftselect-error))))
13879 (defun org-shiftcontrolright ()
13880 "Switch to next TODO set."
13881 (interactive)
13882 (cond
13883 ((and org-support-shift-select (org-region-active-p))
13884 (org-call-for-shift-select 'forward-word))
13885 ((and (not (eq org-support-shift-select 'always))
13886 (org-on-heading-p))
13887 (org-call-with-arg 'org-todo 'nextset))
13888 (org-support-shift-select
13889 (org-call-for-shift-select 'forward-word))
13890 (t (org-shiftselect-error))))
13892 (defun org-shiftcontrolleft ()
13893 "Switch to previous TODO set."
13894 (interactive)
13895 (cond
13896 ((and org-support-shift-select (org-region-active-p))
13897 (org-call-for-shift-select 'backward-word))
13898 ((and (not (eq org-support-shift-select 'always))
13899 (org-on-heading-p))
13900 (org-call-with-arg 'org-todo 'previousset))
13901 (org-support-shift-select
13902 (org-call-for-shift-select 'backward-word))
13903 (t (org-shiftselect-error))))
13905 (defun org-ctrl-c-ret ()
13906 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13907 (interactive)
13908 (cond
13909 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13910 (t (call-interactively 'org-insert-heading))))
13912 (defun org-copy-special ()
13913 "Copy region in table or copy current subtree.
13914 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13915 See the individual commands for more information."
13916 (interactive)
13917 (call-interactively
13918 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13920 (defun org-cut-special ()
13921 "Cut region in table or cut current subtree.
13922 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13923 See the individual commands for more information."
13924 (interactive)
13925 (call-interactively
13926 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13928 (defun org-paste-special (arg)
13929 "Paste rectangular region into table, or past subtree relative to level.
13930 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13931 See the individual commands for more information."
13932 (interactive "P")
13933 (if (org-at-table-p)
13934 (org-table-paste-rectangle)
13935 (org-paste-subtree arg)))
13937 (defun org-edit-special ()
13938 "Call a special editor for the stuff at point.
13939 When at a table, call the formula editor with `org-table-edit-formulas'.
13940 When at the first line of an src example, call `org-edit-src-code'.
13941 When in an #+include line, visit the include file. Otherwise call
13942 `ffap' to visit the file at point."
13943 (interactive)
13944 (cond
13945 ((org-at-table-p)
13946 (call-interactively 'org-table-edit-formulas))
13947 ((save-excursion
13948 (beginning-of-line 1)
13949 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13950 (find-file (org-trim (match-string 1))))
13951 ((org-edit-src-code))
13952 ((org-edit-fixed-width-region))
13953 (t (call-interactively 'ffap))))
13956 (defun org-ctrl-c-ctrl-c (&optional arg)
13957 "Set tags in headline, or update according to changed information at point.
13959 This command does many different things, depending on context:
13961 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
13962 this is what we do.
13964 - If the cursor is in a headline, prompt for tags and insert them
13965 into the current line, aligned to `org-tags-column'. When called
13966 with prefix arg, realign all tags in the current buffer.
13968 - If the cursor is in one of the special #+KEYWORD lines, this
13969 triggers scanning the buffer for these lines and updating the
13970 information.
13972 - If the cursor is inside a table, realign the table. This command
13973 works even if the automatic table editor has been turned off.
13975 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13976 the entire table.
13978 - If the cursor is at a footnote reference or definition, jump to
13979 the corresponding definition or references, respectively.
13981 - If the cursor is a the beginning of a dynamic block, update it.
13983 - If the cursor is inside a table created by the table.el package,
13984 activate that table.
13986 - If the current buffer is a remember buffer, close note and file
13987 it. A prefix argument of 1 files to the default location
13988 without further interaction. A prefix argument of 2 files to
13989 the currently clocking task.
13991 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13992 links in this buffer.
13994 - If the cursor is on a numbered item in a plain list, renumber the
13995 ordered list.
13997 - If the cursor is on a checkbox, toggle it."
13998 (interactive "P")
13999 (let ((org-enable-table-editor t))
14000 (cond
14001 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14002 org-occur-highlights
14003 org-latex-fragment-image-overlays)
14004 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14005 (org-remove-occur-highlights)
14006 (org-remove-latex-fragment-image-overlays)
14007 (message "Temporary highlights/overlays removed from current buffer"))
14008 ((and (local-variable-p 'org-finish-function (current-buffer))
14009 (fboundp org-finish-function))
14010 (funcall org-finish-function))
14011 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14012 ((org-at-property-p)
14013 (call-interactively 'org-property-action))
14014 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14015 ((org-on-heading-p) (call-interactively 'org-set-tags))
14016 ((org-at-table.el-p)
14017 (require 'table)
14018 (beginning-of-line 1)
14019 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14020 (call-interactively 'table-recognize-table))
14021 ((org-at-table-p)
14022 (org-table-maybe-eval-formula)
14023 (if arg
14024 (call-interactively 'org-table-recalculate)
14025 (org-table-maybe-recalculate-line))
14026 (call-interactively 'org-table-align))
14027 ((or (org-footnote-at-reference-p)
14028 (org-footnote-at-definition-p))
14029 (call-interactively 'org-footnote-action))
14030 ((org-at-item-checkbox-p)
14031 (call-interactively 'org-toggle-checkbox))
14032 ((org-at-item-p)
14033 (if arg
14034 (call-interactively 'org-toggle-checkbox)
14035 (call-interactively 'org-maybe-renumber-ordered-list)))
14036 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14037 ;; Dynamic block
14038 (beginning-of-line 1)
14039 (save-excursion (org-update-dblock)))
14040 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14041 (cond
14042 ((equal (match-string 1) "TBLFM")
14043 ;; Recalculate the table before this line
14044 (save-excursion
14045 (beginning-of-line 1)
14046 (skip-chars-backward " \r\n\t")
14047 (if (org-at-table-p)
14048 (org-call-with-arg 'org-table-recalculate t))))
14050 ; (org-set-regexps-and-options)
14051 ; (org-restart-font-lock)
14052 (let ((org-inhibit-startup t)) (org-mode-restart))
14053 (message "Local setup has been refreshed"))))
14054 (t (error "C-c C-c can do nothing useful at this location.")))))
14056 (defun org-mode-restart ()
14057 "Restart Org-mode, to scan again for special lines.
14058 Also updates the keyword regular expressions."
14059 (interactive)
14060 (org-mode)
14061 (message "Org-mode restarted"))
14063 (defun org-kill-note-or-show-branches ()
14064 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14065 (interactive)
14066 (if (not org-finish-function)
14067 (call-interactively 'show-branches)
14068 (let ((org-note-abort t))
14069 (funcall org-finish-function))))
14071 (defun org-return (&optional indent)
14072 "Goto next table row or insert a newline.
14073 Calls `org-table-next-row' or `newline', depending on context.
14074 See the individual commands for more information."
14075 (interactive)
14076 (cond
14077 ((bobp) (if indent (newline-and-indent) (newline)))
14078 ((org-at-table-p)
14079 (org-table-justify-field-maybe)
14080 (call-interactively 'org-table-next-row))
14081 ((and org-return-follows-link
14082 (eq (get-text-property (point) 'face) 'org-link))
14083 (call-interactively 'org-open-at-point))
14084 ((and (org-at-heading-p)
14085 (looking-at
14086 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14087 (org-show-entry)
14088 (end-of-line 1)
14089 (newline))
14090 (t (if indent (newline-and-indent) (newline)))))
14092 (defun org-return-indent ()
14093 "Goto next table row or insert a newline and indent.
14094 Calls `org-table-next-row' or `newline-and-indent', depending on
14095 context. See the individual commands for more information."
14096 (interactive)
14097 (org-return t))
14099 (defun org-ctrl-c-star ()
14100 "Compute table, or change heading status of lines.
14101 Calls `org-table-recalculate' or `org-toggle-heading',
14102 depending on context."
14103 (interactive)
14104 (cond
14105 ((org-at-table-p)
14106 (call-interactively 'org-table-recalculate))
14108 ;; Convert all lines in region to list items
14109 (call-interactively 'org-toggle-heading))))
14111 (defun org-ctrl-c-minus ()
14112 "Insert separator line in table or modify bullet status of line.
14113 Also turns a plain line or a region of lines into list items.
14114 Calls `org-table-insert-hline', `org-toggle-item', or
14115 `org-cycle-list-bullet', depending on context."
14116 (interactive)
14117 (cond
14118 ((org-at-table-p)
14119 (call-interactively 'org-table-insert-hline))
14120 ((org-region-active-p)
14121 (call-interactively 'org-toggle-item))
14122 ((org-in-item-p)
14123 (call-interactively 'org-cycle-list-bullet))
14125 (call-interactively 'org-toggle-item))))
14127 (defun org-toggle-item ()
14128 "Convert headings or normal lines to items, items to normal lines.
14129 If there is no active region, only the current line is considered.
14131 If the first line in the region is a headline, convert all headlines to items.
14133 If the first line in the region is an item, convert all items to normal lines.
14135 If the first line is normal text, add an item bullet to each line."
14136 (interactive)
14137 (let (l2 l beg end)
14138 (if (org-region-active-p)
14139 (setq beg (region-beginning) end (region-end))
14140 (setq beg (point-at-bol)
14141 end (min (1+ (point-at-eol)) (point-max))))
14142 (save-excursion
14143 (goto-char end)
14144 (setq l2 (org-current-line))
14145 (goto-char beg)
14146 (beginning-of-line 1)
14147 (setq l (1- (org-current-line)))
14148 (if (org-at-item-p)
14149 ;; We already have items, de-itemize
14150 (while (< (setq l (1+ l)) l2)
14151 (when (org-at-item-p)
14152 (goto-char (match-beginning 2))
14153 (delete-region (match-beginning 2) (match-end 2))
14154 (and (looking-at "[ \t]+") (replace-match "")))
14155 (beginning-of-line 2))
14156 (if (org-on-heading-p)
14157 ;; Headings, convert to items
14158 (while (< (setq l (1+ l)) l2)
14159 (if (looking-at org-outline-regexp)
14160 (replace-match "- " t t))
14161 (beginning-of-line 2))
14162 ;; normal lines, turn them into items
14163 (while (< (setq l (1+ l)) l2)
14164 (unless (org-at-item-p)
14165 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14166 (replace-match "\\1- \\2")))
14167 (beginning-of-line 2)))))))
14169 (defun org-toggle-heading (&optional nstars)
14170 "Convert headings to normal text, or items or text to headings.
14171 If there is no active region, only the current line is considered.
14173 If the first line is a heading, remove the stars from all headlines
14174 in the region.
14176 If the first line is a plain list item, turn all plain list items into
14177 headings.
14179 If the first line is a normal line, turn each and every line in the region
14180 into a heading.
14182 When converting a line into a heading, the number of stars is chosen
14183 such that the lines become children of the current entry. However, when
14184 a prefix argument is given, its value determines the number of stars to add."
14185 (interactive "P")
14186 (let (l2 l itemp beg end)
14187 (if (org-region-active-p)
14188 (setq beg (region-beginning) end (region-end))
14189 (setq beg (point-at-bol)
14190 end (min (1+ (point-at-eol)) (point-max))))
14191 (save-excursion
14192 (goto-char end)
14193 (setq l2 (org-current-line))
14194 (goto-char beg)
14195 (beginning-of-line 1)
14196 (setq l (1- (org-current-line)))
14197 (if (org-on-heading-p)
14198 ;; We already have headlines, de-star them
14199 (while (< (setq l (1+ l)) l2)
14200 (when (org-on-heading-p t)
14201 (and (looking-at outline-regexp) (replace-match "")))
14202 (beginning-of-line 2))
14203 (setq itemp (org-at-item-p))
14204 (let* ((stars
14205 (if nstars
14206 (make-string (prefix-numeric-value current-prefix-arg)
14208 (save-excursion
14209 (re-search-backward org-complex-heading-regexp nil t)
14210 (or (match-string 1) "*"))))
14211 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
14212 (rpl (concat stars add-stars " ")))
14213 (while (< (setq l (1+ l)) l2)
14214 (if itemp
14215 (and (org-at-item-p) (replace-match rpl t t))
14216 (unless (org-on-heading-p)
14217 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14218 (replace-match (concat rpl (match-string 2))))))
14219 (beginning-of-line 2)))))))
14221 (defun org-meta-return (&optional arg)
14222 "Insert a new heading or wrap a region in a table.
14223 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14224 See the individual commands for more information."
14225 (interactive "P")
14226 (cond
14227 ((run-hook-with-args-until-success 'org-metareturn-hook))
14228 ((org-at-table-p)
14229 (call-interactively 'org-table-wrap-region))
14230 (t (call-interactively 'org-insert-heading))))
14232 ;;; Menu entries
14234 ;; Define the Org-mode menus
14235 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14236 '("Tbl"
14237 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14238 ["Next Field" org-cycle (org-at-table-p)]
14239 ["Previous Field" org-shifttab (org-at-table-p)]
14240 ["Next Row" org-return (org-at-table-p)]
14241 "--"
14242 ["Blank Field" org-table-blank-field (org-at-table-p)]
14243 ["Edit Field" org-table-edit-field (org-at-table-p)]
14244 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14245 "--"
14246 ("Column"
14247 ["Move Column Left" org-metaleft (org-at-table-p)]
14248 ["Move Column Right" org-metaright (org-at-table-p)]
14249 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14250 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14251 ("Row"
14252 ["Move Row Up" org-metaup (org-at-table-p)]
14253 ["Move Row Down" org-metadown (org-at-table-p)]
14254 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14255 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14256 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14257 "--"
14258 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14259 ("Rectangle"
14260 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14261 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14262 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14263 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14264 "--"
14265 ("Calculate"
14266 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14267 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14268 ["Edit Formulas" org-edit-special (org-at-table-p)]
14269 "--"
14270 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14271 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14272 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14273 "--"
14274 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14275 "--"
14276 ["Sum Column/Rectangle" org-table-sum
14277 (or (org-at-table-p) (org-region-active-p))]
14278 ["Which Column?" org-table-current-column (org-at-table-p)])
14279 ["Debug Formulas"
14280 org-table-toggle-formula-debugger
14281 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14282 ["Show Col/Row Numbers"
14283 org-table-toggle-coordinate-overlays
14284 :style toggle
14285 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14286 "--"
14287 ["Create" org-table-create (and (not (org-at-table-p))
14288 org-enable-table-editor)]
14289 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14290 ["Import from File" org-table-import (not (org-at-table-p))]
14291 ["Export to File" org-table-export (org-at-table-p)]
14292 "--"
14293 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14295 (easy-menu-define org-org-menu org-mode-map "Org menu"
14296 '("Org"
14297 ("Show/Hide"
14298 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14299 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14300 ["Sparse Tree..." org-sparse-tree t]
14301 ["Reveal Context" org-reveal t]
14302 ["Show All" show-all t]
14303 "--"
14304 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14305 "--"
14306 ["New Heading" org-insert-heading t]
14307 ("Navigate Headings"
14308 ["Up" outline-up-heading t]
14309 ["Next" outline-next-visible-heading t]
14310 ["Previous" outline-previous-visible-heading t]
14311 ["Next Same Level" outline-forward-same-level t]
14312 ["Previous Same Level" outline-backward-same-level t]
14313 "--"
14314 ["Jump" org-goto t])
14315 ("Edit Structure"
14316 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14317 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14318 "--"
14319 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14320 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14321 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14322 "--"
14323 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14324 "--"
14325 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14326 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14327 ["Demote Heading" org-metaright (not (org-at-table-p))]
14328 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14329 "--"
14330 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14331 "--"
14332 ["Convert to odd levels" org-convert-to-odd-levels t]
14333 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14334 ("Editing"
14335 ["Emphasis..." org-emphasize t]
14336 ["Edit Source Example" org-edit-special t]
14337 "--"
14338 ["Footnote new/jump" org-footnote-action t]
14339 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14340 ("Archive"
14341 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14342 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14343 ; :active t :keys "C-u C-c C-x C-a"]
14344 ["Sparse trees open ARCHIVE trees"
14345 (setq org-sparse-tree-open-archived-trees
14346 (not org-sparse-tree-open-archived-trees))
14347 :style toggle :selected org-sparse-tree-open-archived-trees]
14348 ["Cycling opens ARCHIVE trees"
14349 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14350 :style toggle :selected org-cycle-open-archived-trees]
14351 "--"
14352 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14353 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14354 ; ["Check and Move Children" (org-archive-subtree '(4))
14355 ; :active t :keys "C-u C-c C-x C-s"]
14357 "--"
14358 ("TODO Lists"
14359 ["TODO/DONE/-" org-todo t]
14360 ("Select keyword"
14361 ["Next keyword" org-shiftright (org-on-heading-p)]
14362 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14363 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14364 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14365 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14366 ["Show TODO Tree" org-show-todo-tree t]
14367 ["Global TODO list" org-todo-list t]
14368 "--"
14369 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14370 :selected org-enforce-todo-dependencies :style toggle :active t]
14371 "Settings for tree at point"
14372 ["Do Children sequentially" org-toggle-ordered-property :style radio
14373 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14374 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14375 ["Do Children parallel" org-toggle-ordered-property :style radio
14376 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14377 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14378 "--"
14379 ["Set Priority" org-priority t]
14380 ["Priority Up" org-shiftup t]
14381 ["Priority Down" org-shiftdown t])
14382 ("TAGS and Properties"
14383 ["Set Tags" org-set-tags-command t]
14384 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14385 "--"
14386 ["Set property" org-set-property t]
14387 ["Column view of properties" org-columns t]
14388 ["Insert Column View DBlock" org-insert-columns-dblock t])
14389 ("Dates and Scheduling"
14390 ["Timestamp" org-time-stamp t]
14391 ["Timestamp (inactive)" org-time-stamp-inactive t]
14392 ("Change Date"
14393 ["1 Day Later" org-shiftright t]
14394 ["1 Day Earlier" org-shiftleft t]
14395 ["1 ... Later" org-shiftup t]
14396 ["1 ... Earlier" org-shiftdown t])
14397 ["Compute Time Range" org-evaluate-time-range t]
14398 ["Schedule Item" org-schedule t]
14399 ["Deadline" org-deadline t]
14400 "--"
14401 ["Custom time format" org-toggle-time-stamp-overlays
14402 :style radio :selected org-display-custom-times]
14403 "--"
14404 ["Goto Calendar" org-goto-calendar t]
14405 ["Date from Calendar" org-date-from-calendar t]
14406 "--"
14407 ["Start/Restart Timer" org-timer-start t]
14408 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14409 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14410 ["Insert Timer String" org-timer t]
14411 ["Insert Timer Item" org-timer-item t])
14412 ("Logging work"
14413 ["Clock in" org-clock-in t]
14414 ["Clock out" org-clock-out t]
14415 ["Clock cancel" org-clock-cancel t]
14416 ["Goto running clock" org-clock-goto t]
14417 ["Display times" org-clock-display t]
14418 ["Create clock table" org-clock-report t]
14419 "--"
14420 ["Record DONE time"
14421 (progn (setq org-log-done (not org-log-done))
14422 (message "Switching to %s will %s record a timestamp"
14423 (car org-done-keywords)
14424 (if org-log-done "automatically" "not")))
14425 :style toggle :selected org-log-done])
14426 "--"
14427 ["Agenda Command..." org-agenda t]
14428 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14429 ("File List for Agenda")
14430 ("Special views current file"
14431 ["TODO Tree" org-show-todo-tree t]
14432 ["Check Deadlines" org-check-deadlines t]
14433 ["Timeline" org-timeline t]
14434 ["Tags/Property tree" org-match-sparse-tree t])
14435 "--"
14436 ("Hyperlinks"
14437 ["Store Link (Global)" org-store-link t]
14438 ["Insert Link" org-insert-link t]
14439 ["Follow Link" org-open-at-point t]
14440 "--"
14441 ["Next link" org-next-link t]
14442 ["Previous link" org-previous-link t]
14443 "--"
14444 ["Descriptive Links"
14445 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14446 :style radio
14447 :selected (member '(org-link) buffer-invisibility-spec)]
14448 ["Literal Links"
14449 (progn
14450 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14451 :style radio
14452 :selected (not (member '(org-link) buffer-invisibility-spec))])
14453 "--"
14454 ["Export/Publish..." org-export t]
14455 ("LaTeX"
14456 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14457 :selected org-cdlatex-mode]
14458 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14459 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14460 ["Modify math symbol" org-cdlatex-math-modify
14461 (org-inside-LaTeX-fragment-p)]
14462 ["Export LaTeX fragments as images"
14463 (if (featurep 'org-exp)
14464 (setq org-export-with-LaTeX-fragments
14465 (not org-export-with-LaTeX-fragments))
14466 (require 'org-exp))
14467 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14468 org-export-with-LaTeX-fragments)])
14469 "--"
14470 ("Documentation"
14471 ["Show Version" org-version t]
14472 ["Info Documentation" org-info t])
14473 ("Customize"
14474 ["Browse Org Group" org-customize t]
14475 "--"
14476 ["Expand This Menu" org-create-customize-menu
14477 (fboundp 'customize-menu-create)])
14478 "--"
14479 ("Refresh/Reload"
14480 ["Refresh setup current buffer" org-mode-restart t]
14481 ["Reload Org (after update)" org-reload t]
14482 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14485 (defun org-info (&optional node)
14486 "Read documentation for Org-mode in the info system.
14487 With optional NODE, go directly to that node."
14488 (interactive)
14489 (info (format "(org)%s" (or node ""))))
14491 (defun org-install-agenda-files-menu ()
14492 (let ((bl (buffer-list)))
14493 (save-excursion
14494 (while bl
14495 (set-buffer (pop bl))
14496 (if (org-mode-p) (setq bl nil)))
14497 (when (org-mode-p)
14498 (easy-menu-change
14499 '("Org") "File List for Agenda"
14500 (append
14501 (list
14502 ["Edit File List" (org-edit-agenda-file-list) t]
14503 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14504 ["Remove Current File from List" org-remove-file t]
14505 ["Cycle through agenda files" org-cycle-agenda-files t]
14506 ["Occur in all agenda files" org-occur-in-agenda-files t]
14507 "--")
14508 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14510 ;;;; Documentation
14512 ;;;###autoload
14513 (defun org-require-autoloaded-modules ()
14514 (interactive)
14515 (mapc 'require
14516 '(org-agenda org-archive org-attach org-clock org-colview
14517 org-exp org-id org-export-latex org-publish
14518 org-remember org-table org-timer)))
14520 ;;;###autoload
14521 (defun org-reload (&optional uncompiled)
14522 "Reload all org lisp files.
14523 With prefix arg UNCOMPILED, load the uncompiled versions."
14524 (interactive "P")
14525 (require 'find-func)
14526 (let* ((dir (file-name-directory (find-library-name "org")))
14527 (files (directory-files dir t "\\.el\\'"))
14528 (remove-re (concat (if (featurep 'xemacs)
14529 "org-colview" "org-colview-xemacs")
14530 "\\'")))
14531 (setq files (mapcar 'file-name-sans-extension files))
14532 (setq files (mapcar
14533 (lambda (x) (if (string-match remove-re x) nil x))
14534 files))
14535 (setq files (delq nil files))
14536 (mapc
14537 (lambda (f)
14538 (if (and (not uncompiled)
14539 (file-exists-p (concat f ".elc")))
14540 (load (concat f ".elc") nil nil t)
14541 (load (concat f ".el") nil nil t)))
14542 files)))
14544 ;;;###autoload
14545 (defun org-customize ()
14546 "Call the customize function with org as argument."
14547 (interactive)
14548 (org-load-modules-maybe)
14549 (org-require-autoloaded-modules)
14550 (customize-browse 'org))
14552 (defun org-create-customize-menu ()
14553 "Create a full customization menu for Org-mode, insert it into the menu."
14554 (interactive)
14555 (org-load-modules-maybe)
14556 (org-require-autoloaded-modules)
14557 (if (fboundp 'customize-menu-create)
14558 (progn
14559 (easy-menu-change
14560 '("Org") "Customize"
14561 `(["Browse Org group" org-customize t]
14562 "--"
14563 ,(customize-menu-create 'org)
14564 ["Set" Custom-set t]
14565 ["Save" Custom-save t]
14566 ["Reset to Current" Custom-reset-current t]
14567 ["Reset to Saved" Custom-reset-saved t]
14568 ["Reset to Standard Settings" Custom-reset-standard t]))
14569 (message "\"Org\"-menu now contains full customization menu"))
14570 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14572 ;;;; Miscellaneous stuff
14574 ;;; Generally useful functions
14576 (defun org-find-text-property-in-string (prop s)
14577 "Return the first non-nil value of property PROP in string S."
14578 (or (get-text-property 0 prop s)
14579 (get-text-property (or (next-single-property-change 0 prop s) 0)
14580 prop s)))
14582 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14583 "Display the given MESSAGE as a warning."
14584 (if (fboundp 'display-warning)
14585 (display-warning 'org message
14586 (if (featurep 'xemacs)
14587 'warning
14588 :warning))
14589 (let ((buf (get-buffer-create "*Org warnings*")))
14590 (with-current-buffer buf
14591 (goto-char (point-max))
14592 (insert "Warning (Org): " message)
14593 (unless (bolp)
14594 (newline)))
14595 (display-buffer buf)
14596 (sit-for 0))))
14598 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14599 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14600 (if (and marker (marker-buffer marker)
14601 (buffer-live-p (marker-buffer marker)))
14602 (progn
14603 (switch-to-buffer (marker-buffer marker))
14604 (if (or (> marker (point-max)) (< marker (point-min)))
14605 (widen))
14606 (goto-char marker)
14607 (org-show-context 'org-goto))
14608 (if bookmark
14609 (bookmark-jump bookmark)
14610 (error "Cannot find location"))))
14612 (defun org-quote-csv-field (s)
14613 "Quote field for inclusion in CSV material."
14614 (if (string-match "[\",]" s)
14615 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14618 (defun org-plist-delete (plist property)
14619 "Delete PROPERTY from PLIST.
14620 This is in contrast to merely setting it to 0."
14621 (let (p)
14622 (while plist
14623 (if (not (eq property (car plist)))
14624 (setq p (plist-put p (car plist) (nth 1 plist))))
14625 (setq plist (cddr plist)))
14628 (defun org-force-self-insert (N)
14629 "Needed to enforce self-insert under remapping."
14630 (interactive "p")
14631 (self-insert-command N))
14633 (defun org-string-width (s)
14634 "Compute width of string, ignoring invisible characters.
14635 This ignores character with invisibility property `org-link', and also
14636 characters with property `org-cwidth', because these will become invisible
14637 upon the next fontification round."
14638 (let (b l)
14639 (when (or (eq t buffer-invisibility-spec)
14640 (assq 'org-link buffer-invisibility-spec))
14641 (while (setq b (text-property-any 0 (length s)
14642 'invisible 'org-link s))
14643 (setq s (concat (substring s 0 b)
14644 (substring s (or (next-single-property-change
14645 b 'invisible s) (length s)))))))
14646 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14647 (setq s (concat (substring s 0 b)
14648 (substring s (or (next-single-property-change
14649 b 'org-cwidth s) (length s))))))
14650 (setq l (string-width s) b -1)
14651 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14652 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14655 (defun org-get-indentation (&optional line)
14656 "Get the indentation of the current line, interpreting tabs.
14657 When LINE is given, assume it represents a line and compute its indentation."
14658 (if line
14659 (if (string-match "^ *" (org-remove-tabs line))
14660 (match-end 0))
14661 (save-excursion
14662 (beginning-of-line 1)
14663 (skip-chars-forward " \t")
14664 (current-column))))
14666 (defun org-remove-tabs (s &optional width)
14667 "Replace tabulators in S with spaces.
14668 Assumes that s is a single line, starting in column 0."
14669 (setq width (or width tab-width))
14670 (while (string-match "\t" s)
14671 (setq s (replace-match
14672 (make-string
14673 (- (* width (/ (+ (match-beginning 0) width) width))
14674 (match-beginning 0)) ?\ )
14675 t t s)))
14678 (defun org-fix-indentation (line ind)
14679 "Fix indentation in LINE.
14680 IND is a cons cell with target and minimum indentation.
14681 If the current indentation in LINE is smaller than the minimum,
14682 leave it alone. If it is larger than ind, set it to the target."
14683 (let* ((l (org-remove-tabs line))
14684 (i (org-get-indentation l))
14685 (i1 (car ind)) (i2 (cdr ind)))
14686 (if (>= i i2) (setq l (substring line i2)))
14687 (if (> i1 0)
14688 (concat (make-string i1 ?\ ) l)
14689 l)))
14691 (defun org-base-buffer (buffer)
14692 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14693 (if (not buffer)
14694 buffer
14695 (or (buffer-base-buffer buffer)
14696 buffer)))
14698 (defun org-trim (s)
14699 "Remove whitespace at beginning and end of string."
14700 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14701 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14704 (defun org-wrap (string &optional width lines)
14705 "Wrap string to either a number of lines, or a width in characters.
14706 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14707 that costs. If there is a word longer than WIDTH, the text is actually
14708 wrapped to the length of that word.
14709 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14710 many lines, whatever width that takes.
14711 The return value is a list of lines, without newlines at the end."
14712 (let* ((words (org-split-string string "[ \t\n]+"))
14713 (maxword (apply 'max (mapcar 'org-string-width words)))
14714 w ll)
14715 (cond (width
14716 (org-do-wrap words (max maxword width)))
14717 (lines
14718 (setq w maxword)
14719 (setq ll (org-do-wrap words maxword))
14720 (if (<= (length ll) lines)
14722 (setq ll words)
14723 (while (> (length ll) lines)
14724 (setq w (1+ w))
14725 (setq ll (org-do-wrap words w)))
14726 ll))
14727 (t (error "Cannot wrap this")))))
14729 (defun org-do-wrap (words width)
14730 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14731 (let (lines line)
14732 (while words
14733 (setq line (pop words))
14734 (while (and words (< (+ (length line) (length (car words))) width))
14735 (setq line (concat line " " (pop words))))
14736 (setq lines (push line lines)))
14737 (nreverse lines)))
14739 (defun org-split-string (string &optional separators)
14740 "Splits STRING into substrings at SEPARATORS.
14741 No empty strings are returned if there are matches at the beginning
14742 and end of string."
14743 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14744 (start 0)
14745 notfirst
14746 (list nil))
14747 (while (and (string-match rexp string
14748 (if (and notfirst
14749 (= start (match-beginning 0))
14750 (< start (length string)))
14751 (1+ start) start))
14752 (< (match-beginning 0) (length string)))
14753 (setq notfirst t)
14754 (or (eq (match-beginning 0) 0)
14755 (and (eq (match-beginning 0) (match-end 0))
14756 (eq (match-beginning 0) start))
14757 (setq list
14758 (cons (substring string start (match-beginning 0))
14759 list)))
14760 (setq start (match-end 0)))
14761 (or (eq start (length string))
14762 (setq list
14763 (cons (substring string start)
14764 list)))
14765 (nreverse list)))
14767 (defun org-uuidgen-p (s)
14768 "Is S an ID created by UUIDGEN?"
14769 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
14771 (defun org-context ()
14772 "Return a list of contexts of the current cursor position.
14773 If several contexts apply, all are returned.
14774 Each context entry is a list with a symbol naming the context, and
14775 two positions indicating start and end of the context. Possible
14776 contexts are:
14778 :headline anywhere in a headline
14779 :headline-stars on the leading stars in a headline
14780 :todo-keyword on a TODO keyword (including DONE) in a headline
14781 :tags on the TAGS in a headline
14782 :priority on the priority cookie in a headline
14783 :item on the first line of a plain list item
14784 :item-bullet on the bullet/number of a plain list item
14785 :checkbox on the checkbox in a plain list item
14786 :table in an org-mode table
14787 :table-special on a special filed in a table
14788 :table-table in a table.el table
14789 :link on a hyperlink
14790 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14791 :target on a <<target>>
14792 :radio-target on a <<<radio-target>>>
14793 :latex-fragment on a LaTeX fragment
14794 :latex-preview on a LaTeX fragment with overlayed preview image
14796 This function expects the position to be visible because it uses font-lock
14797 faces as a help to recognize the following contexts: :table-special, :link,
14798 and :keyword."
14799 (let* ((f (get-text-property (point) 'face))
14800 (faces (if (listp f) f (list f)))
14801 (p (point)) clist o)
14802 ;; First the large context
14803 (cond
14804 ((org-on-heading-p t)
14805 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14806 (when (progn
14807 (beginning-of-line 1)
14808 (looking-at org-todo-line-tags-regexp))
14809 (push (org-point-in-group p 1 :headline-stars) clist)
14810 (push (org-point-in-group p 2 :todo-keyword) clist)
14811 (push (org-point-in-group p 4 :tags) clist))
14812 (goto-char p)
14813 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14814 (if (looking-at "\\[#[A-Z0-9]\\]")
14815 (push (org-point-in-group p 0 :priority) clist)))
14817 ((org-at-item-p)
14818 (push (org-point-in-group p 2 :item-bullet) clist)
14819 (push (list :item (point-at-bol)
14820 (save-excursion (org-end-of-item) (point)))
14821 clist)
14822 (and (org-at-item-checkbox-p)
14823 (push (org-point-in-group p 0 :checkbox) clist)))
14825 ((org-at-table-p)
14826 (push (list :table (org-table-begin) (org-table-end)) clist)
14827 (if (memq 'org-formula faces)
14828 (push (list :table-special
14829 (previous-single-property-change p 'face)
14830 (next-single-property-change p 'face)) clist)))
14831 ((org-at-table-p 'any)
14832 (push (list :table-table) clist)))
14833 (goto-char p)
14835 ;; Now the small context
14836 (cond
14837 ((org-at-timestamp-p)
14838 (push (org-point-in-group p 0 :timestamp) clist))
14839 ((memq 'org-link faces)
14840 (push (list :link
14841 (previous-single-property-change p 'face)
14842 (next-single-property-change p 'face)) clist))
14843 ((memq 'org-special-keyword faces)
14844 (push (list :keyword
14845 (previous-single-property-change p 'face)
14846 (next-single-property-change p 'face)) clist))
14847 ((org-on-target-p)
14848 (push (org-point-in-group p 0 :target) clist)
14849 (goto-char (1- (match-beginning 0)))
14850 (if (looking-at org-radio-target-regexp)
14851 (push (org-point-in-group p 0 :radio-target) clist))
14852 (goto-char p))
14853 ((setq o (car (delq nil
14854 (mapcar
14855 (lambda (x)
14856 (if (memq x org-latex-fragment-image-overlays) x))
14857 (org-overlays-at (point))))))
14858 (push (list :latex-fragment
14859 (org-overlay-start o) (org-overlay-end o)) clist)
14860 (push (list :latex-preview
14861 (org-overlay-start o) (org-overlay-end o)) clist))
14862 ((org-inside-LaTeX-fragment-p)
14863 ;; FIXME: positions wrong.
14864 (push (list :latex-fragment (point) (point)) clist)))
14866 (setq clist (nreverse (delq nil clist)))
14867 clist))
14869 ;; FIXME: Compare with at-regexp-p Do we need both?
14870 (defun org-in-regexp (re &optional nlines visually)
14871 "Check if point is inside a match of regexp.
14872 Normally only the current line is checked, but you can include NLINES extra
14873 lines both before and after point into the search.
14874 If VISUALLY is set, require that the cursor is not after the match but
14875 really on, so that the block visually is on the match."
14876 (catch 'exit
14877 (let ((pos (point))
14878 (eol (point-at-eol (+ 1 (or nlines 0))))
14879 (inc (if visually 1 0)))
14880 (save-excursion
14881 (beginning-of-line (- 1 (or nlines 0)))
14882 (while (re-search-forward re eol t)
14883 (if (and (<= (match-beginning 0) pos)
14884 (>= (+ inc (match-end 0)) pos))
14885 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14887 (defun org-at-regexp-p (regexp)
14888 "Is point inside a match of REGEXP in the current line?"
14889 (catch 'exit
14890 (save-excursion
14891 (let ((pos (point)) (end (point-at-eol)))
14892 (beginning-of-line 1)
14893 (while (re-search-forward regexp end t)
14894 (if (and (<= (match-beginning 0) pos)
14895 (>= (match-end 0) pos))
14896 (throw 'exit t)))
14897 nil))))
14899 (defun org-occur-in-agenda-files (regexp &optional nlines)
14900 "Call `multi-occur' with buffers for all agenda files."
14901 (interactive "sOrg-files matching: \np")
14902 (let* ((files (org-agenda-files))
14903 (tnames (mapcar 'file-truename files))
14904 (extra org-agenda-text-search-extra-files)
14906 (when (eq (car extra) 'agenda-archives)
14907 (setq extra (cdr extra))
14908 (setq files (org-add-archive-files files)))
14909 (while (setq f (pop extra))
14910 (unless (member (file-truename f) tnames)
14911 (add-to-list 'files f 'append)
14912 (add-to-list 'tnames (file-truename f) 'append)))
14913 (multi-occur
14914 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14915 regexp)))
14917 (if (boundp 'occur-mode-find-occurrence-hook)
14918 ;; Emacs 23
14919 (add-hook 'occur-mode-find-occurrence-hook
14920 (lambda ()
14921 (when (org-mode-p)
14922 (org-reveal))))
14923 ;; Emacs 22
14924 (defadvice occur-mode-goto-occurrence
14925 (after org-occur-reveal activate)
14926 (and (org-mode-p) (org-reveal)))
14927 (defadvice occur-mode-goto-occurrence-other-window
14928 (after org-occur-reveal activate)
14929 (and (org-mode-p) (org-reveal)))
14930 (defadvice occur-mode-display-occurrence
14931 (after org-occur-reveal activate)
14932 (when (org-mode-p)
14933 (let ((pos (occur-mode-find-occurrence)))
14934 (with-current-buffer (marker-buffer pos)
14935 (save-excursion
14936 (goto-char pos)
14937 (org-reveal)))))))
14939 (defun org-uniquify (list)
14940 "Remove duplicate elements from LIST."
14941 (let (res)
14942 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14943 res))
14945 (defun org-delete-all (elts list)
14946 "Remove all elements in ELTS from LIST."
14947 (while elts
14948 (setq list (delete (pop elts) list)))
14949 list)
14951 (defun org-back-over-empty-lines ()
14952 "Move backwards over whitespace, to the beginning of the first empty line.
14953 Returns the number of empty lines passed."
14954 (let ((pos (point)))
14955 (skip-chars-backward " \t\n\r")
14956 (beginning-of-line 2)
14957 (goto-char (min (point) pos))
14958 (count-lines (point) pos)))
14960 (defun org-skip-whitespace ()
14961 (skip-chars-forward " \t\n\r"))
14963 (defun org-point-in-group (point group &optional context)
14964 "Check if POINT is in match-group GROUP.
14965 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14966 match. If the match group does ot exist or point is not inside it,
14967 return nil."
14968 (and (match-beginning group)
14969 (>= point (match-beginning group))
14970 (<= point (match-end group))
14971 (if context
14972 (list context (match-beginning group) (match-end group))
14973 t)))
14975 (defun org-switch-to-buffer-other-window (&rest args)
14976 "Switch to buffer in a second window on the current frame.
14977 In particular, do not allow pop-up frames."
14978 (let (pop-up-frames special-display-buffer-names special-display-regexps
14979 special-display-function)
14980 (apply 'switch-to-buffer-other-window args)))
14982 (defun org-combine-plists (&rest plists)
14983 "Create a single property list from all plists in PLISTS.
14984 The process starts by copying the first list, and then setting properties
14985 from the other lists. Settings in the last list are the most significant
14986 ones and overrule settings in the other lists."
14987 (let ((rtn (copy-sequence (pop plists)))
14988 p v ls)
14989 (while plists
14990 (setq ls (pop plists))
14991 (while ls
14992 (setq p (pop ls) v (pop ls))
14993 (setq rtn (plist-put rtn p v))))
14994 rtn))
14996 (defun org-move-line-down (arg)
14997 "Move the current line down. With prefix argument, move it past ARG lines."
14998 (interactive "p")
14999 (let ((col (current-column))
15000 beg end pos)
15001 (beginning-of-line 1) (setq beg (point))
15002 (beginning-of-line 2) (setq end (point))
15003 (beginning-of-line (+ 1 arg))
15004 (setq pos (move-marker (make-marker) (point)))
15005 (insert (delete-and-extract-region beg end))
15006 (goto-char pos)
15007 (org-move-to-column col)))
15009 (defun org-move-line-up (arg)
15010 "Move the current line up. With prefix argument, move it past ARG lines."
15011 (interactive "p")
15012 (let ((col (current-column))
15013 beg end pos)
15014 (beginning-of-line 1) (setq beg (point))
15015 (beginning-of-line 2) (setq end (point))
15016 (beginning-of-line (- arg))
15017 (setq pos (move-marker (make-marker) (point)))
15018 (insert (delete-and-extract-region beg end))
15019 (goto-char pos)
15020 (org-move-to-column col)))
15022 (defun org-replace-escapes (string table)
15023 "Replace %-escapes in STRING with values in TABLE.
15024 TABLE is an association list with keys like \"%a\" and string values.
15025 The sequences in STRING may contain normal field width and padding information,
15026 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15027 so values can contain further %-escapes if they are define later in TABLE."
15028 (let ((case-fold-search nil)
15029 e re rpl)
15030 (while (setq e (pop table))
15031 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15032 (while (string-match re string)
15033 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15034 (cdr e)))
15035 (setq string (replace-match rpl t t string))))
15036 string))
15039 (defun org-sublist (list start end)
15040 "Return a section of LIST, from START to END.
15041 Counting starts at 1."
15042 (let (rtn (c start))
15043 (setq list (nthcdr (1- start) list))
15044 (while (and list (<= c end))
15045 (push (pop list) rtn)
15046 (setq c (1+ c)))
15047 (nreverse rtn)))
15049 (defun org-find-base-buffer-visiting (file)
15050 "Like `find-buffer-visiting' but alway return the base buffer and
15051 not an indirect buffer."
15052 (let ((buf (find-buffer-visiting file)))
15053 (if buf
15054 (or (buffer-base-buffer buf) buf)
15055 nil)))
15057 (defun org-image-file-name-regexp (&optional extensions)
15058 "Return regexp matching the file names of images.
15059 If EXTENSIONS is given, only match these."
15060 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15061 (image-file-name-regexp)
15062 (let ((image-file-name-extensions
15063 (or extensions
15064 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15065 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15066 (concat "\\."
15067 (regexp-opt (nconc (mapcar 'upcase
15068 image-file-name-extensions)
15069 image-file-name-extensions)
15071 "\\'"))))
15073 (defun org-file-image-p (file &optional extensions)
15074 "Return non-nil if FILE is an image."
15075 (save-match-data
15076 (string-match (org-image-file-name-regexp extensions) file)))
15078 (defun org-get-cursor-date ()
15079 "Return the date at cursor in as a time.
15080 This works in the calendar and in the agenda, anywhere else it just
15081 returns the current time."
15082 (let (date day defd)
15083 (cond
15084 ((eq major-mode 'calendar-mode)
15085 (setq date (calendar-cursor-to-date)
15086 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15087 ((eq major-mode 'org-agenda-mode)
15088 (setq day (get-text-property (point) 'day))
15089 (if day
15090 (setq date (calendar-gregorian-from-absolute day)
15091 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15092 (nth 2 date))))))
15093 (or defd (current-time))))
15095 (defvar org-agenda-action-marker (make-marker)
15096 "Marker pointing to the entry for the next agenda action.")
15098 (defun org-mark-entry-for-agenda-action ()
15099 "Mark the current entry as target of an agenda action.
15100 Agenda actions are actions executed from the agenda with the key `k',
15101 which make use of the date at the cursor."
15102 (interactive)
15103 (move-marker org-agenda-action-marker
15104 (save-excursion (org-back-to-heading t) (point))
15105 (current-buffer))
15106 (message
15107 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15109 ;;; Paragraph filling stuff.
15110 ;; We want this to be just right, so use the full arsenal.
15112 (defun org-indent-line-function ()
15113 "Indent line like previous, but further if previous was headline or item."
15114 (interactive)
15115 (let* ((pos (point))
15116 (itemp (org-at-item-p))
15117 (org-drawer-regexp (or org-drawer-regexp "\000"))
15118 column bpos bcol tpos tcol bullet btype bullet-type)
15119 ;; Find the previous relevant line
15120 (beginning-of-line 1)
15121 (cond
15122 ((looking-at "#") (setq column 0))
15123 ((looking-at "\\*+ ") (setq column 0))
15124 ((and (looking-at "[ \t]*:END:")
15125 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15126 (save-excursion
15127 (goto-char (1- (match-beginning 1)))
15128 (setq column (current-column))))
15130 (beginning-of-line 0)
15131 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15132 (not (looking-at "[ \t]*:END:"))
15133 (not (looking-at org-drawer-regexp)))
15134 (beginning-of-line 0))
15135 (cond
15136 ((looking-at "\\*+[ \t]+")
15137 (if (not org-adapt-indentation)
15138 (setq column 0)
15139 (goto-char (match-end 0))
15140 (setq column (current-column))))
15141 ((looking-at org-drawer-regexp)
15142 (goto-char (1- (match-beginning 1)))
15143 (setq column (current-column)))
15144 ((looking-at "\\([ \t]*\\):END:")
15145 (goto-char (match-end 1))
15146 (setq column (current-column)))
15147 ((org-in-item-p)
15148 (org-beginning-of-item)
15149 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15150 (setq bpos (match-beginning 1) tpos (match-end 0)
15151 bcol (progn (goto-char bpos) (current-column))
15152 tcol (progn (goto-char tpos) (current-column))
15153 bullet (match-string 1)
15154 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15155 (if (> tcol (+ bcol org-description-max-indent))
15156 (setq tcol (+ bcol 5)))
15157 (if (not itemp)
15158 (setq column tcol)
15159 (goto-char pos)
15160 (beginning-of-line 1)
15161 (if (looking-at "\\S-")
15162 (progn
15163 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15164 (setq bullet (match-string 1)
15165 btype (if (string-match "[0-9]" bullet) "n" bullet))
15166 (setq column (if (equal btype bullet-type) bcol tcol)))
15167 (setq column (org-get-indentation)))))
15168 (t (setq column (org-get-indentation))))))
15169 (goto-char pos)
15170 (if (<= (current-column) (current-indentation))
15171 (org-indent-line-to column)
15172 (save-excursion (org-indent-line-to column)))
15173 (setq column (current-column))
15174 (beginning-of-line 1)
15175 (if (looking-at
15176 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15177 (replace-match (concat "\\1" (format org-property-format
15178 (match-string 2) (match-string 3)))
15179 t nil))
15180 (org-move-to-column column)))
15182 (defun org-set-autofill-regexps ()
15183 (interactive)
15184 ;; In the paragraph separator we include headlines, because filling
15185 ;; text in a line directly attached to a headline would otherwise
15186 ;; fill the headline as well.
15187 (org-set-local 'comment-start-skip "^#+[ \t]*")
15188 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15189 ;; The paragraph starter includes hand-formatted lists.
15190 (org-set-local 'paragraph-start
15191 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15192 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15193 ;; But only if the user has not turned off tables or fixed-width regions
15194 (org-set-local
15195 'auto-fill-inhibit-regexp
15196 (concat "\\*+ \\|#\\+"
15197 "\\|[ \t]*" org-keyword-time-regexp
15198 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15199 (concat
15200 "\\|[ \t]*["
15201 (if org-enable-table-editor "|" "")
15202 (if org-enable-fixed-width-editor ":" "")
15203 "]"))))
15204 ;; We use our own fill-paragraph function, to make sure that tables
15205 ;; and fixed-width regions are not wrapped. That function will pass
15206 ;; through to `fill-paragraph' when appropriate.
15207 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15208 ; Adaptive filling: To get full control, first make sure that
15209 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15210 (org-set-local 'adaptive-fill-regexp "\000")
15211 (org-set-local 'adaptive-fill-function
15212 'org-adaptive-fill-function)
15213 (org-set-local
15214 'align-mode-rules-list
15215 '((org-in-buffer-settings
15216 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15217 (modes . '(org-mode))))))
15219 (defun org-fill-paragraph (&optional justify)
15220 "Re-align a table, pass through to fill-paragraph if no table."
15221 (let ((table-p (org-at-table-p))
15222 (table.el-p (org-at-table.el-p)))
15223 (cond ((and (equal (char-after (point-at-bol)) ?*)
15224 (save-excursion (goto-char (point-at-bol))
15225 (looking-at outline-regexp)))
15226 t) ; skip headlines
15227 (table.el-p t) ; skip table.el tables
15228 (table-p (org-table-align) t) ; align org-mode tables
15229 (t nil)))) ; call paragraph-fill
15231 ;; For reference, this is the default value of adaptive-fill-regexp
15232 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15234 (defun org-adaptive-fill-function ()
15235 "Return a fill prefix for org-mode files.
15236 In particular, this makes sure hanging paragraphs for hand-formatted lists
15237 work correctly."
15238 (cond ((looking-at "#[ \t]+")
15239 (match-string 0))
15240 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15241 (save-excursion
15242 (if (> (match-end 1) (+ (match-beginning 1)
15243 org-description-max-indent))
15244 (goto-char (+ (match-beginning 1) 5))
15245 (goto-char (match-end 0)))
15246 (make-string (current-column) ?\ )))
15247 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15248 (save-excursion
15249 (goto-char (match-end 0))
15250 (make-string (current-column) ?\ )))
15251 (t nil)))
15253 ;;; Other stuff.
15255 (defun org-toggle-fixed-width-section (arg)
15256 "Toggle the fixed-width export.
15257 If there is no active region, the QUOTE keyword at the current headline is
15258 inserted or removed. When present, it causes the text between this headline
15259 and the next to be exported as fixed-width text, and unmodified.
15260 If there is an active region, this command adds or removes a colon as the
15261 first character of this line. If the first character of a line is a colon,
15262 this line is also exported in fixed-width font."
15263 (interactive "P")
15264 (let* ((cc 0)
15265 (regionp (org-region-active-p))
15266 (beg (if regionp (region-beginning) (point)))
15267 (end (if regionp (region-end)))
15268 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15269 (case-fold-search nil)
15270 (re "[ \t]*\\(: \\)")
15271 off)
15272 (if regionp
15273 (save-excursion
15274 (goto-char beg)
15275 (setq cc (current-column))
15276 (beginning-of-line 1)
15277 (setq off (looking-at re))
15278 (while (> nlines 0)
15279 (setq nlines (1- nlines))
15280 (beginning-of-line 1)
15281 (cond
15282 (arg
15283 (org-move-to-column cc t)
15284 (insert ": \n")
15285 (forward-line -1))
15286 ((and off (looking-at re))
15287 (replace-match "" t t nil 1))
15288 ((not off) (org-move-to-column cc t) (insert ": ")))
15289 (forward-line 1)))
15290 (save-excursion
15291 (org-back-to-heading)
15292 (if (looking-at (concat outline-regexp
15293 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15294 (replace-match "" t t nil 1)
15295 (if (looking-at outline-regexp)
15296 (progn
15297 (goto-char (match-end 0))
15298 (insert org-quote-string " "))))))))
15300 ;;;; Functions extending outline functionality
15302 (defun org-beginning-of-line (&optional arg)
15303 "Go to the beginning of the current line. If that is invisible, continue
15304 to a visible line beginning. This makes the function of C-a more intuitive.
15305 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15306 first attempt, and only move to after the tags when the cursor is already
15307 beyond the end of the headline."
15308 (interactive "P")
15309 (let ((pos (point))
15310 (special (if (consp org-special-ctrl-a/e)
15311 (car org-special-ctrl-a/e)
15312 org-special-ctrl-a/e))
15313 refpos)
15314 (beginning-of-line 1)
15315 (if (and arg (fboundp 'move-beginning-of-line))
15316 (call-interactively 'move-beginning-of-line)
15317 (if (bobp)
15319 (backward-char 1)
15320 (if (org-invisible-p)
15321 (while (and (not (bobp)) (org-invisible-p))
15322 (backward-char 1)
15323 (beginning-of-line 1))
15324 (forward-char 1))))
15325 (when special
15326 (cond
15327 ((and (looking-at org-complex-heading-regexp)
15328 (= (char-after (match-end 1)) ?\ ))
15329 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15330 (point-at-eol)))
15331 (goto-char
15332 (if (eq special t)
15333 (cond ((> pos refpos) refpos)
15334 ((= pos (point)) refpos)
15335 (t (point)))
15336 (cond ((> pos (point)) (point))
15337 ((not (eq last-command this-command)) (point))
15338 (t refpos)))))
15339 ((org-at-item-p)
15340 (goto-char
15341 (if (eq special t)
15342 (cond ((> pos (match-end 4)) (match-end 4))
15343 ((= pos (point)) (match-end 4))
15344 (t (point)))
15345 (cond ((> pos (point)) (point))
15346 ((not (eq last-command this-command)) (point))
15347 (t (match-end 4))))))))
15348 (org-no-warnings
15349 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15351 (defun org-end-of-line (&optional arg)
15352 "Go to the end of the line.
15353 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15354 first attempt, and only move to after the tags when the cursor is already
15355 beyond the end of the headline."
15356 (interactive "P")
15357 (let ((special (if (consp org-special-ctrl-a/e)
15358 (cdr org-special-ctrl-a/e)
15359 org-special-ctrl-a/e)))
15360 (if (or (not special)
15361 (not (org-on-heading-p))
15362 arg)
15363 (call-interactively (if (fboundp 'move-end-of-line)
15364 'move-end-of-line
15365 'end-of-line))
15366 (let ((pos (point)))
15367 (beginning-of-line 1)
15368 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15369 (if (eq special t)
15370 (if (or (< pos (match-beginning 1))
15371 (= pos (match-end 0)))
15372 (goto-char (match-beginning 1))
15373 (goto-char (match-end 0)))
15374 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15375 (goto-char (match-end 0))
15376 (goto-char (match-beginning 1))))
15377 (call-interactively (if (fboundp 'move-end-of-line)
15378 'move-end-of-line
15379 'end-of-line)))))
15380 (org-no-warnings
15381 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15383 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15384 (define-key org-mode-map "\C-e" 'org-end-of-line)
15386 (defun org-kill-line (&optional arg)
15387 "Kill line, to tags or end of line."
15388 (interactive "P")
15389 (cond
15390 ((or (not org-special-ctrl-k)
15391 (bolp)
15392 (not (org-on-heading-p)))
15393 (call-interactively 'kill-line))
15394 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15395 (kill-region (point) (match-beginning 1))
15396 (org-set-tags nil t))
15397 (t (kill-region (point) (point-at-eol)))))
15399 (define-key org-mode-map "\C-k" 'org-kill-line)
15401 (defun org-yank (&optional arg)
15402 "Yank. If the kill is a subtree, treat it specially.
15403 This command will look at the current kill and check if is a single
15404 subtree, or a series of subtrees[1]. If it passes the test, and if the
15405 cursor is at the beginning of a line or after the stars of a currently
15406 empty headline, then the yank is handled specially. How exactly depends
15407 on the value of the following variables, both set by default.
15409 org-yank-folded-subtrees
15410 When set, the subtree(s) will be folded after insertion, but only
15411 if doing so would now swallow text after the yanked text.
15413 org-yank-adjusted-subtrees
15414 When set, the subtree will be promoted or demoted in order to
15415 fit into the local outline tree structure, which means that the level
15416 will be adjusted so that it becomes the smaller one of the two
15417 *visible* surrounding headings.
15419 Any prefix to this command will cause `yank' to be called directly with
15420 no special treatment. In particular, a simple `C-u' prefix will just
15421 plainly yank the text as it is.
15423 \[1] Basically, the test checks if the first non-white line is a heading
15424 and if there are no other headings with fewer stars."
15425 (interactive "P")
15426 (setq this-command 'yank)
15427 (if arg
15428 (call-interactively 'yank)
15429 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15430 (and (org-kill-is-subtree-p)
15431 (or (bolp)
15432 (and (looking-at "[ \t]*$")
15433 (string-match
15434 "\\`\\*+\\'"
15435 (buffer-substring (point-at-bol) (point)))))))
15436 swallowp)
15437 (cond
15438 ((and subtreep org-yank-folded-subtrees)
15439 (let ((beg (point))
15440 end)
15441 (if (and subtreep org-yank-adjusted-subtrees)
15442 (org-paste-subtree nil nil 'for-yank)
15443 (call-interactively 'yank))
15444 (setq end (point))
15445 (goto-char beg)
15446 (when (and (bolp) subtreep
15447 (not (setq swallowp
15448 (org-yank-folding-would-swallow-text beg end))))
15449 (or (looking-at outline-regexp)
15450 (re-search-forward (concat "^" outline-regexp) end t))
15451 (while (and (< (point) end) (looking-at outline-regexp))
15452 (hide-subtree)
15453 (org-cycle-show-empty-lines 'folded)
15454 (condition-case nil
15455 (outline-forward-same-level 1)
15456 (error (goto-char end)))))
15457 (when swallowp
15458 (message
15459 "Yanked text not folded because that would swallow text"))
15460 (goto-char end)
15461 (skip-chars-forward " \t\n\r")
15462 (beginning-of-line 1)
15463 (push-mark beg 'nomsg)))
15464 ((and subtreep org-yank-adjusted-subtrees)
15465 (let ((beg (point-at-bol)))
15466 (org-paste-subtree nil nil 'for-yank)
15467 (push-mark beg 'nomsg)))
15469 (call-interactively 'yank))))))
15471 (defun org-yank-folding-would-swallow-text (beg end)
15472 "Would hide-subtree at BEG swallow any text after END?"
15473 (let (level)
15474 (save-excursion
15475 (goto-char beg)
15476 (when (or (looking-at outline-regexp)
15477 (re-search-forward (concat "^" outline-regexp) end t))
15478 (setq level (org-outline-level)))
15479 (goto-char end)
15480 (skip-chars-forward " \t\r\n\v\f")
15481 (if (or (eobp)
15482 (and (bolp) (looking-at org-outline-regexp)
15483 (<= (org-outline-level) level)))
15484 nil ; Nothing would be swallowed
15485 t)))) ; something would swallow
15487 (define-key org-mode-map "\C-y" 'org-yank)
15489 (defun org-invisible-p ()
15490 "Check if point is at a character currently not visible."
15491 ;; Early versions of noutline don't have `outline-invisible-p'.
15492 (if (fboundp 'outline-invisible-p)
15493 (outline-invisible-p)
15494 (get-char-property (point) 'invisible)))
15496 (defun org-invisible-p2 ()
15497 "Check if point is at a character currently not visible."
15498 (save-excursion
15499 (if (and (eolp) (not (bobp))) (backward-char 1))
15500 ;; Early versions of noutline don't have `outline-invisible-p'.
15501 (if (fboundp 'outline-invisible-p)
15502 (outline-invisible-p)
15503 (get-char-property (point) 'invisible))))
15505 (defun org-back-to-heading (&optional invisible-ok)
15506 "Call `outline-back-to-heading', but provide a better error message."
15507 (condition-case nil
15508 (outline-back-to-heading invisible-ok)
15509 (error (error "Before first headline at position %d in buffer %s"
15510 (point) (current-buffer)))))
15512 (defun org-before-first-heading-p ()
15513 "Before first heading?"
15514 (save-excursion
15515 (null (re-search-backward "^\\*+ " nil t))))
15517 (defalias 'org-on-heading-p 'outline-on-heading-p)
15518 (defalias 'org-at-heading-p 'outline-on-heading-p)
15519 (defun org-at-heading-or-item-p ()
15520 (or (org-on-heading-p) (org-at-item-p)))
15522 (defun org-on-target-p ()
15523 (or (org-in-regexp org-radio-target-regexp)
15524 (org-in-regexp org-target-regexp)))
15526 (defun org-up-heading-all (arg)
15527 "Move to the heading line of which the present line is a subheading.
15528 This function considers both visible and invisible heading lines.
15529 With argument, move up ARG levels."
15530 (if (fboundp 'outline-up-heading-all)
15531 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15532 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15534 (defun org-up-heading-safe ()
15535 "Move to the heading line of which the present line is a subheading.
15536 This version will not throw an error. It will return the level of the
15537 headline found, or nil if no higher level is found."
15538 (let (start-level re)
15539 (org-back-to-heading t)
15540 (setq start-level (funcall outline-level))
15541 (if (equal start-level 1)
15543 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15544 (if (re-search-backward re nil t)
15545 (funcall outline-level)))))
15547 (defun org-first-sibling-p ()
15548 "Is this heading the first child of its parents?"
15549 (interactive)
15550 (let ((re (concat "^" outline-regexp))
15551 level l)
15552 (unless (org-at-heading-p t)
15553 (error "Not at a heading"))
15554 (setq level (funcall outline-level))
15555 (save-excursion
15556 (if (not (re-search-backward re nil t))
15558 (setq l (funcall outline-level))
15559 (< l level)))))
15561 (defun org-goto-sibling (&optional previous)
15562 "Goto the next sibling, even if it is invisible.
15563 When PREVIOUS is set, go to the previous sibling instead. Returns t
15564 when a sibling was found. When none is found, return nil and don't
15565 move point."
15566 (let ((fun (if previous 're-search-backward 're-search-forward))
15567 (pos (point))
15568 (re (concat "^" outline-regexp))
15569 level l)
15570 (when (condition-case nil (org-back-to-heading t) (error nil))
15571 (setq level (funcall outline-level))
15572 (catch 'exit
15573 (or previous (forward-char 1))
15574 (while (funcall fun re nil t)
15575 (setq l (funcall outline-level))
15576 (when (< l level) (goto-char pos) (throw 'exit nil))
15577 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15578 (goto-char pos)
15579 nil))))
15581 (defun org-show-siblings ()
15582 "Show all siblings of the current headline."
15583 (save-excursion
15584 (while (org-goto-sibling) (org-flag-heading nil)))
15585 (save-excursion
15586 (while (org-goto-sibling 'previous)
15587 (org-flag-heading nil))))
15589 (defun org-show-hidden-entry ()
15590 "Show an entry where even the heading is hidden."
15591 (save-excursion
15592 (org-show-entry)))
15594 (defun org-flag-heading (flag &optional entry)
15595 "Flag the current heading. FLAG non-nil means make invisible.
15596 When ENTRY is non-nil, show the entire entry."
15597 (save-excursion
15598 (org-back-to-heading t)
15599 ;; Check if we should show the entire entry
15600 (if entry
15601 (progn
15602 (org-show-entry)
15603 (save-excursion
15604 (and (outline-next-heading)
15605 (org-flag-heading nil))))
15606 (outline-flag-region (max (point-min) (1- (point)))
15607 (save-excursion (outline-end-of-heading) (point))
15608 flag))))
15610 (defun org-forward-same-level (arg)
15611 "Move forward to the ARG'th subheading at same level as this one.
15612 Stop at the first and last subheadings of a superior heading.
15613 This is like outline-forward-same-level, but invisible headings are ok."
15614 (interactive "p")
15615 (org-back-to-heading t)
15616 (while (> arg 0)
15617 (let ((point-to-move-to (save-excursion
15618 (org-get-next-sibling))))
15619 (if point-to-move-to
15620 (progn
15621 (goto-char point-to-move-to)
15622 (setq arg (1- arg)))
15623 (progn
15624 (setq arg 0)
15625 (error "No following same-level heading"))))))
15627 (defun org-get-next-sibling ()
15628 "Move to next heading of the same level, and return point.
15629 If there is no such heading, return nil.
15630 This is like outline-next-sibling, but invisible headings are ok."
15631 (let ((level (funcall outline-level)))
15632 (outline-next-heading)
15633 (while (and (not (eobp)) (> (funcall outline-level) level))
15634 (outline-next-heading))
15635 (if (or (eobp) (< (funcall outline-level) level))
15637 (point))))
15639 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15640 ;; This is an exact copy of the original function, but it uses
15641 ;; `org-back-to-heading', to make it work also in invisible
15642 ;; trees. And is uses an invisible-OK argument.
15643 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15644 (org-back-to-heading invisible-OK)
15645 (let ((first t)
15646 (level (funcall outline-level)))
15647 (while (and (not (eobp))
15648 (or first (> (funcall outline-level) level)))
15649 (setq first nil)
15650 (outline-next-heading))
15651 (unless to-heading
15652 (if (memq (preceding-char) '(?\n ?\^M))
15653 (progn
15654 ;; Go to end of line before heading
15655 (forward-char -1)
15656 (if (memq (preceding-char) '(?\n ?\^M))
15657 ;; leave blank line before heading
15658 (forward-char -1))))))
15659 (point))
15661 (defun org-show-subtree ()
15662 "Show everything after this heading at deeper levels."
15663 (outline-flag-region
15664 (point)
15665 (save-excursion
15666 (outline-end-of-subtree) (outline-next-heading) (point))
15667 nil))
15669 (defun org-show-entry ()
15670 "Show the body directly following this heading.
15671 Show the heading too, if it is currently invisible."
15672 (interactive)
15673 (save-excursion
15674 (condition-case nil
15675 (progn
15676 (org-back-to-heading t)
15677 (outline-flag-region
15678 (max (point-min) (1- (point)))
15679 (save-excursion
15680 (if (re-search-forward
15681 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15682 (match-beginning 1)
15683 (point-max)))
15684 nil))
15685 (error nil))))
15687 (defun org-make-options-regexp (kwds &optional extra)
15688 "Make a regular expression for keyword lines."
15689 (concat
15691 "#?[ \t]*\\+\\("
15692 (mapconcat 'regexp-quote kwds "\\|")
15693 (if extra (concat "\\|" extra))
15694 "\\):[ \t]*"
15695 "\\(.+\\)"))
15697 ;; Make isearch reveal the necessary context
15698 (defun org-isearch-end ()
15699 "Reveal context after isearch exits."
15700 (when isearch-success ; only if search was successful
15701 (if (featurep 'xemacs)
15702 ;; Under XEmacs, the hook is run in the correct place,
15703 ;; we directly show the context.
15704 (org-show-context 'isearch)
15705 ;; In Emacs the hook runs *before* restoring the overlays.
15706 ;; So we have to use a one-time post-command-hook to do this.
15707 ;; (Emacs 22 has a special variable, see function `org-mode')
15708 (unless (and (boundp 'isearch-mode-end-hook-quit)
15709 isearch-mode-end-hook-quit)
15710 ;; Only when the isearch was not quitted.
15711 (org-add-hook 'post-command-hook 'org-isearch-post-command
15712 'append 'local)))))
15714 (defun org-isearch-post-command ()
15715 "Remove self from hook, and show context."
15716 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15717 (org-show-context 'isearch))
15720 ;;;; Integration with and fixes for other packages
15722 ;;; Imenu support
15724 (defvar org-imenu-markers nil
15725 "All markers currently used by Imenu.")
15726 (make-variable-buffer-local 'org-imenu-markers)
15728 (defun org-imenu-new-marker (&optional pos)
15729 "Return a new marker for use by Imenu, and remember the marker."
15730 (let ((m (make-marker)))
15731 (move-marker m (or pos (point)))
15732 (push m org-imenu-markers)
15735 (defun org-imenu-get-tree ()
15736 "Produce the index for Imenu."
15737 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15738 (setq org-imenu-markers nil)
15739 (let* ((n org-imenu-depth)
15740 (re (concat "^" outline-regexp))
15741 (subs (make-vector (1+ n) nil))
15742 (last-level 0)
15743 m level head)
15744 (save-excursion
15745 (save-restriction
15746 (widen)
15747 (goto-char (point-max))
15748 (while (re-search-backward re nil t)
15749 (setq level (org-reduced-level (funcall outline-level)))
15750 (when (<= level n)
15751 (looking-at org-complex-heading-regexp)
15752 (setq head (org-link-display-format
15753 (org-match-string-no-properties 4))
15754 m (org-imenu-new-marker))
15755 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15756 (if (>= level last-level)
15757 (push (cons head m) (aref subs level))
15758 (push (cons head (aref subs (1+ level))) (aref subs level))
15759 (loop for i from (1+ level) to n do (aset subs i nil)))
15760 (setq last-level level)))))
15761 (aref subs 1)))
15763 (eval-after-load "imenu"
15764 '(progn
15765 (add-hook 'imenu-after-jump-hook
15766 (lambda ()
15767 (if (eq major-mode 'org-mode)
15768 (org-show-context 'org-goto))))))
15770 (defun org-link-display-format (link)
15771 "Replace a link with either the description, or the link target
15772 if no description is present"
15773 (save-match-data
15774 (if (string-match org-bracket-link-analytic-regexp link)
15775 (replace-match (or (match-string 5 link)
15776 (concat (match-string 1 link)
15777 (match-string 3 link)))
15778 nil nil link)
15779 link)))
15781 ;; Speedbar support
15783 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15784 "Overlay marking the agenda restriction line in speedbar.")
15785 (org-overlay-put org-speedbar-restriction-lock-overlay
15786 'face 'org-agenda-restriction-lock)
15787 (org-overlay-put org-speedbar-restriction-lock-overlay
15788 'help-echo "Agendas are currently limited to this item.")
15789 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15791 (defun org-speedbar-set-agenda-restriction ()
15792 "Restrict future agenda commands to the location at point in speedbar.
15793 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15794 (interactive)
15795 (require 'org-agenda)
15796 (let (p m tp np dir txt)
15797 (cond
15798 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15799 'org-imenu t))
15800 (setq m (get-text-property p 'org-imenu-marker))
15801 (save-excursion
15802 (save-restriction
15803 (set-buffer (marker-buffer m))
15804 (goto-char m)
15805 (org-agenda-set-restriction-lock 'subtree))))
15806 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15807 'speedbar-function 'speedbar-find-file))
15808 (setq tp (previous-single-property-change
15809 (1+ p) 'speedbar-function)
15810 np (next-single-property-change
15811 tp 'speedbar-function)
15812 dir (speedbar-line-directory)
15813 txt (buffer-substring-no-properties (or tp (point-min))
15814 (or np (point-max))))
15815 (save-excursion
15816 (save-restriction
15817 (set-buffer (find-file-noselect
15818 (let ((default-directory dir))
15819 (expand-file-name txt))))
15820 (unless (org-mode-p)
15821 (error "Cannot restrict to non-Org-mode file"))
15822 (org-agenda-set-restriction-lock 'file))))
15823 (t (error "Don't know how to restrict Org-mode's agenda")))
15824 (org-move-overlay org-speedbar-restriction-lock-overlay
15825 (point-at-bol) (point-at-eol))
15826 (setq current-prefix-arg nil)
15827 (org-agenda-maybe-redo)))
15829 (eval-after-load "speedbar"
15830 '(progn
15831 (speedbar-add-supported-extension ".org")
15832 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15833 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15834 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15835 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15836 (add-hook 'speedbar-visiting-tag-hook
15837 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15840 ;;; Fixes and Hacks for problems with other packages
15842 ;; Make flyspell not check words in links, to not mess up our keymap
15843 (defun org-mode-flyspell-verify ()
15844 "Don't let flyspell put overlays at active buttons."
15845 (not (get-text-property (point) 'keymap)))
15847 ;; Make `bookmark-jump' show the jump location if it was hidden.
15848 (eval-after-load "bookmark"
15849 '(if (boundp 'bookmark-after-jump-hook)
15850 ;; We can use the hook
15851 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15852 ;; Hook not available, use advice
15853 (defadvice bookmark-jump (after org-make-visible activate)
15854 "Make the position visible."
15855 (org-bookmark-jump-unhide))))
15857 ;; Make sure saveplace show the location if it was hidden
15858 (eval-after-load "saveplace"
15859 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15860 "Make the position visible."
15861 (org-bookmark-jump-unhide)))
15863 (defun org-bookmark-jump-unhide ()
15864 "Unhide the current position, to show the bookmark location."
15865 (and (org-mode-p)
15866 (or (org-invisible-p)
15867 (save-excursion (goto-char (max (point-min) (1- (point))))
15868 (org-invisible-p)))
15869 (org-show-context 'bookmark-jump)))
15871 ;; Make session.el ignore our circular variable
15872 (eval-after-load "session"
15873 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15875 ;;;; Experimental code
15877 (defun org-closed-in-range ()
15878 "Sparse tree of items closed in a certain time range.
15879 Still experimental, may disappear in the future."
15880 (interactive)
15881 ;; Get the time interval from the user.
15882 (let* ((time1 (time-to-seconds
15883 (org-read-date nil 'to-time nil "Starting date: ")))
15884 (time2 (time-to-seconds
15885 (org-read-date nil 'to-time nil "End date:")))
15886 ;; callback function
15887 (callback (lambda ()
15888 (let ((time
15889 (time-to-seconds
15890 (apply 'encode-time
15891 (org-parse-time-string
15892 (match-string 1))))))
15893 ;; check if time in interval
15894 (and (>= time time1) (<= time time2))))))
15895 ;; make tree, check each match with the callback
15896 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15899 ;;;; Finish up
15901 (provide 'org)
15903 (run-hooks 'org-load-hook)
15905 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15907 ;;; org.el ends here