Emphasis: Allow braces in pre and post match, important for LaTeX footnotes.
[org-mode.git] / lisp / org.el
blobdbd62f9d844df2d7aa990c6f9ba7631a787f6b30
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 shift-selection-mode'
300 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
301 If you want to use Org-mode together with one of these other modes,
302 or more generally if you would like to move some Org-mode commands to
303 other keys, set this variable and configure the keys with the variable
304 `org-disputed-keys'.
306 This option is only relevant at load-time of Org-mode, and must be set
307 *before* org.el is loaded. Changing it requires a restart of Emacs to
308 become effective."
309 :group 'org-startup
310 :type 'boolean)
312 (defcustom org-use-extra-keys nil
313 "Non-nil means use extra key sequence definitions for certain
314 commands. This happens automatically if you run XEmacs or if
315 window-system is nil. This variable lets you do the same
316 manually. You must set it before loading org.
318 Example: on Carbon Emacs 22 running graphically, with an external
319 keyboard on a Powerbook, the default way of setting M-left might
320 not work for either Alt or ESC. Setting this variable will make
321 it work for ESC."
322 :group 'org-startup
323 :type 'boolean)
325 (if (fboundp 'defvaralias)
326 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
328 (defcustom org-disputed-keys
329 '(([(shift up)] . [(meta p)])
330 ([(shift down)] . [(meta n)])
331 ([(shift left)] . [(meta -)])
332 ([(shift right)] . [(meta +)])
333 ([(control shift right)] . [(meta shift +)])
334 ([(control shift left)] . [(meta shift -)]))
335 "Keys for which Org-mode and other modes compete.
336 This is an alist, cars are the default keys, second element specifies
337 the alternative to use when `org-replace-disputed-keys' is t.
339 Keys can be specified in any syntax supported by `define-key'.
340 The value of this option takes effect only at Org-mode's startup,
341 therefore you'll have to restart Emacs to apply it after changing."
342 :group 'org-startup
343 :type 'alist)
345 (defun org-key (key)
346 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
347 Or return the original if not disputed."
348 (if org-replace-disputed-keys
349 (let* ((nkey (key-description key))
350 (x (org-find-if (lambda (x)
351 (equal (key-description (car x)) nkey))
352 org-disputed-keys)))
353 (if x (cdr x) key))
354 key))
356 (defun org-find-if (predicate seq)
357 (catch 'exit
358 (while seq
359 (if (funcall predicate (car seq))
360 (throw 'exit (car seq))
361 (pop seq)))))
363 (defun org-defkey (keymap key def)
364 "Define a key, possibly translated, as returned by `org-key'."
365 (define-key keymap (org-key key) def))
367 (defcustom org-ellipsis nil
368 "The ellipsis to use in the Org-mode outline.
369 When nil, just use the standard three dots. When a string, use that instead,
370 When a face, use the standard 3 dots, but with the specified face.
371 The change affects only Org-mode (which will then use its own display table).
372 Changing this requires executing `M-x org-mode' in a buffer to become
373 effective."
374 :group 'org-startup
375 :type '(choice (const :tag "Default" nil)
376 (face :tag "Face" :value org-warning)
377 (string :tag "String" :value "...#")))
379 (defvar org-display-table nil
380 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
382 (defgroup org-keywords nil
383 "Keywords in Org-mode."
384 :tag "Org Keywords"
385 :group 'org)
387 (defcustom org-deadline-string "DEADLINE:"
388 "String to mark deadline entries.
389 A deadline is this string, followed by a time stamp. Should be a word,
390 terminated by a colon. You can insert a schedule keyword and
391 a timestamp with \\[org-deadline].
392 Changes become only effective after restarting Emacs."
393 :group 'org-keywords
394 :type 'string)
396 (defcustom org-scheduled-string "SCHEDULED:"
397 "String to mark scheduled TODO entries.
398 A schedule is this string, followed by a time stamp. Should be a word,
399 terminated by a colon. You can insert a schedule keyword and
400 a timestamp with \\[org-schedule].
401 Changes become only effective after restarting Emacs."
402 :group 'org-keywords
403 :type 'string)
405 (defcustom org-closed-string "CLOSED:"
406 "String used as the prefix for timestamps logging closing a TODO entry."
407 :group 'org-keywords
408 :type 'string)
410 (defcustom org-clock-string "CLOCK:"
411 "String used as prefix for timestamps clocking work hours on an item."
412 :group 'org-keywords
413 :type 'string)
415 (defcustom org-comment-string "COMMENT"
416 "Entries starting with this keyword will never be exported.
417 An entry can be toggled between COMMENT and normal with
418 \\[org-toggle-comment].
419 Changes become only effective after restarting Emacs."
420 :group 'org-keywords
421 :type 'string)
423 (defcustom org-quote-string "QUOTE"
424 "Entries starting with this keyword will be exported in fixed-width font.
425 Quoting applies only to the text in the entry following the headline, and does
426 not extend beyond the next headline, even if that is lower level.
427 An entry can be toggled between QUOTE and normal with
428 \\[org-toggle-fixed-width-section]."
429 :group 'org-keywords
430 :type 'string)
432 (defconst org-repeat-re
433 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
434 "Regular expression for specifying repeated events.
435 After a match, group 1 contains the repeat expression.")
437 (defgroup org-structure nil
438 "Options concerning the general structure of Org-mode files."
439 :tag "Org Structure"
440 :group 'org)
442 (defgroup org-reveal-location nil
443 "Options about how to make context of a location visible."
444 :tag "Org Reveal Location"
445 :group 'org-structure)
447 (defconst org-context-choice
448 '(choice
449 (const :tag "Always" t)
450 (const :tag "Never" nil)
451 (repeat :greedy t :tag "Individual contexts"
452 (cons
453 (choice :tag "Context"
454 (const agenda)
455 (const org-goto)
456 (const occur-tree)
457 (const tags-tree)
458 (const link-search)
459 (const mark-goto)
460 (const bookmark-jump)
461 (const isearch)
462 (const default))
463 (boolean))))
464 "Contexts for the reveal options.")
466 (defcustom org-show-hierarchy-above '((default . t))
467 "Non-nil means, show full hierarchy when revealing a location.
468 Org-mode often shows locations in an org-mode file which might have
469 been invisible before. When this is set, the hierarchy of headings
470 above the exposed location is shown.
471 Turning this off for example for sparse trees makes them very compact.
472 Instead of t, this can also be an alist specifying this option for different
473 contexts. Valid contexts are
474 agenda when exposing an entry from the agenda
475 org-goto when using the command `org-goto' on key C-c C-j
476 occur-tree when using the command `org-occur' on key C-c /
477 tags-tree when constructing a sparse tree based on tags matches
478 link-search when exposing search matches associated with a link
479 mark-goto when exposing the jump goal of a mark
480 bookmark-jump when exposing a bookmark location
481 isearch when exiting from an incremental search
482 default default for all contexts not set explicitly"
483 :group 'org-reveal-location
484 :type org-context-choice)
486 (defcustom org-show-following-heading '((default . nil))
487 "Non-nil means, show following heading when revealing a location.
488 Org-mode often shows locations in an org-mode file which might have
489 been invisible before. When this is set, the heading following the
490 match is shown.
491 Turning this off for example for sparse trees makes them very compact,
492 but makes it harder to edit the location of the match. In such a case,
493 use the command \\[org-reveal] to show more context.
494 Instead of t, this can also be an alist specifying this option for different
495 contexts. See `org-show-hierarchy-above' for valid contexts."
496 :group 'org-reveal-location
497 :type org-context-choice)
499 (defcustom org-show-siblings '((default . nil) (isearch t))
500 "Non-nil means, show all sibling heading when revealing a location.
501 Org-mode often shows locations in an org-mode file which might have
502 been invisible before. When this is set, the sibling of the current entry
503 heading are all made visible. If `org-show-hierarchy-above' is t,
504 the same happens on each level of the hierarchy above the current entry.
506 By default this is on for the isearch context, off for all other contexts.
507 Turning this off for example for sparse trees makes them very compact,
508 but makes it harder to edit the location of the match. In such a case,
509 use the command \\[org-reveal] to show more context.
510 Instead of t, this can also be an alist specifying this option for different
511 contexts. See `org-show-hierarchy-above' for valid contexts."
512 :group 'org-reveal-location
513 :type org-context-choice)
515 (defcustom org-show-entry-below '((default . nil))
516 "Non-nil means, show the entry below a headline when revealing a location.
517 Org-mode often shows locations in an org-mode file which might have
518 been invisible before. When this is set, the text below the headline that is
519 exposed is also shown.
521 By default this is off for all contexts.
522 Instead of t, this can also be an alist specifying this option for different
523 contexts. See `org-show-hierarchy-above' for valid contexts."
524 :group 'org-reveal-location
525 :type org-context-choice)
527 (defcustom org-indirect-buffer-display 'other-window
528 "How should indirect tree buffers be displayed?
529 This applies to indirect buffers created with the commands
530 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
531 Valid values are:
532 current-window Display in the current window
533 other-window Just display in another window.
534 dedicated-frame Create one new frame, and re-use it each time.
535 new-frame Make a new frame each time. Note that in this case
536 previously-made indirect buffers are kept, and you need to
537 kill these buffers yourself."
538 :group 'org-structure
539 :group 'org-agenda-windows
540 :type '(choice
541 (const :tag "In current window" current-window)
542 (const :tag "In current frame, other window" other-window)
543 (const :tag "Each time a new frame" new-frame)
544 (const :tag "One dedicated frame" dedicated-frame)))
546 (defgroup org-cycle nil
547 "Options concerning visibility cycling in Org-mode."
548 :tag "Org Cycle"
549 :group 'org-structure)
551 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
552 "Names of drawers. Drawers are not opened by cycling on the headline above.
553 Drawers only open with a TAB on the drawer line itself. A drawer looks like
554 this:
555 :DRAWERNAME:
556 .....
557 :END:
558 The drawer \"PROPERTIES\" is special for capturing properties through
559 the property API.
561 Drawers can be defined on the per-file basis with a line like:
563 #+DRAWERS: HIDDEN STATE PROPERTIES"
564 :group 'org-structure
565 :type '(repeat (string :tag "Drawer Name")))
567 (defcustom org-cycle-global-at-bob nil
568 "Cycle globally if cursor is at beginning of buffer and not at a headline.
569 This makes it possible to do global cycling without having to use S-TAB or
570 C-u TAB. For this special case to work, the first line of the buffer
571 must not be a headline - it may be empty or some other text. When used in
572 this way, `org-cycle-hook' is disables temporarily, to make sure the
573 cursor stays at the beginning of the buffer.
574 When this option is nil, don't do anything special at the beginning
575 of the buffer."
576 :group 'org-cycle
577 :type 'boolean)
579 (defcustom org-cycle-emulate-tab t
580 "Where should `org-cycle' emulate TAB.
581 nil Never
582 white Only in completely white lines
583 whitestart Only at the beginning of lines, before the first non-white char
584 t Everywhere except in headlines
585 exc-hl-bol Everywhere except at the start of a headline
586 If TAB is used in a place where it does not emulate TAB, the current subtree
587 visibility is cycled."
588 :group 'org-cycle
589 :type '(choice (const :tag "Never" nil)
590 (const :tag "Only in completely white lines" white)
591 (const :tag "Before first char in a line" whitestart)
592 (const :tag "Everywhere except in headlines" t)
593 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
596 (defcustom org-cycle-separator-lines 2
597 "Number of empty lines needed to keep an empty line between collapsed trees.
598 If you leave an empty line between the end of a subtree and the following
599 headline, this empty line is hidden when the subtree is folded.
600 Org-mode will leave (exactly) one empty line visible if the number of
601 empty lines is equal or larger to the number given in this variable.
602 So the default 2 means, at least 2 empty lines after the end of a subtree
603 are needed to produce free space between a collapsed subtree and the
604 following headline.
606 Special case: when 0, never leave empty lines in collapsed view."
607 :group 'org-cycle
608 :type 'integer)
609 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
611 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
612 org-cycle-hide-drawers
613 org-cycle-show-empty-lines
614 org-optimize-window-after-visibility-change)
615 "Hook that is run after `org-cycle' has changed the buffer visibility.
616 The function(s) in this hook must accept a single argument which indicates
617 the new state that was set by the most recent `org-cycle' command. The
618 argument is a symbol. After a global state change, it can have the values
619 `overview', `content', or `all'. After a local state change, it can have
620 the values `folded', `children', or `subtree'."
621 :group 'org-cycle
622 :type 'hook)
624 (defgroup org-edit-structure nil
625 "Options concerning structure editing in Org-mode."
626 :tag "Org Edit Structure"
627 :group 'org-structure)
629 (defcustom org-odd-levels-only nil
630 "Non-nil means, skip even levels and only use odd levels for the outline.
631 This has the effect that two stars are being added/taken away in
632 promotion/demotion commands. It also influences how levels are
633 handled by the exporters.
634 Changing it requires restart of `font-lock-mode' to become effective
635 for fontification also in regions already fontified.
636 You may also set this on a per-file basis by adding one of the following
637 lines to the buffer:
639 #+STARTUP: odd
640 #+STARTUP: oddeven"
641 :group 'org-edit-structure
642 :group 'org-font-lock
643 :type 'boolean)
645 (defcustom org-adapt-indentation t
646 "Non-nil means, adapt indentation when promoting and demoting.
647 When this is set and the *entire* text in an entry is indented, the
648 indentation is increased by one space in a demotion command, and
649 decreased by one in a promotion command. If any line in the entry
650 body starts at column 0, indentation is not changed at all."
651 :group 'org-edit-structure
652 :type 'boolean)
654 (defcustom org-special-ctrl-a/e nil
655 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
657 When t, `C-a' will bring back the cursor to the beginning of the
658 headline text, i.e. after the stars and after a possible TODO keyword.
659 In an item, this will be the position after the bullet.
660 When the cursor is already at that position, another `C-a' will bring
661 it to the beginning of the line.
663 `C-e' will jump to the end of the headline, ignoring the presence of tags
664 in the headline. A second `C-e' will then jump to the true end of the
665 line, after any tags.
667 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
668 and only a directly following, identical keypress will bring the cursor
669 to the special positions.
671 This may also be a cons cell where the behavior for `C-a' and `C-e' is
672 set separately."
673 :group 'org-edit-structure
674 :type '(choice
675 (const :tag "off" nil)
676 (const :tag "after stars/bullet and before tags first" t)
677 (const :tag "true line boundary first" reversed)
678 (cons :tag "Set C-a and C-e separately"
679 (choice :tag "Special C-a"
680 (const :tag "off" nil)
681 (const :tag "after stars/bullet first" t)
682 (const :tag "before stars/bullet first" reversed))
683 (choice :tag "Special C-e"
684 (const :tag "off" nil)
685 (const :tag "before tags first" t)
686 (const :tag "after tags first" reversed)))))
687 (if (fboundp 'defvaralias)
688 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
690 (defcustom org-special-ctrl-k nil
691 "Non-nil means `C-k' will behave specially in headlines.
692 When nil, `C-k' will call the default `kill-line' command.
693 When t, the following will happen while the cursor is in the headline:
695 - When the cursor is at the beginning of a headline, kill the entire
696 line and possible the folded subtree below the line.
697 - When in the middle of the headline text, kill the headline up to the tags.
698 - When after the headline text, kill the tags."
699 :group 'org-edit-structure
700 :type 'boolean)
702 (defcustom org-yank-folded-subtrees t
703 "Non-nil means, when yanking subtrees, fold them.
704 If the kill is a single subtree, or a sequence of subtrees, i.e. if
705 it starts with a heading and all other headings in it are either children
706 or siblings, then fold all the subtrees. However, do this only if no
707 text after the yank would be swallowed into a folded tree by this action."
708 :group 'org-edit-structure
709 :type 'boolean)
711 (defcustom org-yank-adjusted-subtrees nil
712 "Non-nil means, when yanking subtrees, adjust the level.
713 With this setting, `org-paste-subtree' is used to insert the subtree, see
714 this function for details."
715 :group 'org-edit-structure
716 :type 'boolean)
718 (defcustom org-M-RET-may-split-line '((default . t))
719 "Non-nil means, M-RET will split the line at the cursor position.
720 When nil, it will go to the end of the line before making a
721 new line.
722 You may also set this option in a different way for different
723 contexts. Valid contexts are:
725 headline when creating a new headline
726 item when creating a new item
727 table in a table field
728 default the value to be used for all contexts not explicitly
729 customized"
730 :group 'org-structure
731 :group 'org-table
732 :type '(choice
733 (const :tag "Always" t)
734 (const :tag "Never" nil)
735 (repeat :greedy t :tag "Individual contexts"
736 (cons
737 (choice :tag "Context"
738 (const headline)
739 (const item)
740 (const table)
741 (const default))
742 (boolean)))))
745 (defcustom org-insert-heading-respect-content nil
746 "Non-nil means, insert new headings after the current subtree.
747 When nil, the new heading is created directly after the current line.
748 The commands \\[org-insert-heading-respect-content] and
749 \\[org-insert-todo-heading-respect-content] turn this variable on
750 for the duration of the command."
751 :group 'org-structure
752 :type 'boolean)
754 (defcustom org-blank-before-new-entry '((heading . auto)
755 (plain-list-item . auto))
756 "Should `org-insert-heading' leave a blank line before new heading/item?
757 The value is an alist, with `heading' and `plain-list-item' as car,
758 and a boolean flag as cdr. For plain lists, if the variable
759 `org-empty-line-terminates-plain-lists' is set, the setting here
760 is ignored and no empty line is inserted, to keep the list in tact."
761 :group 'org-edit-structure
762 :type '(list
763 (cons (const heading)
764 (choice (const :tag "Never" nil)
765 (const :tag "Always" t)
766 (const :tag "Auto" auto)))
767 (cons (const plain-list-item)
768 (choice (const :tag "Never" nil)
769 (const :tag "Always" t)
770 (const :tag "Auto" auto)))))
772 (defcustom org-insert-heading-hook nil
773 "Hook being run after inserting a new heading."
774 :group 'org-edit-structure
775 :type 'hook)
777 (defcustom org-enable-fixed-width-editor t
778 "Non-nil means, lines starting with \":\" are treated as fixed-width.
779 This currently only means, they are never auto-wrapped.
780 When nil, such lines will be treated like ordinary lines.
781 See also the QUOTE keyword."
782 :group 'org-edit-structure
783 :type 'boolean)
785 (defcustom org-edit-src-region-extra nil
786 "Additional regexps to identify regions for editing with `org-edit-src-code'.
787 For examples see the function `org-edit-src-find-region-and-lang'.
788 The regular expression identifying the begin marker should end with a newline,
789 and the regexp marking the end line should start with a newline, to make sure
790 there are kept outside the narrowed region."
791 :group 'org-edit-structure
792 :type '(repeat
793 (list
794 (regexp :tag "begin regexp")
795 (regexp :tag "end regexp")
796 (choice :tag "language"
797 (string :tag "specify")
798 (integer :tag "from match group")
799 (const :tag "from `lang' element")
800 (const :tag "from `style' element")))))
802 (defcustom org-coderef-label-format "(ref:%s)"
803 "The default coderef format.
804 This format string will be used to search for coderef labels in literal
805 examples (EXAMPLE and SRC blocks). The format can be overwritten
806 an individual literal example with the -f option, like
808 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
810 #+END_SRC
812 If you want to use this for HTML export, make sure that the format does
813 not introduce special font-locking, and avoid the HTML special
814 characters `<', `>', and `&'. The reason for this restriction is that
815 the labels are searched for only after htmlize has done its job."
816 :group 'org-edit-structure ; FIXME this is not in the right group
817 :type 'string)
819 (defcustom org-edit-fixed-width-region-mode 'artist-mode
820 "The mode that should be used to edit fixed-width regions.
821 These are the regions where each line starts with a colon."
822 :group 'org-edit-structure
823 :type '(choice
824 (const artist-mode)
825 (const picture-mode)
826 (const fundamental-mode)
827 (function :tag "Other (specify)")))
829 (defcustom org-goto-auto-isearch t
830 "Non-nil means, typing characters in org-goto starts incremental search."
831 :group 'org-edit-structure
832 :type 'boolean)
834 (defgroup org-sparse-trees nil
835 "Options concerning sparse trees in Org-mode."
836 :tag "Org Sparse Trees"
837 :group 'org-structure)
839 (defcustom org-highlight-sparse-tree-matches t
840 "Non-nil means, highlight all matches that define a sparse tree.
841 The highlights will automatically disappear the next time the buffer is
842 changed by an edit command."
843 :group 'org-sparse-trees
844 :type 'boolean)
846 (defcustom org-remove-highlights-with-change t
847 "Non-nil means, any change to the buffer will remove temporary highlights.
848 Such highlights are created by `org-occur' and `org-clock-display'.
849 When nil, `C-c C-c needs to be used to get rid of the highlights.
850 The highlights created by `org-preview-latex-fragment' always need
851 `C-c C-c' to be removed."
852 :group 'org-sparse-trees
853 :group 'org-time
854 :type 'boolean)
857 (defcustom org-occur-hook '(org-first-headline-recenter)
858 "Hook that is run after `org-occur' has constructed a sparse tree.
859 This can be used to recenter the window to show as much of the structure
860 as possible."
861 :group 'org-sparse-trees
862 :type 'hook)
864 (defgroup org-imenu-and-speedbar nil
865 "Options concerning imenu and speedbar in Org-mode."
866 :tag "Org Imenu and Speedbar"
867 :group 'org-structure)
869 (defcustom org-imenu-depth 2
870 "The maximum level for Imenu access to Org-mode headlines.
871 This also applied for speedbar access."
872 :group 'org-imenu-and-speedbar
873 :type 'number)
875 (defgroup org-table nil
876 "Options concerning tables in Org-mode."
877 :tag "Org Table"
878 :group 'org)
880 (defcustom org-enable-table-editor 'optimized
881 "Non-nil means, lines starting with \"|\" are handled by the table editor.
882 When nil, such lines will be treated like ordinary lines.
884 When equal to the symbol `optimized', the table editor will be optimized to
885 do the following:
886 - Automatic overwrite mode in front of whitespace in table fields.
887 This makes the structure of the table stay in tact as long as the edited
888 field does not exceed the column width.
889 - Minimize the number of realigns. Normally, the table is aligned each time
890 TAB or RET are pressed to move to another field. With optimization this
891 happens only if changes to a field might have changed the column width.
892 Optimization requires replacing the functions `self-insert-command',
893 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
894 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
895 very good at guessing when a re-align will be necessary, but you can always
896 force one with \\[org-ctrl-c-ctrl-c].
898 If you would like to use the optimized version in Org-mode, but the
899 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
901 This variable can be used to turn on and off the table editor during a session,
902 but in order to toggle optimization, a restart is required.
904 See also the variable `org-table-auto-blank-field'."
905 :group 'org-table
906 :type '(choice
907 (const :tag "off" nil)
908 (const :tag "on" t)
909 (const :tag "on, optimized" optimized)))
911 (defcustom org-self-insert-cluster-for-undo t
912 "Non-nil means cluster self-insert commands for undo when possible.
913 If this is set, then, like in the Emacs command loop, 20 consequtive
914 characters will be undone together.
915 This is configurable, because there is some impact on typing performance."
916 :group 'org-table
917 :type 'boolean)
919 (defcustom org-table-tab-recognizes-table.el t
920 "Non-nil means, TAB will automatically notice a table.el table.
921 When it sees such a table, it moves point into it and - if necessary -
922 calls `table-recognize-table'."
923 :group 'org-table-editing
924 :type 'boolean)
926 (defgroup org-link nil
927 "Options concerning links in Org-mode."
928 :tag "Org Link"
929 :group 'org)
931 (defvar org-link-abbrev-alist-local nil
932 "Buffer-local version of `org-link-abbrev-alist', which see.
933 The value of this is taken from the #+LINK lines.")
934 (make-variable-buffer-local 'org-link-abbrev-alist-local)
936 (defcustom org-link-abbrev-alist nil
937 "Alist of link abbreviations.
938 The car of each element is a string, to be replaced at the start of a link.
939 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
940 links in Org-mode buffers can have an optional tag after a double colon, e.g.
942 [[linkkey:tag][description]]
944 The 'linkkey' must be a word word, starting with a letter, followed
945 by letters, numbers, '-' or '_'.
947 If REPLACE is a string, the tag will simply be appended to create the link.
948 If the string contains \"%s\", the tag will be inserted there. Alternatively,
949 the placeholder \"%h\" will cause a url-encoded version of the tag to
950 be inserted at that point (see the function `url-hexify-string').
952 REPLACE may also be a function that will be called with the tag as the
953 only argument to create the link, which should be returned as a string.
955 See the manual for examples."
956 :group 'org-link
957 :type '(repeat
958 (cons
959 (string :tag "Protocol")
960 (choice
961 (string :tag "Format")
962 (function)))))
964 (defcustom org-descriptive-links t
965 "Non-nil means, hide link part and only show description of bracket links.
966 Bracket links are like [[link][description]]. This variable sets the initial
967 state in new org-mode buffers. The setting can then be toggled on a
968 per-buffer basis from the Org->Hyperlinks menu."
969 :group 'org-link
970 :type 'boolean)
972 (defcustom org-link-file-path-type 'adaptive
973 "How the path name in file links should be stored.
974 Valid values are:
976 relative Relative to the current directory, i.e. the directory of the file
977 into which the link is being inserted.
978 absolute Absolute path, if possible with ~ for home directory.
979 noabbrev Absolute path, no abbreviation of home directory.
980 adaptive Use relative path for files in the current directory and sub-
981 directories of it. For other files, use an absolute path."
982 :group 'org-link
983 :type '(choice
984 (const relative)
985 (const absolute)
986 (const noabbrev)
987 (const adaptive)))
989 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
990 "Types of links that should be activated in Org-mode files.
991 This is a list of symbols, each leading to the activation of a certain link
992 type. In principle, it does not hurt to turn on most link types - there may
993 be a small gain when turning off unused link types. The types are:
995 bracket The recommended [[link][description]] or [[link]] links with hiding.
996 angular Links in angular brackets that may contain whitespace like
997 <bbdb:Carsten Dominik>.
998 plain Plain links in normal text, no whitespace, like http://google.com.
999 radio Text that is matched by a radio target, see manual for details.
1000 tag Tag settings in a headline (link to tag search).
1001 date Time stamps (link to calendar).
1002 footnote Footnote labels.
1004 Changing this variable requires a restart of Emacs to become effective."
1005 :group 'org-link
1006 :type '(set :greedy t
1007 (const :tag "Double bracket links (new style)" bracket)
1008 (const :tag "Angular bracket links (old style)" angular)
1009 (const :tag "Plain text links" plain)
1010 (const :tag "Radio target matches" radio)
1011 (const :tag "Tags" tag)
1012 (const :tag "Timestamps" date)
1013 (const :tag "Footnotes" footnote)))
1015 (defcustom org-make-link-description-function nil
1016 "Function to use to generate link descriptions from links. If
1017 nil the link location will be used. This function must take two
1018 parameters; the first is the link and the second the description
1019 org-insert-link has generated, and should return the description
1020 to use."
1021 :group 'org-link
1022 :type 'function)
1024 (defgroup org-link-store nil
1025 "Options concerning storing links in Org-mode."
1026 :tag "Org Store Link"
1027 :group 'org-link)
1029 (defcustom org-email-link-description-format "Email %c: %.30s"
1030 "Format of the description part of a link to an email or usenet message.
1031 The following %-escapes will be replaced by corresponding information:
1033 %F full \"From\" field
1034 %f name, taken from \"From\" field, address if no name
1035 %T full \"To\" field
1036 %t first name in \"To\" field, address if no name
1037 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1038 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1039 %s subject
1040 %m message-id.
1042 You may use normal field width specification between the % and the letter.
1043 This is for example useful to limit the length of the subject.
1045 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1046 :group 'org-link-store
1047 :type 'string)
1049 (defcustom org-from-is-user-regexp
1050 (let (r1 r2)
1051 (when (and user-mail-address (not (string= user-mail-address "")))
1052 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1053 (when (and user-full-name (not (string= user-full-name "")))
1054 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1055 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1056 "Regexp matched against the \"From:\" header of an email or usenet message.
1057 It should match if the message is from the user him/herself."
1058 :group 'org-link-store
1059 :type 'regexp)
1061 (defcustom org-link-to-org-use-id 'create-if-interactive
1062 "Non-nil means, storing a link to an Org file will use entry IDs.
1064 Note that before this variable is even considered, org-id must be loaded,
1065 to please customize `org-modules' and turn it on.
1067 The variable can have the following values:
1069 t Create an ID if needed to make a link to the current entry.
1071 create-if-interactive
1072 If `org-store-link' is called directly (interactively, as a user
1073 command), do create an ID to support the link. But when doing the
1074 job for remember, only use the ID if it already exists. The
1075 purpose of this setting is to avoid proliferation of unwanted
1076 IDs, just because you happen to be in an Org file when you
1077 call `org-remember' that automatically and preemptively
1078 creates a link. If you do want to get an ID link in a remember
1079 template to an entry not having an ID, create it first by
1080 explicitly creating a link to it, using `C-c C-l' first.
1082 use-existing
1083 Use existing ID, do not create one.
1085 nil Never use an ID to make a link, instead link using a text search for
1086 the headline text."
1087 :group 'org-link-store
1088 :type '(choice
1089 (const :tag "Create ID to make link" t)
1090 (const :tag "Create if string link interactively"
1091 'create-if-interactive)
1092 (const :tag "Only use existing" 'use-existing)
1093 (const :tag "Do not use ID to create link" nil)))
1095 (defcustom org-context-in-file-links t
1096 "Non-nil means, file links from `org-store-link' contain context.
1097 A search string will be added to the file name with :: as separator and
1098 used to find the context when the link is activated by the command
1099 `org-open-at-point'.
1100 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1101 negates this setting for the duration of the command."
1102 :group 'org-link-store
1103 :type 'boolean)
1105 (defcustom org-keep-stored-link-after-insertion nil
1106 "Non-nil means, keep link in list for entire session.
1108 The command `org-store-link' adds a link pointing to the current
1109 location to an internal list. These links accumulate during a session.
1110 The command `org-insert-link' can be used to insert links into any
1111 Org-mode file (offering completion for all stored links). When this
1112 option is nil, every link which has been inserted once using \\[org-insert-link]
1113 will be removed from the list, to make completing the unused links
1114 more efficient."
1115 :group 'org-link-store
1116 :type 'boolean)
1118 (defgroup org-link-follow nil
1119 "Options concerning following links in Org-mode."
1120 :tag "Org Follow Link"
1121 :group 'org-link)
1123 (defcustom org-link-translation-function nil
1124 "Function to translate links with different syntax to Org syntax.
1125 This can be used to translate links created for example by the Planner
1126 or emacs-wiki packages to Org syntax.
1127 The function must accept two parameters, a TYPE containing the link
1128 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1129 which is everything after the link protocol. It should return a cons
1130 with possibly modified values of type and path.
1131 Org contains a function for this, so if you set this variable to
1132 `org-translate-link-from-planner', you should be able follow many
1133 links created by planner."
1134 :group 'org-link-follow
1135 :type 'function)
1137 (defcustom org-follow-link-hook nil
1138 "Hook that is run after a link has been followed."
1139 :group 'org-link-follow
1140 :type 'hook)
1142 (defcustom org-tab-follows-link nil
1143 "Non-nil means, on links TAB will follow the link.
1144 Needs to be set before org.el is loaded.
1145 This really should not be used, it does not make sense, and the
1146 implementation is bad."
1147 :group 'org-link-follow
1148 :type 'boolean)
1150 (defcustom org-return-follows-link nil
1151 "Non-nil means, on links RET will follow the link.
1152 Needs to be set before org.el is loaded."
1153 :group 'org-link-follow
1154 :type 'boolean)
1156 (defcustom org-mouse-1-follows-link
1157 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1158 "Non-nil means, mouse-1 on a link will follow the link.
1159 A longer mouse click will still set point. Does not work on XEmacs.
1160 Needs to be set before org.el is loaded."
1161 :group 'org-link-follow
1162 :type 'boolean)
1164 (defcustom org-mark-ring-length 4
1165 "Number of different positions to be recorded in the ring
1166 Changing this requires a restart of Emacs to work correctly."
1167 :group 'org-link-follow
1168 :type 'integer)
1170 (defcustom org-link-frame-setup
1171 '((vm . vm-visit-folder-other-frame)
1172 (gnus . gnus-other-frame)
1173 (file . find-file-other-window))
1174 "Setup the frame configuration for following links.
1175 When following a link with Emacs, it may often be useful to display
1176 this link in another window or frame. This variable can be used to
1177 set this up for the different types of links.
1178 For VM, use any of
1179 `vm-visit-folder'
1180 `vm-visit-folder-other-frame'
1181 For Gnus, use any of
1182 `gnus'
1183 `gnus-other-frame'
1184 `org-gnus-no-new-news'
1185 For FILE, use any of
1186 `find-file'
1187 `find-file-other-window'
1188 `find-file-other-frame'
1189 For the calendar, use the variable `calendar-setup'.
1190 For BBDB, it is currently only possible to display the matches in
1191 another window."
1192 :group 'org-link-follow
1193 :type '(list
1194 (cons (const vm)
1195 (choice
1196 (const vm-visit-folder)
1197 (const vm-visit-folder-other-window)
1198 (const vm-visit-folder-other-frame)))
1199 (cons (const gnus)
1200 (choice
1201 (const gnus)
1202 (const gnus-other-frame)
1203 (const org-gnus-no-new-news)))
1204 (cons (const file)
1205 (choice
1206 (const find-file)
1207 (const find-file-other-window)
1208 (const find-file-other-frame)))))
1210 (defcustom org-display-internal-link-with-indirect-buffer nil
1211 "Non-nil means, use indirect buffer to display infile links.
1212 Activating internal links (from one location in a file to another location
1213 in the same file) normally just jumps to the location. When the link is
1214 activated with a C-u prefix (or with mouse-3), the link is displayed in
1215 another window. When this option is set, the other window actually displays
1216 an indirect buffer clone of the current buffer, to avoid any visibility
1217 changes to the current buffer."
1218 :group 'org-link-follow
1219 :type 'boolean)
1221 (defcustom org-open-non-existing-files nil
1222 "Non-nil means, `org-open-file' will open non-existing files.
1223 When nil, an error will be generated."
1224 :group 'org-link-follow
1225 :type 'boolean)
1227 (defcustom org-open-directory-means-index-dot-org nil
1228 "Non-nil means, a link to a directory really means to index.org.
1229 When nil, following a directory link will run dired or open a finder/explorer
1230 window on that directory."
1231 :group 'org-link-follow
1232 :type 'boolean)
1234 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1235 "Function and arguments to call for following mailto links.
1236 This is a list with the first element being a lisp function, and the
1237 remaining elements being arguments to the function. In string arguments,
1238 %a will be replaced by the address, and %s will be replaced by the subject
1239 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1240 :group 'org-link-follow
1241 :type '(choice
1242 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1243 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1244 (const :tag "message-mail" (message-mail "%a" "%s"))
1245 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1247 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1248 "Non-nil means, ask for confirmation before executing shell links.
1249 Shell links can be dangerous: just think about a link
1251 [[shell:rm -rf ~/*][Google Search]]
1253 This link would show up in your Org-mode document as \"Google Search\",
1254 but really it would remove your entire home directory.
1255 Therefore we advise against setting this variable to nil.
1256 Just change it to `y-or-n-p' if you want to confirm with a
1257 single keystroke rather than having to type \"yes\"."
1258 :group 'org-link-follow
1259 :type '(choice
1260 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1261 (const :tag "with y-or-n (faster)" y-or-n-p)
1262 (const :tag "no confirmation (dangerous)" nil)))
1264 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1265 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1266 Elisp links can be dangerous: just think about a link
1268 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1270 This link would show up in your Org-mode document as \"Google Search\",
1271 but really it would remove your entire home directory.
1272 Therefore we advise against setting this variable to nil.
1273 Just change it to `y-or-n-p' if you want to confirm with a
1274 single keystroke rather than having to type \"yes\"."
1275 :group 'org-link-follow
1276 :type '(choice
1277 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1278 (const :tag "with y-or-n (faster)" y-or-n-p)
1279 (const :tag "no confirmation (dangerous)" nil)))
1281 (defconst org-file-apps-defaults-gnu
1282 '((remote . emacs)
1283 (system . mailcap)
1284 (t . mailcap))
1285 "Default file applications on a UNIX or GNU/Linux system.
1286 See `org-file-apps'.")
1288 (defconst org-file-apps-defaults-macosx
1289 '((remote . emacs)
1290 (t . "open %s")
1291 (system . "open %s")
1292 ("ps.gz" . "gv %s")
1293 ("eps.gz" . "gv %s")
1294 ("dvi" . "xdvi %s")
1295 ("fig" . "xfig %s"))
1296 "Default file applications on a MacOS X system.
1297 The system \"open\" is known as a default, but we use X11 applications
1298 for some files for which the OS does not have a good default.
1299 See `org-file-apps'.")
1301 (defconst org-file-apps-defaults-windowsnt
1302 (list
1303 '(remote . emacs)
1304 (cons t
1305 (list (if (featurep 'xemacs)
1306 'mswindows-shell-execute
1307 'w32-shell-execute)
1308 "open" 'file))
1309 (cons 'system
1310 (list (if (featurep 'xemacs)
1311 'mswindows-shell-execute
1312 'w32-shell-execute)
1313 "open" 'file)))
1314 "Default file applications on a Windows NT system.
1315 The system \"open\" is used for most files.
1316 See `org-file-apps'.")
1318 (defcustom org-file-apps
1320 (auto-mode . emacs)
1321 ("\\.x?html?\\'" . default)
1322 ("\\.pdf\\'" . default)
1324 "External applications for opening `file:path' items in a document.
1325 Org-mode uses system defaults for different file types, but
1326 you can use this variable to set the application for a given file
1327 extension. The entries in this list are cons cells where the car identifies
1328 files and the cdr the corresponding command. Possible values for the
1329 file identifier are
1330 \"regex\" Regular expression matched against the file name. For backward
1331 compatibility, this can also be a string with only alphanumeric
1332 characters, which is then interpreted as an extension.
1333 `directory' Matches a directory
1334 `remote' Matches a remote file, accessible through tramp or efs.
1335 Remote files most likely should be visited through Emacs
1336 because external applications cannot handle such paths.
1337 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1338 so all files Emacs knows how to handle. Using this with
1339 command `emacs' will open most files in Emacs. Beware that this
1340 will also open html files inside Emacs, unless you add
1341 (\"html\" . default) to the list as well.
1342 t Default for files not matched by any of the other options.
1343 `system' The system command to open files, like `open' on Windows
1344 and Mac OS X, and mailcap under GNU/Linux. This is the command
1345 that will be selected if you call `C-c C-o' with a double
1346 `C-u C-u' prefix.
1348 Possible values for the command are:
1349 `emacs' The file will be visited by the current Emacs process.
1350 `default' Use the default application for this file type, which is the
1351 association for t in the list, most likely in the system-specific
1352 part.
1353 This can be used to overrule an unwanted setting in the
1354 system-specific variable.
1355 `system' Use the system command for opening files, like \"open\".
1356 This command is specified by the entry whose car is `system'.
1357 Most likely, the system-specific version of this variable
1358 does define this command, but you can overrule/replace it
1359 here.
1360 string A command to be executed by a shell; %s will be replaced
1361 by the path to the file.
1362 sexp A Lisp form which will be evaluated. The file path will
1363 be available in the Lisp variable `file'.
1364 For more examples, see the system specific constants
1365 `org-file-apps-defaults-macosx'
1366 `org-file-apps-defaults-windowsnt'
1367 `org-file-apps-defaults-gnu'."
1368 :group 'org-link-follow
1369 :type '(repeat
1370 (cons (choice :value ""
1371 (string :tag "Extension")
1372 (const :tag "System command to open files" system)
1373 (const :tag "Default for unrecognized files" t)
1374 (const :tag "Remote file" remote)
1375 (const :tag "Links to a directory" directory)
1376 (const :tag "Any files that have Emacs modes"
1377 auto-mode))
1378 (choice :value ""
1379 (const :tag "Visit with Emacs" emacs)
1380 (const :tag "Use default" default)
1381 (const :tag "Use the system command" system)
1382 (string :tag "Command")
1383 (sexp :tag "Lisp form")))))
1385 (defgroup org-refile nil
1386 "Options concerning refiling entries in Org-mode."
1387 :tag "Org Refile"
1388 :group 'org)
1390 (defcustom org-directory "~/org"
1391 "Directory with org files.
1392 This is just a default location to look for Org files. There is no need
1393 at all to put your files into this directory. It is only used in the
1394 following situations:
1396 1. When a remember template specifies a target file that is not an
1397 absolute path. The path will then be interpreted relative to
1398 `org-directory'
1399 2. When a remember note is filed away in an interactive way (when exiting the
1400 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1401 with `org-directory' as the default path."
1402 :group 'org-refile
1403 :group 'org-remember
1404 :type 'directory)
1406 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1407 "Default target for storing notes.
1408 Used by the hooks for remember.el. This can be a string, or nil to mean
1409 the value of `remember-data-file'.
1410 You can set this on a per-template basis with the variable
1411 `org-remember-templates'."
1412 :group 'org-refile
1413 :group 'org-remember
1414 :type '(choice
1415 (const :tag "Default from remember-data-file" nil)
1416 file))
1418 (defcustom org-goto-interface 'outline
1419 "The default interface to be used for `org-goto'.
1420 Allowed values are:
1421 outline The interface shows an outline of the relevant file
1422 and the correct heading is found by moving through
1423 the outline or by searching with incremental search.
1424 outline-path-completion Headlines in the current buffer are offered via
1425 completion. This is the interface also used by
1426 the refile command."
1427 :group 'org-refile
1428 :type '(choice
1429 (const :tag "Outline" outline)
1430 (const :tag "Outline-path-completion" outline-path-completion)))
1432 (defcustom org-goto-max-level 5
1433 "Maximum level to be considered when running org-goto with refile interface."
1434 :group 'org-refile
1435 :type 'number)
1437 (defcustom org-reverse-note-order nil
1438 "Non-nil means, store new notes at the beginning of a file or entry.
1439 When nil, new notes will be filed to the end of a file or entry.
1440 This can also be a list with cons cells of regular expressions that
1441 are matched against file names, and values."
1442 :group 'org-remember
1443 :group 'org-refile
1444 :type '(choice
1445 (const :tag "Reverse always" t)
1446 (const :tag "Reverse never" nil)
1447 (repeat :tag "By file name regexp"
1448 (cons regexp boolean))))
1450 (defcustom org-refile-targets nil
1451 "Targets for refiling entries with \\[org-refile].
1452 This is list of cons cells. Each cell contains:
1453 - a specification of the files to be considered, either a list of files,
1454 or a symbol whose function or variable value will be used to retrieve
1455 a file name or a list of file names. If you use `org-agenda-files' for
1456 that, all agenda files will be scanned for targets. Nil means, consider
1457 headings in the current buffer.
1458 - A specification of how to find candidate refile targets. This may be
1459 any of:
1460 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1461 This tag has to be present in all target headlines, inheritance will
1462 not be considered.
1463 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1464 todo keyword.
1465 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1466 headlines that are refiling targets.
1467 - a cons cell (:level . N). Any headline of level N is considered a target.
1468 Note that, when `org-odd-levels-only' is set, level corresponds to
1469 order in hierarchy, not to the number of stars.
1470 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1471 Note that, when `org-odd-levels-only' is set, level corresponds to
1472 order in hierarchy, not to the number of stars.
1474 When this variable is nil, all top-level headlines in the current buffer
1475 are used, equivalent to the value `((nil . (:level . 1))'."
1476 :group 'org-refile
1477 :type '(repeat
1478 (cons
1479 (choice :value org-agenda-files
1480 (const :tag "All agenda files" org-agenda-files)
1481 (const :tag "Current buffer" nil)
1482 (function) (variable) (file))
1483 (choice :tag "Identify target headline by"
1484 (cons :tag "Specific tag" (const :value :tag) (string))
1485 (cons :tag "TODO keyword" (const :value :todo) (string))
1486 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1487 (cons :tag "Level number" (const :value :level) (integer))
1488 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1490 (defcustom org-refile-use-outline-path nil
1491 "Non-nil means, provide refile targets as paths.
1492 So a level 3 headline will be available as level1/level2/level3.
1493 When the value is `file', also include the file name (without directory)
1494 into the path. When `full-file-path', include the full file path."
1495 :group 'org-refile
1496 :type '(choice
1497 (const :tag "Not" nil)
1498 (const :tag "Yes" t)
1499 (const :tag "Start with file name" file)
1500 (const :tag "Start with full file path" full-file-path)))
1502 (defcustom org-outline-path-complete-in-steps t
1503 "Non-nil means, complete the outline path in hierarchical steps.
1504 When Org-mode uses the refile interface to select an outline path
1505 \(see variable `org-refile-use-outline-path'), the completion of
1506 the path can be done is a single go, or if can be done in steps down
1507 the headline hierarchy. Going in steps is probably the best if you
1508 do not use a special completion package like `ido' or `icicles'.
1509 However, when using these packages, going in one step can be very
1510 fast, while still showing the whole path to the entry."
1511 :group 'org-refile
1512 :type 'boolean)
1514 (defgroup org-todo nil
1515 "Options concerning TODO items in Org-mode."
1516 :tag "Org TODO"
1517 :group 'org)
1519 (defgroup org-progress nil
1520 "Options concerning Progress logging in Org-mode."
1521 :tag "Org Progress"
1522 :group 'org-time)
1524 (defvar org-todo-interpretation-widgets
1526 (:tag "Sequence (cycling hits every state)" sequence)
1527 (:tag "Type (cycling directly to DONE)" type))
1528 "The available interpretation symbols for customizing
1529 `org-todo-keywords'.
1530 Interested libraries should add to this list.")
1532 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1533 "List of TODO entry keyword sequences and their interpretation.
1534 \\<org-mode-map>This is a list of sequences.
1536 Each sequence starts with a symbol, either `sequence' or `type',
1537 indicating if the keywords should be interpreted as a sequence of
1538 action steps, or as different types of TODO items. The first
1539 keywords are states requiring action - these states will select a headline
1540 for inclusion into the global TODO list Org-mode produces. If one of
1541 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1542 signify that no further action is necessary. If \"|\" is not found,
1543 the last keyword is treated as the only DONE state of the sequence.
1545 The command \\[org-todo] cycles an entry through these states, and one
1546 additional state where no keyword is present. For details about this
1547 cycling, see the manual.
1549 TODO keywords and interpretation can also be set on a per-file basis with
1550 the special #+SEQ_TODO and #+TYP_TODO lines.
1552 Each keyword can optionally specify a character for fast state selection
1553 \(in combination with the variable `org-use-fast-todo-selection')
1554 and specifiers for state change logging, using the same syntax
1555 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1556 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1557 indicates to record a time stamp each time this state is selected.
1559 Each keyword may also specify if a timestamp or a note should be
1560 recorded when entering or leaving the state, by adding additional
1561 characters in the parenthesis after the keyword. This looks like this:
1562 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1563 record only the time of the state change. With X and Y being either
1564 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1565 Y when leaving the state if and only if the *target* state does not
1566 define X. You may omit any of the fast-selection key or X or /Y,
1567 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1569 For backward compatibility, this variable may also be just a list
1570 of keywords - in this case the interpretation (sequence or type) will be
1571 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1572 :group 'org-todo
1573 :group 'org-keywords
1574 :type '(choice
1575 (repeat :tag "Old syntax, just keywords"
1576 (string :tag "Keyword"))
1577 (repeat :tag "New syntax"
1578 (cons
1579 (choice
1580 :tag "Interpretation"
1581 ;;Quick and dirty way to see
1582 ;;`org-todo-interpretations'. This takes the
1583 ;;place of item arguments
1584 :convert-widget
1585 (lambda (widget)
1586 (widget-put widget
1587 :args (mapcar
1588 #'(lambda (x)
1589 (widget-convert
1590 (cons 'const x)))
1591 org-todo-interpretation-widgets))
1592 widget))
1593 (repeat
1594 (string :tag "Keyword"))))))
1596 (defvar org-todo-keywords-1 nil
1597 "All TODO and DONE keywords active in a buffer.")
1598 (make-variable-buffer-local 'org-todo-keywords-1)
1599 (defvar org-todo-keywords-for-agenda nil)
1600 (defvar org-done-keywords-for-agenda nil)
1601 (defvar org-todo-keyword-alist-for-agenda nil)
1602 (defvar org-tag-alist-for-agenda nil)
1603 (defvar org-agenda-contributing-files nil)
1604 (defvar org-not-done-keywords nil)
1605 (make-variable-buffer-local 'org-not-done-keywords)
1606 (defvar org-done-keywords nil)
1607 (make-variable-buffer-local 'org-done-keywords)
1608 (defvar org-todo-heads nil)
1609 (make-variable-buffer-local 'org-todo-heads)
1610 (defvar org-todo-sets nil)
1611 (make-variable-buffer-local 'org-todo-sets)
1612 (defvar org-todo-log-states nil)
1613 (make-variable-buffer-local 'org-todo-log-states)
1614 (defvar org-todo-kwd-alist nil)
1615 (make-variable-buffer-local 'org-todo-kwd-alist)
1616 (defvar org-todo-key-alist nil)
1617 (make-variable-buffer-local 'org-todo-key-alist)
1618 (defvar org-todo-key-trigger nil)
1619 (make-variable-buffer-local 'org-todo-key-trigger)
1621 (defcustom org-todo-interpretation 'sequence
1622 "Controls how TODO keywords are interpreted.
1623 This variable is in principle obsolete and is only used for
1624 backward compatibility, if the interpretation of todo keywords is
1625 not given already in `org-todo-keywords'. See that variable for
1626 more information."
1627 :group 'org-todo
1628 :group 'org-keywords
1629 :type '(choice (const sequence)
1630 (const type)))
1632 (defcustom org-use-fast-todo-selection t
1633 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1634 This variable describes if and under what circumstances the cycling
1635 mechanism for TODO keywords will be replaced by a single-key, direct
1636 selection scheme.
1638 When nil, fast selection is never used.
1640 When the symbol `prefix', it will be used when `org-todo' is called with
1641 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1642 in an agenda buffer.
1644 When t, fast selection is used by default. In this case, the prefix
1645 argument forces cycling instead.
1647 In all cases, the special interface is only used if access keys have actually
1648 been assigned by the user, i.e. if keywords in the configuration are followed
1649 by a letter in parenthesis, like TODO(t)."
1650 :group 'org-todo
1651 :type '(choice
1652 (const :tag "Never" nil)
1653 (const :tag "By default" t)
1654 (const :tag "Only with C-u C-c C-t" prefix)))
1656 (defcustom org-provide-todo-statistics t
1657 "Non-nil means, update todo statistics after insert and toggle.
1658 When this is set, todo statistics is updated in the parent of the current
1659 entry each time a todo state is changed."
1660 :group 'org-todo
1661 :type 'boolean)
1663 (defcustom org-after-todo-state-change-hook nil
1664 "Hook which is run after the state of a TODO item was changed.
1665 The new state (a string with a TODO keyword, or nil) is available in the
1666 Lisp variable `state'."
1667 :group 'org-todo
1668 :type 'hook)
1670 (defvar org-blocker-hook nil
1671 "Hook for functions that are allowed to block a state change.
1673 Each function gets as its single argument a property list, see
1674 `org-trigger-hook' for more information about this list.
1676 If any of the functions in this hook returns nil, the state change
1677 is blocked.")
1679 (defvar org-trigger-hook nil
1680 "Hook for functions that are triggered by a state change.
1682 Each function gets as its single argument a property list with at least
1683 the following elements:
1685 (:type type-of-change :position pos-at-entry-start
1686 :from old-state :to new-state)
1688 Depending on the type, more properties may be present.
1690 This mechanism is currently implemented for:
1692 TODO state changes
1693 ------------------
1694 :type todo-state-change
1695 :from previous state (keyword as a string), or nil, or a symbol
1696 'todo' or 'done', to indicate the general type of state.
1697 :to new state, like in :from")
1699 (defcustom org-enforce-todo-dependencies nil
1700 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1701 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1702 be blocked if any prior sibling is not yet done.
1703 This variable needs to be set before org.el is loaded, and you need to
1704 restart Emacs after a change to make the change effective. The only way
1705 to change is while Emacs is running is through the customize interface."
1706 :set (lambda (var val)
1707 (set var val)
1708 (if val
1709 (add-hook 'org-blocker-hook
1710 'org-block-todo-from-children-or-siblings)
1711 (remove-hook 'org-blocker-hook
1712 'org-block-todo-from-children-or-siblings)))
1713 :group 'org-todo
1714 :type 'boolean)
1716 (defcustom org-enforce-todo-checkbox-dependencies nil
1717 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1718 When this is nil, checkboxes have no influence on switching TODO states.
1719 When non-nil, you first need to check off all check boxes before the TODO
1720 entry can be switched to DONE.
1721 This variable needs to be set before org.el is loaded, and you need to
1722 restart Emacs after a change to make the change effective. The only way
1723 to change is while Emacs is running is through the customize interface."
1724 :set (lambda (var val)
1725 (set var val)
1726 (if val
1727 (add-hook 'org-blocker-hook
1728 'org-block-todo-from-checkboxes)
1729 (remove-hook 'org-blocker-hook
1730 'org-block-todo-from-checkboxes)))
1731 :group 'org-todo
1732 :type 'boolean)
1734 (defcustom org-todo-state-tags-triggers nil
1735 "Tag changes that should be triggered by TODO state changes.
1736 This is a list. Each entry is
1738 (state-change (tag . flag) .......)
1740 State-change can be a string with a state, and empty string to indicate the
1741 state that has no TODO keyword, or it can be one of the symbols `todo'
1742 or `done', meaning any not-done or done state, respectively."
1743 :group 'org-todo
1744 :group 'org-tags
1745 :type '(repeat
1746 (cons (choice :tag "When changing to"
1747 (const :tag "Not-done state" todo)
1748 (const :tag "Done state" done)
1749 (string :tag "State"))
1750 (repeat
1751 (cons :tag "Tag action"
1752 (string :tag "Tag")
1753 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1755 (defcustom org-log-done nil
1756 "Information to record when a task moves to the DONE state.
1758 Possible values are:
1760 nil Don't add anything, just change the keyword
1761 time Add a time stamp to the task
1762 note Prompt a closing note and add it with template `org-log-note-headings'
1764 This option can also be set with on a per-file-basis with
1766 #+STARTUP: nologdone
1767 #+STARTUP: logdone
1768 #+STARTUP: lognotedone
1770 You can have local logging settings for a subtree by setting the LOGGING
1771 property to one or more of these keywords."
1772 :group 'org-todo
1773 :group 'org-progress
1774 :type '(choice
1775 (const :tag "No logging" nil)
1776 (const :tag "Record CLOSED timestamp" time)
1777 (const :tag "Record CLOSED timestamp with closing note." note)))
1779 ;; Normalize old uses of org-log-done.
1780 (cond
1781 ((eq org-log-done t) (setq org-log-done 'time))
1782 ((and (listp org-log-done) (memq 'done org-log-done))
1783 (setq org-log-done 'note)))
1785 (defcustom org-log-note-clock-out nil
1786 "Non-nil means, record a note when clocking out of an item.
1787 This can also be configured on a per-file basis by adding one of
1788 the following lines anywhere in the buffer:
1790 #+STARTUP: lognoteclock-out
1791 #+STARTUP: nolognoteclock-out"
1792 :group 'org-todo
1793 :group 'org-progress
1794 :type 'boolean)
1796 (defcustom org-log-done-with-time t
1797 "Non-nil means, the CLOSED time stamp will contain date and time.
1798 When nil, only the date will be recorded."
1799 :group 'org-progress
1800 :type 'boolean)
1802 (defcustom org-log-note-headings
1803 '((done . "CLOSING NOTE %t")
1804 (state . "State %-12s from %-12S %t")
1805 (note . "Note taken on %t")
1806 (clock-out . ""))
1807 "Headings for notes added to entries.
1808 The value is an alist, with the car being a symbol indicating the note
1809 context, and the cdr is the heading to be used. The heading may also be the
1810 empty string.
1811 %t in the heading will be replaced by a time stamp.
1812 %s will be replaced by the new TODO state, in double quotes.
1813 %S will be replaced by the old TODO state, in double quotes.
1814 %u will be replaced by the user name.
1815 %U will be replaced by the full user name."
1816 :group 'org-todo
1817 :group 'org-progress
1818 :type '(list :greedy t
1819 (cons (const :tag "Heading when closing an item" done) string)
1820 (cons (const :tag
1821 "Heading when changing todo state (todo sequence only)"
1822 state) string)
1823 (cons (const :tag "Heading when just taking a note" note) string)
1824 (cons (const :tag "Heading when clocking out" clock-out) string)))
1826 (unless (assq 'note org-log-note-headings)
1827 (push '(note . "%t") org-log-note-headings))
1829 (defcustom org-log-into-drawer nil
1830 "Non-nil means, insert state change notes and time stamps into a drawer.
1831 When nil, state changes notes will be inserted after the headline and
1832 any scheduling and clock lines, but not inside a drawer.
1834 The value of this variable should be the name of the drawer to use.
1835 LOGBOOK is proposed at the default drawer for this purpose, you can
1836 also set this to a string to define the drawer of your choice.
1838 A value of t is also allowed, representing \"LOGBOOK\".
1840 If this variable is set, `org-log-state-notes-insert-after-drawers'
1841 will be ignored."
1842 :group 'org-todo
1843 :group 'org-progress
1844 :type '(choice
1845 (const :tag "Not into a drawer" nil)
1846 (const :tag "LOGBOOK" t)
1847 (string :tag "Other")))
1849 (if (fboundp 'defvaralias)
1850 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1852 (defcustom org-log-state-notes-insert-after-drawers nil
1853 "Non-nil means, insert state change notes after any drawers in entry.
1854 Only the drawers that *immediately* follow the headline and the
1855 deadline/scheduled line are skipped.
1856 When nil, insert notes right after the heading and perhaps the line
1857 with deadline/scheduling if present.
1859 This variable will have no effect if `org-log-into-drawer' is
1860 set."
1861 :group 'org-todo
1862 :group 'org-progress
1863 :type 'boolean)
1865 (defcustom org-log-states-order-reversed t
1866 "Non-nil means, the latest state change note will be directly after heading.
1867 When nil, the notes will be orderer according to time."
1868 :group 'org-todo
1869 :group 'org-progress
1870 :type 'boolean)
1872 (defcustom org-log-repeat 'time
1873 "Non-nil means, record moving through the DONE state when triggering repeat.
1874 An auto-repeating tasks is immediately switched back to TODO when marked
1875 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1876 the TODO keyword definition, or recording a closing note by setting
1877 `org-log-done', there will be no record of the task moving through DONE.
1878 This variable forces taking a note anyway. Possible values are:
1880 nil Don't force a record
1881 time Record a time stamp
1882 note Record a note
1884 This option can also be set with on a per-file-basis with
1886 #+STARTUP: logrepeat
1887 #+STARTUP: lognoterepeat
1888 #+STARTUP: nologrepeat
1890 You can have local logging settings for a subtree by setting the LOGGING
1891 property to one or more of these keywords."
1892 :group 'org-todo
1893 :group 'org-progress
1894 :type '(choice
1895 (const :tag "Don't force a record" nil)
1896 (const :tag "Force recording the DONE state" time)
1897 (const :tag "Force recording a note with the DONE state" note)))
1900 (defgroup org-priorities nil
1901 "Priorities in Org-mode."
1902 :tag "Org Priorities"
1903 :group 'org-todo)
1905 (defcustom org-highest-priority ?A
1906 "The highest priority of TODO items. A character like ?A, ?B etc.
1907 Must have a smaller ASCII number than `org-lowest-priority'."
1908 :group 'org-priorities
1909 :type 'character)
1911 (defcustom org-lowest-priority ?C
1912 "The lowest priority of TODO items. A character like ?A, ?B etc.
1913 Must have a larger ASCII number than `org-highest-priority'."
1914 :group 'org-priorities
1915 :type 'character)
1917 (defcustom org-default-priority ?B
1918 "The default priority of TODO items.
1919 This is the priority an item get if no explicit priority is given."
1920 :group 'org-priorities
1921 :type 'character)
1923 (defcustom org-priority-start-cycle-with-default t
1924 "Non-nil means, start with default priority when starting to cycle.
1925 When this is nil, the first step in the cycle will be (depending on the
1926 command used) one higher or lower that the default priority."
1927 :group 'org-priorities
1928 :type 'boolean)
1930 (defgroup org-time nil
1931 "Options concerning time stamps and deadlines in Org-mode."
1932 :tag "Org Time"
1933 :group 'org)
1935 (defcustom org-insert-labeled-timestamps-at-point nil
1936 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1937 When nil, these labeled time stamps are forces into the second line of an
1938 entry, just after the headline. When scheduling from the global TODO list,
1939 the time stamp will always be forced into the second line."
1940 :group 'org-time
1941 :type 'boolean)
1943 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1944 "Formats for `format-time-string' which are used for time stamps.
1945 It is not recommended to change this constant.")
1947 (defcustom org-time-stamp-rounding-minutes '(0 5)
1948 "Number of minutes to round time stamps to.
1949 These are two values, the first applies when first creating a time stamp.
1950 The second applies when changing it with the commands `S-up' and `S-down'.
1951 When changing the time stamp, this means that it will change in steps
1952 of N minutes, as given by the second value.
1954 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1955 numbers should be factors of 60, so for example 5, 10, 15.
1957 When this is larger than 1, you can still force an exact time-stamp by using
1958 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1959 and by using a prefix arg to `S-up/down' to specify the exact number
1960 of minutes to shift."
1961 :group 'org-time
1962 :get '(lambda (var) ; Make sure all entries have 5 elements
1963 (if (integerp (default-value var))
1964 (list (default-value var) 5)
1965 (default-value var)))
1966 :type '(list
1967 (integer :tag "when inserting times")
1968 (integer :tag "when modifying times")))
1970 ;; Normalize old customizations of this variable.
1971 (when (integerp org-time-stamp-rounding-minutes)
1972 (setq org-time-stamp-rounding-minutes
1973 (list org-time-stamp-rounding-minutes
1974 org-time-stamp-rounding-minutes)))
1976 (defcustom org-display-custom-times nil
1977 "Non-nil means, overlay custom formats over all time stamps.
1978 The formats are defined through the variable `org-time-stamp-custom-formats'.
1979 To turn this on on a per-file basis, insert anywhere in the file:
1980 #+STARTUP: customtime"
1981 :group 'org-time
1982 :set 'set-default
1983 :type 'sexp)
1984 (make-variable-buffer-local 'org-display-custom-times)
1986 (defcustom org-time-stamp-custom-formats
1987 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1988 "Custom formats for time stamps. See `format-time-string' for the syntax.
1989 These are overlayed over the default ISO format if the variable
1990 `org-display-custom-times' is set. Time like %H:%M should be at the
1991 end of the second format."
1992 :group 'org-time
1993 :type 'sexp)
1995 (defun org-time-stamp-format (&optional long inactive)
1996 "Get the right format for a time string."
1997 (let ((f (if long (cdr org-time-stamp-formats)
1998 (car org-time-stamp-formats))))
1999 (if inactive
2000 (concat "[" (substring f 1 -1) "]")
2001 f)))
2003 (defcustom org-time-clocksum-format "%d:%02d"
2004 "The format string used when creating CLOCKSUM lines, or when
2005 org-mode generates a time duration."
2006 :group 'org-time
2007 :type 'string)
2009 (defcustom org-deadline-warning-days 14
2010 "No. of days before expiration during which a deadline becomes active.
2011 This variable governs the display in sparse trees and in the agenda.
2012 When 0 or negative, it means use this number (the absolute value of it)
2013 even if a deadline has a different individual lead time specified.
2015 Custom commands can set this variable in the options section."
2016 :group 'org-time
2017 :group 'org-agenda-daily/weekly
2018 :type 'number)
2020 (defcustom org-read-date-prefer-future t
2021 "Non-nil means, assume future for incomplete date input from user.
2022 This affects the following situations:
2023 1. The user gives a day, but no month.
2024 For example, if today is the 15th, and you enter \"3\", Org-mode will
2025 read this as the third of *next* month. However, if you enter \"17\",
2026 it will be considered as *this* month.
2027 2. The user gives a month but not a year.
2028 For example, if it is april and you enter \"feb 2\", this will be read
2029 as feb 2, *next* year. \"May 5\", however, will be this year.
2031 Currently this does not work for ISO week specifications.
2033 When this option is nil, the current month and year will always be used
2034 as defaults."
2035 :group 'org-time
2036 :type 'boolean)
2038 (defcustom org-read-date-display-live t
2039 "Non-nil means, display current interpretation of date prompt live.
2040 This display will be in an overlay, in the minibuffer."
2041 :group 'org-time
2042 :type 'boolean)
2044 (defcustom org-read-date-popup-calendar t
2045 "Non-nil means, pop up a calendar when prompting for a date.
2046 In the calendar, the date can be selected with mouse-1. However, the
2047 minibuffer will also be active, and you can simply enter the date as well.
2048 When nil, only the minibuffer will be available."
2049 :group 'org-time
2050 :type 'boolean)
2051 (if (fboundp 'defvaralias)
2052 (defvaralias 'org-popup-calendar-for-date-prompt
2053 'org-read-date-popup-calendar))
2055 (defcustom org-read-date-minibuffer-setup-hook nil
2056 "Hook to be used to set up keys for the date/time interface.
2057 Add key definitions to `minibuffer-local-map', which will be a temporary
2058 copy."
2059 :group 'org-time
2060 :type 'hook)
2062 (defcustom org-extend-today-until 0
2063 "The hour when your day really ends. Must be an integer.
2064 This has influence for the following applications:
2065 - When switching the agenda to \"today\". It it is still earlier than
2066 the time given here, the day recognized as TODAY is actually yesterday.
2067 - When a date is read from the user and it is still before the time given
2068 here, the current date and time will be assumed to be yesterday, 23:59.
2069 Also, timestamps inserted in remember templates follow this rule.
2071 IMPORTANT: This is a feature whose implementation is and likely will
2072 remain incomplete. Really, it is only here because past midnight seems to
2073 be the favorite working time of John Wiegley :-)"
2074 :group 'org-time
2075 :type 'number)
2077 (defcustom org-edit-timestamp-down-means-later nil
2078 "Non-nil means, S-down will increase the time in a time stamp.
2079 When nil, S-up will increase."
2080 :group 'org-time
2081 :type 'boolean)
2083 (defcustom org-calendar-follow-timestamp-change t
2084 "Non-nil means, make the calendar window follow timestamp changes.
2085 When a timestamp is modified and the calendar window is visible, it will be
2086 moved to the new date."
2087 :group 'org-time
2088 :type 'boolean)
2090 (defgroup org-tags nil
2091 "Options concerning tags in Org-mode."
2092 :tag "Org Tags"
2093 :group 'org)
2095 (defcustom org-tag-alist nil
2096 "List of tags allowed in Org-mode files.
2097 When this list is nil, Org-mode will base TAG input on what is already in the
2098 buffer.
2099 The value of this variable is an alist, the car of each entry must be a
2100 keyword as a string, the cdr may be a character that is used to select
2101 that tag through the fast-tag-selection interface.
2102 See the manual for details."
2103 :group 'org-tags
2104 :type '(repeat
2105 (choice
2106 (cons (string :tag "Tag name")
2107 (character :tag "Access char"))
2108 (const :tag "Start radio group" (:startgroup))
2109 (const :tag "End radio group" (:endgroup))
2110 (const :tag "New line" (:newline)))))
2112 (defcustom org-tag-persistent-alist nil
2113 "List of tags that will always appear in all Org-mode files.
2114 This is in addition to any in buffer settings or customizations
2115 of `org-tag-alist'.
2116 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2117 The value of this variable is an alist, the car of each entry must be a
2118 keyword as a string, the cdr may be a character that is used to select
2119 that tag through the fast-tag-selection interface.
2120 See the manual for details.
2121 To disable these tags on a per-file basis, insert anywhere in the file:
2122 #+STARTUP: noptag"
2123 :group 'org-tags
2124 :type '(repeat
2125 (choice
2126 (cons (string :tag "Tag name")
2127 (character :tag "Access char"))
2128 (const :tag "Start radio group" (:startgroup))
2129 (const :tag "End radio group" (:endgroup))
2130 (const :tag "New line" (:newline)))))
2132 (defvar org-file-tags nil
2133 "List of tags that can be inherited by all entries in the file.
2134 The tags will be inherited if the variable `org-use-tag-inheritance'
2135 says they should be.
2136 This variable is populated from #+TAG lines.")
2138 (defcustom org-use-fast-tag-selection 'auto
2139 "Non-nil means, use fast tag selection scheme.
2140 This is a special interface to select and deselect tags with single keys.
2141 When nil, fast selection is never used.
2142 When the symbol `auto', fast selection is used if and only if selection
2143 characters for tags have been configured, either through the variable
2144 `org-tag-alist' or through a #+TAGS line in the buffer.
2145 When t, fast selection is always used and selection keys are assigned
2146 automatically if necessary."
2147 :group 'org-tags
2148 :type '(choice
2149 (const :tag "Always" t)
2150 (const :tag "Never" nil)
2151 (const :tag "When selection characters are configured" 'auto)))
2153 (defcustom org-fast-tag-selection-single-key nil
2154 "Non-nil means, fast tag selection exits after first change.
2155 When nil, you have to press RET to exit it.
2156 During fast tag selection, you can toggle this flag with `C-c'.
2157 This variable can also have the value `expert'. In this case, the window
2158 displaying the tags menu is not even shown, until you press C-c again."
2159 :group 'org-tags
2160 :type '(choice
2161 (const :tag "No" nil)
2162 (const :tag "Yes" t)
2163 (const :tag "Expert" expert)))
2165 (defvar org-fast-tag-selection-include-todo nil
2166 "Non-nil means, fast tags selection interface will also offer TODO states.
2167 This is an undocumented feature, you should not rely on it.")
2169 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2170 "The column to which tags should be indented in a headline.
2171 If this number is positive, it specifies the column. If it is negative,
2172 it means that the tags should be flushright to that column. For example,
2173 -80 works well for a normal 80 character screen."
2174 :group 'org-tags
2175 :type 'integer)
2177 (defcustom org-auto-align-tags t
2178 "Non-nil means, realign tags after pro/demotion of TODO state change.
2179 These operations change the length of a headline and therefore shift
2180 the tags around. With this options turned on, after each such operation
2181 the tags are again aligned to `org-tags-column'."
2182 :group 'org-tags
2183 :type 'boolean)
2185 (defcustom org-use-tag-inheritance t
2186 "Non-nil means, tags in levels apply also for sublevels.
2187 When nil, only the tags directly given in a specific line apply there.
2188 This may also be a list of tags that should be inherited, or a regexp that
2189 matches tags that should be inherited. Additional control is possible
2190 with the variable `org-tags-exclude-from-inheritance' which gives an
2191 explicit list of tags to be excluded from inheritance., even if the value of
2192 `org-use-tag-inheritance' would select it for inheritance.
2194 If this option is t, a match early-on in a tree can lead to a large
2195 number of matches in the subtree when constructing the agenda or creating
2196 a sparse tree. If you only want to see the first match in a tree during
2197 a search, check out the variable `org-tags-match-list-sublevels'."
2198 :group 'org-tags
2199 :type '(choice
2200 (const :tag "Not" nil)
2201 (const :tag "Always" t)
2202 (repeat :tag "Specific tags" (string :tag "Tag"))
2203 (regexp :tag "Tags matched by regexp")))
2205 (defcustom org-tags-exclude-from-inheritance nil
2206 "List of tags that should never be inherited.
2207 This is a way to exclude a few tags from inheritance. For way to do
2208 the opposite, to actively allow inheritance for selected tags,
2209 see the variable `org-use-tag-inheritance'."
2210 :group 'org-tags
2211 :type '(repeat (string :tag "Tag")))
2213 (defun org-tag-inherit-p (tag)
2214 "Check if TAG is one that should be inherited."
2215 (cond
2216 ((member tag org-tags-exclude-from-inheritance) nil)
2217 ((eq org-use-tag-inheritance t) t)
2218 ((not org-use-tag-inheritance) nil)
2219 ((stringp org-use-tag-inheritance)
2220 (string-match org-use-tag-inheritance tag))
2221 ((listp org-use-tag-inheritance)
2222 (member tag org-use-tag-inheritance))
2223 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2225 (defcustom org-tags-match-list-sublevels t
2226 "Non-nil means list also sublevels of headlines matching a search.
2227 This variable applies to tags/property searches, and also to stuck
2228 projects because this search is based on a tags match as well.
2230 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2231 the sublevels of a headline matching a tag search often also match
2232 the same search. Listing all of them can create very long lists.
2233 Setting this variable to nil causes subtrees of a match to be skipped.
2235 As a special case, if the tag search is restricted to TODO items, the
2236 value of this variable is ignored and sublevels are always checked, to
2237 make sure all corresponding TODO items find their way into the list.
2239 This variable is semi-obsolete and probably should always be true. It
2240 is better to limit inheritance to certain tags using the variables
2241 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2242 :group 'org-tags
2243 :type '(choice
2244 (const :tag "No, don't list them" nil)
2245 (const :tag "Yes, do list them" t)
2246 (const :tag "List them, indented with leading dots" indented)))
2248 (defvar org-tags-history nil
2249 "History of minibuffer reads for tags.")
2250 (defvar org-last-tags-completion-table nil
2251 "The last used completion table for tags.")
2252 (defvar org-after-tags-change-hook nil
2253 "Hook that is run after the tags in a line have changed.")
2255 (defgroup org-properties nil
2256 "Options concerning properties in Org-mode."
2257 :tag "Org Properties"
2258 :group 'org)
2260 (defcustom org-property-format "%-10s %s"
2261 "How property key/value pairs should be formatted by `indent-line'.
2262 When `indent-line' hits a property definition, it will format the line
2263 according to this format, mainly to make sure that the values are
2264 lined-up with respect to each other."
2265 :group 'org-properties
2266 :type 'string)
2268 (defcustom org-use-property-inheritance nil
2269 "Non-nil means, properties apply also for sublevels.
2271 This setting is chiefly used during property searches. Turning it on can
2272 cause significant overhead when doing a search, which is why it is not
2273 on by default.
2275 When nil, only the properties directly given in the current entry count.
2276 When t, every property is inherited. The value may also be a list of
2277 properties that should have inheritance, or a regular expression matching
2278 properties that should be inherited.
2280 However, note that some special properties use inheritance under special
2281 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2282 and the properties ending in \"_ALL\" when they are used as descriptor
2283 for valid values of a property.
2285 Note for programmers:
2286 When querying an entry with `org-entry-get', you can control if inheritance
2287 should be used. By default, `org-entry-get' looks only at the local
2288 properties. You can request inheritance by setting the inherit argument
2289 to t (to force inheritance) or to `selective' (to respect the setting
2290 in this variable)."
2291 :group 'org-properties
2292 :type '(choice
2293 (const :tag "Not" nil)
2294 (const :tag "Always" t)
2295 (repeat :tag "Specific properties" (string :tag "Property"))
2296 (regexp :tag "Properties matched by regexp")))
2298 (defun org-property-inherit-p (property)
2299 "Check if PROPERTY is one that should be inherited."
2300 (cond
2301 ((eq org-use-property-inheritance t) t)
2302 ((not org-use-property-inheritance) nil)
2303 ((stringp org-use-property-inheritance)
2304 (string-match org-use-property-inheritance property))
2305 ((listp org-use-property-inheritance)
2306 (member property org-use-property-inheritance))
2307 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2309 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2310 "The default column format, if no other format has been defined.
2311 This variable can be set on the per-file basis by inserting a line
2313 #+COLUMNS: %25ITEM ....."
2314 :group 'org-properties
2315 :type 'string)
2317 (defcustom org-columns-ellipses ".."
2318 "The ellipses to be used when a field in column view is truncated.
2319 When this is the empty string, as many characters as possible are shown,
2320 but then there will be no visual indication that the field has been truncated.
2321 When this is a string of length N, the last N characters of a truncated
2322 field are replaced by this string. If the column is narrower than the
2323 ellipses string, only part of the ellipses string will be shown."
2324 :group 'org-properties
2325 :type 'string)
2327 (defcustom org-columns-modify-value-for-display-function nil
2328 "Function that modifies values for display in column view.
2329 For example, it can be used to cut out a certain part from a time stamp.
2330 The function must take 2 arguments:
2332 column-title The title of the column (*not* the property name)
2333 value The value that should be modified.
2335 The function should return the value that should be displayed,
2336 or nil if the normal value should be used."
2337 :group 'org-properties
2338 :type 'function)
2340 (defcustom org-effort-property "Effort"
2341 "The property that is being used to keep track of effort estimates.
2342 Effort estimates given in this property need to have the format H:MM."
2343 :group 'org-properties
2344 :group 'org-progress
2345 :type '(string :tag "Property"))
2347 (defconst org-global-properties-fixed
2348 '(("VISIBILITY_ALL" . "folded children content all"))
2349 "List of property/value pairs that can be inherited by any entry.
2351 These are fixed values, for the preset properties. The user variable
2352 that can be used to add to this list is `org-global-properties'.
2354 The entries in this list are cons cells where the car is a property
2355 name and cdr is a string with the value. If the value represents
2356 multiple items like an \"_ALL\" property, separate the items by
2357 spaces.")
2359 (defcustom org-global-properties nil
2360 "List of property/value pairs that can be inherited by any entry.
2362 This list will be combined with the constant `org-global-properties-fixed'.
2364 The entries in this list are cons cells where the car is a property
2365 name and cdr is a string with the value.
2367 You can set buffer-local values for the same purpose in the variable
2368 `org-file-properties' this by adding lines like
2370 #+PROPERTY: NAME VALUE"
2371 :group 'org-properties
2372 :type '(repeat
2373 (cons (string :tag "Property")
2374 (string :tag "Value"))))
2376 (defvar org-file-properties nil
2377 "List of property/value pairs that can be inherited by any entry.
2378 Valid for the current buffer.
2379 This variable is populated from #+PROPERTY lines.")
2380 (make-variable-buffer-local 'org-file-properties)
2382 (defgroup org-agenda nil
2383 "Options concerning agenda views in Org-mode."
2384 :tag "Org Agenda"
2385 :group 'org)
2387 (defvar org-category nil
2388 "Variable used by org files to set a category for agenda display.
2389 Such files should use a file variable to set it, for example
2391 # -*- mode: org; org-category: \"ELisp\"
2393 or contain a special line
2395 #+CATEGORY: ELisp
2397 If the file does not specify a category, then file's base name
2398 is used instead.")
2399 (make-variable-buffer-local 'org-category)
2400 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2402 (defcustom org-agenda-files nil
2403 "The files to be used for agenda display.
2404 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2405 \\[org-remove-file]. You can also use customize to edit the list.
2407 If an entry is a directory, all files in that directory that are matched by
2408 `org-agenda-file-regexp' will be part of the file list.
2410 If the value of the variable is not a list but a single file name, then
2411 the list of agenda files is actually stored and maintained in that file, one
2412 agenda file per line."
2413 :group 'org-agenda
2414 :type '(choice
2415 (repeat :tag "List of files and directories" file)
2416 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2418 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2419 "Regular expression to match files for `org-agenda-files'.
2420 If any element in the list in that variable contains a directory instead
2421 of a normal file, all files in that directory that are matched by this
2422 regular expression will be included."
2423 :group 'org-agenda
2424 :type 'regexp)
2426 (defcustom org-agenda-text-search-extra-files nil
2427 "List of extra files to be searched by text search commands.
2428 These files will be search in addition to the agenda files by the
2429 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2430 Note that these files will only be searched for text search commands,
2431 not for the other agenda views like todo lists, tag searches or the weekly
2432 agenda. This variable is intended to list notes and possibly archive files
2433 that should also be searched by these two commands.
2434 In fact, if the first element in the list is the symbol `agenda-archives',
2435 than all archive files of all agenda files will be added to the search
2436 scope."
2437 :group 'org-agenda
2438 :type '(set :greedy t
2439 (const :tag "Agenda Archives" agenda-archives)
2440 (repeat :inline t (file))))
2442 (if (fboundp 'defvaralias)
2443 (defvaralias 'org-agenda-multi-occur-extra-files
2444 'org-agenda-text-search-extra-files))
2446 (defcustom org-agenda-skip-unavailable-files nil
2447 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2448 A nil value means to remove them, after a query, from the list."
2449 :group 'org-agenda
2450 :type 'boolean)
2452 (defcustom org-calendar-to-agenda-key [?c]
2453 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2454 The command `org-calendar-goto-agenda' will be bound to this key. The
2455 default is the character `c' because then `c' can be used to switch back and
2456 forth between agenda and calendar."
2457 :group 'org-agenda
2458 :type 'sexp)
2460 (defcustom org-calendar-agenda-action-key [?k]
2461 "The key to be installed in `calendar-mode-map' for agenda-action.
2462 The command `org-agenda-action' will be bound to this key. The
2463 default is the character `k' because we use the same key in the agenda."
2464 :group 'org-agenda
2465 :type 'sexp)
2467 (eval-after-load "calendar"
2468 '(progn
2469 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2470 'org-calendar-goto-agenda)
2471 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2472 'org-agenda-action)))
2474 (defgroup org-latex nil
2475 "Options for embedding LaTeX code into Org-mode."
2476 :tag "Org LaTeX"
2477 :group 'org)
2479 (defcustom org-format-latex-options
2480 '(:foreground default :background default :scale 1.0
2481 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2482 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2483 "Options for creating images from LaTeX fragments.
2484 This is a property list with the following properties:
2485 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2486 `default' means use the foreground of the default face.
2487 :background the background color, or \"Transparent\".
2488 `default' means use the background of the default face.
2489 :scale a scaling factor for the size of the images.
2490 :html-foreground, :html-background, :html-scale
2491 the same numbers for HTML export.
2492 :matchers a list indicating which matchers should be used to
2493 find LaTeX fragments. Valid members of this list are:
2494 \"begin\" find environments
2495 \"$1\" find single characters surrounded by $.$
2496 \"$\" find math expressions surrounded by $...$
2497 \"$$\" find math expressions surrounded by $$....$$
2498 \"\\(\" find math expressions surrounded by \\(...\\)
2499 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2500 :group 'org-latex
2501 :type 'plist)
2503 (defcustom org-format-latex-header "\\documentclass{article}
2504 \\usepackage{fullpage} % do not remove
2505 \\usepackage{amssymb}
2506 \\usepackage[usenames]{color}
2507 \\usepackage{amsmath}
2508 \\usepackage{latexsym}
2509 \\usepackage[mathscr]{eucal}
2510 \\pagestyle{empty} % do not remove"
2511 "The document header used for processing LaTeX fragments."
2512 :group 'org-latex
2513 :type 'string)
2516 (defgroup org-font-lock nil
2517 "Font-lock settings for highlighting in Org-mode."
2518 :tag "Org Font Lock"
2519 :group 'org)
2521 (defcustom org-level-color-stars-only nil
2522 "Non-nil means fontify only the stars in each headline.
2523 When nil, the entire headline is fontified.
2524 Changing it requires restart of `font-lock-mode' to become effective
2525 also in regions already fontified."
2526 :group 'org-font-lock
2527 :type 'boolean)
2529 (defcustom org-hide-leading-stars nil
2530 "Non-nil means, hide the first N-1 stars in a headline.
2531 This works by using the face `org-hide' for these stars. This
2532 face is white for a light background, and black for a dark
2533 background. You may have to customize the face `org-hide' to
2534 make this work.
2535 Changing it requires restart of `font-lock-mode' to become effective
2536 also in regions already fontified.
2537 You may also set this on a per-file basis by adding one of the following
2538 lines to the buffer:
2540 #+STARTUP: hidestars
2541 #+STARTUP: showstars"
2542 :group 'org-font-lock
2543 :type 'boolean)
2545 (defcustom org-fontify-done-headline nil
2546 "Non-nil means, change the face of a headline if it is marked DONE.
2547 Normally, only the TODO/DONE keyword indicates the state of a headline.
2548 When this is non-nil, the headline after the keyword is set to the
2549 `org-headline-done' as an additional indication."
2550 :group 'org-font-lock
2551 :type 'boolean)
2553 (defcustom org-fontify-emphasized-text t
2554 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2555 Changing this variable requires a restart of Emacs to take effect."
2556 :group 'org-font-lock
2557 :type 'boolean)
2559 (defcustom org-highlight-latex-fragments-and-specials nil
2560 "Non-nil means, fontify what is treated specially by the exporters."
2561 :group 'org-font-lock
2562 :type 'boolean)
2564 (defcustom org-hide-emphasis-markers nil
2565 "Non-nil mean font-lock should hide the emphasis marker characters."
2566 :group 'org-font-lock
2567 :type 'boolean)
2569 (defvar org-emph-re nil
2570 "Regular expression for matching emphasis.")
2571 (defvar org-verbatim-re nil
2572 "Regular expression for matching verbatim text.")
2573 (defvar org-emphasis-regexp-components) ; defined just below
2574 (defvar org-emphasis-alist) ; defined just below
2575 (defun org-set-emph-re (var val)
2576 "Set variable and compute the emphasis regular expression."
2577 (set var val)
2578 (when (and (boundp 'org-emphasis-alist)
2579 (boundp 'org-emphasis-regexp-components)
2580 org-emphasis-alist org-emphasis-regexp-components)
2581 (let* ((e org-emphasis-regexp-components)
2582 (pre (car e))
2583 (post (nth 1 e))
2584 (border (nth 2 e))
2585 (body (nth 3 e))
2586 (nl (nth 4 e))
2587 (body1 (concat body "*?"))
2588 (markers (mapconcat 'car org-emphasis-alist ""))
2589 (vmarkers (mapconcat
2590 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2591 org-emphasis-alist "")))
2592 ;; make sure special characters appear at the right position in the class
2593 (if (string-match "\\^" markers)
2594 (setq markers (concat (replace-match "" t t markers) "^")))
2595 (if (string-match "-" markers)
2596 (setq markers (concat (replace-match "" t t markers) "-")))
2597 (if (string-match "\\^" vmarkers)
2598 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2599 (if (string-match "-" vmarkers)
2600 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2601 (if (> nl 0)
2602 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2603 (int-to-string nl) "\\}")))
2604 ;; Make the regexp
2605 (setq org-emph-re
2606 (concat "\\([" pre "]\\|^\\)"
2607 "\\("
2608 "\\([" markers "]\\)"
2609 "\\("
2610 "[^" border "]\\|"
2611 "[^" border "]"
2612 body1
2613 "[^" border "]"
2614 "\\)"
2615 "\\3\\)"
2616 "\\([" post "]\\|$\\)"))
2617 (setq org-verbatim-re
2618 (concat "\\([" pre "]\\|^\\)"
2619 "\\("
2620 "\\([" vmarkers "]\\)"
2621 "\\("
2622 "[^" border "]\\|"
2623 "[^" border "]"
2624 body1
2625 "[^" border "]"
2626 "\\)"
2627 "\\3\\)"
2628 "\\([" post "]\\|$\\)")))))
2630 (defcustom org-emphasis-regexp-components
2631 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2632 "Components used to build the regular expression for emphasis.
2633 This is a list with 6 entries. Terminology: In an emphasis string
2634 like \" *strong word* \", we call the initial space PREMATCH, the final
2635 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2636 and \"trong wor\" is the body. The different components in this variable
2637 specify what is allowed/forbidden in each part:
2639 pre Chars allowed as prematch. Beginning of line will be allowed too.
2640 post Chars allowed as postmatch. End of line will be allowed too.
2641 border The chars *forbidden* as border characters.
2642 body-regexp A regexp like \".\" to match a body character. Don't use
2643 non-shy groups here, and don't allow newline here.
2644 newline The maximum number of newlines allowed in an emphasis exp.
2646 Use customize to modify this, or restart Emacs after changing it."
2647 :group 'org-font-lock
2648 :set 'org-set-emph-re
2649 :type '(list
2650 (sexp :tag "Allowed chars in pre ")
2651 (sexp :tag "Allowed chars in post ")
2652 (sexp :tag "Forbidden chars in border ")
2653 (sexp :tag "Regexp for body ")
2654 (integer :tag "number of newlines allowed")
2655 (option (boolean :tag "Please ignore this button"))))
2657 (defcustom org-emphasis-alist
2658 `(("*" bold "<b>" "</b>")
2659 ("/" italic "<i>" "</i>")
2660 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2661 ("=" org-code "<code>" "</code>" verbatim)
2662 ("~" org-verbatim "<code>" "</code>" verbatim)
2663 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2664 "<del>" "</del>")
2666 "Special syntax for emphasized text.
2667 Text starting and ending with a special character will be emphasized, for
2668 example *bold*, _underlined_ and /italic/. This variable sets the marker
2669 characters, the face to be used by font-lock for highlighting in Org-mode
2670 Emacs buffers, and the HTML tags to be used for this.
2671 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2672 Use customize to modify this, or restart Emacs after changing it."
2673 :group 'org-font-lock
2674 :set 'org-set-emph-re
2675 :type '(repeat
2676 (list
2677 (string :tag "Marker character")
2678 (choice
2679 (face :tag "Font-lock-face")
2680 (plist :tag "Face property list"))
2681 (string :tag "HTML start tag")
2682 (string :tag "HTML end tag")
2683 (option (const verbatim)))))
2685 ;;; Miscellaneous options
2687 (defgroup org-completion nil
2688 "Completion in Org-mode."
2689 :tag "Org Completion"
2690 :group 'org)
2692 (defcustom org-completion-use-ido nil
2693 "Non-nil means, use ido completion wherever possible.
2694 Note that `ido-mode' must be active for this variable to be relevant.
2695 If you decide to turn this variable on, you might well want to turn off
2696 `org-outline-path-complete-in-steps'."
2697 :group 'org-completion
2698 :type 'boolean)
2700 (defcustom org-completion-fallback-command 'hippie-expand
2701 "The expansion command called by \\[org-complete] in normal context.
2702 Normal means, no org-mode-specific context."
2703 :group 'org-completion
2704 :type 'function)
2706 ;;; Functions and variables from ther packages
2707 ;; Declared here to avoid compiler warnings
2709 ;; XEmacs only
2710 (defvar outline-mode-menu-heading)
2711 (defvar outline-mode-menu-show)
2712 (defvar outline-mode-menu-hide)
2713 (defvar zmacs-regions) ; XEmacs regions
2715 ;; Emacs only
2716 (defvar mark-active)
2718 ;; Various packages
2719 (declare-function find-library-name "find-func" (library))
2720 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2721 (declare-function calendar-forward-day "cal-move" (arg))
2722 (declare-function calendar-goto-date "cal-move" (date))
2723 (declare-function calendar-goto-today "cal-move" ())
2724 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2725 (defvar calc-embedded-close-formula)
2726 (defvar calc-embedded-open-formula)
2727 (declare-function cdlatex-tab "ext:cdlatex" ())
2728 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2729 (defvar font-lock-unfontify-region-function)
2730 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2731 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2732 (defvar iswitchb-temp-buflist)
2733 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2734 (defvar org-agenda-tags-todo-honor-ignore-options)
2735 (declare-function org-agenda-skip "org-agenda" ())
2736 (declare-function org-format-agenda-item "org-agenda"
2737 (extra txt &optional category tags dotime noprefix remove-re))
2738 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2739 (declare-function org-agenda-change-all-lines "org-agenda"
2740 (newhead hdmarker &optional fixface just-this))
2741 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2742 (declare-function org-agenda-maybe-redo "org-agenda" ())
2743 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2744 (beg end))
2745 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2746 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2747 "org-agenda" (&optional end))
2749 (declare-function parse-time-string "parse-time" (string))
2750 (declare-function remember "remember" (&optional initial))
2751 (declare-function remember-buffer-desc "remember" ())
2752 (declare-function remember-finalize "remember" ())
2753 (defvar remember-save-after-remembering)
2754 (defvar remember-data-file)
2755 (defvar remember-register)
2756 (defvar remember-buffer)
2757 (defvar remember-handler-functions)
2758 (defvar remember-annotation-functions)
2759 (defvar texmathp-why)
2760 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2761 (declare-function table--at-cell-p "table" (position &optional object at-column))
2763 (defvar w3m-current-url)
2764 (defvar w3m-current-title)
2766 (defvar org-latex-regexps)
2768 ;;; Autoload and prepare some org modules
2770 ;; Some table stuff that needs to be defined here, because it is used
2771 ;; by the functions setting up org-mode or checking for table context.
2773 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2774 "Detects an org-type or table-type table.")
2775 (defconst org-table-line-regexp "^[ \t]*|"
2776 "Detects an org-type table line.")
2777 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2778 "Detects an org-type table line.")
2779 (defconst org-table-hline-regexp "^[ \t]*|-"
2780 "Detects an org-type table hline.")
2781 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2782 "Detects a table-type table hline.")
2783 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2784 "Searching from within a table (any type) this finds the first line
2785 outside the table.")
2787 ;; Autoload the functions in org-table.el that are needed by functions here.
2789 (eval-and-compile
2790 (org-autoload "org-table"
2791 '(org-table-align org-table-begin org-table-blank-field
2792 org-table-convert org-table-convert-region org-table-copy-down
2793 org-table-copy-region org-table-create
2794 org-table-create-or-convert-from-region
2795 org-table-create-with-table.el org-table-current-dline
2796 org-table-cut-region org-table-delete-column org-table-edit-field
2797 org-table-edit-formulas org-table-end org-table-eval-formula
2798 org-table-export org-table-field-info
2799 org-table-get-stored-formulas org-table-goto-column
2800 org-table-hline-and-move org-table-import org-table-insert-column
2801 org-table-insert-hline org-table-insert-row org-table-iterate
2802 org-table-justify-field-maybe org-table-kill-row
2803 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2804 org-table-move-column org-table-move-column-left
2805 org-table-move-column-right org-table-move-row
2806 org-table-move-row-down org-table-move-row-up
2807 org-table-next-field org-table-next-row org-table-paste-rectangle
2808 org-table-previous-field org-table-recalculate
2809 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2810 org-table-toggle-coordinate-overlays
2811 org-table-toggle-formula-debugger org-table-wrap-region
2812 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2814 (defun org-at-table-p (&optional table-type)
2815 "Return t if the cursor is inside an org-type table.
2816 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2817 (if org-enable-table-editor
2818 (save-excursion
2819 (beginning-of-line 1)
2820 (looking-at (if table-type org-table-any-line-regexp
2821 org-table-line-regexp)))
2822 nil))
2823 (defsubst org-table-p () (org-at-table-p))
2825 (defun org-at-table.el-p ()
2826 "Return t if and only if we are at a table.el table."
2827 (and (org-at-table-p 'any)
2828 (save-excursion
2829 (goto-char (org-table-begin 'any))
2830 (looking-at org-table1-hline-regexp))))
2831 (defun org-table-recognize-table.el ()
2832 "If there is a table.el table nearby, recognize it and move into it."
2833 (if org-table-tab-recognizes-table.el
2834 (if (org-at-table.el-p)
2835 (progn
2836 (beginning-of-line 1)
2837 (if (looking-at org-table-dataline-regexp)
2839 (if (looking-at org-table1-hline-regexp)
2840 (progn
2841 (beginning-of-line 2)
2842 (if (looking-at org-table-any-border-regexp)
2843 (beginning-of-line -1)))))
2844 (if (re-search-forward "|" (org-table-end t) t)
2845 (progn
2846 (require 'table)
2847 (if (table--at-cell-p (point))
2849 (message "recognizing table.el table...")
2850 (table-recognize-table)
2851 (message "recognizing table.el table...done")))
2852 (error "This should not happen..."))
2854 nil)
2855 nil))
2857 (defun org-at-table-hline-p ()
2858 "Return t if the cursor is inside a hline in a table."
2859 (if org-enable-table-editor
2860 (save-excursion
2861 (beginning-of-line 1)
2862 (looking-at org-table-hline-regexp))
2863 nil))
2865 (defvar org-table-clean-did-remove-column nil)
2867 (defun org-table-map-tables (function)
2868 "Apply FUNCTION to the start of all tables in the buffer."
2869 (save-excursion
2870 (save-restriction
2871 (widen)
2872 (goto-char (point-min))
2873 (while (re-search-forward org-table-any-line-regexp nil t)
2874 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2875 (beginning-of-line 1)
2876 (if (looking-at org-table-line-regexp)
2877 (save-excursion (funcall function)))
2878 (re-search-forward org-table-any-border-regexp nil 1))))
2879 (message "Mapping tables: done"))
2881 ;; Declare and autoload functions from org-exp.el
2883 (declare-function org-default-export-plist "org-exp")
2884 (declare-function org-infile-export-plist "org-exp")
2885 (declare-function org-get-current-options "org-exp")
2886 (eval-and-compile
2887 (org-autoload "org-exp"
2888 '(org-export org-export-as-ascii org-export-visible
2889 org-insert-export-options-template org-export-as-html-and-open
2890 org-export-as-html-batch org-export-as-html-to-buffer
2891 org-replace-region-by-html org-export-region-as-html
2892 org-export-as-html org-export-icalendar-this-file
2893 org-export-icalendar-all-agenda-files
2894 org-table-clean-before-export
2895 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2897 ;; Declare and autoload functions from org-agenda.el
2899 (eval-and-compile
2900 (org-autoload "org-agenda"
2901 '(org-agenda org-agenda-list org-search-view
2902 org-todo-list org-tags-view org-agenda-list-stuck-projects
2903 org-diary org-agenda-to-appt
2904 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2906 ;; Autoload org-remember
2908 (eval-and-compile
2909 (org-autoload "org-remember"
2910 '(org-remember-insinuate org-remember-annotation
2911 org-remember-apply-template org-remember org-remember-handler)))
2913 ;; Autoload org-clock.el
2916 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2917 (beg end))
2918 (declare-function org-clock-update-mode-line "org-clock" ())
2919 (defvar org-clock-start-time)
2920 (defvar org-clock-marker (make-marker)
2921 "Marker recording the last clock-in.")
2923 (eval-and-compile
2924 (org-autoload
2925 "org-clock"
2926 '(org-clock-in org-clock-out org-clock-cancel
2927 org-clock-goto org-clock-sum org-clock-display
2928 org-clock-remove-overlays org-clock-report
2929 org-clocktable-shift org-dblock-write:clocktable
2930 org-get-clocktable)))
2932 (defun org-clock-update-time-maybe ()
2933 "If this is a CLOCK line, update it and return t.
2934 Otherwise, return nil."
2935 (interactive)
2936 (save-excursion
2937 (beginning-of-line 1)
2938 (skip-chars-forward " \t")
2939 (when (looking-at org-clock-string)
2940 (let ((re (concat "[ \t]*" org-clock-string
2941 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2942 "\\([ \t]*=>.*\\)?\\)?"))
2943 ts te h m s neg)
2944 (cond
2945 ((not (looking-at re))
2946 nil)
2947 ((not (match-end 2))
2948 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2949 (> org-clock-marker (point))
2950 (<= org-clock-marker (point-at-eol)))
2951 ;; The clock is running here
2952 (setq org-clock-start-time
2953 (apply 'encode-time
2954 (org-parse-time-string (match-string 1))))
2955 (org-clock-update-mode-line)))
2957 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2958 (end-of-line 1)
2959 (setq ts (match-string 1)
2960 te (match-string 3))
2961 (setq s (- (time-to-seconds
2962 (apply 'encode-time (org-parse-time-string te)))
2963 (time-to-seconds
2964 (apply 'encode-time (org-parse-time-string ts))))
2965 neg (< s 0)
2966 s (abs s)
2967 h (floor (/ s 3600))
2968 s (- s (* 3600 h))
2969 m (floor (/ s 60))
2970 s (- s (* 60 s)))
2971 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2972 t))))))
2974 (defun org-check-running-clock ()
2975 "Check if the current buffer contains the running clock.
2976 If yes, offer to stop it and to save the buffer with the changes."
2977 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2978 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2979 (buffer-name))))
2980 (org-clock-out)
2981 (when (y-or-n-p "Save changed buffer?")
2982 (save-buffer))))
2984 (defun org-clocktable-try-shift (dir n)
2985 "Check if this line starts a clock table, if yes, shift the time block."
2986 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2987 (org-clocktable-shift dir n)))
2989 ;; Autoload org-timer.el
2991 (eval-and-compile
2992 (org-autoload
2993 "org-timer"
2994 '(org-timer-start org-timer org-timer-item
2995 org-timer-change-times-in-region)))
2997 ;; Autoload org-feed.el
2999 (eval-and-compile
3000 (org-autoload
3001 "org-feed"
3002 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3005 ;; Autoload archiving code
3006 ;; The stuff that is needed for cycling and tags has to be defined here.
3008 (defgroup org-archive nil
3009 "Options concerning archiving in Org-mode."
3010 :tag "Org Archive"
3011 :group 'org-structure)
3013 (defcustom org-archive-location "%s_archive::"
3014 "The location where subtrees should be archived.
3016 The value of this variable is a string, consisting of two parts,
3017 separated by a double-colon. The first part is a filename and
3018 the second part is a headline.
3020 When the filename is omitted, archiving happens in the same file.
3021 %s in the filename will be replaced by the current file
3022 name (without the directory part). Archiving to a different file
3023 is useful to keep archived entries from contributing to the
3024 Org-mode Agenda.
3026 The archived entries will be filed as subtrees of the specified
3027 headline. When the headline is omitted, the subtrees are simply
3028 filed away at the end of the file, as top-level entries. Also in
3029 the heading you can use %s to represent the file name, this can be
3030 useful when using the same archive for a number of different files.
3032 Here are a few examples:
3033 \"%s_archive::\"
3034 If the current file is Projects.org, archive in file
3035 Projects.org_archive, as top-level trees. This is the default.
3037 \"::* Archived Tasks\"
3038 Archive in the current file, under the top-level headline
3039 \"* Archived Tasks\".
3041 \"~/org/archive.org::\"
3042 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3044 \"~/org/archive.org::From %s\"
3045 Archive in file ~/org/archive.org (absolute path), und headlines
3046 \"From FILENAME\" where file name is the current file name.
3048 \"basement::** Finished Tasks\"
3049 Archive in file ./basement (relative path), as level 3 trees
3050 below the level 2 heading \"** Finished Tasks\".
3052 You may set this option on a per-file basis by adding to the buffer a
3053 line like
3055 #+ARCHIVE: basement::** Finished Tasks
3057 You may also define it locally for a subtree by setting an ARCHIVE property
3058 in the entry. If such a property is found in an entry, or anywhere up
3059 the hierarchy, it will be used."
3060 :group 'org-archive
3061 :type 'string)
3063 (defcustom org-archive-tag "ARCHIVE"
3064 "The tag that marks a subtree as archived.
3065 An archived subtree does not open during visibility cycling, and does
3066 not contribute to the agenda listings.
3067 After changing this, font-lock must be restarted in the relevant buffers to
3068 get the proper fontification."
3069 :group 'org-archive
3070 :group 'org-keywords
3071 :type 'string)
3073 (defcustom org-agenda-skip-archived-trees t
3074 "Non-nil means, the agenda will skip any items located in archived trees.
3075 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3076 variable is no longer recommended, you should leave it at the value t.
3077 Instead, use the key `v' to cycle the archives-mode in the agenda."
3078 :group 'org-archive
3079 :group 'org-agenda-skip
3080 :type 'boolean)
3082 (defcustom org-columns-skip-arrchived-trees t
3083 "Non-nil means, irgnore archived trees when creating column view."
3084 :group 'org-archive
3085 :group 'org-properties
3086 :type 'boolean)
3088 (defcustom org-cycle-open-archived-trees nil
3089 "Non-nil means, `org-cycle' will open archived trees.
3090 An archived tree is a tree marked with the tag ARCHIVE.
3091 When nil, archived trees will stay folded. You can still open them with
3092 normal outline commands like `show-all', but not with the cycling commands."
3093 :group 'org-archive
3094 :group 'org-cycle
3095 :type 'boolean)
3097 (defcustom org-sparse-tree-open-archived-trees nil
3098 "Non-nil means sparse tree construction shows matches in archived trees.
3099 When nil, matches in these trees are highlighted, but the trees are kept in
3100 collapsed state."
3101 :group 'org-archive
3102 :group 'org-sparse-trees
3103 :type 'boolean)
3105 (defun org-cycle-hide-archived-subtrees (state)
3106 "Re-hide all archived subtrees after a visibility state change."
3107 (when (and (not org-cycle-open-archived-trees)
3108 (not (memq state '(overview folded))))
3109 (save-excursion
3110 (let* ((globalp (memq state '(contents all)))
3111 (beg (if globalp (point-min) (point)))
3112 (end (if globalp (point-max) (org-end-of-subtree t))))
3113 (org-hide-archived-subtrees beg end)
3114 (goto-char beg)
3115 (if (looking-at (concat ".*:" org-archive-tag ":"))
3116 (message "%s" (substitute-command-keys
3117 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3119 (defun org-force-cycle-archived ()
3120 "Cycle subtree even if it is archived."
3121 (interactive)
3122 (setq this-command 'org-cycle)
3123 (let ((org-cycle-open-archived-trees t))
3124 (call-interactively 'org-cycle)))
3126 (defun org-hide-archived-subtrees (beg end)
3127 "Re-hide all archived subtrees after a visibility state change."
3128 (save-excursion
3129 (let* ((re (concat ":" org-archive-tag ":")))
3130 (goto-char beg)
3131 (while (re-search-forward re end t)
3132 (and (org-on-heading-p) (hide-subtree))
3133 (org-end-of-subtree t)))))
3135 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3137 (eval-and-compile
3138 (org-autoload "org-archive"
3139 '(org-add-archive-files org-archive-subtree
3140 org-archive-to-archive-sibling org-toggle-archive-tag)))
3142 ;; Autoload Column View Code
3144 (declare-function org-columns-number-to-string "org-colview")
3145 (declare-function org-columns-get-format-and-top-level "org-colview")
3146 (declare-function org-columns-compute "org-colview")
3148 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3149 '(org-columns-number-to-string org-columns-get-format-and-top-level
3150 org-columns-compute org-agenda-columns org-columns-remove-overlays
3151 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3153 ;; Autoload ID code
3155 (declare-function org-id-store-link "org-id")
3156 (declare-function org-id-locations-load "org-id")
3157 (declare-function org-id-locations-save "org-id")
3158 (defvar org-id-track-globally)
3159 (org-autoload "org-id"
3160 '(org-id-get-create org-id-new org-id-copy org-id-get
3161 org-id-get-with-outline-path-completion
3162 org-id-get-with-outline-drilling
3163 org-id-goto org-id-find org-id-store-link))
3165 ;; Autoload Plotting Code
3167 (org-autoload "org-plot"
3168 '(org-plot/gnuplot))
3170 ;;; Variables for pre-computed regular expressions, all buffer local
3172 (defvar org-drawer-regexp nil
3173 "Matches first line of a hidden block.")
3174 (make-variable-buffer-local 'org-drawer-regexp)
3175 (defvar org-todo-regexp nil
3176 "Matches any of the TODO state keywords.")
3177 (make-variable-buffer-local 'org-todo-regexp)
3178 (defvar org-not-done-regexp nil
3179 "Matches any of the TODO state keywords except the last one.")
3180 (make-variable-buffer-local 'org-not-done-regexp)
3181 (defvar org-todo-line-regexp nil
3182 "Matches a headline and puts TODO state into group 2 if present.")
3183 (make-variable-buffer-local 'org-todo-line-regexp)
3184 (defvar org-complex-heading-regexp nil
3185 "Matches a headline and puts everything into groups:
3186 group 1: the stars
3187 group 2: The todo keyword, maybe
3188 group 3: Priority cookie
3189 group 4: True headline
3190 group 5: Tags")
3191 (make-variable-buffer-local 'org-complex-heading-regexp)
3192 (defvar org-todo-line-tags-regexp nil
3193 "Matches a headline and puts TODO state into group 2 if present.
3194 Also put tags into group 4 if tags are present.")
3195 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3196 (defvar org-nl-done-regexp nil
3197 "Matches newline followed by a headline with the DONE keyword.")
3198 (make-variable-buffer-local 'org-nl-done-regexp)
3199 (defvar org-looking-at-done-regexp nil
3200 "Matches the DONE keyword a point.")
3201 (make-variable-buffer-local 'org-looking-at-done-regexp)
3202 (defvar org-ds-keyword-length 12
3203 "Maximum length of the Deadline and SCHEDULED keywords.")
3204 (make-variable-buffer-local 'org-ds-keyword-length)
3205 (defvar org-deadline-regexp nil
3206 "Matches the DEADLINE keyword.")
3207 (make-variable-buffer-local 'org-deadline-regexp)
3208 (defvar org-deadline-time-regexp nil
3209 "Matches the DEADLINE keyword together with a time stamp.")
3210 (make-variable-buffer-local 'org-deadline-time-regexp)
3211 (defvar org-deadline-line-regexp nil
3212 "Matches the DEADLINE keyword and the rest of the line.")
3213 (make-variable-buffer-local 'org-deadline-line-regexp)
3214 (defvar org-scheduled-regexp nil
3215 "Matches the SCHEDULED keyword.")
3216 (make-variable-buffer-local 'org-scheduled-regexp)
3217 (defvar org-scheduled-time-regexp nil
3218 "Matches the SCHEDULED keyword together with a time stamp.")
3219 (make-variable-buffer-local 'org-scheduled-time-regexp)
3220 (defvar org-closed-time-regexp nil
3221 "Matches the CLOSED keyword together with a time stamp.")
3222 (make-variable-buffer-local 'org-closed-time-regexp)
3224 (defvar org-keyword-time-regexp nil
3225 "Matches any of the 4 keywords, together with the time stamp.")
3226 (make-variable-buffer-local 'org-keyword-time-regexp)
3227 (defvar org-keyword-time-not-clock-regexp nil
3228 "Matches any of the 3 keywords, together with the time stamp.")
3229 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3230 (defvar org-maybe-keyword-time-regexp nil
3231 "Matches a timestamp, possibly preceeded by a keyword.")
3232 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3233 (defvar org-planning-or-clock-line-re nil
3234 "Matches a line with planning or clock info.")
3235 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3237 (defconst org-plain-time-of-day-regexp
3238 (concat
3239 "\\(\\<[012]?[0-9]"
3240 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3241 "\\(--?"
3242 "\\(\\<[012]?[0-9]"
3243 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3244 "\\)?")
3245 "Regular expression to match a plain time or time range.
3246 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3247 groups carry important information:
3248 0 the full match
3249 1 the first time, range or not
3250 8 the second time, if it is a range.")
3252 (defconst org-plain-time-extension-regexp
3253 (concat
3254 "\\(\\<[012]?[0-9]"
3255 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3256 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3257 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3258 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3259 groups carry important information:
3260 0 the full match
3261 7 hours of duration
3262 9 minutes of duration")
3264 (defconst org-stamp-time-of-day-regexp
3265 (concat
3266 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3267 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3268 "\\(--?"
3269 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3270 "Regular expression to match a timestamp time or time range.
3271 After a match, the following groups carry important information:
3272 0 the full match
3273 1 date plus weekday, for backreferencing to make sure both times on same day
3274 2 the first time, range or not
3275 4 the second time, if it is a range.")
3277 (defconst org-startup-options
3278 '(("fold" org-startup-folded t)
3279 ("overview" org-startup-folded t)
3280 ("nofold" org-startup-folded nil)
3281 ("showall" org-startup-folded nil)
3282 ("content" org-startup-folded content)
3283 ("hidestars" org-hide-leading-stars t)
3284 ("showstars" org-hide-leading-stars nil)
3285 ("odd" org-odd-levels-only t)
3286 ("oddeven" org-odd-levels-only nil)
3287 ("align" org-startup-align-all-tables t)
3288 ("noalign" org-startup-align-all-tables nil)
3289 ("customtime" org-display-custom-times t)
3290 ("logdone" org-log-done time)
3291 ("lognotedone" org-log-done note)
3292 ("nologdone" org-log-done nil)
3293 ("lognoteclock-out" org-log-note-clock-out t)
3294 ("nolognoteclock-out" org-log-note-clock-out nil)
3295 ("logrepeat" org-log-repeat state)
3296 ("lognoterepeat" org-log-repeat note)
3297 ("nologrepeat" org-log-repeat nil)
3298 ("fninline" org-footnote-define-inline t)
3299 ("nofninline" org-footnote-define-inline nil)
3300 ("fnlocal" org-footnote-section nil)
3301 ("fnauto" org-footnote-auto-label t)
3302 ("fnprompt" org-footnote-auto-label nil)
3303 ("fnconfirm" org-footnote-auto-label confirm)
3304 ("fnplain" org-footnote-auto-label plain)
3305 ("constcgs" constants-unit-system cgs)
3306 ("constSI" constants-unit-system SI)
3307 ("noptag" org-tag-persistent-alist nil))
3308 "Variable associated with STARTUP options for org-mode.
3309 Each element is a list of three items: The startup options as written
3310 in the #+STARTUP line, the corresponding variable, and the value to
3311 set this variable to if the option is found. An optional forth element PUSH
3312 means to push this value onto the list in the variable.")
3314 (defun org-set-regexps-and-options ()
3315 "Precompute regular expressions for current buffer."
3316 (when (org-mode-p)
3317 (org-set-local 'org-todo-kwd-alist nil)
3318 (org-set-local 'org-todo-key-alist nil)
3319 (org-set-local 'org-todo-key-trigger nil)
3320 (org-set-local 'org-todo-keywords-1 nil)
3321 (org-set-local 'org-done-keywords nil)
3322 (org-set-local 'org-todo-heads nil)
3323 (org-set-local 'org-todo-sets nil)
3324 (org-set-local 'org-todo-log-states nil)
3325 (org-set-local 'org-file-properties nil)
3326 (org-set-local 'org-file-tags nil)
3327 (let ((re (org-make-options-regexp
3328 '("CATEGORY" "TODO" "COLUMNS"
3329 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3330 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3331 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3332 (splitre "[ \t]+")
3333 kwds kws0 kwsa key log value cat arch tags const links hw dws
3334 tail sep kws1 prio props ftags drawers
3335 ext-setup-or-nil setup-contents (start 0))
3336 (save-excursion
3337 (save-restriction
3338 (widen)
3339 (goto-char (point-min))
3340 (while (or (and ext-setup-or-nil
3341 (string-match re ext-setup-or-nil start)
3342 (setq start (match-end 0)))
3343 (and (setq ext-setup-or-nil nil start 0)
3344 (re-search-forward re nil t)))
3345 (setq key (upcase (match-string 1 ext-setup-or-nil))
3346 value (org-match-string-no-properties 2 ext-setup-or-nil))
3347 (cond
3348 ((equal key "CATEGORY")
3349 (if (string-match "[ \t]+$" value)
3350 (setq value (replace-match "" t t value)))
3351 (setq cat value))
3352 ((member key '("SEQ_TODO" "TODO"))
3353 (push (cons 'sequence (org-split-string value splitre)) kwds))
3354 ((equal key "TYP_TODO")
3355 (push (cons 'type (org-split-string value splitre)) kwds))
3356 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3357 ;; general TODO-like setup
3358 (push (cons (intern (downcase (match-string 1 key)))
3359 (org-split-string value splitre)) kwds))
3360 ((equal key "TAGS")
3361 (setq tags (append tags (if tags '("\\n") nil)
3362 (org-split-string value splitre))))
3363 ((equal key "COLUMNS")
3364 (org-set-local 'org-columns-default-format value))
3365 ((equal key "LINK")
3366 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3367 (push (cons (match-string 1 value)
3368 (org-trim (match-string 2 value)))
3369 links)))
3370 ((equal key "PRIORITIES")
3371 (setq prio (org-split-string value " +")))
3372 ((equal key "PROPERTY")
3373 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3374 (push (cons (match-string 1 value) (match-string 2 value))
3375 props)))
3376 ((equal key "FILETAGS")
3377 (when (string-match "\\S-" value)
3378 (setq ftags
3379 (append
3380 ftags
3381 (apply 'append
3382 (mapcar (lambda (x) (org-split-string x ":"))
3383 (org-split-string value)))))))
3384 ((equal key "DRAWERS")
3385 (setq drawers (org-split-string value splitre)))
3386 ((equal key "CONSTANTS")
3387 (setq const (append const (org-split-string value splitre))))
3388 ((equal key "STARTUP")
3389 (let ((opts (org-split-string value splitre))
3390 l var val)
3391 (while (setq l (pop opts))
3392 (when (setq l (assoc l org-startup-options))
3393 (setq var (nth 1 l) val (nth 2 l))
3394 (if (not (nth 3 l))
3395 (set (make-local-variable var) val)
3396 (if (not (listp (symbol-value var)))
3397 (set (make-local-variable var) nil))
3398 (set (make-local-variable var) (symbol-value var))
3399 (add-to-list var val))))))
3400 ((equal key "ARCHIVE")
3401 (string-match " *$" value)
3402 (setq arch (replace-match "" t t value))
3403 (remove-text-properties 0 (length arch)
3404 '(face t fontified t) arch))
3405 ((equal key "SETUPFILE")
3406 (setq setup-contents (org-file-contents
3407 (expand-file-name
3408 (org-remove-double-quotes value))
3409 'noerror))
3410 (if (not ext-setup-or-nil)
3411 (setq ext-setup-or-nil setup-contents start 0)
3412 (setq ext-setup-or-nil
3413 (concat (substring ext-setup-or-nil 0 start)
3414 "\n" setup-contents "\n"
3415 (substring ext-setup-or-nil start)))))
3416 ))))
3417 (when cat
3418 (org-set-local 'org-category (intern cat))
3419 (push (cons "CATEGORY" cat) props))
3420 (when prio
3421 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3422 (setq prio (mapcar 'string-to-char prio))
3423 (org-set-local 'org-highest-priority (nth 0 prio))
3424 (org-set-local 'org-lowest-priority (nth 1 prio))
3425 (org-set-local 'org-default-priority (nth 2 prio)))
3426 (and props (org-set-local 'org-file-properties (nreverse props)))
3427 (and ftags (org-set-local 'org-file-tags
3428 (mapcar 'org-add-prop-inherited ftags)))
3429 (and drawers (org-set-local 'org-drawers drawers))
3430 (and arch (org-set-local 'org-archive-location arch))
3431 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3432 ;; Process the TODO keywords
3433 (unless kwds
3434 ;; Use the global values as if they had been given locally.
3435 (setq kwds (default-value 'org-todo-keywords))
3436 (if (stringp (car kwds))
3437 (setq kwds (list (cons org-todo-interpretation
3438 (default-value 'org-todo-keywords)))))
3439 (setq kwds (reverse kwds)))
3440 (setq kwds (nreverse kwds))
3441 (let (inter kws kw)
3442 (while (setq kws (pop kwds))
3443 (let ((kws (or
3444 (run-hook-with-args-until-success
3445 'org-todo-setup-filter-hook kws)
3446 kws)))
3447 (setq inter (pop kws) sep (member "|" kws)
3448 kws0 (delete "|" (copy-sequence kws))
3449 kwsa nil
3450 kws1 (mapcar
3451 (lambda (x)
3452 ;; 1 2
3453 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3454 (progn
3455 (setq kw (match-string 1 x)
3456 key (and (match-end 2) (match-string 2 x))
3457 log (org-extract-log-state-settings x))
3458 (push (cons kw (and key (string-to-char key))) kwsa)
3459 (and log (push log org-todo-log-states))
3461 (error "Invalid TODO keyword %s" x)))
3462 kws0)
3463 kwsa (if kwsa (append '((:startgroup))
3464 (nreverse kwsa)
3465 '((:endgroup))))
3466 hw (car kws1)
3467 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3468 tail (list inter hw (car dws) (org-last dws))))
3469 (add-to-list 'org-todo-heads hw 'append)
3470 (push kws1 org-todo-sets)
3471 (setq org-done-keywords (append org-done-keywords dws nil))
3472 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3473 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3474 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3475 (setq org-todo-sets (nreverse org-todo-sets)
3476 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3477 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3478 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3479 ;; Process the constants
3480 (when const
3481 (let (e cst)
3482 (while (setq e (pop const))
3483 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3484 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3485 (setq org-table-formula-constants-local cst)))
3487 ;; Process the tags.
3488 (when tags
3489 (let (e tgs)
3490 (while (setq e (pop tags))
3491 (cond
3492 ((equal e "{") (push '(:startgroup) tgs))
3493 ((equal e "}") (push '(:endgroup) tgs))
3494 ((equal e "\\n") (push '(:newline) tgs))
3495 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3496 (push (cons (match-string 1 e)
3497 (string-to-char (match-string 2 e)))
3498 tgs))
3499 (t (push (list e) tgs))))
3500 (org-set-local 'org-tag-alist nil)
3501 (while (setq e (pop tgs))
3502 (or (and (stringp (car e))
3503 (assoc (car e) org-tag-alist))
3504 (push e org-tag-alist)))))
3506 ;; Compute the regular expressions and other local variables
3507 (if (not org-done-keywords)
3508 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3509 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3510 (length org-scheduled-string)
3511 (length org-clock-string)
3512 (length org-closed-string)))
3513 org-drawer-regexp
3514 (concat "^[ \t]*:\\("
3515 (mapconcat 'regexp-quote org-drawers "\\|")
3516 "\\):[ \t]*$")
3517 org-not-done-keywords
3518 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3519 org-todo-regexp
3520 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3521 "\\|") "\\)\\>")
3522 org-not-done-regexp
3523 (concat "\\<\\("
3524 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3525 "\\)\\>")
3526 org-todo-line-regexp
3527 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3528 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3529 "\\)\\>\\)?[ \t]*\\(.*\\)")
3530 org-complex-heading-regexp
3531 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3532 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3533 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3534 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3535 org-nl-done-regexp
3536 (concat "\n\\*+[ \t]+"
3537 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3538 "\\)" "\\>")
3539 org-todo-line-tags-regexp
3540 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3541 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3542 (org-re
3543 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3544 org-looking-at-done-regexp
3545 (concat "^" "\\(?:"
3546 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3547 "\\>")
3548 org-deadline-regexp (concat "\\<" org-deadline-string)
3549 org-deadline-time-regexp
3550 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3551 org-deadline-line-regexp
3552 (concat "\\<\\(" org-deadline-string "\\).*")
3553 org-scheduled-regexp
3554 (concat "\\<" org-scheduled-string)
3555 org-scheduled-time-regexp
3556 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3557 org-closed-time-regexp
3558 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3559 org-keyword-time-regexp
3560 (concat "\\<\\(" org-scheduled-string
3561 "\\|" org-deadline-string
3562 "\\|" org-closed-string
3563 "\\|" org-clock-string "\\)"
3564 " *[[<]\\([^]>]+\\)[]>]")
3565 org-keyword-time-not-clock-regexp
3566 (concat "\\<\\(" org-scheduled-string
3567 "\\|" org-deadline-string
3568 "\\|" org-closed-string
3569 "\\)"
3570 " *[[<]\\([^]>]+\\)[]>]")
3571 org-maybe-keyword-time-regexp
3572 (concat "\\(\\<\\(" org-scheduled-string
3573 "\\|" org-deadline-string
3574 "\\|" org-closed-string
3575 "\\|" org-clock-string "\\)\\)?"
3576 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3577 org-planning-or-clock-line-re
3578 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3579 "\\|" org-deadline-string
3580 "\\|" org-closed-string "\\|" org-clock-string
3581 "\\)\\>\\)")
3583 (org-compute-latex-and-specials-regexp)
3584 (org-set-font-lock-defaults))))
3586 (defun org-file-contents (file &optional noerror)
3587 "Return the contents of FILE, as a string."
3588 (if (or (not file)
3589 (not (file-readable-p file)))
3590 (if noerror
3591 (progn
3592 (message "Cannot read file %s" file)
3593 (ding) (sit-for 2)
3595 (error "Cannot read file %s" file))
3596 (with-temp-buffer
3597 (insert-file-contents file)
3598 (buffer-string))))
3600 (defun org-extract-log-state-settings (x)
3601 "Extract the log state setting from a TODO keyword string.
3602 This will extract info from a string like \"WAIT(w@/!)\"."
3603 (let (kw key log1 log2)
3604 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3605 (setq kw (match-string 1 x)
3606 key (and (match-end 2) (match-string 2 x))
3607 log1 (and (match-end 3) (match-string 3 x))
3608 log2 (and (match-end 4) (match-string 4 x)))
3609 (and (or log1 log2)
3610 (list kw
3611 (and log1 (if (equal log1 "!") 'time 'note))
3612 (and log2 (if (equal log2 "!") 'time 'note)))))))
3614 (defun org-remove-keyword-keys (list)
3615 "Remove a pair of parenthesis at the end of each string in LIST."
3616 (mapcar (lambda (x)
3617 (if (string-match "(.*)$" x)
3618 (substring x 0 (match-beginning 0))
3620 list))
3622 ;; FIXME: this could be done much better, using second characters etc.
3623 (defun org-assign-fast-keys (alist)
3624 "Assign fast keys to a keyword-key alist.
3625 Respect keys that are already there."
3626 (let (new e k c c1 c2 (char ?a))
3627 (while (setq e (pop alist))
3628 (cond
3629 ((equal e '(:startgroup)) (push e new))
3630 ((equal e '(:endgroup)) (push e new))
3631 ((equal e '(:newline)) (push e new))
3633 (setq k (car e) c2 nil)
3634 (if (cdr e)
3635 (setq c (cdr e))
3636 ;; automatically assign a character.
3637 (setq c1 (string-to-char
3638 (downcase (substring
3639 k (if (= (string-to-char k) ?@) 1 0)))))
3640 (if (or (rassoc c1 new) (rassoc c1 alist))
3641 (while (or (rassoc char new) (rassoc char alist))
3642 (setq char (1+ char)))
3643 (setq c2 c1))
3644 (setq c (or c2 char)))
3645 (push (cons k c) new))))
3646 (nreverse new)))
3648 ;;; Some variables used in various places
3650 (defvar org-window-configuration nil
3651 "Used in various places to store a window configuration.")
3652 (defvar org-finish-function nil
3653 "Function to be called when `C-c C-c' is used.
3654 This is for getting out of special buffers like remember.")
3657 ;; FIXME: Occasionally check by commenting these, to make sure
3658 ;; no other functions uses these, forgetting to let-bind them.
3659 (defvar entry)
3660 (defvar state)
3661 (defvar last-state)
3662 (defvar date)
3663 (defvar description)
3665 ;; Defined somewhere in this file, but used before definition.
3666 (defvar org-html-entities)
3667 (defvar org-struct-menu)
3668 (defvar org-org-menu)
3669 (defvar org-tbl-menu)
3670 (defvar org-agenda-keymap)
3672 ;;;; Define the Org-mode
3674 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3675 (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."))
3678 ;; We use a before-change function to check if a table might need
3679 ;; an update.
3680 (defvar org-table-may-need-update t
3681 "Indicates that a table might need an update.
3682 This variable is set by `org-before-change-function'.
3683 `org-table-align' sets it back to nil.")
3684 (defun org-before-change-function (beg end)
3685 "Every change indicates that a table might need an update."
3686 (setq org-table-may-need-update t))
3687 (defvar org-mode-map)
3688 (defvar org-mode-hook nil
3689 "Mode hook for Org-mode, run after the mode was turned on.")
3690 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3691 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3692 (defvar org-table-buffer-is-an nil)
3693 (defconst org-outline-regexp "\\*+ ")
3695 ;;;###autoload
3696 (define-derived-mode org-mode outline-mode "Org"
3697 "Outline-based notes management and organizer, alias
3698 \"Carsten's outline-mode for keeping track of everything.\"
3700 Org-mode develops organizational tasks around a NOTES file which
3701 contains information about projects as plain text. Org-mode is
3702 implemented on top of outline-mode, which is ideal to keep the content
3703 of large files well structured. It supports ToDo items, deadlines and
3704 time stamps, which magically appear in the diary listing of the Emacs
3705 calendar. Tables are easily created with a built-in table editor.
3706 Plain text URL-like links connect to websites, emails (VM), Usenet
3707 messages (Gnus), BBDB entries, and any files related to the project.
3708 For printing and sharing of notes, an Org-mode file (or a part of it)
3709 can be exported as a structured ASCII or HTML file.
3711 The following commands are available:
3713 \\{org-mode-map}"
3715 ;; Get rid of Outline menus, they are not needed
3716 ;; Need to do this here because define-derived-mode sets up
3717 ;; the keymap so late. Still, it is a waste to call this each time
3718 ;; we switch another buffer into org-mode.
3719 (if (featurep 'xemacs)
3720 (when (boundp 'outline-mode-menu-heading)
3721 ;; Assume this is Greg's port, it used easymenu
3722 (easy-menu-remove outline-mode-menu-heading)
3723 (easy-menu-remove outline-mode-menu-show)
3724 (easy-menu-remove outline-mode-menu-hide))
3725 (define-key org-mode-map [menu-bar headings] 'undefined)
3726 (define-key org-mode-map [menu-bar hide] 'undefined)
3727 (define-key org-mode-map [menu-bar show] 'undefined))
3729 (org-load-modules-maybe)
3730 (easy-menu-add org-org-menu)
3731 (easy-menu-add org-tbl-menu)
3732 (org-install-agenda-files-menu)
3733 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3734 (org-add-to-invisibility-spec '(org-cwidth))
3735 (when (featurep 'xemacs)
3736 (org-set-local 'line-move-ignore-invisible t))
3737 (org-set-local 'outline-regexp org-outline-regexp)
3738 (org-set-local 'outline-level 'org-outline-level)
3739 (when (and org-ellipsis
3740 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3741 (fboundp 'make-glyph-code))
3742 (unless org-display-table
3743 (setq org-display-table (make-display-table)))
3744 (set-display-table-slot
3745 org-display-table 4
3746 (vconcat (mapcar
3747 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3748 org-ellipsis)))
3749 (if (stringp org-ellipsis) org-ellipsis "..."))))
3750 (setq buffer-display-table org-display-table))
3751 (org-set-regexps-and-options)
3752 (when (and org-tag-faces (not org-tags-special-faces-re))
3753 ;; tag faces set outside customize.... force initialization.
3754 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3755 ;; Calc embedded
3756 (org-set-local 'calc-embedded-open-mode "# ")
3757 (modify-syntax-entry ?# "<")
3758 (modify-syntax-entry ?@ "w")
3759 (if org-startup-truncated (setq truncate-lines t))
3760 (org-set-local 'font-lock-unfontify-region-function
3761 'org-unfontify-region)
3762 ;; Activate before-change-function
3763 (org-set-local 'org-table-may-need-update t)
3764 (org-add-hook 'before-change-functions 'org-before-change-function nil
3765 'local)
3766 ;; Check for running clock before killing a buffer
3767 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3768 ;; Paragraphs and auto-filling
3769 (org-set-autofill-regexps)
3770 (setq indent-line-function 'org-indent-line-function)
3771 (org-update-radio-target-regexp)
3772 ;; Make sure dependence stuff works reliably, even for users who set it
3773 ;; too late :-(
3774 (if org-enforce-todo-dependencies
3775 (add-hook 'org-blocker-hook
3776 'org-block-todo-from-children-or-siblings)
3777 (remove-hook 'org-blocker-hook
3778 'org-block-todo-from-children-or-siblings))
3779 (if org-enforce-todo-checkbox-dependencies
3780 (add-hook 'org-blocker-hook
3781 'org-block-todo-from-checkboxes)
3782 (remove-hook 'org-blocker-hook
3783 'org-block-todo-from-checkboxes))
3785 ;; Comment characters
3786 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3787 (org-set-local 'comment-padding " ")
3789 ;; Align options lines
3790 (org-set-local
3791 'align-mode-rules-list
3792 '((org-in-buffer-settings
3793 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3794 (modes . '(org-mode)))))
3796 ;; Imenu
3797 (org-set-local 'imenu-create-index-function
3798 'org-imenu-get-tree)
3800 ;; Make isearch reveal context
3801 (if (or (featurep 'xemacs)
3802 (not (boundp 'outline-isearch-open-invisible-function)))
3803 ;; Emacs 21 and XEmacs make use of the hook
3804 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3805 ;; Emacs 22 deals with this through a special variable
3806 (org-set-local 'outline-isearch-open-invisible-function
3807 (lambda (&rest ignore) (org-show-context 'isearch))))
3809 ;; If empty file that did not turn on org-mode automatically, make it to.
3810 (if (and org-insert-mode-line-in-empty-file
3811 (interactive-p)
3812 (= (point-min) (point-max)))
3813 (insert "# -*- mode: org -*-\n\n"))
3815 (unless org-inhibit-startup
3816 (when org-startup-align-all-tables
3817 (let ((bmp (buffer-modified-p)))
3818 (org-table-map-tables 'org-table-align)
3819 (set-buffer-modified-p bmp)))
3820 (org-set-startup-visibility)))
3822 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3824 (defun org-current-time ()
3825 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3826 (if (> (car org-time-stamp-rounding-minutes) 1)
3827 (let ((r (car org-time-stamp-rounding-minutes))
3828 (time (decode-time)))
3829 (apply 'encode-time
3830 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3831 (nthcdr 2 time))))
3832 (current-time)))
3834 ;;;; Font-Lock stuff, including the activators
3836 (defvar org-mouse-map (make-sparse-keymap))
3837 (org-defkey org-mouse-map
3838 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3839 (org-defkey org-mouse-map
3840 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3841 (when org-mouse-1-follows-link
3842 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3843 (when org-tab-follows-link
3844 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3845 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3847 (require 'font-lock)
3849 (defconst org-non-link-chars "]\t\n\r<>")
3850 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3851 "shell" "elisp"))
3852 (defvar org-link-types-re nil
3853 "Matches a link that has a url-like prefix like \"http:\"")
3854 (defvar org-link-re-with-space nil
3855 "Matches a link with spaces, optional angular brackets around it.")
3856 (defvar org-link-re-with-space2 nil
3857 "Matches a link with spaces, optional angular brackets around it.")
3858 (defvar org-link-re-with-space3 nil
3859 "Matches a link with spaces, only for internal part in bracket links.")
3860 (defvar org-angle-link-re nil
3861 "Matches link with angular brackets, spaces are allowed.")
3862 (defvar org-plain-link-re nil
3863 "Matches plain link, without spaces.")
3864 (defvar org-bracket-link-regexp nil
3865 "Matches a link in double brackets.")
3866 (defvar org-bracket-link-analytic-regexp nil
3867 "Regular expression used to analyze links.
3868 Here is what the match groups contain after a match:
3869 1: http:
3870 2: http
3871 3: path
3872 4: [desc]
3873 5: desc")
3874 (defvar org-bracket-link-analytic-regexp++ nil
3875 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3876 (defvar org-any-link-re nil
3877 "Regular expression matching any link.")
3879 (defun org-make-link-regexps ()
3880 "Update the link regular expressions.
3881 This should be called after the variable `org-link-types' has changed."
3882 (setq org-link-types-re
3883 (concat
3884 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3885 org-link-re-with-space
3886 (concat
3887 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3888 "\\([^" org-non-link-chars " ]"
3889 "[^" org-non-link-chars "]*"
3890 "[^" org-non-link-chars " ]\\)>?")
3891 org-link-re-with-space2
3892 (concat
3893 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3894 "\\([^" org-non-link-chars " ]"
3895 "[^\t\n\r]*"
3896 "[^" org-non-link-chars " ]\\)>?")
3897 org-link-re-with-space3
3898 (concat
3899 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3900 "\\([^" org-non-link-chars " ]"
3901 "[^\t\n\r]*\\)")
3902 org-angle-link-re
3903 (concat
3904 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3905 "\\([^" org-non-link-chars " ]"
3906 "[^" org-non-link-chars "]*"
3907 "\\)>")
3908 org-plain-link-re
3909 (concat
3910 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3911 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3912 org-bracket-link-regexp
3913 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3914 org-bracket-link-analytic-regexp
3915 (concat
3916 "\\[\\["
3917 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3918 "\\([^]]+\\)"
3919 "\\]"
3920 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3921 "\\]")
3922 org-bracket-link-analytic-regexp++
3923 (concat
3924 "\\[\\["
3925 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3926 "\\([^]]+\\)"
3927 "\\]"
3928 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3929 "\\]")
3930 org-any-link-re
3931 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3932 org-angle-link-re "\\)\\|\\("
3933 org-plain-link-re "\\)")))
3935 (org-make-link-regexps)
3937 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3938 "Regular expression for fast time stamp matching.")
3939 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3940 "Regular expression for fast time stamp matching.")
3941 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3942 "Regular expression matching time strings for analysis.
3943 This one does not require the space after the date, so it can be used
3944 on a string that terminates immediately after the date.")
3945 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3946 "Regular expression matching time strings for analysis.")
3947 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3948 "Regular expression matching time stamps, with groups.")
3949 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3950 "Regular expression matching time stamps (also [..]), with groups.")
3951 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3952 "Regular expression matching a time stamp range.")
3953 (defconst org-tr-regexp-both
3954 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3955 "Regular expression matching a time stamp range.")
3956 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3957 org-ts-regexp "\\)?")
3958 "Regular expression matching a time stamp or time stamp range.")
3959 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3960 org-ts-regexp-both "\\)?")
3961 "Regular expression matching a time stamp or time stamp range.
3962 The time stamps may be either active or inactive.")
3964 (defvar org-emph-face nil)
3966 (defun org-do-emphasis-faces (limit)
3967 "Run through the buffer and add overlays to links."
3968 (let (rtn)
3969 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3970 (if (not (= (char-after (match-beginning 3))
3971 (char-after (match-beginning 4))))
3972 (progn
3973 (setq rtn t)
3974 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3975 'face
3976 (nth 1 (assoc (match-string 3)
3977 org-emphasis-alist)))
3978 (add-text-properties (match-beginning 2) (match-end 2)
3979 '(font-lock-multiline t))
3980 (when org-hide-emphasis-markers
3981 (add-text-properties (match-end 4) (match-beginning 5)
3982 '(invisible org-link))
3983 (add-text-properties (match-beginning 3) (match-end 3)
3984 '(invisible org-link)))))
3985 (backward-char 1))
3986 rtn))
3988 (defun org-emphasize (&optional char)
3989 "Insert or change an emphasis, i.e. a font like bold or italic.
3990 If there is an active region, change that region to a new emphasis.
3991 If there is no region, just insert the marker characters and position
3992 the cursor between them.
3993 CHAR should be either the marker character, or the first character of the
3994 HTML tag associated with that emphasis. If CHAR is a space, the means
3995 to remove the emphasis of the selected region.
3996 If char is not given (for example in an interactive call) it
3997 will be prompted for."
3998 (interactive)
3999 (let ((eal org-emphasis-alist) e det
4000 (erc org-emphasis-regexp-components)
4001 (prompt "")
4002 (string "") beg end move tag c s)
4003 (if (org-region-active-p)
4004 (setq beg (region-beginning) end (region-end)
4005 string (buffer-substring beg end))
4006 (setq move t))
4008 (while (setq e (pop eal))
4009 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4010 c (aref tag 0))
4011 (push (cons c (string-to-char (car e))) det)
4012 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4013 (substring tag 1)))))
4014 (setq det (nreverse det))
4015 (unless char
4016 (message "%s" (concat "Emphasis marker or tag:" prompt))
4017 (setq char (read-char-exclusive)))
4018 (setq char (or (cdr (assoc char det)) char))
4019 (if (equal char ?\ )
4020 (setq s "" move nil)
4021 (unless (assoc (char-to-string char) org-emphasis-alist)
4022 (error "No such emphasis marker: \"%c\"" char))
4023 (setq s (char-to-string char)))
4024 (while (and (> (length string) 1)
4025 (equal (substring string 0 1) (substring string -1))
4026 (assoc (substring string 0 1) org-emphasis-alist))
4027 (setq string (substring string 1 -1)))
4028 (setq string (concat s string s))
4029 (if beg (delete-region beg end))
4030 (unless (or (bolp)
4031 (string-match (concat "[" (nth 0 erc) "\n]")
4032 (char-to-string (char-before (point)))))
4033 (insert " "))
4034 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4035 (char-to-string (char-after (point))))
4036 (insert " ") (backward-char 1))
4037 (insert string)
4038 (and move (backward-char 1))))
4040 (defconst org-nonsticky-props
4041 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4044 (defun org-activate-plain-links (limit)
4045 "Run through the buffer and add overlays to links."
4046 (catch 'exit
4047 (let (f)
4048 (while (re-search-forward org-plain-link-re limit t)
4049 (setq f (get-text-property (match-beginning 0) 'face))
4050 (if (or (eq f 'org-tag)
4051 (and (listp f) (memq 'org-tag f)))
4053 (add-text-properties (match-beginning 0) (match-end 0)
4054 (list 'mouse-face 'highlight
4055 'rear-nonsticky org-nonsticky-props
4056 'keymap org-mouse-map
4058 (throw 'exit t))))))
4060 (defun org-activate-code (limit)
4061 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4062 (progn
4063 (remove-text-properties (match-beginning 0) (match-end 0)
4064 '(display t invisible t intangible t))
4065 t)))
4067 (defun org-activate-angle-links (limit)
4068 "Run through the buffer and add overlays to links."
4069 (if (re-search-forward org-angle-link-re limit t)
4070 (progn
4071 (add-text-properties (match-beginning 0) (match-end 0)
4072 (list 'mouse-face 'highlight
4073 'rear-nonsticky org-nonsticky-props
4074 'keymap org-mouse-map
4076 t)))
4078 (defun org-activate-footnote-links (limit)
4079 "Run through the buffer and add overlays to links."
4080 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4081 limit t)
4082 (progn
4083 (add-text-properties (match-beginning 2) (match-end 2)
4084 (list 'mouse-face 'highlight
4085 'rear-nonsticky org-nonsticky-props
4086 'keymap org-mouse-map
4087 'help-echo
4088 (if (= (point-at-bol) (match-beginning 2))
4089 "Footnote definition"
4090 "Footnote reference")
4092 t)))
4094 (defun org-activate-bracket-links (limit)
4095 "Run through the buffer and add overlays to bracketed links."
4096 (if (re-search-forward org-bracket-link-regexp limit t)
4097 (let* ((help (concat "LINK: "
4098 (org-match-string-no-properties 1)))
4099 ;; FIXME: above we should remove the escapes.
4100 ;; but that requires another match, protecting match data,
4101 ;; a lot of overhead for font-lock.
4102 (ip (org-maybe-intangible
4103 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4104 'keymap org-mouse-map 'mouse-face 'highlight
4105 'font-lock-multiline t 'help-echo help)))
4106 (vp (list 'rear-nonsticky org-nonsticky-props
4107 'keymap org-mouse-map 'mouse-face 'highlight
4108 'font-lock-multiline t 'help-echo help)))
4109 ;; We need to remove the invisible property here. Table narrowing
4110 ;; may have made some of this invisible.
4111 (remove-text-properties (match-beginning 0) (match-end 0)
4112 '(invisible nil))
4113 (if (match-end 3)
4114 (progn
4115 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4116 (add-text-properties (match-beginning 3) (match-end 3) vp)
4117 (add-text-properties (match-end 3) (match-end 0) ip))
4118 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4119 (add-text-properties (match-beginning 1) (match-end 1) vp)
4120 (add-text-properties (match-end 1) (match-end 0) ip))
4121 t)))
4123 (defun org-activate-dates (limit)
4124 "Run through the buffer and add overlays to dates."
4125 (if (re-search-forward org-tsr-regexp-both limit t)
4126 (progn
4127 (add-text-properties (match-beginning 0) (match-end 0)
4128 (list 'mouse-face 'highlight
4129 'rear-nonsticky org-nonsticky-props
4130 'keymap org-mouse-map))
4131 (when org-display-custom-times
4132 (if (match-end 3)
4133 (org-display-custom-time (match-beginning 3) (match-end 3)))
4134 (org-display-custom-time (match-beginning 1) (match-end 1)))
4135 t)))
4137 (defvar org-target-link-regexp nil
4138 "Regular expression matching radio targets in plain text.")
4139 (make-variable-buffer-local 'org-target-link-regexp)
4140 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4141 "Regular expression matching a link target.")
4142 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4143 "Regular expression matching a radio target.")
4144 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4145 "Regular expression matching any target.")
4147 (defun org-activate-target-links (limit)
4148 "Run through the buffer and add overlays to target matches."
4149 (when org-target-link-regexp
4150 (let ((case-fold-search t))
4151 (if (re-search-forward org-target-link-regexp limit t)
4152 (progn
4153 (add-text-properties (match-beginning 0) (match-end 0)
4154 (list 'mouse-face 'highlight
4155 'rear-nonsticky org-nonsticky-props
4156 'keymap org-mouse-map
4157 'help-echo "Radio target link"
4158 'org-linked-text t))
4159 t)))))
4161 (defun org-update-radio-target-regexp ()
4162 "Find all radio targets in this file and update the regular expression."
4163 (interactive)
4164 (when (memq 'radio org-activate-links)
4165 (setq org-target-link-regexp
4166 (org-make-target-link-regexp (org-all-targets 'radio)))
4167 (org-restart-font-lock)))
4169 (defun org-hide-wide-columns (limit)
4170 (let (s e)
4171 (setq s (text-property-any (point) (or limit (point-max))
4172 'org-cwidth t))
4173 (when s
4174 (setq e (next-single-property-change s 'org-cwidth))
4175 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4176 (goto-char e)
4177 t)))
4179 (defvar org-latex-and-specials-regexp nil
4180 "Regular expression for highlighting export special stuff.")
4181 (defvar org-match-substring-regexp)
4182 (defvar org-match-substring-with-braces-regexp)
4183 (defvar org-export-html-special-string-regexps)
4185 (defun org-compute-latex-and-specials-regexp ()
4186 "Compute regular expression for stuff treated specially by exporters."
4187 (if (not org-highlight-latex-fragments-and-specials)
4188 (org-set-local 'org-latex-and-specials-regexp nil)
4189 (require 'org-exp)
4190 (let*
4191 ((matchers (plist-get org-format-latex-options :matchers))
4192 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4193 org-latex-regexps)))
4194 (options (org-combine-plists (org-default-export-plist)
4195 (org-infile-export-plist)))
4196 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4197 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4198 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4199 (org-export-html-expand (plist-get options :expand-quoted-html))
4200 (org-export-with-special-strings (plist-get options :special-strings))
4201 (re-sub
4202 (cond
4203 ((equal org-export-with-sub-superscripts '{})
4204 (list org-match-substring-with-braces-regexp))
4205 (org-export-with-sub-superscripts
4206 (list org-match-substring-regexp))
4207 (t nil)))
4208 (re-latex
4209 (if org-export-with-LaTeX-fragments
4210 (mapcar (lambda (x) (nth 1 x)) latexs)))
4211 (re-macros
4212 (if org-export-with-TeX-macros
4213 (list (concat "\\\\"
4214 (regexp-opt
4215 (append (mapcar 'car org-html-entities)
4216 (if (boundp 'org-latex-entities)
4217 org-latex-entities nil))
4218 'words))) ; FIXME
4220 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4221 (re-special (if org-export-with-special-strings
4222 (mapcar (lambda (x) (car x))
4223 org-export-html-special-string-regexps)))
4224 (re-rest
4225 (delq nil
4226 (list
4227 (if org-export-html-expand "@<[^>\n]+>")
4228 ))))
4229 (org-set-local
4230 'org-latex-and-specials-regexp
4231 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4232 re-rest) "\\|")))))
4234 (defun org-do-latex-and-special-faces (limit)
4235 "Run through the buffer and add overlays to links."
4236 (when org-latex-and-specials-regexp
4237 (let (rtn d)
4238 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4239 limit t))
4240 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4241 'face))
4242 '(org-code org-verbatim underline)))
4243 (progn
4244 (setq rtn t
4245 d (cond ((member (char-after (1+ (match-beginning 0)))
4246 '(?_ ?^)) 1)
4247 (t 0)))
4248 (font-lock-prepend-text-property
4249 (+ d (match-beginning 0)) (match-end 0)
4250 'face 'org-latex-and-export-specials)
4251 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4252 '(font-lock-multiline t)))))
4253 rtn)))
4255 (defun org-restart-font-lock ()
4256 "Restart font-lock-mode, to force refontification."
4257 (when (and (boundp 'font-lock-mode) font-lock-mode)
4258 (font-lock-mode -1)
4259 (font-lock-mode 1)))
4261 (defun org-all-targets (&optional radio)
4262 "Return a list of all targets in this file.
4263 With optional argument RADIO, only find radio targets."
4264 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4265 rtn)
4266 (save-excursion
4267 (goto-char (point-min))
4268 (while (re-search-forward re nil t)
4269 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4270 rtn)))
4272 (defun org-make-target-link-regexp (targets)
4273 "Make regular expression matching all strings in TARGETS.
4274 The regular expression finds the targets also if there is a line break
4275 between words."
4276 (and targets
4277 (concat
4278 "\\<\\("
4279 (mapconcat
4280 (lambda (x)
4281 (while (string-match " +" x)
4282 (setq x (replace-match "\\s-+" t t x)))
4284 targets
4285 "\\|")
4286 "\\)\\>")))
4288 (defun org-activate-tags (limit)
4289 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4290 (progn
4291 (add-text-properties (match-beginning 1) (match-end 1)
4292 (list 'mouse-face 'highlight
4293 'rear-nonsticky org-nonsticky-props
4294 'keymap org-mouse-map))
4295 t)))
4297 (defun org-outline-level ()
4298 (save-excursion
4299 (looking-at outline-regexp)
4300 (if (match-beginning 1)
4301 (+ (org-get-string-indentation (match-string 1)) 1000)
4302 (1- (- (match-end 0) (match-beginning 0))))))
4304 (defvar org-font-lock-keywords nil)
4306 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4307 "Regular expression matching a property line.")
4309 (defvar org-font-lock-hook nil
4310 "Functions to be called for special font lock stuff.")
4312 (defun org-font-lock-hook (limit)
4313 (run-hook-with-args 'org-font-lock-hook limit))
4315 (defun org-set-font-lock-defaults ()
4316 (let* ((em org-fontify-emphasized-text)
4317 (lk org-activate-links)
4318 (org-font-lock-extra-keywords
4319 (list
4320 ;; Call the hook
4321 '(org-font-lock-hook)
4322 ;; Headlines
4323 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4324 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4325 ;; Table lines
4326 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4327 (1 'org-table t))
4328 ;; Table internals
4329 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4330 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4331 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4332 ;; Drawers
4333 (list org-drawer-regexp '(0 'org-special-keyword t))
4334 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4335 ;; Properties
4336 (list org-property-re
4337 '(1 'org-special-keyword t)
4338 '(3 'org-property-value t))
4339 (if org-format-transports-properties-p
4340 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4341 ;; Links
4342 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4343 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4344 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4345 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4346 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4347 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4348 (if (memq 'footnote lk) '(org-activate-footnote-links
4349 (2 'org-footnote t)))
4350 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4351 '(org-hide-wide-columns (0 nil append))
4352 ;; TODO lines
4353 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4354 '(1 (org-get-todo-face 1) t))
4355 ;; DONE
4356 (if org-fontify-done-headline
4357 (list (concat "^[*]+ +\\<\\("
4358 (mapconcat 'regexp-quote org-done-keywords "\\|")
4359 "\\)\\(.*\\)")
4360 '(2 'org-headline-done t))
4361 nil)
4362 ;; Priorities
4363 '(org-font-lock-add-priority-faces)
4364 ;; Tags
4365 '(org-font-lock-add-tag-faces)
4366 ;; Special keywords
4367 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4368 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4369 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4370 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4371 ;; Emphasis
4372 (if em
4373 (if (featurep 'xemacs)
4374 '(org-do-emphasis-faces (0 nil append))
4375 '(org-do-emphasis-faces)))
4376 ;; Checkboxes
4377 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4378 2 'org-checkbox prepend)
4379 (if org-provide-checkbox-statistics
4380 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4381 (0 (org-get-checkbox-statistics-face) t)))
4382 ;; Description list items
4383 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4384 2 'bold prepend)
4385 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4386 '(1 'org-archived prepend))
4387 ;; Specials
4388 '(org-do-latex-and-special-faces)
4389 ;; Code
4390 '(org-activate-code (1 'org-code t))
4391 ;; COMMENT
4392 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4393 "\\|" org-quote-string "\\)\\>")
4394 '(1 'org-special-keyword t))
4395 '("^#.*" (0 'font-lock-comment-face t))
4397 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4398 ;; Now set the full font-lock-keywords
4399 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4400 (org-set-local 'font-lock-defaults
4401 '(org-font-lock-keywords t nil nil backward-paragraph))
4402 (kill-local-variable 'font-lock-keywords) nil))
4404 (defvar org-m nil)
4405 (defvar org-l nil)
4406 (defvar org-f nil)
4407 (defun org-get-level-face (n)
4408 "Get the right face for match N in font-lock matching of headlines."
4409 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4410 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4411 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4412 (cond
4413 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4414 ((eq n 2) org-f)
4415 (t (if org-level-color-stars-only nil org-f))))
4417 (defun org-get-todo-face (kwd)
4418 "Get the right face for a TODO keyword KWD.
4419 If KWD is a number, get the corresponding match group."
4420 (if (numberp kwd) (setq kwd (match-string kwd)))
4421 (or (cdr (assoc kwd org-todo-keyword-faces))
4422 (and (member kwd org-done-keywords) 'org-done)
4423 'org-todo))
4425 (defun org-font-lock-add-tag-faces (limit)
4426 "Add the special tag faces."
4427 (when (and org-tag-faces org-tags-special-faces-re)
4428 (while (re-search-forward org-tags-special-faces-re limit t)
4429 (add-text-properties (match-beginning 1) (match-end 1)
4430 (list 'face (org-get-tag-face 1)
4431 'font-lock-fontified t))
4432 (backward-char 1))))
4434 (defun org-font-lock-add-priority-faces (limit)
4435 "Add the special priority faces."
4436 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4437 (add-text-properties
4438 (match-beginning 0) (match-end 0)
4439 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4440 org-priority-faces))
4441 'org-special-keyword)
4442 'font-lock-fontified t))))
4444 (defun org-get-tag-face (kwd)
4445 "Get the right face for a TODO keyword KWD.
4446 If KWD is a number, get the corresponding match group."
4447 (if (numberp kwd) (setq kwd (match-string kwd)))
4448 (or (cdr (assoc kwd org-tag-faces))
4449 'org-tag))
4451 (defun org-unfontify-region (beg end &optional maybe_loudly)
4452 "Remove fontification and activation overlays from links."
4453 (font-lock-default-unfontify-region beg end)
4454 (let* ((buffer-undo-list t)
4455 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4456 (inhibit-modification-hooks t)
4457 deactivate-mark buffer-file-name buffer-file-truename)
4458 (remove-text-properties beg end
4459 '(mouse-face t keymap t org-linked-text t
4460 invisible t intangible t))))
4462 ;;;; Visibility cycling, including org-goto and indirect buffer
4464 ;;; Cycling
4466 (defvar org-cycle-global-status nil)
4467 (make-variable-buffer-local 'org-cycle-global-status)
4468 (defvar org-cycle-subtree-status nil)
4469 (make-variable-buffer-local 'org-cycle-subtree-status)
4471 ;;;###autoload
4472 (defun org-cycle (&optional arg)
4473 "Visibility cycling for Org-mode.
4475 - When this function is called with a prefix argument, rotate the entire
4476 buffer through 3 states (global cycling)
4477 1. OVERVIEW: Show only top-level headlines.
4478 2. CONTENTS: Show all headlines of all levels, but no body text.
4479 3. SHOW ALL: Show everything.
4480 When called with two C-u C-u prefixes, switch to the startup visibility,
4481 determined by the variable `org-startup-folded', and by any VISIBILITY
4482 properties in the buffer.
4483 When called with three C-u C-u C-u prefixed, show the entire buffer,
4484 including drawers.
4486 - When point is at the beginning of a headline, rotate the subtree started
4487 by this line through 3 different states (local cycling)
4488 1. FOLDED: Only the main headline is shown.
4489 2. CHILDREN: The main headline and the direct children are shown.
4490 From this state, you can move to one of the children
4491 and zoom in further.
4492 3. SUBTREE: Show the entire subtree, including body text.
4494 - When there is a numeric prefix, go up to a heading with level ARG, do
4495 a `show-subtree' and return to the previous cursor position. If ARG
4496 is negative, go up that many levels.
4498 - When point is not at the beginning of a headline, execute the global
4499 binding for TAB, which is re-indenting the line. See the option
4500 `org-cycle-emulate-tab' for details.
4502 - Special case: if point is at the beginning of the buffer and there is
4503 no headline in line 1, this function will act as if called with prefix arg.
4504 But only if also the variable `org-cycle-global-at-bob' is t."
4505 (interactive "P")
4506 (org-load-modules-maybe)
4507 (let* ((outline-regexp
4508 (if (and (org-mode-p) org-cycle-include-plain-lists)
4509 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4510 outline-regexp))
4511 (bob-special (and org-cycle-global-at-bob (bobp)
4512 (not (looking-at outline-regexp))))
4513 (org-cycle-hook
4514 (if bob-special
4515 (delq 'org-optimize-window-after-visibility-change
4516 (copy-sequence org-cycle-hook))
4517 org-cycle-hook))
4518 (pos (point)))
4520 (if (or bob-special (equal arg '(4)))
4521 ;; special case: use global cycling
4522 (setq arg t))
4524 (cond
4526 ((equal arg '(16))
4527 (org-set-startup-visibility)
4528 (message "Startup visibility, plus VISIBILITY properties"))
4530 ((equal arg '(64))
4531 (show-all)
4532 (message "Entire buffer visible, including drawers"))
4534 ((org-at-table-p 'any)
4535 ;; Enter the table or move to the next field in the table
4536 (or (org-table-recognize-table.el)
4537 (progn
4538 (if arg (org-table-edit-field t)
4539 (org-table-justify-field-maybe)
4540 (call-interactively 'org-table-next-field)))))
4542 ((eq arg t) ;; Global cycling
4544 (cond
4545 ((and (eq last-command this-command)
4546 (eq org-cycle-global-status 'overview))
4547 ;; We just created the overview - now do table of contents
4548 ;; This can be slow in very large buffers, so indicate action
4549 (message "CONTENTS...")
4550 (org-content)
4551 (message "CONTENTS...done")
4552 (setq org-cycle-global-status 'contents)
4553 (run-hook-with-args 'org-cycle-hook 'contents))
4555 ((and (eq last-command this-command)
4556 (eq org-cycle-global-status 'contents))
4557 ;; We just showed the table of contents - now show everything
4558 (show-all)
4559 (message "SHOW ALL")
4560 (setq org-cycle-global-status 'all)
4561 (run-hook-with-args 'org-cycle-hook 'all))
4564 ;; Default action: go to overview
4565 (org-overview)
4566 (message "OVERVIEW")
4567 (setq org-cycle-global-status 'overview)
4568 (run-hook-with-args 'org-cycle-hook 'overview))))
4570 ((and org-drawers org-drawer-regexp
4571 (save-excursion
4572 (beginning-of-line 1)
4573 (looking-at org-drawer-regexp)))
4574 ;; Toggle block visibility
4575 (org-flag-drawer
4576 (not (get-char-property (match-end 0) 'invisible))))
4578 ((integerp arg)
4579 ;; Show-subtree, ARG levels up from here.
4580 (save-excursion
4581 (org-back-to-heading)
4582 (outline-up-heading (if (< arg 0) (- arg)
4583 (- (funcall outline-level) arg)))
4584 (org-show-subtree)))
4586 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4587 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4588 ;; At a heading: rotate between three different views
4589 (org-back-to-heading)
4590 (let ((goal-column 0) eoh eol eos)
4591 ;; First, some boundaries
4592 (save-excursion
4593 (org-back-to-heading)
4594 (save-excursion
4595 (beginning-of-line 2)
4596 (while (and (not (eobp)) ;; this is like `next-line'
4597 (get-char-property (1- (point)) 'invisible))
4598 (beginning-of-line 2)) (setq eol (point)))
4599 (outline-end-of-heading) (setq eoh (point))
4600 (org-end-of-subtree t)
4601 (unless (eobp)
4602 (skip-chars-forward " \t\n")
4603 (beginning-of-line 1) ; in case this is an item
4605 (setq eos (1- (point))))
4606 ;; Find out what to do next and set `this-command'
4607 (cond
4608 ((= eos eoh)
4609 ;; Nothing is hidden behind this heading
4610 (message "EMPTY ENTRY")
4611 (setq org-cycle-subtree-status nil)
4612 (save-excursion
4613 (goto-char eos)
4614 (outline-next-heading)
4615 (if (org-invisible-p) (org-flag-heading nil))))
4616 ((or (>= eol eos)
4617 (not (string-match "\\S-" (buffer-substring eol eos))))
4618 ;; Entire subtree is hidden in one line: open it
4619 (org-show-entry)
4620 (show-children)
4621 (message "CHILDREN")
4622 (save-excursion
4623 (goto-char eos)
4624 (outline-next-heading)
4625 (if (org-invisible-p) (org-flag-heading nil)))
4626 (setq org-cycle-subtree-status 'children)
4627 (run-hook-with-args 'org-cycle-hook 'children))
4628 ((and (eq last-command this-command)
4629 (eq org-cycle-subtree-status 'children))
4630 ;; We just showed the children, now show everything.
4631 (org-show-subtree)
4632 (message "SUBTREE")
4633 (setq org-cycle-subtree-status 'subtree)
4634 (run-hook-with-args 'org-cycle-hook 'subtree))
4636 ;; Default action: hide the subtree.
4637 (hide-subtree)
4638 (message "FOLDED")
4639 (setq org-cycle-subtree-status 'folded)
4640 (run-hook-with-args 'org-cycle-hook 'folded)))))
4642 ;; TAB emulation and template completion
4643 (buffer-read-only (org-back-to-heading))
4645 ((org-try-structure-completion))
4647 ((org-try-cdlatex-tab))
4649 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4650 (or (not (bolp))
4651 (not (looking-at outline-regexp))))
4652 (call-interactively (global-key-binding "\t")))
4654 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4655 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4656 (or (and (eq org-cycle-emulate-tab 'white)
4657 (= (match-end 0) (point-at-eol)))
4658 (and (eq org-cycle-emulate-tab 'whitestart)
4659 (>= (match-end 0) pos))))
4661 (eq org-cycle-emulate-tab t))
4662 (call-interactively (global-key-binding "\t")))
4664 (t (save-excursion
4665 (org-back-to-heading)
4666 (org-cycle))))))
4668 ;;;###autoload
4669 (defun org-global-cycle (&optional arg)
4670 "Cycle the global visibility. For details see `org-cycle'.
4671 With C-u prefix arg, switch to startup visibility.
4672 With a numeric prefix, show all headlines up to that level."
4673 (interactive "P")
4674 (let ((org-cycle-include-plain-lists
4675 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4676 (cond
4677 ((integerp arg)
4678 (show-all)
4679 (hide-sublevels arg)
4680 (setq org-cycle-global-status 'contents))
4681 ((equal arg '(4))
4682 (org-set-startup-visibility)
4683 (message "Startup visibility, plus VISIBILITY properties."))
4685 (org-cycle '(4))))))
4687 (defun org-set-startup-visibility ()
4688 "Set the visibility required by startup options and properties."
4689 (cond
4690 ((eq org-startup-folded t)
4691 (org-cycle '(4)))
4692 ((eq org-startup-folded 'content)
4693 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4694 (org-cycle '(4)) (org-cycle '(4)))))
4695 (org-set-visibility-according-to-property 'no-cleanup)
4696 (org-cycle-hide-archived-subtrees 'all)
4697 (org-cycle-hide-drawers 'all)
4698 (org-cycle-show-empty-lines 'all))
4700 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4701 "Switch subtree visibilities according to :VISIBILITY: property."
4702 (interactive)
4703 (let (org-show-entry-below state)
4704 (save-excursion
4705 (goto-char (point-min))
4706 (while (re-search-forward
4707 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4708 nil t)
4709 (setq state (match-string 1))
4710 (save-excursion
4711 (org-back-to-heading t)
4712 (hide-subtree)
4713 (org-reveal)
4714 (cond
4715 ((equal state '("fold" "folded"))
4716 (hide-subtree))
4717 ((equal state "children")
4718 (org-show-hidden-entry)
4719 (show-children))
4720 ((equal state "content")
4721 (save-excursion
4722 (save-restriction
4723 (org-narrow-to-subtree)
4724 (org-content))))
4725 ((member state '("all" "showall"))
4726 (show-subtree)))))
4727 (unless no-cleanup
4728 (org-cycle-hide-archived-subtrees 'all)
4729 (org-cycle-hide-drawers 'all)
4730 (org-cycle-show-empty-lines 'all)))))
4732 (defun org-overview ()
4733 "Switch to overview mode, showing only top-level headlines.
4734 Really, this shows all headlines with level equal or greater than the level
4735 of the first headline in the buffer. This is important, because if the
4736 first headline is not level one, then (hide-sublevels 1) gives confusing
4737 results."
4738 (interactive)
4739 (let ((level (save-excursion
4740 (goto-char (point-min))
4741 (if (re-search-forward (concat "^" outline-regexp) nil t)
4742 (progn
4743 (goto-char (match-beginning 0))
4744 (funcall outline-level))))))
4745 (and level (hide-sublevels level))))
4747 (defun org-content (&optional arg)
4748 "Show all headlines in the buffer, like a table of contents.
4749 With numerical argument N, show content up to level N."
4750 (interactive "P")
4751 (save-excursion
4752 ;; Visit all headings and show their offspring
4753 (and (integerp arg) (org-overview))
4754 (goto-char (point-max))
4755 (catch 'exit
4756 (while (and (progn (condition-case nil
4757 (outline-previous-visible-heading 1)
4758 (error (goto-char (point-min))))
4760 (looking-at outline-regexp))
4761 (if (integerp arg)
4762 (show-children (1- arg))
4763 (show-branches))
4764 (if (bobp) (throw 'exit nil))))))
4767 (defun org-optimize-window-after-visibility-change (state)
4768 "Adjust the window after a change in outline visibility.
4769 This function is the default value of the hook `org-cycle-hook'."
4770 (when (get-buffer-window (current-buffer))
4771 (cond
4772 ((eq state 'content) nil)
4773 ((eq state 'all) nil)
4774 ((eq state 'folded) nil)
4775 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4776 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4778 (defun org-compact-display-after-subtree-move ()
4779 "Show a compacter version of the tree of the entry's parent."
4780 (save-excursion
4781 (if (org-up-heading-safe)
4782 (progn
4783 (hide-subtree)
4784 (show-entry)
4785 (show-children)
4786 (org-cycle-show-empty-lines 'children)
4787 (org-cycle-hide-drawers 'children))
4788 (org-overview))))
4790 (defun org-cycle-show-empty-lines (state)
4791 "Show empty lines above all visible headlines.
4792 The region to be covered depends on STATE when called through
4793 `org-cycle-hook'. Lisp program can use t for STATE to get the
4794 entire buffer covered. Note that an empty line is only shown if there
4795 are at least `org-cycle-separator-lines' empty lines before the headline."
4796 (when (> org-cycle-separator-lines 0)
4797 (save-excursion
4798 (let* ((n org-cycle-separator-lines)
4799 (re (cond
4800 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4801 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4802 (t (let ((ns (number-to-string (- n 2))))
4803 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4804 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4805 beg end)
4806 (cond
4807 ((memq state '(overview contents t))
4808 (setq beg (point-min) end (point-max)))
4809 ((memq state '(children folded))
4810 (setq beg (point) end (progn (org-end-of-subtree t t)
4811 (beginning-of-line 2)
4812 (point)))))
4813 (when beg
4814 (goto-char beg)
4815 (while (re-search-forward re end t)
4816 (if (not (get-char-property (match-end 1) 'invisible))
4817 (outline-flag-region
4818 (match-beginning 1) (match-end 1) nil)))))))
4819 ;; Never hide empty lines at the end of the file.
4820 (save-excursion
4821 (goto-char (point-max))
4822 (outline-previous-heading)
4823 (outline-end-of-heading)
4824 (if (and (looking-at "[ \t\n]+")
4825 (= (match-end 0) (point-max)))
4826 (outline-flag-region (point) (match-end 0) nil))))
4828 (defun org-show-empty-lines-in-parent ()
4829 "Move to the parent and re-show empty lines before visible headlines."
4830 (save-excursion
4831 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4832 (org-cycle-show-empty-lines context))))
4834 (defun org-cycle-hide-drawers (state)
4835 "Re-hide all drawers after a visibility state change."
4836 (when (and (org-mode-p)
4837 (not (memq state '(overview folded))))
4838 (save-excursion
4839 (let* ((globalp (memq state '(contents all)))
4840 (beg (if globalp (point-min) (point)))
4841 (end (if globalp (point-max) (org-end-of-subtree t))))
4842 (goto-char beg)
4843 (while (re-search-forward org-drawer-regexp end t)
4844 (org-flag-drawer t))))))
4846 (defun org-flag-drawer (flag)
4847 (save-excursion
4848 (beginning-of-line 1)
4849 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4850 (let ((b (match-end 0))
4851 (outline-regexp org-outline-regexp))
4852 (if (re-search-forward
4853 "^[ \t]*:END:"
4854 (save-excursion (outline-next-heading) (point)) t)
4855 (outline-flag-region b (point-at-eol) flag)
4856 (error ":END: line missing"))))))
4858 (defun org-subtree-end-visible-p ()
4859 "Is the end of the current subtree visible?"
4860 (pos-visible-in-window-p
4861 (save-excursion (org-end-of-subtree t) (point))))
4863 (defun org-first-headline-recenter (&optional N)
4864 "Move cursor to the first headline and recenter the headline.
4865 Optional argument N means, put the headline into the Nth line of the window."
4866 (goto-char (point-min))
4867 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4868 (beginning-of-line)
4869 (recenter (prefix-numeric-value N))))
4871 ;;; Org-goto
4873 (defvar org-goto-window-configuration nil)
4874 (defvar org-goto-marker nil)
4875 (defvar org-goto-map
4876 (let ((map (make-sparse-keymap)))
4877 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4878 (while (setq cmd (pop cmds))
4879 (substitute-key-definition cmd cmd map global-map)))
4880 (suppress-keymap map)
4881 (org-defkey map "\C-m" 'org-goto-ret)
4882 (org-defkey map [(return)] 'org-goto-ret)
4883 (org-defkey map [(left)] 'org-goto-left)
4884 (org-defkey map [(right)] 'org-goto-right)
4885 (org-defkey map [(control ?g)] 'org-goto-quit)
4886 (org-defkey map "\C-i" 'org-cycle)
4887 (org-defkey map [(tab)] 'org-cycle)
4888 (org-defkey map [(down)] 'outline-next-visible-heading)
4889 (org-defkey map [(up)] 'outline-previous-visible-heading)
4890 (if org-goto-auto-isearch
4891 (if (fboundp 'define-key-after)
4892 (define-key-after map [t] 'org-goto-local-auto-isearch)
4893 nil)
4894 (org-defkey map "q" 'org-goto-quit)
4895 (org-defkey map "n" 'outline-next-visible-heading)
4896 (org-defkey map "p" 'outline-previous-visible-heading)
4897 (org-defkey map "f" 'outline-forward-same-level)
4898 (org-defkey map "b" 'outline-backward-same-level)
4899 (org-defkey map "u" 'outline-up-heading))
4900 (org-defkey map "/" 'org-occur)
4901 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4902 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4903 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4904 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4905 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4906 map))
4908 (defconst org-goto-help
4909 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4910 RET=jump to location [Q]uit and return to previous location
4911 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4913 (defvar org-goto-start-pos) ; dynamically scoped parameter
4915 ;; FIXME: Docstring doe not mention both interfaces
4916 (defun org-goto (&optional alternative-interface)
4917 "Look up a different location in the current file, keeping current visibility.
4919 When you want look-up or go to a different location in a document, the
4920 fastest way is often to fold the entire buffer and then dive into the tree.
4921 This method has the disadvantage, that the previous location will be folded,
4922 which may not be what you want.
4924 This command works around this by showing a copy of the current buffer
4925 in an indirect buffer, in overview mode. You can dive into the tree in
4926 that copy, use org-occur and incremental search to find a location.
4927 When pressing RET or `Q', the command returns to the original buffer in
4928 which the visibility is still unchanged. After RET is will also jump to
4929 the location selected in the indirect buffer and expose the
4930 the headline hierarchy above."
4931 (interactive "P")
4932 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4933 (org-refile-use-outline-path t)
4934 (interface
4935 (if (not alternative-interface)
4936 org-goto-interface
4937 (if (eq org-goto-interface 'outline)
4938 'outline-path-completion
4939 'outline)))
4940 (org-goto-start-pos (point))
4941 (selected-point
4942 (if (eq interface 'outline)
4943 (car (org-get-location (current-buffer) org-goto-help))
4944 (nth 3 (org-refile-get-location "Goto: ")))))
4945 (if selected-point
4946 (progn
4947 (org-mark-ring-push org-goto-start-pos)
4948 (goto-char selected-point)
4949 (if (or (org-invisible-p) (org-invisible-p2))
4950 (org-show-context 'org-goto)))
4951 (message "Quit"))))
4953 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4954 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4955 (defvar org-goto-local-auto-isearch-map) ; defined below
4957 (defun org-get-location (buf help)
4958 "Let the user select a location in the Org-mode buffer BUF.
4959 This function uses a recursive edit. It returns the selected position
4960 or nil."
4961 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4962 (isearch-hide-immediately nil)
4963 (isearch-search-fun-function
4964 (lambda () 'org-goto-local-search-headings))
4965 (org-goto-selected-point org-goto-exit-command))
4966 (save-excursion
4967 (save-window-excursion
4968 (delete-other-windows)
4969 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4970 (switch-to-buffer
4971 (condition-case nil
4972 (make-indirect-buffer (current-buffer) "*org-goto*")
4973 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4974 (with-output-to-temp-buffer "*Help*"
4975 (princ help))
4976 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4977 (setq buffer-read-only nil)
4978 (let ((org-startup-truncated t)
4979 (org-startup-folded nil)
4980 (org-startup-align-all-tables nil))
4981 (org-mode)
4982 (org-overview))
4983 (setq buffer-read-only t)
4984 (if (and (boundp 'org-goto-start-pos)
4985 (integer-or-marker-p org-goto-start-pos))
4986 (let ((org-show-hierarchy-above t)
4987 (org-show-siblings t)
4988 (org-show-following-heading t))
4989 (goto-char org-goto-start-pos)
4990 (and (org-invisible-p) (org-show-context)))
4991 (goto-char (point-min)))
4992 (let (org-special-ctrl-a/e) (org-beginning-of-line))
4993 (message "Select location and press RET")
4994 (use-local-map org-goto-map)
4995 (recursive-edit)
4997 (kill-buffer "*org-goto*")
4998 (cons org-goto-selected-point org-goto-exit-command)))
5000 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5001 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5002 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5003 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5005 (defun org-goto-local-search-headings (string bound noerror)
5006 "Search and make sure that any matches are in headlines."
5007 (catch 'return
5008 (while (if isearch-forward
5009 (search-forward string bound noerror)
5010 (search-backward string bound noerror))
5011 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5012 (and (member :headline context)
5013 (not (member :tags context))))
5014 (throw 'return (point))))))
5016 (defun org-goto-local-auto-isearch ()
5017 "Start isearch."
5018 (interactive)
5019 (goto-char (point-min))
5020 (let ((keys (this-command-keys)))
5021 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5022 (isearch-mode t)
5023 (isearch-process-search-char (string-to-char keys)))))
5025 (defun org-goto-ret (&optional arg)
5026 "Finish `org-goto' by going to the new location."
5027 (interactive "P")
5028 (setq org-goto-selected-point (point)
5029 org-goto-exit-command 'return)
5030 (throw 'exit nil))
5032 (defun org-goto-left ()
5033 "Finish `org-goto' by going to the new location."
5034 (interactive)
5035 (if (org-on-heading-p)
5036 (progn
5037 (beginning-of-line 1)
5038 (setq org-goto-selected-point (point)
5039 org-goto-exit-command 'left)
5040 (throw 'exit nil))
5041 (error "Not on a heading")))
5043 (defun org-goto-right ()
5044 "Finish `org-goto' by going to the new location."
5045 (interactive)
5046 (if (org-on-heading-p)
5047 (progn
5048 (setq org-goto-selected-point (point)
5049 org-goto-exit-command 'right)
5050 (throw 'exit nil))
5051 (error "Not on a heading")))
5053 (defun org-goto-quit ()
5054 "Finish `org-goto' without cursor motion."
5055 (interactive)
5056 (setq org-goto-selected-point nil)
5057 (setq org-goto-exit-command 'quit)
5058 (throw 'exit nil))
5060 ;;; Indirect buffer display of subtrees
5062 (defvar org-indirect-dedicated-frame nil
5063 "This is the frame being used for indirect tree display.")
5064 (defvar org-last-indirect-buffer nil)
5066 (defun org-tree-to-indirect-buffer (&optional arg)
5067 "Create indirect buffer and narrow it to current subtree.
5068 With numerical prefix ARG, go up to this level and then take that tree.
5069 If ARG is negative, go up that many levels.
5070 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5071 indirect buffer previously made with this command, to avoid proliferation of
5072 indirect buffers. However, when you call the command with a `C-u' prefix, or
5073 when `org-indirect-buffer-display' is `new-frame', the last buffer
5074 is kept so that you can work with several indirect buffers at the same time.
5075 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5076 requests that a new frame be made for the new buffer, so that the dedicated
5077 frame is not changed."
5078 (interactive "P")
5079 (let ((cbuf (current-buffer))
5080 (cwin (selected-window))
5081 (pos (point))
5082 beg end level heading ibuf)
5083 (save-excursion
5084 (org-back-to-heading t)
5085 (when (numberp arg)
5086 (setq level (org-outline-level))
5087 (if (< arg 0) (setq arg (+ level arg)))
5088 (while (> (setq level (org-outline-level)) arg)
5089 (outline-up-heading 1 t)))
5090 (setq beg (point)
5091 heading (org-get-heading))
5092 (org-end-of-subtree t) (setq end (point)))
5093 (if (and (buffer-live-p org-last-indirect-buffer)
5094 (not (eq org-indirect-buffer-display 'new-frame))
5095 (not arg))
5096 (kill-buffer org-last-indirect-buffer))
5097 (setq ibuf (org-get-indirect-buffer cbuf)
5098 org-last-indirect-buffer ibuf)
5099 (cond
5100 ((or (eq org-indirect-buffer-display 'new-frame)
5101 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5102 (select-frame (make-frame))
5103 (delete-other-windows)
5104 (switch-to-buffer ibuf)
5105 (org-set-frame-title heading))
5106 ((eq org-indirect-buffer-display 'dedicated-frame)
5107 (raise-frame
5108 (select-frame (or (and org-indirect-dedicated-frame
5109 (frame-live-p org-indirect-dedicated-frame)
5110 org-indirect-dedicated-frame)
5111 (setq org-indirect-dedicated-frame (make-frame)))))
5112 (delete-other-windows)
5113 (switch-to-buffer ibuf)
5114 (org-set-frame-title (concat "Indirect: " heading)))
5115 ((eq org-indirect-buffer-display 'current-window)
5116 (switch-to-buffer ibuf))
5117 ((eq org-indirect-buffer-display 'other-window)
5118 (pop-to-buffer ibuf))
5119 (t (error "Invalid value.")))
5120 (if (featurep 'xemacs)
5121 (save-excursion (org-mode) (turn-on-font-lock)))
5122 (narrow-to-region beg end)
5123 (show-all)
5124 (goto-char pos)
5125 (and (window-live-p cwin) (select-window cwin))))
5127 (defun org-get-indirect-buffer (&optional buffer)
5128 (setq buffer (or buffer (current-buffer)))
5129 (let ((n 1) (base (buffer-name buffer)) bname)
5130 (while (buffer-live-p
5131 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5132 (setq n (1+ n)))
5133 (condition-case nil
5134 (make-indirect-buffer buffer bname 'clone)
5135 (error (make-indirect-buffer buffer bname)))))
5137 (defun org-set-frame-title (title)
5138 "Set the title of the current frame to the string TITLE."
5139 ;; FIXME: how to name a single frame in XEmacs???
5140 (unless (featurep 'xemacs)
5141 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5143 ;;;; Structure editing
5145 ;;; Inserting headlines
5147 (defun org-previous-line-empty-p ()
5148 (save-excursion
5149 (and (not (bobp))
5150 (or (beginning-of-line 0) t)
5151 (save-match-data
5152 (looking-at "[ \t]*$")))))
5154 (defun org-insert-heading (&optional force-heading)
5155 "Insert a new heading or item with same depth at point.
5156 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5157 If point is at the beginning of a headline, insert a sibling before the
5158 current headline. If point is not at the beginning, do not split the line,
5159 but create the new headline after the current line."
5160 (interactive "P")
5161 (if (= (buffer-size) 0)
5162 (insert "\n* ")
5163 (when (or force-heading (not (org-insert-item)))
5164 (let* ((empty-line-p nil)
5165 (head (save-excursion
5166 (condition-case nil
5167 (progn
5168 (org-back-to-heading)
5169 (setq empty-line-p (org-previous-line-empty-p))
5170 (match-string 0))
5171 (error "*"))))
5172 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5173 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5174 pos hide-previous previous-pos)
5175 (cond
5176 ((and (org-on-heading-p) (bolp)
5177 (or (bobp)
5178 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5179 ;; insert before the current line
5180 (open-line (if blank 2 1)))
5181 ((and (bolp)
5182 (or (bobp)
5183 (save-excursion
5184 (backward-char 1) (not (org-invisible-p)))))
5185 ;; insert right here
5186 nil)
5188 ;; somewhere in the line
5189 (save-excursion
5190 (setq previous-pos (point-at-bol))
5191 (end-of-line)
5192 (setq hide-previous (org-invisible-p)))
5193 (and org-insert-heading-respect-content (org-show-subtree))
5194 (let ((split
5195 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5196 (save-excursion
5197 (let ((p (point)))
5198 (goto-char (point-at-bol))
5199 (and (looking-at org-complex-heading-regexp)
5200 (> p (match-beginning 4)))))))
5201 tags pos)
5202 (cond
5203 (org-insert-heading-respect-content
5204 (org-end-of-subtree nil t)
5205 (or (bolp) (newline))
5206 (or (org-previous-line-empty-p)
5207 (and blank (newline)))
5208 (open-line 1))
5209 ((org-on-heading-p)
5210 (when hide-previous
5211 (show-children)
5212 (org-show-entry))
5213 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5214 (setq tags (and (match-end 2) (match-string 2)))
5215 (and (match-end 1)
5216 (delete-region (match-beginning 1) (match-end 1)))
5217 (setq pos (point-at-bol))
5218 (or split (end-of-line 1))
5219 (delete-horizontal-space)
5220 (newline (if blank 2 1))
5221 (when tags
5222 (save-excursion
5223 (goto-char pos)
5224 (end-of-line 1)
5225 (insert " " tags)
5226 (org-set-tags nil 'align))))
5228 (or split (end-of-line 1))
5229 (newline (if blank 2 1)))))))
5230 (insert head) (just-one-space)
5231 (setq pos (point))
5232 (end-of-line 1)
5233 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5234 (when (and org-insert-heading-respect-content hide-previous)
5235 (save-excursion
5236 (goto-char previous-pos)
5237 (hide-subtree)))
5238 (run-hooks 'org-insert-heading-hook)))))
5240 (defun org-get-heading (&optional no-tags)
5241 "Return the heading of the current entry, without the stars."
5242 (save-excursion
5243 (org-back-to-heading t)
5244 (if (looking-at
5245 (if no-tags
5246 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5247 "\\*+[ \t]+\\([^\r\n]*\\)"))
5248 (match-string 1) "")))
5250 (defun org-heading-components ()
5251 "Return the components of the current heading.
5252 This is a list with the following elements:
5253 - the level as an integer
5254 - the reduced level, different if `org-odd-levels-only' is set.
5255 - the TODO keyword, or nil
5256 - the priority character, like ?A, or nil if no priority is given
5257 - the headline text itself, or the tags string if no headline text
5258 - the tags string, or nil."
5259 (save-excursion
5260 (org-back-to-heading t)
5261 (if (looking-at org-complex-heading-regexp)
5262 (list (length (match-string 1))
5263 (org-reduced-level (length (match-string 1)))
5264 (org-match-string-no-properties 2)
5265 (and (match-end 3) (aref (match-string 3) 2))
5266 (org-match-string-no-properties 4)
5267 (org-match-string-no-properties 5)))))
5269 (defun org-insert-heading-after-current ()
5270 "Insert a new heading with same level as current, after current subtree."
5271 (interactive)
5272 (org-back-to-heading)
5273 (org-insert-heading)
5274 (org-move-subtree-down)
5275 (end-of-line 1))
5277 (defun org-insert-heading-respect-content ()
5278 (interactive)
5279 (let ((org-insert-heading-respect-content t))
5280 (org-insert-heading t)))
5282 (defun org-insert-todo-heading-respect-content (&optional force-state)
5283 (interactive "P")
5284 (let ((org-insert-heading-respect-content t))
5285 (org-insert-todo-heading force-state t)))
5287 (defun org-insert-todo-heading (arg &optional force-heading)
5288 "Insert a new heading with the same level and TODO state as current heading.
5289 If the heading has no TODO state, or if the state is DONE, use the first
5290 state (TODO by default). Also with prefix arg, force first state."
5291 (interactive "P")
5292 (when (or force-heading (not (org-insert-item 'checkbox)))
5293 (org-insert-heading force-heading)
5294 (save-excursion
5295 (org-back-to-heading)
5296 (outline-previous-heading)
5297 (looking-at org-todo-line-regexp))
5298 (let*
5299 ((new-mark-x
5300 (if (or arg
5301 (not (match-beginning 2))
5302 (member (match-string 2) org-done-keywords))
5303 (car org-todo-keywords-1)
5304 (match-string 2)))
5305 (new-mark
5307 (run-hook-with-args-until-success
5308 'org-todo-get-default-hook new-mark-x nil)
5309 new-mark-x)))
5310 (beginning-of-line 1)
5311 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5312 (insert new-mark " ")))
5313 (when org-provide-todo-statistics
5314 (org-update-parent-todo-statistics))))
5316 (defun org-insert-subheading (arg)
5317 "Insert a new subheading and demote it.
5318 Works for outline headings and for plain lists alike."
5319 (interactive "P")
5320 (org-insert-heading arg)
5321 (cond
5322 ((org-on-heading-p) (org-do-demote))
5323 ((org-at-item-p) (org-indent-item 1))))
5325 (defun org-insert-todo-subheading (arg)
5326 "Insert a new subheading with TODO keyword or checkbox and demote it.
5327 Works for outline headings and for plain lists alike."
5328 (interactive "P")
5329 (org-insert-todo-heading arg)
5330 (cond
5331 ((org-on-heading-p) (org-do-demote))
5332 ((org-at-item-p) (org-indent-item 1))))
5334 ;;; Promotion and Demotion
5336 (defun org-promote-subtree ()
5337 "Promote the entire subtree.
5338 See also `org-promote'."
5339 (interactive)
5340 (save-excursion
5341 (org-map-tree 'org-promote))
5342 (org-fix-position-after-promote))
5344 (defun org-demote-subtree ()
5345 "Demote the entire subtree. See `org-demote'.
5346 See also `org-promote'."
5347 (interactive)
5348 (save-excursion
5349 (org-map-tree 'org-demote))
5350 (org-fix-position-after-promote))
5353 (defun org-do-promote ()
5354 "Promote the current heading higher up the tree.
5355 If the region is active in `transient-mark-mode', promote all headings
5356 in the region."
5357 (interactive)
5358 (save-excursion
5359 (if (org-region-active-p)
5360 (org-map-region 'org-promote (region-beginning) (region-end))
5361 (org-promote)))
5362 (org-fix-position-after-promote))
5364 (defun org-do-demote ()
5365 "Demote the current heading lower down the tree.
5366 If the region is active in `transient-mark-mode', demote all headings
5367 in the region."
5368 (interactive)
5369 (save-excursion
5370 (if (org-region-active-p)
5371 (org-map-region 'org-demote (region-beginning) (region-end))
5372 (org-demote)))
5373 (org-fix-position-after-promote))
5375 (defun org-fix-position-after-promote ()
5376 "Make sure that after pro/demotion cursor position is right."
5377 (let ((pos (point)))
5378 (when (save-excursion
5379 (beginning-of-line 1)
5380 (looking-at org-todo-line-regexp)
5381 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5382 (cond ((eobp) (insert " "))
5383 ((eolp) (insert " "))
5384 ((equal (char-after) ?\ ) (forward-char 1))))))
5386 (defun org-reduced-level (l)
5387 "Compute the effective level of a heading.
5388 This takes into account the setting of `org-odd-levels-only'."
5389 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5391 (defun org-get-valid-level (level &optional change)
5392 "Rectify a level change under the influence of `org-odd-levels-only'
5393 LEVEL is a current level, CHANGE is by how much the level should be
5394 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5395 even level numbers will become the next higher odd number."
5396 (if org-odd-levels-only
5397 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5398 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5399 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5400 (max 1 (+ level (or change 0)))))
5402 (if (boundp 'define-obsolete-function-alias)
5403 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5404 (define-obsolete-function-alias 'org-get-legal-level
5405 'org-get-valid-level)
5406 (define-obsolete-function-alias 'org-get-legal-level
5407 'org-get-valid-level "23.1")))
5409 (defun org-promote ()
5410 "Promote the current heading higher up the tree.
5411 If the region is active in `transient-mark-mode', promote all headings
5412 in the region."
5413 (org-back-to-heading t)
5414 (let* ((level (save-match-data (funcall outline-level)))
5415 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5416 (diff (abs (- level (length up-head) -1))))
5417 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5418 (replace-match up-head nil t)
5419 ;; Fixup tag positioning
5420 (and org-auto-align-tags (org-set-tags nil t))
5421 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5423 (defun org-demote ()
5424 "Demote the current heading lower down the tree.
5425 If the region is active in `transient-mark-mode', demote all headings
5426 in the region."
5427 (org-back-to-heading t)
5428 (let* ((level (save-match-data (funcall outline-level)))
5429 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5430 (diff (abs (- level (length down-head) -1))))
5431 (replace-match down-head nil t)
5432 ;; Fixup tag positioning
5433 (and org-auto-align-tags (org-set-tags nil t))
5434 (if org-adapt-indentation (org-fixup-indentation diff))))
5436 (defun org-map-tree (fun)
5437 "Call FUN for every heading underneath the current one."
5438 (org-back-to-heading)
5439 (let ((level (funcall outline-level)))
5440 (save-excursion
5441 (funcall fun)
5442 (while (and (progn
5443 (outline-next-heading)
5444 (> (funcall outline-level) level))
5445 (not (eobp)))
5446 (funcall fun)))))
5448 (defun org-map-region (fun beg end)
5449 "Call FUN for every heading between BEG and END."
5450 (let ((org-ignore-region t))
5451 (save-excursion
5452 (setq end (copy-marker end))
5453 (goto-char beg)
5454 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5455 (< (point) end))
5456 (funcall fun))
5457 (while (and (progn
5458 (outline-next-heading)
5459 (< (point) end))
5460 (not (eobp)))
5461 (funcall fun)))))
5463 (defun org-fixup-indentation (diff)
5464 "Change the indentation in the current entry by DIFF
5465 However, if any line in the current entry has no indentation, or if it
5466 would end up with no indentation after the change, nothing at all is done."
5467 (save-excursion
5468 (let ((end (save-excursion (outline-next-heading)
5469 (point-marker)))
5470 (prohibit (if (> diff 0)
5471 "^\\S-"
5472 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5473 col)
5474 (unless (save-excursion (end-of-line 1)
5475 (re-search-forward prohibit end t))
5476 (while (and (< (point) end)
5477 (re-search-forward "^[ \t]+" end t))
5478 (goto-char (match-end 0))
5479 (setq col (current-column))
5480 (if (< diff 0) (replace-match ""))
5481 (org-indent-to-column (+ diff col))))
5482 (move-marker end nil))))
5484 (defun org-convert-to-odd-levels ()
5485 "Convert an org-mode file with all levels allowed to one with odd levels.
5486 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5487 level 5 etc."
5488 (interactive)
5489 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5490 (let ((org-odd-levels-only nil) n)
5491 (save-excursion
5492 (goto-char (point-min))
5493 (while (re-search-forward "^\\*\\*+ " nil t)
5494 (setq n (- (length (match-string 0)) 2))
5495 (while (>= (setq n (1- n)) 0)
5496 (org-demote))
5497 (end-of-line 1))))))
5500 (defun org-convert-to-oddeven-levels ()
5501 "Convert an org-mode file with only odd levels to one with odd and even levels.
5502 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5503 section with an even level, conversion would destroy the structure of the file. An error
5504 is signaled in this case."
5505 (interactive)
5506 (goto-char (point-min))
5507 ;; First check if there are no even levels
5508 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5509 (org-show-context t)
5510 (error "Not all levels are odd in this file. Conversion not possible."))
5511 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5512 (let ((org-odd-levels-only nil) n)
5513 (save-excursion
5514 (goto-char (point-min))
5515 (while (re-search-forward "^\\*\\*+ " nil t)
5516 (setq n (/ (1- (length (match-string 0))) 2))
5517 (while (>= (setq n (1- n)) 0)
5518 (org-promote))
5519 (end-of-line 1))))))
5521 (defun org-tr-level (n)
5522 "Make N odd if required."
5523 (if org-odd-levels-only (1+ (/ n 2)) n))
5525 ;;; Vertical tree motion, cutting and pasting of subtrees
5527 (defun org-move-subtree-up (&optional arg)
5528 "Move the current subtree up past ARG headlines of the same level."
5529 (interactive "p")
5530 (org-move-subtree-down (- (prefix-numeric-value arg))))
5532 (defun org-move-subtree-down (&optional arg)
5533 "Move the current subtree down past ARG headlines of the same level."
5534 (interactive "p")
5535 (setq arg (prefix-numeric-value arg))
5536 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5537 'outline-get-last-sibling))
5538 (ins-point (make-marker))
5539 (cnt (abs arg))
5540 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5541 ;; Select the tree
5542 (org-back-to-heading)
5543 (setq beg0 (point))
5544 (save-excursion
5545 (setq ne-beg (org-back-over-empty-lines))
5546 (setq beg (point)))
5547 (save-match-data
5548 (save-excursion (outline-end-of-heading)
5549 (setq folded (org-invisible-p)))
5550 (outline-end-of-subtree))
5551 (outline-next-heading)
5552 (setq ne-end (org-back-over-empty-lines))
5553 (setq end (point))
5554 (goto-char beg0)
5555 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5556 ;; include less whitespace
5557 (save-excursion
5558 (goto-char beg)
5559 (forward-line (- ne-beg ne-end))
5560 (setq beg (point))))
5561 ;; Find insertion point, with error handling
5562 (while (> cnt 0)
5563 (or (and (funcall movfunc) (looking-at outline-regexp))
5564 (progn (goto-char beg0)
5565 (error "Cannot move past superior level or buffer limit")))
5566 (setq cnt (1- cnt)))
5567 (if (> arg 0)
5568 ;; Moving forward - still need to move over subtree
5569 (progn (org-end-of-subtree t t)
5570 (save-excursion
5571 (org-back-over-empty-lines)
5572 (or (bolp) (newline)))))
5573 (setq ne-ins (org-back-over-empty-lines))
5574 (move-marker ins-point (point))
5575 (setq txt (buffer-substring beg end))
5576 (org-save-markers-in-region beg end)
5577 (delete-region beg end)
5578 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5579 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5580 (let ((bbb (point)))
5581 (insert-before-markers txt)
5582 (org-reinstall-markers-in-region bbb)
5583 (move-marker ins-point bbb))
5584 (or (bolp) (insert "\n"))
5585 (setq ins-end (point))
5586 (goto-char ins-point)
5587 (org-skip-whitespace)
5588 (when (and (< arg 0)
5589 (org-first-sibling-p)
5590 (> ne-ins ne-beg))
5591 ;; Move whitespace back to beginning
5592 (save-excursion
5593 (goto-char ins-end)
5594 (let ((kill-whole-line t))
5595 (kill-line (- ne-ins ne-beg)) (point)))
5596 (insert (make-string (- ne-ins ne-beg) ?\n)))
5597 (move-marker ins-point nil)
5598 (org-compact-display-after-subtree-move)
5599 (org-show-empty-lines-in-parent)
5600 (unless folded
5601 (org-show-entry)
5602 (show-children)
5603 (org-cycle-hide-drawers 'children))))
5605 (defvar org-subtree-clip ""
5606 "Clipboard for cut and paste of subtrees.
5607 This is actually only a copy of the kill, because we use the normal kill
5608 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5610 (defvar org-subtree-clip-folded nil
5611 "Was the last copied subtree folded?
5612 This is used to fold the tree back after pasting.")
5614 (defun org-cut-subtree (&optional n)
5615 "Cut the current subtree into the clipboard.
5616 With prefix arg N, cut this many sequential subtrees.
5617 This is a short-hand for marking the subtree and then cutting it."
5618 (interactive "p")
5619 (org-copy-subtree n 'cut))
5621 (defun org-copy-subtree (&optional n cut force-store-markers)
5622 "Cut the current subtree into the clipboard.
5623 With prefix arg N, cut this many sequential subtrees.
5624 This is a short-hand for marking the subtree and then copying it.
5625 If CUT is non-nil, actually cut the subtree.
5626 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5627 of some markers in the region, even if CUT is non-nil. This is
5628 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5629 (interactive "p")
5630 (let (beg end folded (beg0 (point)))
5631 (if (interactive-p)
5632 (org-back-to-heading nil) ; take what looks like a subtree
5633 (org-back-to-heading t)) ; take what is really there
5634 (org-back-over-empty-lines)
5635 (setq beg (point))
5636 (skip-chars-forward " \t\r\n")
5637 (save-match-data
5638 (save-excursion (outline-end-of-heading)
5639 (setq folded (org-invisible-p)))
5640 (condition-case nil
5641 (outline-forward-same-level (1- n))
5642 (error nil))
5643 (org-end-of-subtree t t))
5644 (org-back-over-empty-lines)
5645 (setq end (point))
5646 (goto-char beg0)
5647 (when (> end beg)
5648 (setq org-subtree-clip-folded folded)
5649 (when (or cut force-store-markers)
5650 (org-save-markers-in-region beg end))
5651 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5652 (setq org-subtree-clip (current-kill 0))
5653 (message "%s: Subtree(s) with %d characters"
5654 (if cut "Cut" "Copied")
5655 (length org-subtree-clip)))))
5657 (defun org-paste-subtree (&optional level tree for-yank)
5658 "Paste the clipboard as a subtree, with modification of headline level.
5659 The entire subtree is promoted or demoted in order to match a new headline
5660 level.
5662 If the cursor is at the beginning of a headline, the same level as
5663 that headline is used to paste the tree
5665 If not, the new level is derived from the *visible* headings
5666 before and after the insertion point, and taken to be the inferior headline
5667 level of the two. So if the previous visible heading is level 3 and the
5668 next is level 4 (or vice versa), level 4 will be used for insertion.
5669 This makes sure that the subtree remains an independent subtree and does
5670 not swallow low level entries.
5672 You can also force a different level, either by using a numeric prefix
5673 argument, or by inserting the heading marker by hand. For example, if the
5674 cursor is after \"*****\", then the tree will be shifted to level 5.
5676 If optional TREE is given, use this text instead of the kill ring.
5678 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5679 move back over whitespace before inserting, and move point to the end of
5680 the inserted text when done."
5681 (interactive "P")
5682 (unless (org-kill-is-subtree-p tree)
5683 (error "%s"
5684 (substitute-command-keys
5685 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5686 (let* ((visp (not (org-invisible-p)))
5687 (txt (or tree (and kill-ring (current-kill 0))))
5688 (^re (concat "^\\(" outline-regexp "\\)"))
5689 (re (concat "\\(" outline-regexp "\\)"))
5690 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5692 (old-level (if (string-match ^re txt)
5693 (- (match-end 0) (match-beginning 0) 1)
5694 -1))
5695 (force-level (cond (level (prefix-numeric-value level))
5696 ((and (looking-at "[ \t]*$")
5697 (string-match
5698 ^re_ (buffer-substring
5699 (point-at-bol) (point))))
5700 (- (match-end 1) (match-beginning 1)))
5701 ((and (bolp)
5702 (looking-at org-outline-regexp))
5703 (- (match-end 0) (point) 1))
5704 (t nil)))
5705 (previous-level (save-excursion
5706 (condition-case nil
5707 (progn
5708 (outline-previous-visible-heading 1)
5709 (if (looking-at re)
5710 (- (match-end 0) (match-beginning 0) 1)
5712 (error 1))))
5713 (next-level (save-excursion
5714 (condition-case nil
5715 (progn
5716 (or (looking-at outline-regexp)
5717 (outline-next-visible-heading 1))
5718 (if (looking-at re)
5719 (- (match-end 0) (match-beginning 0) 1)
5721 (error 1))))
5722 (new-level (or force-level (max previous-level next-level)))
5723 (shift (if (or (= old-level -1)
5724 (= new-level -1)
5725 (= old-level new-level))
5727 (- new-level old-level)))
5728 (delta (if (> shift 0) -1 1))
5729 (func (if (> shift 0) 'org-demote 'org-promote))
5730 (org-odd-levels-only nil)
5731 beg end newend)
5732 ;; Remove the forced level indicator
5733 (if force-level
5734 (delete-region (point-at-bol) (point)))
5735 ;; Paste
5736 (beginning-of-line 1)
5737 (unless for-yank (org-back-over-empty-lines))
5738 (setq beg (point))
5739 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5740 (insert-before-markers txt)
5741 (unless (string-match "\n\\'" txt) (insert "\n"))
5742 (setq newend (point))
5743 (org-reinstall-markers-in-region beg)
5744 (setq end (point))
5745 (goto-char beg)
5746 (skip-chars-forward " \t\n\r")
5747 (setq beg (point))
5748 (if (and (org-invisible-p) visp)
5749 (save-excursion (outline-show-heading)))
5750 ;; Shift if necessary
5751 (unless (= shift 0)
5752 (save-restriction
5753 (narrow-to-region beg end)
5754 (while (not (= shift 0))
5755 (org-map-region func (point-min) (point-max))
5756 (setq shift (+ delta shift)))
5757 (goto-char (point-min))
5758 (setq newend (point-max))))
5759 (when (or (interactive-p) for-yank)
5760 (message "Clipboard pasted as level %d subtree" new-level))
5761 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5762 kill-ring
5763 (eq org-subtree-clip (current-kill 0))
5764 org-subtree-clip-folded)
5765 ;; The tree was folded before it was killed/copied
5766 (hide-subtree))
5767 (and for-yank (goto-char newend))))
5769 (defun org-kill-is-subtree-p (&optional txt)
5770 "Check if the current kill is an outline subtree, or a set of trees.
5771 Returns nil if kill does not start with a headline, or if the first
5772 headline level is not the largest headline level in the tree.
5773 So this will actually accept several entries of equal levels as well,
5774 which is OK for `org-paste-subtree'.
5775 If optional TXT is given, check this string instead of the current kill."
5776 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5777 (start-level (and kill
5778 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5779 org-outline-regexp "\\)")
5780 kill)
5781 (- (match-end 2) (match-beginning 2) 1)))
5782 (re (concat "^" org-outline-regexp))
5783 (start (1+ (or (match-beginning 2) -1))))
5784 (if (not start-level)
5785 (progn
5786 nil) ;; does not even start with a heading
5787 (catch 'exit
5788 (while (setq start (string-match re kill (1+ start)))
5789 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5790 (throw 'exit nil)))
5791 t))))
5793 (defvar org-markers-to-move nil
5794 "Markers that should be moved with a cut-and-paste operation.
5795 Those markers are stored together with their positions relative to
5796 the start of the region.")
5798 (defun org-save-markers-in-region (beg end)
5799 "Check markers in region.
5800 If these markers are between BEG and END, record their position relative
5801 to BEG, so that after moving the block of text, we can put the markers back
5802 into place.
5803 This function gets called just before an entry or tree gets cut from the
5804 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5805 called immediately, to move the markers with the entries."
5806 (setq org-markers-to-move nil)
5807 (when (featurep 'org-clock)
5808 (org-clock-save-markers-for-cut-and-paste beg end))
5809 (when (featurep 'org-agenda)
5810 (org-agenda-save-markers-for-cut-and-paste beg end)))
5812 (defun org-check-and-save-marker (marker beg end)
5813 "Check if MARKER is between BEG and END.
5814 If yes, remember the marker and the distance to BEG."
5815 (when (and (marker-buffer marker)
5816 (equal (marker-buffer marker) (current-buffer)))
5817 (if (and (>= marker beg) (< marker end))
5818 (push (cons marker (- marker beg)) org-markers-to-move))))
5820 (defun org-reinstall-markers-in-region (beg)
5821 "Move all remembered markers to their position relative to BEG."
5822 (mapc (lambda (x)
5823 (move-marker (car x) (+ beg (cdr x))))
5824 org-markers-to-move)
5825 (setq org-markers-to-move nil))
5827 (defun org-narrow-to-subtree ()
5828 "Narrow buffer to the current subtree."
5829 (interactive)
5830 (save-excursion
5831 (save-match-data
5832 (narrow-to-region
5833 (progn (org-back-to-heading) (point))
5834 (progn (org-end-of-subtree t) (point))))))
5836 (defun org-clone-subtree-with-time-shift (n &optional shift)
5837 "Clone the task (subtree) at point N times.
5838 The clones will be inserted as siblings.
5840 In interactive use, the user will be prompted for the number of clones
5841 to be produced, and for a time SHIFT, which may be a repeater as used
5842 in time stamps, for example `+3d'.
5844 When a valid repeater is given and the entry contains any time stamps,
5845 the clones will become a sequence in time, with time stamps in the
5846 subtree shifted for each clone produced. If SHIFT is nil or the
5847 empty string, time stamps will be left alone.
5849 If the original subtree did contain time stamps with a repeater,
5850 the following will happen:
5851 - the repeater will be removed in each clone
5852 - an additional clone will be produced, with the current, unshifted
5853 date(s) in the entry.
5854 - the original entry will be placed *after* all the clones, with
5855 repeater intact.
5856 - the start days in the repeater in the original entry will be shifted
5857 to past the last clone.
5858 I this way you can spell out a number of instances of a repeating task,
5859 and still retain the repeater to cover future instances of the task."
5860 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
5861 (let (beg end template task
5862 shift-n shift-what doshift nmin nmax (n-no-remove -1))
5863 (if (not (and (integerp n) (> n 0)))
5864 (error "Invalid number of replications %s" n))
5865 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
5866 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
5867 shift)))
5868 (error "Invalid shift specification %s" shift))
5869 (when doshift
5870 (setq shift-n (string-to-number (match-string 1 shift))
5871 shift-what (cdr (assoc (match-string 2 shift)
5872 '(("d" . day) ("w" . week)
5873 ("m" . month) ("y" . year))))))
5874 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
5875 (setq nmin 1 nmax n)
5876 (org-back-to-heading t)
5877 (setq beg (point))
5878 (org-end-of-subtree t t)
5879 (setq end (point))
5880 (setq template (buffer-substring beg end))
5881 (when (and doshift
5882 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
5883 (delete-region beg end)
5884 (setq end beg)
5885 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
5886 (goto-char end)
5887 (loop for n from nmin to nmax do
5888 (if (not doshift)
5889 (setq task template)
5890 (with-temp-buffer
5891 (insert template)
5892 (org-mode)
5893 (goto-char (point-min))
5894 (while (re-search-forward org-ts-regexp nil t)
5895 (org-timestamp-change (* n shift-n) shift-what))
5896 (unless (= n n-no-remove)
5897 (goto-char (point-min))
5898 (while (re-search-forward org-ts-regexp nil t)
5899 (save-excursion
5900 (goto-char (match-beginning 0))
5901 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
5902 (delete-region (match-beginning 1) (match-end 1))))))
5903 (setq task (buffer-string))))
5904 (insert task))
5905 (goto-char beg)))
5907 ;;; Outline Sorting
5909 (defun org-sort (with-case)
5910 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5911 Optional argument WITH-CASE means sort case-sensitively.
5912 With a double prefix argument, also remove duplicate entries."
5913 (interactive "P")
5914 (if (org-at-table-p)
5915 (org-call-with-arg 'org-table-sort-lines with-case)
5916 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5918 (defun org-sort-remove-invisible (s)
5919 (remove-text-properties 0 (length s) org-rm-props s)
5920 (while (string-match org-bracket-link-regexp s)
5921 (setq s (replace-match (if (match-end 2)
5922 (match-string 3 s)
5923 (match-string 1 s)) t t s)))
5926 (defvar org-priority-regexp) ; defined later in the file
5928 (defun org-sort-entries-or-items
5929 (&optional with-case sorting-type getkey-func compare-func property)
5930 "Sort entries on a certain level of an outline tree.
5931 If there is an active region, the entries in the region are sorted.
5932 Else, if the cursor is before the first entry, sort the top-level items.
5933 Else, the children of the entry at point are sorted.
5935 Sorting can be alphabetically, numerically, and by date/time as given by
5936 the first time stamp in the entry. The command prompts for the sorting
5937 type unless it has been given to the function through the SORTING-TYPE
5938 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5939 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5940 called with point at the beginning of the record. It must return either
5941 a string or a number that should serve as the sorting key for that record.
5943 Comparing entries ignores case by default. However, with an optional argument
5944 WITH-CASE, the sorting considers case as well."
5945 (interactive "P")
5946 (let ((case-func (if with-case 'identity 'downcase))
5947 start beg end stars re re2
5948 txt what tmp plain-list-p)
5949 ;; Find beginning and end of region to sort
5950 (cond
5951 ((org-region-active-p)
5952 ;; we will sort the region
5953 (setq end (region-end)
5954 what "region")
5955 (goto-char (region-beginning))
5956 (if (not (org-on-heading-p)) (outline-next-heading))
5957 (setq start (point)))
5958 ((org-at-item-p)
5959 ;; we will sort this plain list
5960 (org-beginning-of-item-list) (setq start (point))
5961 (org-end-of-item-list) (setq end (point))
5962 (goto-char start)
5963 (setq plain-list-p t
5964 what "plain list"))
5965 ((or (org-on-heading-p)
5966 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5967 ;; we will sort the children of the current headline
5968 (org-back-to-heading)
5969 (setq start (point)
5970 end (progn (org-end-of-subtree t t)
5971 (org-back-over-empty-lines)
5972 (point))
5973 what "children")
5974 (goto-char start)
5975 (show-subtree)
5976 (outline-next-heading))
5978 ;; we will sort the top-level entries in this file
5979 (goto-char (point-min))
5980 (or (org-on-heading-p) (outline-next-heading))
5981 (setq start (point) end (point-max) what "top-level")
5982 (goto-char start)
5983 (show-all)))
5985 (setq beg (point))
5986 (if (>= beg end) (error "Nothing to sort"))
5988 (unless plain-list-p
5989 (looking-at "\\(\\*+\\)")
5990 (setq stars (match-string 1)
5991 re (concat "^" (regexp-quote stars) " +")
5992 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5993 txt (buffer-substring beg end))
5994 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5995 (if (and (not (equal stars "*")) (string-match re2 txt))
5996 (error "Region to sort contains a level above the first entry")))
5998 (unless sorting-type
5999 (message
6000 (if plain-list-p
6001 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6002 "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:")
6003 what)
6004 (setq sorting-type (read-char-exclusive))
6006 (and (= (downcase sorting-type) ?f)
6007 (setq getkey-func
6008 (org-ido-completing-read "Sort using function: "
6009 obarray 'fboundp t nil nil))
6010 (setq getkey-func (intern getkey-func)))
6012 (and (= (downcase sorting-type) ?r)
6013 (setq property
6014 (org-ido-completing-read "Property: "
6015 (mapcar 'list (org-buffer-property-keys t))
6016 nil t))))
6018 (message "Sorting entries...")
6020 (save-restriction
6021 (narrow-to-region start end)
6023 (let ((dcst (downcase sorting-type))
6024 (now (current-time)))
6025 (sort-subr
6026 (/= dcst sorting-type)
6027 ;; This function moves to the beginning character of the "record" to
6028 ;; be sorted.
6029 (if plain-list-p
6030 (lambda nil
6031 (if (org-at-item-p) t (goto-char (point-max))))
6032 (lambda nil
6033 (if (re-search-forward re nil t)
6034 (goto-char (match-beginning 0))
6035 (goto-char (point-max)))))
6036 ;; This function moves to the last character of the "record" being
6037 ;; sorted.
6038 (if plain-list-p
6039 'org-end-of-item
6040 (lambda nil
6041 (save-match-data
6042 (condition-case nil
6043 (outline-forward-same-level 1)
6044 (error
6045 (goto-char (point-max)))))))
6047 ;; This function returns the value that gets sorted against.
6048 (if plain-list-p
6049 (lambda nil
6050 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6051 (cond
6052 ((= dcst ?n)
6053 (string-to-number (buffer-substring (match-end 0)
6054 (point-at-eol))))
6055 ((= dcst ?a)
6056 (buffer-substring (match-end 0) (point-at-eol)))
6057 ((= dcst ?t)
6058 (if (re-search-forward org-ts-regexp
6059 (point-at-eol) t)
6060 (org-time-string-to-time (match-string 0))
6061 now))
6062 ((= dcst ?f)
6063 (if getkey-func
6064 (progn
6065 (setq tmp (funcall getkey-func))
6066 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6067 tmp)
6068 (error "Invalid key function `%s'" getkey-func)))
6069 (t (error "Invalid sorting type `%c'" sorting-type)))))
6070 (lambda nil
6071 (cond
6072 ((= dcst ?n)
6073 (if (looking-at org-complex-heading-regexp)
6074 (string-to-number (match-string 4))
6075 nil))
6076 ((= dcst ?a)
6077 (if (looking-at org-complex-heading-regexp)
6078 (funcall case-func (match-string 4))
6079 nil))
6080 ((= dcst ?t)
6081 (if (re-search-forward org-ts-regexp
6082 (save-excursion
6083 (forward-line 2)
6084 (point)) t)
6085 (org-time-string-to-time (match-string 0))
6086 now))
6087 ((= dcst ?p)
6088 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6089 (string-to-char (match-string 2))
6090 org-default-priority))
6091 ((= dcst ?r)
6092 (or (org-entry-get nil property) ""))
6093 ((= dcst ?o)
6094 (if (looking-at org-complex-heading-regexp)
6095 (- 9999 (length (member (match-string 2)
6096 org-todo-keywords-1)))))
6097 ((= dcst ?f)
6098 (if getkey-func
6099 (progn
6100 (setq tmp (funcall getkey-func))
6101 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6102 tmp)
6103 (error "Invalid key function `%s'" getkey-func)))
6104 (t (error "Invalid sorting type `%c'" sorting-type)))))
6106 (cond
6107 ((= dcst ?a) 'string<)
6108 ((= dcst ?t) 'time-less-p)
6109 ((= dcst ?f) compare-func)
6110 (t nil)))))
6111 (message "Sorting entries...done")))
6113 (defun org-do-sort (table what &optional with-case sorting-type)
6114 "Sort TABLE of WHAT according to SORTING-TYPE.
6115 The user will be prompted for the SORTING-TYPE if the call to this
6116 function does not specify it. WHAT is only for the prompt, to indicate
6117 what is being sorted. The sorting key will be extracted from
6118 the car of the elements of the table.
6119 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6120 (unless sorting-type
6121 (message
6122 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6123 what)
6124 (setq sorting-type (read-char-exclusive)))
6125 (let ((dcst (downcase sorting-type))
6126 extractfun comparefun)
6127 ;; Define the appropriate functions
6128 (cond
6129 ((= dcst ?n)
6130 (setq extractfun 'string-to-number
6131 comparefun (if (= dcst sorting-type) '< '>)))
6132 ((= dcst ?a)
6133 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6134 (lambda(x) (downcase (org-sort-remove-invisible x))))
6135 comparefun (if (= dcst sorting-type)
6136 'string<
6137 (lambda (a b) (and (not (string< a b))
6138 (not (string= a b)))))))
6139 ((= dcst ?t)
6140 (setq extractfun
6141 (lambda (x)
6142 (if (or (string-match org-ts-regexp x)
6143 (string-match org-ts-regexp-both x))
6144 (time-to-seconds
6145 (org-time-string-to-time (match-string 0 x)))
6147 comparefun (if (= dcst sorting-type) '< '>)))
6148 (t (error "Invalid sorting type `%c'" sorting-type)))
6150 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6151 table)
6152 (lambda (a b) (funcall comparefun (car a) (car b))))))
6154 ;;; Editing source examples
6156 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6157 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6158 (defvar org-edit-src-force-single-line nil)
6159 (defvar org-edit-src-from-org-mode nil)
6160 (defvar org-edit-src-picture nil)
6162 (define-minor-mode org-exit-edit-mode
6163 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6165 (defun org-edit-src-code ()
6166 "Edit the source code example at point.
6167 An indirect buffer is created, and that buffer is then narrowed to the
6168 example at point and switched to the correct language mode. When done,
6169 exit by killing the buffer with \\[org-edit-src-exit]."
6170 (interactive)
6171 (let ((line (org-current-line))
6172 (case-fold-search t)
6173 (msg (substitute-command-keys
6174 "Edit, then exit with C-c ' (C-c and single quote)"))
6175 (info (org-edit-src-find-region-and-lang))
6176 (org-mode-p (eq major-mode 'org-mode))
6177 beg end lang lang-f single lfmt)
6178 (if (not info)
6180 (setq beg (nth 0 info)
6181 end (nth 1 info)
6182 lang (nth 2 info)
6183 single (nth 3 info)
6184 lfmt (nth 4 info)
6185 lang-f (intern (concat lang "-mode")))
6186 (unless (functionp lang-f)
6187 (error "No such language mode: %s" lang-f))
6188 (goto-line line)
6189 (if (get-buffer "*Org Edit Src Example*")
6190 (kill-buffer "*Org Edit Src Example*"))
6191 (switch-to-buffer (make-indirect-buffer (current-buffer)
6192 "*Org Edit Src Example*"))
6193 (narrow-to-region beg end)
6194 (remove-text-properties beg end '(display nil invisible nil
6195 intangible nil))
6196 (let ((org-inhibit-startup t))
6197 (funcall lang-f))
6198 (set (make-local-variable 'org-edit-src-force-single-line) single)
6199 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6200 (when lfmt
6201 (set (make-local-variable 'org-coderef-label-format) lfmt))
6202 (when org-mode-p
6203 (goto-char (point-min))
6204 (while (re-search-forward "^," nil t)
6205 (replace-match "")))
6206 (goto-line line)
6207 (org-exit-edit-mode)
6208 (org-set-local 'header-line-format msg)
6209 (message "%s" msg)
6210 t)))
6212 (defun org-edit-fixed-width-region ()
6213 "Edit the fixed-width ascii drawing at point.
6214 This must be a region where each line starts with a colon followed by
6215 a space character.
6216 An indirect buffer is created, and that buffer is then narrowed to the
6217 example at point and switched to artist-mode. When done,
6218 exit by killing the buffer with \\[org-edit-src-exit]."
6219 (interactive)
6220 (let ((line (org-current-line))
6221 (case-fold-search t)
6222 (msg (substitute-command-keys
6223 "Edit, then exit with C-c ' (C-c and single quote)"))
6224 (org-mode-p (eq major-mode 'org-mode))
6225 beg end)
6226 (beginning-of-line 1)
6227 (if (looking-at "[ \t]*[^:\n \t]")
6229 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6230 (setq beg (point) end beg)
6231 (save-excursion
6232 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6233 (setq beg (point-at-bol 2))
6234 (setq beg (point))))
6235 (save-excursion
6236 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6237 (setq end (1- (match-beginning 0)))
6238 (setq end (point))))
6239 (goto-line line))
6240 (if (get-buffer "*Org Edit Picture*")
6241 (kill-buffer "*Org Edit Picture*"))
6242 (switch-to-buffer (make-indirect-buffer (current-buffer)
6243 "*Org Edit Picture*"))
6244 (narrow-to-region beg end)
6245 (remove-text-properties beg end '(display nil invisible nil
6246 intangible nil))
6247 (when (fboundp 'font-lock-unfontify-region)
6248 (font-lock-unfontify-region (point-min) (point-max)))
6249 (cond
6250 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6251 (fundamental-mode)
6252 (artist-mode 1))
6253 (t (funcall org-edit-fixed-width-region-mode)))
6254 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6255 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6256 (set (make-local-variable 'org-edit-src-picture) t)
6257 (goto-char (point-min))
6258 (while (re-search-forward "^[ \t]*: ?" nil t)
6259 (replace-match ""))
6260 (goto-line line)
6261 (org-exit-edit-mode)
6262 (org-set-local 'header-line-format msg)
6263 (message "%s" msg)
6264 t)))
6267 (defun org-edit-src-find-region-and-lang ()
6268 "Find the region and language for a local edit.
6269 Return a list with beginning and end of the region, a string representing
6270 the language, a switch telling of the content should be in a single line."
6271 (let ((re-list
6272 (append
6273 org-edit-src-region-extra
6275 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6276 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6277 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6278 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6279 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6280 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6281 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6282 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6283 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6284 ("^#\\+html:" "\n" "html" single-line)
6285 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6286 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6287 ("^#\\+latex:" "\n" "latex" single-line)
6288 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6289 ("^#\\+ascii:" "\n" "ascii" single-line)
6291 (pos (point))
6292 re1 re2 single beg end lang lfmt match-re1)
6293 (catch 'exit
6294 (while (setq entry (pop re-list))
6295 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6296 single (nth 3 entry))
6297 (save-excursion
6298 (if (or (looking-at re1)
6299 (re-search-backward re1 nil t))
6300 (progn
6301 (setq match-re1 (match-string 0))
6302 (setq beg (match-end 0)
6303 lang (org-edit-src-get-lang lang)
6304 lfmt (org-edit-src-get-label-format match-re1))
6305 (if (and (re-search-forward re2 nil t)
6306 (>= (match-end 0) pos))
6307 (throw 'exit (list beg (match-beginning 0)
6308 lang single lfmt))))
6309 (if (or (looking-at re2)
6310 (re-search-forward re2 nil t))
6311 (progn
6312 (setq end (match-beginning 0))
6313 (if (and (re-search-backward re1 nil t)
6314 (<= (match-beginning 0) pos))
6315 (progn
6316 (setq lfmt (org-edit-src-get-label-format
6317 (match-string 0)))
6318 (throw 'exit
6319 (list (match-end 0) end
6320 (org-edit-src-get-lang lang)
6321 single lfmt))))))))))))
6323 (defun org-edit-src-get-lang (lang)
6324 "Extract the src language."
6325 (let ((m (match-string 0)))
6326 (cond
6327 ((stringp lang) lang)
6328 ((integerp lang) (match-string lang))
6329 ((and (eq lang 'lang)
6330 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6331 (match-string 1 m))
6332 ((and (eq lang 'style)
6333 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6334 (match-string 1 m))
6335 (t "fundamental"))))
6337 (defun org-edit-src-get-label-format (s)
6338 "Extract the label format."
6339 (save-match-data
6340 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6341 (match-string 1 s))))
6343 (defun org-edit-src-exit ()
6344 "Exit special edit and protect problematic lines."
6345 (interactive)
6346 (unless (buffer-base-buffer (current-buffer))
6347 (error "This is not an indirect buffer, something is wrong..."))
6348 (unless (> (point-min) 1)
6349 (error "This buffer is not narrowed, something is wrong..."))
6350 (goto-char (point-min))
6351 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6352 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6353 (when (org-bound-and-true-p org-edit-src-force-single-line)
6354 (goto-char (point-min))
6355 (while (re-search-forward "\n" nil t)
6356 (replace-match " "))
6357 (goto-char (point-min))
6358 (if (looking-at "\\s-*") (replace-match " "))
6359 (if (re-search-forward "\\s-+\\'" nil t)
6360 (replace-match "")))
6361 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6362 (goto-char (point-min))
6363 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6364 (replace-match ",\\1"))
6365 (when font-lock-mode
6366 (font-lock-unfontify-region (point-min) (point-max)))
6367 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6368 (when (org-bound-and-true-p org-edit-src-picture)
6369 (untabify (point-min) (point-max))
6370 (goto-char (point-min))
6371 (while (re-search-forward "^" nil t)
6372 (replace-match ": "))
6373 (when font-lock-mode
6374 (font-lock-unfontify-region (point-min) (point-max)))
6375 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6376 (kill-buffer (current-buffer))
6377 (and (org-mode-p) (org-restart-font-lock)))
6380 ;;; The orgstruct minor mode
6382 ;; Define a minor mode which can be used in other modes in order to
6383 ;; integrate the org-mode structure editing commands.
6385 ;; This is really a hack, because the org-mode structure commands use
6386 ;; keys which normally belong to the major mode. Here is how it
6387 ;; works: The minor mode defines all the keys necessary to operate the
6388 ;; structure commands, but wraps the commands into a function which
6389 ;; tests if the cursor is currently at a headline or a plain list
6390 ;; item. If that is the case, the structure command is used,
6391 ;; temporarily setting many Org-mode variables like regular
6392 ;; expressions for filling etc. However, when any of those keys is
6393 ;; used at a different location, function uses `key-binding' to look
6394 ;; up if the key has an associated command in another currently active
6395 ;; keymap (minor modes, major mode, global), and executes that
6396 ;; command. There might be problems if any of the keys is otherwise
6397 ;; used as a prefix key.
6399 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6400 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6401 ;; addresses this by checking explicitly for both bindings.
6403 (defvar orgstruct-mode-map (make-sparse-keymap)
6404 "Keymap for the minor `orgstruct-mode'.")
6406 (defvar org-local-vars nil
6407 "List of local variables, for use by `orgstruct-mode'")
6409 ;;;###autoload
6410 (define-minor-mode orgstruct-mode
6411 "Toggle the minor more `orgstruct-mode'.
6412 This mode is for using Org-mode structure commands in other modes.
6413 The following key behave as if Org-mode was active, if the cursor
6414 is on a headline, or on a plain list item (both in the definition
6415 of Org-mode).
6417 M-up Move entry/item up
6418 M-down Move entry/item down
6419 M-left Promote
6420 M-right Demote
6421 M-S-up Move entry/item up
6422 M-S-down Move entry/item down
6423 M-S-left Promote subtree
6424 M-S-right Demote subtree
6425 M-q Fill paragraph and items like in Org-mode
6426 C-c ^ Sort entries
6427 C-c - Cycle list bullet
6428 TAB Cycle item visibility
6429 M-RET Insert new heading/item
6430 S-M-RET Insert new TODO heading / Checkbox item
6431 C-c C-c Set tags / toggle checkbox"
6432 nil " OrgStruct" nil
6433 (org-load-modules-maybe)
6434 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6436 ;;;###autoload
6437 (defun turn-on-orgstruct ()
6438 "Unconditionally turn on `orgstruct-mode'."
6439 (orgstruct-mode 1))
6441 (defun orgstruct++-mode (&optional arg)
6442 "Toggle `orgstruct-mode', the enhanced version of it.
6443 In addition to setting orgstruct-mode, this also exports all indentation and
6444 autofilling variables from org-mode into the buffer. It will also
6445 recognize item context in multiline items.
6446 Note that turning off orgstruct-mode will *not* remove the
6447 indentation/paragraph settings. This can only be done by refreshing the
6448 major mode, for example with \[normal-mode]."
6449 (interactive "P")
6450 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6451 (if (< arg 1)
6452 (orgstruct-mode -1)
6453 (orgstruct-mode 1)
6454 (let (var val)
6455 (mapc
6456 (lambda (x)
6457 (when (string-match
6458 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6459 (symbol-name (car x)))
6460 (setq var (car x) val (nth 1 x))
6461 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6462 org-local-vars)
6463 (org-set-local 'orgstruct-is-++ t))))
6465 (defvar orgstruct-is-++ nil
6466 "Is orgstruct-mode in ++ version in the current-buffer?")
6467 (make-variable-buffer-local 'orgstruct-is-++)
6469 ;;;###autoload
6470 (defun turn-on-orgstruct++ ()
6471 "Unconditionally turn on `orgstruct++-mode'."
6472 (orgstruct++-mode 1))
6474 (defun orgstruct-error ()
6475 "Error when there is no default binding for a structure key."
6476 (interactive)
6477 (error "This key has no function outside structure elements"))
6479 (defun orgstruct-setup ()
6480 "Setup orgstruct keymaps."
6481 (let ((nfunc 0)
6482 (bindings
6483 (list
6484 '([(meta up)] org-metaup)
6485 '([(meta down)] org-metadown)
6486 '([(meta left)] org-metaleft)
6487 '([(meta right)] org-metaright)
6488 '([(meta shift up)] org-shiftmetaup)
6489 '([(meta shift down)] org-shiftmetadown)
6490 '([(meta shift left)] org-shiftmetaleft)
6491 '([(meta shift right)] org-shiftmetaright)
6492 '([(shift up)] org-shiftup)
6493 '([(shift down)] org-shiftdown)
6494 '([(shift left)] org-shiftleft)
6495 '([(shift right)] org-shiftright)
6496 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6497 '("\M-q" fill-paragraph)
6498 '("\C-c^" org-sort)
6499 '("\C-c-" org-cycle-list-bullet)))
6500 elt key fun cmd)
6501 (while (setq elt (pop bindings))
6502 (setq nfunc (1+ nfunc))
6503 (setq key (org-key (car elt))
6504 fun (nth 1 elt)
6505 cmd (orgstruct-make-binding fun nfunc key))
6506 (org-defkey orgstruct-mode-map key cmd))
6508 ;; Special treatment needed for TAB and RET
6509 (org-defkey orgstruct-mode-map [(tab)]
6510 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6511 (org-defkey orgstruct-mode-map "\C-i"
6512 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6514 (org-defkey orgstruct-mode-map "\M-\C-m"
6515 (orgstruct-make-binding 'org-insert-heading 105
6516 "\M-\C-m" [(meta return)]))
6517 (org-defkey orgstruct-mode-map [(meta return)]
6518 (orgstruct-make-binding 'org-insert-heading 106
6519 [(meta return)] "\M-\C-m"))
6521 (org-defkey orgstruct-mode-map [(shift meta return)]
6522 (orgstruct-make-binding 'org-insert-todo-heading 107
6523 [(meta return)] "\M-\C-m"))
6525 (unless org-local-vars
6526 (setq org-local-vars (org-get-local-variables)))
6530 (defun orgstruct-make-binding (fun n &rest keys)
6531 "Create a function for binding in the structure minor mode.
6532 FUN is the command to call inside a table. N is used to create a unique
6533 command name. KEYS are keys that should be checked in for a command
6534 to execute outside of tables."
6535 (eval
6536 (list 'defun
6537 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6538 '(arg)
6539 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6540 "Outside of structure, run the binding of `"
6541 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6542 "'.")
6543 '(interactive "p")
6544 (list 'if
6545 `(org-context-p 'headline 'item
6546 (and orgstruct-is-++
6547 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6548 'item-body))
6549 (list 'org-run-like-in-org-mode (list 'quote fun))
6550 (list 'let '(orgstruct-mode)
6551 (list 'call-interactively
6552 (append '(or)
6553 (mapcar (lambda (k)
6554 (list 'key-binding k))
6555 keys)
6556 '('orgstruct-error))))))))
6558 (defun org-context-p (&rest contexts)
6559 "Check if local context is any of CONTEXTS.
6560 Possible values in the list of contexts are `table', `headline', and `item'."
6561 (let ((pos (point)))
6562 (goto-char (point-at-bol))
6563 (prog1 (or (and (memq 'table contexts)
6564 (looking-at "[ \t]*|"))
6565 (and (memq 'headline contexts)
6566 ;;????????? (looking-at "\\*+"))
6567 (looking-at outline-regexp))
6568 (and (memq 'item contexts)
6569 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6570 (and (memq 'item-body contexts)
6571 (org-in-item-p)))
6572 (goto-char pos))))
6574 (defun org-get-local-variables ()
6575 "Return a list of all local variables in an org-mode buffer."
6576 (let (varlist)
6577 (with-current-buffer (get-buffer-create "*Org tmp*")
6578 (erase-buffer)
6579 (org-mode)
6580 (setq varlist (buffer-local-variables)))
6581 (kill-buffer "*Org tmp*")
6582 (delq nil
6583 (mapcar
6584 (lambda (x)
6585 (setq x
6586 (if (symbolp x)
6587 (list x)
6588 (list (car x) (list 'quote (cdr x)))))
6589 (if (string-match
6590 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6591 (symbol-name (car x)))
6592 x nil))
6593 varlist))))
6595 ;;;###autoload
6596 (defun org-run-like-in-org-mode (cmd)
6597 "Run a command, pretending that the current buffer is in Org-mode.
6598 This will temporarily bind local variables that are typically bound in
6599 Org-mode to the values they have in Org-mode, and then interactively
6600 call CMD."
6601 (org-load-modules-maybe)
6602 (unless org-local-vars
6603 (setq org-local-vars (org-get-local-variables)))
6604 (eval (list 'let org-local-vars
6605 (list 'call-interactively (list 'quote cmd)))))
6607 ;;;; Archiving
6609 (defun org-get-category (&optional pos)
6610 "Get the category applying to position POS."
6611 (get-text-property (or pos (point)) 'org-category))
6613 (defun org-refresh-category-properties ()
6614 "Refresh category text properties in the buffer."
6615 (let ((def-cat (cond
6616 ((null org-category)
6617 (if buffer-file-name
6618 (file-name-sans-extension
6619 (file-name-nondirectory buffer-file-name))
6620 "???"))
6621 ((symbolp org-category) (symbol-name org-category))
6622 (t org-category)))
6623 beg end cat pos optionp)
6624 (org-unmodified
6625 (save-excursion
6626 (save-restriction
6627 (widen)
6628 (goto-char (point-min))
6629 (put-text-property (point) (point-max) 'org-category def-cat)
6630 (while (re-search-forward
6631 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6632 (setq pos (match-end 0)
6633 optionp (equal (char-after (match-beginning 0)) ?#)
6634 cat (org-trim (match-string 2)))
6635 (if optionp
6636 (setq beg (point-at-bol) end (point-max))
6637 (org-back-to-heading t)
6638 (setq beg (point) end (org-end-of-subtree t t)))
6639 (put-text-property beg end 'org-category cat)
6640 (goto-char pos)))))))
6643 ;;;; Link Stuff
6645 ;;; Link abbreviations
6647 (defun org-link-expand-abbrev (link)
6648 "Apply replacements as defined in `org-link-abbrev-alist."
6649 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6650 (let* ((key (match-string 1 link))
6651 (as (or (assoc key org-link-abbrev-alist-local)
6652 (assoc key org-link-abbrev-alist)))
6653 (tag (and (match-end 2) (match-string 3 link)))
6654 rpl)
6655 (if (not as)
6656 link
6657 (setq rpl (cdr as))
6658 (cond
6659 ((symbolp rpl) (funcall rpl tag))
6660 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6661 ((string-match "%h" rpl)
6662 (replace-match (url-hexify-string (or tag "")) t t rpl))
6663 (t (concat rpl tag)))))
6664 link))
6666 ;;; Storing and inserting links
6668 (defvar org-insert-link-history nil
6669 "Minibuffer history for links inserted with `org-insert-link'.")
6671 (defvar org-stored-links nil
6672 "Contains the links stored with `org-store-link'.")
6674 (defvar org-store-link-plist nil
6675 "Plist with info about the most recently link created with `org-store-link'.")
6677 (defvar org-link-protocols nil
6678 "Link protocols added to Org-mode using `org-add-link-type'.")
6680 (defvar org-store-link-functions nil
6681 "List of functions that are called to create and store a link.
6682 Each function will be called in turn until one returns a non-nil
6683 value. Each function should check if it is responsible for creating
6684 this link (for example by looking at the major mode).
6685 If not, it must exit and return nil.
6686 If yes, it should return a non-nil value after a calling
6687 `org-store-link-props' with a list of properties and values.
6688 Special properties are:
6690 :type The link prefix. like \"http\". This must be given.
6691 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6692 This is obligatory as well.
6693 :description Optional default description for the second pair
6694 of brackets in an Org-mode link. The user can still change
6695 this when inserting this link into an Org-mode buffer.
6697 In addition to these, any additional properties can be specified
6698 and then used in remember templates.")
6700 (defun org-add-link-type (type &optional follow export)
6701 "Add TYPE to the list of `org-link-types'.
6702 Re-compute all regular expressions depending on `org-link-types'
6704 FOLLOW and EXPORT are two functions.
6706 FOLLOW should take the link path as the single argument and do whatever
6707 is necessary to follow the link, for example find a file or display
6708 a mail message.
6710 EXPORT should format the link path for export to one of the export formats.
6711 It should be a function accepting three arguments:
6713 path the path of the link, the text after the prefix (like \"http:\")
6714 desc the description of the link, if any, nil if there was no description
6715 format the export format, a symbol like `html' or `latex'.
6717 The function may use the FORMAT information to return different values
6718 depending on the format. The return value will be put literally into
6719 the exported file.
6720 Org-mode has a built-in default for exporting links. If you are happy with
6721 this default, there is no need to define an export function for the link
6722 type. For a simple example of an export function, see `org-bbdb.el'."
6723 (add-to-list 'org-link-types type t)
6724 (org-make-link-regexps)
6725 (if (assoc type org-link-protocols)
6726 (setcdr (assoc type org-link-protocols) (list follow export))
6727 (push (list type follow export) org-link-protocols)))
6729 ;;;###autoload
6730 (defun org-store-link (arg)
6731 "\\<org-mode-map>Store an org-link to the current location.
6732 This link is added to `org-stored-links' and can later be inserted
6733 into an org-buffer with \\[org-insert-link].
6735 For some link types, a prefix arg is interpreted:
6736 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6737 For file links, arg negates `org-context-in-file-links'."
6738 (interactive "P")
6739 (org-load-modules-maybe)
6740 (setq org-store-link-plist nil) ; reset
6741 (let (link cpltxt desc description search txt)
6742 (cond
6744 ((run-hook-with-args-until-success 'org-store-link-functions)
6745 (setq link (plist-get org-store-link-plist :link)
6746 desc (or (plist-get org-store-link-plist :description) link)))
6748 ((equal (buffer-name) "*Org Edit Src Example*")
6749 (let (label gc)
6750 (while (or (not label)
6751 (save-excursion
6752 (save-restriction
6753 (widen)
6754 (goto-char (point-min))
6755 (re-search-forward
6756 (regexp-quote (format org-coderef-label-format label))
6757 nil t))))
6758 (when label (message "Label exists already") (sit-for 2))
6759 (setq label (read-string "Code line label: " label)))
6760 (end-of-line 1)
6761 (setq link (format org-coderef-label-format label))
6762 (setq gc (- 79 (length link)))
6763 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6764 (insert link)
6765 (setq link (concat "(" label ")") desc nil)))
6767 ((eq major-mode 'calendar-mode)
6768 (let ((cd (calendar-cursor-to-date)))
6769 (setq link
6770 (format-time-string
6771 (car org-time-stamp-formats)
6772 (apply 'encode-time
6773 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6774 nil nil nil))))
6775 (org-store-link-props :type "calendar" :date cd)))
6777 ((eq major-mode 'w3-mode)
6778 (setq cpltxt (if (and (buffer-name)
6779 (not (string-match "Untitled" (buffer-name))))
6780 (buffer-name)
6781 (url-view-url t))
6782 link (org-make-link (url-view-url t)))
6783 (org-store-link-props :type "w3" :url (url-view-url t)))
6785 ((eq major-mode 'w3m-mode)
6786 (setq cpltxt (or w3m-current-title w3m-current-url)
6787 link (org-make-link w3m-current-url))
6788 (org-store-link-props :type "w3m" :url (url-view-url t)))
6790 ((setq search (run-hook-with-args-until-success
6791 'org-create-file-search-functions))
6792 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6793 "::" search))
6794 (setq cpltxt (or description link)))
6796 ((eq major-mode 'image-mode)
6797 (setq cpltxt (concat "file:"
6798 (abbreviate-file-name buffer-file-name))
6799 link (org-make-link cpltxt))
6800 (org-store-link-props :type "image" :file buffer-file-name))
6802 ((eq major-mode 'dired-mode)
6803 ;; link to the file in the current line
6804 (setq cpltxt (concat "file:"
6805 (abbreviate-file-name
6806 (expand-file-name
6807 (dired-get-filename nil t))))
6808 link (org-make-link cpltxt)))
6810 ((and buffer-file-name (org-mode-p))
6811 (cond
6812 ((org-in-regexp "<<\\(.*?\\)>>")
6813 (setq cpltxt
6814 (concat "file:"
6815 (abbreviate-file-name buffer-file-name)
6816 "::" (match-string 1))
6817 link (org-make-link cpltxt)))
6818 ((and (featurep 'org-id)
6819 (or (eq org-link-to-org-use-id t)
6820 (and (eq org-link-to-org-use-id 'create-if-interactive)
6821 (interactive-p))
6822 (and org-link-to-org-use-id
6823 (condition-case nil
6824 (org-entry-get nil "ID")
6825 (error nil)))))
6826 ;; We can make a link using the ID.
6827 (setq link (condition-case nil
6828 (prog1 (org-id-store-link)
6829 (setq desc (plist-get org-store-link-plist
6830 :description)))
6831 (error
6832 ;; probably before first headline, link to file only
6833 (concat "file:"
6834 (abbreviate-file-name buffer-file-name))))))
6836 ;; Just link to current headline
6837 (setq cpltxt (concat "file:"
6838 (abbreviate-file-name buffer-file-name)))
6839 ;; Add a context search string
6840 (when (org-xor org-context-in-file-links arg)
6841 (setq txt (cond
6842 ((org-on-heading-p) nil)
6843 ((org-region-active-p)
6844 (buffer-substring (region-beginning) (region-end)))
6845 (t nil)))
6846 (when (or (null txt) (string-match "\\S-" txt))
6847 (setq cpltxt
6848 (concat cpltxt "::"
6849 (condition-case nil
6850 (org-make-org-heading-search-string txt)
6851 (error "")))
6852 desc "NONE")))
6853 (if (string-match "::\\'" cpltxt)
6854 (setq cpltxt (substring cpltxt 0 -2)))
6855 (setq link (org-make-link cpltxt)))))
6857 ((buffer-file-name (buffer-base-buffer))
6858 ;; Just link to this file here.
6859 (setq cpltxt (concat "file:"
6860 (abbreviate-file-name
6861 (buffer-file-name (buffer-base-buffer)))))
6862 ;; Add a context string
6863 (when (org-xor org-context-in-file-links arg)
6864 (setq txt (if (org-region-active-p)
6865 (buffer-substring (region-beginning) (region-end))
6866 (buffer-substring (point-at-bol) (point-at-eol))))
6867 ;; Only use search option if there is some text.
6868 (when (string-match "\\S-" txt)
6869 (setq cpltxt
6870 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6871 desc "NONE")))
6872 (setq link (org-make-link cpltxt)))
6874 ((interactive-p)
6875 (error "Cannot link to a buffer which is not visiting a file"))
6877 (t (setq link nil)))
6879 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6880 (setq link (or link cpltxt)
6881 desc (or desc cpltxt))
6882 (if (equal desc "NONE") (setq desc nil))
6884 (if (and (interactive-p) link)
6885 (progn
6886 (setq org-stored-links
6887 (cons (list link desc) org-stored-links))
6888 (message "Stored: %s" (or desc link)))
6889 (and link (org-make-link-string link desc)))))
6891 (defun org-store-link-props (&rest plist)
6892 "Store link properties, extract names and addresses."
6893 (let (x adr)
6894 (when (setq x (plist-get plist :from))
6895 (setq adr (mail-extract-address-components x))
6896 (setq plist (plist-put plist :fromname (car adr)))
6897 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6898 (when (setq x (plist-get plist :to))
6899 (setq adr (mail-extract-address-components x))
6900 (setq plist (plist-put plist :toname (car adr)))
6901 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6902 (let ((from (plist-get plist :from))
6903 (to (plist-get plist :to)))
6904 (when (and from to org-from-is-user-regexp)
6905 (setq plist
6906 (plist-put plist :fromto
6907 (if (string-match org-from-is-user-regexp from)
6908 (concat "to %t")
6909 (concat "from %f"))))))
6910 (setq org-store-link-plist plist))
6912 (defun org-add-link-props (&rest plist)
6913 "Add these properties to the link property list."
6914 (let (key value)
6915 (while plist
6916 (setq key (pop plist) value (pop plist))
6917 (setq org-store-link-plist
6918 (plist-put org-store-link-plist key value)))))
6920 (defun org-email-link-description (&optional fmt)
6921 "Return the description part of an email link.
6922 This takes information from `org-store-link-plist' and formats it
6923 according to FMT (default from `org-email-link-description-format')."
6924 (setq fmt (or fmt org-email-link-description-format))
6925 (let* ((p org-store-link-plist)
6926 (to (plist-get p :toaddress))
6927 (from (plist-get p :fromaddress))
6928 (table
6929 (list
6930 (cons "%c" (plist-get p :fromto))
6931 (cons "%F" (plist-get p :from))
6932 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6933 (cons "%T" (plist-get p :to))
6934 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6935 (cons "%s" (plist-get p :subject))
6936 (cons "%m" (plist-get p :message-id)))))
6937 (when (string-match "%c" fmt)
6938 ;; Check if the user wrote this message
6939 (if (and org-from-is-user-regexp from to
6940 (save-match-data (string-match org-from-is-user-regexp from)))
6941 (setq fmt (replace-match "to %t" t t fmt))
6942 (setq fmt (replace-match "from %f" t t fmt))))
6943 (org-replace-escapes fmt table)))
6945 (defun org-make-org-heading-search-string (&optional string heading)
6946 "Make search string for STRING or current headline."
6947 (interactive)
6948 (let ((s (or string (org-get-heading))))
6949 (unless (and string (not heading))
6950 ;; We are using a headline, clean up garbage in there.
6951 (if (string-match org-todo-regexp s)
6952 (setq s (replace-match "" t t s)))
6953 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6954 (setq s (replace-match "" t t s)))
6955 (setq s (org-trim s))
6956 (if (string-match (concat "^\\(" org-quote-string "\\|"
6957 org-comment-string "\\)") s)
6958 (setq s (replace-match "" t t s)))
6959 (while (string-match org-ts-regexp s)
6960 (setq s (replace-match "" t t s))))
6961 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6962 (setq s (replace-match " " t t s)))
6963 (or string (setq s (concat "*" s))) ; Add * for headlines
6964 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6966 (defun org-make-link (&rest strings)
6967 "Concatenate STRINGS."
6968 (apply 'concat strings))
6970 (defun org-make-link-string (link &optional description)
6971 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6972 (unless (string-match "\\S-" link)
6973 (error "Empty link"))
6974 (when (stringp description)
6975 ;; Remove brackets from the description, they are fatal.
6976 (while (string-match "\\[" description)
6977 (setq description (replace-match "{" t t description)))
6978 (while (string-match "\\]" description)
6979 (setq description (replace-match "}" t t description))))
6980 (when (equal (org-link-escape link) description)
6981 ;; No description needed, it is identical
6982 (setq description nil))
6983 (when (and (not description)
6984 (not (equal link (org-link-escape link))))
6985 (setq description (org-extract-attributes link)))
6986 (concat "[[" (org-link-escape link) "]"
6987 (if description (concat "[" description "]") "")
6988 "]"))
6990 (defconst org-link-escape-chars
6991 '((?\ . "%20")
6992 (?\[ . "%5B")
6993 (?\] . "%5D")
6994 (?\340 . "%E0") ; `a
6995 (?\342 . "%E2") ; ^a
6996 (?\347 . "%E7") ; ,c
6997 (?\350 . "%E8") ; `e
6998 (?\351 . "%E9") ; 'e
6999 (?\352 . "%EA") ; ^e
7000 (?\356 . "%EE") ; ^i
7001 (?\364 . "%F4") ; ^o
7002 (?\371 . "%F9") ; `u
7003 (?\373 . "%FB") ; ^u
7004 (?\; . "%3B")
7005 (?? . "%3F")
7006 (?= . "%3D")
7007 (?+ . "%2B")
7009 "Association list of escapes for some characters problematic in links.
7010 This is the list that is used for internal purposes.")
7012 (defconst org-link-escape-chars-browser
7013 '((?\ . "%20")) ; 32 for the SPC char
7014 "Association list of escapes for some characters problematic in links.
7015 This is the list that is used before handing over to the browser.")
7017 (defun org-link-escape (text &optional table)
7018 "Escape characters in TEXT that are problematic for links."
7019 (setq table (or table org-link-escape-chars))
7020 (when text
7021 (let ((re (mapconcat (lambda (x) (regexp-quote
7022 (char-to-string (car x))))
7023 table "\\|")))
7024 (while (string-match re text)
7025 (setq text
7026 (replace-match
7027 (cdr (assoc (string-to-char (match-string 0 text))
7028 table))
7029 t t text)))
7030 text)))
7032 (defun org-link-unescape (text &optional table)
7033 "Reverse the action of `org-link-escape'."
7034 (setq table (or table org-link-escape-chars))
7035 (when text
7036 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7037 table "\\|")))
7038 (while (string-match re text)
7039 (setq text
7040 (replace-match
7041 (char-to-string (car (rassoc (match-string 0 text) table)))
7042 t t text)))
7043 text)))
7045 (defun org-xor (a b)
7046 "Exclusive or."
7047 (if a (not b) b))
7049 (defun org-fixup-message-id-for-http (s)
7050 "Replace special characters in a message id, so it can be used in an http query."
7051 (while (string-match "<" s)
7052 (setq s (replace-match "%3C" t t s)))
7053 (while (string-match ">" s)
7054 (setq s (replace-match "%3E" t t s)))
7055 (while (string-match "@" s)
7056 (setq s (replace-match "%40" t t s)))
7059 ;;;###autoload
7060 (defun org-insert-link-global ()
7061 "Insert a link like Org-mode does.
7062 This command can be called in any mode to insert a link in Org-mode syntax."
7063 (interactive)
7064 (org-load-modules-maybe)
7065 (org-run-like-in-org-mode 'org-insert-link))
7067 (defun org-insert-link (&optional complete-file link-location)
7068 "Insert a link. At the prompt, enter the link.
7070 Completion can be used to insert any of the link protocol prefixes like
7071 http or ftp in use.
7073 The history can be used to select a link previously stored with
7074 `org-store-link'. When the empty string is entered (i.e. if you just
7075 press RET at the prompt), the link defaults to the most recently
7076 stored link. As SPC triggers completion in the minibuffer, you need to
7077 use M-SPC or C-q SPC to force the insertion of a space character.
7079 You will also be prompted for a description, and if one is given, it will
7080 be displayed in the buffer instead of the link.
7082 If there is already a link at point, this command will allow you to edit link
7083 and description parts.
7085 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7086 be selected using completion. The path to the file will be relative to the
7087 current directory if the file is in the current directory or a subdirectory.
7088 Otherwise, the link will be the absolute path as completed in the minibuffer
7089 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7090 option `org-link-file-path-type'.
7092 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7093 the current directory or below.
7095 With three \\[universal-argument] prefixes, negate the meaning of
7096 `org-keep-stored-link-after-insertion'.
7098 If `org-make-link-description-function' is non-nil, this function will be
7099 called with the link target, and the result will be the default
7100 link description.
7102 If the LINK-LOCATION parameter is non-nil, this value will be
7103 used as the link location instead of reading one interactively."
7104 (interactive "P")
7105 (let* ((wcf (current-window-configuration))
7106 (region (if (org-region-active-p)
7107 (buffer-substring (region-beginning) (region-end))))
7108 (remove (and region (list (region-beginning) (region-end))))
7109 (desc region)
7110 tmphist ; byte-compile incorrectly complains about this
7111 (link link-location)
7112 entry file)
7113 (cond
7114 (link-location) ; specified by arg, just use it.
7115 ((org-in-regexp org-bracket-link-regexp 1)
7116 ;; We do have a link at point, and we are going to edit it.
7117 (setq remove (list (match-beginning 0) (match-end 0)))
7118 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7119 (setq link (read-string "Link: "
7120 (org-link-unescape
7121 (org-match-string-no-properties 1)))))
7122 ((or (org-in-regexp org-angle-link-re)
7123 (org-in-regexp org-plain-link-re))
7124 ;; Convert to bracket link
7125 (setq remove (list (match-beginning 0) (match-end 0))
7126 link (read-string "Link: "
7127 (org-remove-angle-brackets (match-string 0)))))
7128 ((member complete-file '((4) (16)))
7129 ;; Completing read for file names.
7130 (setq file (read-file-name "File: "))
7131 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7132 (pwd1 (file-name-as-directory (abbreviate-file-name
7133 (expand-file-name ".")))))
7134 (cond
7135 ((equal complete-file '(16))
7136 (setq link (org-make-link
7137 "file:"
7138 (abbreviate-file-name (expand-file-name file)))))
7139 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7140 (setq link (org-make-link "file:" (match-string 1 file))))
7141 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7142 (expand-file-name file))
7143 (setq link (org-make-link
7144 "file:" (match-string 1 (expand-file-name file)))))
7145 (t (setq link (org-make-link "file:" file))))))
7147 ;; Read link, with completion for stored links.
7148 (with-output-to-temp-buffer "*Org Links*"
7149 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7150 (when org-stored-links
7151 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7152 (princ (mapconcat
7153 (lambda (x)
7154 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7155 (reverse org-stored-links) "\n"))))
7156 (let ((cw (selected-window)))
7157 (select-window (get-buffer-window "*Org Links*"))
7158 (setq truncate-lines t)
7159 (org-fit-window-to-buffer)
7160 (select-window cw))
7161 ;; Fake a link history, containing the stored links.
7162 (setq tmphist (append (mapcar 'car org-stored-links)
7163 org-insert-link-history))
7164 (unwind-protect
7165 (setq link
7166 (let ((org-completion-use-ido nil))
7167 (org-completing-read
7168 "Link: "
7169 (append
7170 (mapcar (lambda (x) (list (concat (car x) ":")))
7171 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7172 (mapcar (lambda (x) (list (concat x ":")))
7173 org-link-types))
7174 nil nil nil
7175 'tmphist
7176 (or (car (car org-stored-links))))))
7177 (set-window-configuration wcf)
7178 (kill-buffer "*Org Links*"))
7179 (setq entry (assoc link org-stored-links))
7180 (or entry (push link org-insert-link-history))
7181 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7182 (not org-keep-stored-link-after-insertion))
7183 (setq org-stored-links (delq (assoc link org-stored-links)
7184 org-stored-links)))
7185 (setq desc (or desc (nth 1 entry)))))
7187 (if (string-match org-plain-link-re link)
7188 ;; URL-like link, normalize the use of angular brackets.
7189 (setq link (org-make-link (org-remove-angle-brackets link))))
7191 ;; Check if we are linking to the current file with a search option
7192 ;; If yes, simplify the link by using only the search option.
7193 (when (and buffer-file-name
7194 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7195 (let* ((path (match-string 1 link))
7196 (case-fold-search nil)
7197 (search (match-string 2 link)))
7198 (save-match-data
7199 (if (equal (file-truename buffer-file-name) (file-truename path))
7200 ;; We are linking to this same file, with a search option
7201 (setq link search)))))
7203 ;; Check if we can/should use a relative path. If yes, simplify the link
7204 (when (string-match "^file:\\(.*\\)" link)
7205 (let* ((path (match-string 1 link))
7206 (origpath path)
7207 (case-fold-search nil))
7208 (cond
7209 ((or (eq org-link-file-path-type 'absolute)
7210 (equal complete-file '(16)))
7211 (setq path (abbreviate-file-name (expand-file-name path))))
7212 ((eq org-link-file-path-type 'noabbrev)
7213 (setq path (expand-file-name path)))
7214 ((eq org-link-file-path-type 'relative)
7215 (setq path (file-relative-name path)))
7217 (save-match-data
7218 (if (string-match (concat "^" (regexp-quote
7219 (file-name-as-directory
7220 (expand-file-name "."))))
7221 (expand-file-name path))
7222 ;; We are linking a file with relative path name.
7223 (setq path (substring (expand-file-name path)
7224 (match-end 0)))
7225 (setq path (abbreviate-file-name (expand-file-name path)))))))
7226 (setq link (concat "file:" path))
7227 (if (equal desc origpath)
7228 (setq desc path))))
7230 (if org-make-link-description-function
7231 (setq desc (funcall org-make-link-description-function link desc)))
7233 (setq desc (read-string "Description: " desc))
7234 (unless (string-match "\\S-" desc) (setq desc nil))
7235 (if remove (apply 'delete-region remove))
7236 (insert (org-make-link-string link desc))))
7238 (defun org-completing-read (&rest args)
7239 "Completing-read with SPACE being a normal character."
7240 (let ((minibuffer-local-completion-map
7241 (copy-keymap minibuffer-local-completion-map)))
7242 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7243 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7244 (apply 'org-ido-completing-read args)))
7246 (defun org-completing-read-no-ido (&rest args)
7247 (let (org-completion-use-ido)
7248 (apply 'org-completing-read args)))
7250 (defun org-ido-completing-read (&rest args)
7251 "Completing-read using `ido-mode' speedups if available"
7252 (if (and org-completion-use-ido
7253 (fboundp 'ido-completing-read)
7254 (boundp 'ido-mode) ido-mode
7255 (listp (second args)))
7256 (let ((ido-enter-matching-directory nil))
7257 (apply 'ido-completing-read (concat (car args))
7258 (mapcar (lambda (x) (car x)) (nth 1 args))
7259 (cddr args)))
7260 (apply 'completing-read args)))
7263 (defun org-extract-attributes (s)
7264 "Extract the attributes cookie from a string and set as text property."
7265 (let (a attr (start 0) key value)
7266 (save-match-data
7267 (when (string-match "{{\\([^}]+\\)}}$" s)
7268 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7269 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7270 (setq key (match-string 1 a) value (match-string 2 a)
7271 start (match-end 0)
7272 attr (plist-put attr (intern key) value))))
7273 (org-add-props s nil 'org-attr attr))
7276 (defun org-attributes-to-string (plist)
7277 "Format a property list into an HTML attribute list."
7278 (let ((s "") key value)
7279 (while plist
7280 (setq key (pop plist) value (pop plist))
7281 (and value
7282 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7285 ;;; Opening/following a link
7287 (defvar org-link-search-failed nil)
7289 (defun org-next-link ()
7290 "Move forward to the next link.
7291 If the link is in hidden text, expose it."
7292 (interactive)
7293 (when (and org-link-search-failed (eq this-command last-command))
7294 (goto-char (point-min))
7295 (message "Link search wrapped back to beginning of buffer"))
7296 (setq org-link-search-failed nil)
7297 (let* ((pos (point))
7298 (ct (org-context))
7299 (a (assoc :link ct)))
7300 (if a (goto-char (nth 2 a)))
7301 (if (re-search-forward org-any-link-re nil t)
7302 (progn
7303 (goto-char (match-beginning 0))
7304 (if (org-invisible-p) (org-show-context)))
7305 (goto-char pos)
7306 (setq org-link-search-failed t)
7307 (error "No further link found"))))
7309 (defun org-previous-link ()
7310 "Move backward to the previous link.
7311 If the link is in hidden text, expose it."
7312 (interactive)
7313 (when (and org-link-search-failed (eq this-command last-command))
7314 (goto-char (point-max))
7315 (message "Link search wrapped back to end of buffer"))
7316 (setq org-link-search-failed nil)
7317 (let* ((pos (point))
7318 (ct (org-context))
7319 (a (assoc :link ct)))
7320 (if a (goto-char (nth 1 a)))
7321 (if (re-search-backward org-any-link-re nil t)
7322 (progn
7323 (goto-char (match-beginning 0))
7324 (if (org-invisible-p) (org-show-context)))
7325 (goto-char pos)
7326 (setq org-link-search-failed t)
7327 (error "No further link found"))))
7329 (defun org-translate-link (s)
7330 "Translate a link string if a translation function has been defined."
7331 (if (and org-link-translation-function
7332 (fboundp org-link-translation-function)
7333 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7334 (progn
7335 (setq s (funcall org-link-translation-function
7336 (match-string 1) (match-string 2)))
7337 (concat (car s) ":" (cdr s)))
7340 (defun org-translate-link-from-planner (type path)
7341 "Translate a link from Emacs Planner syntax so that Org can follow it.
7342 This is still an experimental function, your mileage may vary."
7343 (cond
7344 ((member type '("http" "https" "news" "ftp"))
7345 ;; standard Internet links are the same.
7346 nil)
7347 ((and (equal type "irc") (string-match "^//" path))
7348 ;; Planner has two / at the beginning of an irc link, we have 1.
7349 ;; We should have zero, actually....
7350 (setq path (substring path 1)))
7351 ((and (equal type "lisp") (string-match "^/" path))
7352 ;; Planner has a slash, we do not.
7353 (setq type "elisp" path (substring path 1)))
7354 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7355 ;; A typical message link. Planner has the id after the fina slash,
7356 ;; we separate it with a hash mark
7357 (setq path (concat (match-string 1 path) "#"
7358 (org-remove-angle-brackets (match-string 2 path)))))
7360 (cons type path))
7362 (defun org-find-file-at-mouse (ev)
7363 "Open file link or URL at mouse."
7364 (interactive "e")
7365 (mouse-set-point ev)
7366 (org-open-at-point 'in-emacs))
7368 (defun org-open-at-mouse (ev)
7369 "Open file link or URL at mouse."
7370 (interactive "e")
7371 (mouse-set-point ev)
7372 (if (eq major-mode 'org-agenda-mode)
7373 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7374 (org-open-at-point))
7376 (defvar org-window-config-before-follow-link nil
7377 "The window configuration before following a link.
7378 This is saved in case the need arises to restore it.")
7380 (defvar org-open-link-marker (make-marker)
7381 "Marker pointing to the location where `org-open-at-point; was called.")
7383 ;;;###autoload
7384 (defun org-open-at-point-global ()
7385 "Follow a link like Org-mode does.
7386 This command can be called in any mode to follow a link that has
7387 Org-mode syntax."
7388 (interactive)
7389 (org-run-like-in-org-mode 'org-open-at-point))
7391 ;;;###autoload
7392 (defun org-open-link-from-string (s &optional arg)
7393 "Open a link in the string S, as if it was in Org-mode."
7394 (interactive "sLink: \nP")
7395 (with-temp-buffer
7396 (let ((org-inhibit-startup t))
7397 (org-mode)
7398 (insert s)
7399 (goto-char (point-min))
7400 (org-open-at-point arg))))
7402 (defun org-open-at-point (&optional in-emacs)
7403 "Open link at or after point.
7404 If there is no link at point, this function will search forward up to
7405 the end of the current subtree.
7406 Normally, files will be opened by an appropriate application. If the
7407 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7408 With a double prefix argument, try to open outside of Emacs, in the
7409 application the system uses for this file type."
7410 (interactive "P")
7411 (org-load-modules-maybe)
7412 (move-marker org-open-link-marker (point))
7413 (setq org-window-config-before-follow-link (current-window-configuration))
7414 (org-remove-occur-highlights nil nil t)
7415 (cond
7416 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7417 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7418 (org-footnote-action))
7420 (let (type path link line search (pos (point)))
7421 (catch 'match
7422 (save-excursion
7423 (skip-chars-forward "^]\n\r")
7424 (when (org-in-regexp org-bracket-link-regexp)
7425 (setq link (org-extract-attributes
7426 (org-link-unescape (org-match-string-no-properties 1))))
7427 (while (string-match " *\n *" link)
7428 (setq link (replace-match " " t t link)))
7429 (setq link (org-link-expand-abbrev link))
7430 (cond
7431 ((or (file-name-absolute-p link)
7432 (string-match "^\\.\\.?/" link))
7433 (setq type "file" path link))
7434 ((string-match org-link-re-with-space3 link)
7435 (setq type (match-string 1 link) path (match-string 2 link)))
7436 (t (setq type "thisfile" path link)))
7437 (throw 'match t)))
7439 (when (get-text-property (point) 'org-linked-text)
7440 (setq type "thisfile"
7441 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7442 (1+ (point)) (point))
7443 path (buffer-substring
7444 (previous-single-property-change pos 'org-linked-text)
7445 (next-single-property-change pos 'org-linked-text)))
7446 (throw 'match t))
7448 (save-excursion
7449 (when (or (org-in-regexp org-angle-link-re)
7450 (org-in-regexp org-plain-link-re))
7451 (setq type (match-string 1) path (match-string 2))
7452 (throw 'match t)))
7453 (save-excursion
7454 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7455 (setq type "tags"
7456 path (match-string 1))
7457 (while (string-match ":" path)
7458 (setq path (replace-match "+" t t path)))
7459 (throw 'match t)))
7460 (when (org-in-regexp "<\\([^><\n]+\\)>")
7461 (setq type "tree-match"
7462 path (match-string 1))
7463 (throw 'match t)))
7464 (unless path
7465 (error "No link found"))
7466 ;; Remove any trailing spaces in path
7467 (if (string-match " +\\'" path)
7468 (setq path (replace-match "" t t path)))
7469 (if (and org-link-translation-function
7470 (fboundp org-link-translation-function))
7471 ;; Check if we need to translate the link
7472 (let ((tmp (funcall org-link-translation-function type path)))
7473 (setq type (car tmp) path (cdr tmp))))
7475 (cond
7477 ((assoc type org-link-protocols)
7478 (funcall (nth 1 (assoc type org-link-protocols)) path))
7480 ((equal type "mailto")
7481 (let ((cmd (car org-link-mailto-program))
7482 (args (cdr org-link-mailto-program)) args1
7483 (address path) (subject "") a)
7484 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7485 (setq address (match-string 1 path)
7486 subject (org-link-escape (match-string 2 path))))
7487 (while args
7488 (cond
7489 ((not (stringp (car args))) (push (pop args) args1))
7490 (t (setq a (pop args))
7491 (if (string-match "%a" a)
7492 (setq a (replace-match address t t a)))
7493 (if (string-match "%s" a)
7494 (setq a (replace-match subject t t a)))
7495 (push a args1))))
7496 (apply cmd (nreverse args1))))
7498 ((member type '("http" "https" "ftp" "news"))
7499 (browse-url (concat type ":" (org-link-escape
7500 path org-link-escape-chars-browser))))
7502 ((member type '("message"))
7503 (browse-url (concat type ":" path)))
7505 ((string= type "tags")
7506 (org-tags-view in-emacs path))
7507 ((string= type "thisfile")
7508 (if in-emacs
7509 (switch-to-buffer-other-window
7510 (org-get-buffer-for-internal-link (current-buffer)))
7511 (org-mark-ring-push))
7512 (let ((cmd `(org-link-search
7513 ,path
7514 ,(cond ((equal in-emacs '(4)) 'occur)
7515 ((equal in-emacs '(16)) 'org-occur)
7516 (t nil))
7517 ,pos)))
7518 (condition-case nil (eval cmd)
7519 (error (progn (widen) (eval cmd))))))
7521 ((string= type "tree-match")
7522 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7524 ((string= type "file")
7525 (if (string-match "::\\([0-9]+\\)\\'" path)
7526 (setq line (string-to-number (match-string 1 path))
7527 path (substring path 0 (match-beginning 0)))
7528 (if (string-match "::\\(.+\\)\\'" path)
7529 (setq search (match-string 1 path)
7530 path (substring path 0 (match-beginning 0)))))
7531 (if (string-match "[*?{]" (file-name-nondirectory path))
7532 (dired path)
7533 (org-open-file path in-emacs line search)))
7535 ((string= type "news")
7536 (require 'org-gnus)
7537 (org-gnus-follow-link path))
7539 ((string= type "shell")
7540 (let ((cmd path))
7541 (if (or (not org-confirm-shell-link-function)
7542 (funcall org-confirm-shell-link-function
7543 (format "Execute \"%s\" in shell? "
7544 (org-add-props cmd nil
7545 'face 'org-warning))))
7546 (progn
7547 (message "Executing %s" cmd)
7548 (shell-command cmd))
7549 (error "Abort"))))
7551 ((string= type "elisp")
7552 (let ((cmd path))
7553 (if (or (not org-confirm-elisp-link-function)
7554 (funcall org-confirm-elisp-link-function
7555 (format "Execute \"%s\" as elisp? "
7556 (org-add-props cmd nil
7557 'face 'org-warning))))
7558 (message "%s => %s" cmd
7559 (if (equal (string-to-char cmd) ?\()
7560 (eval (read cmd))
7561 (call-interactively (read cmd))))
7562 (error "Abort"))))
7565 (browse-url-at-point))))))
7566 (move-marker org-open-link-marker nil)
7567 (run-hook-with-args 'org-follow-link-hook))
7569 ;;;; Time estimates
7571 (defun org-get-effort (&optional pom)
7572 "Get the effort estimate for the current entry."
7573 (org-entry-get pom org-effort-property))
7575 ;;; File search
7577 (defvar org-create-file-search-functions nil
7578 "List of functions to construct the right search string for a file link.
7579 These functions are called in turn with point at the location to
7580 which the link should point.
7582 A function in the hook should first test if it would like to
7583 handle this file type, for example by checking the major-mode or
7584 the file extension. If it decides not to handle this file, it
7585 should just return nil to give other functions a chance. If it
7586 does handle the file, it must return the search string to be used
7587 when following the link. The search string will be part of the
7588 file link, given after a double colon, and `org-open-at-point'
7589 will automatically search for it. If special measures must be
7590 taken to make the search successful, another function should be
7591 added to the companion hook `org-execute-file-search-functions',
7592 which see.
7594 A function in this hook may also use `setq' to set the variable
7595 `description' to provide a suggestion for the descriptive text to
7596 be used for this link when it gets inserted into an Org-mode
7597 buffer with \\[org-insert-link].")
7599 (defvar org-execute-file-search-functions nil
7600 "List of functions to execute a file search triggered by a link.
7602 Functions added to this hook must accept a single argument, the
7603 search string that was part of the file link, the part after the
7604 double colon. The function must first check if it would like to
7605 handle this search, for example by checking the major-mode or the
7606 file extension. If it decides not to handle this search, it
7607 should just return nil to give other functions a chance. If it
7608 does handle the search, it must return a non-nil value to keep
7609 other functions from trying.
7611 Each function can access the current prefix argument through the
7612 variable `current-prefix-argument'. Note that a single prefix is
7613 used to force opening a link in Emacs, so it may be good to only
7614 use a numeric or double prefix to guide the search function.
7616 In case this is needed, a function in this hook can also restore
7617 the window configuration before `org-open-at-point' was called using:
7619 (set-window-configuration org-window-config-before-follow-link)")
7621 (defun org-link-search (s &optional type avoid-pos)
7622 "Search for a link search option.
7623 If S is surrounded by forward slashes, it is interpreted as a
7624 regular expression. In org-mode files, this will create an `org-occur'
7625 sparse tree. In ordinary files, `occur' will be used to list matches.
7626 If the current buffer is in `dired-mode', grep will be used to search
7627 in all files. If AVOID-POS is given, ignore matches near that position."
7628 (let ((case-fold-search t)
7629 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7630 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7631 (append '(("") (" ") ("\t") ("\n"))
7632 org-emphasis-alist)
7633 "\\|") "\\)"))
7634 (pos (point))
7635 (pre nil) (post nil)
7636 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7637 (cond
7638 ;; First check if there are any special
7639 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7640 ;; Now try the builtin stuff
7641 ((save-excursion
7642 (goto-char (point-min))
7643 (and
7644 (re-search-forward
7645 (concat "<<" (regexp-quote s0) ">>") nil t)
7646 (setq type 'dedicated
7647 pos (match-beginning 0))))
7648 ;; There is an exact target for this
7649 (goto-char pos))
7650 ((and (string-match "^(\\(.*\\))$" s0)
7651 (save-excursion
7652 (goto-char (point-min))
7653 (and
7654 (re-search-forward
7655 (concat "[^[]" (regexp-quote
7656 (format org-coderef-label-format
7657 (match-string 1 s0))))
7658 nil t)
7659 (setq type 'dedicated
7660 pos (1+ (match-beginning 0))))))
7661 ;; There is a coderef target for this
7662 (goto-char pos))
7663 ((string-match "^/\\(.*\\)/$" s)
7664 ;; A regular expression
7665 (cond
7666 ((org-mode-p)
7667 (org-occur (match-string 1 s)))
7668 ;;((eq major-mode 'dired-mode)
7669 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7670 (t (org-do-occur (match-string 1 s)))))
7672 ;; A normal search strings
7673 (when (equal (string-to-char s) ?*)
7674 ;; Anchor on headlines, post may include tags.
7675 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7676 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7677 s (substring s 1)))
7678 (remove-text-properties
7679 0 (length s)
7680 '(face nil mouse-face nil keymap nil fontified nil) s)
7681 ;; Make a series of regular expressions to find a match
7682 (setq words (org-split-string s "[ \n\r\t]+")
7684 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7685 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7686 "\\)" markers)
7687 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7688 re2a (concat "[ \t\r\n]" re2a_)
7689 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7690 re4 (concat "[^a-zA-Z_]" re4_)
7692 re1 (concat pre re2 post)
7693 re3 (concat pre (if pre re4_ re4) post)
7694 re5 (concat pre ".*" re4)
7695 re2 (concat pre re2)
7696 re2a (concat pre (if pre re2a_ re2a))
7697 re4 (concat pre (if pre re4_ re4))
7698 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7699 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7700 re5 "\\)"
7702 (cond
7703 ((eq type 'org-occur) (org-occur reall))
7704 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7705 (t (goto-char (point-min))
7706 (setq type 'fuzzy)
7707 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7708 (org-search-not-self 1 re1 nil t)
7709 (org-search-not-self 1 re2 nil t)
7710 (org-search-not-self 1 re2a nil t)
7711 (org-search-not-self 1 re3 nil t)
7712 (org-search-not-self 1 re4 nil t)
7713 (org-search-not-self 1 re5 nil t)
7715 (goto-char (match-beginning 1))
7716 (goto-char pos)
7717 (error "No match")))))
7719 ;; Normal string-search
7720 (goto-char (point-min))
7721 (if (search-forward s nil t)
7722 (goto-char (match-beginning 0))
7723 (error "No match"))))
7724 (and (org-mode-p) (org-show-context 'link-search))
7725 type))
7727 (defun org-search-not-self (group &rest args)
7728 "Execute `re-search-forward', but only accept matches that do not
7729 enclose the position of `org-open-link-marker'."
7730 (let ((m org-open-link-marker))
7731 (catch 'exit
7732 (while (apply 're-search-forward args)
7733 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7734 (goto-char (match-end group))
7735 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7736 (> (match-beginning 0) (marker-position m))
7737 (< (match-end 0) (marker-position m)))
7738 (save-match-data
7739 (or (not (org-in-regexp
7740 org-bracket-link-analytic-regexp 1))
7741 (not (match-end 4)) ; no description
7742 (and (<= (match-beginning 4) (point))
7743 (>= (match-end 4) (point))))))
7744 (throw 'exit (point))))))))
7746 (defun org-get-buffer-for-internal-link (buffer)
7747 "Return a buffer to be used for displaying the link target of internal links."
7748 (cond
7749 ((not org-display-internal-link-with-indirect-buffer)
7750 buffer)
7751 ((string-match "(Clone)$" (buffer-name buffer))
7752 (message "Buffer is already a clone, not making another one")
7753 ;; we also do not modify visibility in this case
7754 buffer)
7755 (t ; make a new indirect buffer for displaying the link
7756 (let* ((bn (buffer-name buffer))
7757 (ibn (concat bn "(Clone)"))
7758 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7759 (with-current-buffer ib (org-overview))
7760 ib))))
7762 (defun org-do-occur (regexp &optional cleanup)
7763 "Call the Emacs command `occur'.
7764 If CLEANUP is non-nil, remove the printout of the regular expression
7765 in the *Occur* buffer. This is useful if the regex is long and not useful
7766 to read."
7767 (occur regexp)
7768 (when cleanup
7769 (let ((cwin (selected-window)) win beg end)
7770 (when (setq win (get-buffer-window "*Occur*"))
7771 (select-window win))
7772 (goto-char (point-min))
7773 (when (re-search-forward "match[a-z]+" nil t)
7774 (setq beg (match-end 0))
7775 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7776 (setq end (1- (match-beginning 0)))))
7777 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7778 (goto-char (point-min))
7779 (select-window cwin))))
7781 ;;; The mark ring for links jumps
7783 (defvar org-mark-ring nil
7784 "Mark ring for positions before jumps in Org-mode.")
7785 (defvar org-mark-ring-last-goto nil
7786 "Last position in the mark ring used to go back.")
7787 ;; Fill and close the ring
7788 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7789 (loop for i from 1 to org-mark-ring-length do
7790 (push (make-marker) org-mark-ring))
7791 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7792 org-mark-ring)
7794 (defun org-mark-ring-push (&optional pos buffer)
7795 "Put the current position or POS into the mark ring and rotate it."
7796 (interactive)
7797 (setq pos (or pos (point)))
7798 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7799 (move-marker (car org-mark-ring)
7800 (or pos (point))
7801 (or buffer (current-buffer)))
7802 (message "%s"
7803 (substitute-command-keys
7804 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7806 (defun org-mark-ring-goto (&optional n)
7807 "Jump to the previous position in the mark ring.
7808 With prefix arg N, jump back that many stored positions. When
7809 called several times in succession, walk through the entire ring.
7810 Org-mode commands jumping to a different position in the current file,
7811 or to another Org-mode file, automatically push the old position
7812 onto the ring."
7813 (interactive "p")
7814 (let (p m)
7815 (if (eq last-command this-command)
7816 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7817 (setq p org-mark-ring))
7818 (setq org-mark-ring-last-goto p)
7819 (setq m (car p))
7820 (switch-to-buffer (marker-buffer m))
7821 (goto-char m)
7822 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7824 (defun org-remove-angle-brackets (s)
7825 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7826 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7828 (defun org-add-angle-brackets (s)
7829 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7830 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7832 (defun org-remove-double-quotes (s)
7833 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7834 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7837 ;;; Following specific links
7839 (defun org-follow-timestamp-link ()
7840 (cond
7841 ((org-at-date-range-p t)
7842 (let ((org-agenda-start-on-weekday)
7843 (t1 (match-string 1))
7844 (t2 (match-string 2)))
7845 (setq t1 (time-to-days (org-time-string-to-time t1))
7846 t2 (time-to-days (org-time-string-to-time t2)))
7847 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7848 ((org-at-timestamp-p t)
7849 (org-agenda-list nil (time-to-days (org-time-string-to-time
7850 (substring (match-string 1) 0 10)))
7852 (t (error "This should not happen"))))
7855 ;;; Following file links
7856 (defvar org-wait nil)
7857 (defun org-open-file (path &optional in-emacs line search)
7858 "Open the file at PATH.
7859 First, this expands any special file name abbreviations. Then the
7860 configuration variable `org-file-apps' is checked if it contains an
7861 entry for this file type, and if yes, the corresponding command is launched.
7863 If no application is found, Emacs simply visits the file.
7865 With optional prefix argument IN-EMACS, Emacs will visit the file.
7866 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7867 and o use an external application to visit the file.
7869 Optional LINE specifies a line to go to, optional SEARCH a string to
7870 search for. If LINE or SEARCH is given, the file will always be
7871 opened in Emacs.
7872 If the file does not exist, an error is thrown."
7873 (setq in-emacs (or in-emacs line search))
7874 (let* ((file (if (equal path "")
7875 buffer-file-name
7876 (substitute-in-file-name (expand-file-name path))))
7877 (apps (append org-file-apps (org-default-apps)))
7878 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7879 (dirp (if remp nil (file-directory-p file)))
7880 (file (if (and dirp org-open-directory-means-index-dot-org)
7881 (concat (file-name-as-directory file) "index.org")
7882 file))
7883 (a-m-a-p (assq 'auto-mode apps))
7884 (dfile (downcase file))
7885 (old-buffer (current-buffer))
7886 (old-pos (point))
7887 (old-mode major-mode)
7888 ext cmd)
7889 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7890 (setq ext (match-string 1 dfile))
7891 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7892 (setq ext (match-string 1 dfile))))
7893 (cond
7894 ((equal in-emacs '(16))
7895 (setq cmd (cdr (assoc 'system apps))))
7896 (in-emacs (setq cmd 'emacs))
7898 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7899 (and dirp (cdr (assoc 'directory apps)))
7900 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7901 'string-match)
7902 (cdr (assoc ext apps))
7903 (cdr (assoc t apps))))))
7904 (when (eq cmd 'system)
7905 (setq cmd (cdr (assoc 'system apps))))
7906 (when (eq cmd 'default)
7907 (setq cmd (cdr (assoc t apps))))
7908 (when (eq cmd 'mailcap)
7909 (require 'mailcap)
7910 (mailcap-parse-mailcaps)
7911 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7912 (command (mailcap-mime-info mime-type)))
7913 (if (stringp command)
7914 (setq cmd command)
7915 (setq cmd 'emacs))))
7916 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7917 (not (file-exists-p file))
7918 (not org-open-non-existing-files))
7919 (error "No such file: %s" file))
7920 (cond
7921 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7922 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7923 (while (string-match "['\"]%s['\"]" cmd)
7924 (setq cmd (replace-match "%s" t t cmd)))
7925 (while (string-match "%s" cmd)
7926 (setq cmd (replace-match
7927 (save-match-data
7928 (shell-quote-argument
7929 (convert-standard-filename file)))
7930 t t cmd)))
7931 (save-window-excursion
7932 (start-process-shell-command cmd nil cmd)
7933 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7935 ((or (stringp cmd)
7936 (eq cmd 'emacs))
7937 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7938 (widen)
7939 (if line (goto-line line)
7940 (if search (org-link-search search))))
7941 ((consp cmd)
7942 (let ((file (convert-standard-filename file)))
7943 (eval cmd)))
7944 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7945 (and (org-mode-p) (eq old-mode 'org-mode)
7946 (or (not (equal old-buffer (current-buffer)))
7947 (not (equal old-pos (point))))
7948 (org-mark-ring-push old-pos old-buffer))))
7950 (defun org-default-apps ()
7951 "Return the default applications for this operating system."
7952 (cond
7953 ((eq system-type 'darwin)
7954 org-file-apps-defaults-macosx)
7955 ((eq system-type 'windows-nt)
7956 org-file-apps-defaults-windowsnt)
7957 (t org-file-apps-defaults-gnu)))
7959 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7960 "Convert extensions to regular expressions in the cars of LIST.
7961 Also, weed out any non-string entries, because the return value is used
7962 only for regexp matching.
7963 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7964 point to the symbol `emacs', indicating that the file should
7965 be opened in Emacs."
7966 (append
7967 (delq nil
7968 (mapcar (lambda (x)
7969 (if (not (stringp (car x)))
7971 (if (string-match "\\W" (car x))
7973 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7974 list))
7975 (if add-auto-mode
7976 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7978 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7979 (defun org-file-remote-p (file)
7980 "Test whether FILE specifies a location on a remote system.
7981 Return non-nil if the location is indeed remote.
7983 For example, the filename \"/user@host:/foo\" specifies a location
7984 on the system \"/user@host:\"."
7985 (cond ((fboundp 'file-remote-p)
7986 (file-remote-p file))
7987 ((fboundp 'tramp-handle-file-remote-p)
7988 (tramp-handle-file-remote-p file))
7989 ((and (boundp 'ange-ftp-name-format)
7990 (string-match (car ange-ftp-name-format) file))
7992 (t nil)))
7995 ;;;; Refiling
7997 (defun org-get-org-file ()
7998 "Read a filename, with default directory `org-directory'."
7999 (let ((default (or org-default-notes-file remember-data-file)))
8000 (read-file-name (format "File name [%s]: " default)
8001 (file-name-as-directory org-directory)
8002 default)))
8004 (defun org-notes-order-reversed-p ()
8005 "Check if the current file should receive notes in reversed order."
8006 (cond
8007 ((not org-reverse-note-order) nil)
8008 ((eq t org-reverse-note-order) t)
8009 ((not (listp org-reverse-note-order)) nil)
8010 (t (catch 'exit
8011 (let ((all org-reverse-note-order)
8012 entry)
8013 (while (setq entry (pop all))
8014 (if (string-match (car entry) buffer-file-name)
8015 (throw 'exit (cdr entry))))
8016 nil)))))
8018 (defvar org-refile-target-table nil
8019 "The list of refile targets, created by `org-refile'.")
8021 (defvar org-agenda-new-buffers nil
8022 "Buffers created to visit agenda files.")
8024 (defun org-get-refile-targets (&optional default-buffer)
8025 "Produce a table with refile targets."
8026 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8027 targets txt re files f desc descre fast-path-p level)
8028 (message "Getting targets...")
8029 (with-current-buffer (or default-buffer (current-buffer))
8030 (while (setq entry (pop entries))
8031 (setq files (car entry) desc (cdr entry))
8032 (setq fast-path-p nil)
8033 (cond
8034 ((null files) (setq files (list (current-buffer))))
8035 ((eq files 'org-agenda-files)
8036 (setq files (org-agenda-files 'unrestricted)))
8037 ((and (symbolp files) (fboundp files))
8038 (setq files (funcall files)))
8039 ((and (symbolp files) (boundp files))
8040 (setq files (symbol-value files))))
8041 (if (stringp files) (setq files (list files)))
8042 (cond
8043 ((eq (car desc) :tag)
8044 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8045 ((eq (car desc) :todo)
8046 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8047 ((eq (car desc) :regexp)
8048 (setq descre (cdr desc)))
8049 ((eq (car desc) :level)
8050 (setq descre (concat "^\\*\\{" (number-to-string
8051 (if org-odd-levels-only
8052 (1- (* 2 (cdr desc)))
8053 (cdr desc)))
8054 "\\}[ \t]")))
8055 ((eq (car desc) :maxlevel)
8056 (setq fast-path-p t)
8057 (setq descre (concat "^\\*\\{1," (number-to-string
8058 (if org-odd-levels-only
8059 (1- (* 2 (cdr desc)))
8060 (cdr desc)))
8061 "\\}[ \t]")))
8062 (t (error "Bad refiling target description %s" desc)))
8063 (while (setq f (pop files))
8064 (save-excursion
8065 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8066 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8067 (setq f (expand-file-name f))
8068 (save-excursion
8069 (save-restriction
8070 (widen)
8071 (goto-char (point-min))
8072 (while (re-search-forward descre nil t)
8073 (goto-char (point-at-bol))
8074 (when (looking-at org-complex-heading-regexp)
8075 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8076 txt (org-link-display-format (match-string 4))
8077 re (concat "^" (regexp-quote
8078 (buffer-substring (match-beginning 1)
8079 (match-end 4)))))
8080 (if (match-end 5) (setq re (concat re "[ \t]+"
8081 (regexp-quote
8082 (match-string 5)))))
8083 (setq re (concat re "[ \t]*$"))
8084 (when org-refile-use-outline-path
8085 (setq txt (mapconcat 'org-protect-slash
8086 (append
8087 (if (eq org-refile-use-outline-path 'file)
8088 (list (file-name-nondirectory
8089 (buffer-file-name (buffer-base-buffer))))
8090 (if (eq org-refile-use-outline-path 'full-file-path)
8091 (list (buffer-file-name (buffer-base-buffer)))))
8092 (org-get-outline-path fast-path-p level txt)
8093 (list txt))
8094 "/")))
8095 (push (list txt f re (point)) targets))
8096 (goto-char (point-at-eol))))))))
8097 (message "Getting targets...done")
8098 (nreverse targets))))
8100 (defun org-protect-slash (s)
8101 (while (string-match "/" s)
8102 (setq s (replace-match "\\" t t s)))
8105 (defvar org-olpa (make-vector 20 nil))
8107 (defun org-get-outline-path (&optional fastp level heading)
8108 "Return the outline path to the current entry, as a list."
8109 (if fastp
8110 (progn
8111 (if (> level 19)
8112 (error "Outline path failure, more than 19 levels."))
8113 (loop for i from level upto 19 do
8114 (aset org-olpa i nil))
8115 (prog1
8116 (delq nil (append org-olpa nil))
8117 (aset org-olpa level heading)))
8118 (let (rtn)
8119 (save-excursion
8120 (while (org-up-heading-safe)
8121 (when (looking-at org-complex-heading-regexp)
8122 (push (org-match-string-no-properties 4) rtn)))
8123 rtn))))
8125 (defvar org-refile-history nil
8126 "History for refiling operations.")
8128 (defun org-refile (&optional goto default-buffer)
8129 "Move the entry at point to another heading.
8130 The list of target headings is compiled using the information in
8131 `org-refile-targets', which see. This list is created before each use
8132 and will therefore always be up-to-date.
8134 At the target location, the entry is filed as a subitem of the target heading.
8135 Depending on `org-reverse-note-order', the new subitem will either be the
8136 first or the last subitem.
8138 If there is an active region, all entries in that region will be moved.
8139 However, the region must fulfil the requirement that the first heading
8140 is the first one sets the top-level of the moved text - at most siblings
8141 below it are allowed.
8143 With prefix arg GOTO, the command will only visit the target location,
8144 not actually move anything.
8145 With a double prefix `C-u C-u', go to the location where the last refiling
8146 operation has put the subtree."
8147 (interactive "P")
8148 (let* ((cbuf (current-buffer))
8149 (regionp (org-region-active-p))
8150 (region-start (and regionp (region-beginning)))
8151 (region-end (and regionp (region-end)))
8152 (region-length (and regionp (- region-end region-start)))
8153 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8154 pos it nbuf file re level reversed)
8155 (when regionp (goto-char region-start)
8156 (unless (org-kill-is-subtree-p
8157 (buffer-substring region-start region-end))
8158 (error "The region is not a (sequence of) subtree(s)")))
8159 (if (equal goto '(16))
8160 (org-refile-goto-last-stored)
8161 (when (setq it (org-refile-get-location
8162 (if goto "Goto: " "Refile to: ") default-buffer))
8163 (setq file (nth 1 it)
8164 re (nth 2 it)
8165 pos (nth 3 it))
8166 (if (and (not goto)
8167 (equal (buffer-file-name) file)
8168 (if regionp
8169 (and (>= pos region-start)
8170 (<= pos region-end))
8171 (and (>= pos (point))
8172 (< pos (save-excursion
8173 (org-end-of-subtree t t))))))
8174 (error "Cannot refile to position inside the tree or region"))
8176 (setq nbuf (or (find-buffer-visiting file)
8177 (find-file-noselect file)))
8178 (if goto
8179 (progn
8180 (switch-to-buffer nbuf)
8181 (goto-char pos)
8182 (org-show-context 'org-goto))
8183 (if regionp
8184 (progn
8185 (kill-new (buffer-substring region-start region-end))
8186 (org-save-markers-in-region region-start region-end))
8187 (org-copy-subtree 1 nil t))
8188 (save-excursion
8189 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8190 (find-file-noselect file))))
8191 (setq reversed (org-notes-order-reversed-p))
8192 (save-excursion
8193 (save-restriction
8194 (widen)
8195 (goto-char pos)
8196 (looking-at outline-regexp)
8197 (setq level (org-get-valid-level (funcall outline-level) 1))
8198 (goto-char
8199 (if reversed
8200 (or (outline-next-heading) (point-max))
8201 (or (save-excursion (outline-get-next-sibling))
8202 (org-end-of-subtree t t)
8203 (point-max))))
8204 (if (not (bolp)) (newline))
8205 (bookmark-set "org-refile-last-stored")
8206 (org-paste-subtree level))))
8207 (if regionp
8208 (delete-region (point) (+ (point) region-length))
8209 (org-cut-subtree))
8210 (setq org-markers-to-move nil)
8211 (message "Refiled to \"%s\"" (car it)))))))
8213 (defun org-refile-goto-last-stored ()
8214 "Go to the location where the last refile was stored."
8215 (interactive)
8216 (bookmark-jump "org-refile-last-stored")
8217 (message "This is the location of the last refile"))
8219 (defun org-refile-get-location (&optional prompt default-buffer)
8220 "Prompt the user for a refile location, using PROMPT."
8221 (let ((org-refile-targets org-refile-targets)
8222 (org-refile-use-outline-path org-refile-use-outline-path))
8223 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8224 (unless org-refile-target-table
8225 (error "No refile targets"))
8226 (let* ((cbuf (current-buffer))
8227 (partial-completion-mode nil)
8228 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8229 (cfunc (if (and org-refile-use-outline-path
8230 org-outline-path-complete-in-steps)
8231 'org-olpath-completing-read
8232 'org-ido-completing-read))
8233 (extra (if org-refile-use-outline-path "/" ""))
8234 (filename (and cfn (expand-file-name cfn)))
8235 (tbl (mapcar
8236 (lambda (x)
8237 (if (not (equal filename (nth 1 x)))
8238 (cons (concat (car x) extra " ("
8239 (file-name-nondirectory (nth 1 x)) ")")
8240 (cdr x))
8241 (cons (concat (car x) extra) (cdr x))))
8242 org-refile-target-table))
8243 (completion-ignore-case t))
8244 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8245 tbl)))
8247 (defun org-olpath-completing-read (prompt collection &rest args)
8248 "Read an outline path like a file name."
8249 (let ((thetable collection)
8250 (org-completion-use-ido nil)) ; does not work with ido.
8251 (apply
8252 'org-ido-completing-read prompt
8253 (lambda (string predicate &optional flag)
8254 (let (rtn r f (l (length string)))
8255 (cond
8256 ((eq flag nil)
8257 ;; try completion
8258 (try-completion string thetable))
8259 ((eq flag t)
8260 ;; all-completions
8261 (setq rtn (all-completions string thetable predicate))
8262 (mapcar
8263 (lambda (x)
8264 (setq r (substring x l))
8265 (if (string-match " ([^)]*)$" x)
8266 (setq f (match-string 0 x))
8267 (setq f ""))
8268 (if (string-match "/" r)
8269 (concat string (substring r 0 (match-end 0)) f)
8271 rtn))
8272 ((eq flag 'lambda)
8273 ;; exact match?
8274 (assoc string thetable)))
8276 args)))
8278 ;;;; Dynamic blocks
8280 (defun org-find-dblock (name)
8281 "Find the first dynamic block with name NAME in the buffer.
8282 If not found, stay at current position and return nil."
8283 (let (pos)
8284 (save-excursion
8285 (goto-char (point-min))
8286 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8287 nil t)
8288 (match-beginning 0))))
8289 (if pos (goto-char pos))
8290 pos))
8292 (defconst org-dblock-start-re
8293 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8294 "Matches the startline of a dynamic block, with parameters.")
8296 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8297 "Matches the end of a dynamic block.")
8299 (defun org-create-dblock (plist)
8300 "Create a dynamic block section, with parameters taken from PLIST.
8301 PLIST must contain a :name entry which is used as name of the block."
8302 (unless (bolp) (newline))
8303 (let ((name (plist-get plist :name)))
8304 (insert "#+BEGIN: " name)
8305 (while plist
8306 (if (eq (car plist) :name)
8307 (setq plist (cddr plist))
8308 (insert " " (prin1-to-string (pop plist)))))
8309 (insert "\n\n#+END:\n")
8310 (beginning-of-line -2)))
8312 (defun org-prepare-dblock ()
8313 "Prepare dynamic block for refresh.
8314 This empties the block, puts the cursor at the insert position and returns
8315 the property list including an extra property :name with the block name."
8316 (unless (looking-at org-dblock-start-re)
8317 (error "Not at a dynamic block"))
8318 (let* ((begdel (1+ (match-end 0)))
8319 (name (org-no-properties (match-string 1)))
8320 (params (append (list :name name)
8321 (read (concat "(" (match-string 3) ")")))))
8322 (unless (re-search-forward org-dblock-end-re nil t)
8323 (error "Dynamic block not terminated"))
8324 (setq params
8325 (append params
8326 (list :content (buffer-substring
8327 begdel (match-beginning 0)))))
8328 (delete-region begdel (match-beginning 0))
8329 (goto-char begdel)
8330 (open-line 1)
8331 params))
8333 (defun org-map-dblocks (&optional command)
8334 "Apply COMMAND to all dynamic blocks in the current buffer.
8335 If COMMAND is not given, use `org-update-dblock'."
8336 (let ((cmd (or command 'org-update-dblock))
8337 pos)
8338 (save-excursion
8339 (goto-char (point-min))
8340 (while (re-search-forward org-dblock-start-re nil t)
8341 (goto-char (setq pos (match-beginning 0)))
8342 (condition-case nil
8343 (funcall cmd)
8344 (error (message "Error during update of dynamic block")))
8345 (goto-char pos)
8346 (unless (re-search-forward org-dblock-end-re nil t)
8347 (error "Dynamic block not terminated"))))))
8349 (defun org-dblock-update (&optional arg)
8350 "User command for updating dynamic blocks.
8351 Update the dynamic block at point. With prefix ARG, update all dynamic
8352 blocks in the buffer."
8353 (interactive "P")
8354 (if arg
8355 (org-update-all-dblocks)
8356 (or (looking-at org-dblock-start-re)
8357 (org-beginning-of-dblock))
8358 (org-update-dblock)))
8360 (defun org-update-dblock ()
8361 "Update the dynamic block at point
8362 This means to empty the block, parse for parameters and then call
8363 the correct writing function."
8364 (save-window-excursion
8365 (let* ((pos (point))
8366 (line (org-current-line))
8367 (params (org-prepare-dblock))
8368 (name (plist-get params :name))
8369 (cmd (intern (concat "org-dblock-write:" name))))
8370 (message "Updating dynamic block `%s' at line %d..." name line)
8371 (funcall cmd params)
8372 (message "Updating dynamic block `%s' at line %d...done" name line)
8373 (goto-char pos))))
8375 (defun org-beginning-of-dblock ()
8376 "Find the beginning of the dynamic block at point.
8377 Error if there is no such block at point."
8378 (let ((pos (point))
8379 beg)
8380 (end-of-line 1)
8381 (if (and (re-search-backward org-dblock-start-re nil t)
8382 (setq beg (match-beginning 0))
8383 (re-search-forward org-dblock-end-re nil t)
8384 (> (match-end 0) pos))
8385 (goto-char beg)
8386 (goto-char pos)
8387 (error "Not in a dynamic block"))))
8389 (defun org-update-all-dblocks ()
8390 "Update all dynamic blocks in the buffer.
8391 This function can be used in a hook."
8392 (when (org-mode-p)
8393 (org-map-dblocks 'org-update-dblock)))
8396 ;;;; Completion
8398 (defconst org-additional-option-like-keywords
8399 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8400 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8401 "BEGIN_EXAMPLE" "END_EXAMPLE"
8402 "BEGIN_QUOTE" "END_QUOTE"
8403 "BEGIN_VERSE" "END_VERSE"
8404 "BEGIN_CENTER" "END_CENTER"
8405 "BEGIN_SRC" "END_SRC"
8406 "CATEGORY" "COLUMNS"
8407 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8409 (defcustom org-structure-template-alist
8411 ("s" "#+begin_src ?\n\n#+end_src"
8412 "<src lang=\"?\">\n\n</src>")
8413 ("e" "#+begin_example\n?\n#+end_example"
8414 "<example>\n?\n</example>")
8415 ("q" "#+begin_quote\n?\n#+end_quote"
8416 "<quote>\n?\n</quote>")
8417 ("v" "#+begin_verse\n?\n#+end_verse"
8418 "<verse>\n?\n/verse>")
8419 ("c" "#+begin_center\n?\n#+end_center"
8420 "<center>\n?\n/center>")
8421 ("l" "#+begin_latex\n?\n#+end_latex"
8422 "<literal style=\"latex\">\n?\n</literal>")
8423 ("L" "#+latex: "
8424 "<literal style=\"latex\">?</literal>")
8425 ("h" "#+begin_html\n?\n#+end_html"
8426 "<literal style=\"html\">\n?\n</literal>")
8427 ("H" "#+html: "
8428 "<literal style=\"html\">?</literal>")
8429 ("a" "#+begin_ascii\n?\n#+end_ascii")
8430 ("A" "#+ascii: ")
8431 ("i" "#+include %file ?"
8432 "<include file=%file markup=\"?\">")
8434 "Structure completion elements.
8435 This is a list of abbreviation keys and values. The value gets inserted
8436 it you type @samp{.} followed by the key and then the completion key,
8437 usually `M-TAB'. %file will be replaced by a file name after prompting
8438 for the file using completion.
8439 There are two templates for each key, the first uses the original Org syntax,
8440 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8441 the default when the /org-mtags.el/ module has been loaded. See also the
8442 variable `org-mtags-prefer-muse-templates'.
8443 This is an experimental feature, it is undecided if it is going to stay in."
8444 :group 'org-completion
8445 :type '(repeat
8446 (string :tag "Key")
8447 (string :tag "Template")
8448 (string :tag "Muse Template")))
8450 (defun org-try-structure-completion ()
8451 "Try to complete a structure template before point.
8452 This looks for strings like \"<e\" on an otherwise empty line and
8453 expands them."
8454 (let ((l (buffer-substring (point-at-bol) (point)))
8456 (when (and (looking-at "[ \t]*$")
8457 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8458 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8459 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8460 (match-beginning 1)) a)
8461 t)))
8463 (defun org-complete-expand-structure-template (start cell)
8464 "Expand a structure template."
8465 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8466 (rpl (nth (if musep 2 1) cell)))
8467 (delete-region start (point))
8468 (when (string-match "\\`#\\+" rpl)
8469 (cond
8470 ((bolp))
8471 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8472 (delete-region (point-at-bol) (point)))
8473 (t (newline))))
8474 (setq start (point))
8475 (if (string-match "%file" rpl)
8476 (setq rpl (replace-match
8477 (concat
8478 "\""
8479 (save-match-data
8480 (abbreviate-file-name (read-file-name "Include file: ")))
8481 "\"")
8482 t t rpl)))
8483 (insert rpl)
8484 (if (re-search-backward "\\?" start t) (delete-char 1))))
8487 (defun org-complete (&optional arg)
8488 "Perform completion on word at point.
8489 At the beginning of a headline, this completes TODO keywords as given in
8490 `org-todo-keywords'.
8491 If the current word is preceded by a backslash, completes the TeX symbols
8492 that are supported for HTML support.
8493 If the current word is preceded by \"#+\", completes special words for
8494 setting file options.
8495 In the line after \"#+STARTUP:, complete valid keywords.\"
8496 At all other locations, this simply calls the value of
8497 `org-completion-fallback-command'."
8498 (interactive "P")
8499 (org-without-partial-completion
8500 (catch 'exit
8501 (let* ((a nil)
8502 (end (point))
8503 (beg1 (save-excursion
8504 (skip-chars-backward (org-re "[:alnum:]_@"))
8505 (point)))
8506 (beg (save-excursion
8507 (skip-chars-backward "a-zA-Z0-9_:$")
8508 (point)))
8509 (confirm (lambda (x) (stringp (car x))))
8510 (searchhead (equal (char-before beg) ?*))
8511 (struct
8512 (when (and (member (char-before beg1) '(?. ?<))
8513 (setq a (assoc (buffer-substring beg1 (point))
8514 org-structure-template-alist)))
8515 (org-complete-expand-structure-template (1- beg1) a)
8516 (throw 'exit t)))
8517 (tag (and (equal (char-before beg1) ?:)
8518 (equal (char-after (point-at-bol)) ?*)))
8519 (prop (and (equal (char-before beg1) ?:)
8520 (not (equal (char-after (point-at-bol)) ?*))))
8521 (texp (equal (char-before beg) ?\\))
8522 (link (equal (char-before beg) ?\[))
8523 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8524 beg)
8525 "#+"))
8526 (startup (string-match "^#\\+STARTUP:.*"
8527 (buffer-substring (point-at-bol) (point))))
8528 (completion-ignore-case opt)
8529 (type nil)
8530 (tbl nil)
8531 (table (cond
8532 (opt
8533 (setq type :opt)
8534 (require 'org-exp)
8535 (append
8536 (mapcar
8537 (lambda (x)
8538 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8539 (cons (match-string 2 x) (match-string 1 x)))
8540 (org-split-string (org-get-current-options) "\n"))
8541 (mapcar 'list org-additional-option-like-keywords)))
8542 (startup
8543 (setq type :startup)
8544 org-startup-options)
8545 (link (append org-link-abbrev-alist-local
8546 org-link-abbrev-alist))
8547 (texp
8548 (setq type :tex)
8549 org-html-entities)
8550 ((string-match "\\`\\*+[ \t]+\\'"
8551 (buffer-substring (point-at-bol) beg))
8552 (setq type :todo)
8553 (mapcar 'list org-todo-keywords-1))
8554 (searchhead
8555 (setq type :searchhead)
8556 (save-excursion
8557 (goto-char (point-min))
8558 (while (re-search-forward org-todo-line-regexp nil t)
8559 (push (list
8560 (org-make-org-heading-search-string
8561 (match-string 3) t))
8562 tbl)))
8563 tbl)
8564 (tag (setq type :tag beg beg1)
8565 (or org-tag-alist (org-get-buffer-tags)))
8566 (prop (setq type :prop beg beg1)
8567 (mapcar 'list (org-buffer-property-keys nil t t)))
8568 (t (progn
8569 (call-interactively org-completion-fallback-command)
8570 (throw 'exit nil)))))
8571 (pattern (buffer-substring-no-properties beg end))
8572 (completion (try-completion pattern table confirm)))
8573 (cond ((eq completion t)
8574 (if (not (assoc (upcase pattern) table))
8575 (message "Already complete")
8576 (if (and (equal type :opt)
8577 (not (member (car (assoc (upcase pattern) table))
8578 org-additional-option-like-keywords)))
8579 (insert (substring (cdr (assoc (upcase pattern) table))
8580 (length pattern)))
8581 (if (memq type '(:tag :prop)) (insert ":")))))
8582 ((null completion)
8583 (message "Can't find completion for \"%s\"" pattern)
8584 (ding))
8585 ((not (string= pattern completion))
8586 (delete-region beg end)
8587 (if (string-match " +$" completion)
8588 (setq completion (replace-match "" t t completion)))
8589 (insert completion)
8590 (if (get-buffer-window "*Completions*")
8591 (delete-window (get-buffer-window "*Completions*")))
8592 (if (assoc completion table)
8593 (if (eq type :todo) (insert " ")
8594 (if (memq type '(:tag :prop)) (insert ":"))))
8595 (if (and (equal type :opt) (assoc completion table))
8596 (message "%s" (substitute-command-keys
8597 "Press \\[org-complete] again to insert example settings"))))
8599 (message "Making completion list...")
8600 (let ((list (sort (all-completions pattern table confirm)
8601 'string<)))
8602 (with-output-to-temp-buffer "*Completions*"
8603 (condition-case nil
8604 ;; Protection needed for XEmacs and emacs 21
8605 (display-completion-list list pattern)
8606 (error (display-completion-list list)))))
8607 (message "Making completion list...%s" "done")))))))
8609 ;;;; TODO, DEADLINE, Comments
8611 (defun org-toggle-comment ()
8612 "Change the COMMENT state of an entry."
8613 (interactive)
8614 (save-excursion
8615 (org-back-to-heading)
8616 (let (case-fold-search)
8617 (if (looking-at (concat outline-regexp
8618 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8619 (replace-match "" t t nil 1)
8620 (if (looking-at outline-regexp)
8621 (progn
8622 (goto-char (match-end 0))
8623 (insert org-comment-string " ")))))))
8625 (defvar org-last-todo-state-is-todo nil
8626 "This is non-nil when the last TODO state change led to a TODO state.
8627 If the last change removed the TODO tag or switched to DONE, then
8628 this is nil.")
8630 (defvar org-setting-tags nil) ; dynamically skipped
8632 (defun org-parse-local-options (string var)
8633 "Parse STRING for startup setting relevant for variable VAR."
8634 (let ((rtn (symbol-value var))
8635 e opts)
8636 (save-match-data
8637 (if (or (not string) (not (string-match "\\S-" string)))
8639 (setq opts (delq nil (mapcar (lambda (x)
8640 (setq e (assoc x org-startup-options))
8641 (if (eq (nth 1 e) var) e nil))
8642 (org-split-string string "[ \t]+"))))
8643 (if (not opts)
8645 (setq rtn nil)
8646 (while (setq e (pop opts))
8647 (if (not (nth 3 e))
8648 (setq rtn (nth 2 e))
8649 (if (not (listp rtn)) (setq rtn nil))
8650 (push (nth 2 e) rtn)))
8651 rtn)))))
8653 (defvar org-todo-setup-filter-hook nil
8654 "Hook for functions that pre-filter todo specs.
8656 Each function takes a todo spec and returns either `nil' or the spec
8657 transformed into canonical form." )
8659 (defvar org-todo-get-default-hook nil
8660 "Hook for functions that get a default item for todo.
8662 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8663 `nil' or a string to be used for the todo mark." )
8665 (defvar org-agenda-headline-snapshot-before-repeat)
8666 (defun org-todo (&optional arg)
8667 "Change the TODO state of an item.
8668 The state of an item is given by a keyword at the start of the heading,
8669 like
8670 *** TODO Write paper
8671 *** DONE Call mom
8673 The different keywords are specified in the variable `org-todo-keywords'.
8674 By default the available states are \"TODO\" and \"DONE\".
8675 So for this example: when the item starts with TODO, it is changed to DONE.
8676 When it starts with DONE, the DONE is removed. And when neither TODO nor
8677 DONE are present, add TODO at the beginning of the heading.
8679 With C-u prefix arg, use completion to determine the new state.
8680 With numeric prefix arg, switch to that state.
8681 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8682 With a tripple C-u prefix, circumvent any state blocking.
8684 For calling through lisp, arg is also interpreted in the following way:
8685 'none -> empty state
8686 \"\"(empty string) -> switch to empty state
8687 'done -> switch to DONE
8688 'nextset -> switch to the next set of keywords
8689 'previousset -> switch to the previous set of keywords
8690 \"WAITING\" -> switch to the specified keyword, but only if it
8691 really is a member of `org-todo-keywords'."
8692 (interactive "P")
8693 (if (equal arg '(16)) (setq arg 'nextset))
8694 (let ((org-blocker-hook org-blocker-hook))
8695 (when (equal arg '(64))
8696 (setq arg nil org-blocker-hook nil))
8697 (save-excursion
8698 (catch 'exit
8699 (org-back-to-heading)
8700 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8701 (or (looking-at (concat " +" org-todo-regexp " *"))
8702 (looking-at " *"))
8703 (let* ((match-data (match-data))
8704 (startpos (point-at-bol))
8705 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8706 (org-log-done org-log-done)
8707 (org-log-repeat org-log-repeat)
8708 (org-todo-log-states org-todo-log-states)
8709 (this (match-string 1))
8710 (hl-pos (match-beginning 0))
8711 (head (org-get-todo-sequence-head this))
8712 (ass (assoc head org-todo-kwd-alist))
8713 (interpret (nth 1 ass))
8714 (done-word (nth 3 ass))
8715 (final-done-word (nth 4 ass))
8716 (last-state (or this ""))
8717 (completion-ignore-case t)
8718 (member (member this org-todo-keywords-1))
8719 (tail (cdr member))
8720 (state (cond
8721 ((and org-todo-key-trigger
8722 (or (and (equal arg '(4))
8723 (eq org-use-fast-todo-selection 'prefix))
8724 (and (not arg) org-use-fast-todo-selection
8725 (not (eq org-use-fast-todo-selection
8726 'prefix)))))
8727 ;; Use fast selection
8728 (org-fast-todo-selection))
8729 ((and (equal arg '(4))
8730 (or (not org-use-fast-todo-selection)
8731 (not org-todo-key-trigger)))
8732 ;; Read a state with completion
8733 (org-ido-completing-read
8734 "State: " (mapcar (lambda(x) (list x))
8735 org-todo-keywords-1)
8736 nil t))
8737 ((eq arg 'right)
8738 (if this
8739 (if tail (car tail) nil)
8740 (car org-todo-keywords-1)))
8741 ((eq arg 'left)
8742 (if (equal member org-todo-keywords-1)
8744 (if this
8745 (nth (- (length org-todo-keywords-1)
8746 (length tail) 2)
8747 org-todo-keywords-1)
8748 (org-last org-todo-keywords-1))))
8749 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8750 (setq arg nil))) ; hack to fall back to cycling
8751 (arg
8752 ;; user or caller requests a specific state
8753 (cond
8754 ((equal arg "") nil)
8755 ((eq arg 'none) nil)
8756 ((eq arg 'done) (or done-word (car org-done-keywords)))
8757 ((eq arg 'nextset)
8758 (or (car (cdr (member head org-todo-heads)))
8759 (car org-todo-heads)))
8760 ((eq arg 'previousset)
8761 (let ((org-todo-heads (reverse org-todo-heads)))
8762 (or (car (cdr (member head org-todo-heads)))
8763 (car org-todo-heads))))
8764 ((car (member arg org-todo-keywords-1)))
8765 ((nth (1- (prefix-numeric-value arg))
8766 org-todo-keywords-1))))
8767 ((null member) (or head (car org-todo-keywords-1)))
8768 ((equal this final-done-word) nil) ;; -> make empty
8769 ((null tail) nil) ;; -> first entry
8770 ((memq interpret '(type priority))
8771 (if (eq this-command last-command)
8772 (car tail)
8773 (if (> (length tail) 0)
8774 (or done-word (car org-done-keywords))
8775 nil)))
8777 (car tail))))
8778 (state (or
8779 (run-hook-with-args-until-success
8780 'org-todo-get-default-hook state last-state)
8781 state))
8782 (next (if state (concat " " state " ") " "))
8783 (change-plist (list :type 'todo-state-change :from this :to state
8784 :position startpos))
8785 dolog now-done-p)
8786 (when org-blocker-hook
8787 (setq org-last-todo-state-is-todo
8788 (not (member this org-done-keywords)))
8789 (unless (save-excursion
8790 (save-match-data
8791 (run-hook-with-args-until-failure
8792 'org-blocker-hook change-plist)))
8793 (if (interactive-p)
8794 (error "TODO state change from %s to %s blocked" this state)
8795 ;; fail silently
8796 (message "TODO state change from %s to %s blocked" this state)
8797 (throw 'exit nil))))
8798 (store-match-data match-data)
8799 (replace-match next t t)
8800 (unless (pos-visible-in-window-p hl-pos)
8801 (message "TODO state changed to %s" (org-trim next)))
8802 (unless head
8803 (setq head (org-get-todo-sequence-head state)
8804 ass (assoc head org-todo-kwd-alist)
8805 interpret (nth 1 ass)
8806 done-word (nth 3 ass)
8807 final-done-word (nth 4 ass)))
8808 (when (memq arg '(nextset previousset))
8809 (message "Keyword-Set %d/%d: %s"
8810 (- (length org-todo-sets) -1
8811 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8812 (length org-todo-sets)
8813 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8814 (setq org-last-todo-state-is-todo
8815 (not (member state org-done-keywords)))
8816 (setq now-done-p (and (member state org-done-keywords)
8817 (not (member this org-done-keywords))))
8818 (and logging (org-local-logging logging))
8819 (when (and (or org-todo-log-states org-log-done)
8820 (not (memq arg '(nextset previousset))))
8821 ;; we need to look at recording a time and note
8822 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8823 (nth 2 (assoc this org-todo-log-states))))
8824 (when (and state
8825 (member state org-not-done-keywords)
8826 (not (member this org-not-done-keywords)))
8827 ;; This is now a todo state and was not one before
8828 ;; If there was a CLOSED time stamp, get rid of it.
8829 (org-add-planning-info nil nil 'closed))
8830 (when (and now-done-p org-log-done)
8831 ;; It is now done, and it was not done before
8832 (org-add-planning-info 'closed (org-current-time))
8833 (if (and (not dolog) (eq 'note org-log-done))
8834 (org-add-log-setup 'done state this 'findpos 'note)))
8835 (when (and state dolog)
8836 ;; This is a non-nil state, and we need to log it
8837 (org-add-log-setup 'state state this 'findpos dolog)))
8838 ;; Fixup tag positioning
8839 (org-todo-trigger-tag-changes state)
8840 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8841 (when org-provide-todo-statistics
8842 (org-update-parent-todo-statistics))
8843 (run-hooks 'org-after-todo-state-change-hook)
8844 (if (and arg (not (member state org-done-keywords)))
8845 (setq head (org-get-todo-sequence-head state)))
8846 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8847 ;; Do we need to trigger a repeat?
8848 (when now-done-p
8849 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8850 ;; This is for the agenda, take a snapshot of the headline.
8851 (save-match-data
8852 (setq org-agenda-headline-snapshot-before-repeat
8853 (org-get-heading))))
8854 (org-auto-repeat-maybe state))
8855 ;; Fixup cursor location if close to the keyword
8856 (if (and (outline-on-heading-p)
8857 (not (bolp))
8858 (save-excursion (beginning-of-line 1)
8859 (looking-at org-todo-line-regexp))
8860 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8861 (progn
8862 (goto-char (or (match-end 2) (match-end 1)))
8863 (just-one-space)))
8864 (when org-trigger-hook
8865 (save-excursion
8866 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8868 (defun org-block-todo-from-children-or-siblings (change-plist)
8869 "Block turning an entry into a TODO, using the hierarchy.
8870 This checks whether the current task should be blocked from state
8871 changes. Such blocking occurs when:
8873 1. The task has children which are not all in a completed state.
8875 2. A task has a parent with the property :ORDERED:, and there
8876 are siblings prior to the current task with incomplete
8877 status."
8878 (catch 'dont-block
8879 ;; If this is not a todo state change, or if this entry is already DONE,
8880 ;; do not block
8881 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8882 (member (plist-get change-plist :from)
8883 (cons 'done org-done-keywords))
8884 (member (plist-get change-plist :to)
8885 (cons 'todo org-not-done-keywords)))
8886 (throw 'dont-block t))
8887 ;; If this task has children, and any are undone, it's blocked
8888 (save-excursion
8889 (org-back-to-heading t)
8890 (let ((this-level (funcall outline-level)))
8891 (outline-next-heading)
8892 (let ((child-level (funcall outline-level)))
8893 (while (and (not (eobp))
8894 (> child-level this-level))
8895 ;; this todo has children, check whether they are all
8896 ;; completed
8897 (if (and (not (org-entry-is-done-p))
8898 (org-entry-is-todo-p))
8899 (throw 'dont-block nil))
8900 (outline-next-heading)
8901 (setq child-level (funcall outline-level))))))
8902 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8903 ;; any previous siblings are undone, it's blocked
8904 (save-excursion
8905 (org-back-to-heading t)
8906 (when (save-excursion
8907 (ignore-errors
8908 (org-up-heading-all 1)
8909 (org-entry-get (point) "ORDERED")))
8910 (let* ((this-level (funcall outline-level))
8911 (current-level this-level))
8912 (while (and (not (bobp))
8913 (>= current-level this-level))
8914 (outline-previous-heading)
8915 (setq current-level (funcall outline-level))
8916 (if (= current-level this-level)
8917 ;; This is a younger sibling, check if it is completed
8918 (if (and (not (org-entry-is-done-p))
8919 (org-entry-is-todo-p))
8920 (throw 'dont-block nil)))))))
8921 t)) ; don't block
8923 (defcustom org-track-ordered-property-with-tag nil
8924 "Should the ORDERED property also be shown as a tag?
8925 The ORDERED property decides if an entry should require subtasks to be
8926 completed in sequence. Since a property is not very visible, setting
8927 this option means that toggling the ORDERED property with the command
8928 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
8929 not relevant for the behavior, but it makes things more visible.
8931 Note that toggling the tag with tags commands will not change the property
8932 and therefore not influence behavior!
8934 This can be t, meaning the tag ORDERED should be used, It can also be a
8935 string to select a different tag for this task."
8936 :group 'org-todo
8937 :type '(choice
8938 (const :tag "No tracking" nil)
8939 (const :tag "Track with ORDERED tag" t)
8940 (string :tag "Use other tag")))
8942 (defun org-toggle-ordered-property ()
8943 "Toggle the ORDERED property of the current entry.
8944 For better visibility, you can track the value of this property with a tag.
8945 See variable `org-track-ordered-property-with-tag'."
8946 (interactive)
8947 (let* ((t1 org-track-ordered-property-with-tag)
8948 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
8949 (save-excursion
8950 (org-back-to-heading)
8951 (if (org-entry-get nil "ORDERED")
8952 (progn
8953 (org-delete-property "ORDERED")
8954 (and tag (org-toggle-tag tag 'off))
8955 (message "Subtasks can be completed in arbitrary order"))
8956 (org-entry-put nil "ORDERED" "t")
8957 (and tag (org-toggle-tag tag 'on))
8958 (message "Subtasks must be completed in sequence")))))
8960 (defvar org-blocked-by-checkboxes) ; dynamically scoped
8961 (defun org-block-todo-from-checkboxes (change-plist)
8962 "Block turning an entry into a TODO, using checkboxes.
8963 This checks whether the current task should be blocked from state
8964 changes because there are uncheckd boxes in this entry."
8965 (catch 'dont-block
8966 ;; If this is not a todo state change, or if this entry is already DONE,
8967 ;; do not block
8968 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8969 (member (plist-get change-plist :from)
8970 (cons 'done org-done-keywords))
8971 (member (plist-get change-plist :to)
8972 (cons 'todo org-not-done-keywords)))
8973 (throw 'dont-block t))
8974 ;; If this task has checkboxes that are not checked, it's blocked
8975 (save-excursion
8976 (org-back-to-heading t)
8977 (let ((beg (point)) end)
8978 (outline-next-heading)
8979 (setq end (point))
8980 (goto-char beg)
8981 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8982 end t)
8983 (progn
8984 (if (boundp 'org-blocked-by-checkboxes)
8985 (setq org-blocked-by-checkboxes t))
8986 (throw 'dont-block nil)))))
8987 t)) ; do not block
8989 (defun org-update-parent-todo-statistics ()
8990 "Update any statistics cookie in the parent of the current headline."
8991 (interactive)
8992 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8993 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
8994 (catch 'exit
8995 (save-excursion
8996 (setq level (org-up-heading-safe))
8997 (unless level
8998 (throw 'exit nil))
8999 (while (re-search-forward box-re (point-at-eol) t)
9000 (setq cnt-all 0 cnt-done 0 cookie-present t)
9001 (setq is-percent (match-end 2))
9002 (save-match-data
9003 (unless (outline-next-heading) (throw 'exit nil))
9004 (while (looking-at org-todo-line-regexp)
9005 (setq kwd (match-string 2))
9006 (and kwd (setq cnt-all (1+ cnt-all)))
9007 (and (member kwd org-done-keywords)
9008 (setq cnt-done (1+ cnt-done)))
9009 (condition-case nil
9010 (org-forward-same-level 1)
9011 (error (end-of-line 1)))))
9012 (replace-match
9013 (if is-percent
9014 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9015 (format "[%d/%d]" cnt-done cnt-all))))
9016 (when cookie-present
9017 (run-hook-with-args 'org-after-todo-statistics-hook
9018 cnt-done (- cnt-all cnt-done)))))))
9020 (defvar org-after-todo-statistics-hook nil
9021 "Hook that is called after a TODO statistics cookie has been updated.
9022 Each function is called with two arguments: the number of not-done entries
9023 and the number of done entries.
9025 For example, the following function, when added to this hook, will switch
9026 an entry to DONE when all children are done, and back to TODO when new
9027 entries are set to a TODO status. Note that this hook is only called
9028 when there is a statistics cookie in the headline!
9030 (defun org-summary-todo (n-done n-not-done)
9031 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9032 (let (org-log-done org-log-states) ; turn off logging
9033 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9036 (defun org-todo-trigger-tag-changes (state)
9037 "Apply the changes defined in `org-todo-state-tags-triggers'."
9038 (let ((l org-todo-state-tags-triggers)
9039 changes)
9040 (when (or (not state) (equal state ""))
9041 (setq changes (append changes (cdr (assoc "" l)))))
9042 (when (and (stringp state) (> (length state) 0))
9043 (setq changes (append changes (cdr (assoc state l)))))
9044 (when (member state org-not-done-keywords)
9045 (setq changes (append changes (cdr (assoc 'todo l)))))
9046 (when (member state org-done-keywords)
9047 (setq changes (append changes (cdr (assoc 'done l)))))
9048 (dolist (c changes)
9049 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9051 (defun org-local-logging (value)
9052 "Get logging settings from a property VALUE."
9053 (let* (words w a)
9054 ;; directly set the variables, they are already local.
9055 (setq org-log-done nil
9056 org-log-repeat nil
9057 org-todo-log-states nil)
9058 (setq words (org-split-string value))
9059 (while (setq w (pop words))
9060 (cond
9061 ((setq a (assoc w org-startup-options))
9062 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9063 (set (nth 1 a) (nth 2 a))))
9064 ((setq a (org-extract-log-state-settings w))
9065 (and (member (car a) org-todo-keywords-1)
9066 (push a org-todo-log-states)))))))
9068 (defun org-get-todo-sequence-head (kwd)
9069 "Return the head of the TODO sequence to which KWD belongs.
9070 If KWD is not set, check if there is a text property remembering the
9071 right sequence."
9072 (let (p)
9073 (cond
9074 ((not kwd)
9075 (or (get-text-property (point-at-bol) 'org-todo-head)
9076 (progn
9077 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9078 nil (point-at-eol)))
9079 (get-text-property p 'org-todo-head))))
9080 ((not (member kwd org-todo-keywords-1))
9081 (car org-todo-keywords-1))
9082 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9084 (defun org-fast-todo-selection ()
9085 "Fast TODO keyword selection with single keys.
9086 Returns the new TODO keyword, or nil if no state change should occur."
9087 (let* ((fulltable org-todo-key-alist)
9088 (done-keywords org-done-keywords) ;; needed for the faces.
9089 (maxlen (apply 'max (mapcar
9090 (lambda (x)
9091 (if (stringp (car x)) (string-width (car x)) 0))
9092 fulltable)))
9093 (expert nil)
9094 (fwidth (+ maxlen 3 1 3))
9095 (ncol (/ (- (window-width) 4) fwidth))
9096 tg cnt e c tbl
9097 groups ingroup)
9098 (save-excursion
9099 (save-window-excursion
9100 (if expert
9101 (set-buffer (get-buffer-create " *Org todo*"))
9102 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9103 (erase-buffer)
9104 (org-set-local 'org-done-keywords done-keywords)
9105 (setq tbl fulltable cnt 0)
9106 (while (setq e (pop tbl))
9107 (cond
9108 ((equal e '(:startgroup))
9109 (push '() groups) (setq ingroup t)
9110 (when (not (= cnt 0))
9111 (setq cnt 0)
9112 (insert "\n"))
9113 (insert "{ "))
9114 ((equal e '(:endgroup))
9115 (setq ingroup nil cnt 0)
9116 (insert "}\n"))
9117 ((equal e '(:newline))
9118 (when (not (= cnt 0))
9119 (setq cnt 0)
9120 (insert "\n")
9121 (setq e (car tbl))
9122 (while (equal (car tbl) '(:newline))
9123 (insert "\n")
9124 (setq tbl (cdr tbl)))))
9126 (setq tg (car e) c (cdr e))
9127 (if ingroup (push tg (car groups)))
9128 (setq tg (org-add-props tg nil 'face
9129 (org-get-todo-face tg)))
9130 (if (and (= cnt 0) (not ingroup)) (insert " "))
9131 (insert "[" c "] " tg (make-string
9132 (- fwidth 4 (length tg)) ?\ ))
9133 (when (= (setq cnt (1+ cnt)) ncol)
9134 (insert "\n")
9135 (if ingroup (insert " "))
9136 (setq cnt 0)))))
9137 (insert "\n")
9138 (goto-char (point-min))
9139 (if (not expert) (org-fit-window-to-buffer))
9140 (message "[a-z..]:Set [SPC]:clear")
9141 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9142 (cond
9143 ((or (= c ?\C-g)
9144 (and (= c ?q) (not (rassoc c fulltable))))
9145 (setq quit-flag t))
9146 ((= c ?\ ) nil)
9147 ((setq e (rassoc c fulltable) tg (car e))
9149 (t (setq quit-flag t)))))))
9151 (defun org-entry-is-todo-p ()
9152 (member (org-get-todo-state) org-not-done-keywords))
9154 (defun org-entry-is-done-p ()
9155 (member (org-get-todo-state) org-done-keywords))
9157 (defun org-get-todo-state ()
9158 (save-excursion
9159 (org-back-to-heading t)
9160 (and (looking-at org-todo-line-regexp)
9161 (match-end 2)
9162 (match-string 2))))
9164 (defun org-at-date-range-p (&optional inactive-ok)
9165 "Is the cursor inside a date range?"
9166 (interactive)
9167 (save-excursion
9168 (catch 'exit
9169 (let ((pos (point)))
9170 (skip-chars-backward "^[<\r\n")
9171 (skip-chars-backward "<[")
9172 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9173 (>= (match-end 0) pos)
9174 (throw 'exit t))
9175 (skip-chars-backward "^<[\r\n")
9176 (skip-chars-backward "<[")
9177 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9178 (>= (match-end 0) pos)
9179 (throw 'exit t)))
9180 nil)))
9182 (defun org-get-repeat ()
9183 "Check if there is a deadline/schedule with repeater in this entry."
9184 (save-match-data
9185 (save-excursion
9186 (org-back-to-heading t)
9187 (if (re-search-forward
9188 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9189 (match-string 1)))))
9191 (defvar org-last-changed-timestamp)
9192 (defvar org-last-inserted-timestamp)
9193 (defvar org-log-post-message)
9194 (defvar org-log-note-purpose)
9195 (defvar org-log-note-how)
9196 (defvar org-log-note-extra)
9197 (defun org-auto-repeat-maybe (done-word)
9198 "Check if the current headline contains a repeated deadline/schedule.
9199 If yes, set TODO state back to what it was and change the base date
9200 of repeating deadline/scheduled time stamps to new date.
9201 This function is run automatically after each state change to a DONE state."
9202 ;; last-state is dynamically scoped into this function
9203 (let* ((repeat (org-get-repeat))
9204 (aa (assoc last-state org-todo-kwd-alist))
9205 (interpret (nth 1 aa))
9206 (head (nth 2 aa))
9207 (whata '(("d" . day) ("m" . month) ("y" . year)))
9208 (msg "Entry repeats: ")
9209 (org-log-done nil)
9210 (org-todo-log-states nil)
9211 (nshiftmax 10) (nshift 0)
9212 re type n what ts time)
9213 (when repeat
9214 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9215 (org-todo (if (eq interpret 'type) last-state head))
9216 (when org-log-repeat
9217 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9218 (memq 'org-add-log-note post-command-hook))
9219 ;; OK, we are already setup for some record
9220 (if (eq org-log-repeat 'note)
9221 ;; make sure we take a note, not only a time stamp
9222 (setq org-log-note-how 'note))
9223 ;; Set up for taking a record
9224 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9225 last-state
9226 'findpos org-log-repeat)))
9227 (org-back-to-heading t)
9228 (org-add-planning-info nil nil 'closed)
9229 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9230 org-deadline-time-regexp "\\)\\|\\("
9231 org-ts-regexp "\\)"))
9232 (while (re-search-forward
9233 re (save-excursion (outline-next-heading) (point)) t)
9234 (setq type (if (match-end 1) org-scheduled-string
9235 (if (match-end 3) org-deadline-string "Plain:"))
9236 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9237 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9238 (setq n (string-to-number (match-string 2 ts))
9239 what (match-string 3 ts))
9240 (if (equal what "w") (setq n (* n 7) what "d"))
9241 ;; Preparation, see if we need to modify the start date for the change
9242 (when (match-end 1)
9243 (setq time (save-match-data (org-time-string-to-time ts)))
9244 (cond
9245 ((equal (match-string 1 ts) ".")
9246 ;; Shift starting date to today
9247 (org-timestamp-change
9248 (- (time-to-days (current-time)) (time-to-days time))
9249 'day))
9250 ((equal (match-string 1 ts) "+")
9251 (while (or (= nshift 0)
9252 (<= (time-to-days time) (time-to-days (current-time))))
9253 (when (= (incf nshift) nshiftmax)
9254 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9255 (error "Abort")))
9256 (org-timestamp-change n (cdr (assoc what whata)))
9257 (org-at-timestamp-p t)
9258 (setq ts (match-string 1))
9259 (setq time (save-match-data (org-time-string-to-time ts))))
9260 (org-timestamp-change (- n) (cdr (assoc what whata)))
9261 ;; rematch, so that we have everything in place for the real shift
9262 (org-at-timestamp-p t)
9263 (setq ts (match-string 1))
9264 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9265 (org-timestamp-change n (cdr (assoc what whata)))
9266 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9267 (setq org-log-post-message msg)
9268 (message "%s" msg))))
9270 (defun org-show-todo-tree (arg)
9271 "Make a compact tree which shows all headlines marked with TODO.
9272 The tree will show the lines where the regexp matches, and all higher
9273 headlines above the match.
9274 With a \\[universal-argument] prefix, also show the DONE entries.
9275 With a numeric prefix N, construct a sparse tree for the Nth element
9276 of `org-todo-keywords-1'."
9277 (interactive "P")
9278 (let ((case-fold-search nil)
9279 (kwd-re
9280 (cond ((null arg) org-not-done-regexp)
9281 ((equal arg '(4))
9282 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9283 (mapcar 'list org-todo-keywords-1))))
9284 (concat "\\("
9285 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9286 "\\)\\>")))
9287 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9288 (regexp-quote (nth (1- (prefix-numeric-value arg))
9289 org-todo-keywords-1)))
9290 (t (error "Invalid prefix argument: %s" arg)))))
9291 (message "%d TODO entries found"
9292 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9294 (defun org-deadline (&optional remove time)
9295 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9296 With argument REMOVE, remove any deadline from the item.
9297 When TIME is set, it should be an internal time specification, and the
9298 scheduling will use the corresponding date."
9299 (interactive "P")
9300 (if remove
9301 (progn
9302 (org-remove-timestamp-with-keyword org-deadline-string)
9303 (message "Item no longer has a deadline."))
9304 (if (org-get-repeat)
9305 (error "Cannot change deadline on task with repeater, please do that by hand")
9306 (org-add-planning-info 'deadline time 'closed)
9307 (message "Deadline on %s" org-last-inserted-timestamp))))
9309 (defun org-schedule (&optional remove time)
9310 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9311 With argument REMOVE, remove any scheduling date from the item.
9312 When TIME is set, it should be an internal time specification, and the
9313 scheduling will use the corresponding date."
9314 (interactive "P")
9315 (if remove
9316 (progn
9317 (org-remove-timestamp-with-keyword org-scheduled-string)
9318 (message "Item is no longer scheduled."))
9319 (if (org-get-repeat)
9320 (error "Cannot reschedule task with repeater, please do that by hand")
9321 (org-add-planning-info 'scheduled time 'closed)
9322 (message "Scheduled to %s" org-last-inserted-timestamp))))
9324 (defun org-get-scheduled-time (pom &optional inherit)
9325 "Get the scheduled time as a time tuple, of a format suitable
9326 for calling org-schedule with, or if there is no scheduling,
9327 returns nil."
9328 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9329 (when time
9330 (apply 'encode-time (org-parse-time-string time)))))
9332 (defun org-get-deadline-time (pom &optional inherit)
9333 "Get the deadine as a time tuple, of a format suitable for
9334 calling org-deadlin with, or if there is no scheduling, returns
9335 nil."
9336 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9337 (when time
9338 (apply 'encode-time (org-parse-time-string time)))))
9340 (defun org-remove-timestamp-with-keyword (keyword)
9341 "Remove all time stamps with KEYWORD in the current entry."
9342 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9343 beg)
9344 (save-excursion
9345 (org-back-to-heading t)
9346 (setq beg (point))
9347 (org-end-of-subtree t t)
9348 (while (re-search-backward re beg t)
9349 (replace-match "")
9350 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9351 (equal (char-before) ?\ ))
9352 (backward-delete-char 1)
9353 (if (string-match "^[ \t]*$" (buffer-substring
9354 (point-at-bol) (point-at-eol)))
9355 (delete-region (point-at-bol)
9356 (min (point-max) (1+ (point-at-eol))))))))))
9358 (defun org-add-planning-info (what &optional time &rest remove)
9359 "Insert new timestamp with keyword in the line directly after the headline.
9360 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9361 If non is given, the user is prompted for a date.
9362 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9363 be removed."
9364 (interactive)
9365 (let (org-time-was-given org-end-time-was-given ts
9366 end default-time default-input)
9368 (catch 'exit
9369 (when (and (not time) (memq what '(scheduled deadline)))
9370 ;; Try to get a default date/time from existing timestamp
9371 (save-excursion
9372 (org-back-to-heading t)
9373 (setq end (save-excursion (outline-next-heading) (point)))
9374 (when (re-search-forward (if (eq what 'scheduled)
9375 org-scheduled-time-regexp
9376 org-deadline-time-regexp)
9377 end t)
9378 (setq ts (match-string 1)
9379 default-time
9380 (apply 'encode-time (org-parse-time-string ts))
9381 default-input (and ts (org-get-compact-tod ts))))))
9382 (when what
9383 ;; If necessary, get the time from the user
9384 (setq time (or time (org-read-date nil 'to-time nil nil
9385 default-time default-input))))
9387 (when (and org-insert-labeled-timestamps-at-point
9388 (member what '(scheduled deadline)))
9389 (insert
9390 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9391 (org-insert-time-stamp time org-time-was-given
9392 nil nil nil (list org-end-time-was-given))
9393 (setq what nil))
9394 (save-excursion
9395 (save-restriction
9396 (let (col list elt ts buffer-invisibility-spec)
9397 (org-back-to-heading t)
9398 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9399 (goto-char (match-end 1))
9400 (setq col (current-column))
9401 (goto-char (match-end 0))
9402 (if (eobp) (insert "\n") (forward-char 1))
9403 (when (and (not what)
9404 (not (looking-at
9405 (concat "[ \t]*"
9406 org-keyword-time-not-clock-regexp))))
9407 ;; Nothing to add, nothing to remove...... :-)
9408 (throw 'exit nil))
9409 (if (and (not (looking-at outline-regexp))
9410 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9411 "[^\r\n]*"))
9412 (not (equal (match-string 1) org-clock-string)))
9413 (narrow-to-region (match-beginning 0) (match-end 0))
9414 (insert-before-markers "\n")
9415 (backward-char 1)
9416 (narrow-to-region (point) (point))
9417 (and org-adapt-indentation (org-indent-to-column col)))
9418 ;; Check if we have to remove something.
9419 (setq list (cons what remove))
9420 (while list
9421 (setq elt (pop list))
9422 (goto-char (point-min))
9423 (when (or (and (eq elt 'scheduled)
9424 (re-search-forward org-scheduled-time-regexp nil t))
9425 (and (eq elt 'deadline)
9426 (re-search-forward org-deadline-time-regexp nil t))
9427 (and (eq elt 'closed)
9428 (re-search-forward org-closed-time-regexp nil t)))
9429 (replace-match "")
9430 (if (looking-at "--+<[^>]+>") (replace-match ""))
9431 (if (looking-at " +") (replace-match ""))))
9432 (goto-char (point-max))
9433 (when what
9434 (insert
9435 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9436 (cond ((eq what 'scheduled) org-scheduled-string)
9437 ((eq what 'deadline) org-deadline-string)
9438 ((eq what 'closed) org-closed-string))
9439 " ")
9440 (setq ts (org-insert-time-stamp
9441 time
9442 (or org-time-was-given
9443 (and (eq what 'closed) org-log-done-with-time))
9444 (eq what 'closed)
9445 nil nil (list org-end-time-was-given)))
9446 (end-of-line 1))
9447 (goto-char (point-min))
9448 (widen)
9449 (if (and (looking-at "[ \t]+\n")
9450 (equal (char-before) ?\n))
9451 (delete-region (1- (point)) (point-at-eol)))
9452 ts))))))
9454 (defvar org-log-note-marker (make-marker))
9455 (defvar org-log-note-purpose nil)
9456 (defvar org-log-note-state nil)
9457 (defvar org-log-note-previous-state nil)
9458 (defvar org-log-note-how nil)
9459 (defvar org-log-note-extra nil)
9460 (defvar org-log-note-window-configuration nil)
9461 (defvar org-log-note-return-to (make-marker))
9462 (defvar org-log-post-message nil
9463 "Message to be displayed after a log note has been stored.
9464 The auto-repeater uses this.")
9466 (defun org-add-note ()
9467 "Add a note to the current entry.
9468 This is done in the same way as adding a state change note."
9469 (interactive)
9470 (org-add-log-setup 'note nil nil 'findpos nil))
9472 (defvar org-property-end-re)
9473 (defun org-add-log-setup (&optional purpose state prev-state
9474 findpos how &optional extra)
9475 "Set up the post command hook to take a note.
9476 If this is about to TODO state change, the new state is expected in STATE.
9477 When FINDPOS is non-nil, find the correct position for the note in
9478 the current entry. If not, assume that it can be inserted at point.
9479 HOW is an indicator what kind of note should be created.
9480 EXTRA is additional text that will be inserted into the notes buffer."
9481 (let ((drawer (cond ((stringp org-log-into-drawer)
9482 org-log-into-drawer)
9483 (org-log-into-drawer "LOGBOOK")
9484 (t nil))))
9485 (save-restriction
9486 (save-excursion
9487 (when findpos
9488 (org-back-to-heading t)
9489 (narrow-to-region (point) (save-excursion
9490 (outline-next-heading) (point)))
9491 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9492 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9493 "[^\r\n]*\\)?"))
9494 (goto-char (match-end 0))
9495 (cond
9496 (drawer
9497 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9498 nil t)
9499 (progn
9500 (goto-char (match-end 0))
9501 (or org-log-states-order-reversed
9502 (and (re-search-forward org-property-end-re nil t)
9503 (goto-char (1- (match-beginning 0))))))
9504 (insert "\n:" drawer ":\n:END:")
9505 (beginning-of-line 0)
9506 (org-indent-line-function)
9507 (beginning-of-line 2)
9508 (org-indent-line-function)
9509 (end-of-line 0)))
9510 ((and org-log-state-notes-insert-after-drawers
9511 (save-excursion
9512 (forward-line) (looking-at org-drawer-regexp)))
9513 (forward-line)
9514 (while (looking-at org-drawer-regexp)
9515 (goto-char (match-end 0))
9516 (re-search-forward org-property-end-re (point-max) t)
9517 (forward-line))
9518 (forward-line -1)))
9519 (unless org-log-states-order-reversed
9520 (and (= (char-after) ?\n) (forward-char 1))
9521 (org-skip-over-state-notes)
9522 (skip-chars-backward " \t\n\r")))
9523 (move-marker org-log-note-marker (point))
9524 (setq org-log-note-purpose purpose
9525 org-log-note-state state
9526 org-log-note-previous-state prev-state
9527 org-log-note-how how
9528 org-log-note-extra extra)
9529 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9531 (defun org-skip-over-state-notes ()
9532 "Skip past the list of State notes in an entry."
9533 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9534 (while (looking-at "[ \t]*- State")
9535 (condition-case nil
9536 (org-next-item)
9537 (error (org-end-of-item)))))
9539 (defun org-add-log-note (&optional purpose)
9540 "Pop up a window for taking a note, and add this note later at point."
9541 (remove-hook 'post-command-hook 'org-add-log-note)
9542 (setq org-log-note-window-configuration (current-window-configuration))
9543 (delete-other-windows)
9544 (move-marker org-log-note-return-to (point))
9545 (switch-to-buffer (marker-buffer org-log-note-marker))
9546 (goto-char org-log-note-marker)
9547 (org-switch-to-buffer-other-window "*Org Note*")
9548 (erase-buffer)
9549 (if (memq org-log-note-how '(time state))
9550 (let (current-prefix-arg) (org-store-log-note))
9551 (let ((org-inhibit-startup t)) (org-mode))
9552 (insert (format "# Insert note for %s.
9553 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9554 (cond
9555 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9556 ((eq org-log-note-purpose 'done) "closed todo item")
9557 ((eq org-log-note-purpose 'state)
9558 (format "state change from \"%s\" to \"%s\""
9559 (or org-log-note-previous-state "")
9560 (or org-log-note-state "")))
9561 ((eq org-log-note-purpose 'note)
9562 "this entry")
9563 (t (error "This should not happen")))))
9564 (if org-log-note-extra (insert org-log-note-extra))
9565 (org-set-local 'org-finish-function 'org-store-log-note)))
9567 (defvar org-note-abort nil) ; dynamically scoped
9568 (defun org-store-log-note ()
9569 "Finish taking a log note, and insert it to where it belongs."
9570 (let ((txt (buffer-string))
9571 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9572 lines ind)
9573 (kill-buffer (current-buffer))
9574 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9575 (setq txt (replace-match "" t t txt)))
9576 (if (string-match "\\s-+\\'" txt)
9577 (setq txt (replace-match "" t t txt)))
9578 (setq lines (org-split-string txt "\n"))
9579 (when (and note (string-match "\\S-" note))
9580 (setq note
9581 (org-replace-escapes
9582 note
9583 (list (cons "%u" (user-login-name))
9584 (cons "%U" user-full-name)
9585 (cons "%t" (format-time-string
9586 (org-time-stamp-format 'long 'inactive)
9587 (current-time)))
9588 (cons "%s" (if org-log-note-state
9589 (concat "\"" org-log-note-state "\"")
9590 ""))
9591 (cons "%S" (if org-log-note-previous-state
9592 (concat "\"" org-log-note-previous-state "\"")
9593 "\"\"")))))
9594 (if lines (setq note (concat note " \\\\")))
9595 (push note lines))
9596 (when (or current-prefix-arg org-note-abort)
9597 (when org-log-into-drawer
9598 (org-remove-empty-drawer-at
9599 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
9600 org-log-note-marker))
9601 (setq lines nil))
9602 (when lines
9603 (save-excursion
9604 (set-buffer (marker-buffer org-log-note-marker))
9605 (save-excursion
9606 (goto-char org-log-note-marker)
9607 (move-marker org-log-note-marker nil)
9608 (end-of-line 1)
9609 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9610 (insert "- " (pop lines))
9611 (org-indent-line-function)
9612 (beginning-of-line 1)
9613 (looking-at "[ \t]*")
9614 (setq ind (concat (match-string 0) " "))
9615 (end-of-line 1)
9616 (while lines (insert "\n" ind (pop lines)))
9617 (message "Note stored")
9618 (org-back-to-heading t)
9619 (org-cycle-hide-drawers 'children)))))
9620 (set-window-configuration org-log-note-window-configuration)
9621 (with-current-buffer (marker-buffer org-log-note-return-to)
9622 (goto-char org-log-note-return-to))
9623 (move-marker org-log-note-return-to nil)
9624 (and org-log-post-message (message "%s" org-log-post-message)))
9626 (defun org-remove-empty-drawer-at (drawer pos)
9627 "Remove an emptyr DARWER drawer at position POS.
9628 POS may also be a marker."
9629 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
9630 (save-excursion
9631 (save-restriction
9632 (widen)
9633 (goto-char pos)
9634 (if (org-in-regexp
9635 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
9636 (replace-match ""))))))
9638 (defun org-sparse-tree (&optional arg)
9639 "Create a sparse tree, prompt for the details.
9640 This command can create sparse trees. You first need to select the type
9641 of match used to create the tree:
9643 t Show entries with a specific TODO keyword.
9644 m Show entries selected by a tags/property match.
9645 p Enter a property name and its value (both with completion on existing
9646 names/values) and show entries with that property.
9647 r Show entries matching a regular expression.
9648 d Show deadlines due within `org-deadline-warning-days'.
9649 b Show deadlines and scheduled items before a date.
9650 a Show deadlines and scheduled items after a date."
9651 (interactive "P")
9652 (let (ans kwd value)
9653 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
9654 (setq ans (read-char-exclusive))
9655 (cond
9656 ((equal ans ?d)
9657 (call-interactively 'org-check-deadlines))
9658 ((equal ans ?b)
9659 (call-interactively 'org-check-before-date))
9660 ((equal ans ?a)
9661 (call-interactively 'org-check-after-date))
9662 ((equal ans ?t)
9663 (org-show-todo-tree '(4)))
9664 ((member ans '(?T ?m))
9665 (call-interactively 'org-match-sparse-tree))
9666 ((member ans '(?p ?P))
9667 (setq kwd (org-ido-completing-read "Property: "
9668 (mapcar 'list (org-buffer-property-keys))))
9669 (setq value (org-ido-completing-read "Value: "
9670 (mapcar 'list (org-property-values kwd))))
9671 (unless (string-match "\\`{.*}\\'" value)
9672 (setq value (concat "\"" value "\"")))
9673 (org-match-sparse-tree arg (concat kwd "=" value)))
9674 ((member ans '(?r ?R ?/))
9675 (call-interactively 'org-occur))
9676 (t (error "No such sparse tree command \"%c\"" ans)))))
9678 (defvar org-occur-highlights nil
9679 "List of overlays used for occur matches.")
9680 (make-variable-buffer-local 'org-occur-highlights)
9681 (defvar org-occur-parameters nil
9682 "Parameters of the active org-occur calls.
9683 This is a list, each call to org-occur pushes as cons cell,
9684 containing the regular expression and the callback, onto the list.
9685 The list can contain several entries if `org-occur' has been called
9686 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9687 will only contain one set of parameters. When the highlights are
9688 removed (for example with `C-c C-c', or with the next edit (depending
9689 on `org-remove-highlights-with-change'), this variable is emptied
9690 as well.")
9691 (make-variable-buffer-local 'org-occur-parameters)
9693 (defun org-occur (regexp &optional keep-previous callback)
9694 "Make a compact tree which shows all matches of REGEXP.
9695 The tree will show the lines where the regexp matches, and all higher
9696 headlines above the match. It will also show the heading after the match,
9697 to make sure editing the matching entry is easy.
9698 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9699 call to `org-occur' will be kept, to allow stacking of calls to this
9700 command.
9701 If CALLBACK is non-nil, it is a function which is called to confirm
9702 that the match should indeed be shown."
9703 (interactive "sRegexp: \nP")
9704 (unless keep-previous
9705 (org-remove-occur-highlights nil nil t))
9706 (push (cons regexp callback) org-occur-parameters)
9707 (let ((cnt 0))
9708 (save-excursion
9709 (goto-char (point-min))
9710 (if (or (not keep-previous) ; do not want to keep
9711 (not org-occur-highlights)) ; no previous matches
9712 ;; hide everything
9713 (org-overview))
9714 (while (re-search-forward regexp nil t)
9715 (when (or (not callback)
9716 (save-match-data (funcall callback)))
9717 (setq cnt (1+ cnt))
9718 (when org-highlight-sparse-tree-matches
9719 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9720 (org-show-context 'occur-tree))))
9721 (when org-remove-highlights-with-change
9722 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9723 nil 'local))
9724 (unless org-sparse-tree-open-archived-trees
9725 (org-hide-archived-subtrees (point-min) (point-max)))
9726 (run-hooks 'org-occur-hook)
9727 (if (interactive-p)
9728 (message "%d match(es) for regexp %s" cnt regexp))
9729 cnt))
9731 (defun org-show-context (&optional key)
9732 "Make sure point and context and visible.
9733 How much context is shown depends upon the variables
9734 `org-show-hierarchy-above', `org-show-following-heading'. and
9735 `org-show-siblings'."
9736 (let ((heading-p (org-on-heading-p t))
9737 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9738 (following-p (org-get-alist-option org-show-following-heading key))
9739 (entry-p (org-get-alist-option org-show-entry-below key))
9740 (siblings-p (org-get-alist-option org-show-siblings key)))
9741 (catch 'exit
9742 ;; Show heading or entry text
9743 (if (and heading-p (not entry-p))
9744 (org-flag-heading nil) ; only show the heading
9745 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9746 (org-show-hidden-entry))) ; show entire entry
9747 (when following-p
9748 ;; Show next sibling, or heading below text
9749 (save-excursion
9750 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9751 (org-flag-heading nil))))
9752 (when siblings-p (org-show-siblings))
9753 (when hierarchy-p
9754 ;; show all higher headings, possibly with siblings
9755 (save-excursion
9756 (while (and (condition-case nil
9757 (progn (org-up-heading-all 1) t)
9758 (error nil))
9759 (not (bobp)))
9760 (org-flag-heading nil)
9761 (when siblings-p (org-show-siblings))))))))
9763 (defun org-reveal (&optional siblings)
9764 "Show current entry, hierarchy above it, and the following headline.
9765 This can be used to show a consistent set of context around locations
9766 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9767 not t for the search context.
9769 With optional argument SIBLINGS, on each level of the hierarchy all
9770 siblings are shown. This repairs the tree structure to what it would
9771 look like when opened with hierarchical calls to `org-cycle'."
9772 (interactive "P")
9773 (let ((org-show-hierarchy-above t)
9774 (org-show-following-heading t)
9775 (org-show-siblings (if siblings t org-show-siblings)))
9776 (org-show-context nil)))
9778 (defun org-highlight-new-match (beg end)
9779 "Highlight from BEG to END and mark the highlight is an occur headline."
9780 (let ((ov (org-make-overlay beg end)))
9781 (org-overlay-put ov 'face 'secondary-selection)
9782 (push ov org-occur-highlights)))
9784 (defun org-remove-occur-highlights (&optional beg end noremove)
9785 "Remove the occur highlights from the buffer.
9786 BEG and END are ignored. If NOREMOVE is nil, remove this function
9787 from the `before-change-functions' in the current buffer."
9788 (interactive)
9789 (unless org-inhibit-highlight-removal
9790 (mapc 'org-delete-overlay org-occur-highlights)
9791 (setq org-occur-highlights nil)
9792 (setq org-occur-parameters nil)
9793 (unless noremove
9794 (remove-hook 'before-change-functions
9795 'org-remove-occur-highlights 'local))))
9797 ;;;; Priorities
9799 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9800 "Regular expression matching the priority indicator.")
9802 (defvar org-remove-priority-next-time nil)
9804 (defun org-priority-up ()
9805 "Increase the priority of the current item."
9806 (interactive)
9807 (org-priority 'up))
9809 (defun org-priority-down ()
9810 "Decrease the priority of the current item."
9811 (interactive)
9812 (org-priority 'down))
9814 (defun org-priority (&optional action)
9815 "Change the priority of an item by ARG.
9816 ACTION can be `set', `up', `down', or a character."
9817 (interactive)
9818 (setq action (or action 'set))
9819 (let (current new news have remove)
9820 (save-excursion
9821 (org-back-to-heading t)
9822 (if (looking-at org-priority-regexp)
9823 (setq current (string-to-char (match-string 2))
9824 have t)
9825 (setq current org-default-priority))
9826 (cond
9827 ((or (eq action 'set)
9828 (if (featurep 'xemacs) (characterp action) (integerp action)))
9829 (if (not (eq action 'set))
9830 (setq new action)
9831 (message "Priority %c-%c, SPC to remove: "
9832 org-highest-priority org-lowest-priority)
9833 (setq new (read-char-exclusive)))
9834 (if (and (= (upcase org-highest-priority) org-highest-priority)
9835 (= (upcase org-lowest-priority) org-lowest-priority))
9836 (setq new (upcase new)))
9837 (cond ((equal new ?\ ) (setq remove t))
9838 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9839 (error "Priority must be between `%c' and `%c'"
9840 org-highest-priority org-lowest-priority))))
9841 ((eq action 'up)
9842 (if (and (not have) (eq last-command this-command))
9843 (setq new org-lowest-priority)
9844 (setq new (if (and org-priority-start-cycle-with-default (not have))
9845 org-default-priority (1- current)))))
9846 ((eq action 'down)
9847 (if (and (not have) (eq last-command this-command))
9848 (setq new org-highest-priority)
9849 (setq new (if (and org-priority-start-cycle-with-default (not have))
9850 org-default-priority (1+ current)))))
9851 (t (error "Invalid action")))
9852 (if (or (< (upcase new) org-highest-priority)
9853 (> (upcase new) org-lowest-priority))
9854 (setq remove t))
9855 (setq news (format "%c" new))
9856 (if have
9857 (if remove
9858 (replace-match "" t t nil 1)
9859 (replace-match news t t nil 2))
9860 (if remove
9861 (error "No priority cookie found in line")
9862 (looking-at org-todo-line-regexp)
9863 (if (match-end 2)
9864 (progn
9865 (goto-char (match-end 2))
9866 (insert " [#" news "]"))
9867 (goto-char (match-beginning 3))
9868 (insert "[#" news "] ")))))
9869 (org-preserve-lc (org-set-tags nil 'align))
9870 (if remove
9871 (message "Priority removed")
9872 (message "Priority of current item set to %s" news))))
9875 (defun org-get-priority (s)
9876 "Find priority cookie and return priority."
9877 (save-match-data
9878 (if (not (string-match org-priority-regexp s))
9879 (* 1000 (- org-lowest-priority org-default-priority))
9880 (* 1000 (- org-lowest-priority
9881 (string-to-char (match-string 2 s)))))))
9883 ;;;; Tags
9885 (defvar org-agenda-archives-mode)
9886 (defvar org-scanner-tags nil
9887 "The current tag list while the tags scanner is running.")
9888 (defvar org-trust-scanner-tags nil
9889 "Should `org-get-tags-at' use the tags fro the scanner.
9890 This is for internal dynamical scoping only.
9891 When this is non-nil, the function `org-get-tags-at' will return the value
9892 of `org-scanner-tags' instead of building the list by itself. This
9893 can lead to large speed-ups when the tags scanner is used in a file with
9894 many entries, and when the list of tags is retrieved, for example to
9895 obtain a list of properties. Building the tags list for each entry in such
9896 a file becomes an N^2 operation - but with this variable set, it scales
9897 as N.")
9899 (defun org-scan-tags (action matcher &optional todo-only)
9900 "Scan headline tags with inheritance and produce output ACTION.
9902 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9903 or `agenda' to produce an entry list for an agenda view. It can also be
9904 a Lisp form or a function that should be called at each matched headline, in
9905 this case the return value is a list of all return values from these calls.
9907 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9908 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9909 only lines with a TODO keyword are included in the output."
9910 (require 'org-agenda)
9911 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9912 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9913 (org-re
9914 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9915 (props (list 'face 'default
9916 'done-face 'org-agenda-done
9917 'undone-face 'default
9918 'mouse-face 'highlight
9919 'org-not-done-regexp org-not-done-regexp
9920 'org-todo-regexp org-todo-regexp
9921 'keymap org-agenda-keymap
9922 'help-echo
9923 (format "mouse-2 or RET jump to org file %s"
9924 (abbreviate-file-name
9925 (or (buffer-file-name (buffer-base-buffer))
9926 (buffer-name (buffer-base-buffer)))))))
9927 (case-fold-search nil)
9928 lspos tags tags-list
9929 (tags-alist (list (cons 0 org-file-tags)))
9930 (llast 0) rtn rtn1 level category i txt
9931 todo marker entry priority)
9932 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9933 (setq action (list 'lambda nil action)))
9934 (save-excursion
9935 (goto-char (point-min))
9936 (when (eq action 'sparse-tree)
9937 (org-overview)
9938 (org-remove-occur-highlights))
9939 (while (re-search-forward re nil t)
9940 (catch :skip
9941 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
9942 tags (if (match-end 4) (org-match-string-no-properties 4)))
9943 (goto-char (setq lspos (1+ (match-beginning 0))))
9944 (setq level (org-reduced-level (funcall outline-level))
9945 category (org-get-category))
9946 (setq i llast llast level)
9947 ;; remove tag lists from same and sublevels
9948 (while (>= i level)
9949 (when (setq entry (assoc i tags-alist))
9950 (setq tags-alist (delete entry tags-alist)))
9951 (setq i (1- i)))
9952 ;; add the next tags
9953 (when tags
9954 (setq tags (org-split-string tags ":")
9955 tags-alist
9956 (cons (cons level tags) tags-alist)))
9957 ;; compile tags for current headline
9958 (setq tags-list
9959 (if org-use-tag-inheritance
9960 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9961 tags)
9962 org-scanner-tags tags-list)
9963 (when org-use-tag-inheritance
9964 (setcdr (car tags-alist)
9965 (mapcar (lambda (x)
9966 (setq x (copy-sequence x))
9967 (org-add-prop-inherited x))
9968 (cdar tags-alist))))
9969 (when (and tags org-use-tag-inheritance
9970 (or (not (eq t org-use-tag-inheritance))
9971 org-tags-exclude-from-inheritance))
9972 ;; selective inheritance, remove uninherited ones
9973 (setcdr (car tags-alist)
9974 (org-remove-uniherited-tags (cdar tags-alist))))
9975 (when (and (or (not todo-only)
9976 (and (member todo org-not-done-keywords)
9977 (or (not org-agenda-tags-todo-honor-ignore-options)
9978 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9979 (let ((case-fold-search t)) (eval matcher))
9981 (not (member org-archive-tag tags-list))
9982 ;; we have an archive tag, should we use this anyway?
9983 (or (not org-agenda-skip-archived-trees)
9984 (and (eq action 'agenda) org-agenda-archives-mode))))
9985 (unless (eq action 'sparse-tree) (org-agenda-skip))
9987 ;; select this headline
9989 (cond
9990 ((eq action 'sparse-tree)
9991 (and org-highlight-sparse-tree-matches
9992 (org-get-heading) (match-end 0)
9993 (org-highlight-new-match
9994 (match-beginning 0) (match-beginning 1)))
9995 (org-show-context 'tags-tree))
9996 ((eq action 'agenda)
9997 (setq txt (org-format-agenda-item
9999 (concat
10000 (if (eq org-tags-match-list-sublevels 'indented)
10001 (make-string (1- level) ?.) "")
10002 (org-get-heading))
10003 category
10004 tags-list
10006 priority (org-get-priority txt))
10007 (goto-char lspos)
10008 (setq marker (org-agenda-new-marker))
10009 (org-add-props txt props
10010 'org-marker marker 'org-hd-marker marker 'org-category category
10011 'todo-state todo
10012 'priority priority 'type "tagsmatch")
10013 (push txt rtn))
10014 ((functionp action)
10015 (save-excursion
10016 (setq rtn1 (funcall action))
10017 (push rtn1 rtn))
10018 (goto-char (point-at-eol)))
10019 (t (error "Invalid action")))
10021 ;; if we are to skip sublevels, jump to end of subtree
10022 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
10023 (when (and (eq action 'sparse-tree)
10024 (not org-sparse-tree-open-archived-trees))
10025 (org-hide-archived-subtrees (point-min) (point-max)))
10026 (nreverse rtn)))
10028 (defun org-remove-uniherited-tags (tags)
10029 "Remove all tags that are not inherited from the list TAGS."
10030 (cond
10031 ((eq org-use-tag-inheritance t)
10032 (if org-tags-exclude-from-inheritance
10033 (org-delete-all org-tags-exclude-from-inheritance tags)
10034 tags))
10035 ((not org-use-tag-inheritance) nil)
10036 ((stringp org-use-tag-inheritance)
10037 (delq nil (mapcar
10038 (lambda (x)
10039 (if (and (string-match org-use-tag-inheritance x)
10040 (not (member x org-tags-exclude-from-inheritance)))
10041 x nil))
10042 tags)))
10043 ((listp org-use-tag-inheritance)
10044 (delq nil (mapcar
10045 (lambda (x)
10046 (if (member x org-use-tag-inheritance) x nil))
10047 tags)))))
10049 (defvar todo-only) ;; dynamically scoped
10051 (defun org-match-sparse-tree (&optional todo-only match)
10052 "Create a sparse tree according to tags string MATCH.
10053 MATCH can contain positive and negative selection of tags, like
10054 \"+WORK+URGENT-WITHBOSS\".
10055 If optional argument TODO-ONLY is non-nil, only select lines that are
10056 also TODO lines."
10057 (interactive "P")
10058 (org-prepare-agenda-buffers (list (current-buffer)))
10059 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10061 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10063 (defvar org-cached-props nil)
10064 (defun org-cached-entry-get (pom property)
10065 (if (or (eq t org-use-property-inheritance)
10066 (and (stringp org-use-property-inheritance)
10067 (string-match org-use-property-inheritance property))
10068 (and (listp org-use-property-inheritance)
10069 (member property org-use-property-inheritance)))
10070 ;; Caching is not possible, check it directly
10071 (org-entry-get pom property 'inherit)
10072 ;; Get all properties, so that we can do complicated checks easily
10073 (cdr (assoc property (or org-cached-props
10074 (setq org-cached-props
10075 (org-entry-properties pom)))))))
10077 (defun org-global-tags-completion-table (&optional files)
10078 "Return the list of all tags in all agenda buffer/files."
10079 (save-excursion
10080 (org-uniquify
10081 (delq nil
10082 (apply 'append
10083 (mapcar
10084 (lambda (file)
10085 (set-buffer (find-file-noselect file))
10086 (append (org-get-buffer-tags)
10087 (mapcar (lambda (x) (if (stringp (car-safe x))
10088 (list (car-safe x)) nil))
10089 org-tag-alist)))
10090 (if (and files (car files))
10091 files
10092 (org-agenda-files))))))))
10094 (defun org-make-tags-matcher (match)
10095 "Create the TAGS//TODO matcher form for the selection string MATCH."
10096 ;; todo-only is scoped dynamically into this function, and the function
10097 ;; may change it if the matcher asks for it.
10098 (unless match
10099 ;; Get a new match request, with completion
10100 (let ((org-last-tags-completion-table
10101 (org-global-tags-completion-table)))
10102 (setq match (org-completing-read-no-ido
10103 "Match: " 'org-tags-completion-function nil nil nil
10104 'org-tags-history))))
10106 ;; Parse the string and create a lisp form
10107 (let ((match0 match)
10108 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10109 minus tag mm
10110 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10111 orterms term orlist re-p str-p level-p level-op time-p
10112 prop-p pn pv po cat-p gv rest)
10113 (if (string-match "/+" match)
10114 ;; match contains also a todo-matching request
10115 (progn
10116 (setq tagsmatch (substring match 0 (match-beginning 0))
10117 todomatch (substring match (match-end 0)))
10118 (if (string-match "^!" todomatch)
10119 (setq todo-only t todomatch (substring todomatch 1)))
10120 (if (string-match "^\\s-*$" todomatch)
10121 (setq todomatch nil)))
10122 ;; only matching tags
10123 (setq tagsmatch match todomatch nil))
10125 ;; Make the tags matcher
10126 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10127 (setq tagsmatcher t)
10128 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10129 (while (setq term (pop orterms))
10130 (while (and (equal (substring term -1) "\\") orterms)
10131 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10132 (while (string-match re term)
10133 (setq rest (substring term (match-end 0))
10134 minus (and (match-end 1)
10135 (equal (match-string 1 term) "-"))
10136 tag (match-string 2 term)
10137 re-p (equal (string-to-char tag) ?{)
10138 level-p (match-end 4)
10139 prop-p (match-end 5)
10140 mm (cond
10141 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10142 (level-p
10143 (setq level-op (org-op-to-function (match-string 3 term)))
10144 `(,level-op level ,(string-to-number
10145 (match-string 4 term))))
10146 (prop-p
10147 (setq pn (match-string 5 term)
10148 po (match-string 6 term)
10149 pv (match-string 7 term)
10150 cat-p (equal pn "CATEGORY")
10151 re-p (equal (string-to-char pv) ?{)
10152 str-p (equal (string-to-char pv) ?\")
10153 time-p (save-match-data
10154 (string-match "^\"[[<].*[]>]\"$" pv))
10155 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10156 (if time-p (setq pv (org-matcher-time pv)))
10157 (setq po (org-op-to-function po (if time-p 'time str-p)))
10158 (cond
10159 ((equal pn "CATEGORY")
10160 (setq gv '(get-text-property (point) 'org-category)))
10161 ((equal pn "TODO")
10162 (setq gv 'todo))
10164 (setq gv `(org-cached-entry-get nil ,pn))))
10165 (if re-p
10166 (if (eq po 'org<>)
10167 `(not (string-match ,pv (or ,gv "")))
10168 `(string-match ,pv (or ,gv "")))
10169 (if str-p
10170 `(,po (or ,gv "") ,pv)
10171 `(,po (string-to-number (or ,gv ""))
10172 ,(string-to-number pv) ))))
10173 (t `(member ,tag tags-list)))
10174 mm (if minus (list 'not mm) mm)
10175 term rest)
10176 (push mm tagsmatcher))
10177 (push (if (> (length tagsmatcher) 1)
10178 (cons 'and tagsmatcher)
10179 (car tagsmatcher))
10180 orlist)
10181 (setq tagsmatcher nil))
10182 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10183 (setq tagsmatcher
10184 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10185 ;; Make the todo matcher
10186 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10187 (setq todomatcher t)
10188 (setq orterms (org-split-string todomatch "|") orlist nil)
10189 (while (setq term (pop orterms))
10190 (while (string-match re term)
10191 (setq minus (and (match-end 1)
10192 (equal (match-string 1 term) "-"))
10193 kwd (match-string 2 term)
10194 re-p (equal (string-to-char kwd) ?{)
10195 term (substring term (match-end 0))
10196 mm (if re-p
10197 `(string-match ,(substring kwd 1 -1) todo)
10198 (list 'equal 'todo kwd))
10199 mm (if minus (list 'not mm) mm))
10200 (push mm todomatcher))
10201 (push (if (> (length todomatcher) 1)
10202 (cons 'and todomatcher)
10203 (car todomatcher))
10204 orlist)
10205 (setq todomatcher nil))
10206 (setq todomatcher (if (> (length orlist) 1)
10207 (cons 'or orlist) (car orlist))))
10209 ;; Return the string and lisp forms of the matcher
10210 (setq matcher (if todomatcher
10211 (list 'and tagsmatcher todomatcher)
10212 tagsmatcher))
10213 (cons match0 matcher)))
10215 (defun org-op-to-function (op &optional stringp)
10216 "Turn an operator into the appropriate function."
10217 (setq op
10218 (cond
10219 ((equal op "<" ) '(< string< org-time<))
10220 ((equal op ">" ) '(> org-string> org-time>))
10221 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10222 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10223 ((member op '("=" "==")) '(= string= org-time=))
10224 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10225 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10227 (defun org<> (a b) (not (= a b)))
10228 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10229 (defun org-string>= (a b) (not (string< a b)))
10230 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10231 (defun org-string<> (a b) (not (string= a b)))
10232 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10233 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10234 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10235 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10236 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10237 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10238 (defun org-2ft (s)
10239 "Convert S to a floating point time.
10240 If S is already a number, just return it. If it is a string, parse
10241 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10242 (cond
10243 ((numberp s) s)
10244 ((stringp s)
10245 (condition-case nil
10246 (float-time (apply 'encode-time (org-parse-time-string s)))
10247 (error 0.)))
10248 (t 0.)))
10250 (defun org-time-today ()
10251 "Time in seconds today at 0:00.
10252 Returns the float number of seconds since the beginning of the
10253 epoch to the beginning of today (00:00)."
10254 (float-time (apply 'encode-time
10255 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10257 (defun org-matcher-time (s)
10258 "Interpret a time comparison value."
10259 (save-match-data
10260 (cond
10261 ((string= s "<now>") (float-time))
10262 ((string= s "<today>") (org-time-today))
10263 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10264 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10265 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10266 (+ (org-time-today)
10267 (* (string-to-number (match-string 1 s))
10268 (cdr (assoc (match-string 2 s)
10269 '(("d" . 86400.0) ("w" . 604800.0)
10270 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10271 (t (org-2ft s)))))
10273 (defun org-match-any-p (re list)
10274 "Does re match any element of list?"
10275 (setq list (mapcar (lambda (x) (string-match re x)) list))
10276 (delq nil list))
10278 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10279 (defvar org-tags-overlay (org-make-overlay 1 1))
10280 (org-detach-overlay org-tags-overlay)
10282 (defun org-get-local-tags-at (&optional pos)
10283 "Get a list of tags defined in the current headline."
10284 (org-get-tags-at pos 'local))
10286 (defun org-get-local-tags ()
10287 "Get a list of tags defined in the current headline."
10288 (org-get-tags-at nil 'local))
10290 (defun org-get-tags-at (&optional pos local)
10291 "Get a list of all headline tags applicable at POS.
10292 POS defaults to point. If tags are inherited, the list contains
10293 the targets in the same sequence as the headlines appear, i.e.
10294 the tags of the current headline come last.
10295 When LOCAL is non-nil, only return tags from the current headline,
10296 ignore inherited ones."
10297 (interactive)
10298 (if (and org-trust-scanner-tags
10299 (or (not pos) (equal pos (point)))
10300 (not local))
10301 org-scanner-tags
10302 (let (tags ltags lastpos parent)
10303 (save-excursion
10304 (save-restriction
10305 (widen)
10306 (goto-char (or pos (point)))
10307 (save-match-data
10308 (catch 'done
10309 (condition-case nil
10310 (progn
10311 (org-back-to-heading t)
10312 (while (not (equal lastpos (point)))
10313 (setq lastpos (point))
10314 (when (looking-at
10315 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10316 (setq ltags (org-split-string
10317 (org-match-string-no-properties 1) ":"))
10318 (when parent
10319 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10320 (setq tags (append
10321 (if parent
10322 (org-remove-uniherited-tags ltags)
10323 ltags)
10324 tags)))
10325 (or org-use-tag-inheritance (throw 'done t))
10326 (if local (throw 'done t))
10327 (org-up-heading-all 1)
10328 (setq parent t)))
10329 (error nil)))))
10330 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10332 (defun org-add-prop-inherited (s)
10333 (add-text-properties 0 (length s) '(inherited t) s)
10336 (defun org-toggle-tag (tag &optional onoff)
10337 "Toggle the tag TAG for the current line.
10338 If ONOFF is `on' or `off', don't toggle but set to this state."
10339 (let (res current)
10340 (save-excursion
10341 (org-back-to-heading t)
10342 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10343 (point-at-eol) t)
10344 (progn
10345 (setq current (match-string 1))
10346 (replace-match ""))
10347 (setq current ""))
10348 (setq current (nreverse (org-split-string current ":")))
10349 (cond
10350 ((eq onoff 'on)
10351 (setq res t)
10352 (or (member tag current) (push tag current)))
10353 ((eq onoff 'off)
10354 (or (not (member tag current)) (setq current (delete tag current))))
10355 (t (if (member tag current)
10356 (setq current (delete tag current))
10357 (setq res t)
10358 (push tag current))))
10359 (end-of-line 1)
10360 (if current
10361 (progn
10362 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10363 (org-set-tags nil t))
10364 (delete-horizontal-space))
10365 (run-hooks 'org-after-tags-change-hook))
10366 res))
10368 (defun org-align-tags-here (to-col)
10369 ;; Assumes that this is a headline
10370 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10371 (beginning-of-line 1)
10372 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10373 (< pos (match-beginning 2)))
10374 (progn
10375 (setq tags-l (- (match-end 2) (match-beginning 2)))
10376 (goto-char (match-beginning 1))
10377 (insert " ")
10378 (delete-region (point) (1+ (match-beginning 2)))
10379 (setq ncol (max (1+ (current-column))
10380 (1+ col)
10381 (if (> to-col 0)
10382 to-col
10383 (- (abs to-col) tags-l))))
10384 (setq p (point))
10385 (insert (make-string (- ncol (current-column)) ?\ ))
10386 (setq ncol (current-column))
10387 (when indent-tabs-mode (tabify p (point-at-eol)))
10388 (org-move-to-column (min ncol col) t))
10389 (goto-char pos))))
10391 (defun org-set-tags-command (&optional arg just-align)
10392 "Call the set-tags command for the current entry."
10393 (interactive "P")
10394 (if (org-on-heading-p)
10395 (org-set-tags arg just-align)
10396 (save-excursion
10397 (org-back-to-heading t)
10398 (org-set-tags arg just-align))))
10400 (defun org-set-tags (&optional arg just-align)
10401 "Set the tags for the current headline.
10402 With prefix ARG, realign all tags in headings in the current buffer."
10403 (interactive "P")
10404 (let* ((re (concat "^" outline-regexp))
10405 (current (org-get-tags-string))
10406 (col (current-column))
10407 (org-setting-tags t)
10408 table current-tags inherited-tags ; computed below when needed
10409 tags p0 c0 c1 rpl)
10410 (if arg
10411 (save-excursion
10412 (goto-char (point-min))
10413 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10414 (while (re-search-forward re nil t)
10415 (org-set-tags nil t)
10416 (end-of-line 1)))
10417 (message "All tags realigned to column %d" org-tags-column))
10418 (if just-align
10419 (setq tags current)
10420 ;; Get a new set of tags from the user
10421 (save-excursion
10422 (setq table (append org-tag-persistent-alist
10423 (or org-tag-alist (org-get-buffer-tags)))
10424 org-last-tags-completion-table table
10425 current-tags (org-split-string current ":")
10426 inherited-tags (nreverse
10427 (nthcdr (length current-tags)
10428 (nreverse (org-get-tags-at))))
10429 tags
10430 (if (or (eq t org-use-fast-tag-selection)
10431 (and org-use-fast-tag-selection
10432 (delq nil (mapcar 'cdr table))))
10433 (org-fast-tag-selection
10434 current-tags inherited-tags table
10435 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10436 (let ((org-add-colon-after-tag-completion t))
10437 (org-trim
10438 (org-without-partial-completion
10439 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10440 nil nil current 'org-tags-history)))))))
10441 (while (string-match "[-+&]+" tags)
10442 ;; No boolean logic, just a list
10443 (setq tags (replace-match ":" t t tags))))
10445 (if (string-match "\\`[\t ]*\\'" tags)
10446 (setq tags "")
10447 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10448 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10450 ;; Insert new tags at the correct column
10451 (beginning-of-line 1)
10452 (cond
10453 ((and (equal current "") (equal tags "")))
10454 ((re-search-forward
10455 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10456 (point-at-eol) t)
10457 (if (equal tags "")
10458 (setq rpl "")
10459 (goto-char (match-beginning 0))
10460 (setq c0 (current-column) p0 (point)
10461 c1 (max (1+ c0) (if (> org-tags-column 0)
10462 org-tags-column
10463 (- (- org-tags-column) (length tags))))
10464 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10465 (replace-match rpl t t)
10466 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10467 tags)
10468 (t (error "Tags alignment failed")))
10469 (org-move-to-column col)
10470 (unless just-align
10471 (run-hooks 'org-after-tags-change-hook)))))
10473 (defun org-change-tag-in-region (beg end tag off)
10474 "Add or remove TAG for each entry in the region.
10475 This works in the agenda, and also in an org-mode buffer."
10476 (interactive
10477 (list (region-beginning) (region-end)
10478 (let ((org-last-tags-completion-table
10479 (if (org-mode-p)
10480 (org-get-buffer-tags)
10481 (org-global-tags-completion-table))))
10482 (org-ido-completing-read
10483 "Tag: " 'org-tags-completion-function nil nil nil
10484 'org-tags-history))
10485 (progn
10486 (message "[s]et or [r]emove? ")
10487 (equal (read-char-exclusive) ?r))))
10488 (if (fboundp 'deactivate-mark) (deactivate-mark))
10489 (let ((agendap (equal major-mode 'org-agenda-mode))
10490 l1 l2 m buf pos newhead (cnt 0))
10491 (goto-char end)
10492 (setq l2 (1- (org-current-line)))
10493 (goto-char beg)
10494 (setq l1 (org-current-line))
10495 (loop for l from l1 to l2 do
10496 (goto-line l)
10497 (setq m (get-text-property (point) 'org-hd-marker))
10498 (when (or (and (org-mode-p) (org-on-heading-p))
10499 (and agendap m))
10500 (setq buf (if agendap (marker-buffer m) (current-buffer))
10501 pos (if agendap m (point)))
10502 (with-current-buffer buf
10503 (save-excursion
10504 (save-restriction
10505 (goto-char pos)
10506 (setq cnt (1+ cnt))
10507 (org-toggle-tag tag (if off 'off 'on))
10508 (setq newhead (org-get-heading)))))
10509 (and agendap (org-agenda-change-all-lines newhead m))))
10510 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10512 (defun org-tags-completion-function (string predicate &optional flag)
10513 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10514 (confirm (lambda (x) (stringp (car x)))))
10515 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10516 (setq s1 (match-string 1 string)
10517 s2 (match-string 2 string))
10518 (setq s1 "" s2 string))
10519 (cond
10520 ((eq flag nil)
10521 ;; try completion
10522 (setq rtn (try-completion s2 ctable confirm))
10523 (if (stringp rtn)
10524 (setq rtn
10525 (concat s1 s2 (substring rtn (length s2))
10526 (if (and org-add-colon-after-tag-completion
10527 (assoc rtn ctable))
10528 ":" ""))))
10529 rtn)
10530 ((eq flag t)
10531 ;; all-completions
10532 (all-completions s2 ctable confirm)
10534 ((eq flag 'lambda)
10535 ;; exact match?
10536 (assoc s2 ctable)))
10539 (defun org-fast-tag-insert (kwd tags face &optional end)
10540 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10541 (insert (format "%-12s" (concat kwd ":"))
10542 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10543 (or end "")))
10545 (defun org-fast-tag-show-exit (flag)
10546 (save-excursion
10547 (goto-line 3)
10548 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10549 (replace-match ""))
10550 (when flag
10551 (end-of-line 1)
10552 (org-move-to-column (- (window-width) 19) t)
10553 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10555 (defun org-set-current-tags-overlay (current prefix)
10556 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10557 (if (featurep 'xemacs)
10558 (org-overlay-display org-tags-overlay (concat prefix s)
10559 'secondary-selection)
10560 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10561 (org-overlay-display org-tags-overlay (concat prefix s)))))
10563 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10564 "Fast tag selection with single keys.
10565 CURRENT is the current list of tags in the headline, INHERITED is the
10566 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10567 possibly with grouping information. TODO-TABLE is a similar table with
10568 TODO keywords, should these have keys assigned to them.
10569 If the keys are nil, a-z are automatically assigned.
10570 Returns the new tags string, or nil to not change the current settings."
10571 (let* ((fulltable (append table todo-table))
10572 (maxlen (apply 'max (mapcar
10573 (lambda (x)
10574 (if (stringp (car x)) (string-width (car x)) 0))
10575 fulltable)))
10576 (buf (current-buffer))
10577 (expert (eq org-fast-tag-selection-single-key 'expert))
10578 (buffer-tags nil)
10579 (fwidth (+ maxlen 3 1 3))
10580 (ncol (/ (- (window-width) 4) fwidth))
10581 (i-face 'org-done)
10582 (c-face 'org-todo)
10583 tg cnt e c char c1 c2 ntable tbl rtn
10584 ov-start ov-end ov-prefix
10585 (exit-after-next org-fast-tag-selection-single-key)
10586 (done-keywords org-done-keywords)
10587 groups ingroup)
10588 (save-excursion
10589 (beginning-of-line 1)
10590 (if (looking-at
10591 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10592 (setq ov-start (match-beginning 1)
10593 ov-end (match-end 1)
10594 ov-prefix "")
10595 (setq ov-start (1- (point-at-eol))
10596 ov-end (1+ ov-start))
10597 (skip-chars-forward "^\n\r")
10598 (setq ov-prefix
10599 (concat
10600 (buffer-substring (1- (point)) (point))
10601 (if (> (current-column) org-tags-column)
10603 (make-string (- org-tags-column (current-column)) ?\ ))))))
10604 (org-move-overlay org-tags-overlay ov-start ov-end)
10605 (save-window-excursion
10606 (if expert
10607 (set-buffer (get-buffer-create " *Org tags*"))
10608 (delete-other-windows)
10609 (split-window-vertically)
10610 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10611 (erase-buffer)
10612 (org-set-local 'org-done-keywords done-keywords)
10613 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10614 (org-fast-tag-insert "Current" current c-face "\n\n")
10615 (org-fast-tag-show-exit exit-after-next)
10616 (org-set-current-tags-overlay current ov-prefix)
10617 (setq tbl fulltable char ?a cnt 0)
10618 (while (setq e (pop tbl))
10619 (cond
10620 ((equal e '(:startgroup))
10621 (push '() groups) (setq ingroup t)
10622 (when (not (= cnt 0))
10623 (setq cnt 0)
10624 (insert "\n"))
10625 (insert "{ "))
10626 ((equal e '(:endgroup))
10627 (setq ingroup nil cnt 0)
10628 (insert "}\n"))
10629 ((equal e '(:newline))
10630 (when (not (= cnt 0))
10631 (setq cnt 0)
10632 (insert "\n")
10633 (setq e (car tbl))
10634 (while (equal (car tbl) '(:newline))
10635 (insert "\n")
10636 (setq tbl (cdr tbl)))))
10638 (setq tg (car e) c2 nil)
10639 (if (cdr e)
10640 (setq c (cdr e))
10641 ;; automatically assign a character.
10642 (setq c1 (string-to-char
10643 (downcase (substring
10644 tg (if (= (string-to-char tg) ?@) 1 0)))))
10645 (if (or (rassoc c1 ntable) (rassoc c1 table))
10646 (while (or (rassoc char ntable) (rassoc char table))
10647 (setq char (1+ char)))
10648 (setq c2 c1))
10649 (setq c (or c2 char)))
10650 (if ingroup (push tg (car groups)))
10651 (setq tg (org-add-props tg nil 'face
10652 (cond
10653 ((not (assoc tg table))
10654 (org-get-todo-face tg))
10655 ((member tg current) c-face)
10656 ((member tg inherited) i-face)
10657 (t nil))))
10658 (if (and (= cnt 0) (not ingroup)) (insert " "))
10659 (insert "[" c "] " tg (make-string
10660 (- fwidth 4 (length tg)) ?\ ))
10661 (push (cons tg c) ntable)
10662 (when (= (setq cnt (1+ cnt)) ncol)
10663 (insert "\n")
10664 (if ingroup (insert " "))
10665 (setq cnt 0)))))
10666 (setq ntable (nreverse ntable))
10667 (insert "\n")
10668 (goto-char (point-min))
10669 (if (not expert) (org-fit-window-to-buffer))
10670 (setq rtn
10671 (catch 'exit
10672 (while t
10673 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10674 (if groups " [!] no groups" " [!]groups")
10675 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10676 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10677 (cond
10678 ((= c ?\r) (throw 'exit t))
10679 ((= c ?!)
10680 (setq groups (not groups))
10681 (goto-char (point-min))
10682 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10683 ((= c ?\C-c)
10684 (if (not expert)
10685 (org-fast-tag-show-exit
10686 (setq exit-after-next (not exit-after-next)))
10687 (setq expert nil)
10688 (delete-other-windows)
10689 (split-window-vertically)
10690 (org-switch-to-buffer-other-window " *Org tags*")
10691 (org-fit-window-to-buffer)))
10692 ((or (= c ?\C-g)
10693 (and (= c ?q) (not (rassoc c ntable))))
10694 (org-detach-overlay org-tags-overlay)
10695 (setq quit-flag t))
10696 ((= c ?\ )
10697 (setq current nil)
10698 (if exit-after-next (setq exit-after-next 'now)))
10699 ((= c ?\t)
10700 (condition-case nil
10701 (setq tg (org-ido-completing-read
10702 "Tag: "
10703 (or buffer-tags
10704 (with-current-buffer buf
10705 (org-get-buffer-tags)))))
10706 (quit (setq tg "")))
10707 (when (string-match "\\S-" tg)
10708 (add-to-list 'buffer-tags (list tg))
10709 (if (member tg current)
10710 (setq current (delete tg current))
10711 (push tg current)))
10712 (if exit-after-next (setq exit-after-next 'now)))
10713 ((setq e (rassoc c todo-table) tg (car e))
10714 (with-current-buffer buf
10715 (save-excursion (org-todo tg)))
10716 (if exit-after-next (setq exit-after-next 'now)))
10717 ((setq e (rassoc c ntable) tg (car e))
10718 (if (member tg current)
10719 (setq current (delete tg current))
10720 (loop for g in groups do
10721 (if (member tg g)
10722 (mapc (lambda (x)
10723 (setq current (delete x current)))
10724 g)))
10725 (push tg current))
10726 (if exit-after-next (setq exit-after-next 'now))))
10728 ;; Create a sorted list
10729 (setq current
10730 (sort current
10731 (lambda (a b)
10732 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10733 (if (eq exit-after-next 'now) (throw 'exit t))
10734 (goto-char (point-min))
10735 (beginning-of-line 2)
10736 (delete-region (point) (point-at-eol))
10737 (org-fast-tag-insert "Current" current c-face)
10738 (org-set-current-tags-overlay current ov-prefix)
10739 (while (re-search-forward
10740 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10741 (setq tg (match-string 1))
10742 (add-text-properties
10743 (match-beginning 1) (match-end 1)
10744 (list 'face
10745 (cond
10746 ((member tg current) c-face)
10747 ((member tg inherited) i-face)
10748 (t (get-text-property (match-beginning 1) 'face))))))
10749 (goto-char (point-min)))))
10750 (org-detach-overlay org-tags-overlay)
10751 (if rtn
10752 (mapconcat 'identity current ":")
10753 nil))))
10755 (defun org-get-tags-string ()
10756 "Get the TAGS string in the current headline."
10757 (unless (org-on-heading-p t)
10758 (error "Not on a heading"))
10759 (save-excursion
10760 (beginning-of-line 1)
10761 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10762 (org-match-string-no-properties 1)
10763 "")))
10765 (defun org-get-tags ()
10766 "Get the list of tags specified in the current headline."
10767 (org-split-string (org-get-tags-string) ":"))
10769 (defun org-get-buffer-tags ()
10770 "Get a table of all tags used in the buffer, for completion."
10771 (let (tags)
10772 (save-excursion
10773 (goto-char (point-min))
10774 (while (re-search-forward
10775 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10776 (when (equal (char-after (point-at-bol 0)) ?*)
10777 (mapc (lambda (x) (add-to-list 'tags x))
10778 (org-split-string (org-match-string-no-properties 1) ":")))))
10779 (mapcar 'list tags)))
10781 ;;;; The mapping API
10783 ;;;###autoload
10784 (defun org-map-entries (func &optional match scope &rest skip)
10785 "Call FUNC at each headline selected by MATCH in SCOPE.
10787 FUNC is a function or a lisp form. The function will be called without
10788 arguments, with the cursor positioned at the beginning of the headline.
10789 The return values of all calls to the function will be collected and
10790 returned as a list.
10792 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10793 Only headlines that are matched by this query will be considered during
10794 the iteration. When MATCH is nil or t, all headlines will be
10795 visited by the iteration.
10797 SCOPE determines the scope of this command. It can be any of:
10799 nil The current buffer, respecting the restriction if any
10800 tree The subtree started with the entry at point
10801 file The current buffer, without restriction
10802 file-with-archives
10803 The current buffer, and any archives associated with it
10804 agenda All agenda files
10805 agenda-with-archives
10806 All agenda files with any archive files associated with them
10807 \(file1 file2 ...)
10808 If this is a list, all files in the list will be scanned
10810 The remaining args are treated as settings for the skipping facilities of
10811 the scanner. The following items can be given here:
10813 archive skip trees with the archive tag.
10814 comment skip trees with the COMMENT keyword
10815 function or Emacs Lisp form:
10816 will be used as value for `org-agenda-skip-function', so whenever
10817 the the function returns t, FUNC will not be called for that
10818 entry and search will continue from the point where the
10819 function leaves it.
10821 If your function needs to retrieve the tags including inherited tags
10822 at the *current* entry, you can use the value of the variable
10823 `org-scanner-tags' which will be much faster than getting the value
10824 with `org-get-tags-at'. If your function gets properties with
10825 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
10826 to t around the call to `org-entry-properties' to get the same speedup.
10827 Note that if your function moves around to retrieve tags and properties at
10828 a *different* entry, you cannot use these techniques."
10829 (let* ((org-agenda-archives-mode nil) ; just to make sure
10830 (org-agenda-skip-archived-trees (memq 'archive skip))
10831 (org-agenda-skip-comment-trees (memq 'comment skip))
10832 (org-agenda-skip-function
10833 (car (org-delete-all '(comment archive) skip)))
10834 (org-tags-match-list-sublevels t)
10835 matcher file res
10836 org-todo-keywords-for-agenda
10837 org-done-keywords-for-agenda
10838 org-todo-keyword-alist-for-agenda
10839 org-tag-alist-for-agenda)
10841 (cond
10842 ((eq match t) (setq matcher t))
10843 ((eq match nil) (setq matcher t))
10844 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10846 (save-excursion
10847 (save-restriction
10848 (when (eq scope 'tree)
10849 (org-back-to-heading t)
10850 (org-narrow-to-subtree)
10851 (setq scope nil))
10853 (if (not scope)
10854 (progn
10855 (org-prepare-agenda-buffers
10856 (list (buffer-file-name (current-buffer))))
10857 (setq res (org-scan-tags func matcher)))
10858 ;; Get the right scope
10859 (cond
10860 ((and scope (listp scope) (symbolp (car scope)))
10861 (setq scope (eval scope)))
10862 ((eq scope 'agenda)
10863 (setq scope (org-agenda-files t)))
10864 ((eq scope 'agenda-with-archives)
10865 (setq scope (org-agenda-files t))
10866 (setq scope (org-add-archive-files scope)))
10867 ((eq scope 'file)
10868 (setq scope (list (buffer-file-name))))
10869 ((eq scope 'file-with-archives)
10870 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10871 (org-prepare-agenda-buffers scope)
10872 (while (setq file (pop scope))
10873 (with-current-buffer (org-find-base-buffer-visiting file)
10874 (save-excursion
10875 (save-restriction
10876 (widen)
10877 (goto-char (point-min))
10878 (setq res (append res (org-scan-tags func matcher))))))))))
10879 res))
10881 ;;;; Properties
10883 ;;; Setting and retrieving properties
10885 (defconst org-special-properties
10886 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10887 "TIMESTAMP" "TIMESTAMP_IA")
10888 "The special properties valid in Org-mode.
10890 These are properties that are not defined in the property drawer,
10891 but in some other way.")
10893 (defconst org-default-properties
10894 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10895 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10896 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10897 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10898 "Some properties that are used by Org-mode for various purposes.
10899 Being in this list makes sure that they are offered for completion.")
10901 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10902 "Regular expression matching the first line of a property drawer.")
10904 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10905 "Regular expression matching the first line of a property drawer.")
10907 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10908 "Regular expression matching the first line of a property drawer.")
10910 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10911 "Regular expression matching the first line of a property drawer.")
10913 (defconst org-property-drawer-re
10914 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10915 org-property-end-re "\\)\n?")
10916 "Matches an entire property drawer.")
10918 (defconst org-clock-drawer-re
10919 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10920 org-property-end-re "\\)\n?")
10921 "Matches an entire clock drawer.")
10923 (defun org-property-action ()
10924 "Do an action on properties."
10925 (interactive)
10926 (let (c)
10927 (org-at-property-p)
10928 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10929 (setq c (read-char-exclusive))
10930 (cond
10931 ((equal c ?s)
10932 (call-interactively 'org-set-property))
10933 ((equal c ?d)
10934 (call-interactively 'org-delete-property))
10935 ((equal c ?D)
10936 (call-interactively 'org-delete-property-globally))
10937 ((equal c ?c)
10938 (call-interactively 'org-compute-property-at-point))
10939 (t (error "No such property action %c" c)))))
10941 (defun org-at-property-p ()
10942 "Is the cursor in a property line?"
10943 ;; FIXME: Does not check if we are actually in the drawer.
10944 ;; FIXME: also returns true on any drawers.....
10945 ;; This is used by C-c C-c for property action.
10946 (save-excursion
10947 (beginning-of-line 1)
10948 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10950 (defun org-get-property-block (&optional beg end force)
10951 "Return the (beg . end) range of the body of the property drawer.
10952 BEG and END can be beginning and end of subtree, if not given
10953 they will be found.
10954 If the drawer does not exist and FORCE is non-nil, create the drawer."
10955 (catch 'exit
10956 (save-excursion
10957 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10958 (end (or end (progn (outline-next-heading) (point)))))
10959 (goto-char beg)
10960 (if (re-search-forward org-property-start-re end t)
10961 (setq beg (1+ (match-end 0)))
10962 (if force
10963 (save-excursion
10964 (org-insert-property-drawer)
10965 (setq end (progn (outline-next-heading) (point))))
10966 (throw 'exit nil))
10967 (goto-char beg)
10968 (if (re-search-forward org-property-start-re end t)
10969 (setq beg (1+ (match-end 0)))))
10970 (if (re-search-forward org-property-end-re end t)
10971 (setq end (match-beginning 0))
10972 (or force (throw 'exit nil))
10973 (goto-char beg)
10974 (setq end beg)
10975 (org-indent-line-function)
10976 (insert ":END:\n"))
10977 (cons beg end)))))
10979 (defun org-entry-properties (&optional pom which)
10980 "Get all properties of the entry at point-or-marker POM.
10981 This includes the TODO keyword, the tags, time strings for deadline,
10982 scheduled, and clocking, and any additional properties defined in the
10983 entry. The return value is an alist, keys may occur multiple times
10984 if the property key was used several times.
10985 POM may also be nil, in which case the current entry is used.
10986 If WHICH is nil or `all', get all properties. If WHICH is
10987 `special' or `standard', only get that subclass."
10988 (setq which (or which 'all))
10989 (org-with-point-at pom
10990 (let ((clockstr (substring org-clock-string 0 -1))
10991 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10992 beg end range props sum-props key value string clocksum)
10993 (save-excursion
10994 (when (condition-case nil
10995 (and (org-mode-p) (org-back-to-heading t))
10996 (error nil))
10997 (setq beg (point))
10998 (setq sum-props (get-text-property (point) 'org-summaries))
10999 (setq clocksum (get-text-property (point) :org-clock-minutes))
11000 (outline-next-heading)
11001 (setq end (point))
11002 (when (memq which '(all special))
11003 ;; Get the special properties, like TODO and tags
11004 (goto-char beg)
11005 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11006 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11007 (when (looking-at org-priority-regexp)
11008 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11009 (when (and (setq value (org-get-tags-string))
11010 (string-match "\\S-" value))
11011 (push (cons "TAGS" value) props))
11012 (when (setq value (org-get-tags-at))
11013 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11014 props))
11015 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11016 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11017 string (if (equal key clockstr)
11018 (org-no-properties
11019 (org-trim
11020 (buffer-substring
11021 (match-beginning 3) (goto-char (point-at-eol)))))
11022 (substring (org-match-string-no-properties 3) 1 -1)))
11023 (unless key
11024 (if (= (char-after (match-beginning 3)) ?\[)
11025 (setq key "TIMESTAMP_IA")
11026 (setq key "TIMESTAMP")))
11027 (when (or (equal key clockstr) (not (assoc key props)))
11028 (push (cons key string) props)))
11032 (when (memq which '(all standard))
11033 ;; Get the standard properties, like :PROP: ...
11034 (setq range (org-get-property-block beg end))
11035 (when range
11036 (goto-char (car range))
11037 (while (re-search-forward
11038 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11039 (cdr range) t)
11040 (setq key (org-match-string-no-properties 1)
11041 value (org-trim (or (org-match-string-no-properties 2) "")))
11042 (unless (member key excluded)
11043 (push (cons key (or value "")) props)))))
11044 (if clocksum
11045 (push (cons "CLOCKSUM"
11046 (org-columns-number-to-string (/ (float clocksum) 60.)
11047 'add_times))
11048 props))
11049 (unless (assoc "CATEGORY" props)
11050 (setq value (or (org-get-category)
11051 (progn (org-refresh-category-properties)
11052 (org-get-category))))
11053 (push (cons "CATEGORY" value) props))
11054 (append sum-props (nreverse props)))))))
11056 (defun org-entry-get (pom property &optional inherit)
11057 "Get value of PROPERTY for entry at point-or-marker POM.
11058 If INHERIT is non-nil and the entry does not have the property,
11059 then also check higher levels of the hierarchy.
11060 If INHERIT is the symbol `selective', use inheritance only if the setting
11061 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11062 If the property is present but empty, the return value is the empty string.
11063 If the property is not present at all, nil is returned."
11064 (org-with-point-at pom
11065 (if (and inherit (if (eq inherit 'selective)
11066 (org-property-inherit-p property)
11068 (org-entry-get-with-inheritance property)
11069 (if (member property org-special-properties)
11070 ;; We need a special property. Use brute force, get all properties.
11071 (cdr (assoc property (org-entry-properties nil 'special)))
11072 (let ((range (org-get-property-block)))
11073 (if (and range
11074 (goto-char (car range))
11075 (re-search-forward
11076 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11077 (cdr range) t))
11078 ;; Found the property, return it.
11079 (if (match-end 1)
11080 (org-match-string-no-properties 1)
11081 "")))))))
11083 (defun org-property-or-variable-value (var &optional inherit)
11084 "Check if there is a property fixing the value of VAR.
11085 If yes, return this value. If not, return the current value of the variable."
11086 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11087 (if (and prop (stringp prop) (string-match "\\S-" prop))
11088 (read prop)
11089 (symbol-value var))))
11091 (defun org-entry-delete (pom property)
11092 "Delete the property PROPERTY from entry at point-or-marker POM."
11093 (org-with-point-at pom
11094 (if (member property org-special-properties)
11095 nil ; cannot delete these properties.
11096 (let ((range (org-get-property-block)))
11097 (if (and range
11098 (goto-char (car range))
11099 (re-search-forward
11100 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11101 (cdr range) t))
11102 (progn
11103 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11105 nil)))))
11107 ;; Multi-values properties are properties that contain multiple values
11108 ;; These values are assumed to be single words, separated by whitespace.
11109 (defun org-entry-add-to-multivalued-property (pom property value)
11110 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11111 (let* ((old (org-entry-get pom property))
11112 (values (and old (org-split-string old "[ \t]"))))
11113 (setq value (org-entry-protect-space value))
11114 (unless (member value values)
11115 (setq values (cons value values))
11116 (org-entry-put pom property
11117 (mapconcat 'identity values " ")))))
11119 (defun org-entry-remove-from-multivalued-property (pom property value)
11120 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11121 (let* ((old (org-entry-get pom property))
11122 (values (and old (org-split-string old "[ \t]"))))
11123 (setq value (org-entry-protect-space value))
11124 (when (member value values)
11125 (setq values (delete value values))
11126 (org-entry-put pom property
11127 (mapconcat 'identity values " ")))))
11129 (defun org-entry-member-in-multivalued-property (pom property value)
11130 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11131 (let* ((old (org-entry-get pom property))
11132 (values (and old (org-split-string old "[ \t]"))))
11133 (setq value (org-entry-protect-space value))
11134 (member value values)))
11136 (defun org-entry-get-multivalued-property (pom property)
11137 "Return a list of values in a multivalued property."
11138 (let* ((value (org-entry-get pom property))
11139 (values (and value (org-split-string value "[ \t]"))))
11140 (mapcar 'org-entry-restore-space values)))
11142 (defun org-entry-put-multivalued-property (pom property &rest values)
11143 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11144 VALUES should be a list of strings. Spaces will be protected."
11145 (org-entry-put pom property
11146 (mapconcat 'org-entry-protect-space values " "))
11147 (let* ((value (org-entry-get pom property))
11148 (values (and value (org-split-string value "[ \t]"))))
11149 (mapcar 'org-entry-restore-space values)))
11151 (defun org-entry-protect-space (s)
11152 "Protect spaces and newline in string S."
11153 (while (string-match " " s)
11154 (setq s (replace-match "%20" t t s)))
11155 (while (string-match "\n" s)
11156 (setq s (replace-match "%0A" t t s)))
11159 (defun org-entry-restore-space (s)
11160 "Restore spaces and newline in string S."
11161 (while (string-match "%20" s)
11162 (setq s (replace-match " " t t s)))
11163 (while (string-match "%0A" s)
11164 (setq s (replace-match "\n" t t s)))
11167 (defvar org-entry-property-inherited-from (make-marker)
11168 "Marker pointing to the entry from where a property was inherited.
11169 Each call to `org-entry-get-with-inheritance' will set this marker to the
11170 location of the entry where the inheritance search matched. If there was
11171 no match, the marker will point nowhere.
11172 Note that also `org-entry-get' calls this function, if the INHERIT flag
11173 is set.")
11175 (defun org-entry-get-with-inheritance (property)
11176 "Get entry property, and search higher levels if not present."
11177 (move-marker org-entry-property-inherited-from nil)
11178 (let (tmp)
11179 (save-excursion
11180 (save-restriction
11181 (widen)
11182 (catch 'ex
11183 (while t
11184 (when (setq tmp (org-entry-get nil property))
11185 (org-back-to-heading t)
11186 (move-marker org-entry-property-inherited-from (point))
11187 (throw 'ex tmp))
11188 (or (org-up-heading-safe) (throw 'ex nil)))))
11189 (or tmp
11190 (cdr (assoc property org-file-properties))
11191 (cdr (assoc property org-global-properties))
11192 (cdr (assoc property org-global-properties-fixed))))))
11194 (defun org-entry-put (pom property value)
11195 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11196 (org-with-point-at pom
11197 (org-back-to-heading t)
11198 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11199 range)
11200 (cond
11201 ((equal property "TODO")
11202 (when (and (stringp value) (string-match "\\S-" value)
11203 (not (member value org-todo-keywords-1)))
11204 (error "\"%s\" is not a valid TODO state" value))
11205 (if (or (not value)
11206 (not (string-match "\\S-" value)))
11207 (setq value 'none))
11208 (org-todo value)
11209 (org-set-tags nil 'align))
11210 ((equal property "PRIORITY")
11211 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11212 (string-to-char value) ?\ ))
11213 (org-set-tags nil 'align))
11214 ((equal property "SCHEDULED")
11215 (if (re-search-forward org-scheduled-time-regexp end t)
11216 (cond
11217 ((eq value 'earlier) (org-timestamp-change -1 'day))
11218 ((eq value 'later) (org-timestamp-change 1 'day))
11219 (t (call-interactively 'org-schedule)))
11220 (call-interactively 'org-schedule)))
11221 ((equal property "DEADLINE")
11222 (if (re-search-forward org-deadline-time-regexp end t)
11223 (cond
11224 ((eq value 'earlier) (org-timestamp-change -1 'day))
11225 ((eq value 'later) (org-timestamp-change 1 'day))
11226 (t (call-interactively 'org-deadline)))
11227 (call-interactively 'org-deadline)))
11228 ((member property org-special-properties)
11229 (error "The %s property can not yet be set with `org-entry-put'"
11230 property))
11231 (t ; a non-special property
11232 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11233 (setq range (org-get-property-block beg end 'force))
11234 (goto-char (car range))
11235 (if (re-search-forward
11236 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11237 (progn
11238 (delete-region (match-beginning 1) (match-end 1))
11239 (goto-char (match-beginning 1)))
11240 (goto-char (cdr range))
11241 (insert "\n")
11242 (backward-char 1)
11243 (org-indent-line-function)
11244 (insert ":" property ":"))
11245 (and value (insert " " value))
11246 (org-indent-line-function)))))))
11248 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11249 "Get all property keys in the current buffer.
11250 With INCLUDE-SPECIALS, also list the special properties that reflect things
11251 like tags and TODO state.
11252 With INCLUDE-DEFAULTS, also include properties that has special meaning
11253 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11254 With INCLUDE-COLUMNS, also include property names given in COLUMN
11255 formats in the current buffer."
11256 (let (rtn range cfmt s p)
11257 (save-excursion
11258 (save-restriction
11259 (widen)
11260 (goto-char (point-min))
11261 (while (re-search-forward org-property-start-re nil t)
11262 (setq range (org-get-property-block))
11263 (goto-char (car range))
11264 (while (re-search-forward
11265 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11266 (cdr range) t)
11267 (add-to-list 'rtn (org-match-string-no-properties 1)))
11268 (outline-next-heading))))
11270 (when include-specials
11271 (setq rtn (append org-special-properties rtn)))
11273 (when include-defaults
11274 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11276 (when include-columns
11277 (save-excursion
11278 (save-restriction
11279 (widen)
11280 (goto-char (point-min))
11281 (while (re-search-forward
11282 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11283 nil t)
11284 (setq cfmt (match-string 2) s 0)
11285 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11286 cfmt s)
11287 (setq s (match-end 0)
11288 p (match-string 1 cfmt))
11289 (unless (or (equal p "ITEM")
11290 (member p org-special-properties))
11291 (add-to-list 'rtn (match-string 1 cfmt))))))))
11293 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11295 (defun org-property-values (key)
11296 "Return a list of all values of property KEY."
11297 (save-excursion
11298 (save-restriction
11299 (widen)
11300 (goto-char (point-min))
11301 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11302 values)
11303 (while (re-search-forward re nil t)
11304 (add-to-list 'values (org-trim (match-string 1))))
11305 (delete "" values)))))
11307 (defun org-insert-property-drawer ()
11308 "Insert a property drawer into the current entry."
11309 (interactive)
11310 (org-back-to-heading t)
11311 (looking-at outline-regexp)
11312 (let ((indent (- (match-end 0)(match-beginning 0)))
11313 (beg (point))
11314 (re (concat "^[ \t]*" org-keyword-time-regexp))
11315 end hiddenp)
11316 (outline-next-heading)
11317 (setq end (point))
11318 (goto-char beg)
11319 (while (re-search-forward re end t))
11320 (setq hiddenp (org-invisible-p))
11321 (end-of-line 1)
11322 (and (equal (char-after) ?\n) (forward-char 1))
11323 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11324 (if (member (match-string 1) '("CLOCK:" ":END:"))
11325 ;; just skip this line
11326 (beginning-of-line 2)
11327 ;; Drawer start, find the end
11328 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11329 (beginning-of-line 1)))
11330 (org-skip-over-state-notes)
11331 (skip-chars-backward " \t\n\r")
11332 (if (eq (char-before) ?*) (forward-char 1))
11333 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11334 (beginning-of-line 0)
11335 (org-indent-to-column indent)
11336 (beginning-of-line 2)
11337 (org-indent-to-column indent)
11338 (beginning-of-line 0)
11339 (if hiddenp
11340 (save-excursion
11341 (org-back-to-heading t)
11342 (hide-entry))
11343 (org-flag-drawer t))))
11345 (defun org-set-property (property value)
11346 "In the current entry, set PROPERTY to VALUE.
11347 When called interactively, this will prompt for a property name, offering
11348 completion on existing and default properties. And then it will prompt
11349 for a value, offering completion either on allowed values (via an inherited
11350 xxx_ALL property) or on existing values in other instances of this property
11351 in the current file."
11352 (interactive
11353 (let* ((completion-ignore-case t)
11354 (keys (org-buffer-property-keys nil t t))
11355 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11356 (prop (if (member prop0 keys)
11357 prop0
11358 (or (cdr (assoc (downcase prop0)
11359 (mapcar (lambda (x) (cons (downcase x) x))
11360 keys)))
11361 prop0)))
11362 (cur (org-entry-get nil prop))
11363 (allowed (org-property-get-allowed-values nil prop 'table))
11364 (existing (mapcar 'list (org-property-values prop)))
11365 (val (if allowed
11366 (org-completing-read "Value: " allowed nil 'req-match)
11367 (let (org-completion-use-ido)
11368 (org-completing-read
11369 (concat "Value" (if (and cur (string-match "\\S-" cur))
11370 (concat "[" cur "]") "")
11371 ": ")
11372 existing nil nil "" nil cur)))))
11373 (list prop (if (equal val "") cur val))))
11374 (unless (equal (org-entry-get nil property) value)
11375 (org-entry-put nil property value)))
11377 (defun org-delete-property (property)
11378 "In the current entry, delete PROPERTY."
11379 (interactive
11380 (let* ((completion-ignore-case t)
11381 (prop (org-ido-completing-read
11382 "Property: " (org-entry-properties nil 'standard))))
11383 (list prop)))
11384 (message "Property %s %s" property
11385 (if (org-entry-delete nil property)
11386 "deleted"
11387 "was not present in the entry")))
11389 (defun org-delete-property-globally (property)
11390 "Remove PROPERTY globally, from all entries."
11391 (interactive
11392 (let* ((completion-ignore-case t)
11393 (prop (org-ido-completing-read
11394 "Globally remove property: "
11395 (mapcar 'list (org-buffer-property-keys)))))
11396 (list prop)))
11397 (save-excursion
11398 (save-restriction
11399 (widen)
11400 (goto-char (point-min))
11401 (let ((cnt 0))
11402 (while (re-search-forward
11403 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11404 nil t)
11405 (setq cnt (1+ cnt))
11406 (replace-match ""))
11407 (message "Property \"%s\" removed from %d entries" property cnt)))))
11409 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11411 (defun org-compute-property-at-point ()
11412 "Compute the property at point.
11413 This looks for an enclosing column format, extracts the operator and
11414 then applies it to the property in the column format's scope."
11415 (interactive)
11416 (unless (org-at-property-p)
11417 (error "Not at a property"))
11418 (let ((prop (org-match-string-no-properties 2)))
11419 (org-columns-get-format-and-top-level)
11420 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11421 (error "No operator defined for property %s" prop))
11422 (org-columns-compute prop)))
11424 (defun org-property-get-allowed-values (pom property &optional table)
11425 "Get allowed values for the property PROPERTY.
11426 When TABLE is non-nil, return an alist that can directly be used for
11427 completion."
11428 (let (vals)
11429 (cond
11430 ((equal property "TODO")
11431 (setq vals (org-with-point-at pom
11432 (append org-todo-keywords-1 '("")))))
11433 ((equal property "PRIORITY")
11434 (let ((n org-lowest-priority))
11435 (while (>= n org-highest-priority)
11436 (push (char-to-string n) vals)
11437 (setq n (1- n)))))
11438 ((member property org-special-properties))
11440 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11442 (when (and vals (string-match "\\S-" vals))
11443 (setq vals (car (read-from-string (concat "(" vals ")"))))
11444 (setq vals (mapcar (lambda (x)
11445 (cond ((stringp x) x)
11446 ((numberp x) (number-to-string x))
11447 ((symbolp x) (symbol-name x))
11448 (t "???")))
11449 vals)))))
11450 (if table (mapcar 'list vals) vals)))
11452 (defun org-property-previous-allowed-value (&optional previous)
11453 "Switch to the next allowed value for this property."
11454 (interactive)
11455 (org-property-next-allowed-value t))
11457 (defun org-property-next-allowed-value (&optional previous)
11458 "Switch to the next allowed value for this property."
11459 (interactive)
11460 (unless (org-at-property-p)
11461 (error "Not at a property"))
11462 (let* ((key (match-string 2))
11463 (value (match-string 3))
11464 (allowed (or (org-property-get-allowed-values (point) key)
11465 (and (member value '("[ ]" "[-]" "[X]"))
11466 '("[ ]" "[X]"))))
11467 nval)
11468 (unless allowed
11469 (error "Allowed values for this property have not been defined"))
11470 (if previous (setq allowed (reverse allowed)))
11471 (if (member value allowed)
11472 (setq nval (car (cdr (member value allowed)))))
11473 (setq nval (or nval (car allowed)))
11474 (if (equal nval value)
11475 (error "Only one allowed value for this property"))
11476 (org-at-property-p)
11477 (replace-match (concat " :" key ": " nval) t t)
11478 (org-indent-line-function)
11479 (beginning-of-line 1)
11480 (skip-chars-forward " \t")))
11482 (defun org-find-entry-with-id (ident)
11483 "Locate the entry that contains the ID property with exact value IDENT.
11484 IDENT can be a string, a symbol or a number, this function will search for
11485 the string representation of it.
11486 Return the position where this entry starts, or nil if there is no such entry."
11487 (interactive "sID: ")
11488 (let ((id (cond
11489 ((stringp ident) ident)
11490 ((symbol-name ident) (symbol-name ident))
11491 ((numberp ident) (number-to-string ident))
11492 (t (error "IDENT %s must be a string, symbol or number" ident))))
11493 (case-fold-search nil))
11494 (save-excursion
11495 (save-restriction
11496 (widen)
11497 (goto-char (point-min))
11498 (when (re-search-forward
11499 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11500 nil t)
11501 (org-back-to-heading)
11502 (point))))))
11504 ;;;; Timestamps
11506 (defvar org-last-changed-timestamp nil)
11507 (defvar org-last-inserted-timestamp nil
11508 "The last time stamp inserted with `org-insert-time-stamp'.")
11509 (defvar org-time-was-given) ; dynamically scoped parameter
11510 (defvar org-end-time-was-given) ; dynamically scoped parameter
11511 (defvar org-ts-what) ; dynamically scoped parameter
11513 (defun org-time-stamp (arg &optional inactive)
11514 "Prompt for a date/time and insert a time stamp.
11515 If the user specifies a time like HH:MM, or if this command is called
11516 with a prefix argument, the time stamp will contain date and time.
11517 Otherwise, only the date will be included. All parts of a date not
11518 specified by the user will be filled in from the current date/time.
11519 So if you press just return without typing anything, the time stamp
11520 will represent the current date/time. If there is already a timestamp
11521 at the cursor, it will be modified."
11522 (interactive "P")
11523 (let* ((ts nil)
11524 (default-time
11525 ;; Default time is either today, or, when entering a range,
11526 ;; the range start.
11527 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11528 (save-excursion
11529 (re-search-backward
11530 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11531 (- (point) 20) t)))
11532 (apply 'encode-time (org-parse-time-string (match-string 1)))
11533 (current-time)))
11534 (default-input (and ts (org-get-compact-tod ts)))
11535 org-time-was-given org-end-time-was-given time)
11536 (cond
11537 ((and (org-at-timestamp-p t)
11538 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11539 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11540 (insert "--")
11541 (setq time (let ((this-command this-command))
11542 (org-read-date arg 'totime nil nil
11543 default-time default-input)))
11544 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11545 ((org-at-timestamp-p t)
11546 (setq time (let ((this-command this-command))
11547 (org-read-date arg 'totime nil nil default-time default-input)))
11548 (when (org-at-timestamp-p t) ; just to get the match data
11549 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11550 (replace-match "")
11551 (setq org-last-changed-timestamp
11552 (org-insert-time-stamp
11553 time (or org-time-was-given arg)
11554 inactive nil nil (list org-end-time-was-given))))
11555 (message "Timestamp updated"))
11557 (setq time (let ((this-command this-command))
11558 (org-read-date arg 'totime nil nil default-time default-input)))
11559 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11560 nil nil (list org-end-time-was-given))))))
11562 ;; FIXME: can we use this for something else, like computing time differences?
11563 (defun org-get-compact-tod (s)
11564 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11565 (let* ((t1 (match-string 1 s))
11566 (h1 (string-to-number (match-string 2 s)))
11567 (m1 (string-to-number (match-string 3 s)))
11568 (t2 (and (match-end 4) (match-string 5 s)))
11569 (h2 (and t2 (string-to-number (match-string 6 s))))
11570 (m2 (and t2 (string-to-number (match-string 7 s))))
11571 dh dm)
11572 (if (not t2)
11574 (setq dh (- h2 h1) dm (- m2 m1))
11575 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11576 (concat t1 "+" (number-to-string dh)
11577 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11579 (defun org-time-stamp-inactive (&optional arg)
11580 "Insert an inactive time stamp.
11581 An inactive time stamp is enclosed in square brackets instead of angle
11582 brackets. It is inactive in the sense that it does not trigger agenda entries,
11583 does not link to the calendar and cannot be changed with the S-cursor keys.
11584 So these are more for recording a certain time/date."
11585 (interactive "P")
11586 (org-time-stamp arg 'inactive))
11588 (defvar org-date-ovl (org-make-overlay 1 1))
11589 (org-overlay-put org-date-ovl 'face 'org-warning)
11590 (org-detach-overlay org-date-ovl)
11592 (defvar org-ans1) ; dynamically scoped parameter
11593 (defvar org-ans2) ; dynamically scoped parameter
11595 (defvar org-plain-time-of-day-regexp) ; defined below
11597 (defvar org-overriding-default-time nil) ; dynamically scoped
11598 (defvar org-read-date-overlay nil)
11599 (defvar org-dcst nil) ; dynamically scoped
11600 (defvar org-read-date-history nil)
11602 (defun org-read-date (&optional with-time to-time from-string prompt
11603 default-time default-input)
11604 "Read a date, possibly a time, and make things smooth for the user.
11605 The prompt will suggest to enter an ISO date, but you can also enter anything
11606 which will at least partially be understood by `parse-time-string'.
11607 Unrecognized parts of the date will default to the current day, month, year,
11608 hour and minute. If this command is called to replace a timestamp at point,
11609 of to enter the second timestamp of a range, the default time is taken from the
11610 existing stamp. For example,
11611 3-2-5 --> 2003-02-05
11612 feb 15 --> currentyear-02-15
11613 sep 12 9 --> 2009-09-12
11614 12:45 --> today 12:45
11615 22 sept 0:34 --> currentyear-09-22 0:34
11616 12 --> currentyear-currentmonth-12
11617 Fri --> nearest Friday (today or later)
11618 etc.
11620 Furthermore you can specify a relative date by giving, as the *first* thing
11621 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11622 change in days weeks, months, years.
11623 With a single plus or minus, the date is relative to today. With a double
11624 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11625 +4d --> four days from today
11626 +4 --> same as above
11627 +2w --> two weeks from today
11628 ++5 --> five days from default date
11630 The function understands only English month and weekday abbreviations,
11631 but this can be configured with the variables `parse-time-months' and
11632 `parse-time-weekdays'.
11634 While prompting, a calendar is popped up - you can also select the
11635 date with the mouse (button 1). The calendar shows a period of three
11636 months. To scroll it to other months, use the keys `>' and `<'.
11637 If you don't like the calendar, turn it off with
11638 \(setq org-read-date-popup-calendar nil)
11640 With optional argument TO-TIME, the date will immediately be converted
11641 to an internal time.
11642 With an optional argument WITH-TIME, the prompt will suggest to also
11643 insert a time. Note that when WITH-TIME is not set, you can still
11644 enter a time, and this function will inform the calling routine about
11645 this change. The calling routine may then choose to change the format
11646 used to insert the time stamp into the buffer to include the time.
11647 With optional argument FROM-STRING, read from this string instead from
11648 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11649 the time/date that is used for everything that is not specified by the
11650 user."
11651 (require 'parse-time)
11652 (let* ((org-time-stamp-rounding-minutes
11653 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11654 (org-dcst org-display-custom-times)
11655 (ct (org-current-time))
11656 (def (or org-overriding-default-time default-time ct))
11657 (defdecode (decode-time def))
11658 (dummy (progn
11659 (when (< (nth 2 defdecode) org-extend-today-until)
11660 (setcar (nthcdr 2 defdecode) -1)
11661 (setcar (nthcdr 1 defdecode) 59)
11662 (setq def (apply 'encode-time defdecode)
11663 defdecode (decode-time def)))))
11664 (calendar-move-hook nil)
11665 (calendar-view-diary-initially-flag nil)
11666 (view-diary-entries-initially nil)
11667 (calendar-view-holidays-initially-flag nil)
11668 (view-calendar-holidays-initially nil)
11669 (timestr (format-time-string
11670 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11671 (prompt (concat (if prompt (concat prompt " ") "")
11672 (format "Date+time [%s]: " timestr)))
11673 ans (org-ans0 "") org-ans1 org-ans2 final)
11675 (cond
11676 (from-string (setq ans from-string))
11677 (org-read-date-popup-calendar
11678 (save-excursion
11679 (save-window-excursion
11680 (calendar)
11681 (calendar-forward-day (- (time-to-days def)
11682 (calendar-absolute-from-gregorian
11683 (calendar-current-date))))
11684 (org-eval-in-calendar nil t)
11685 (let* ((old-map (current-local-map))
11686 (map (copy-keymap calendar-mode-map))
11687 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11688 (org-defkey map (kbd "RET") 'org-calendar-select)
11689 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11690 'org-calendar-select-mouse)
11691 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11692 'org-calendar-select-mouse)
11693 (org-defkey minibuffer-local-map [(meta shift left)]
11694 (lambda () (interactive)
11695 (org-eval-in-calendar '(calendar-backward-month 1))))
11696 (org-defkey minibuffer-local-map [(meta shift right)]
11697 (lambda () (interactive)
11698 (org-eval-in-calendar '(calendar-forward-month 1))))
11699 (org-defkey minibuffer-local-map [(meta shift up)]
11700 (lambda () (interactive)
11701 (org-eval-in-calendar '(calendar-backward-year 1))))
11702 (org-defkey minibuffer-local-map [(meta shift down)]
11703 (lambda () (interactive)
11704 (org-eval-in-calendar '(calendar-forward-year 1))))
11705 (org-defkey minibuffer-local-map [(shift up)]
11706 (lambda () (interactive)
11707 (org-eval-in-calendar '(calendar-backward-week 1))))
11708 (org-defkey minibuffer-local-map [(shift down)]
11709 (lambda () (interactive)
11710 (org-eval-in-calendar '(calendar-forward-week 1))))
11711 (org-defkey minibuffer-local-map [(shift left)]
11712 (lambda () (interactive)
11713 (org-eval-in-calendar '(calendar-backward-day 1))))
11714 (org-defkey minibuffer-local-map [(shift right)]
11715 (lambda () (interactive)
11716 (org-eval-in-calendar '(calendar-forward-day 1))))
11717 (org-defkey minibuffer-local-map ">"
11718 (lambda () (interactive)
11719 (org-eval-in-calendar '(scroll-calendar-left 1))))
11720 (org-defkey minibuffer-local-map "<"
11721 (lambda () (interactive)
11722 (org-eval-in-calendar '(scroll-calendar-right 1))))
11723 (run-hooks 'org-read-date-minibuffer-setup-hook)
11724 (unwind-protect
11725 (progn
11726 (use-local-map map)
11727 (add-hook 'post-command-hook 'org-read-date-display)
11728 (setq org-ans0 (read-string prompt default-input
11729 'org-read-date-history nil))
11730 ;; org-ans0: from prompt
11731 ;; org-ans1: from mouse click
11732 ;; org-ans2: from calendar motion
11733 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11734 (remove-hook 'post-command-hook 'org-read-date-display)
11735 (use-local-map old-map)
11736 (when org-read-date-overlay
11737 (org-delete-overlay org-read-date-overlay)
11738 (setq org-read-date-overlay nil)))))))
11740 (t ; Naked prompt only
11741 (unwind-protect
11742 (setq ans (read-string prompt default-input
11743 'org-read-date-history timestr))
11744 (when org-read-date-overlay
11745 (org-delete-overlay org-read-date-overlay)
11746 (setq org-read-date-overlay nil)))))
11748 (setq final (org-read-date-analyze ans def defdecode))
11750 (if to-time
11751 (apply 'encode-time final)
11752 (if (and (boundp 'org-time-was-given) org-time-was-given)
11753 (format "%04d-%02d-%02d %02d:%02d"
11754 (nth 5 final) (nth 4 final) (nth 3 final)
11755 (nth 2 final) (nth 1 final))
11756 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11757 (defvar def)
11758 (defvar defdecode)
11759 (defvar with-time)
11760 (defun org-read-date-display ()
11761 "Display the current date prompt interpretation in the minibuffer."
11762 (when org-read-date-display-live
11763 (when org-read-date-overlay
11764 (org-delete-overlay org-read-date-overlay))
11765 (let ((p (point)))
11766 (end-of-line 1)
11767 (while (not (equal (buffer-substring
11768 (max (point-min) (- (point) 4)) (point))
11769 " "))
11770 (insert " "))
11771 (goto-char p))
11772 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11773 " " (or org-ans1 org-ans2)))
11774 (org-end-time-was-given nil)
11775 (f (org-read-date-analyze ans def defdecode))
11776 (fmts (if org-dcst
11777 org-time-stamp-custom-formats
11778 org-time-stamp-formats))
11779 (fmt (if (or with-time
11780 (and (boundp 'org-time-was-given) org-time-was-given))
11781 (cdr fmts)
11782 (car fmts)))
11783 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11784 (when (and org-end-time-was-given
11785 (string-match org-plain-time-of-day-regexp txt))
11786 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11787 org-end-time-was-given
11788 (substring txt (match-end 0)))))
11789 (setq org-read-date-overlay
11790 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11791 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11793 (defun org-read-date-analyze (ans def defdecode)
11794 "Analyse the combined answer of the date prompt."
11795 ;; FIXME: cleanup and comment
11796 (let (delta deltan deltaw deltadef year month day
11797 hour minute second wday pm h2 m2 tl wday1
11798 iso-year iso-weekday iso-week iso-year iso-date)
11800 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11801 (setq ans "+0"))
11803 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11804 (setq ans (replace-match "" t t ans)
11805 deltan (car delta)
11806 deltaw (nth 1 delta)
11807 deltadef (nth 2 delta)))
11809 ;; Check if there is an iso week date in there
11810 ;; If yes, sore the info and postpone interpreting it until the rest
11811 ;; of the parsing is done
11812 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11813 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11814 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11815 iso-week (string-to-number (match-string 2 ans)))
11816 (setq ans (replace-match "" t t ans)))
11818 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11819 (when (string-match
11820 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11821 (setq year (if (match-end 2)
11822 (string-to-number (match-string 2 ans))
11823 (string-to-number (format-time-string "%Y")))
11824 month (string-to-number (match-string 3 ans))
11825 day (string-to-number (match-string 4 ans)))
11826 (if (< year 100) (setq year (+ 2000 year)))
11827 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11828 t nil ans)))
11829 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11830 ;; If there is a time with am/pm, and *no* time without it, we convert
11831 ;; so that matching will be successful.
11832 (loop for i from 1 to 2 do ; twice, for end time as well
11833 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11834 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11835 (setq hour (string-to-number (match-string 1 ans))
11836 minute (if (match-end 3)
11837 (string-to-number (match-string 3 ans))
11839 pm (equal ?p
11840 (string-to-char (downcase (match-string 4 ans)))))
11841 (if (and (= hour 12) (not pm))
11842 (setq hour 0)
11843 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11844 (setq ans (replace-match (format "%02d:%02d" hour minute)
11845 t t ans))))
11847 ;; Check if a time range is given as a duration
11848 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11849 (setq hour (string-to-number (match-string 1 ans))
11850 h2 (+ hour (string-to-number (match-string 3 ans)))
11851 minute (string-to-number (match-string 2 ans))
11852 m2 (+ minute (if (match-end 5) (string-to-number
11853 (match-string 5 ans))0)))
11854 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11855 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11856 t t ans)))
11858 ;; Check if there is a time range
11859 (when (boundp 'org-end-time-was-given)
11860 (setq org-time-was-given nil)
11861 (when (and (string-match org-plain-time-of-day-regexp ans)
11862 (match-end 8))
11863 (setq org-end-time-was-given (match-string 8 ans))
11864 (setq ans (concat (substring ans 0 (match-beginning 7))
11865 (substring ans (match-end 7))))))
11867 (setq tl (parse-time-string ans)
11868 day (or (nth 3 tl) (nth 3 defdecode))
11869 month (or (nth 4 tl)
11870 (if (and org-read-date-prefer-future
11871 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11872 (1+ (nth 4 defdecode))
11873 (nth 4 defdecode)))
11874 year (or (nth 5 tl)
11875 (if (and org-read-date-prefer-future
11876 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11877 (1+ (nth 5 defdecode))
11878 (nth 5 defdecode)))
11879 hour (or (nth 2 tl) (nth 2 defdecode))
11880 minute (or (nth 1 tl) (nth 1 defdecode))
11881 second (or (nth 0 tl) 0)
11882 wday (nth 6 tl))
11884 ;; Special date definitions below
11885 (cond
11886 (iso-week
11887 ;; There was an iso week
11888 (setq year (or iso-year year)
11889 day (or iso-weekday wday 1)
11890 wday nil ; to make sure that the trigger below does not match
11891 iso-date (calendar-gregorian-from-absolute
11892 (calendar-absolute-from-iso
11893 (list iso-week day year))))
11894 ; FIXME: Should we also push ISO weeks into the future?
11895 ; (when (and org-read-date-prefer-future
11896 ; (not iso-year)
11897 ; (< (calendar-absolute-from-gregorian iso-date)
11898 ; (time-to-days (current-time))))
11899 ; (setq year (1+ year)
11900 ; iso-date (calendar-gregorian-from-absolute
11901 ; (calendar-absolute-from-iso
11902 ; (list iso-week day year)))))
11903 (setq month (car iso-date)
11904 year (nth 2 iso-date)
11905 day (nth 1 iso-date)))
11906 (deltan
11907 (unless deltadef
11908 (let ((now (decode-time (current-time))))
11909 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11910 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11911 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11912 ((equal deltaw "m") (setq month (+ month deltan)))
11913 ((equal deltaw "y") (setq year (+ year deltan)))))
11914 ((and wday (not (nth 3 tl)))
11915 ;; Weekday was given, but no day, so pick that day in the week
11916 ;; on or after the derived date.
11917 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11918 (unless (equal wday wday1)
11919 (setq day (+ day (% (- wday wday1 -7) 7))))))
11920 (if (and (boundp 'org-time-was-given)
11921 (nth 2 tl))
11922 (setq org-time-was-given t))
11923 (if (< year 100) (setq year (+ 2000 year)))
11924 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11925 (list second minute hour day month year)))
11927 (defvar parse-time-weekdays)
11929 (defun org-read-date-get-relative (s today default)
11930 "Check string S for special relative date string.
11931 TODAY and DEFAULT are internal times, for today and for a default.
11932 Return shift list (N what def-flag)
11933 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11934 N is the number of WHATs to shift.
11935 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11936 the DEFAULT date rather than TODAY."
11937 (when (and
11938 (string-match
11939 (concat
11940 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11941 "\\([0-9]+\\)?"
11942 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11943 "\\([ \t]\\|$\\)") s)
11944 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11945 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11946 (string-to-char (substring (match-string 1 s) -1))
11947 ?+))
11948 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11949 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11950 (what (if (match-end 3) (match-string 3 s) "d"))
11951 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11952 (date (if rel default today))
11953 (wday (nth 6 (decode-time date)))
11954 delta)
11955 (if wday1
11956 (progn
11957 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11958 (if (= dir ?-) (setq delta (- delta 7)))
11959 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11960 (list delta "d" rel))
11961 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11963 (defun org-eval-in-calendar (form &optional keepdate)
11964 "Eval FORM in the calendar window and return to current window.
11965 Also, store the cursor date in variable org-ans2."
11966 (let ((sw (selected-window)))
11967 (select-window (get-buffer-window "*Calendar*"))
11968 (eval form)
11969 (when (and (not keepdate) (calendar-cursor-to-date))
11970 (let* ((date (calendar-cursor-to-date))
11971 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11972 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11973 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11974 (select-window sw)))
11976 (defun org-calendar-select ()
11977 "Return to `org-read-date' with the date currently selected.
11978 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11979 (interactive)
11980 (when (calendar-cursor-to-date)
11981 (let* ((date (calendar-cursor-to-date))
11982 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11983 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11984 (if (active-minibuffer-window) (exit-minibuffer))))
11986 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11987 "Insert a date stamp for the date given by the internal TIME.
11988 WITH-HM means, use the stamp format that includes the time of the day.
11989 INACTIVE means use square brackets instead of angular ones, so that the
11990 stamp will not contribute to the agenda.
11991 PRE and POST are optional strings to be inserted before and after the
11992 stamp.
11993 The command returns the inserted time stamp."
11994 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11995 stamp)
11996 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11997 (insert-before-markers (or pre ""))
11998 (insert-before-markers (setq stamp (format-time-string fmt time)))
11999 (when (listp extra)
12000 (setq extra (car extra))
12001 (if (and (stringp extra)
12002 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12003 (setq extra (format "-%02d:%02d"
12004 (string-to-number (match-string 1 extra))
12005 (string-to-number (match-string 2 extra))))
12006 (setq extra nil)))
12007 (when extra
12008 (backward-char 1)
12009 (insert-before-markers extra)
12010 (forward-char 1))
12011 (insert-before-markers (or post ""))
12012 (setq org-last-inserted-timestamp stamp)))
12014 (defun org-toggle-time-stamp-overlays ()
12015 "Toggle the use of custom time stamp formats."
12016 (interactive)
12017 (setq org-display-custom-times (not org-display-custom-times))
12018 (unless org-display-custom-times
12019 (let ((p (point-min)) (bmp (buffer-modified-p)))
12020 (while (setq p (next-single-property-change p 'display))
12021 (if (and (get-text-property p 'display)
12022 (eq (get-text-property p 'face) 'org-date))
12023 (remove-text-properties
12024 p (setq p (next-single-property-change p 'display))
12025 '(display t))))
12026 (set-buffer-modified-p bmp)))
12027 (if (featurep 'xemacs)
12028 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12029 (org-restart-font-lock)
12030 (setq org-table-may-need-update t)
12031 (if org-display-custom-times
12032 (message "Time stamps are overlayed with custom format")
12033 (message "Time stamp overlays removed")))
12035 (defun org-display-custom-time (beg end)
12036 "Overlay modified time stamp format over timestamp between BEG and END."
12037 (let* ((ts (buffer-substring beg end))
12038 t1 w1 with-hm tf time str w2 (off 0))
12039 (save-match-data
12040 (setq t1 (org-parse-time-string ts t))
12041 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12042 (setq off (- (match-end 0) (match-beginning 0)))))
12043 (setq end (- end off))
12044 (setq w1 (- end beg)
12045 with-hm (and (nth 1 t1) (nth 2 t1))
12046 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12047 time (org-fix-decoded-time t1)
12048 str (org-add-props
12049 (format-time-string
12050 (substring tf 1 -1) (apply 'encode-time time))
12051 nil 'mouse-face 'highlight)
12052 w2 (length str))
12053 (if (not (= w2 w1))
12054 (add-text-properties (1+ beg) (+ 2 beg)
12055 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12056 (if (featurep 'xemacs)
12057 (progn
12058 (put-text-property beg end 'invisible t)
12059 (put-text-property beg end 'end-glyph (make-glyph str)))
12060 (put-text-property beg end 'display str))))
12062 (defun org-translate-time (string)
12063 "Translate all timestamps in STRING to custom format.
12064 But do this only if the variable `org-display-custom-times' is set."
12065 (when org-display-custom-times
12066 (save-match-data
12067 (let* ((start 0)
12068 (re org-ts-regexp-both)
12069 t1 with-hm inactive tf time str beg end)
12070 (while (setq start (string-match re string start))
12071 (setq beg (match-beginning 0)
12072 end (match-end 0)
12073 t1 (save-match-data
12074 (org-parse-time-string (substring string beg end) t))
12075 with-hm (and (nth 1 t1) (nth 2 t1))
12076 inactive (equal (substring string beg (1+ beg)) "[")
12077 tf (funcall (if with-hm 'cdr 'car)
12078 org-time-stamp-custom-formats)
12079 time (org-fix-decoded-time t1)
12080 str (format-time-string
12081 (concat
12082 (if inactive "[" "<") (substring tf 1 -1)
12083 (if inactive "]" ">"))
12084 (apply 'encode-time time))
12085 string (replace-match str t t string)
12086 start (+ start (length str)))))))
12087 string)
12089 (defun org-fix-decoded-time (time)
12090 "Set 0 instead of nil for the first 6 elements of time.
12091 Don't touch the rest."
12092 (let ((n 0))
12093 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12095 (defun org-days-to-time (timestamp-string)
12096 "Difference between TIMESTAMP-STRING and now in days."
12097 (- (time-to-days (org-time-string-to-time timestamp-string))
12098 (time-to-days (current-time))))
12100 (defun org-deadline-close (timestamp-string &optional ndays)
12101 "Is the time in TIMESTAMP-STRING close to the current date?"
12102 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12103 (and (< (org-days-to-time timestamp-string) ndays)
12104 (not (org-entry-is-done-p))))
12106 (defun org-get-wdays (ts)
12107 "Get the deadline lead time appropriate for timestring TS."
12108 (cond
12109 ((<= org-deadline-warning-days 0)
12110 ;; 0 or negative, enforce this value no matter what
12111 (- org-deadline-warning-days))
12112 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12113 ;; lead time is specified.
12114 (floor (* (string-to-number (match-string 1 ts))
12115 (cdr (assoc (match-string 2 ts)
12116 '(("d" . 1) ("w" . 7)
12117 ("m" . 30.4) ("y" . 365.25)))))))
12118 ;; go for the default.
12119 (t org-deadline-warning-days)))
12121 (defun org-calendar-select-mouse (ev)
12122 "Return to `org-read-date' with the date currently selected.
12123 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12124 (interactive "e")
12125 (mouse-set-point ev)
12126 (when (calendar-cursor-to-date)
12127 (let* ((date (calendar-cursor-to-date))
12128 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12129 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12130 (if (active-minibuffer-window) (exit-minibuffer))))
12132 (defun org-check-deadlines (ndays)
12133 "Check if there are any deadlines due or past due.
12134 A deadline is considered due if it happens within `org-deadline-warning-days'
12135 days from today's date. If the deadline appears in an entry marked DONE,
12136 it is not shown. The prefix arg NDAYS can be used to test that many
12137 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12138 (interactive "P")
12139 (let* ((org-warn-days
12140 (cond
12141 ((equal ndays '(4)) 100000)
12142 (ndays (prefix-numeric-value ndays))
12143 (t (abs org-deadline-warning-days))))
12144 (case-fold-search nil)
12145 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12146 (callback
12147 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12149 (message "%d deadlines past-due or due within %d days"
12150 (org-occur regexp nil callback)
12151 org-warn-days)))
12153 (defun org-check-before-date (date)
12154 "Check if there are deadlines or scheduled entries before DATE."
12155 (interactive (list (org-read-date)))
12156 (let ((case-fold-search nil)
12157 (regexp (concat "\\<\\(" org-deadline-string
12158 "\\|" org-scheduled-string
12159 "\\) *<\\([^>]+\\)>"))
12160 (callback
12161 (lambda () (time-less-p
12162 (org-time-string-to-time (match-string 2))
12163 (org-time-string-to-time date)))))
12164 (message "%d entries before %s"
12165 (org-occur regexp nil callback) date)))
12167 (defun org-check-after-date (date)
12168 "Check if there are deadlines or scheduled entries after DATE."
12169 (interactive (list (org-read-date)))
12170 (let ((case-fold-search nil)
12171 (regexp (concat "\\<\\(" org-deadline-string
12172 "\\|" org-scheduled-string
12173 "\\) *<\\([^>]+\\)>"))
12174 (callback
12175 (lambda () (not
12176 (time-less-p
12177 (org-time-string-to-time (match-string 2))
12178 (org-time-string-to-time date))))))
12179 (message "%d entries after %s"
12180 (org-occur regexp nil callback) date)))
12182 (defun org-evaluate-time-range (&optional to-buffer)
12183 "Evaluate a time range by computing the difference between start and end.
12184 Normally the result is just printed in the echo area, but with prefix arg
12185 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12186 If the time range is actually in a table, the result is inserted into the
12187 next column.
12188 For time difference computation, a year is assumed to be exactly 365
12189 days in order to avoid rounding problems."
12190 (interactive "P")
12192 (org-clock-update-time-maybe)
12193 (save-excursion
12194 (unless (org-at-date-range-p t)
12195 (goto-char (point-at-bol))
12196 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12197 (if (not (org-at-date-range-p t))
12198 (error "Not at a time-stamp range, and none found in current line")))
12199 (let* ((ts1 (match-string 1))
12200 (ts2 (match-string 2))
12201 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12202 (match-end (match-end 0))
12203 (time1 (org-time-string-to-time ts1))
12204 (time2 (org-time-string-to-time ts2))
12205 (t1 (time-to-seconds time1))
12206 (t2 (time-to-seconds time2))
12207 (diff (abs (- t2 t1)))
12208 (negative (< (- t2 t1) 0))
12209 ;; (ys (floor (* 365 24 60 60)))
12210 (ds (* 24 60 60))
12211 (hs (* 60 60))
12212 (fy "%dy %dd %02d:%02d")
12213 (fy1 "%dy %dd")
12214 (fd "%dd %02d:%02d")
12215 (fd1 "%dd")
12216 (fh "%02d:%02d")
12217 y d h m align)
12218 (if havetime
12219 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12221 d (floor (/ diff ds)) diff (mod diff ds)
12222 h (floor (/ diff hs)) diff (mod diff hs)
12223 m (floor (/ diff 60)))
12224 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12226 d (floor (+ (/ diff ds) 0.5))
12227 h 0 m 0))
12228 (if (not to-buffer)
12229 (message "%s" (org-make-tdiff-string y d h m))
12230 (if (org-at-table-p)
12231 (progn
12232 (goto-char match-end)
12233 (setq align t)
12234 (and (looking-at " *|") (goto-char (match-end 0))))
12235 (goto-char match-end))
12236 (if (looking-at
12237 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12238 (replace-match ""))
12239 (if negative (insert " -"))
12240 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12241 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12242 (insert " " (format fh h m))))
12243 (if align (org-table-align))
12244 (message "Time difference inserted")))))
12246 (defun org-make-tdiff-string (y d h m)
12247 (let ((fmt "")
12248 (l nil))
12249 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12250 l (push y l)))
12251 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12252 l (push d l)))
12253 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12254 l (push h l)))
12255 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12256 l (push m l)))
12257 (apply 'format fmt (nreverse l))))
12259 (defun org-time-string-to-time (s)
12260 (apply 'encode-time (org-parse-time-string s)))
12262 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12263 "Convert a time stamp to an absolute day number.
12264 If there is a specifyer for a cyclic time stamp, get the closest date to
12265 DAYNR.
12266 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12267 (cond
12268 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12269 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12270 daynr
12271 (+ daynr 1000)))
12272 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12273 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12274 (time-to-days (current-time))) (match-string 0 s)
12275 prefer show-all))
12276 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12278 (defun org-days-to-iso-week (days)
12279 "Return the iso week number."
12280 (require 'cal-iso)
12281 (car (calendar-iso-from-absolute days)))
12283 (defun org-small-year-to-year (year)
12284 "Convert 2-digit years into 4-digit years.
12285 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12286 The year 2000 cannot be abbreviated. Any year larger than 99
12287 is returned unchanged."
12288 (if (< year 38)
12289 (setq year (+ 2000 year))
12290 (if (< year 100)
12291 (setq year (+ 1900 year))))
12292 year)
12294 (defun org-time-from-absolute (d)
12295 "Return the time corresponding to date D.
12296 D may be an absolute day number, or a calendar-type list (month day year)."
12297 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12298 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12300 (defun org-calendar-holiday ()
12301 "List of holidays, for Diary display in Org-mode."
12302 (require 'holidays)
12303 (let ((hl (funcall
12304 (if (fboundp 'calendar-check-holidays)
12305 'calendar-check-holidays 'check-calendar-holidays) date)))
12306 (if hl (mapconcat 'identity hl "; "))))
12308 (defun org-diary-sexp-entry (sexp entry date)
12309 "Process a SEXP diary ENTRY for DATE."
12310 (require 'diary-lib)
12311 (let ((result (if calendar-debug-sexp
12312 (let ((stack-trace-on-error t))
12313 (eval (car (read-from-string sexp))))
12314 (condition-case nil
12315 (eval (car (read-from-string sexp)))
12316 (error
12317 (beep)
12318 (message "Bad sexp at line %d in %s: %s"
12319 (org-current-line)
12320 (buffer-file-name) sexp)
12321 (sleep-for 2))))))
12322 (cond ((stringp result) result)
12323 ((and (consp result)
12324 (stringp (cdr result))) (cdr result))
12325 (result entry)
12326 (t nil))))
12328 (defun org-diary-to-ical-string (frombuf)
12329 "Get iCalendar entries from diary entries in buffer FROMBUF.
12330 This uses the icalendar.el library."
12331 (let* ((tmpdir (if (featurep 'xemacs)
12332 (temp-directory)
12333 temporary-file-directory))
12334 (tmpfile (make-temp-name
12335 (expand-file-name "orgics" tmpdir)))
12336 buf rtn b e)
12337 (save-excursion
12338 (set-buffer frombuf)
12339 (icalendar-export-region (point-min) (point-max) tmpfile)
12340 (setq buf (find-buffer-visiting tmpfile))
12341 (set-buffer buf)
12342 (goto-char (point-min))
12343 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12344 (setq b (match-beginning 0)))
12345 (goto-char (point-max))
12346 (if (re-search-backward "^END:VEVENT" nil t)
12347 (setq e (match-end 0)))
12348 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12349 (kill-buffer buf)
12350 (delete-file tmpfile)
12351 rtn))
12353 (defun org-closest-date (start current change prefer show-all)
12354 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12355 When PREFER is `past' return a date that is either CURRENT or past.
12356 When PREFER is `future', return a date that is either CURRENT or future.
12357 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12358 ;; Make the proper lists from the dates
12359 (catch 'exit
12360 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12361 dn dw sday cday n1 n2 n0
12362 d m y y1 y2 date1 date2 nmonths nm ny m2)
12364 (setq start (org-date-to-gregorian start)
12365 current (org-date-to-gregorian
12366 (if show-all
12367 current
12368 (time-to-days (current-time))))
12369 sday (calendar-absolute-from-gregorian start)
12370 cday (calendar-absolute-from-gregorian current))
12372 (if (<= cday sday) (throw 'exit sday))
12374 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12375 (setq dn (string-to-number (match-string 1 change))
12376 dw (cdr (assoc (match-string 2 change) a1)))
12377 (error "Invalid change specifyer: %s" change))
12378 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12379 (cond
12380 ((eq dw 'day)
12381 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12382 n2 (+ n1 dn)))
12383 ((eq dw 'year)
12384 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12385 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12386 (setq date1 (list m d y1)
12387 n1 (calendar-absolute-from-gregorian date1)
12388 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12389 n2 (calendar-absolute-from-gregorian date2)))
12390 ((eq dw 'month)
12391 ;; approx number of month between the two dates
12392 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12393 ;; How often does dn fit in there?
12394 (setq d (nth 1 start) m (car start) y (nth 2 start)
12395 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12396 m (+ m nm)
12397 ny (floor (/ m 12))
12398 y (+ y ny)
12399 m (- m (* ny 12)))
12400 (while (> m 12) (setq m (- m 12) y (1+ y)))
12401 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12402 (setq m2 (+ m dn) y2 y)
12403 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12404 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12405 (while (<= n2 cday)
12406 (setq n1 n2 m m2 y y2)
12407 (setq m2 (+ m dn) y2 y)
12408 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12409 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12410 ;; Make sure n1 is the earlier date
12411 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12412 (if show-all
12413 (cond
12414 ((eq prefer 'past) n1)
12415 ((eq prefer 'future) (if (= cday n1) n1 n2))
12416 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12417 (cond
12418 ((eq prefer 'past) n1)
12419 ((eq prefer 'future) (if (= cday n1) n1 n2))
12420 (t (if (= cday n1) n1 n2)))))))
12422 (defun org-date-to-gregorian (date)
12423 "Turn any specification of DATE into a gregorian date for the calendar."
12424 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12425 ((and (listp date) (= (length date) 3)) date)
12426 ((stringp date)
12427 (setq date (org-parse-time-string date))
12428 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12429 ((listp date)
12430 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12432 (defun org-parse-time-string (s &optional nodefault)
12433 "Parse the standard Org-mode time string.
12434 This should be a lot faster than the normal `parse-time-string'.
12435 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12436 hour and minute fields will be nil if not given."
12437 (if (string-match org-ts-regexp0 s)
12438 (list 0
12439 (if (or (match-beginning 8) (not nodefault))
12440 (string-to-number (or (match-string 8 s) "0")))
12441 (if (or (match-beginning 7) (not nodefault))
12442 (string-to-number (or (match-string 7 s) "0")))
12443 (string-to-number (match-string 4 s))
12444 (string-to-number (match-string 3 s))
12445 (string-to-number (match-string 2 s))
12446 nil nil nil)
12447 (make-list 9 0)))
12449 (defun org-timestamp-up (&optional arg)
12450 "Increase the date item at the cursor by one.
12451 If the cursor is on the year, change the year. If it is on the month or
12452 the day, change that.
12453 With prefix ARG, change by that many units."
12454 (interactive "p")
12455 (org-timestamp-change (prefix-numeric-value arg)))
12457 (defun org-timestamp-down (&optional arg)
12458 "Decrease the date item at the cursor by one.
12459 If the cursor is on the year, change the year. If it is on the month or
12460 the day, change that.
12461 With prefix ARG, change by that many units."
12462 (interactive "p")
12463 (org-timestamp-change (- (prefix-numeric-value arg))))
12465 (defun org-timestamp-up-day (&optional arg)
12466 "Increase the date in the time stamp by one day.
12467 With prefix ARG, change that many days."
12468 (interactive "p")
12469 (if (and (not (org-at-timestamp-p t))
12470 (org-on-heading-p))
12471 (org-todo 'up)
12472 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12474 (defun org-timestamp-down-day (&optional arg)
12475 "Decrease the date in the time stamp by one day.
12476 With prefix ARG, change that many days."
12477 (interactive "p")
12478 (if (and (not (org-at-timestamp-p t))
12479 (org-on-heading-p))
12480 (org-todo 'down)
12481 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12483 (defun org-at-timestamp-p (&optional inactive-ok)
12484 "Determine if the cursor is in or at a timestamp."
12485 (interactive)
12486 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12487 (pos (point))
12488 (ans (or (looking-at tsr)
12489 (save-excursion
12490 (skip-chars-backward "^[<\n\r\t")
12491 (if (> (point) (point-min)) (backward-char 1))
12492 (and (looking-at tsr)
12493 (> (- (match-end 0) pos) -1))))))
12494 (and ans
12495 (boundp 'org-ts-what)
12496 (setq org-ts-what
12497 (cond
12498 ((= pos (match-beginning 0)) 'bracket)
12499 ((= pos (1- (match-end 0))) 'bracket)
12500 ((org-pos-in-match-range pos 2) 'year)
12501 ((org-pos-in-match-range pos 3) 'month)
12502 ((org-pos-in-match-range pos 7) 'hour)
12503 ((org-pos-in-match-range pos 8) 'minute)
12504 ((or (org-pos-in-match-range pos 4)
12505 (org-pos-in-match-range pos 5)) 'day)
12506 ((and (> pos (or (match-end 8) (match-end 5)))
12507 (< pos (match-end 0)))
12508 (- pos (or (match-end 8) (match-end 5))))
12509 (t 'day))))
12510 ans))
12512 (defun org-toggle-timestamp-type ()
12513 "Toggle the type (<active> or [inactive]) of a time stamp."
12514 (interactive)
12515 (when (org-at-timestamp-p t)
12516 (let ((beg (match-beginning 0)) (end (match-end 0))
12517 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12518 (save-excursion
12519 (goto-char beg)
12520 (while (re-search-forward "[][<>]" end t)
12521 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12522 t t)))
12523 (message "Timestamp is now %sactive"
12524 (if (equal (char-after beg) ?<) "" "in")))))
12526 (defun org-timestamp-change (n &optional what)
12527 "Change the date in the time stamp at point.
12528 The date will be changed by N times WHAT. WHAT can be `day', `month',
12529 `year', `minute', `second'. If WHAT is not given, the cursor position
12530 in the timestamp determines what will be changed."
12531 (let ((pos (point))
12532 with-hm inactive
12533 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12534 org-ts-what
12535 extra rem
12536 ts time time0)
12537 (if (not (org-at-timestamp-p t))
12538 (error "Not at a timestamp"))
12539 (if (and (not what) (eq org-ts-what 'bracket))
12540 (org-toggle-timestamp-type)
12541 (if (and (not what) (not (eq org-ts-what 'day))
12542 org-display-custom-times
12543 (get-text-property (point) 'display)
12544 (not (get-text-property (1- (point)) 'display)))
12545 (setq org-ts-what 'day))
12546 (setq org-ts-what (or what org-ts-what)
12547 inactive (= (char-after (match-beginning 0)) ?\[)
12548 ts (match-string 0))
12549 (replace-match "")
12550 (if (string-match
12551 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12553 (setq extra (match-string 1 ts)))
12554 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12555 (setq with-hm t))
12556 (setq time0 (org-parse-time-string ts))
12557 (when (and (eq org-ts-what 'minute)
12558 (eq current-prefix-arg nil))
12559 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12560 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12561 (setcar (cdr time0) (+ (nth 1 time0)
12562 (if (> n 0) (- rem) (- dm rem))))))
12563 (setq time
12564 (encode-time (or (car time0) 0)
12565 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12566 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12567 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12568 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12569 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12570 (nthcdr 6 time0)))
12571 (when (and (member org-ts-what '(hour minute))
12572 extra
12573 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
12574 (setq extra (org-modify-ts-extra
12575 extra
12576 (if (eq org-ts-what 'hour) 2 5)
12577 n dm)))
12578 (when (integerp org-ts-what)
12579 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12580 (if (eq what 'calendar)
12581 (let ((cal-date (org-get-date-from-calendar)))
12582 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12583 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12584 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12585 (setcar time0 (or (car time0) 0))
12586 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12587 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12588 (setq time (apply 'encode-time time0))))
12589 (setq org-last-changed-timestamp
12590 (org-insert-time-stamp time with-hm inactive nil nil extra))
12591 (org-clock-update-time-maybe)
12592 (goto-char pos)
12593 ;; Try to recenter the calendar window, if any
12594 (if (and org-calendar-follow-timestamp-change
12595 (get-buffer-window "*Calendar*" t)
12596 (memq org-ts-what '(day month year)))
12597 (org-recenter-calendar (time-to-days time))))))
12599 (defun org-modify-ts-extra (s pos n dm)
12600 "Change the different parts of the lead-time and repeat fields in timestamp."
12601 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12602 ng h m new rem)
12603 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12604 (cond
12605 ((or (org-pos-in-match-range pos 2)
12606 (org-pos-in-match-range pos 3))
12607 (setq m (string-to-number (match-string 3 s))
12608 h (string-to-number (match-string 2 s)))
12609 (if (org-pos-in-match-range pos 2)
12610 (setq h (+ h n))
12611 (setq n (* dm (org-no-warnings (signum n))))
12612 (when (not (= 0 (setq rem (% m dm))))
12613 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12614 (setq m (+ m n)))
12615 (if (< m 0) (setq m (+ m 60) h (1- h)))
12616 (if (> m 59) (setq m (- m 60) h (1+ h)))
12617 (setq h (min 24 (max 0 h)))
12618 (setq ng 1 new (format "-%02d:%02d" h m)))
12619 ((org-pos-in-match-range pos 6)
12620 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12621 ((org-pos-in-match-range pos 5)
12622 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12624 ((org-pos-in-match-range pos 9)
12625 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12626 ((org-pos-in-match-range pos 8)
12627 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12629 (when ng
12630 (setq s (concat
12631 (substring s 0 (match-beginning ng))
12633 (substring s (match-end ng))))))
12636 (defun org-recenter-calendar (date)
12637 "If the calendar is visible, recenter it to DATE."
12638 (let* ((win (selected-window))
12639 (cwin (get-buffer-window "*Calendar*" t))
12640 (calendar-move-hook nil))
12641 (when cwin
12642 (select-window cwin)
12643 (calendar-goto-date (if (listp date) date
12644 (calendar-gregorian-from-absolute date)))
12645 (select-window win))))
12647 (defun org-goto-calendar (&optional arg)
12648 "Go to the Emacs calendar at the current date.
12649 If there is a time stamp in the current line, go to that date.
12650 A prefix ARG can be used to force the current date."
12651 (interactive "P")
12652 (let ((tsr org-ts-regexp) diff
12653 (calendar-move-hook nil)
12654 (calendar-view-holidays-initially-flag nil)
12655 (view-calendar-holidays-initially nil)
12656 (calendar-view-diary-initially-flag nil)
12657 (view-diary-entries-initially nil))
12658 (if (or (org-at-timestamp-p)
12659 (save-excursion
12660 (beginning-of-line 1)
12661 (looking-at (concat ".*" tsr))))
12662 (let ((d1 (time-to-days (current-time)))
12663 (d2 (time-to-days
12664 (org-time-string-to-time (match-string 1)))))
12665 (setq diff (- d2 d1))))
12666 (calendar)
12667 (calendar-goto-today)
12668 (if (and diff (not arg)) (calendar-forward-day diff))))
12670 (defun org-get-date-from-calendar ()
12671 "Return a list (month day year) of date at point in calendar."
12672 (with-current-buffer "*Calendar*"
12673 (save-match-data
12674 (calendar-cursor-to-date))))
12676 (defun org-date-from-calendar ()
12677 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12678 If there is already a time stamp at the cursor position, update it."
12679 (interactive)
12680 (if (org-at-timestamp-p t)
12681 (org-timestamp-change 0 'calendar)
12682 (let ((cal-date (org-get-date-from-calendar)))
12683 (org-insert-time-stamp
12684 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12686 (defun org-minutes-to-hh:mm-string (m)
12687 "Compute H:MM from a number of minutes."
12688 (let ((h (/ m 60)))
12689 (setq m (- m (* 60 h)))
12690 (format org-time-clocksum-format h m)))
12692 (defun org-hh:mm-string-to-minutes (s)
12693 "Convert a string H:MM to a number of minutes."
12694 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12695 (+ (* (string-to-number (match-string 1 s)) 60)
12696 (string-to-number (match-string 2 s)))
12699 ;;;; Files
12701 (defun org-save-all-org-buffers ()
12702 "Save all Org-mode buffers without user confirmation."
12703 (interactive)
12704 (message "Saving all Org-mode buffers...")
12705 (save-some-buffers t 'org-mode-p)
12706 (when (featurep 'org-id) (org-id-locations-save))
12707 (message "Saving all Org-mode buffers... done"))
12709 (defun org-revert-all-org-buffers ()
12710 "Revert all Org-mode buffers.
12711 Prompt for confirmation when there are unsaved changes.
12712 Be sure you know what you are doing before letting this function
12713 overwrite your changes.
12715 This function is useful in a setup where one tracks org files
12716 with a version control system, to revert on one machine after pulling
12717 changes from another. I believe the procedure must be like this:
12719 1. M-x org-save-all-org-buffers
12720 2. Pull changes from the other machine, resolve conflicts
12721 3. M-x org-revert-all-org-buffers"
12722 (interactive)
12723 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12724 (error "Abort"))
12725 (save-excursion
12726 (save-window-excursion
12727 (mapc
12728 (lambda (b)
12729 (when (and (with-current-buffer b (org-mode-p))
12730 (with-current-buffer b buffer-file-name))
12731 (switch-to-buffer b)
12732 (revert-buffer t 'no-confirm)))
12733 (buffer-list))
12734 (when (and (featurep 'org-id) org-id-track-globally)
12735 (org-id-locations-load)))))
12737 ;;;; Agenda files
12739 ;;;###autoload
12740 (defun org-iswitchb (&optional arg)
12741 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12742 With a prefix argument, restrict available to files.
12743 With two prefix arguments, restrict available buffers to agenda files.
12745 Due to some yet unresolved reason, the global function
12746 `iswitchb-mode' needs to be active for this function to work."
12747 (interactive "P")
12748 (require 'iswitchb)
12749 (let ((enabled iswitchb-mode) blist)
12750 (or enabled (iswitchb-mode 1))
12751 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12752 ((equal arg '(16)) (org-buffer-list 'agenda))
12753 (t (org-buffer-list))))
12754 (unwind-protect
12755 (let ((iswitchb-make-buflist-hook
12756 (lambda ()
12757 (setq iswitchb-temp-buflist
12758 (mapcar 'buffer-name blist)))))
12759 (switch-to-buffer
12760 (iswitchb-read-buffer
12761 "Switch-to: " nil t))
12762 (or enabled (iswitchb-mode -1))))))
12764 ;;;###autoload
12765 (defun org-ido-switchb (&optional arg)
12766 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12767 With a prefix argument, restrict available to files.
12768 With two prefix arguments, restrict available buffers to agenda files."
12769 (interactive "P")
12770 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12771 ((equal arg '(16)) (org-buffer-list 'agenda))
12772 (t (org-buffer-list)))))
12773 (switch-to-buffer
12774 (org-ido-completing-read "Org buffer: "
12775 (mapcar 'list (mapcar 'buffer-name blist))
12776 nil t))))
12778 (defun org-buffer-list (&optional predicate exclude-tmp)
12779 "Return a list of Org buffers.
12780 PREDICATE can be `export', `files' or `agenda'.
12782 export restrict the list to Export buffers.
12783 files restrict the list to buffers visiting Org files.
12784 agenda restrict the list to buffers visiting agenda files.
12786 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12787 (let* ((bfn nil)
12788 (agenda-files (and (eq predicate 'agenda)
12789 (mapcar 'file-truename (org-agenda-files t))))
12790 (filter
12791 (cond
12792 ((eq predicate 'files)
12793 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12794 ((eq predicate 'export)
12795 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12796 ((eq predicate 'agenda)
12797 (lambda (b)
12798 (with-current-buffer b
12799 (and (eq major-mode 'org-mode)
12800 (setq bfn (buffer-file-name b))
12801 (member (file-truename bfn) agenda-files)))))
12802 (t (lambda (b) (with-current-buffer b
12803 (or (eq major-mode 'org-mode)
12804 (string-match "\*Org .*Export"
12805 (buffer-name b)))))))))
12806 (delq nil
12807 (mapcar
12808 (lambda(b)
12809 (if (and (funcall filter b)
12810 (or (not exclude-tmp)
12811 (not (string-match "tmp" (buffer-name b)))))
12813 nil))
12814 (buffer-list)))))
12816 (defun org-agenda-files (&optional unrestricted archives)
12817 "Get the list of agenda files.
12818 Optional UNRESTRICTED means return the full list even if a restriction
12819 is currently in place.
12820 When ARCHIVES is t, include all archive files hat are really being
12821 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12822 `org-agenda-archives-mode' is t."
12823 (let ((files
12824 (cond
12825 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12826 ((stringp org-agenda-files) (org-read-agenda-file-list))
12827 ((listp org-agenda-files) org-agenda-files)
12828 (t (error "Invalid value of `org-agenda-files'")))))
12829 (setq files (apply 'append
12830 (mapcar (lambda (f)
12831 (if (file-directory-p f)
12832 (directory-files
12833 f t org-agenda-file-regexp)
12834 (list f)))
12835 files)))
12836 (when org-agenda-skip-unavailable-files
12837 (setq files (delq nil
12838 (mapcar (function
12839 (lambda (file)
12840 (and (file-readable-p file) file)))
12841 files))))
12842 (when (or (eq archives t)
12843 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12844 (setq files (org-add-archive-files files)))
12845 files))
12847 (defun org-edit-agenda-file-list ()
12848 "Edit the list of agenda files.
12849 Depending on setup, this either uses customize to edit the variable
12850 `org-agenda-files', or it visits the file that is holding the list. In the
12851 latter case, the buffer is set up in a way that saving it automatically kills
12852 the buffer and restores the previous window configuration."
12853 (interactive)
12854 (if (stringp org-agenda-files)
12855 (let ((cw (current-window-configuration)))
12856 (find-file org-agenda-files)
12857 (org-set-local 'org-window-configuration cw)
12858 (org-add-hook 'after-save-hook
12859 (lambda ()
12860 (set-window-configuration
12861 (prog1 org-window-configuration
12862 (kill-buffer (current-buffer))))
12863 (org-install-agenda-files-menu)
12864 (message "New agenda file list installed"))
12865 nil 'local)
12866 (message "%s" (substitute-command-keys
12867 "Edit list and finish with \\[save-buffer]")))
12868 (customize-variable 'org-agenda-files)))
12870 (defun org-store-new-agenda-file-list (list)
12871 "Set new value for the agenda file list and save it correctly."
12872 (if (stringp org-agenda-files)
12873 (let ((f org-agenda-files) b)
12874 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12875 (with-temp-file f
12876 (insert (mapconcat 'identity list "\n") "\n")))
12877 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12878 (setq org-agenda-files list)
12879 (customize-save-variable 'org-agenda-files org-agenda-files))))
12881 (defun org-read-agenda-file-list ()
12882 "Read the list of agenda files from a file."
12883 (when (file-directory-p org-agenda-files)
12884 (error "`org-agenda-files' cannot be a single directory"))
12885 (when (stringp org-agenda-files)
12886 (with-temp-buffer
12887 (insert-file-contents org-agenda-files)
12888 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12891 ;;;###autoload
12892 (defun org-cycle-agenda-files ()
12893 "Cycle through the files in `org-agenda-files'.
12894 If the current buffer visits an agenda file, find the next one in the list.
12895 If the current buffer does not, find the first agenda file."
12896 (interactive)
12897 (let* ((fs (org-agenda-files t))
12898 (files (append fs (list (car fs))))
12899 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12900 file)
12901 (unless files (error "No agenda files"))
12902 (catch 'exit
12903 (while (setq file (pop files))
12904 (if (equal (file-truename file) tcf)
12905 (when (car files)
12906 (find-file (car files))
12907 (throw 'exit t))))
12908 (find-file (car fs)))
12909 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12911 (defun org-agenda-file-to-front (&optional to-end)
12912 "Move/add the current file to the top of the agenda file list.
12913 If the file is not present in the list, it is added to the front. If it is
12914 present, it is moved there. With optional argument TO-END, add/move to the
12915 end of the list."
12916 (interactive "P")
12917 (let ((org-agenda-skip-unavailable-files nil)
12918 (file-alist (mapcar (lambda (x)
12919 (cons (file-truename x) x))
12920 (org-agenda-files t)))
12921 (ctf (file-truename buffer-file-name))
12922 x had)
12923 (setq x (assoc ctf file-alist) had x)
12925 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12926 (if to-end
12927 (setq file-alist (append (delq x file-alist) (list x)))
12928 (setq file-alist (cons x (delq x file-alist))))
12929 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12930 (org-install-agenda-files-menu)
12931 (message "File %s to %s of agenda file list"
12932 (if had "moved" "added") (if to-end "end" "front"))))
12934 (defun org-remove-file (&optional file)
12935 "Remove current file from the list of files in variable `org-agenda-files'.
12936 These are the files which are being checked for agenda entries.
12937 Optional argument FILE means, use this file instead of the current."
12938 (interactive)
12939 (let* ((org-agenda-skip-unavailable-files nil)
12940 (file (or file buffer-file-name))
12941 (true-file (file-truename file))
12942 (afile (abbreviate-file-name file))
12943 (files (delq nil (mapcar
12944 (lambda (x)
12945 (if (equal true-file
12946 (file-truename x))
12947 nil x))
12948 (org-agenda-files t)))))
12949 (if (not (= (length files) (length (org-agenda-files t))))
12950 (progn
12951 (org-store-new-agenda-file-list files)
12952 (org-install-agenda-files-menu)
12953 (message "Removed file: %s" afile))
12954 (message "File was not in list: %s (not removed)" afile))))
12956 (defun org-file-menu-entry (file)
12957 (vector file (list 'find-file file) t))
12959 (defun org-check-agenda-file (file)
12960 "Make sure FILE exists. If not, ask user what to do."
12961 (when (not (file-exists-p file))
12962 (message "non-existent file %s. [R]emove from list or [A]bort?"
12963 (abbreviate-file-name file))
12964 (let ((r (downcase (read-char-exclusive))))
12965 (cond
12966 ((equal r ?r)
12967 (org-remove-file file)
12968 (throw 'nextfile t))
12969 (t (error "Abort"))))))
12971 (defun org-get-agenda-file-buffer (file)
12972 "Get a buffer visiting FILE. If the buffer needs to be created, add
12973 it to the list of buffers which might be released later."
12974 (let ((buf (org-find-base-buffer-visiting file)))
12975 (if buf
12976 buf ; just return it
12977 ;; Make a new buffer and remember it
12978 (setq buf (find-file-noselect file))
12979 (if buf (push buf org-agenda-new-buffers))
12980 buf)))
12982 (defun org-release-buffers (blist)
12983 "Release all buffers in list, asking the user for confirmation when needed.
12984 When a buffer is unmodified, it is just killed. When modified, it is saved
12985 \(if the user agrees) and then killed."
12986 (let (buf file)
12987 (while (setq buf (pop blist))
12988 (setq file (buffer-file-name buf))
12989 (when (and (buffer-modified-p buf)
12990 file
12991 (y-or-n-p (format "Save file %s? " file)))
12992 (with-current-buffer buf (save-buffer)))
12993 (kill-buffer buf))))
12995 (defun org-prepare-agenda-buffers (files)
12996 "Create buffers for all agenda files, protect archived trees and comments."
12997 (interactive)
12998 (let ((pa '(:org-archived t))
12999 (pc '(:org-comment t))
13000 (pall '(:org-archived t :org-comment t))
13001 (inhibit-read-only t)
13002 (rea (concat ":" org-archive-tag ":"))
13003 bmp file re)
13004 (save-excursion
13005 (save-restriction
13006 (while (setq file (pop files))
13007 (if (bufferp file)
13008 (set-buffer file)
13009 (org-check-agenda-file file)
13010 (set-buffer (org-get-agenda-file-buffer file)))
13011 (widen)
13012 (setq bmp (buffer-modified-p))
13013 (org-refresh-category-properties)
13014 (setq org-todo-keywords-for-agenda
13015 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13016 (setq org-done-keywords-for-agenda
13017 (append org-done-keywords-for-agenda org-done-keywords))
13018 (setq org-todo-keyword-alist-for-agenda
13019 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13020 (setq org-tag-alist-for-agenda
13021 (append org-tag-alist-for-agenda org-tag-alist))
13023 (save-excursion
13024 (remove-text-properties (point-min) (point-max) pall)
13025 (when org-agenda-skip-archived-trees
13026 (goto-char (point-min))
13027 (while (re-search-forward rea nil t)
13028 (if (org-on-heading-p t)
13029 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13030 (goto-char (point-min))
13031 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13032 (while (re-search-forward re nil t)
13033 (add-text-properties
13034 (match-beginning 0) (org-end-of-subtree t) pc)))
13035 (set-buffer-modified-p bmp))))
13036 (setq org-todo-keyword-alist-for-agenda
13037 (org-uniquify org-todo-keyword-alist-for-agenda)
13038 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13040 ;;;; Embedded LaTeX
13042 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13043 "Keymap for the minor `org-cdlatex-mode'.")
13045 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13046 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13047 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13048 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13049 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13051 (defvar org-cdlatex-texmathp-advice-is-done nil
13052 "Flag remembering if we have applied the advice to texmathp already.")
13054 (define-minor-mode org-cdlatex-mode
13055 "Toggle the minor `org-cdlatex-mode'.
13056 This mode supports entering LaTeX environment and math in LaTeX fragments
13057 in Org-mode.
13058 \\{org-cdlatex-mode-map}"
13059 nil " OCDL" nil
13060 (when org-cdlatex-mode (require 'cdlatex))
13061 (unless org-cdlatex-texmathp-advice-is-done
13062 (setq org-cdlatex-texmathp-advice-is-done t)
13063 (defadvice texmathp (around org-math-always-on activate)
13064 "Always return t in org-mode buffers.
13065 This is because we want to insert math symbols without dollars even outside
13066 the LaTeX math segments. If Orgmode thinks that point is actually inside
13067 an embedded LaTeX fragment, let texmathp do its job.
13068 \\[org-cdlatex-mode-map]"
13069 (interactive)
13070 (let (p)
13071 (cond
13072 ((not (org-mode-p)) ad-do-it)
13073 ((eq this-command 'cdlatex-math-symbol)
13074 (setq ad-return-value t
13075 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13077 (let ((p (org-inside-LaTeX-fragment-p)))
13078 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13079 (setq ad-return-value t
13080 texmathp-why '("Org-mode embedded math" . 0))
13081 (if p ad-do-it)))))))))
13083 (defun turn-on-org-cdlatex ()
13084 "Unconditionally turn on `org-cdlatex-mode'."
13085 (org-cdlatex-mode 1))
13087 (defun org-inside-LaTeX-fragment-p ()
13088 "Test if point is inside a LaTeX fragment.
13089 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13090 sequence appearing also before point.
13091 Even though the matchers for math are configurable, this function assumes
13092 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13093 delimiters are skipped when they have been removed by customization.
13094 The return value is nil, or a cons cell with the delimiter and
13095 and the position of this delimiter.
13097 This function does a reasonably good job, but can locally be fooled by
13098 for example currency specifications. For example it will assume being in
13099 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13100 fragments that are properly closed, but during editing, we have to live
13101 with the uncertainty caused by missing closing delimiters. This function
13102 looks only before point, not after."
13103 (catch 'exit
13104 (let ((pos (point))
13105 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13106 (lim (progn
13107 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13108 (point)))
13109 dd-on str (start 0) m re)
13110 (goto-char pos)
13111 (when dodollar
13112 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13113 re (nth 1 (assoc "$" org-latex-regexps)))
13114 (while (string-match re str start)
13115 (cond
13116 ((= (match-end 0) (length str))
13117 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13118 ((= (match-end 0) (- (length str) 5))
13119 (throw 'exit nil))
13120 (t (setq start (match-end 0))))))
13121 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13122 (goto-char pos)
13123 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13124 (and (match-beginning 2) (throw 'exit nil))
13125 ;; count $$
13126 (while (re-search-backward "\\$\\$" lim t)
13127 (setq dd-on (not dd-on)))
13128 (goto-char pos)
13129 (if dd-on (cons "$$" m))))))
13132 (defun org-try-cdlatex-tab ()
13133 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13134 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13135 - inside a LaTeX fragment, or
13136 - after the first word in a line, where an abbreviation expansion could
13137 insert a LaTeX environment."
13138 (when org-cdlatex-mode
13139 (cond
13140 ((save-excursion
13141 (skip-chars-backward "a-zA-Z0-9*")
13142 (skip-chars-backward " \t")
13143 (bolp))
13144 (cdlatex-tab) t)
13145 ((org-inside-LaTeX-fragment-p)
13146 (cdlatex-tab) t)
13147 (t nil))))
13149 (defun org-cdlatex-underscore-caret (&optional arg)
13150 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13151 Revert to the normal definition outside of these fragments."
13152 (interactive "P")
13153 (if (org-inside-LaTeX-fragment-p)
13154 (call-interactively 'cdlatex-sub-superscript)
13155 (let (org-cdlatex-mode)
13156 (call-interactively (key-binding (vector last-input-event))))))
13158 (defun org-cdlatex-math-modify (&optional arg)
13159 "Execute `cdlatex-math-modify' in LaTeX fragments.
13160 Revert to the normal definition outside of these fragments."
13161 (interactive "P")
13162 (if (org-inside-LaTeX-fragment-p)
13163 (call-interactively 'cdlatex-math-modify)
13164 (let (org-cdlatex-mode)
13165 (call-interactively (key-binding (vector last-input-event))))))
13167 (defvar org-latex-fragment-image-overlays nil
13168 "List of overlays carrying the images of latex fragments.")
13169 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13171 (defun org-remove-latex-fragment-image-overlays ()
13172 "Remove all overlays with LaTeX fragment images in current buffer."
13173 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13174 (setq org-latex-fragment-image-overlays nil))
13176 (defun org-preview-latex-fragment (&optional subtree)
13177 "Preview the LaTeX fragment at point, or all locally or globally.
13178 If the cursor is in a LaTeX fragment, create the image and overlay
13179 it over the source code. If there is no fragment at point, display
13180 all fragments in the current text, from one headline to the next. With
13181 prefix SUBTREE, display all fragments in the current subtree. With a
13182 double prefix `C-u C-u', or when the cursor is before the first headline,
13183 display all fragments in the buffer.
13184 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13185 (interactive "P")
13186 (org-remove-latex-fragment-image-overlays)
13187 (save-excursion
13188 (save-restriction
13189 (let (beg end at msg)
13190 (cond
13191 ((or (equal subtree '(16))
13192 (not (save-excursion
13193 (re-search-backward (concat "^" outline-regexp) nil t))))
13194 (setq beg (point-min) end (point-max)
13195 msg "Creating images for buffer...%s"))
13196 ((equal subtree '(4))
13197 (org-back-to-heading)
13198 (setq beg (point) end (org-end-of-subtree t)
13199 msg "Creating images for subtree...%s"))
13201 (if (setq at (org-inside-LaTeX-fragment-p))
13202 (goto-char (max (point-min) (- (cdr at) 2)))
13203 (org-back-to-heading))
13204 (setq beg (point) end (progn (outline-next-heading) (point))
13205 msg (if at "Creating image...%s"
13206 "Creating images for entry...%s"))))
13207 (message msg "")
13208 (narrow-to-region beg end)
13209 (goto-char beg)
13210 (org-format-latex
13211 (concat "ltxpng/" (file-name-sans-extension
13212 (file-name-nondirectory
13213 buffer-file-name)))
13214 default-directory 'overlays msg at 'forbuffer)
13215 (message msg "done. Use `C-c C-c' to remove images.")))))
13217 (defvar org-latex-regexps
13218 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13219 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13220 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13221 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13222 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13223 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13224 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13225 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13226 "Regular expressions for matching embedded LaTeX.")
13228 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13229 "Replace LaTeX fragments with links to an image, and produce images."
13230 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13231 (let* ((prefixnodir (file-name-nondirectory prefix))
13232 (absprefix (expand-file-name prefix dir))
13233 (todir (file-name-directory absprefix))
13234 (opt org-format-latex-options)
13235 (matchers (plist-get opt :matchers))
13236 (re-list org-latex-regexps)
13237 (cnt 0) txt link beg end re e checkdir
13238 m n block linkfile movefile ov)
13239 ;; Check if there are old images files with this prefix, and remove them
13240 (when (file-directory-p todir)
13241 (mapc 'delete-file
13242 (directory-files
13243 todir 'full
13244 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13245 ;; Check the different regular expressions
13246 (while (setq e (pop re-list))
13247 (setq m (car e) re (nth 1 e) n (nth 2 e)
13248 block (if (nth 3 e) "\n\n" ""))
13249 (when (member m matchers)
13250 (goto-char (point-min))
13251 (while (re-search-forward re nil t)
13252 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13253 (not (get-text-property (match-beginning n)
13254 'org-protected)))
13255 (setq txt (match-string n)
13256 beg (match-beginning n) end (match-end n)
13257 cnt (1+ cnt)
13258 linkfile (format "%s_%04d.png" prefix cnt)
13259 movefile (format "%s_%04d.png" absprefix cnt)
13260 link (concat block "[[file:" linkfile "]]" block))
13261 (if msg (message msg cnt))
13262 (goto-char beg)
13263 (unless checkdir ; make sure the directory exists
13264 (setq checkdir t)
13265 (or (file-directory-p todir) (make-directory todir)))
13266 (org-create-formula-image
13267 txt movefile opt forbuffer)
13268 (if overlays
13269 (progn
13270 (setq ov (org-make-overlay beg end))
13271 (if (featurep 'xemacs)
13272 (progn
13273 (org-overlay-put ov 'invisible t)
13274 (org-overlay-put
13275 ov 'end-glyph
13276 (make-glyph (vector 'png :file movefile))))
13277 (org-overlay-put
13278 ov 'display
13279 (list 'image :type 'png :file movefile :ascent 'center)))
13280 (push ov org-latex-fragment-image-overlays)
13281 (goto-char end))
13282 (delete-region beg end)
13283 (insert link))))))))
13285 ;; This function borrows from Ganesh Swami's latex2png.el
13286 (defun org-create-formula-image (string tofile options buffer)
13287 (let* ((tmpdir (if (featurep 'xemacs)
13288 (temp-directory)
13289 temporary-file-directory))
13290 (texfilebase (make-temp-name
13291 (expand-file-name "orgtex" tmpdir)))
13292 (texfile (concat texfilebase ".tex"))
13293 (dvifile (concat texfilebase ".dvi"))
13294 (pngfile (concat texfilebase ".png"))
13295 (fnh (if (featurep 'xemacs)
13296 (font-height (get-face-font 'default))
13297 (face-attribute 'default :height nil)))
13298 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13299 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13300 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13301 "Black"))
13302 (bg (or (plist-get options (if buffer :background :html-background))
13303 "Transparent")))
13304 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13305 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13306 (with-temp-file texfile
13307 (insert org-format-latex-header
13308 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13309 (let ((dir default-directory))
13310 (condition-case nil
13311 (progn
13312 (cd tmpdir)
13313 (call-process "latex" nil nil nil texfile))
13314 (error nil))
13315 (cd dir))
13316 (if (not (file-exists-p dvifile))
13317 (progn (message "Failed to create dvi file from %s" texfile) nil)
13318 (condition-case nil
13319 (call-process "dvipng" nil nil nil
13320 "-E" "-fg" fg "-bg" bg
13321 "-D" dpi
13322 ;;"-x" scale "-y" scale
13323 "-T" "tight"
13324 "-o" pngfile
13325 dvifile)
13326 (error nil))
13327 (if (not (file-exists-p pngfile))
13328 (progn (message "Failed to create png file from %s" texfile) nil)
13329 ;; Use the requested file name and clean up
13330 (copy-file pngfile tofile 'replace)
13331 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13332 (delete-file (concat texfilebase e)))
13333 pngfile))))
13335 (defun org-dvipng-color (attr)
13336 "Return an rgb color specification for dvipng."
13337 (apply 'format "rgb %s %s %s"
13338 (mapcar 'org-normalize-color
13339 (color-values (face-attribute 'default attr nil)))))
13341 (defun org-normalize-color (value)
13342 "Return string to be used as color value for an RGB component."
13343 (format "%g" (/ value 65535.0)))
13345 ;;;; Key bindings
13347 ;; Make `C-c C-x' a prefix key
13348 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13350 ;; TAB key with modifiers
13351 (org-defkey org-mode-map "\C-i" 'org-cycle)
13352 (org-defkey org-mode-map [(tab)] 'org-cycle)
13353 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13354 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13355 (org-defkey org-mode-map "\M-\t" 'org-complete)
13356 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13357 ;; The following line is necessary under Suse GNU/Linux
13358 (unless (featurep 'xemacs)
13359 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13360 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13361 (define-key org-mode-map [backtab] 'org-shifttab)
13363 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13364 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13365 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13367 ;; Cursor keys with modifiers
13368 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13369 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13370 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13371 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13373 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13374 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13375 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13376 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13378 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13379 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13380 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13381 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13383 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13384 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13386 ;;; Extra keys for tty access.
13387 ;; We only set them when really needed because otherwise the
13388 ;; menus don't show the simple keys
13390 (when (or org-use-extra-keys
13391 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13392 (not window-system))
13393 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13394 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13395 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13396 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13397 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13398 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13399 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13400 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13401 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13402 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13403 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13404 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13405 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13406 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13407 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13408 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13409 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13410 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13411 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13412 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13413 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13414 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13416 ;; All the other keys
13418 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13419 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13420 (if (boundp 'narrow-map)
13421 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13422 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13423 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13424 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13425 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13426 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13427 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13428 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13429 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13430 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13431 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13432 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13433 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13434 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13435 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13436 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13437 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13438 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13439 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13440 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13441 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13442 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13443 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13444 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13445 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13446 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13447 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13448 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13449 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13450 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13451 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13452 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13453 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13454 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13455 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13456 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13457 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13458 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13459 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13460 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13461 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13462 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13463 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13464 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13465 (org-defkey org-mode-map "\C-c^" 'org-sort)
13466 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13467 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13468 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13469 (org-defkey org-mode-map "\C-m" 'org-return)
13470 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13471 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13472 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13473 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13474 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13475 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13476 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13477 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13478 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13479 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13480 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13481 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13482 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13483 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13484 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13485 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13486 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13488 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13489 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13490 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13491 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13493 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13494 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13495 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13496 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13497 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13498 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13499 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13500 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13501 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13502 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13503 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13504 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13505 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13507 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13508 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13509 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13510 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13512 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13514 (define-key org-mode-map "\C-c\C-xr" 'org-reload)
13516 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
13517 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
13519 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
13522 (when (featurep 'xemacs)
13523 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13526 (defvar org-self-insert-command-undo-counter 0)
13528 (defvar org-table-auto-blank-field) ; defined in org-table.el
13529 (defun org-self-insert-command (N)
13530 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13531 If the cursor is in a table looking at whitespace, the whitespace is
13532 overwritten, and the table is not marked as requiring realignment."
13533 (interactive "p")
13534 (if (and
13535 (org-table-p)
13536 (progn
13537 ;; check if we blank the field, and if that triggers align
13538 (and (featurep 'org-table) org-table-auto-blank-field
13539 (member last-command
13540 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13541 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13542 ;; got extra space, this field does not determine column width
13543 (let (org-table-may-need-update) (org-table-blank-field))
13544 ;; no extra space, this field may determine column width
13545 (org-table-blank-field)))
13547 (eq N 1)
13548 (looking-at "[^|\n]* |"))
13549 (let (org-table-may-need-update)
13550 (goto-char (1- (match-end 0)))
13551 (delete-backward-char 1)
13552 (goto-char (match-beginning 0))
13553 (self-insert-command N))
13554 (setq org-table-may-need-update t)
13555 (self-insert-command N)
13556 (org-fix-tags-on-the-fly)
13557 (if org-self-insert-cluster-for-undo
13558 (if (not (eq last-command 'org-self-insert-command))
13559 (setq org-self-insert-command-undo-counter 1)
13560 (if (>= org-self-insert-command-undo-counter 20)
13561 (setq org-self-insert-command-undo-counter 1)
13562 (and (> org-self-insert-command-undo-counter 0)
13563 buffer-undo-list
13564 (not (cadr buffer-undo-list)) ; remove nil entry
13565 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13566 (setq org-self-insert-command-undo-counter
13567 (1+ org-self-insert-command-undo-counter)))))))
13569 (defun org-fix-tags-on-the-fly ()
13570 (when (and (equal (char-after (point-at-bol)) ?*)
13571 (org-on-heading-p))
13572 (org-align-tags-here org-tags-column)))
13574 (defun org-delete-backward-char (N)
13575 "Like `delete-backward-char', insert whitespace at field end in tables.
13576 When deleting backwards, in tables this function will insert whitespace in
13577 front of the next \"|\" separator, to keep the table aligned. The table will
13578 still be marked for re-alignment if the field did fill the entire column,
13579 because, in this case the deletion might narrow the column."
13580 (interactive "p")
13581 (if (and (org-table-p)
13582 (eq N 1)
13583 (string-match "|" (buffer-substring (point-at-bol) (point)))
13584 (looking-at ".*?|"))
13585 (let ((pos (point))
13586 (noalign (looking-at "[^|\n\r]* |"))
13587 (c org-table-may-need-update))
13588 (backward-delete-char N)
13589 (skip-chars-forward "^|")
13590 (insert " ")
13591 (goto-char (1- pos))
13592 ;; noalign: if there were two spaces at the end, this field
13593 ;; does not determine the width of the column.
13594 (if noalign (setq org-table-may-need-update c)))
13595 (backward-delete-char N)
13596 (org-fix-tags-on-the-fly)))
13598 (defun org-delete-char (N)
13599 "Like `delete-char', but insert whitespace at field end in tables.
13600 When deleting characters, in tables this function will insert whitespace in
13601 front of the next \"|\" separator, to keep the table aligned. The table will
13602 still be marked for re-alignment if the field did fill the entire column,
13603 because, in this case the deletion might narrow the column."
13604 (interactive "p")
13605 (if (and (org-table-p)
13606 (not (bolp))
13607 (not (= (char-after) ?|))
13608 (eq N 1))
13609 (if (looking-at ".*?|")
13610 (let ((pos (point))
13611 (noalign (looking-at "[^|\n\r]* |"))
13612 (c org-table-may-need-update))
13613 (replace-match (concat
13614 (substring (match-string 0) 1 -1)
13615 " |"))
13616 (goto-char pos)
13617 ;; noalign: if there were two spaces at the end, this field
13618 ;; does not determine the width of the column.
13619 (if noalign (setq org-table-may-need-update c)))
13620 (delete-char N))
13621 (delete-char N)
13622 (org-fix-tags-on-the-fly)))
13624 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13625 (put 'org-self-insert-command 'delete-selection t)
13626 (put 'orgtbl-self-insert-command 'delete-selection t)
13627 (put 'org-delete-char 'delete-selection 'supersede)
13628 (put 'org-delete-backward-char 'delete-selection 'supersede)
13629 (put 'org-yank 'delete-selection 'yank)
13631 ;; Make `flyspell-mode' delay after some commands
13632 (put 'org-self-insert-command 'flyspell-delayed t)
13633 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13634 (put 'org-delete-char 'flyspell-delayed t)
13635 (put 'org-delete-backward-char 'flyspell-delayed t)
13637 ;; Make pabbrev-mode expand after org-mode commands
13638 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13639 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13641 ;; How to do this: Measure non-white length of current string
13642 ;; If equal to column width, we should realign.
13644 (defun org-remap (map &rest commands)
13645 "In MAP, remap the functions given in COMMANDS.
13646 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13647 (let (new old)
13648 (while commands
13649 (setq old (pop commands) new (pop commands))
13650 (if (fboundp 'command-remapping)
13651 (org-defkey map (vector 'remap old) new)
13652 (substitute-key-definition old new map global-map)))))
13654 (when (eq org-enable-table-editor 'optimized)
13655 ;; If the user wants maximum table support, we need to hijack
13656 ;; some standard editing functions
13657 (org-remap org-mode-map
13658 'self-insert-command 'org-self-insert-command
13659 'delete-char 'org-delete-char
13660 'delete-backward-char 'org-delete-backward-char)
13661 (org-defkey org-mode-map "|" 'org-force-self-insert))
13663 (defvar org-ctrl-c-ctrl-c-hook nil
13664 "Hook for functions attaching themselves to `C-c C-c'.
13665 This can be used to add additional functionality to the C-c C-c key which
13666 executes context-dependent commands.
13667 Each function will be called with no arguments. The function must check
13668 if the context is appropriate for it to act. If yes, it should do its
13669 thing and then return a non-nil value. If the context is wrong,
13670 just do nothing.")
13672 (defvar org-metaleft-hook nil
13673 "Hook for functions attaching themselves to `M-left'.
13674 See `org-ctrl-c-ctrl-c-hook' for more information.")
13675 (defvar org-metaright-hook nil
13676 "Hook for functions attaching themselves to `M-right'.
13677 See `org-ctrl-c-ctrl-c-hook' for more information.")
13678 (defvar org-metaup-hook nil
13679 "Hook for functions attaching themselves to `M-up'.
13680 See `org-ctrl-c-ctrl-c-hook' for more information.")
13681 (defvar org-metadown-hook nil
13682 "Hook for functions attaching themselves to `M-down'.
13683 See `org-ctrl-c-ctrl-c-hook' for more information.")
13684 (defvar org-shiftmetaleft-hook nil
13685 "Hook for functions attaching themselves to `M-S-left'.
13686 See `org-ctrl-c-ctrl-c-hook' for more information.")
13687 (defvar org-shiftmetaright-hook nil
13688 "Hook for functions attaching themselves to `M-S-right'.
13689 See `org-ctrl-c-ctrl-c-hook' for more information.")
13690 (defvar org-shiftmetaup-hook nil
13691 "Hook for functions attaching themselves to `M-S-up'.
13692 See `org-ctrl-c-ctrl-c-hook' for more information.")
13693 (defvar org-shiftmetadown-hook nil
13694 "Hook for functions attaching themselves to `M-S-down'.
13695 See `org-ctrl-c-ctrl-c-hook' for more information.")
13696 (defvar org-metareturn-hook nil
13697 "Hook for functions attaching themselves to `M-RET'.
13698 See `org-ctrl-c-ctrl-c-hook' for more information.")
13700 (defun org-modifier-cursor-error ()
13701 "Throw an error, a modified cursor command was applied in wrong context."
13702 (error "This command is active in special context like tables, headlines or items"))
13704 (defun org-shiftselect-error ()
13705 "Throw an error because Shift-Cursor command was applied in wrong context."
13706 (if (and (boundp 'shift-select-mode) shift-select-mode)
13707 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13708 (error "This command works only in special context like headlines or timestamps.")))
13710 (defun org-call-for-shift-select (cmd)
13711 (let ((this-command-keys-shift-translated t))
13712 (call-interactively cmd)))
13714 (defun org-shifttab (&optional arg)
13715 "Global visibility cycling or move to previous table field.
13716 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13717 on context.
13718 See the individual commands for more information."
13719 (interactive "P")
13720 (cond
13721 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13722 ((integerp arg)
13723 (message "Content view to level: %d" arg)
13724 (org-content (prefix-numeric-value arg))
13725 (setq org-cycle-global-status 'overview))
13726 (t (call-interactively 'org-global-cycle))))
13728 (defun org-shiftmetaleft ()
13729 "Promote subtree or delete table column.
13730 Calls `org-promote-subtree', `org-outdent-item',
13731 or `org-table-delete-column', depending on context.
13732 See the individual commands for more information."
13733 (interactive)
13734 (cond
13735 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13736 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13737 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13738 ((org-at-item-p) (call-interactively 'org-outdent-item))
13739 (t (org-modifier-cursor-error))))
13741 (defun org-shiftmetaright ()
13742 "Demote subtree or insert table column.
13743 Calls `org-demote-subtree', `org-indent-item',
13744 or `org-table-insert-column', depending on context.
13745 See the individual commands for more information."
13746 (interactive)
13747 (cond
13748 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13749 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13750 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13751 ((org-at-item-p) (call-interactively 'org-indent-item))
13752 (t (org-modifier-cursor-error))))
13754 (defun org-shiftmetaup (&optional arg)
13755 "Move subtree up or kill table row.
13756 Calls `org-move-subtree-up' or `org-table-kill-row' or
13757 `org-move-item-up' depending on context. See the individual commands
13758 for more information."
13759 (interactive "P")
13760 (cond
13761 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13762 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13763 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13764 ((org-at-item-p) (call-interactively 'org-move-item-up))
13765 (t (org-modifier-cursor-error))))
13767 (defun org-shiftmetadown (&optional arg)
13768 "Move subtree down or insert table row.
13769 Calls `org-move-subtree-down' or `org-table-insert-row' or
13770 `org-move-item-down', depending on context. See the individual
13771 commands for more information."
13772 (interactive "P")
13773 (cond
13774 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13775 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13776 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13777 ((org-at-item-p) (call-interactively 'org-move-item-down))
13778 (t (org-modifier-cursor-error))))
13780 (defun org-metaleft (&optional arg)
13781 "Promote heading or move table column to left.
13782 Calls `org-do-promote' or `org-table-move-column', depending on context.
13783 With no specific context, calls the Emacs default `backward-word'.
13784 See the individual commands for more information."
13785 (interactive "P")
13786 (cond
13787 ((run-hook-with-args-until-success 'org-metaleft-hook))
13788 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13789 ((or (org-on-heading-p)
13790 (and (org-region-active-p)
13791 (save-excursion
13792 (goto-char (region-beginning))
13793 (org-on-heading-p))))
13794 (call-interactively 'org-do-promote))
13795 ((or (org-at-item-p)
13796 (and (org-region-active-p)
13797 (save-excursion
13798 (goto-char (region-beginning))
13799 (org-at-item-p))))
13800 (call-interactively 'org-outdent-item))
13801 (t (call-interactively 'backward-word))))
13803 (defun org-metaright (&optional arg)
13804 "Demote subtree or move table column to right.
13805 Calls `org-do-demote' or `org-table-move-column', depending on context.
13806 With no specific context, calls the Emacs default `forward-word'.
13807 See the individual commands for more information."
13808 (interactive "P")
13809 (cond
13810 ((run-hook-with-args-until-success 'org-metaright-hook))
13811 ((org-at-table-p) (call-interactively 'org-table-move-column))
13812 ((or (org-on-heading-p)
13813 (and (org-region-active-p)
13814 (save-excursion
13815 (goto-char (region-beginning))
13816 (org-on-heading-p))))
13817 (call-interactively 'org-do-demote))
13818 ((or (org-at-item-p)
13819 (and (org-region-active-p)
13820 (save-excursion
13821 (goto-char (region-beginning))
13822 (org-at-item-p))))
13823 (call-interactively 'org-indent-item))
13824 (t (call-interactively 'forward-word))))
13826 (defun org-metaup (&optional arg)
13827 "Move subtree up or move table row up.
13828 Calls `org-move-subtree-up' or `org-table-move-row' or
13829 `org-move-item-up', depending on context. See the individual commands
13830 for more information."
13831 (interactive "P")
13832 (cond
13833 ((run-hook-with-args-until-success 'org-metaup-hook))
13834 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13835 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13836 ((org-at-item-p) (call-interactively 'org-move-item-up))
13837 (t (transpose-lines 1) (beginning-of-line -1))))
13839 (defun org-metadown (&optional arg)
13840 "Move subtree down or move table row down.
13841 Calls `org-move-subtree-down' or `org-table-move-row' or
13842 `org-move-item-down', depending on context. See the individual
13843 commands for more information."
13844 (interactive "P")
13845 (cond
13846 ((run-hook-with-args-until-success 'org-metadown-hook))
13847 ((org-at-table-p) (call-interactively 'org-table-move-row))
13848 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13849 ((org-at-item-p) (call-interactively 'org-move-item-down))
13850 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13852 (defun org-shiftup (&optional arg)
13853 "Increase item in timestamp or increase priority of current headline.
13854 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13855 depending on context. See the individual commands for more information."
13856 (interactive "P")
13857 (cond
13858 ((and org-support-shift-select (org-region-active-p))
13859 (org-call-for-shift-select 'previous-line))
13860 ((org-at-timestamp-p t)
13861 (call-interactively (if org-edit-timestamp-down-means-later
13862 'org-timestamp-down 'org-timestamp-up)))
13863 ((and (not (eq org-support-shift-select 'always))
13864 (org-on-heading-p))
13865 (call-interactively 'org-priority-up))
13866 ((and (not org-support-shift-select) (org-at-item-p))
13867 (call-interactively 'org-previous-item))
13868 ((org-clocktable-try-shift 'up arg))
13869 (org-support-shift-select
13870 (org-call-for-shift-select 'previous-line))
13871 (t (org-shiftselect-error))))
13873 (defun org-shiftdown (&optional arg)
13874 "Decrease item in timestamp or decrease priority of current headline.
13875 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13876 depending on context. See the individual commands for more information."
13877 (interactive "P")
13878 (cond
13879 ((and org-support-shift-select (org-region-active-p))
13880 (org-call-for-shift-select 'next-line))
13881 ((org-at-timestamp-p t)
13882 (call-interactively (if org-edit-timestamp-down-means-later
13883 'org-timestamp-up 'org-timestamp-down)))
13884 ((and (not (eq org-support-shift-select 'always))
13885 (org-on-heading-p))
13886 (call-interactively 'org-priority-down))
13887 ((and (not org-support-shift-select) (org-at-item-p))
13888 (call-interactively 'org-next-item))
13889 ((org-clocktable-try-shift 'down arg))
13890 (org-support-shift-select
13891 (org-call-for-shift-select 'next-line))
13892 (t (org-shiftselect-error))))
13894 (defun org-shiftright (&optional arg)
13895 "Cycle the thing at point or in the current line, depending on context.
13896 Depending on context, this does one of the following:
13898 - switch a timestamp at point one day into the future
13899 - on a headline, switch to the next TODO keyword.
13900 - on an item, switch entire list to the next bullet type
13901 - on a property line, switch to the next allowed value
13902 - on a clocktable definition line, move time block into the future"
13903 (interactive "P")
13904 (cond
13905 ((and org-support-shift-select (org-region-active-p))
13906 (org-call-for-shift-select 'forward-char))
13907 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13908 ((and (not (eq org-support-shift-select 'always))
13909 (org-on-heading-p))
13910 (org-call-with-arg 'org-todo 'right))
13911 ((or (and org-support-shift-select
13912 (not (eq org-support-shift-select 'always))
13913 (org-at-item-bullet-p))
13914 (and (not org-support-shift-select) (org-at-item-p)))
13915 (org-call-with-arg 'org-cycle-list-bullet nil))
13916 ((and (not (eq org-support-shift-select 'always))
13917 (org-at-property-p))
13918 (call-interactively 'org-property-next-allowed-value))
13919 ((org-clocktable-try-shift 'right arg))
13920 (org-support-shift-select
13921 (org-call-for-shift-select 'forward-char))
13922 (t (org-shiftselect-error))))
13924 (defun org-shiftleft (&optional arg)
13925 "Cycle the thing at point or in the current line, depending on context.
13926 Depending on context, this does one of the following:
13928 - switch a timestamp at point one day into the past
13929 - on a headline, switch to the previous TODO keyword.
13930 - on an item, switch entire list to the previous bullet type
13931 - on a property line, switch to the previous allowed value
13932 - on a clocktable definition line, move time block into the past"
13933 (interactive "P")
13934 (cond
13935 ((and org-support-shift-select (org-region-active-p))
13936 (org-call-for-shift-select 'backward-char))
13937 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13938 ((and (not (eq org-support-shift-select 'always))
13939 (org-on-heading-p))
13940 (org-call-with-arg 'org-todo 'left))
13941 ((or (and org-support-shift-select
13942 (not (eq org-support-shift-select 'always))
13943 (org-at-item-bullet-p))
13944 (and (not org-support-shift-select) (org-at-item-p)))
13945 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13946 ((and (not (eq org-support-shift-select 'always))
13947 (org-at-property-p))
13948 (call-interactively 'org-property-previous-allowed-value))
13949 ((org-clocktable-try-shift 'left arg))
13950 (org-support-shift-select
13951 (org-call-for-shift-select 'backward-char))
13952 (t (org-shiftselect-error))))
13954 (defun org-shiftcontrolright ()
13955 "Switch to next TODO set."
13956 (interactive)
13957 (cond
13958 ((and org-support-shift-select (org-region-active-p))
13959 (org-call-for-shift-select 'forward-word))
13960 ((and (not (eq org-support-shift-select 'always))
13961 (org-on-heading-p))
13962 (org-call-with-arg 'org-todo 'nextset))
13963 (org-support-shift-select
13964 (org-call-for-shift-select 'forward-word))
13965 (t (org-shiftselect-error))))
13967 (defun org-shiftcontrolleft ()
13968 "Switch to previous TODO set."
13969 (interactive)
13970 (cond
13971 ((and org-support-shift-select (org-region-active-p))
13972 (org-call-for-shift-select 'backward-word))
13973 ((and (not (eq org-support-shift-select 'always))
13974 (org-on-heading-p))
13975 (org-call-with-arg 'org-todo 'previousset))
13976 (org-support-shift-select
13977 (org-call-for-shift-select 'backward-word))
13978 (t (org-shiftselect-error))))
13980 (defun org-ctrl-c-ret ()
13981 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13982 (interactive)
13983 (cond
13984 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13985 (t (call-interactively 'org-insert-heading))))
13987 (defun org-copy-special ()
13988 "Copy region in table or copy current subtree.
13989 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13990 See the individual commands for more information."
13991 (interactive)
13992 (call-interactively
13993 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13995 (defun org-cut-special ()
13996 "Cut region in table or cut current subtree.
13997 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13998 See the individual commands for more information."
13999 (interactive)
14000 (call-interactively
14001 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14003 (defun org-paste-special (arg)
14004 "Paste rectangular region into table, or past subtree relative to level.
14005 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14006 See the individual commands for more information."
14007 (interactive "P")
14008 (if (org-at-table-p)
14009 (org-table-paste-rectangle)
14010 (org-paste-subtree arg)))
14012 (defun org-edit-special ()
14013 "Call a special editor for the stuff at point.
14014 When at a table, call the formula editor with `org-table-edit-formulas'.
14015 When at the first line of an src example, call `org-edit-src-code'.
14016 When in an #+include line, visit the include file. Otherwise call
14017 `ffap' to visit the file at point."
14018 (interactive)
14019 (cond
14020 ((org-at-table-p)
14021 (call-interactively 'org-table-edit-formulas))
14022 ((save-excursion
14023 (beginning-of-line 1)
14024 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14025 (find-file (org-trim (match-string 1))))
14026 ((org-edit-src-code))
14027 ((org-edit-fixed-width-region))
14028 (t (call-interactively 'ffap))))
14031 (defun org-ctrl-c-ctrl-c (&optional arg)
14032 "Set tags in headline, or update according to changed information at point.
14034 This command does many different things, depending on context:
14036 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14037 this is what we do.
14039 - If the cursor is in a headline, prompt for tags and insert them
14040 into the current line, aligned to `org-tags-column'. When called
14041 with prefix arg, realign all tags in the current buffer.
14043 - If the cursor is in one of the special #+KEYWORD lines, this
14044 triggers scanning the buffer for these lines and updating the
14045 information.
14047 - If the cursor is inside a table, realign the table. This command
14048 works even if the automatic table editor has been turned off.
14050 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14051 the entire table.
14053 - If the cursor is at a footnote reference or definition, jump to
14054 the corresponding definition or references, respectively.
14056 - If the cursor is a the beginning of a dynamic block, update it.
14058 - If the cursor is inside a table created by the table.el package,
14059 activate that table.
14061 - If the current buffer is a remember buffer, close note and file
14062 it. A prefix argument of 1 files to the default location
14063 without further interaction. A prefix argument of 2 files to
14064 the currently clocking task.
14066 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14067 links in this buffer.
14069 - If the cursor is on a numbered item in a plain list, renumber the
14070 ordered list.
14072 - If the cursor is on a checkbox, toggle it."
14073 (interactive "P")
14074 (let ((org-enable-table-editor t))
14075 (cond
14076 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14077 org-occur-highlights
14078 org-latex-fragment-image-overlays)
14079 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14080 (org-remove-occur-highlights)
14081 (org-remove-latex-fragment-image-overlays)
14082 (message "Temporary highlights/overlays removed from current buffer"))
14083 ((and (local-variable-p 'org-finish-function (current-buffer))
14084 (fboundp org-finish-function))
14085 (funcall org-finish-function))
14086 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14087 ((org-at-property-p)
14088 (call-interactively 'org-property-action))
14089 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14090 ((org-on-heading-p) (call-interactively 'org-set-tags))
14091 ((org-at-table.el-p)
14092 (require 'table)
14093 (beginning-of-line 1)
14094 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14095 (call-interactively 'table-recognize-table))
14096 ((org-at-table-p)
14097 (org-table-maybe-eval-formula)
14098 (if arg
14099 (call-interactively 'org-table-recalculate)
14100 (org-table-maybe-recalculate-line))
14101 (call-interactively 'org-table-align))
14102 ((or (org-footnote-at-reference-p)
14103 (org-footnote-at-definition-p))
14104 (call-interactively 'org-footnote-action))
14105 ((org-at-item-checkbox-p)
14106 (call-interactively 'org-toggle-checkbox))
14107 ((org-at-item-p)
14108 (if arg
14109 (call-interactively 'org-toggle-checkbox)
14110 (call-interactively 'org-maybe-renumber-ordered-list)))
14111 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14112 ;; Dynamic block
14113 (beginning-of-line 1)
14114 (save-excursion (org-update-dblock)))
14115 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14116 (cond
14117 ((equal (match-string 1) "TBLFM")
14118 ;; Recalculate the table before this line
14119 (save-excursion
14120 (beginning-of-line 1)
14121 (skip-chars-backward " \r\n\t")
14122 (if (org-at-table-p)
14123 (org-call-with-arg 'org-table-recalculate t))))
14125 ; (org-set-regexps-and-options)
14126 ; (org-restart-font-lock)
14127 (let ((org-inhibit-startup t)) (org-mode-restart))
14128 (message "Local setup has been refreshed"))))
14129 (t (error "C-c C-c can do nothing useful at this location.")))))
14131 (defun org-mode-restart ()
14132 "Restart Org-mode, to scan again for special lines.
14133 Also updates the keyword regular expressions."
14134 (interactive)
14135 (org-mode)
14136 (message "Org-mode restarted"))
14138 (defun org-kill-note-or-show-branches ()
14139 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14140 (interactive)
14141 (if (not org-finish-function)
14142 (call-interactively 'show-branches)
14143 (let ((org-note-abort t))
14144 (funcall org-finish-function))))
14146 (defun org-return (&optional indent)
14147 "Goto next table row or insert a newline.
14148 Calls `org-table-next-row' or `newline', depending on context.
14149 See the individual commands for more information."
14150 (interactive)
14151 (cond
14152 ((bobp) (if indent (newline-and-indent) (newline)))
14153 ((org-at-table-p)
14154 (org-table-justify-field-maybe)
14155 (call-interactively 'org-table-next-row))
14156 ((and org-return-follows-link
14157 (eq (get-text-property (point) 'face) 'org-link))
14158 (call-interactively 'org-open-at-point))
14159 ((and (org-at-heading-p)
14160 (looking-at
14161 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14162 (org-show-entry)
14163 (end-of-line 1)
14164 (newline))
14165 (t (if indent (newline-and-indent) (newline)))))
14167 (defun org-return-indent ()
14168 "Goto next table row or insert a newline and indent.
14169 Calls `org-table-next-row' or `newline-and-indent', depending on
14170 context. See the individual commands for more information."
14171 (interactive)
14172 (org-return t))
14174 (defun org-ctrl-c-star ()
14175 "Compute table, or change heading status of lines.
14176 Calls `org-table-recalculate' or `org-toggle-heading',
14177 depending on context."
14178 (interactive)
14179 (cond
14180 ((org-at-table-p)
14181 (call-interactively 'org-table-recalculate))
14183 ;; Convert all lines in region to list items
14184 (call-interactively 'org-toggle-heading))))
14186 (defun org-ctrl-c-minus ()
14187 "Insert separator line in table or modify bullet status of line.
14188 Also turns a plain line or a region of lines into list items.
14189 Calls `org-table-insert-hline', `org-toggle-item', or
14190 `org-cycle-list-bullet', depending on context."
14191 (interactive)
14192 (cond
14193 ((org-at-table-p)
14194 (call-interactively 'org-table-insert-hline))
14195 ((org-region-active-p)
14196 (call-interactively 'org-toggle-item))
14197 ((org-in-item-p)
14198 (call-interactively 'org-cycle-list-bullet))
14200 (call-interactively 'org-toggle-item))))
14202 (defun org-toggle-item ()
14203 "Convert headings or normal lines to items, items to normal lines.
14204 If there is no active region, only the current line is considered.
14206 If the first line in the region is a headline, convert all headlines to items.
14208 If the first line in the region is an item, convert all items to normal lines.
14210 If the first line is normal text, add an item bullet to each line."
14211 (interactive)
14212 (let (l2 l beg end)
14213 (if (org-region-active-p)
14214 (setq beg (region-beginning) end (region-end))
14215 (setq beg (point-at-bol)
14216 end (min (1+ (point-at-eol)) (point-max))))
14217 (save-excursion
14218 (goto-char end)
14219 (setq l2 (org-current-line))
14220 (goto-char beg)
14221 (beginning-of-line 1)
14222 (setq l (1- (org-current-line)))
14223 (if (org-at-item-p)
14224 ;; We already have items, de-itemize
14225 (while (< (setq l (1+ l)) l2)
14226 (when (org-at-item-p)
14227 (goto-char (match-beginning 2))
14228 (delete-region (match-beginning 2) (match-end 2))
14229 (and (looking-at "[ \t]+") (replace-match "")))
14230 (beginning-of-line 2))
14231 (if (org-on-heading-p)
14232 ;; Headings, convert to items
14233 (while (< (setq l (1+ l)) l2)
14234 (if (looking-at org-outline-regexp)
14235 (replace-match "- " t t))
14236 (beginning-of-line 2))
14237 ;; normal lines, turn them into items
14238 (while (< (setq l (1+ l)) l2)
14239 (unless (org-at-item-p)
14240 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14241 (replace-match "\\1- \\2")))
14242 (beginning-of-line 2)))))))
14244 (defun org-toggle-heading (&optional nstars)
14245 "Convert headings to normal text, or items or text to headings.
14246 If there is no active region, only the current line is considered.
14248 If the first line is a heading, remove the stars from all headlines
14249 in the region.
14251 If the first line is a plain list item, turn all plain list items into
14252 headings.
14254 If the first line is a normal line, turn each and every line in the region
14255 into a heading.
14257 When converting a line into a heading, the number of stars is chosen
14258 such that the lines become children of the current entry. However, when
14259 a prefix argument is given, its value determines the number of stars to add."
14260 (interactive "P")
14261 (let (l2 l itemp beg end)
14262 (if (org-region-active-p)
14263 (setq beg (region-beginning) end (region-end))
14264 (setq beg (point-at-bol)
14265 end (min (1+ (point-at-eol)) (point-max))))
14266 (save-excursion
14267 (goto-char end)
14268 (setq l2 (org-current-line))
14269 (goto-char beg)
14270 (beginning-of-line 1)
14271 (setq l (1- (org-current-line)))
14272 (if (org-on-heading-p)
14273 ;; We already have headlines, de-star them
14274 (while (< (setq l (1+ l)) l2)
14275 (when (org-on-heading-p t)
14276 (and (looking-at outline-regexp) (replace-match "")))
14277 (beginning-of-line 2))
14278 (setq itemp (org-at-item-p))
14279 (let* ((stars
14280 (if nstars
14281 (make-string (prefix-numeric-value current-prefix-arg)
14283 (save-excursion
14284 (re-search-backward org-complex-heading-regexp nil t)
14285 (or (match-string 1) ""))))
14286 (add-stars (cond (nstars "")
14287 ((equal stars "") "*")
14288 (org-odd-levels-only "**")
14289 (t "*")))
14290 (rpl (concat stars add-stars " ")))
14291 (while (< (setq l (1+ l)) l2)
14292 (if itemp
14293 (and (org-at-item-p) (replace-match rpl t t))
14294 (unless (org-on-heading-p)
14295 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14296 (replace-match (concat rpl (match-string 2))))))
14297 (beginning-of-line 2)))))))
14299 (defun org-meta-return (&optional arg)
14300 "Insert a new heading or wrap a region in a table.
14301 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14302 See the individual commands for more information."
14303 (interactive "P")
14304 (cond
14305 ((run-hook-with-args-until-success 'org-metareturn-hook))
14306 ((org-at-table-p)
14307 (call-interactively 'org-table-wrap-region))
14308 (t (call-interactively 'org-insert-heading))))
14310 ;;; Menu entries
14312 ;; Define the Org-mode menus
14313 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14314 '("Tbl"
14315 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14316 ["Next Field" org-cycle (org-at-table-p)]
14317 ["Previous Field" org-shifttab (org-at-table-p)]
14318 ["Next Row" org-return (org-at-table-p)]
14319 "--"
14320 ["Blank Field" org-table-blank-field (org-at-table-p)]
14321 ["Edit Field" org-table-edit-field (org-at-table-p)]
14322 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14323 "--"
14324 ("Column"
14325 ["Move Column Left" org-metaleft (org-at-table-p)]
14326 ["Move Column Right" org-metaright (org-at-table-p)]
14327 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14328 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14329 ("Row"
14330 ["Move Row Up" org-metaup (org-at-table-p)]
14331 ["Move Row Down" org-metadown (org-at-table-p)]
14332 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14333 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14334 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14335 "--"
14336 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14337 ("Rectangle"
14338 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14339 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14340 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14341 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14342 "--"
14343 ("Calculate"
14344 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14345 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14346 ["Edit Formulas" org-edit-special (org-at-table-p)]
14347 "--"
14348 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14349 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14350 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14351 "--"
14352 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14353 "--"
14354 ["Sum Column/Rectangle" org-table-sum
14355 (or (org-at-table-p) (org-region-active-p))]
14356 ["Which Column?" org-table-current-column (org-at-table-p)])
14357 ["Debug Formulas"
14358 org-table-toggle-formula-debugger
14359 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14360 ["Show Col/Row Numbers"
14361 org-table-toggle-coordinate-overlays
14362 :style toggle
14363 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14364 "--"
14365 ["Create" org-table-create (and (not (org-at-table-p))
14366 org-enable-table-editor)]
14367 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14368 ["Import from File" org-table-import (not (org-at-table-p))]
14369 ["Export to File" org-table-export (org-at-table-p)]
14370 "--"
14371 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14373 (easy-menu-define org-org-menu org-mode-map "Org menu"
14374 '("Org"
14375 ("Show/Hide"
14376 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14377 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14378 ["Sparse Tree..." org-sparse-tree t]
14379 ["Reveal Context" org-reveal t]
14380 ["Show All" show-all t]
14381 "--"
14382 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14383 "--"
14384 ["New Heading" org-insert-heading t]
14385 ("Navigate Headings"
14386 ["Up" outline-up-heading t]
14387 ["Next" outline-next-visible-heading t]
14388 ["Previous" outline-previous-visible-heading t]
14389 ["Next Same Level" outline-forward-same-level t]
14390 ["Previous Same Level" outline-backward-same-level t]
14391 "--"
14392 ["Jump" org-goto t])
14393 ("Edit Structure"
14394 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14395 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14396 "--"
14397 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14398 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14399 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14400 "--"
14401 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14402 "--"
14403 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14404 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14405 ["Demote Heading" org-metaright (not (org-at-table-p))]
14406 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14407 "--"
14408 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14409 "--"
14410 ["Convert to odd levels" org-convert-to-odd-levels t]
14411 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14412 ("Editing"
14413 ["Emphasis..." org-emphasize t]
14414 ["Edit Source Example" org-edit-special t]
14415 "--"
14416 ["Footnote new/jump" org-footnote-action t]
14417 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14418 ("Archive"
14419 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14420 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14421 ; :active t :keys "C-u C-c C-x C-a"]
14422 ["Sparse trees open ARCHIVE trees"
14423 (setq org-sparse-tree-open-archived-trees
14424 (not org-sparse-tree-open-archived-trees))
14425 :style toggle :selected org-sparse-tree-open-archived-trees]
14426 ["Cycling opens ARCHIVE trees"
14427 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14428 :style toggle :selected org-cycle-open-archived-trees]
14429 "--"
14430 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14431 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14432 ; ["Check and Move Children" (org-archive-subtree '(4))
14433 ; :active t :keys "C-u C-c C-x C-s"]
14435 "--"
14436 ("TODO Lists"
14437 ["TODO/DONE/-" org-todo t]
14438 ("Select keyword"
14439 ["Next keyword" org-shiftright (org-on-heading-p)]
14440 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14441 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14442 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14443 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14444 ["Show TODO Tree" org-show-todo-tree t]
14445 ["Global TODO list" org-todo-list t]
14446 "--"
14447 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14448 :selected org-enforce-todo-dependencies :style toggle :active t]
14449 "Settings for tree at point"
14450 ["Do Children sequentially" org-toggle-ordered-property :style radio
14451 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14452 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14453 ["Do Children parallel" org-toggle-ordered-property :style radio
14454 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14455 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14456 "--"
14457 ["Set Priority" org-priority t]
14458 ["Priority Up" org-shiftup t]
14459 ["Priority Down" org-shiftdown t]
14460 "--"
14461 ["Get news from all feeds" org-feed-update-all t]
14462 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
14463 ["Customize feeds" (customize-variable 'org-feed-alist) t])
14464 ("TAGS and Properties"
14465 ["Set Tags" org-set-tags-command t]
14466 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14467 "--"
14468 ["Set property" org-set-property t]
14469 ["Column view of properties" org-columns t]
14470 ["Insert Column View DBlock" org-insert-columns-dblock t])
14471 ("Dates and Scheduling"
14472 ["Timestamp" org-time-stamp t]
14473 ["Timestamp (inactive)" org-time-stamp-inactive t]
14474 ("Change Date"
14475 ["1 Day Later" org-shiftright t]
14476 ["1 Day Earlier" org-shiftleft t]
14477 ["1 ... Later" org-shiftup t]
14478 ["1 ... Earlier" org-shiftdown t])
14479 ["Compute Time Range" org-evaluate-time-range t]
14480 ["Schedule Item" org-schedule t]
14481 ["Deadline" org-deadline t]
14482 "--"
14483 ["Custom time format" org-toggle-time-stamp-overlays
14484 :style radio :selected org-display-custom-times]
14485 "--"
14486 ["Goto Calendar" org-goto-calendar t]
14487 ["Date from Calendar" org-date-from-calendar t]
14488 "--"
14489 ["Start/Restart Timer" org-timer-start t]
14490 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14491 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14492 ["Insert Timer String" org-timer t]
14493 ["Insert Timer Item" org-timer-item t])
14494 ("Logging work"
14495 ["Clock in" org-clock-in t]
14496 ["Clock out" org-clock-out t]
14497 ["Clock cancel" org-clock-cancel t]
14498 ["Goto running clock" org-clock-goto t]
14499 ["Display times" org-clock-display t]
14500 ["Create clock table" org-clock-report t]
14501 "--"
14502 ["Record DONE time"
14503 (progn (setq org-log-done (not org-log-done))
14504 (message "Switching to %s will %s record a timestamp"
14505 (car org-done-keywords)
14506 (if org-log-done "automatically" "not")))
14507 :style toggle :selected org-log-done])
14508 "--"
14509 ["Agenda Command..." org-agenda t]
14510 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14511 ("File List for Agenda")
14512 ("Special views current file"
14513 ["TODO Tree" org-show-todo-tree t]
14514 ["Check Deadlines" org-check-deadlines t]
14515 ["Timeline" org-timeline t]
14516 ["Tags/Property tree" org-match-sparse-tree t])
14517 "--"
14518 ("Hyperlinks"
14519 ["Store Link (Global)" org-store-link t]
14520 ["Insert Link" org-insert-link t]
14521 ["Follow Link" org-open-at-point t]
14522 "--"
14523 ["Next link" org-next-link t]
14524 ["Previous link" org-previous-link t]
14525 "--"
14526 ["Descriptive Links"
14527 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14528 :style radio
14529 :selected (member '(org-link) buffer-invisibility-spec)]
14530 ["Literal Links"
14531 (progn
14532 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14533 :style radio
14534 :selected (not (member '(org-link) buffer-invisibility-spec))])
14535 "--"
14536 ["Export/Publish..." org-export t]
14537 ("LaTeX"
14538 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14539 :selected org-cdlatex-mode]
14540 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14541 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14542 ["Modify math symbol" org-cdlatex-math-modify
14543 (org-inside-LaTeX-fragment-p)]
14544 ["Export LaTeX fragments as images"
14545 (if (featurep 'org-exp)
14546 (setq org-export-with-LaTeX-fragments
14547 (not org-export-with-LaTeX-fragments))
14548 (require 'org-exp))
14549 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14550 org-export-with-LaTeX-fragments)])
14551 "--"
14552 ("Documentation"
14553 ["Show Version" org-version t]
14554 ["Info Documentation" org-info t])
14555 ("Customize"
14556 ["Browse Org Group" org-customize t]
14557 "--"
14558 ["Expand This Menu" org-create-customize-menu
14559 (fboundp 'customize-menu-create)])
14560 "--"
14561 ("Refresh/Reload"
14562 ["Refresh setup current buffer" org-mode-restart t]
14563 ["Reload Org (after update)" org-reload t]
14564 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14567 (defun org-info (&optional node)
14568 "Read documentation for Org-mode in the info system.
14569 With optional NODE, go directly to that node."
14570 (interactive)
14571 (info (format "(org)%s" (or node ""))))
14573 (defun org-install-agenda-files-menu ()
14574 (let ((bl (buffer-list)))
14575 (save-excursion
14576 (while bl
14577 (set-buffer (pop bl))
14578 (if (org-mode-p) (setq bl nil)))
14579 (when (org-mode-p)
14580 (easy-menu-change
14581 '("Org") "File List for Agenda"
14582 (append
14583 (list
14584 ["Edit File List" (org-edit-agenda-file-list) t]
14585 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14586 ["Remove Current File from List" org-remove-file t]
14587 ["Cycle through agenda files" org-cycle-agenda-files t]
14588 ["Occur in all agenda files" org-occur-in-agenda-files t]
14589 "--")
14590 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14592 ;;;; Documentation
14594 ;;;###autoload
14595 (defun org-require-autoloaded-modules ()
14596 (interactive)
14597 (mapc 'require
14598 '(org-agenda org-archive org-attach org-clock org-colview
14599 org-exp org-id org-export-latex org-docbook.el
14600 org-publish org-remember org-table org-timer)))
14602 ;;;###autoload
14603 (defun org-reload (&optional uncompiled)
14604 "Reload all org lisp files.
14605 With prefix arg UNCOMPILED, load the uncompiled versions."
14606 (interactive "P")
14607 (require 'find-func)
14608 (let* ((dir (file-name-directory (find-library-name "org")))
14609 (files (directory-files dir t "\\.el\\'"))
14610 (remove-re (concat (if (featurep 'xemacs)
14611 "org-colview" "org-colview-xemacs")
14612 "\\'")))
14613 (setq files (mapcar 'file-name-sans-extension files))
14614 (setq files (mapcar
14615 (lambda (x) (if (string-match remove-re x) nil x))
14616 files))
14617 (setq files (delq nil files))
14618 (mapc
14619 (lambda (f)
14620 (if (and (not uncompiled)
14621 (file-exists-p (concat f ".elc")))
14622 (load (concat f ".elc") nil nil t)
14623 (load (concat f ".el") nil nil t)))
14624 files)))
14626 ;;;###autoload
14627 (defun org-customize ()
14628 "Call the customize function with org as argument."
14629 (interactive)
14630 (org-load-modules-maybe)
14631 (org-require-autoloaded-modules)
14632 (customize-browse 'org))
14634 (defun org-create-customize-menu ()
14635 "Create a full customization menu for Org-mode, insert it into the menu."
14636 (interactive)
14637 (org-load-modules-maybe)
14638 (org-require-autoloaded-modules)
14639 (if (fboundp 'customize-menu-create)
14640 (progn
14641 (easy-menu-change
14642 '("Org") "Customize"
14643 `(["Browse Org group" org-customize t]
14644 "--"
14645 ,(customize-menu-create 'org)
14646 ["Set" Custom-set t]
14647 ["Save" Custom-save t]
14648 ["Reset to Current" Custom-reset-current t]
14649 ["Reset to Saved" Custom-reset-saved t]
14650 ["Reset to Standard Settings" Custom-reset-standard t]))
14651 (message "\"Org\"-menu now contains full customization menu"))
14652 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14654 ;;;; Miscellaneous stuff
14656 ;;; Generally useful functions
14658 (defun org-find-text-property-in-string (prop s)
14659 "Return the first non-nil value of property PROP in string S."
14660 (or (get-text-property 0 prop s)
14661 (get-text-property (or (next-single-property-change 0 prop s) 0)
14662 prop s)))
14664 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14665 "Display the given MESSAGE as a warning."
14666 (if (fboundp 'display-warning)
14667 (display-warning 'org message
14668 (if (featurep 'xemacs)
14669 'warning
14670 :warning))
14671 (let ((buf (get-buffer-create "*Org warnings*")))
14672 (with-current-buffer buf
14673 (goto-char (point-max))
14674 (insert "Warning (Org): " message)
14675 (unless (bolp)
14676 (newline)))
14677 (display-buffer buf)
14678 (sit-for 0))))
14680 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14681 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14682 (if (and marker (marker-buffer marker)
14683 (buffer-live-p (marker-buffer marker)))
14684 (progn
14685 (switch-to-buffer (marker-buffer marker))
14686 (if (or (> marker (point-max)) (< marker (point-min)))
14687 (widen))
14688 (goto-char marker)
14689 (org-show-context 'org-goto))
14690 (if bookmark
14691 (bookmark-jump bookmark)
14692 (error "Cannot find location"))))
14694 (defun org-quote-csv-field (s)
14695 "Quote field for inclusion in CSV material."
14696 (if (string-match "[\",]" s)
14697 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14700 (defun org-plist-delete (plist property)
14701 "Delete PROPERTY from PLIST.
14702 This is in contrast to merely setting it to 0."
14703 (let (p)
14704 (while plist
14705 (if (not (eq property (car plist)))
14706 (setq p (plist-put p (car plist) (nth 1 plist))))
14707 (setq plist (cddr plist)))
14710 (defun org-force-self-insert (N)
14711 "Needed to enforce self-insert under remapping."
14712 (interactive "p")
14713 (self-insert-command N))
14715 (defun org-string-width (s)
14716 "Compute width of string, ignoring invisible characters.
14717 This ignores character with invisibility property `org-link', and also
14718 characters with property `org-cwidth', because these will become invisible
14719 upon the next fontification round."
14720 (let (b l)
14721 (when (or (eq t buffer-invisibility-spec)
14722 (assq 'org-link buffer-invisibility-spec))
14723 (while (setq b (text-property-any 0 (length s)
14724 'invisible 'org-link s))
14725 (setq s (concat (substring s 0 b)
14726 (substring s (or (next-single-property-change
14727 b 'invisible s) (length s)))))))
14728 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14729 (setq s (concat (substring s 0 b)
14730 (substring s (or (next-single-property-change
14731 b 'org-cwidth s) (length s))))))
14732 (setq l (string-width s) b -1)
14733 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14734 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14737 (defun org-get-indentation (&optional line)
14738 "Get the indentation of the current line, interpreting tabs.
14739 When LINE is given, assume it represents a line and compute its indentation."
14740 (if line
14741 (if (string-match "^ *" (org-remove-tabs line))
14742 (match-end 0))
14743 (save-excursion
14744 (beginning-of-line 1)
14745 (skip-chars-forward " \t")
14746 (current-column))))
14748 (defun org-remove-tabs (s &optional width)
14749 "Replace tabulators in S with spaces.
14750 Assumes that s is a single line, starting in column 0."
14751 (setq width (or width tab-width))
14752 (while (string-match "\t" s)
14753 (setq s (replace-match
14754 (make-string
14755 (- (* width (/ (+ (match-beginning 0) width) width))
14756 (match-beginning 0)) ?\ )
14757 t t s)))
14760 (defun org-fix-indentation (line ind)
14761 "Fix indentation in LINE.
14762 IND is a cons cell with target and minimum indentation.
14763 If the current indentation in LINE is smaller than the minimum,
14764 leave it alone. If it is larger than ind, set it to the target."
14765 (let* ((l (org-remove-tabs line))
14766 (i (org-get-indentation l))
14767 (i1 (car ind)) (i2 (cdr ind)))
14768 (if (>= i i2) (setq l (substring line i2)))
14769 (if (> i1 0)
14770 (concat (make-string i1 ?\ ) l)
14771 l)))
14773 (defun org-base-buffer (buffer)
14774 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14775 (if (not buffer)
14776 buffer
14777 (or (buffer-base-buffer buffer)
14778 buffer)))
14780 (defun org-trim (s)
14781 "Remove whitespace at beginning and end of string."
14782 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14783 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14786 (defun org-wrap (string &optional width lines)
14787 "Wrap string to either a number of lines, or a width in characters.
14788 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14789 that costs. If there is a word longer than WIDTH, the text is actually
14790 wrapped to the length of that word.
14791 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14792 many lines, whatever width that takes.
14793 The return value is a list of lines, without newlines at the end."
14794 (let* ((words (org-split-string string "[ \t\n]+"))
14795 (maxword (apply 'max (mapcar 'org-string-width words)))
14796 w ll)
14797 (cond (width
14798 (org-do-wrap words (max maxword width)))
14799 (lines
14800 (setq w maxword)
14801 (setq ll (org-do-wrap words maxword))
14802 (if (<= (length ll) lines)
14804 (setq ll words)
14805 (while (> (length ll) lines)
14806 (setq w (1+ w))
14807 (setq ll (org-do-wrap words w)))
14808 ll))
14809 (t (error "Cannot wrap this")))))
14811 (defun org-do-wrap (words width)
14812 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14813 (let (lines line)
14814 (while words
14815 (setq line (pop words))
14816 (while (and words (< (+ (length line) (length (car words))) width))
14817 (setq line (concat line " " (pop words))))
14818 (setq lines (push line lines)))
14819 (nreverse lines)))
14821 (defun org-split-string (string &optional separators)
14822 "Splits STRING into substrings at SEPARATORS.
14823 No empty strings are returned if there are matches at the beginning
14824 and end of string."
14825 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14826 (start 0)
14827 notfirst
14828 (list nil))
14829 (while (and (string-match rexp string
14830 (if (and notfirst
14831 (= start (match-beginning 0))
14832 (< start (length string)))
14833 (1+ start) start))
14834 (< (match-beginning 0) (length string)))
14835 (setq notfirst t)
14836 (or (eq (match-beginning 0) 0)
14837 (and (eq (match-beginning 0) (match-end 0))
14838 (eq (match-beginning 0) start))
14839 (setq list
14840 (cons (substring string start (match-beginning 0))
14841 list)))
14842 (setq start (match-end 0)))
14843 (or (eq start (length string))
14844 (setq list
14845 (cons (substring string start)
14846 list)))
14847 (nreverse list)))
14849 (defun org-uuidgen-p (s)
14850 "Is S an ID created by UUIDGEN?"
14851 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
14853 (defun org-context ()
14854 "Return a list of contexts of the current cursor position.
14855 If several contexts apply, all are returned.
14856 Each context entry is a list with a symbol naming the context, and
14857 two positions indicating start and end of the context. Possible
14858 contexts are:
14860 :headline anywhere in a headline
14861 :headline-stars on the leading stars in a headline
14862 :todo-keyword on a TODO keyword (including DONE) in a headline
14863 :tags on the TAGS in a headline
14864 :priority on the priority cookie in a headline
14865 :item on the first line of a plain list item
14866 :item-bullet on the bullet/number of a plain list item
14867 :checkbox on the checkbox in a plain list item
14868 :table in an org-mode table
14869 :table-special on a special filed in a table
14870 :table-table in a table.el table
14871 :link on a hyperlink
14872 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14873 :target on a <<target>>
14874 :radio-target on a <<<radio-target>>>
14875 :latex-fragment on a LaTeX fragment
14876 :latex-preview on a LaTeX fragment with overlayed preview image
14878 This function expects the position to be visible because it uses font-lock
14879 faces as a help to recognize the following contexts: :table-special, :link,
14880 and :keyword."
14881 (let* ((f (get-text-property (point) 'face))
14882 (faces (if (listp f) f (list f)))
14883 (p (point)) clist o)
14884 ;; First the large context
14885 (cond
14886 ((org-on-heading-p t)
14887 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14888 (when (progn
14889 (beginning-of-line 1)
14890 (looking-at org-todo-line-tags-regexp))
14891 (push (org-point-in-group p 1 :headline-stars) clist)
14892 (push (org-point-in-group p 2 :todo-keyword) clist)
14893 (push (org-point-in-group p 4 :tags) clist))
14894 (goto-char p)
14895 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14896 (if (looking-at "\\[#[A-Z0-9]\\]")
14897 (push (org-point-in-group p 0 :priority) clist)))
14899 ((org-at-item-p)
14900 (push (org-point-in-group p 2 :item-bullet) clist)
14901 (push (list :item (point-at-bol)
14902 (save-excursion (org-end-of-item) (point)))
14903 clist)
14904 (and (org-at-item-checkbox-p)
14905 (push (org-point-in-group p 0 :checkbox) clist)))
14907 ((org-at-table-p)
14908 (push (list :table (org-table-begin) (org-table-end)) clist)
14909 (if (memq 'org-formula faces)
14910 (push (list :table-special
14911 (previous-single-property-change p 'face)
14912 (next-single-property-change p 'face)) clist)))
14913 ((org-at-table-p 'any)
14914 (push (list :table-table) clist)))
14915 (goto-char p)
14917 ;; Now the small context
14918 (cond
14919 ((org-at-timestamp-p)
14920 (push (org-point-in-group p 0 :timestamp) clist))
14921 ((memq 'org-link faces)
14922 (push (list :link
14923 (previous-single-property-change p 'face)
14924 (next-single-property-change p 'face)) clist))
14925 ((memq 'org-special-keyword faces)
14926 (push (list :keyword
14927 (previous-single-property-change p 'face)
14928 (next-single-property-change p 'face)) clist))
14929 ((org-on-target-p)
14930 (push (org-point-in-group p 0 :target) clist)
14931 (goto-char (1- (match-beginning 0)))
14932 (if (looking-at org-radio-target-regexp)
14933 (push (org-point-in-group p 0 :radio-target) clist))
14934 (goto-char p))
14935 ((setq o (car (delq nil
14936 (mapcar
14937 (lambda (x)
14938 (if (memq x org-latex-fragment-image-overlays) x))
14939 (org-overlays-at (point))))))
14940 (push (list :latex-fragment
14941 (org-overlay-start o) (org-overlay-end o)) clist)
14942 (push (list :latex-preview
14943 (org-overlay-start o) (org-overlay-end o)) clist))
14944 ((org-inside-LaTeX-fragment-p)
14945 ;; FIXME: positions wrong.
14946 (push (list :latex-fragment (point) (point)) clist)))
14948 (setq clist (nreverse (delq nil clist)))
14949 clist))
14951 ;; FIXME: Compare with at-regexp-p Do we need both?
14952 (defun org-in-regexp (re &optional nlines visually)
14953 "Check if point is inside a match of regexp.
14954 Normally only the current line is checked, but you can include NLINES extra
14955 lines both before and after point into the search.
14956 If VISUALLY is set, require that the cursor is not after the match but
14957 really on, so that the block visually is on the match."
14958 (catch 'exit
14959 (let ((pos (point))
14960 (eol (point-at-eol (+ 1 (or nlines 0))))
14961 (inc (if visually 1 0)))
14962 (save-excursion
14963 (beginning-of-line (- 1 (or nlines 0)))
14964 (while (re-search-forward re eol t)
14965 (if (and (<= (match-beginning 0) pos)
14966 (>= (+ inc (match-end 0)) pos))
14967 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14969 (defun org-at-regexp-p (regexp)
14970 "Is point inside a match of REGEXP in the current line?"
14971 (catch 'exit
14972 (save-excursion
14973 (let ((pos (point)) (end (point-at-eol)))
14974 (beginning-of-line 1)
14975 (while (re-search-forward regexp end t)
14976 (if (and (<= (match-beginning 0) pos)
14977 (>= (match-end 0) pos))
14978 (throw 'exit t)))
14979 nil))))
14981 (defun org-occur-in-agenda-files (regexp &optional nlines)
14982 "Call `multi-occur' with buffers for all agenda files."
14983 (interactive "sOrg-files matching: \np")
14984 (let* ((files (org-agenda-files))
14985 (tnames (mapcar 'file-truename files))
14986 (extra org-agenda-text-search-extra-files)
14988 (when (eq (car extra) 'agenda-archives)
14989 (setq extra (cdr extra))
14990 (setq files (org-add-archive-files files)))
14991 (while (setq f (pop extra))
14992 (unless (member (file-truename f) tnames)
14993 (add-to-list 'files f 'append)
14994 (add-to-list 'tnames (file-truename f) 'append)))
14995 (multi-occur
14996 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14997 regexp)))
14999 (if (boundp 'occur-mode-find-occurrence-hook)
15000 ;; Emacs 23
15001 (add-hook 'occur-mode-find-occurrence-hook
15002 (lambda ()
15003 (when (org-mode-p)
15004 (org-reveal))))
15005 ;; Emacs 22
15006 (defadvice occur-mode-goto-occurrence
15007 (after org-occur-reveal activate)
15008 (and (org-mode-p) (org-reveal)))
15009 (defadvice occur-mode-goto-occurrence-other-window
15010 (after org-occur-reveal activate)
15011 (and (org-mode-p) (org-reveal)))
15012 (defadvice occur-mode-display-occurrence
15013 (after org-occur-reveal activate)
15014 (when (org-mode-p)
15015 (let ((pos (occur-mode-find-occurrence)))
15016 (with-current-buffer (marker-buffer pos)
15017 (save-excursion
15018 (goto-char pos)
15019 (org-reveal)))))))
15021 (defun org-uniquify (list)
15022 "Remove duplicate elements from LIST."
15023 (let (res)
15024 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15025 res))
15027 (defun org-delete-all (elts list)
15028 "Remove all elements in ELTS from LIST."
15029 (while elts
15030 (setq list (delete (pop elts) list)))
15031 list)
15033 (defun org-back-over-empty-lines ()
15034 "Move backwards over whitespace, to the beginning of the first empty line.
15035 Returns the number of empty lines passed."
15036 (let ((pos (point)))
15037 (skip-chars-backward " \t\n\r")
15038 (beginning-of-line 2)
15039 (goto-char (min (point) pos))
15040 (count-lines (point) pos)))
15042 (defun org-skip-whitespace ()
15043 (skip-chars-forward " \t\n\r"))
15045 (defun org-point-in-group (point group &optional context)
15046 "Check if POINT is in match-group GROUP.
15047 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15048 match. If the match group does ot exist or point is not inside it,
15049 return nil."
15050 (and (match-beginning group)
15051 (>= point (match-beginning group))
15052 (<= point (match-end group))
15053 (if context
15054 (list context (match-beginning group) (match-end group))
15055 t)))
15057 (defun org-switch-to-buffer-other-window (&rest args)
15058 "Switch to buffer in a second window on the current frame.
15059 In particular, do not allow pop-up frames."
15060 (let (pop-up-frames special-display-buffer-names special-display-regexps
15061 special-display-function)
15062 (apply 'switch-to-buffer-other-window args)))
15064 (defun org-combine-plists (&rest plists)
15065 "Create a single property list from all plists in PLISTS.
15066 The process starts by copying the first list, and then setting properties
15067 from the other lists. Settings in the last list are the most significant
15068 ones and overrule settings in the other lists."
15069 (let ((rtn (copy-sequence (pop plists)))
15070 p v ls)
15071 (while plists
15072 (setq ls (pop plists))
15073 (while ls
15074 (setq p (pop ls) v (pop ls))
15075 (setq rtn (plist-put rtn p v))))
15076 rtn))
15078 (defun org-move-line-down (arg)
15079 "Move the current line down. With prefix argument, move it past ARG lines."
15080 (interactive "p")
15081 (let ((col (current-column))
15082 beg end pos)
15083 (beginning-of-line 1) (setq beg (point))
15084 (beginning-of-line 2) (setq end (point))
15085 (beginning-of-line (+ 1 arg))
15086 (setq pos (move-marker (make-marker) (point)))
15087 (insert (delete-and-extract-region beg end))
15088 (goto-char pos)
15089 (org-move-to-column col)))
15091 (defun org-move-line-up (arg)
15092 "Move the current line up. With prefix argument, move it past ARG lines."
15093 (interactive "p")
15094 (let ((col (current-column))
15095 beg end pos)
15096 (beginning-of-line 1) (setq beg (point))
15097 (beginning-of-line 2) (setq end (point))
15098 (beginning-of-line (- arg))
15099 (setq pos (move-marker (make-marker) (point)))
15100 (insert (delete-and-extract-region beg end))
15101 (goto-char pos)
15102 (org-move-to-column col)))
15104 (defun org-replace-escapes (string table)
15105 "Replace %-escapes in STRING with values in TABLE.
15106 TABLE is an association list with keys like \"%a\" and string values.
15107 The sequences in STRING may contain normal field width and padding information,
15108 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15109 so values can contain further %-escapes if they are define later in TABLE."
15110 (let ((case-fold-search nil)
15111 e re rpl)
15112 (while (setq e (pop table))
15113 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15114 (while (string-match re string)
15115 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15116 (cdr e)))
15117 (setq string (replace-match rpl t t string))))
15118 string))
15121 (defun org-sublist (list start end)
15122 "Return a section of LIST, from START to END.
15123 Counting starts at 1."
15124 (let (rtn (c start))
15125 (setq list (nthcdr (1- start) list))
15126 (while (and list (<= c end))
15127 (push (pop list) rtn)
15128 (setq c (1+ c)))
15129 (nreverse rtn)))
15131 (defun org-find-base-buffer-visiting (file)
15132 "Like `find-buffer-visiting' but alway return the base buffer and
15133 not an indirect buffer."
15134 (let ((buf (find-buffer-visiting file)))
15135 (if buf
15136 (or (buffer-base-buffer buf) buf)
15137 nil)))
15139 (defun org-image-file-name-regexp (&optional extensions)
15140 "Return regexp matching the file names of images.
15141 If EXTENSIONS is given, only match these."
15142 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15143 (image-file-name-regexp)
15144 (let ((image-file-name-extensions
15145 (or extensions
15146 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15147 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15148 (concat "\\."
15149 (regexp-opt (nconc (mapcar 'upcase
15150 image-file-name-extensions)
15151 image-file-name-extensions)
15153 "\\'"))))
15155 (defun org-file-image-p (file &optional extensions)
15156 "Return non-nil if FILE is an image."
15157 (save-match-data
15158 (string-match (org-image-file-name-regexp extensions) file)))
15160 (defun org-get-cursor-date ()
15161 "Return the date at cursor in as a time.
15162 This works in the calendar and in the agenda, anywhere else it just
15163 returns the current time."
15164 (let (date day defd)
15165 (cond
15166 ((eq major-mode 'calendar-mode)
15167 (setq date (calendar-cursor-to-date)
15168 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15169 ((eq major-mode 'org-agenda-mode)
15170 (setq day (get-text-property (point) 'day))
15171 (if day
15172 (setq date (calendar-gregorian-from-absolute day)
15173 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15174 (nth 2 date))))))
15175 (or defd (current-time))))
15177 (defvar org-agenda-action-marker (make-marker)
15178 "Marker pointing to the entry for the next agenda action.")
15180 (defun org-mark-entry-for-agenda-action ()
15181 "Mark the current entry as target of an agenda action.
15182 Agenda actions are actions executed from the agenda with the key `k',
15183 which make use of the date at the cursor."
15184 (interactive)
15185 (move-marker org-agenda-action-marker
15186 (save-excursion (org-back-to-heading t) (point))
15187 (current-buffer))
15188 (message
15189 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15191 ;;; Paragraph filling stuff.
15192 ;; We want this to be just right, so use the full arsenal.
15194 (defun org-indent-line-function ()
15195 "Indent line like previous, but further if previous was headline or item."
15196 (interactive)
15197 (let* ((pos (point))
15198 (itemp (org-at-item-p))
15199 (org-drawer-regexp (or org-drawer-regexp "\000"))
15200 column bpos bcol tpos tcol bullet btype bullet-type)
15201 ;; Find the previous relevant line
15202 (beginning-of-line 1)
15203 (cond
15204 ((looking-at "#") (setq column 0))
15205 ((looking-at "\\*+ ") (setq column 0))
15206 ((and (looking-at "[ \t]*:END:")
15207 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15208 (save-excursion
15209 (goto-char (1- (match-beginning 1)))
15210 (setq column (current-column))))
15212 (beginning-of-line 0)
15213 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15214 (not (looking-at "[ \t]*:END:"))
15215 (not (looking-at org-drawer-regexp)))
15216 (beginning-of-line 0))
15217 (cond
15218 ((looking-at "\\*+[ \t]+")
15219 (if (not org-adapt-indentation)
15220 (setq column 0)
15221 (goto-char (match-end 0))
15222 (setq column (current-column))))
15223 ((looking-at org-drawer-regexp)
15224 (goto-char (1- (match-beginning 1)))
15225 (setq column (current-column)))
15226 ((looking-at "\\([ \t]*\\):END:")
15227 (goto-char (match-end 1))
15228 (setq column (current-column)))
15229 ((org-in-item-p)
15230 (org-beginning-of-item)
15231 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15232 (setq bpos (match-beginning 1) tpos (match-end 0)
15233 bcol (progn (goto-char bpos) (current-column))
15234 tcol (progn (goto-char tpos) (current-column))
15235 bullet (match-string 1)
15236 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15237 (if (> tcol (+ bcol org-description-max-indent))
15238 (setq tcol (+ bcol 5)))
15239 (if (not itemp)
15240 (setq column tcol)
15241 (goto-char pos)
15242 (beginning-of-line 1)
15243 (if (looking-at "\\S-")
15244 (progn
15245 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15246 (setq bullet (match-string 1)
15247 btype (if (string-match "[0-9]" bullet) "n" bullet))
15248 (setq column (if (equal btype bullet-type) bcol tcol)))
15249 (setq column (org-get-indentation)))))
15250 (t (setq column (org-get-indentation))))))
15251 (goto-char pos)
15252 (if (<= (current-column) (current-indentation))
15253 (org-indent-line-to column)
15254 (save-excursion (org-indent-line-to column)))
15255 (setq column (current-column))
15256 (beginning-of-line 1)
15257 (if (looking-at
15258 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15259 (replace-match (concat "\\1" (format org-property-format
15260 (match-string 2) (match-string 3)))
15261 t nil))
15262 (org-move-to-column column)))
15264 (defun org-set-autofill-regexps ()
15265 (interactive)
15266 ;; In the paragraph separator we include headlines, because filling
15267 ;; text in a line directly attached to a headline would otherwise
15268 ;; fill the headline as well.
15269 (org-set-local 'comment-start-skip "^#+[ \t]*")
15270 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15271 ;; The paragraph starter includes hand-formatted lists.
15272 (org-set-local 'paragraph-start
15273 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15274 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15275 ;; But only if the user has not turned off tables or fixed-width regions
15276 (org-set-local
15277 'auto-fill-inhibit-regexp
15278 (concat "\\*+ \\|#\\+"
15279 "\\|[ \t]*" org-keyword-time-regexp
15280 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15281 (concat
15282 "\\|[ \t]*["
15283 (if org-enable-table-editor "|" "")
15284 (if org-enable-fixed-width-editor ":" "")
15285 "]"))))
15286 ;; We use our own fill-paragraph function, to make sure that tables
15287 ;; and fixed-width regions are not wrapped. That function will pass
15288 ;; through to `fill-paragraph' when appropriate.
15289 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15290 ; Adaptive filling: To get full control, first make sure that
15291 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15292 (org-set-local 'adaptive-fill-regexp "\000")
15293 (org-set-local 'adaptive-fill-function
15294 'org-adaptive-fill-function)
15295 (org-set-local
15296 'align-mode-rules-list
15297 '((org-in-buffer-settings
15298 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15299 (modes . '(org-mode))))))
15301 (defun org-fill-paragraph (&optional justify)
15302 "Re-align a table, pass through to fill-paragraph if no table."
15303 (let ((table-p (org-at-table-p))
15304 (table.el-p (org-at-table.el-p)))
15305 (cond ((and (equal (char-after (point-at-bol)) ?*)
15306 (save-excursion (goto-char (point-at-bol))
15307 (looking-at outline-regexp)))
15308 t) ; skip headlines
15309 (table.el-p t) ; skip table.el tables
15310 (table-p (org-table-align) t) ; align org-mode tables
15311 (t nil)))) ; call paragraph-fill
15313 ;; For reference, this is the default value of adaptive-fill-regexp
15314 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15316 (defun org-adaptive-fill-function ()
15317 "Return a fill prefix for org-mode files.
15318 In particular, this makes sure hanging paragraphs for hand-formatted lists
15319 work correctly."
15320 (cond ((looking-at "#[ \t]+")
15321 (match-string 0))
15322 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15323 (save-excursion
15324 (if (> (match-end 1) (+ (match-beginning 1)
15325 org-description-max-indent))
15326 (goto-char (+ (match-beginning 1) 5))
15327 (goto-char (match-end 0)))
15328 (make-string (current-column) ?\ )))
15329 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15330 (save-excursion
15331 (goto-char (match-end 0))
15332 (make-string (current-column) ?\ )))
15333 (t nil)))
15335 ;;; Other stuff.
15337 (defun org-toggle-fixed-width-section (arg)
15338 "Toggle the fixed-width export.
15339 If there is no active region, the QUOTE keyword at the current headline is
15340 inserted or removed. When present, it causes the text between this headline
15341 and the next to be exported as fixed-width text, and unmodified.
15342 If there is an active region, this command adds or removes a colon as the
15343 first character of this line. If the first character of a line is a colon,
15344 this line is also exported in fixed-width font."
15345 (interactive "P")
15346 (let* ((cc 0)
15347 (regionp (org-region-active-p))
15348 (beg (if regionp (region-beginning) (point)))
15349 (end (if regionp (region-end)))
15350 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15351 (case-fold-search nil)
15352 (re "[ \t]*\\(: \\)")
15353 off)
15354 (if regionp
15355 (save-excursion
15356 (goto-char beg)
15357 (setq cc (current-column))
15358 (beginning-of-line 1)
15359 (setq off (looking-at re))
15360 (while (> nlines 0)
15361 (setq nlines (1- nlines))
15362 (beginning-of-line 1)
15363 (cond
15364 (arg
15365 (org-move-to-column cc t)
15366 (insert ": \n")
15367 (forward-line -1))
15368 ((and off (looking-at re))
15369 (replace-match "" t t nil 1))
15370 ((not off) (org-move-to-column cc t) (insert ": ")))
15371 (forward-line 1)))
15372 (save-excursion
15373 (org-back-to-heading)
15374 (if (looking-at (concat outline-regexp
15375 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15376 (replace-match "" t t nil 1)
15377 (if (looking-at outline-regexp)
15378 (progn
15379 (goto-char (match-end 0))
15380 (insert org-quote-string " "))))))))
15382 (defun org-reftex-citation ()
15383 "Use reftex-citation to insert a citation into the buffer.
15384 This looks for a line like
15386 #+BIBLIOGRAPHY: foo plain option:-d
15388 and derives from it that foo.bib is the bbliography file relevant
15389 for this document. It then installs the necessary environment for RefTeX
15390 to work in this buffer and calls `reftex-citation' to insert a citation
15391 into the buffer.
15393 Export of such citations to both LaTeX and HTML is handled by the contributed
15394 package org-exp-bibtex by Taru Karttunen."
15395 (interactive)
15396 (let ((reftex-docstruct-symbol 'rds)
15397 (reftex-cite-format "\\cite{%l}")
15398 rds bib)
15399 (save-excursion
15400 (save-restriction
15401 (widen)
15402 (let ((case-fold-search t)
15403 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15404 (if (not (save-excursion
15405 (or (re-search-forward re nil t)
15406 (re-search-backward re nil t))))
15407 (error "No bibliography defined in file")
15408 (setq bib (concat (match-string 1) ".bib")
15409 rds (list (list 'bib bib)))))))
15410 (call-interactively 'reftex-citation)))
15412 ;;;; Functions extending outline functionality
15414 (defun org-beginning-of-line (&optional arg)
15415 "Go to the beginning of the current line. If that is invisible, continue
15416 to a visible line beginning. This makes the function of C-a more intuitive.
15417 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15418 first attempt, and only move to after the tags when the cursor is already
15419 beyond the end of the headline."
15420 (interactive "P")
15421 (let ((pos (point))
15422 (special (if (consp org-special-ctrl-a/e)
15423 (car org-special-ctrl-a/e)
15424 org-special-ctrl-a/e))
15425 refpos)
15426 (beginning-of-line 1)
15427 (if (and arg (fboundp 'move-beginning-of-line))
15428 (call-interactively 'move-beginning-of-line)
15429 (if (bobp)
15431 (backward-char 1)
15432 (if (org-invisible-p)
15433 (while (and (not (bobp)) (org-invisible-p))
15434 (backward-char 1)
15435 (beginning-of-line 1))
15436 (forward-char 1))))
15437 (when special
15438 (cond
15439 ((and (looking-at org-complex-heading-regexp)
15440 (= (char-after (match-end 1)) ?\ ))
15441 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15442 (point-at-eol)))
15443 (goto-char
15444 (if (eq special t)
15445 (cond ((> pos refpos) refpos)
15446 ((= pos (point)) refpos)
15447 (t (point)))
15448 (cond ((> pos (point)) (point))
15449 ((not (eq last-command this-command)) (point))
15450 (t refpos)))))
15451 ((org-at-item-p)
15452 (goto-char
15453 (if (eq special t)
15454 (cond ((> pos (match-end 4)) (match-end 4))
15455 ((= pos (point)) (match-end 4))
15456 (t (point)))
15457 (cond ((> pos (point)) (point))
15458 ((not (eq last-command this-command)) (point))
15459 (t (match-end 4))))))))
15460 (org-no-warnings
15461 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15463 (defun org-end-of-line (&optional arg)
15464 "Go to the end of the line.
15465 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15466 first attempt, and only move to after the tags when the cursor is already
15467 beyond the end of the headline."
15468 (interactive "P")
15469 (let ((special (if (consp org-special-ctrl-a/e)
15470 (cdr org-special-ctrl-a/e)
15471 org-special-ctrl-a/e)))
15472 (if (or (not special)
15473 (not (org-on-heading-p))
15474 arg)
15475 (call-interactively (if (fboundp 'move-end-of-line)
15476 'move-end-of-line
15477 'end-of-line))
15478 (let ((pos (point)))
15479 (beginning-of-line 1)
15480 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15481 (if (eq special t)
15482 (if (or (< pos (match-beginning 1))
15483 (= pos (match-end 0)))
15484 (goto-char (match-beginning 1))
15485 (goto-char (match-end 0)))
15486 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15487 (goto-char (match-end 0))
15488 (goto-char (match-beginning 1))))
15489 (call-interactively (if (fboundp 'move-end-of-line)
15490 'move-end-of-line
15491 'end-of-line)))))
15492 (org-no-warnings
15493 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15495 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15496 (define-key org-mode-map "\C-e" 'org-end-of-line)
15498 (defun org-backward-sentence (&optional arg)
15499 "Go to beginning of sentence, or beginning of table field.
15500 This will call `backward-sentence' or `org-table-beginning-of-field',
15501 depending on context."
15502 (interactive "P")
15503 (cond
15504 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
15505 (t (call-interactively 'backward-sentence))))
15507 (defun org-forward-sentence (&optional arg)
15508 "Go to end of sentence, or end of table field.
15509 This will call `forward-sentence' or `org-table-end-of-field',
15510 depending on context."
15511 (interactive "P")
15512 (cond
15513 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
15514 (t (call-interactively 'forward-sentence))))
15516 (define-key org-mode-map "\M-a" 'org-backward-sentence)
15517 (define-key org-mode-map "\M-e" 'org-forward-sentence)
15519 (defun org-kill-line (&optional arg)
15520 "Kill line, to tags or end of line."
15521 (interactive "P")
15522 (cond
15523 ((or (not org-special-ctrl-k)
15524 (bolp)
15525 (not (org-on-heading-p)))
15526 (call-interactively 'kill-line))
15527 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15528 (kill-region (point) (match-beginning 1))
15529 (org-set-tags nil t))
15530 (t (kill-region (point) (point-at-eol)))))
15532 (define-key org-mode-map "\C-k" 'org-kill-line)
15534 (defun org-yank (&optional arg)
15535 "Yank. If the kill is a subtree, treat it specially.
15536 This command will look at the current kill and check if is a single
15537 subtree, or a series of subtrees[1]. If it passes the test, and if the
15538 cursor is at the beginning of a line or after the stars of a currently
15539 empty headline, then the yank is handled specially. How exactly depends
15540 on the value of the following variables, both set by default.
15542 org-yank-folded-subtrees
15543 When set, the subtree(s) will be folded after insertion, but only
15544 if doing so would now swallow text after the yanked text.
15546 org-yank-adjusted-subtrees
15547 When set, the subtree will be promoted or demoted in order to
15548 fit into the local outline tree structure, which means that the level
15549 will be adjusted so that it becomes the smaller one of the two
15550 *visible* surrounding headings.
15552 Any prefix to this command will cause `yank' to be called directly with
15553 no special treatment. In particular, a simple `C-u' prefix will just
15554 plainly yank the text as it is.
15556 \[1] Basically, the test checks if the first non-white line is a heading
15557 and if there are no other headings with fewer stars."
15558 (interactive "P")
15559 (setq this-command 'yank)
15560 (if arg
15561 (call-interactively 'yank)
15562 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15563 (and (org-kill-is-subtree-p)
15564 (or (bolp)
15565 (and (looking-at "[ \t]*$")
15566 (string-match
15567 "\\`\\*+\\'"
15568 (buffer-substring (point-at-bol) (point)))))))
15569 swallowp)
15570 (cond
15571 ((and subtreep org-yank-folded-subtrees)
15572 (let ((beg (point))
15573 end)
15574 (if (and subtreep org-yank-adjusted-subtrees)
15575 (org-paste-subtree nil nil 'for-yank)
15576 (call-interactively 'yank))
15577 (setq end (point))
15578 (goto-char beg)
15579 (when (and (bolp) subtreep
15580 (not (setq swallowp
15581 (org-yank-folding-would-swallow-text beg end))))
15582 (or (looking-at outline-regexp)
15583 (re-search-forward (concat "^" outline-regexp) end t))
15584 (while (and (< (point) end) (looking-at outline-regexp))
15585 (hide-subtree)
15586 (org-cycle-show-empty-lines 'folded)
15587 (condition-case nil
15588 (outline-forward-same-level 1)
15589 (error (goto-char end)))))
15590 (when swallowp
15591 (message
15592 "Yanked text not folded because that would swallow text"))
15593 (goto-char end)
15594 (skip-chars-forward " \t\n\r")
15595 (beginning-of-line 1)
15596 (push-mark beg 'nomsg)))
15597 ((and subtreep org-yank-adjusted-subtrees)
15598 (let ((beg (point-at-bol)))
15599 (org-paste-subtree nil nil 'for-yank)
15600 (push-mark beg 'nomsg)))
15602 (call-interactively 'yank))))))
15604 (defun org-yank-folding-would-swallow-text (beg end)
15605 "Would hide-subtree at BEG swallow any text after END?"
15606 (let (level)
15607 (save-excursion
15608 (goto-char beg)
15609 (when (or (looking-at outline-regexp)
15610 (re-search-forward (concat "^" outline-regexp) end t))
15611 (setq level (org-outline-level)))
15612 (goto-char end)
15613 (skip-chars-forward " \t\r\n\v\f")
15614 (if (or (eobp)
15615 (and (bolp) (looking-at org-outline-regexp)
15616 (<= (org-outline-level) level)))
15617 nil ; Nothing would be swallowed
15618 t)))) ; something would swallow
15620 (define-key org-mode-map "\C-y" 'org-yank)
15622 (defun org-invisible-p ()
15623 "Check if point is at a character currently not visible."
15624 ;; Early versions of noutline don't have `outline-invisible-p'.
15625 (if (fboundp 'outline-invisible-p)
15626 (outline-invisible-p)
15627 (get-char-property (point) 'invisible)))
15629 (defun org-invisible-p2 ()
15630 "Check if point is at a character currently not visible."
15631 (save-excursion
15632 (if (and (eolp) (not (bobp))) (backward-char 1))
15633 ;; Early versions of noutline don't have `outline-invisible-p'.
15634 (if (fboundp 'outline-invisible-p)
15635 (outline-invisible-p)
15636 (get-char-property (point) 'invisible))))
15638 (defun org-back-to-heading (&optional invisible-ok)
15639 "Call `outline-back-to-heading', but provide a better error message."
15640 (condition-case nil
15641 (outline-back-to-heading invisible-ok)
15642 (error (error "Before first headline at position %d in buffer %s"
15643 (point) (current-buffer)))))
15645 (defun org-before-first-heading-p ()
15646 "Before first heading?"
15647 (save-excursion
15648 (null (re-search-backward "^\\*+ " nil t))))
15650 (defalias 'org-on-heading-p 'outline-on-heading-p)
15651 (defalias 'org-at-heading-p 'outline-on-heading-p)
15652 (defun org-at-heading-or-item-p ()
15653 (or (org-on-heading-p) (org-at-item-p)))
15655 (defun org-on-target-p ()
15656 (or (org-in-regexp org-radio-target-regexp)
15657 (org-in-regexp org-target-regexp)))
15659 (defun org-up-heading-all (arg)
15660 "Move to the heading line of which the present line is a subheading.
15661 This function considers both visible and invisible heading lines.
15662 With argument, move up ARG levels."
15663 (if (fboundp 'outline-up-heading-all)
15664 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15665 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15667 (defun org-up-heading-safe ()
15668 "Move to the heading line of which the present line is a subheading.
15669 This version will not throw an error. It will return the level of the
15670 headline found, or nil if no higher level is found."
15671 (let (start-level re)
15672 (org-back-to-heading t)
15673 (setq start-level (funcall outline-level))
15674 (if (equal start-level 1)
15676 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15677 (if (re-search-backward re nil t)
15678 (funcall outline-level)))))
15680 (defun org-first-sibling-p ()
15681 "Is this heading the first child of its parents?"
15682 (interactive)
15683 (let ((re (concat "^" outline-regexp))
15684 level l)
15685 (unless (org-at-heading-p t)
15686 (error "Not at a heading"))
15687 (setq level (funcall outline-level))
15688 (save-excursion
15689 (if (not (re-search-backward re nil t))
15691 (setq l (funcall outline-level))
15692 (< l level)))))
15694 (defun org-goto-sibling (&optional previous)
15695 "Goto the next sibling, even if it is invisible.
15696 When PREVIOUS is set, go to the previous sibling instead. Returns t
15697 when a sibling was found. When none is found, return nil and don't
15698 move point."
15699 (let ((fun (if previous 're-search-backward 're-search-forward))
15700 (pos (point))
15701 (re (concat "^" outline-regexp))
15702 level l)
15703 (when (condition-case nil (org-back-to-heading t) (error nil))
15704 (setq level (funcall outline-level))
15705 (catch 'exit
15706 (or previous (forward-char 1))
15707 (while (funcall fun re nil t)
15708 (setq l (funcall outline-level))
15709 (when (< l level) (goto-char pos) (throw 'exit nil))
15710 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15711 (goto-char pos)
15712 nil))))
15714 (defun org-show-siblings ()
15715 "Show all siblings of the current headline."
15716 (save-excursion
15717 (while (org-goto-sibling) (org-flag-heading nil)))
15718 (save-excursion
15719 (while (org-goto-sibling 'previous)
15720 (org-flag-heading nil))))
15722 (defun org-show-hidden-entry ()
15723 "Show an entry where even the heading is hidden."
15724 (save-excursion
15725 (org-show-entry)))
15727 (defun org-flag-heading (flag &optional entry)
15728 "Flag the current heading. FLAG non-nil means make invisible.
15729 When ENTRY is non-nil, show the entire entry."
15730 (save-excursion
15731 (org-back-to-heading t)
15732 ;; Check if we should show the entire entry
15733 (if entry
15734 (progn
15735 (org-show-entry)
15736 (save-excursion
15737 (and (outline-next-heading)
15738 (org-flag-heading nil))))
15739 (outline-flag-region (max (point-min) (1- (point)))
15740 (save-excursion (outline-end-of-heading) (point))
15741 flag))))
15743 (defun org-forward-same-level (arg)
15744 "Move forward to the ARG'th subheading at same level as this one.
15745 Stop at the first and last subheadings of a superior heading.
15746 This is like outline-forward-same-level, but invisible headings are ok."
15747 (interactive "p")
15748 (org-back-to-heading t)
15749 (while (> arg 0)
15750 (let ((point-to-move-to (save-excursion
15751 (org-get-next-sibling))))
15752 (if point-to-move-to
15753 (progn
15754 (goto-char point-to-move-to)
15755 (setq arg (1- arg)))
15756 (progn
15757 (setq arg 0)
15758 (error "No following same-level heading"))))))
15760 (defun org-get-next-sibling ()
15761 "Move to next heading of the same level, and return point.
15762 If there is no such heading, return nil.
15763 This is like outline-next-sibling, but invisible headings are ok."
15764 (let ((level (funcall outline-level)))
15765 (outline-next-heading)
15766 (while (and (not (eobp)) (> (funcall outline-level) level))
15767 (outline-next-heading))
15768 (if (or (eobp) (< (funcall outline-level) level))
15770 (point))))
15772 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15773 ;; This is an exact copy of the original function, but it uses
15774 ;; `org-back-to-heading', to make it work also in invisible
15775 ;; trees. And is uses an invisible-OK argument.
15776 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15777 (org-back-to-heading invisible-OK)
15778 (let ((first t)
15779 (level (funcall outline-level)))
15780 (while (and (not (eobp))
15781 (or first (> (funcall outline-level) level)))
15782 (setq first nil)
15783 (outline-next-heading))
15784 (unless to-heading
15785 (if (memq (preceding-char) '(?\n ?\^M))
15786 (progn
15787 ;; Go to end of line before heading
15788 (forward-char -1)
15789 (if (memq (preceding-char) '(?\n ?\^M))
15790 ;; leave blank line before heading
15791 (forward-char -1))))))
15792 (point))
15794 (defun org-show-subtree ()
15795 "Show everything after this heading at deeper levels."
15796 (outline-flag-region
15797 (point)
15798 (save-excursion
15799 (outline-end-of-subtree) (outline-next-heading) (point))
15800 nil))
15802 (defun org-show-entry ()
15803 "Show the body directly following this heading.
15804 Show the heading too, if it is currently invisible."
15805 (interactive)
15806 (save-excursion
15807 (condition-case nil
15808 (progn
15809 (org-back-to-heading t)
15810 (outline-flag-region
15811 (max (point-min) (1- (point)))
15812 (save-excursion
15813 (if (re-search-forward
15814 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15815 (match-beginning 1)
15816 (point-max)))
15817 nil))
15818 (error nil))))
15820 (defun org-make-options-regexp (kwds &optional extra)
15821 "Make a regular expression for keyword lines."
15822 (concat
15824 "#?[ \t]*\\+\\("
15825 (mapconcat 'regexp-quote kwds "\\|")
15826 (if extra (concat "\\|" extra))
15827 "\\):[ \t]*"
15828 "\\(.+\\)"))
15830 ;; Make isearch reveal the necessary context
15831 (defun org-isearch-end ()
15832 "Reveal context after isearch exits."
15833 (when isearch-success ; only if search was successful
15834 (if (featurep 'xemacs)
15835 ;; Under XEmacs, the hook is run in the correct place,
15836 ;; we directly show the context.
15837 (org-show-context 'isearch)
15838 ;; In Emacs the hook runs *before* restoring the overlays.
15839 ;; So we have to use a one-time post-command-hook to do this.
15840 ;; (Emacs 22 has a special variable, see function `org-mode')
15841 (unless (and (boundp 'isearch-mode-end-hook-quit)
15842 isearch-mode-end-hook-quit)
15843 ;; Only when the isearch was not quitted.
15844 (org-add-hook 'post-command-hook 'org-isearch-post-command
15845 'append 'local)))))
15847 (defun org-isearch-post-command ()
15848 "Remove self from hook, and show context."
15849 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15850 (org-show-context 'isearch))
15853 ;;;; Integration with and fixes for other packages
15855 ;;; Imenu support
15857 (defvar org-imenu-markers nil
15858 "All markers currently used by Imenu.")
15859 (make-variable-buffer-local 'org-imenu-markers)
15861 (defun org-imenu-new-marker (&optional pos)
15862 "Return a new marker for use by Imenu, and remember the marker."
15863 (let ((m (make-marker)))
15864 (move-marker m (or pos (point)))
15865 (push m org-imenu-markers)
15868 (defun org-imenu-get-tree ()
15869 "Produce the index for Imenu."
15870 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15871 (setq org-imenu-markers nil)
15872 (let* ((n org-imenu-depth)
15873 (re (concat "^" outline-regexp))
15874 (subs (make-vector (1+ n) nil))
15875 (last-level 0)
15876 m level head)
15877 (save-excursion
15878 (save-restriction
15879 (widen)
15880 (goto-char (point-max))
15881 (while (re-search-backward re nil t)
15882 (setq level (org-reduced-level (funcall outline-level)))
15883 (when (<= level n)
15884 (looking-at org-complex-heading-regexp)
15885 (setq head (org-link-display-format
15886 (org-match-string-no-properties 4))
15887 m (org-imenu-new-marker))
15888 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15889 (if (>= level last-level)
15890 (push (cons head m) (aref subs level))
15891 (push (cons head (aref subs (1+ level))) (aref subs level))
15892 (loop for i from (1+ level) to n do (aset subs i nil)))
15893 (setq last-level level)))))
15894 (aref subs 1)))
15896 (eval-after-load "imenu"
15897 '(progn
15898 (add-hook 'imenu-after-jump-hook
15899 (lambda ()
15900 (if (eq major-mode 'org-mode)
15901 (org-show-context 'org-goto))))))
15903 (defun org-link-display-format (link)
15904 "Replace a link with either the description, or the link target
15905 if no description is present"
15906 (save-match-data
15907 (if (string-match org-bracket-link-analytic-regexp link)
15908 (replace-match (or (match-string 5 link)
15909 (concat (match-string 1 link)
15910 (match-string 3 link)))
15911 nil nil link)
15912 link)))
15914 ;; Speedbar support
15916 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15917 "Overlay marking the agenda restriction line in speedbar.")
15918 (org-overlay-put org-speedbar-restriction-lock-overlay
15919 'face 'org-agenda-restriction-lock)
15920 (org-overlay-put org-speedbar-restriction-lock-overlay
15921 'help-echo "Agendas are currently limited to this item.")
15922 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15924 (defun org-speedbar-set-agenda-restriction ()
15925 "Restrict future agenda commands to the location at point in speedbar.
15926 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15927 (interactive)
15928 (require 'org-agenda)
15929 (let (p m tp np dir txt)
15930 (cond
15931 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15932 'org-imenu t))
15933 (setq m (get-text-property p 'org-imenu-marker))
15934 (save-excursion
15935 (save-restriction
15936 (set-buffer (marker-buffer m))
15937 (goto-char m)
15938 (org-agenda-set-restriction-lock 'subtree))))
15939 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15940 'speedbar-function 'speedbar-find-file))
15941 (setq tp (previous-single-property-change
15942 (1+ p) 'speedbar-function)
15943 np (next-single-property-change
15944 tp 'speedbar-function)
15945 dir (speedbar-line-directory)
15946 txt (buffer-substring-no-properties (or tp (point-min))
15947 (or np (point-max))))
15948 (save-excursion
15949 (save-restriction
15950 (set-buffer (find-file-noselect
15951 (let ((default-directory dir))
15952 (expand-file-name txt))))
15953 (unless (org-mode-p)
15954 (error "Cannot restrict to non-Org-mode file"))
15955 (org-agenda-set-restriction-lock 'file))))
15956 (t (error "Don't know how to restrict Org-mode's agenda")))
15957 (org-move-overlay org-speedbar-restriction-lock-overlay
15958 (point-at-bol) (point-at-eol))
15959 (setq current-prefix-arg nil)
15960 (org-agenda-maybe-redo)))
15962 (eval-after-load "speedbar"
15963 '(progn
15964 (speedbar-add-supported-extension ".org")
15965 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15966 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15967 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15968 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15969 (add-hook 'speedbar-visiting-tag-hook
15970 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15973 ;;; Fixes and Hacks for problems with other packages
15975 ;; Make flyspell not check words in links, to not mess up our keymap
15976 (defun org-mode-flyspell-verify ()
15977 "Don't let flyspell put overlays at active buttons."
15978 (not (get-text-property (point) 'keymap)))
15980 ;; Make `bookmark-jump' show the jump location if it was hidden.
15981 (eval-after-load "bookmark"
15982 '(if (boundp 'bookmark-after-jump-hook)
15983 ;; We can use the hook
15984 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15985 ;; Hook not available, use advice
15986 (defadvice bookmark-jump (after org-make-visible activate)
15987 "Make the position visible."
15988 (org-bookmark-jump-unhide))))
15990 ;; Make sure saveplace show the location if it was hidden
15991 (eval-after-load "saveplace"
15992 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15993 "Make the position visible."
15994 (org-bookmark-jump-unhide)))
15996 (defun org-bookmark-jump-unhide ()
15997 "Unhide the current position, to show the bookmark location."
15998 (and (org-mode-p)
15999 (or (org-invisible-p)
16000 (save-excursion (goto-char (max (point-min) (1- (point))))
16001 (org-invisible-p)))
16002 (org-show-context 'bookmark-jump)))
16004 ;; Make session.el ignore our circular variable
16005 (eval-after-load "session"
16006 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16008 ;;;; Experimental code
16010 (defun org-closed-in-range ()
16011 "Sparse tree of items closed in a certain time range.
16012 Still experimental, may disappear in the future."
16013 (interactive)
16014 ;; Get the time interval from the user.
16015 (let* ((time1 (time-to-seconds
16016 (org-read-date nil 'to-time nil "Starting date: ")))
16017 (time2 (time-to-seconds
16018 (org-read-date nil 'to-time nil "End date:")))
16019 ;; callback function
16020 (callback (lambda ()
16021 (let ((time
16022 (time-to-seconds
16023 (apply 'encode-time
16024 (org-parse-time-string
16025 (match-string 1))))))
16026 ;; check if time in interval
16027 (and (>= time time1) (<= time time2))))))
16028 ;; make tree, check each match with the callback
16029 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16031 ;;;; Finish up
16033 (provide 'org)
16035 (run-hooks 'org-load-hook)
16037 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16039 ;;; org.el ends here