Release 6.22a
[org-mode.git] / lisp / org.el
blobba4963677743c852890118553c6728e105ac605b
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.22a
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.22a"
98 "The version number of the file org.el.")
100 (defun org-version (&optional here)
101 "Show the org-mode version in the echo area.
102 With prefix arg HERE, insert it at point."
103 (interactive "P")
104 (let ((version (format "Org-mode version %s" org-version)))
105 (message version)
106 (if here
107 (insert version))))
109 ;;; Compatibility constants
111 ;;; The custom variables
113 (defgroup org nil
114 "Outline-based notes management and organizer."
115 :tag "Org"
116 :group 'outlines
117 :group 'hypermedia
118 :group 'calendar)
120 (defcustom org-load-hook nil
121 "Hook that is run after org.el has been loaded."
122 :group 'org
123 :type 'hook)
125 (defvar org-modules) ; defined below
126 (defvar org-modules-loaded nil
127 "Have the modules been loaded already?")
129 (defun org-load-modules-maybe (&optional force)
130 "Load all extensions listed in `org-modules'."
131 (when (or force (not org-modules-loaded))
132 (mapc (lambda (ext)
133 (condition-case nil (require ext)
134 (error (message "Problems while trying to load feature `%s'" ext))))
135 org-modules)
136 (setq org-modules-loaded t)))
138 (defun org-set-modules (var value)
139 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
140 (set var value)
141 (when (featurep 'org)
142 (org-load-modules-maybe 'force)))
144 (when (org-bound-and-true-p org-modules)
145 (let ((a (member 'org-infojs org-modules)))
146 (and a (setcar a 'org-jsinfo))))
148 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
149 "Modules that should always be loaded together with org.el.
150 If a description starts with <C>, the file is not part of Emacs
151 and loading it will require that you have downloaded and properly installed
152 the org-mode distribution.
154 You can also use this system to load external packages (i.e. neither Org
155 core modules, not modules from the CONTRIB directory). Just add symbols
156 to the end of the list. If the package is called org-xyz.el, then you need
157 to add the symbol `xyz', and the package must have a call to
159 (provide 'org-xyz)"
160 :group 'org
161 :set 'org-set-modules
162 :type
163 '(set :greedy t
164 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
165 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
166 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
167 (const :tag " id: Global IDs for identifying entries" org-id)
168 (const :tag " info: Links to Info nodes" org-info)
169 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
170 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
171 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
172 (const :tag " mew Links to Mew folders/messages" org-mew)
173 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
174 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
175 (const :tag " vm: Links to VM folders/messages" org-vm)
176 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
177 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
178 (const :tag " mouse: Additional mouse support" org-mouse)
180 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
181 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
182 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
183 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
184 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
185 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
186 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
187 (const :tag "C eval: Include command output as text" org-eval)
188 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
189 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
190 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
191 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
192 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
193 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
194 (const :tag "C mtags: Support for muse-like tags" org-mtags)
195 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
196 (const :tag "C registry: A registry for Org links" org-registry)
197 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
198 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
199 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
200 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
201 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
203 (defcustom org-support-shift-select nil
204 "Non-nil means, make shift-cursor commands select text when possible.
206 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
207 selecting a region, or enlarge thusly regions started in this way.
208 In Org-mode, in special contexts, these same keys are used for other
209 purposes, important enough to compete with shift selection. Org tries
210 to balance these needs by supporting `shift-select-mode' outside these
211 special contexts, under control of this variable.
213 The default of this variable is nil, to avoid confusing behavior. Shifted
214 cursor keys will then execute Org commands in the following contexts:
215 - on a headline, changing TODO state (left/right) and priority (up/down)
216 - on a time stamp, changing the time
217 - in a plain list item, changing the bullet type
218 - in a property definition line, switching between allowed values
219 - in the BEGIN line of a clock table (changing the time block).
220 Outside these contexts, the commands will throw an error.
222 When this variable is t and the cursor is not in a special context,
223 Org-mode will support shift-selection for making and enlarging regions.
224 To make this more effective, the bullet cycling will no longer happen
225 anywhere in an item line, but only if the cursor is exactly on the bullet.
227 If you set this variable to the symbol `always', then the keys
228 will not be special in headlines, property lines, and item lines, to make
229 shift selection work there as well. If this is what you want, you can
230 use the following alternative commands: `C-c C-t' and `C-c ,' to
231 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
232 TODO sets, `C-c -' to cycle item bullet types, and properties can be
233 edited by hand or in column view.
235 However, when the cursor is on a timestamp, shift-cursor commands
236 will still edit the time stamp - this is just too good to give up.
238 XEmacs user should have this variable set to nil, because shift-select-mode
239 is Emacs 23 only."
240 :group 'org
241 :type '(choice
242 (const :tag "Never" nil)
243 (const :tag "When outside special context" t)
244 (const :tag "Everywhere except timestamps" always)))
246 (defgroup org-startup nil
247 "Options concerning startup of Org-mode."
248 :tag "Org Startup"
249 :group 'org)
251 (defcustom org-startup-folded t
252 "Non-nil means, entering Org-mode will switch to OVERVIEW.
253 This can also be configured on a per-file basis by adding one of
254 the following lines anywhere in the buffer:
256 #+STARTUP: fold
257 #+STARTUP: nofold
258 #+STARTUP: content"
259 :group 'org-startup
260 :type '(choice
261 (const :tag "nofold: show all" nil)
262 (const :tag "fold: overview" t)
263 (const :tag "content: all headlines" content)))
265 (defcustom org-startup-truncated t
266 "Non-nil means, entering Org-mode will set `truncate-lines'.
267 This is useful since some lines containing links can be very long and
268 uninteresting. Also tables look terrible when wrapped."
269 :group 'org-startup
270 :type 'boolean)
272 (defcustom org-startup-align-all-tables nil
273 "Non-nil means, align all tables when visiting a file.
274 This is useful when the column width in tables is forced with <N> cookies
275 in table fields. Such tables will look correct only after the first re-align.
276 This can also be configured on a per-file basis by adding one of
277 the following lines anywhere in the buffer:
278 #+STARTUP: align
279 #+STARTUP: noalign"
280 :group 'org-startup
281 :type 'boolean)
283 (defcustom org-insert-mode-line-in-empty-file nil
284 "Non-nil means insert the first line setting Org-mode in empty files.
285 When the function `org-mode' is called interactively in an empty file, this
286 normally means that the file name does not automatically trigger Org-mode.
287 To ensure that the file will always be in Org-mode in the future, a
288 line enforcing Org-mode will be inserted into the buffer, if this option
289 has been set."
290 :group 'org-startup
291 :type 'boolean)
293 (defcustom org-replace-disputed-keys nil
294 "Non-nil means use alternative key bindings for some keys.
295 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
296 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
297 If you want to use Org-mode together with one of these other modes,
298 or more generally if you would like to move some Org-mode commands to
299 other keys, set this variable and configure the keys with the variable
300 `org-disputed-keys'.
302 This option is only relevant at load-time of Org-mode, and must be set
303 *before* org.el is loaded. Changing it requires a restart of Emacs to
304 become effective."
305 :group 'org-startup
306 :type 'boolean)
308 (defcustom org-use-extra-keys nil
309 "Non-nil means use extra key sequence definitions for certain
310 commands. This happens automatically if you run XEmacs or if
311 window-system is nil. This variable lets you do the same
312 manually. You must set it before loading org.
314 Example: on Carbon Emacs 22 running graphically, with an external
315 keyboard on a Powerbook, the default way of setting M-left might
316 not work for either Alt or ESC. Setting this variable will make
317 it work for ESC."
318 :group 'org-startup
319 :type 'boolean)
321 (if (fboundp 'defvaralias)
322 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
324 (defcustom org-disputed-keys
325 '(([(shift up)] . [(meta p)])
326 ([(shift down)] . [(meta n)])
327 ([(shift left)] . [(meta -)])
328 ([(shift right)] . [(meta +)])
329 ([(control shift right)] . [(meta shift +)])
330 ([(control shift left)] . [(meta shift -)]))
331 "Keys for which Org-mode and other modes compete.
332 This is an alist, cars are the default keys, second element specifies
333 the alternative to use when `org-replace-disputed-keys' is t.
335 Keys can be specified in any syntax supported by `define-key'.
336 The value of this option takes effect only at Org-mode's startup,
337 therefore you'll have to restart Emacs to apply it after changing."
338 :group 'org-startup
339 :type 'alist)
341 (defun org-key (key)
342 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
343 Or return the original if not disputed."
344 (if org-replace-disputed-keys
345 (let* ((nkey (key-description key))
346 (x (org-find-if (lambda (x)
347 (equal (key-description (car x)) nkey))
348 org-disputed-keys)))
349 (if x (cdr x) key))
350 key))
352 (defun org-find-if (predicate seq)
353 (catch 'exit
354 (while seq
355 (if (funcall predicate (car seq))
356 (throw 'exit (car seq))
357 (pop seq)))))
359 (defun org-defkey (keymap key def)
360 "Define a key, possibly translated, as returned by `org-key'."
361 (define-key keymap (org-key key) def))
363 (defcustom org-ellipsis nil
364 "The ellipsis to use in the Org-mode outline.
365 When nil, just use the standard three dots. When a string, use that instead,
366 When a face, use the standard 3 dots, but with the specified face.
367 The change affects only Org-mode (which will then use its own display table).
368 Changing this requires executing `M-x org-mode' in a buffer to become
369 effective."
370 :group 'org-startup
371 :type '(choice (const :tag "Default" nil)
372 (face :tag "Face" :value org-warning)
373 (string :tag "String" :value "...#")))
375 (defvar org-display-table nil
376 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
378 (defgroup org-keywords nil
379 "Keywords in Org-mode."
380 :tag "Org Keywords"
381 :group 'org)
383 (defcustom org-deadline-string "DEADLINE:"
384 "String to mark deadline entries.
385 A deadline is this string, followed by a time stamp. Should be a word,
386 terminated by a colon. You can insert a schedule keyword and
387 a timestamp with \\[org-deadline].
388 Changes become only effective after restarting Emacs."
389 :group 'org-keywords
390 :type 'string)
392 (defcustom org-scheduled-string "SCHEDULED:"
393 "String to mark scheduled TODO entries.
394 A schedule is this string, followed by a time stamp. Should be a word,
395 terminated by a colon. You can insert a schedule keyword and
396 a timestamp with \\[org-schedule].
397 Changes become only effective after restarting Emacs."
398 :group 'org-keywords
399 :type 'string)
401 (defcustom org-closed-string "CLOSED:"
402 "String used as the prefix for timestamps logging closing a TODO entry."
403 :group 'org-keywords
404 :type 'string)
406 (defcustom org-clock-string "CLOCK:"
407 "String used as prefix for timestamps clocking work hours on an item."
408 :group 'org-keywords
409 :type 'string)
411 (defcustom org-comment-string "COMMENT"
412 "Entries starting with this keyword will never be exported.
413 An entry can be toggled between COMMENT and normal with
414 \\[org-toggle-comment].
415 Changes become only effective after restarting Emacs."
416 :group 'org-keywords
417 :type 'string)
419 (defcustom org-quote-string "QUOTE"
420 "Entries starting with this keyword will be exported in fixed-width font.
421 Quoting applies only to the text in the entry following the headline, and does
422 not extend beyond the next headline, even if that is lower level.
423 An entry can be toggled between QUOTE and normal with
424 \\[org-toggle-fixed-width-section]."
425 :group 'org-keywords
426 :type 'string)
428 (defconst org-repeat-re
429 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
430 "Regular expression for specifying repeated events.
431 After a match, group 1 contains the repeat expression.")
433 (defgroup org-structure nil
434 "Options concerning the general structure of Org-mode files."
435 :tag "Org Structure"
436 :group 'org)
438 (defgroup org-reveal-location nil
439 "Options about how to make context of a location visible."
440 :tag "Org Reveal Location"
441 :group 'org-structure)
443 (defconst org-context-choice
444 '(choice
445 (const :tag "Always" t)
446 (const :tag "Never" nil)
447 (repeat :greedy t :tag "Individual contexts"
448 (cons
449 (choice :tag "Context"
450 (const agenda)
451 (const org-goto)
452 (const occur-tree)
453 (const tags-tree)
454 (const link-search)
455 (const mark-goto)
456 (const bookmark-jump)
457 (const isearch)
458 (const default))
459 (boolean))))
460 "Contexts for the reveal options.")
462 (defcustom org-show-hierarchy-above '((default . t))
463 "Non-nil means, show full hierarchy when revealing a location.
464 Org-mode often shows locations in an org-mode file which might have
465 been invisible before. When this is set, the hierarchy of headings
466 above the exposed location is shown.
467 Turning this off for example for sparse trees makes them very compact.
468 Instead of t, this can also be an alist specifying this option for different
469 contexts. Valid contexts are
470 agenda when exposing an entry from the agenda
471 org-goto when using the command `org-goto' on key C-c C-j
472 occur-tree when using the command `org-occur' on key C-c /
473 tags-tree when constructing a sparse tree based on tags matches
474 link-search when exposing search matches associated with a link
475 mark-goto when exposing the jump goal of a mark
476 bookmark-jump when exposing a bookmark location
477 isearch when exiting from an incremental search
478 default default for all contexts not set explicitly"
479 :group 'org-reveal-location
480 :type org-context-choice)
482 (defcustom org-show-following-heading '((default . nil))
483 "Non-nil means, show following heading when revealing a location.
484 Org-mode often shows locations in an org-mode file which might have
485 been invisible before. When this is set, the heading following the
486 match is shown.
487 Turning this off for example for sparse trees makes them very compact,
488 but makes it harder to edit the location of the match. In such a case,
489 use the command \\[org-reveal] to show more context.
490 Instead of t, this can also be an alist specifying this option for different
491 contexts. See `org-show-hierarchy-above' for valid contexts."
492 :group 'org-reveal-location
493 :type org-context-choice)
495 (defcustom org-show-siblings '((default . nil) (isearch t))
496 "Non-nil means, show all sibling heading when revealing a location.
497 Org-mode often shows locations in an org-mode file which might have
498 been invisible before. When this is set, the sibling of the current entry
499 heading are all made visible. If `org-show-hierarchy-above' is t,
500 the same happens on each level of the hierarchy above the current entry.
502 By default this is on for the isearch context, off for all other contexts.
503 Turning this off for example for sparse trees makes them very compact,
504 but makes it harder to edit the location of the match. In such a case,
505 use the command \\[org-reveal] to show more context.
506 Instead of t, this can also be an alist specifying this option for different
507 contexts. See `org-show-hierarchy-above' for valid contexts."
508 :group 'org-reveal-location
509 :type org-context-choice)
511 (defcustom org-show-entry-below '((default . nil))
512 "Non-nil means, show the entry below a headline when revealing a location.
513 Org-mode often shows locations in an org-mode file which might have
514 been invisible before. When this is set, the text below the headline that is
515 exposed is also shown.
517 By default this is off for all contexts.
518 Instead of t, this can also be an alist specifying this option for different
519 contexts. See `org-show-hierarchy-above' for valid contexts."
520 :group 'org-reveal-location
521 :type org-context-choice)
523 (defcustom org-indirect-buffer-display 'other-window
524 "How should indirect tree buffers be displayed?
525 This applies to indirect buffers created with the commands
526 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
527 Valid values are:
528 current-window Display in the current window
529 other-window Just display in another window.
530 dedicated-frame Create one new frame, and re-use it each time.
531 new-frame Make a new frame each time. Note that in this case
532 previously-made indirect buffers are kept, and you need to
533 kill these buffers yourself."
534 :group 'org-structure
535 :group 'org-agenda-windows
536 :type '(choice
537 (const :tag "In current window" current-window)
538 (const :tag "In current frame, other window" other-window)
539 (const :tag "Each time a new frame" new-frame)
540 (const :tag "One dedicated frame" dedicated-frame)))
542 (defgroup org-cycle nil
543 "Options concerning visibility cycling in Org-mode."
544 :tag "Org Cycle"
545 :group 'org-structure)
547 (defcustom org-drawers '("PROPERTIES" "CLOCK")
548 "Names of drawers. Drawers are not opened by cycling on the headline above.
549 Drawers only open with a TAB on the drawer line itself. A drawer looks like
550 this:
551 :DRAWERNAME:
552 .....
553 :END:
554 The drawer \"PROPERTIES\" is special for capturing properties through
555 the property API.
557 Drawers can be defined on the per-file basis with a line like:
559 #+DRAWERS: HIDDEN STATE PROPERTIES"
560 :group 'org-structure
561 :type '(repeat (string :tag "Drawer Name")))
563 (defcustom org-cycle-global-at-bob nil
564 "Cycle globally if cursor is at beginning of buffer and not at a headline.
565 This makes it possible to do global cycling without having to use S-TAB or
566 C-u TAB. For this special case to work, the first line of the buffer
567 must not be a headline - it may be empty or some other text. When used in
568 this way, `org-cycle-hook' is disables temporarily, to make sure the
569 cursor stays at the beginning of the buffer.
570 When this option is nil, don't do anything special at the beginning
571 of the buffer."
572 :group 'org-cycle
573 :type 'boolean)
575 (defcustom org-cycle-emulate-tab t
576 "Where should `org-cycle' emulate TAB.
577 nil Never
578 white Only in completely white lines
579 whitestart Only at the beginning of lines, before the first non-white char
580 t Everywhere except in headlines
581 exc-hl-bol Everywhere except at the start of a headline
582 If TAB is used in a place where it does not emulate TAB, the current subtree
583 visibility is cycled."
584 :group 'org-cycle
585 :type '(choice (const :tag "Never" nil)
586 (const :tag "Only in completely white lines" white)
587 (const :tag "Before first char in a line" whitestart)
588 (const :tag "Everywhere except in headlines" t)
589 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
592 (defcustom org-cycle-separator-lines 2
593 "Number of empty lines needed to keep an empty line between collapsed trees.
594 If you leave an empty line between the end of a subtree and the following
595 headline, this empty line is hidden when the subtree is folded.
596 Org-mode will leave (exactly) one empty line visible if the number of
597 empty lines is equal or larger to the number given in this variable.
598 So the default 2 means, at least 2 empty lines after the end of a subtree
599 are needed to produce free space between a collapsed subtree and the
600 following headline.
602 Special case: when 0, never leave empty lines in collapsed view."
603 :group 'org-cycle
604 :type 'integer)
605 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
607 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
608 org-cycle-hide-drawers
609 org-cycle-show-empty-lines
610 org-optimize-window-after-visibility-change)
611 "Hook that is run after `org-cycle' has changed the buffer visibility.
612 The function(s) in this hook must accept a single argument which indicates
613 the new state that was set by the most recent `org-cycle' command. The
614 argument is a symbol. After a global state change, it can have the values
615 `overview', `content', or `all'. After a local state change, it can have
616 the values `folded', `children', or `subtree'."
617 :group 'org-cycle
618 :type 'hook)
620 (defgroup org-edit-structure nil
621 "Options concerning structure editing in Org-mode."
622 :tag "Org Edit Structure"
623 :group 'org-structure)
625 (defcustom org-odd-levels-only nil
626 "Non-nil means, skip even levels and only use odd levels for the outline.
627 This has the effect that two stars are being added/taken away in
628 promotion/demotion commands. It also influences how levels are
629 handled by the exporters.
630 Changing it requires restart of `font-lock-mode' to become effective
631 for fontification also in regions already fontified.
632 You may also set this on a per-file basis by adding one of the following
633 lines to the buffer:
635 #+STARTUP: odd
636 #+STARTUP: oddeven"
637 :group 'org-edit-structure
638 :group 'org-font-lock
639 :type 'boolean)
641 (defcustom org-adapt-indentation t
642 "Non-nil means, adapt indentation when promoting and demoting.
643 When this is set and the *entire* text in an entry is indented, the
644 indentation is increased by one space in a demotion command, and
645 decreased by one in a promotion command. If any line in the entry
646 body starts at column 0, indentation is not changed at all."
647 :group 'org-edit-structure
648 :type 'boolean)
650 (defcustom org-special-ctrl-a/e nil
651 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
652 When t, `C-a' will bring back the cursor to the beginning of the
653 headline text, i.e. after the stars and after a possible TODO keyword.
654 In an item, this will be the position after the bullet.
655 When the cursor is already at that position, another `C-a' will bring
656 it to the beginning of the line.
657 `C-e' will jump to the end of the headline, ignoring the presence of tags
658 in the headline. A second `C-e' will then jump to the true end of the
659 line, after any tags.
660 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
661 and only a directly following, identical keypress will bring the cursor
662 to the special positions."
663 :group 'org-edit-structure
664 :type '(choice
665 (const :tag "off" nil)
666 (const :tag "after bullet first" t)
667 (const :tag "border first" reversed)))
669 (if (fboundp 'defvaralias)
670 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
672 (defcustom org-special-ctrl-k nil
673 "Non-nil means `C-k' will behave specially in headlines.
674 When nil, `C-k' will call the default `kill-line' command.
675 When t, the following will happen while the cursor is in the headline:
677 - When the cursor is at the beginning of a headline, kill the entire
678 line and possible the folded subtree below the line.
679 - When in the middle of the headline text, kill the headline up to the tags.
680 - When after the headline text, kill the tags."
681 :group 'org-edit-structure
682 :type 'boolean)
684 (defcustom org-yank-folded-subtrees t
685 "Non-nil means, when yanking subtrees, fold them.
686 If the kill is a single subtree, or a sequence of subtrees, i.e. if
687 it starts with a heading and all other headings in it are either children
688 or siblings, then fold all the subtrees. However, do this only if no
689 text after the yank would be swallowed into a folded tree by this action."
690 :group 'org-edit-structure
691 :type 'boolean)
693 (defcustom org-yank-adjusted-subtrees nil
694 "Non-nil means, when yanking subtrees, adjust the level.
695 With this setting, `org-paste-subtree' is used to insert the subtree, see
696 this function for details."
697 :group 'org-edit-structure
698 :type 'boolean)
700 (defcustom org-M-RET-may-split-line '((default . t))
701 "Non-nil means, M-RET will split the line at the cursor position.
702 When nil, it will go to the end of the line before making a
703 new line.
704 You may also set this option in a different way for different
705 contexts. Valid contexts are:
707 headline when creating a new headline
708 item when creating a new item
709 table in a table field
710 default the value to be used for all contexts not explicitly
711 customized"
712 :group 'org-structure
713 :group 'org-table
714 :type '(choice
715 (const :tag "Always" t)
716 (const :tag "Never" nil)
717 (repeat :greedy t :tag "Individual contexts"
718 (cons
719 (choice :tag "Context"
720 (const headline)
721 (const item)
722 (const table)
723 (const default))
724 (boolean)))))
727 (defcustom org-insert-heading-respect-content nil
728 "Non-nil means, insert new headings after the current subtree.
729 When nil, the new heading is created directly after the current line.
730 The commands \\[org-insert-heading-respect-content] and
731 \\[org-insert-todo-heading-respect-content] turn this variable on
732 for the duration of the command."
733 :group 'org-structure
734 :type 'boolean)
736 (defcustom org-blank-before-new-entry '((heading . auto)
737 (plain-list-item . auto))
738 "Should `org-insert-heading' leave a blank line before new heading/item?
739 The value is an alist, with `heading' and `plain-list-item' as car,
740 and a boolean flag as cdr."
741 :group 'org-edit-structure
742 :type '(list
743 (cons (const heading)
744 (choice (const :tag "Never" nil)
745 (const :tag "Always" t)
746 (const :tag "Auto" auto)))
747 (cons (const plain-list-item)
748 (choice (const :tag "Never" nil)
749 (const :tag "Always" t)
750 (const :tag "Auto" auto)))))
752 (defcustom org-insert-heading-hook nil
753 "Hook being run after inserting a new heading."
754 :group 'org-edit-structure
755 :type 'hook)
757 (defcustom org-enable-fixed-width-editor t
758 "Non-nil means, lines starting with \":\" are treated as fixed-width.
759 This currently only means, they are never auto-wrapped.
760 When nil, such lines will be treated like ordinary lines.
761 See also the QUOTE keyword."
762 :group 'org-edit-structure
763 :type 'boolean)
765 (defcustom org-edit-src-region-extra nil
766 "Additional regexps to identify regions for editing with `org-edit-src-code'.
767 For examples see the function `org-edit-src-find-region-and-lang'.
768 The regular expression identifying the begin marker should end with a newline,
769 and the regexp marking the end line should start with a newline, to make sure
770 there are kept outside the narrowed region."
771 :group 'org-edit-structure
772 :type '(repeat
773 (list
774 (regexp :tag "begin regexp")
775 (regexp :tag "end regexp")
776 (choice :tag "language"
777 (string :tag "specify")
778 (integer :tag "from match group")
779 (const :tag "from `lang' element")
780 (const :tag "from `style' element")))))
782 (defcustom org-coderef-label-format "(ref:%s)"
783 "The default coderef format.
784 This format string will be used to search for coderef labels in literal
785 examples (EXAMPLE and SRC blocks). The format can be overwritten
786 an individual literal example with the -f option, like
788 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
790 #+END_SRC
792 If you want to use this for HTML export, make sure that the format does
793 not introduce special font-locking, and avoid the HTML special
794 characters `<', `>', and `&'. The reason for this restriction is that
795 the labels are searched for only after htmlize has done its job."
796 :group 'org-edit-structure ; FIXME this is not in the right group
797 :type 'string)
799 (defcustom org-edit-fixed-width-region-mode 'artist-mode
800 "The mode that should be used to edit fixed-width regions.
801 These are the regions where each line starts with a colon."
802 :group 'org-edit-structure
803 :type '(choice
804 (const artist-mode)
805 (const picture-mode)
806 (const fundamental-mode)
807 (function :tag "Other (specify)")))
809 (defcustom org-goto-auto-isearch t
810 "Non-nil means, typing characters in org-goto starts incremental search."
811 :group 'org-edit-structure
812 :type 'boolean)
814 (defgroup org-sparse-trees nil
815 "Options concerning sparse trees in Org-mode."
816 :tag "Org Sparse Trees"
817 :group 'org-structure)
819 (defcustom org-highlight-sparse-tree-matches t
820 "Non-nil means, highlight all matches that define a sparse tree.
821 The highlights will automatically disappear the next time the buffer is
822 changed by an edit command."
823 :group 'org-sparse-trees
824 :type 'boolean)
826 (defcustom org-remove-highlights-with-change t
827 "Non-nil means, any change to the buffer will remove temporary highlights.
828 Such highlights are created by `org-occur' and `org-clock-display'.
829 When nil, `C-c C-c needs to be used to get rid of the highlights.
830 The highlights created by `org-preview-latex-fragment' always need
831 `C-c C-c' to be removed."
832 :group 'org-sparse-trees
833 :group 'org-time
834 :type 'boolean)
837 (defcustom org-occur-hook '(org-first-headline-recenter)
838 "Hook that is run after `org-occur' has constructed a sparse tree.
839 This can be used to recenter the window to show as much of the structure
840 as possible."
841 :group 'org-sparse-trees
842 :type 'hook)
844 (defgroup org-imenu-and-speedbar nil
845 "Options concerning imenu and speedbar in Org-mode."
846 :tag "Org Imenu and Speedbar"
847 :group 'org-structure)
849 (defcustom org-imenu-depth 2
850 "The maximum level for Imenu access to Org-mode headlines.
851 This also applied for speedbar access."
852 :group 'org-imenu-and-speedbar
853 :type 'number)
855 (defgroup org-table nil
856 "Options concerning tables in Org-mode."
857 :tag "Org Table"
858 :group 'org)
860 (defcustom org-enable-table-editor 'optimized
861 "Non-nil means, lines starting with \"|\" are handled by the table editor.
862 When nil, such lines will be treated like ordinary lines.
864 When equal to the symbol `optimized', the table editor will be optimized to
865 do the following:
866 - Automatic overwrite mode in front of whitespace in table fields.
867 This makes the structure of the table stay in tact as long as the edited
868 field does not exceed the column width.
869 - Minimize the number of realigns. Normally, the table is aligned each time
870 TAB or RET are pressed to move to another field. With optimization this
871 happens only if changes to a field might have changed the column width.
872 Optimization requires replacing the functions `self-insert-command',
873 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
874 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
875 very good at guessing when a re-align will be necessary, but you can always
876 force one with \\[org-ctrl-c-ctrl-c].
878 If you would like to use the optimized version in Org-mode, but the
879 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
881 This variable can be used to turn on and off the table editor during a session,
882 but in order to toggle optimization, a restart is required.
884 See also the variable `org-table-auto-blank-field'."
885 :group 'org-table
886 :type '(choice
887 (const :tag "off" nil)
888 (const :tag "on" t)
889 (const :tag "on, optimized" optimized)))
891 (defcustom org-table-tab-recognizes-table.el t
892 "Non-nil means, TAB will automatically notice a table.el table.
893 When it sees such a table, it moves point into it and - if necessary -
894 calls `table-recognize-table'."
895 :group 'org-table-editing
896 :type 'boolean)
898 (defgroup org-link nil
899 "Options concerning links in Org-mode."
900 :tag "Org Link"
901 :group 'org)
903 (defvar org-link-abbrev-alist-local nil
904 "Buffer-local version of `org-link-abbrev-alist', which see.
905 The value of this is taken from the #+LINK lines.")
906 (make-variable-buffer-local 'org-link-abbrev-alist-local)
908 (defcustom org-link-abbrev-alist nil
909 "Alist of link abbreviations.
910 The car of each element is a string, to be replaced at the start of a link.
911 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
912 links in Org-mode buffers can have an optional tag after a double colon, e.g.
914 [[linkkey:tag][description]]
916 If REPLACE is a string, the tag will simply be appended to create the link.
917 If the string contains \"%s\", the tag will be inserted there. Alternatively,
918 the placeholder \"%h\" will cause a url-encoded version of the tag to
919 be inserted at that point (see the function `url-hexify-string').
921 REPLACE may also be a function that will be called with the tag as the
922 only argument to create the link, which should be returned as a string.
924 See the manual for examples."
925 :group 'org-link
926 :type '(repeat
927 (cons
928 (string :tag "Protocol")
929 (choice
930 (string :tag "Format")
931 (function)))))
933 (defcustom org-descriptive-links t
934 "Non-nil means, hide link part and only show description of bracket links.
935 Bracket links are like [[link][description]]. This variable sets the initial
936 state in new org-mode buffers. The setting can then be toggled on a
937 per-buffer basis from the Org->Hyperlinks menu."
938 :group 'org-link
939 :type 'boolean)
941 (defcustom org-link-file-path-type 'adaptive
942 "How the path name in file links should be stored.
943 Valid values are:
945 relative Relative to the current directory, i.e. the directory of the file
946 into which the link is being inserted.
947 absolute Absolute path, if possible with ~ for home directory.
948 noabbrev Absolute path, no abbreviation of home directory.
949 adaptive Use relative path for files in the current directory and sub-
950 directories of it. For other files, use an absolute path."
951 :group 'org-link
952 :type '(choice
953 (const relative)
954 (const absolute)
955 (const noabbrev)
956 (const adaptive)))
958 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
959 "Types of links that should be activated in Org-mode files.
960 This is a list of symbols, each leading to the activation of a certain link
961 type. In principle, it does not hurt to turn on most link types - there may
962 be a small gain when turning off unused link types. The types are:
964 bracket The recommended [[link][description]] or [[link]] links with hiding.
965 angular Links in angular brackets that may contain whitespace like
966 <bbdb:Carsten Dominik>.
967 plain Plain links in normal text, no whitespace, like http://google.com.
968 radio Text that is matched by a radio target, see manual for details.
969 tag Tag settings in a headline (link to tag search).
970 date Time stamps (link to calendar).
971 footnote Footnote labels.
973 Changing this variable requires a restart of Emacs to become effective."
974 :group 'org-link
975 :type '(set :greedy t
976 (const :tag "Double bracket links (new style)" bracket)
977 (const :tag "Angular bracket links (old style)" angular)
978 (const :tag "Plain text links" plain)
979 (const :tag "Radio target matches" radio)
980 (const :tag "Tags" tag)
981 (const :tag "Timestamps" date)
982 (const :tag "Footnotes" footnote)))
984 (defcustom org-make-link-description-function nil
985 "Function to use to generate link descriptions from links. If
986 nil the link location will be used. This function must take two
987 parameters; the first is the link and the second the description
988 org-insert-link has generated, and should return the description
989 to use."
990 :group 'org-link
991 :type 'function)
993 (defgroup org-link-store nil
994 "Options concerning storing links in Org-mode."
995 :tag "Org Store Link"
996 :group 'org-link)
998 (defcustom org-email-link-description-format "Email %c: %.30s"
999 "Format of the description part of a link to an email or usenet message.
1000 The following %-escapes will be replaced by corresponding information:
1002 %F full \"From\" field
1003 %f name, taken from \"From\" field, address if no name
1004 %T full \"To\" field
1005 %t first name in \"To\" field, address if no name
1006 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1007 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1008 %s subject
1009 %m message-id.
1011 You may use normal field width specification between the % and the letter.
1012 This is for example useful to limit the length of the subject.
1014 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1015 :group 'org-link-store
1016 :type 'string)
1018 (defcustom org-from-is-user-regexp
1019 (let (r1 r2)
1020 (when (and user-mail-address (not (string= user-mail-address "")))
1021 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1022 (when (and user-full-name (not (string= user-full-name "")))
1023 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1024 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1025 "Regexp matched against the \"From:\" header of an email or usenet message.
1026 It should match if the message is from the user him/herself."
1027 :group 'org-link-store
1028 :type 'regexp)
1030 (defcustom org-link-to-org-use-id 'create-if-interactive
1031 "Non-nil means, storing a link to an Org file will use entry IDs.
1033 Note that before this variable is even considered, org-id must be loaded,
1034 to please customize `org-modules' and turn it on.
1036 The variable can have the following values:
1038 t Create an ID if needed to make a link to the current entry.
1040 create-if-interactive
1041 If `org-store-link' is called directly (interactively, as a user
1042 command), do create an ID to support the link. But when doing the
1043 job for remember, only use the ID if it already exists. The
1044 purpose of this setting is to avoid proliferation of unwanted
1045 IDs, just because you happen to be in an Org file when you
1046 call `org-remember' that automatically and preemptively
1047 creates a link. If you do want to get an ID link in a remember
1048 template to an entry not having an ID, create it first by
1049 explicitly creating a link to it, using `C-c C-l' first.
1051 use-existing
1052 Use existing ID, do not create one.
1054 nil Never use an ID to make a link, instead link using a text search for
1055 the headline text."
1056 :group 'org-link-store
1057 :type '(choice
1058 (const :tag "Create ID to make link" t)
1059 (const :tag "Create if string link interactively"
1060 'create-if-interactive)
1061 (const :tag "Only use existing" 'use-existing)
1062 (const :tag "Do not use ID to create link" nil)))
1064 (defcustom org-context-in-file-links t
1065 "Non-nil means, file links from `org-store-link' contain context.
1066 A search string will be added to the file name with :: as separator and
1067 used to find the context when the link is activated by the command
1068 `org-open-at-point'.
1069 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1070 negates this setting for the duration of the command."
1071 :group 'org-link-store
1072 :type 'boolean)
1074 (defcustom org-keep-stored-link-after-insertion nil
1075 "Non-nil means, keep link in list for entire session.
1077 The command `org-store-link' adds a link pointing to the current
1078 location to an internal list. These links accumulate during a session.
1079 The command `org-insert-link' can be used to insert links into any
1080 Org-mode file (offering completion for all stored links). When this
1081 option is nil, every link which has been inserted once using \\[org-insert-link]
1082 will be removed from the list, to make completing the unused links
1083 more efficient."
1084 :group 'org-link-store
1085 :type 'boolean)
1087 (defgroup org-link-follow nil
1088 "Options concerning following links in Org-mode."
1089 :tag "Org Follow Link"
1090 :group 'org-link)
1092 (defcustom org-link-translation-function nil
1093 "Function to translate links with different syntax to Org syntax.
1094 This can be used to translate links created for example by the Planner
1095 or emacs-wiki packages to Org syntax.
1096 The function must accept two parameters, a TYPE containing the link
1097 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1098 which is everything after the link protocol. It should return a cons
1099 with possibly modified values of type and path.
1100 Org contains a function for this, so if you set this variable to
1101 `org-translate-link-from-planner', you should be able follow many
1102 links created by planner."
1103 :group 'org-link-follow
1104 :type 'function)
1106 (defcustom org-follow-link-hook nil
1107 "Hook that is run after a link has been followed."
1108 :group 'org-link-follow
1109 :type 'hook)
1111 (defcustom org-tab-follows-link nil
1112 "Non-nil means, on links TAB will follow the link.
1113 Needs to be set before org.el is loaded.
1114 This really should not be used, it does not make sense, and the
1115 implementation is bad."
1116 :group 'org-link-follow
1117 :type 'boolean)
1119 (defcustom org-return-follows-link nil
1120 "Non-nil means, on links RET will follow the link.
1121 Needs to be set before org.el is loaded."
1122 :group 'org-link-follow
1123 :type 'boolean)
1125 (defcustom org-mouse-1-follows-link
1126 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1127 "Non-nil means, mouse-1 on a link will follow the link.
1128 A longer mouse click will still set point. Does not work on XEmacs.
1129 Needs to be set before org.el is loaded."
1130 :group 'org-link-follow
1131 :type 'boolean)
1133 (defcustom org-mark-ring-length 4
1134 "Number of different positions to be recorded in the ring
1135 Changing this requires a restart of Emacs to work correctly."
1136 :group 'org-link-follow
1137 :type 'integer)
1139 (defcustom org-link-frame-setup
1140 '((vm . vm-visit-folder-other-frame)
1141 (gnus . gnus-other-frame)
1142 (file . find-file-other-window))
1143 "Setup the frame configuration for following links.
1144 When following a link with Emacs, it may often be useful to display
1145 this link in another window or frame. This variable can be used to
1146 set this up for the different types of links.
1147 For VM, use any of
1148 `vm-visit-folder'
1149 `vm-visit-folder-other-frame'
1150 For Gnus, use any of
1151 `gnus'
1152 `gnus-other-frame'
1153 `org-gnus-no-new-news'
1154 For FILE, use any of
1155 `find-file'
1156 `find-file-other-window'
1157 `find-file-other-frame'
1158 For the calendar, use the variable `calendar-setup'.
1159 For BBDB, it is currently only possible to display the matches in
1160 another window."
1161 :group 'org-link-follow
1162 :type '(list
1163 (cons (const vm)
1164 (choice
1165 (const vm-visit-folder)
1166 (const vm-visit-folder-other-window)
1167 (const vm-visit-folder-other-frame)))
1168 (cons (const gnus)
1169 (choice
1170 (const gnus)
1171 (const gnus-other-frame)
1172 (const org-gnus-no-new-news)))
1173 (cons (const file)
1174 (choice
1175 (const find-file)
1176 (const find-file-other-window)
1177 (const find-file-other-frame)))))
1179 (defcustom org-display-internal-link-with-indirect-buffer nil
1180 "Non-nil means, use indirect buffer to display infile links.
1181 Activating internal links (from one location in a file to another location
1182 in the same file) normally just jumps to the location. When the link is
1183 activated with a C-u prefix (or with mouse-3), the link is displayed in
1184 another window. When this option is set, the other window actually displays
1185 an indirect buffer clone of the current buffer, to avoid any visibility
1186 changes to the current buffer."
1187 :group 'org-link-follow
1188 :type 'boolean)
1190 (defcustom org-open-non-existing-files nil
1191 "Non-nil means, `org-open-file' will open non-existing files.
1192 When nil, an error will be generated."
1193 :group 'org-link-follow
1194 :type 'boolean)
1196 (defcustom org-open-directory-means-index-dot-org nil
1197 "Non-nil means, a link to a directory really means to index.org.
1198 When nil, following a directory link will run dired or open a finder/explorer
1199 window on that directory."
1200 :group 'org-link-follow
1201 :type 'boolean)
1203 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1204 "Function and arguments to call for following mailto links.
1205 This is a list with the first element being a lisp function, and the
1206 remaining elements being arguments to the function. In string arguments,
1207 %a will be replaced by the address, and %s will be replaced by the subject
1208 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1209 :group 'org-link-follow
1210 :type '(choice
1211 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1212 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1213 (const :tag "message-mail" (message-mail "%a" "%s"))
1214 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1216 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1217 "Non-nil means, ask for confirmation before executing shell links.
1218 Shell links can be dangerous: just think about a link
1220 [[shell:rm -rf ~/*][Google Search]]
1222 This link would show up in your Org-mode document as \"Google Search\",
1223 but really it would remove your entire home directory.
1224 Therefore we advise against setting this variable to nil.
1225 Just change it to `y-or-n-p' of you want to confirm with a
1226 single keystroke rather than having to type \"yes\"."
1227 :group 'org-link-follow
1228 :type '(choice
1229 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1230 (const :tag "with y-or-n (faster)" y-or-n-p)
1231 (const :tag "no confirmation (dangerous)" nil)))
1233 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1234 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1235 Elisp links can be dangerous: just think about a link
1237 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1239 This link would show up in your Org-mode document as \"Google Search\",
1240 but really it would remove your entire home directory.
1241 Therefore we advise against setting this variable to nil.
1242 Just change it to `y-or-n-p' of you want to confirm with a
1243 single keystroke rather than having to type \"yes\"."
1244 :group 'org-link-follow
1245 :type '(choice
1246 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1247 (const :tag "with y-or-n (faster)" y-or-n-p)
1248 (const :tag "no confirmation (dangerous)" nil)))
1250 (defconst org-file-apps-defaults-gnu
1251 '((remote . emacs)
1252 (system . mailcap)
1253 (t . mailcap))
1254 "Default file applications on a UNIX or GNU/Linux system.
1255 See `org-file-apps'.")
1257 (defconst org-file-apps-defaults-macosx
1258 '((remote . emacs)
1259 (t . "open %s")
1260 (system . "open %s")
1261 ("ps.gz" . "gv %s")
1262 ("eps.gz" . "gv %s")
1263 ("dvi" . "xdvi %s")
1264 ("fig" . "xfig %s"))
1265 "Default file applications on a MacOS X system.
1266 The system \"open\" is known as a default, but we use X11 applications
1267 for some files for which the OS does not have a good default.
1268 See `org-file-apps'.")
1270 (defconst org-file-apps-defaults-windowsnt
1271 (list
1272 '(remote . emacs)
1273 (cons t
1274 (list (if (featurep 'xemacs)
1275 'mswindows-shell-execute
1276 'w32-shell-execute)
1277 "open" 'file))
1278 (cons 'system
1279 (list (if (featurep 'xemacs)
1280 'mswindows-shell-execute
1281 'w32-shell-execute)
1282 "open" 'file)))
1283 "Default file applications on a Windows NT system.
1284 The system \"open\" is used for most files.
1285 See `org-file-apps'.")
1287 (defcustom org-file-apps
1289 (auto-mode . emacs)
1290 ("\\.x?html?\\'" . default)
1291 ("\\.pdf\\'" . default)
1293 "External applications for opening `file:path' items in a document.
1294 Org-mode uses system defaults for different file types, but
1295 you can use this variable to set the application for a given file
1296 extension. The entries in this list are cons cells where the car identifies
1297 files and the cdr the corresponding command. Possible values for the
1298 file identifier are
1299 \"regex\" Regular expression matched against the file name. For backward
1300 compatibility, this can also be a string with only alphanumeric
1301 characters, which is then interpreted as an extension.
1302 `directory' Matches a directory
1303 `remote' Matches a remote file, accessible through tramp or efs.
1304 Remote files most likely should be visited through Emacs
1305 because external applications cannot handle such paths.
1306 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1307 so all files Emacs knows how to handle. Using this with
1308 command `emacs' will open most files in Emacs. Beware that this
1309 will also open html files inside Emacs, unless you add
1310 (\"html\" . default) to the list as well.
1311 t Default for files not matched by any of the other options.
1312 `system' The system command to open files, like `open' on Windows
1313 and Mac OS X, and mailcap under GNU/Linux. This is the command
1314 that will be selected if you call `C-c C-o' with a double
1315 `C-u C-u' prefix.
1317 Possible values for the command are:
1318 `emacs' The file will be visited by the current Emacs process.
1319 `default' Use the default application for this file type, which is the
1320 association for t in the list, most likely in the system-specific
1321 part.
1322 This can be used to overrule an unwanted setting in the
1323 system-specific variable.
1324 `system' Use the system command for opening files, like \"open\".
1325 This command is specified by the entry whose car is `system'.
1326 Most likely, the system-specific version of this variable
1327 does define this command, but you can overrule/replace it
1328 here.
1329 string A command to be executed by a shell; %s will be replaced
1330 by the path to the file.
1331 sexp A Lisp form which will be evaluated. The file path will
1332 be available in the Lisp variable `file'.
1333 For more examples, see the system specific constants
1334 `org-file-apps-defaults-macosx'
1335 `org-file-apps-defaults-windowsnt'
1336 `org-file-apps-defaults-gnu'."
1337 :group 'org-link-follow
1338 :type '(repeat
1339 (cons (choice :value ""
1340 (string :tag "Extension")
1341 (const :tag "System command to open files" system)
1342 (const :tag "Default for unrecognized files" t)
1343 (const :tag "Remote file" remote)
1344 (const :tag "Links to a directory" directory)
1345 (const :tag "Any files that have Emacs modes"
1346 auto-mode))
1347 (choice :value ""
1348 (const :tag "Visit with Emacs" emacs)
1349 (const :tag "Use default" default)
1350 (const :tag "Use the system command" system)
1351 (string :tag "Command")
1352 (sexp :tag "Lisp form")))))
1354 (defgroup org-refile nil
1355 "Options concerning refiling entries in Org-mode."
1356 :tag "Org Refile"
1357 :group 'org)
1359 (defcustom org-directory "~/org"
1360 "Directory with org files.
1361 This is just a default location to look for Org files. There is no need
1362 at all to put your files into this directory. It is only used in the
1363 following situations:
1365 1. When a remember template specifies a target file that is not an
1366 absolute path. The path will then be interpreted relative to
1367 `org-directory'
1368 2. When a remember note is filed away in an interactive way (when exiting the
1369 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1370 with `org-directory' as the default path."
1371 :group 'org-refile
1372 :group 'org-remember
1373 :type 'directory)
1375 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1376 "Default target for storing notes.
1377 Used by the hooks for remember.el. This can be a string, or nil to mean
1378 the value of `remember-data-file'.
1379 You can set this on a per-template basis with the variable
1380 `org-remember-templates'."
1381 :group 'org-refile
1382 :group 'org-remember
1383 :type '(choice
1384 (const :tag "Default from remember-data-file" nil)
1385 file))
1387 (defcustom org-goto-interface 'outline
1388 "The default interface to be used for `org-goto'.
1389 Allowed values are:
1390 outline The interface shows an outline of the relevant file
1391 and the correct heading is found by moving through
1392 the outline or by searching with incremental search.
1393 outline-path-completion Headlines in the current buffer are offered via
1394 completion. This is the interface also used by
1395 the refile command."
1396 :group 'org-refile
1397 :type '(choice
1398 (const :tag "Outline" outline)
1399 (const :tag "Outline-path-completion" outline-path-completion)))
1401 (defcustom org-goto-max-level 5
1402 "Maximum level to be considered when running org-goto with refile interface."
1403 :group 'org-refile
1404 :type 'number)
1406 (defcustom org-reverse-note-order nil
1407 "Non-nil means, store new notes at the beginning of a file or entry.
1408 When nil, new notes will be filed to the end of a file or entry.
1409 This can also be a list with cons cells of regular expressions that
1410 are matched against file names, and values."
1411 :group 'org-remember
1412 :group 'org-refile
1413 :type '(choice
1414 (const :tag "Reverse always" t)
1415 (const :tag "Reverse never" nil)
1416 (repeat :tag "By file name regexp"
1417 (cons regexp boolean))))
1419 (defcustom org-refile-targets nil
1420 "Targets for refiling entries with \\[org-refile].
1421 This is list of cons cells. Each cell contains:
1422 - a specification of the files to be considered, either a list of files,
1423 or a symbol whose function or variable value will be used to retrieve
1424 a file name or a list of file names. If you use `org-agenda-files' for
1425 that, all agenda files will be scanned for targets. Nil means, consider
1426 headings in the current buffer.
1427 - A specification of how to find candidate refile targets. This may be
1428 any of:
1429 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1430 This tag has to be present in all target headlines, inheritance will
1431 not be considered.
1432 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1433 todo keyword.
1434 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1435 headlines that are refiling targets.
1436 - a cons cell (:level . N). Any headline of level N is considered a target.
1437 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1439 When this variable is nil, all top-level headlines in the current buffer
1440 are used, equivalent to the value `((nil . (:level . 1))'."
1441 :group 'org-refile
1442 :type '(repeat
1443 (cons
1444 (choice :value org-agenda-files
1445 (const :tag "All agenda files" org-agenda-files)
1446 (const :tag "Current buffer" nil)
1447 (function) (variable) (file))
1448 (choice :tag "Identify target headline by"
1449 (cons :tag "Specific tag" (const :value :tag) (string))
1450 (cons :tag "TODO keyword" (const :value :todo) (string))
1451 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1452 (cons :tag "Level number" (const :value :level) (integer))
1453 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1455 (defcustom org-refile-use-outline-path nil
1456 "Non-nil means, provide refile targets as paths.
1457 So a level 3 headline will be available as level1/level2/level3.
1458 When the value is `file', also include the file name (without directory)
1459 into the path. When `full-file-path', include the full file path."
1460 :group 'org-refile
1461 :type '(choice
1462 (const :tag "Not" nil)
1463 (const :tag "Yes" t)
1464 (const :tag "Start with file name" file)
1465 (const :tag "Start with full file path" full-file-path)))
1467 (defcustom org-outline-path-complete-in-steps t
1468 "Non-nil means, complete the outline path in hierarchical steps.
1469 When Org-mode uses the refile interface to select an outline path
1470 \(see variable `org-refile-use-outline-path'), the completion of
1471 the path can be done is a single go, or if can be done in steps down
1472 the headline hierarchy. Going in steps is probably the best if you
1473 do not use a special completion package like `ido' or `icicles'.
1474 However, when using these packages, going in one step can be very
1475 fast, while still showing the whole path to the entry."
1476 :group 'org-refile
1477 :type 'boolean)
1479 (defgroup org-todo nil
1480 "Options concerning TODO items in Org-mode."
1481 :tag "Org TODO"
1482 :group 'org)
1484 (defgroup org-progress nil
1485 "Options concerning Progress logging in Org-mode."
1486 :tag "Org Progress"
1487 :group 'org-time)
1489 (defvar org-todo-interpretation-widgets
1491 (:tag "Sequence (cycling hits every state)" sequence)
1492 (:tag "Type (cycling directly to DONE)" type))
1493 "The available interpretation symbols for customizing
1494 `org-todo-keywords'.
1495 Interested libraries should add to this list.")
1497 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1498 "List of TODO entry keyword sequences and their interpretation.
1499 \\<org-mode-map>This is a list of sequences.
1501 Each sequence starts with a symbol, either `sequence' or `type',
1502 indicating if the keywords should be interpreted as a sequence of
1503 action steps, or as different types of TODO items. The first
1504 keywords are states requiring action - these states will select a headline
1505 for inclusion into the global TODO list Org-mode produces. If one of
1506 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1507 signify that no further action is necessary. If \"|\" is not found,
1508 the last keyword is treated as the only DONE state of the sequence.
1510 The command \\[org-todo] cycles an entry through these states, and one
1511 additional state where no keyword is present. For details about this
1512 cycling, see the manual.
1514 TODO keywords and interpretation can also be set on a per-file basis with
1515 the special #+SEQ_TODO and #+TYP_TODO lines.
1517 Each keyword can optionally specify a character for fast state selection
1518 \(in combination with the variable `org-use-fast-todo-selection')
1519 and specifiers for state change logging, using the same syntax
1520 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1521 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1522 indicates to record a time stamp each time this state is selected.
1524 Each keyword may also specify if a timestamp or a note should be
1525 recorded when entering or leaving the state, by adding additional
1526 characters in the parenthesis after the keyword. This looks like this:
1527 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1528 record only the time of the state change. With X and Y being either
1529 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1530 Y when leaving the state if and only if the *target* state does not
1531 define X. You may omit any of the fast-selection key or X or /Y,
1532 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1534 For backward compatibility, this variable may also be just a list
1535 of keywords - in this case the interpretation (sequence or type) will be
1536 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1537 :group 'org-todo
1538 :group 'org-keywords
1539 :type '(choice
1540 (repeat :tag "Old syntax, just keywords"
1541 (string :tag "Keyword"))
1542 (repeat :tag "New syntax"
1543 (cons
1544 (choice
1545 :tag "Interpretation"
1546 ;;Quick and dirty way to see
1547 ;;`org-todo-interpretations'. This takes the
1548 ;;place of item arguments
1549 :convert-widget
1550 (lambda (widget)
1551 (widget-put widget
1552 :args (mapcar
1553 #'(lambda (x)
1554 (widget-convert
1555 (cons 'const x)))
1556 org-todo-interpretation-widgets))
1557 widget))
1558 (repeat
1559 (string :tag "Keyword"))))))
1561 (defvar org-todo-keywords-1 nil
1562 "All TODO and DONE keywords active in a buffer.")
1563 (make-variable-buffer-local 'org-todo-keywords-1)
1564 (defvar org-todo-keywords-for-agenda nil)
1565 (defvar org-done-keywords-for-agenda nil)
1566 (defvar org-todo-keyword-alist-for-agenda nil)
1567 (defvar org-tag-alist-for-agenda nil)
1568 (defvar org-agenda-contributing-files nil)
1569 (defvar org-not-done-keywords nil)
1570 (make-variable-buffer-local 'org-not-done-keywords)
1571 (defvar org-done-keywords nil)
1572 (make-variable-buffer-local 'org-done-keywords)
1573 (defvar org-todo-heads nil)
1574 (make-variable-buffer-local 'org-todo-heads)
1575 (defvar org-todo-sets nil)
1576 (make-variable-buffer-local 'org-todo-sets)
1577 (defvar org-todo-log-states nil)
1578 (make-variable-buffer-local 'org-todo-log-states)
1579 (defvar org-todo-kwd-alist nil)
1580 (make-variable-buffer-local 'org-todo-kwd-alist)
1581 (defvar org-todo-key-alist nil)
1582 (make-variable-buffer-local 'org-todo-key-alist)
1583 (defvar org-todo-key-trigger nil)
1584 (make-variable-buffer-local 'org-todo-key-trigger)
1586 (defcustom org-todo-interpretation 'sequence
1587 "Controls how TODO keywords are interpreted.
1588 This variable is in principle obsolete and is only used for
1589 backward compatibility, if the interpretation of todo keywords is
1590 not given already in `org-todo-keywords'. See that variable for
1591 more information."
1592 :group 'org-todo
1593 :group 'org-keywords
1594 :type '(choice (const sequence)
1595 (const type)))
1597 (defcustom org-use-fast-todo-selection t
1598 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1599 This variable describes if and under what circumstances the cycling
1600 mechanism for TODO keywords will be replaced by a single-key, direct
1601 selection scheme.
1603 When nil, fast selection is never used.
1605 When the symbol `prefix', it will be used when `org-todo' is called with
1606 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1607 in an agenda buffer.
1609 When t, fast selection is used by default. In this case, the prefix
1610 argument forces cycling instead.
1612 In all cases, the special interface is only used if access keys have actually
1613 been assigned by the user, i.e. if keywords in the configuration are followed
1614 by a letter in parenthesis, like TODO(t)."
1615 :group 'org-todo
1616 :type '(choice
1617 (const :tag "Never" nil)
1618 (const :tag "By default" t)
1619 (const :tag "Only with C-u C-c C-t" prefix)))
1621 (defcustom org-provide-todo-statistics t
1622 "Non-nil means, update todo statistics after insert and toggle.
1623 When this is set, todo statistics is updated in the parent of the current
1624 entry each time a todo state is changed."
1625 :group 'org-todo
1626 :type 'boolean)
1628 (defcustom org-after-todo-state-change-hook nil
1629 "Hook which is run after the state of a TODO item was changed.
1630 The new state (a string with a TODO keyword, or nil) is available in the
1631 Lisp variable `state'."
1632 :group 'org-todo
1633 :type 'hook)
1635 (defvar org-blocker-hook nil
1636 "Hook for functions that are allowed to block a state change.
1638 Each function gets as its single argument a property list, see
1639 `org-trigger-hook' for more information about this list.
1641 If any of the functions in this hook returns nil, the state change
1642 is blocked.")
1644 (defvar org-trigger-hook nil
1645 "Hook for functions that are triggered by a state change.
1647 Each function gets as its single argument a property list with at least
1648 the following elements:
1650 (:type type-of-change :position pos-at-entry-start
1651 :from old-state :to new-state)
1653 Depending on the type, more properties may be present.
1655 This mechanism is currently implemented for:
1657 TODO state changes
1658 ------------------
1659 :type todo-state-change
1660 :from previous state (keyword as a string), or nil, or a symbol
1661 'todo' or 'done', to indicate the general type of state.
1662 :to new state, like in :from")
1664 (defcustom org-enforce-todo-dependencies nil
1665 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1666 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1667 be blocked if any prior sibling is not yet done.
1668 This variable needs to be set before org.el is loaded, and you need to
1669 restart Emacs after a change to make the change effective. The only way
1670 to change is while Emacs is running is through the customize interface."
1671 :set (lambda (var val)
1672 (set var val)
1673 (if val
1674 (add-hook 'org-blocker-hook
1675 'org-block-todo-from-children-or-siblings)
1676 (remove-hook 'org-blocker-hook
1677 'org-block-todo-from-children-or-siblings)))
1678 :group 'org-todo
1679 :type 'boolean)
1681 (defcustom org-enforce-todo-checkbox-dependencies nil
1682 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1683 When this is nil, checkboxes have no influence on switching TODO states.
1684 When non-nil, you first need to check off all check boxes before the TODO
1685 entry can be switched to DONE.
1686 This variable needs to be set before org.el is loaded, and you need to
1687 restart Emacs after a change to make the change effective. The only way
1688 to change is while Emacs is running is through the customize interface."
1689 :set (lambda (var val)
1690 (set var val)
1691 (if val
1692 (add-hook 'org-blocker-hook
1693 'org-block-todo-from-checkboxes)
1694 (remove-hook 'org-blocker-hook
1695 'org-block-todo-from-checkboxes)))
1696 :group 'org-todo
1697 :type 'boolean)
1699 (defcustom org-todo-state-tags-triggers nil
1700 "Tag changes that should be triggered by TODO state changes.
1701 This is a list. Each entry is
1703 (state-change (tag . flag) .......)
1705 State-change can be a string with a state, and empty string to indicate the
1706 state that has no TODO keyword, or it can be one of the symbols `todo'
1707 or `done', meaning any not-done or done state, respectively."
1708 :group 'org-todo
1709 :group 'org-tags
1710 :type '(repeat
1711 (cons (choice :tag "When changing to"
1712 (const :tag "Not-done state" todo)
1713 (const :tag "Done state" done)
1714 (string :tag "State"))
1715 (repeat
1716 (cons :tag "Tag action"
1717 (string :tag "Tag")
1718 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1720 (defcustom org-log-done nil
1721 "Information to record when a task moves to the DONE state.
1723 Possible values are:
1725 nil Don't add anything, just change the keyword
1726 time Add a time stamp to the task
1727 note Prompt a closing note and add it with template `org-log-note-headings'
1729 This option can also be set with on a per-file-basis with
1731 #+STARTUP: nologdone
1732 #+STARTUP: logdone
1733 #+STARTUP: lognotedone
1735 You can have local logging settings for a subtree by setting the LOGGING
1736 property to one or more of these keywords."
1737 :group 'org-todo
1738 :group 'org-progress
1739 :type '(choice
1740 (const :tag "No logging" nil)
1741 (const :tag "Record CLOSED timestamp" time)
1742 (const :tag "Record CLOSED timestamp with closing note." note)))
1744 ;; Normalize old uses of org-log-done.
1745 (cond
1746 ((eq org-log-done t) (setq org-log-done 'time))
1747 ((and (listp org-log-done) (memq 'done org-log-done))
1748 (setq org-log-done 'note)))
1750 (defcustom org-log-note-clock-out nil
1751 "Non-nil means, record a note when clocking out of an item.
1752 This can also be configured on a per-file basis by adding one of
1753 the following lines anywhere in the buffer:
1755 #+STARTUP: lognoteclock-out
1756 #+STARTUP: nolognoteclock-out"
1757 :group 'org-todo
1758 :group 'org-progress
1759 :type 'boolean)
1761 (defcustom org-log-done-with-time t
1762 "Non-nil means, the CLOSED time stamp will contain date and time.
1763 When nil, only the date will be recorded."
1764 :group 'org-progress
1765 :type 'boolean)
1767 (defcustom org-log-note-headings
1768 '((done . "CLOSING NOTE %t")
1769 (state . "State %-12s %t")
1770 (note . "Note taken on %t")
1771 (clock-out . ""))
1772 "Headings for notes added to entries.
1773 The value is an alist, with the car being a symbol indicating the note
1774 context, and the cdr is the heading to be used. The heading may also be the
1775 empty string.
1776 %t in the heading will be replaced by a time stamp.
1777 %s will be replaced by the new TODO state, in double quotes.
1778 %u will be replaced by the user name.
1779 %U will be replaced by the full user name."
1780 :group 'org-todo
1781 :group 'org-progress
1782 :type '(list :greedy t
1783 (cons (const :tag "Heading when closing an item" done) string)
1784 (cons (const :tag
1785 "Heading when changing todo state (todo sequence only)"
1786 state) string)
1787 (cons (const :tag "Heading when just taking a note" note) string)
1788 (cons (const :tag "Heading when clocking out" clock-out) string)))
1790 (unless (assq 'note org-log-note-headings)
1791 (push '(note . "%t") org-log-note-headings))
1793 (defcustom org-log-state-notes-insert-after-drawers nil
1794 "Non-nil means, insert state change notes after any drawers in entry.
1795 Only the drawers that *immediately* follow the headline and the
1796 deadline/scheduled line are skipped.
1797 When nil, insert notes right after the heading and perhaps the line
1798 with deadline/scheduling if present."
1799 :group 'org-todo
1800 :group 'org-progress
1801 :type 'boolean)
1803 (defcustom org-log-states-order-reversed t
1804 "Non-nil means, the latest state change note will be directly after heading.
1805 When nil, the notes will be orderer according to time."
1806 :group 'org-todo
1807 :group 'org-progress
1808 :type 'boolean)
1810 (defcustom org-log-repeat 'time
1811 "Non-nil means, record moving through the DONE state when triggering repeat.
1812 An auto-repeating tasks is immediately switched back to TODO when marked
1813 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1814 the TODO keyword definition, or recording a closing note by setting
1815 `org-log-done', there will be no record of the task moving through DONE.
1816 This variable forces taking a note anyway. Possible values are:
1818 nil Don't force a record
1819 time Record a time stamp
1820 note Record a note
1822 This option can also be set with on a per-file-basis with
1824 #+STARTUP: logrepeat
1825 #+STARTUP: lognoterepeat
1826 #+STARTUP: nologrepeat
1828 You can have local logging settings for a subtree by setting the LOGGING
1829 property to one or more of these keywords."
1830 :group 'org-todo
1831 :group 'org-progress
1832 :type '(choice
1833 (const :tag "Don't force a record" nil)
1834 (const :tag "Force recording the DONE state" time)
1835 (const :tag "Force recording a note with the DONE state" note)))
1838 (defgroup org-priorities nil
1839 "Priorities in Org-mode."
1840 :tag "Org Priorities"
1841 :group 'org-todo)
1843 (defcustom org-highest-priority ?A
1844 "The highest priority of TODO items. A character like ?A, ?B etc.
1845 Must have a smaller ASCII number than `org-lowest-priority'."
1846 :group 'org-priorities
1847 :type 'character)
1849 (defcustom org-lowest-priority ?C
1850 "The lowest priority of TODO items. A character like ?A, ?B etc.
1851 Must have a larger ASCII number than `org-highest-priority'."
1852 :group 'org-priorities
1853 :type 'character)
1855 (defcustom org-default-priority ?B
1856 "The default priority of TODO items.
1857 This is the priority an item get if no explicit priority is given."
1858 :group 'org-priorities
1859 :type 'character)
1861 (defcustom org-priority-start-cycle-with-default t
1862 "Non-nil means, start with default priority when starting to cycle.
1863 When this is nil, the first step in the cycle will be (depending on the
1864 command used) one higher or lower that the default priority."
1865 :group 'org-priorities
1866 :type 'boolean)
1868 (defgroup org-time nil
1869 "Options concerning time stamps and deadlines in Org-mode."
1870 :tag "Org Time"
1871 :group 'org)
1873 (defcustom org-insert-labeled-timestamps-at-point nil
1874 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1875 When nil, these labeled time stamps are forces into the second line of an
1876 entry, just after the headline. When scheduling from the global TODO list,
1877 the time stamp will always be forced into the second line."
1878 :group 'org-time
1879 :type 'boolean)
1881 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1882 "Formats for `format-time-string' which are used for time stamps.
1883 It is not recommended to change this constant.")
1885 (defcustom org-time-stamp-rounding-minutes '(0 5)
1886 "Number of minutes to round time stamps to.
1887 These are two values, the first applies when first creating a time stamp.
1888 The second applies when changing it with the commands `S-up' and `S-down'.
1889 When changing the time stamp, this means that it will change in steps
1890 of N minutes, as given by the second value.
1892 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1893 numbers should be factors of 60, so for example 5, 10, 15.
1895 When this is larger than 1, you can still force an exact time-stamp by using
1896 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1897 and by using a prefix arg to `S-up/down' to specify the exact number
1898 of minutes to shift."
1899 :group 'org-time
1900 :get '(lambda (var) ; Make sure all entries have 5 elements
1901 (if (integerp (default-value var))
1902 (list (default-value var) 5)
1903 (default-value var)))
1904 :type '(list
1905 (integer :tag "when inserting times")
1906 (integer :tag "when modifying times")))
1908 ;; Normalize old customizations of this variable.
1909 (when (integerp org-time-stamp-rounding-minutes)
1910 (setq org-time-stamp-rounding-minutes
1911 (list org-time-stamp-rounding-minutes
1912 org-time-stamp-rounding-minutes)))
1914 (defcustom org-display-custom-times nil
1915 "Non-nil means, overlay custom formats over all time stamps.
1916 The formats are defined through the variable `org-time-stamp-custom-formats'.
1917 To turn this on on a per-file basis, insert anywhere in the file:
1918 #+STARTUP: customtime"
1919 :group 'org-time
1920 :set 'set-default
1921 :type 'sexp)
1922 (make-variable-buffer-local 'org-display-custom-times)
1924 (defcustom org-time-stamp-custom-formats
1925 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1926 "Custom formats for time stamps. See `format-time-string' for the syntax.
1927 These are overlayed over the default ISO format if the variable
1928 `org-display-custom-times' is set. Time like %H:%M should be at the
1929 end of the second format."
1930 :group 'org-time
1931 :type 'sexp)
1933 (defun org-time-stamp-format (&optional long inactive)
1934 "Get the right format for a time string."
1935 (let ((f (if long (cdr org-time-stamp-formats)
1936 (car org-time-stamp-formats))))
1937 (if inactive
1938 (concat "[" (substring f 1 -1) "]")
1939 f)))
1941 (defcustom org-time-clocksum-format "%d:%02d"
1942 "The format string used when creating CLOCKSUM lines, or when
1943 org-mode generates a time duration."
1944 :group 'org-time
1945 :type 'string)
1947 (defcustom org-deadline-warning-days 14
1948 "No. of days before expiration during which a deadline becomes active.
1949 This variable governs the display in sparse trees and in the agenda.
1950 When 0 or negative, it means use this number (the absolute value of it)
1951 even if a deadline has a different individual lead time specified."
1952 :group 'org-time
1953 :group 'org-agenda-daily/weekly
1954 :type 'number)
1956 (defcustom org-read-date-prefer-future t
1957 "Non-nil means, assume future for incomplete date input from user.
1958 This affects the following situations:
1959 1. The user gives a day, but no month.
1960 For example, if today is the 15th, and you enter \"3\", Org-mode will
1961 read this as the third of *next* month. However, if you enter \"17\",
1962 it will be considered as *this* month.
1963 2. The user gives a month but not a year.
1964 For example, if it is april and you enter \"feb 2\", this will be read
1965 as feb 2, *next* year. \"May 5\", however, will be this year.
1967 Currently this does not work for ISO week specifications.
1969 When this option is nil, the current month and year will always be used
1970 as defaults."
1971 :group 'org-time
1972 :type 'boolean)
1974 (defcustom org-read-date-display-live t
1975 "Non-nil means, display current interpretation of date prompt live.
1976 This display will be in an overlay, in the minibuffer."
1977 :group 'org-time
1978 :type 'boolean)
1980 (defcustom org-read-date-popup-calendar t
1981 "Non-nil means, pop up a calendar when prompting for a date.
1982 In the calendar, the date can be selected with mouse-1. However, the
1983 minibuffer will also be active, and you can simply enter the date as well.
1984 When nil, only the minibuffer will be available."
1985 :group 'org-time
1986 :type 'boolean)
1987 (if (fboundp 'defvaralias)
1988 (defvaralias 'org-popup-calendar-for-date-prompt
1989 'org-read-date-popup-calendar))
1991 (defcustom org-extend-today-until 0
1992 "The hour when your day really ends. Must be an integer.
1993 This has influence for the following applications:
1994 - When switching the agenda to \"today\". It it is still earlier than
1995 the time given here, the day recognized as TODAY is actually yesterday.
1996 - When a date is read from the user and it is still before the time given
1997 here, the current date and time will be assumed to be yesterday, 23:59.
1998 Also, timestamps inserted in remember templates follow this rule.
2000 IMPORTANT: This is a feature whose implementation is and likely will
2001 remain incomplete. Really, it is only here because past midnight seems to
2002 be the favorite working time of John Wiegley :-)"
2003 :group 'org-time
2004 :type 'number)
2006 (defcustom org-edit-timestamp-down-means-later nil
2007 "Non-nil means, S-down will increase the time in a time stamp.
2008 When nil, S-up will increase."
2009 :group 'org-time
2010 :type 'boolean)
2012 (defcustom org-calendar-follow-timestamp-change t
2013 "Non-nil means, make the calendar window follow timestamp changes.
2014 When a timestamp is modified and the calendar window is visible, it will be
2015 moved to the new date."
2016 :group 'org-time
2017 :type 'boolean)
2019 (defgroup org-tags nil
2020 "Options concerning tags in Org-mode."
2021 :tag "Org Tags"
2022 :group 'org)
2024 (defcustom org-tag-alist nil
2025 "List of tags allowed in Org-mode files.
2026 When this list is nil, Org-mode will base TAG input on what is already in the
2027 buffer.
2028 The value of this variable is an alist, the car of each entry must be a
2029 keyword as a string, the cdr may be a character that is used to select
2030 that tag through the fast-tag-selection interface.
2031 See the manual for details."
2032 :group 'org-tags
2033 :type '(repeat
2034 (choice
2035 (cons (string :tag "Tag name")
2036 (character :tag "Access char"))
2037 (const :tag "Start radio group" (:startgroup))
2038 (const :tag "End radio group" (:endgroup)))))
2040 (defvar org-file-tags nil
2041 "List of tags that can be inherited by all entries in the file.
2042 The tags will be inherited if the variable `org-use-tag-inheritance'
2043 says they should be.
2044 This variable is populated from #+TAG lines.")
2046 (defcustom org-use-fast-tag-selection 'auto
2047 "Non-nil means, use fast tag selection scheme.
2048 This is a special interface to select and deselect tags with single keys.
2049 When nil, fast selection is never used.
2050 When the symbol `auto', fast selection is used if and only if selection
2051 characters for tags have been configured, either through the variable
2052 `org-tag-alist' or through a #+TAGS line in the buffer.
2053 When t, fast selection is always used and selection keys are assigned
2054 automatically if necessary."
2055 :group 'org-tags
2056 :type '(choice
2057 (const :tag "Always" t)
2058 (const :tag "Never" nil)
2059 (const :tag "When selection characters are configured" 'auto)))
2061 (defcustom org-fast-tag-selection-single-key nil
2062 "Non-nil means, fast tag selection exits after first change.
2063 When nil, you have to press RET to exit it.
2064 During fast tag selection, you can toggle this flag with `C-c'.
2065 This variable can also have the value `expert'. In this case, the window
2066 displaying the tags menu is not even shown, until you press C-c again."
2067 :group 'org-tags
2068 :type '(choice
2069 (const :tag "No" nil)
2070 (const :tag "Yes" t)
2071 (const :tag "Expert" expert)))
2073 (defvar org-fast-tag-selection-include-todo nil
2074 "Non-nil means, fast tags selection interface will also offer TODO states.
2075 This is an undocumented feature, you should not rely on it.")
2077 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2078 "The column to which tags should be indented in a headline.
2079 If this number is positive, it specifies the column. If it is negative,
2080 it means that the tags should be flushright to that column. For example,
2081 -80 works well for a normal 80 character screen."
2082 :group 'org-tags
2083 :type 'integer)
2085 (defcustom org-auto-align-tags t
2086 "Non-nil means, realign tags after pro/demotion of TODO state change.
2087 These operations change the length of a headline and therefore shift
2088 the tags around. With this options turned on, after each such operation
2089 the tags are again aligned to `org-tags-column'."
2090 :group 'org-tags
2091 :type 'boolean)
2093 (defcustom org-use-tag-inheritance t
2094 "Non-nil means, tags in levels apply also for sublevels.
2095 When nil, only the tags directly given in a specific line apply there.
2096 This may also be a list of tags that should be inherited, or a regexp that
2097 matches tags that should be inherited. Additional control is possible
2098 with the variable `org-tags-exclude-from-inheritance' which gives an
2099 explicit list of tags to be excluded from inheritance., even if the value of
2100 `org-use-tag-inheritance' would select it for inheritance.
2102 If this option is t, a match early-on in a tree can lead to a large
2103 number of matches in the subtree when constructing the agenda or creating
2104 a sparse tree. If you only want to see the first match in a tree during
2105 a search, check out the variable `org-tags-match-list-sublevels'."
2106 :group 'org-tags
2107 :type '(choice
2108 (const :tag "Not" nil)
2109 (const :tag "Always" t)
2110 (repeat :tag "Specific tags" (string :tag "Tag"))
2111 (regexp :tag "Tags matched by regexp")))
2113 (defcustom org-tags-exclude-from-inheritance nil
2114 "List of tags that should never be inherited.
2115 This is a way to exclude a few tags from inheritance. For way to do
2116 the opposite, to actively allow inheritance for selected tags,
2117 see the variable `org-use-tag-inheritance'."
2118 :group 'org-tags
2119 :type '(repeat (string :tag "Tag")))
2121 (defun org-tag-inherit-p (tag)
2122 "Check if TAG is one that should be inherited."
2123 (cond
2124 ((member tag org-tags-exclude-from-inheritance) nil)
2125 ((eq org-use-tag-inheritance t) t)
2126 ((not org-use-tag-inheritance) nil)
2127 ((stringp org-use-tag-inheritance)
2128 (string-match org-use-tag-inheritance tag))
2129 ((listp org-use-tag-inheritance)
2130 (member tag org-use-tag-inheritance))
2131 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2133 (defcustom org-tags-match-list-sublevels t
2134 "Non-nil means list also sublevels of headlines matching tag search.
2135 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2136 the sublevels of a headline matching a tag search often also match
2137 the same search. Listing all of them can create very long lists.
2138 Setting this variable to nil causes subtrees of a match to be skipped.
2139 This option is off by default, because inheritance in on. If you turn
2140 inheritance off, you very likely want to turn this option on.
2142 As a special case, if the tag search is restricted to TODO items, the
2143 value of this variable is ignored and sublevels are always checked, to
2144 make sure all corresponding TODO items find their way into the list.
2146 This variable is semi-obsolete and probably should always be true. It
2147 is better to limit inheritance to certain tags using the variables
2148 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2149 :group 'org-tags
2150 :type 'boolean)
2152 (defvar org-tags-history nil
2153 "History of minibuffer reads for tags.")
2154 (defvar org-last-tags-completion-table nil
2155 "The last used completion table for tags.")
2156 (defvar org-after-tags-change-hook nil
2157 "Hook that is run after the tags in a line have changed.")
2159 (defgroup org-properties nil
2160 "Options concerning properties in Org-mode."
2161 :tag "Org Properties"
2162 :group 'org)
2164 (defcustom org-property-format "%-10s %s"
2165 "How property key/value pairs should be formatted by `indent-line'.
2166 When `indent-line' hits a property definition, it will format the line
2167 according to this format, mainly to make sure that the values are
2168 lined-up with respect to each other."
2169 :group 'org-properties
2170 :type 'string)
2172 (defcustom org-use-property-inheritance nil
2173 "Non-nil means, properties apply also for sublevels.
2175 This setting is chiefly used during property searches. Turning it on can
2176 cause significant overhead when doing a search, which is why it is not
2177 on by default.
2179 When nil, only the properties directly given in the current entry count.
2180 When t, every property is inherited. The value may also be a list of
2181 properties that should have inheritance, or a regular expression matching
2182 properties that should be inherited.
2184 However, note that some special properties use inheritance under special
2185 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2186 and the properties ending in \"_ALL\" when they are used as descriptor
2187 for valid values of a property.
2189 Note for programmers:
2190 When querying an entry with `org-entry-get', you can control if inheritance
2191 should be used. By default, `org-entry-get' looks only at the local
2192 properties. You can request inheritance by setting the inherit argument
2193 to t (to force inheritance) or to `selective' (to respect the setting
2194 in this variable)."
2195 :group 'org-properties
2196 :type '(choice
2197 (const :tag "Not" nil)
2198 (const :tag "Always" t)
2199 (repeat :tag "Specific properties" (string :tag "Property"))
2200 (regexp :tag "Properties matched by regexp")))
2202 (defun org-property-inherit-p (property)
2203 "Check if PROPERTY is one that should be inherited."
2204 (cond
2205 ((eq org-use-property-inheritance t) t)
2206 ((not org-use-property-inheritance) nil)
2207 ((stringp org-use-property-inheritance)
2208 (string-match org-use-property-inheritance property))
2209 ((listp org-use-property-inheritance)
2210 (member property org-use-property-inheritance))
2211 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2213 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2214 "The default column format, if no other format has been defined.
2215 This variable can be set on the per-file basis by inserting a line
2217 #+COLUMNS: %25ITEM ....."
2218 :group 'org-properties
2219 :type 'string)
2221 (defcustom org-columns-ellipses ".."
2222 "The ellipses to be used when a field in column view is truncated.
2223 When this is the empty string, as many characters as possible are shown,
2224 but then there will be no visual indication that the field has been truncated.
2225 When this is a string of length N, the last N characters of a truncated
2226 field are replaced by this string. If the column is narrower than the
2227 ellipses string, only part of the ellipses string will be shown."
2228 :group 'org-properties
2229 :type 'string)
2231 (defcustom org-columns-modify-value-for-display-function nil
2232 "Function that modifies values for display in column view.
2233 For example, it can be used to cut out a certain part from a time stamp.
2234 The function must take 2 arguments:
2236 column-title The title of the column (*not* the property name)
2237 value The value that should be modified.
2239 The function should return the value that should be displayed,
2240 or nil if the normal value should be used."
2241 :group 'org-properties
2242 :type 'function)
2244 (defcustom org-effort-property "Effort"
2245 "The property that is being used to keep track of effort estimates.
2246 Effort estimates given in this property need to have the format H:MM."
2247 :group 'org-properties
2248 :group 'org-progress
2249 :type '(string :tag "Property"))
2251 (defconst org-global-properties-fixed
2252 '(("VISIBILITY_ALL" . "folded children content all"))
2253 "List of property/value pairs that can be inherited by any entry.
2254 These are fixed values, for the preset properties.")
2257 (defcustom org-global-properties nil
2258 "List of property/value pairs that can be inherited by any entry.
2259 You can set buffer-local values for the same purpose in the variable
2260 `org-file-properties' this by adding lines like
2262 #+PROPERTY: NAME VALUE"
2263 :group 'org-properties
2264 :type '(repeat
2265 (cons (string :tag "Property")
2266 (string :tag "Value"))))
2268 (defvar org-file-properties nil
2269 "List of property/value pairs that can be inherited by any entry.
2270 Valid for the current buffer.
2271 This variable is populated from #+PROPERTY lines.")
2272 (make-variable-buffer-local 'org-file-properties)
2274 (defgroup org-agenda nil
2275 "Options concerning agenda views in Org-mode."
2276 :tag "Org Agenda"
2277 :group 'org)
2279 (defvar org-category nil
2280 "Variable used by org files to set a category for agenda display.
2281 Such files should use a file variable to set it, for example
2283 # -*- mode: org; org-category: \"ELisp\"
2285 or contain a special line
2287 #+CATEGORY: ELisp
2289 If the file does not specify a category, then file's base name
2290 is used instead.")
2291 (make-variable-buffer-local 'org-category)
2292 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2294 (defcustom org-agenda-files nil
2295 "The files to be used for agenda display.
2296 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2297 \\[org-remove-file]. You can also use customize to edit the list.
2299 If an entry is a directory, all files in that directory that are matched by
2300 `org-agenda-file-regexp' will be part of the file list.
2302 If the value of the variable is not a list but a single file name, then
2303 the list of agenda files is actually stored and maintained in that file, one
2304 agenda file per line."
2305 :group 'org-agenda
2306 :type '(choice
2307 (repeat :tag "List of files and directories" file)
2308 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2310 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2311 "Regular expression to match files for `org-agenda-files'.
2312 If any element in the list in that variable contains a directory instead
2313 of a normal file, all files in that directory that are matched by this
2314 regular expression will be included."
2315 :group 'org-agenda
2316 :type 'regexp)
2318 (defcustom org-agenda-text-search-extra-files nil
2319 "List of extra files to be searched by text search commands.
2320 These files will be search in addition to the agenda files by the
2321 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2322 Note that these files will only be searched for text search commands,
2323 not for the other agenda views like todo lists, tag searches or the weekly
2324 agenda. This variable is intended to list notes and possibly archive files
2325 that should also be searched by these two commands.
2326 In fact, if the first element in the list is the symbol `agenda-archives',
2327 than all archive files of all agenda files will be added to the search
2328 scope."
2329 :group 'org-agenda
2330 :type '(set :greedy t
2331 (const :tag "Agenda Archives" agenda-archives)
2332 (repeat :inline t (file))))
2334 (if (fboundp 'defvaralias)
2335 (defvaralias 'org-agenda-multi-occur-extra-files
2336 'org-agenda-text-search-extra-files))
2338 (defcustom org-agenda-skip-unavailable-files nil
2339 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2340 A nil value means to remove them, after a query, from the list."
2341 :group 'org-agenda
2342 :type 'boolean)
2344 (defcustom org-calendar-to-agenda-key [?c]
2345 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2346 The command `org-calendar-goto-agenda' will be bound to this key. The
2347 default is the character `c' because then `c' can be used to switch back and
2348 forth between agenda and calendar."
2349 :group 'org-agenda
2350 :type 'sexp)
2352 (defcustom org-calendar-agenda-action-key [?k]
2353 "The key to be installed in `calendar-mode-map' for agenda-action.
2354 The command `org-agenda-action' will be bound to this key. The
2355 default is the character `k' because we use the same key in the agenda."
2356 :group 'org-agenda
2357 :type 'sexp)
2359 (eval-after-load "calendar"
2360 '(progn
2361 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2362 'org-calendar-goto-agenda)
2363 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2364 'org-agenda-action)))
2366 (defgroup org-latex nil
2367 "Options for embedding LaTeX code into Org-mode."
2368 :tag "Org LaTeX"
2369 :group 'org)
2371 (defcustom org-format-latex-options
2372 '(:foreground default :background default :scale 1.0
2373 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2374 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2375 "Options for creating images from LaTeX fragments.
2376 This is a property list with the following properties:
2377 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2378 `default' means use the foreground of the default face.
2379 :background the background color, or \"Transparent\".
2380 `default' means use the background of the default face.
2381 :scale a scaling factor for the size of the images.
2382 :html-foreground, :html-background, :html-scale
2383 the same numbers for HTML export.
2384 :matchers a list indicating which matchers should be used to
2385 find LaTeX fragments. Valid members of this list are:
2386 \"begin\" find environments
2387 \"$1\" find single characters surrounded by $.$
2388 \"$\" find math expressions surrounded by $...$
2389 \"$$\" find math expressions surrounded by $$....$$
2390 \"\\(\" find math expressions surrounded by \\(...\\)
2391 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2392 :group 'org-latex
2393 :type 'plist)
2395 (defcustom org-format-latex-header "\\documentclass{article}
2396 \\usepackage{fullpage} % do not remove
2397 \\usepackage{amssymb}
2398 \\usepackage[usenames]{color}
2399 \\usepackage{amsmath}
2400 \\usepackage{latexsym}
2401 \\usepackage[mathscr]{eucal}
2402 \\pagestyle{empty} % do not remove"
2403 "The document header used for processing LaTeX fragments."
2404 :group 'org-latex
2405 :type 'string)
2408 (defgroup org-font-lock nil
2409 "Font-lock settings for highlighting in Org-mode."
2410 :tag "Org Font Lock"
2411 :group 'org)
2413 (defcustom org-level-color-stars-only nil
2414 "Non-nil means fontify only the stars in each headline.
2415 When nil, the entire headline is fontified.
2416 Changing it requires restart of `font-lock-mode' to become effective
2417 also in regions already fontified."
2418 :group 'org-font-lock
2419 :type 'boolean)
2421 (defcustom org-hide-leading-stars nil
2422 "Non-nil means, hide the first N-1 stars in a headline.
2423 This works by using the face `org-hide' for these stars. This
2424 face is white for a light background, and black for a dark
2425 background. You may have to customize the face `org-hide' to
2426 make this work.
2427 Changing it requires restart of `font-lock-mode' to become effective
2428 also in regions already fontified.
2429 You may also set this on a per-file basis by adding one of the following
2430 lines to the buffer:
2432 #+STARTUP: hidestars
2433 #+STARTUP: showstars"
2434 :group 'org-font-lock
2435 :type 'boolean)
2437 (defcustom org-fontify-done-headline nil
2438 "Non-nil means, change the face of a headline if it is marked DONE.
2439 Normally, only the TODO/DONE keyword indicates the state of a headline.
2440 When this is non-nil, the headline after the keyword is set to the
2441 `org-headline-done' as an additional indication."
2442 :group 'org-font-lock
2443 :type 'boolean)
2445 (defcustom org-fontify-emphasized-text t
2446 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2447 Changing this variable requires a restart of Emacs to take effect."
2448 :group 'org-font-lock
2449 :type 'boolean)
2451 (defcustom org-highlight-latex-fragments-and-specials nil
2452 "Non-nil means, fontify what is treated specially by the exporters."
2453 :group 'org-font-lock
2454 :type 'boolean)
2456 (defcustom org-hide-emphasis-markers nil
2457 "Non-nil mean font-lock should hide the emphasis marker characters."
2458 :group 'org-font-lock
2459 :type 'boolean)
2461 (defvar org-emph-re nil
2462 "Regular expression for matching emphasis.")
2463 (defvar org-verbatim-re nil
2464 "Regular expression for matching verbatim text.")
2465 (defvar org-emphasis-regexp-components) ; defined just below
2466 (defvar org-emphasis-alist) ; defined just below
2467 (defun org-set-emph-re (var val)
2468 "Set variable and compute the emphasis regular expression."
2469 (set var val)
2470 (when (and (boundp 'org-emphasis-alist)
2471 (boundp 'org-emphasis-regexp-components)
2472 org-emphasis-alist org-emphasis-regexp-components)
2473 (let* ((e org-emphasis-regexp-components)
2474 (pre (car e))
2475 (post (nth 1 e))
2476 (border (nth 2 e))
2477 (body (nth 3 e))
2478 (nl (nth 4 e))
2479 (body1 (concat body "*?"))
2480 (markers (mapconcat 'car org-emphasis-alist ""))
2481 (vmarkers (mapconcat
2482 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2483 org-emphasis-alist "")))
2484 ;; make sure special characters appear at the right position in the class
2485 (if (string-match "\\^" markers)
2486 (setq markers (concat (replace-match "" t t markers) "^")))
2487 (if (string-match "-" markers)
2488 (setq markers (concat (replace-match "" t t markers) "-")))
2489 (if (string-match "\\^" vmarkers)
2490 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2491 (if (string-match "-" vmarkers)
2492 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2493 (if (> nl 0)
2494 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2495 (int-to-string nl) "\\}")))
2496 ;; Make the regexp
2497 (setq org-emph-re
2498 (concat "\\([" pre "]\\|^\\)"
2499 "\\("
2500 "\\([" markers "]\\)"
2501 "\\("
2502 "[^" border "]\\|"
2503 "[^" border "]"
2504 body1
2505 "[^" border "]"
2506 "\\)"
2507 "\\3\\)"
2508 "\\([" post "]\\|$\\)"))
2509 (setq org-verbatim-re
2510 (concat "\\([" pre "]\\|^\\)"
2511 "\\("
2512 "\\([" vmarkers "]\\)"
2513 "\\("
2514 "[^" border "]\\|"
2515 "[^" border "]"
2516 body1
2517 "[^" border "]"
2518 "\\)"
2519 "\\3\\)"
2520 "\\([" post "]\\|$\\)")))))
2522 (defcustom org-emphasis-regexp-components
2523 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2524 "Components used to build the regular expression for emphasis.
2525 This is a list with 6 entries. Terminology: In an emphasis string
2526 like \" *strong word* \", we call the initial space PREMATCH, the final
2527 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2528 and \"trong wor\" is the body. The different components in this variable
2529 specify what is allowed/forbidden in each part:
2531 pre Chars allowed as prematch. Beginning of line will be allowed too.
2532 post Chars allowed as postmatch. End of line will be allowed too.
2533 border The chars *forbidden* as border characters.
2534 body-regexp A regexp like \".\" to match a body character. Don't use
2535 non-shy groups here, and don't allow newline here.
2536 newline The maximum number of newlines allowed in an emphasis exp.
2538 Use customize to modify this, or restart Emacs after changing it."
2539 :group 'org-font-lock
2540 :set 'org-set-emph-re
2541 :type '(list
2542 (sexp :tag "Allowed chars in pre ")
2543 (sexp :tag "Allowed chars in post ")
2544 (sexp :tag "Forbidden chars in border ")
2545 (sexp :tag "Regexp for body ")
2546 (integer :tag "number of newlines allowed")
2547 (option (boolean :tag "Please ignore this button"))))
2549 (defcustom org-emphasis-alist
2550 `(("*" bold "<b>" "</b>")
2551 ("/" italic "<i>" "</i>")
2552 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2553 ("=" org-code "<code>" "</code>" verbatim)
2554 ("~" org-verbatim "<code>" "</code>" verbatim)
2555 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2556 "<del>" "</del>")
2558 "Special syntax for emphasized text.
2559 Text starting and ending with a special character will be emphasized, for
2560 example *bold*, _underlined_ and /italic/. This variable sets the marker
2561 characters, the face to be used by font-lock for highlighting in Org-mode
2562 Emacs buffers, and the HTML tags to be used for this.
2563 Use customize to modify this, or restart Emacs after changing it."
2564 :group 'org-font-lock
2565 :set 'org-set-emph-re
2566 :type '(repeat
2567 (list
2568 (string :tag "Marker character")
2569 (choice
2570 (face :tag "Font-lock-face")
2571 (plist :tag "Face property list"))
2572 (string :tag "HTML start tag")
2573 (string :tag "HTML end tag")
2574 (option (const verbatim)))))
2576 ;;; Miscellaneous options
2578 (defgroup org-completion nil
2579 "Completion in Org-mode."
2580 :tag "Org Completion"
2581 :group 'org)
2583 (defcustom org-completion-use-ido nil
2584 "Non-nil means, use ido completion wherever possible.
2585 Note that `ido-mode' must be active for this variable to be relevant.
2586 If you decide to turn this variable on, you might well want to turn off
2587 `org-outline-path-complete-in-steps'."
2588 :group 'org-completion
2589 :type 'boolean)
2591 (defcustom org-completion-fallback-command 'hippie-expand
2592 "The expansion command called by \\[org-complete] in normal context.
2593 Normal means, no org-mode-specific context."
2594 :group 'org-completion
2595 :type 'function)
2597 ;;; Functions and variables from ther packages
2598 ;; Declared here to avoid compiler warnings
2600 ;; XEmacs only
2601 (defvar outline-mode-menu-heading)
2602 (defvar outline-mode-menu-show)
2603 (defvar outline-mode-menu-hide)
2604 (defvar zmacs-regions) ; XEmacs regions
2606 ;; Emacs only
2607 (defvar mark-active)
2609 ;; Various packages
2610 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2611 (declare-function calendar-forward-day "cal-move" (arg))
2612 (declare-function calendar-goto-date "cal-move" (date))
2613 (declare-function calendar-goto-today "cal-move" ())
2614 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2615 (defvar calc-embedded-close-formula)
2616 (defvar calc-embedded-open-formula)
2617 (declare-function cdlatex-tab "ext:cdlatex" ())
2618 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2619 (defvar font-lock-unfontify-region-function)
2620 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2621 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2622 (defvar iswitchb-temp-buflist)
2623 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2624 (defvar org-agenda-tags-todo-honor-ignore-options)
2625 (declare-function org-agenda-skip "org-agenda" ())
2626 (declare-function org-format-agenda-item "org-agenda"
2627 (extra txt &optional category tags dotime noprefix remove-re))
2628 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2629 (declare-function org-agenda-change-all-lines "org-agenda"
2630 (newhead hdmarker &optional fixface just-this))
2631 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2632 (declare-function org-agenda-maybe-redo "org-agenda" ())
2633 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2634 (beg end))
2635 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2636 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2637 "org-agenda" (&optional end))
2639 (declare-function parse-time-string "parse-time" (string))
2640 (declare-function remember "remember" (&optional initial))
2641 (declare-function remember-buffer-desc "remember" ())
2642 (declare-function remember-finalize "remember" ())
2643 (defvar remember-save-after-remembering)
2644 (defvar remember-data-file)
2645 (defvar remember-register)
2646 (defvar remember-buffer)
2647 (defvar remember-handler-functions)
2648 (defvar remember-annotation-functions)
2649 (defvar texmathp-why)
2650 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2651 (declare-function table--at-cell-p "table" (position &optional object at-column))
2653 (defvar w3m-current-url)
2654 (defvar w3m-current-title)
2656 (defvar org-latex-regexps)
2658 ;;; Autoload and prepare some org modules
2660 ;; Some table stuff that needs to be defined here, because it is used
2661 ;; by the functions setting up org-mode or checking for table context.
2663 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2664 "Detects an org-type or table-type table.")
2665 (defconst org-table-line-regexp "^[ \t]*|"
2666 "Detects an org-type table line.")
2667 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2668 "Detects an org-type table line.")
2669 (defconst org-table-hline-regexp "^[ \t]*|-"
2670 "Detects an org-type table hline.")
2671 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2672 "Detects a table-type table hline.")
2673 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2674 "Searching from within a table (any type) this finds the first line
2675 outside the table.")
2677 ;; Autoload the functions in org-table.el that are needed by functions here.
2679 (eval-and-compile
2680 (org-autoload "org-table"
2681 '(org-table-align org-table-begin org-table-blank-field
2682 org-table-convert org-table-convert-region org-table-copy-down
2683 org-table-copy-region org-table-create
2684 org-table-create-or-convert-from-region
2685 org-table-create-with-table.el org-table-current-dline
2686 org-table-cut-region org-table-delete-column org-table-edit-field
2687 org-table-edit-formulas org-table-end org-table-eval-formula
2688 org-table-export org-table-field-info
2689 org-table-get-stored-formulas org-table-goto-column
2690 org-table-hline-and-move org-table-import org-table-insert-column
2691 org-table-insert-hline org-table-insert-row org-table-iterate
2692 org-table-justify-field-maybe org-table-kill-row
2693 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2694 org-table-move-column org-table-move-column-left
2695 org-table-move-column-right org-table-move-row
2696 org-table-move-row-down org-table-move-row-up
2697 org-table-next-field org-table-next-row org-table-paste-rectangle
2698 org-table-previous-field org-table-recalculate
2699 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2700 org-table-toggle-coordinate-overlays
2701 org-table-toggle-formula-debugger org-table-wrap-region
2702 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2704 (defun org-at-table-p (&optional table-type)
2705 "Return t if the cursor is inside an org-type table.
2706 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2707 (if org-enable-table-editor
2708 (save-excursion
2709 (beginning-of-line 1)
2710 (looking-at (if table-type org-table-any-line-regexp
2711 org-table-line-regexp)))
2712 nil))
2713 (defsubst org-table-p () (org-at-table-p))
2715 (defun org-at-table.el-p ()
2716 "Return t if and only if we are at a table.el table."
2717 (and (org-at-table-p 'any)
2718 (save-excursion
2719 (goto-char (org-table-begin 'any))
2720 (looking-at org-table1-hline-regexp))))
2721 (defun org-table-recognize-table.el ()
2722 "If there is a table.el table nearby, recognize it and move into it."
2723 (if org-table-tab-recognizes-table.el
2724 (if (org-at-table.el-p)
2725 (progn
2726 (beginning-of-line 1)
2727 (if (looking-at org-table-dataline-regexp)
2729 (if (looking-at org-table1-hline-regexp)
2730 (progn
2731 (beginning-of-line 2)
2732 (if (looking-at org-table-any-border-regexp)
2733 (beginning-of-line -1)))))
2734 (if (re-search-forward "|" (org-table-end t) t)
2735 (progn
2736 (require 'table)
2737 (if (table--at-cell-p (point))
2739 (message "recognizing table.el table...")
2740 (table-recognize-table)
2741 (message "recognizing table.el table...done")))
2742 (error "This should not happen..."))
2744 nil)
2745 nil))
2747 (defun org-at-table-hline-p ()
2748 "Return t if the cursor is inside a hline in a table."
2749 (if org-enable-table-editor
2750 (save-excursion
2751 (beginning-of-line 1)
2752 (looking-at org-table-hline-regexp))
2753 nil))
2755 (defvar org-table-clean-did-remove-column nil)
2757 (defun org-table-map-tables (function)
2758 "Apply FUNCTION to the start of all tables in the buffer."
2759 (save-excursion
2760 (save-restriction
2761 (widen)
2762 (goto-char (point-min))
2763 (while (re-search-forward org-table-any-line-regexp nil t)
2764 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2765 (beginning-of-line 1)
2766 (if (looking-at org-table-line-regexp)
2767 (save-excursion (funcall function)))
2768 (re-search-forward org-table-any-border-regexp nil 1))))
2769 (message "Mapping tables: done"))
2771 ;; Declare and autoload functions from org-exp.el
2773 (declare-function org-default-export-plist "org-exp")
2774 (declare-function org-infile-export-plist "org-exp")
2775 (declare-function org-get-current-options "org-exp")
2776 (eval-and-compile
2777 (org-autoload "org-exp"
2778 '(org-export org-export-as-ascii org-export-visible
2779 org-insert-export-options-template org-export-as-html-and-open
2780 org-export-as-html-batch org-export-as-html-to-buffer
2781 org-replace-region-by-html org-export-region-as-html
2782 org-export-as-html org-export-icalendar-this-file
2783 org-export-icalendar-all-agenda-files
2784 org-table-clean-before-export
2785 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2787 ;; Declare and autoload functions from org-agenda.el
2789 (eval-and-compile
2790 (org-autoload "org-agenda"
2791 '(org-agenda org-agenda-list org-search-view
2792 org-todo-list org-tags-view org-agenda-list-stuck-projects
2793 org-diary org-agenda-to-appt
2794 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2796 ;; Autoload org-remember
2798 (eval-and-compile
2799 (org-autoload "org-remember"
2800 '(org-remember-insinuate org-remember-annotation
2801 org-remember-apply-template org-remember org-remember-handler)))
2803 ;; Autoload org-clock.el
2806 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2807 (beg end))
2808 (declare-function org-clock-update-mode-line "org-clock" ())
2809 (defvar org-clock-start-time)
2810 (defvar org-clock-marker (make-marker)
2811 "Marker recording the last clock-in.")
2813 (eval-and-compile
2814 (org-autoload
2815 "org-clock"
2816 '(org-clock-in org-clock-out org-clock-cancel
2817 org-clock-goto org-clock-sum org-clock-display
2818 org-clock-remove-overlays org-clock-report
2819 org-clocktable-shift org-dblock-write:clocktable
2820 org-get-clocktable)))
2822 (defun org-clock-update-time-maybe ()
2823 "If this is a CLOCK line, update it and return t.
2824 Otherwise, return nil."
2825 (interactive)
2826 (save-excursion
2827 (beginning-of-line 1)
2828 (skip-chars-forward " \t")
2829 (when (looking-at org-clock-string)
2830 (let ((re (concat "[ \t]*" org-clock-string
2831 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2832 "\\([ \t]*=>.*\\)?\\)?"))
2833 ts te h m s neg)
2834 (cond
2835 ((not (looking-at re))
2836 nil)
2837 ((not (match-end 2))
2838 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2839 (> org-clock-marker (point))
2840 (<= org-clock-marker (point-at-eol)))
2841 ;; The clock is running here
2842 (setq org-clock-start-time
2843 (apply 'encode-time
2844 (org-parse-time-string (match-string 1))))
2845 (org-clock-update-mode-line)))
2847 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2848 (end-of-line 1)
2849 (setq ts (match-string 1)
2850 te (match-string 3))
2851 (setq s (- (time-to-seconds
2852 (apply 'encode-time (org-parse-time-string te)))
2853 (time-to-seconds
2854 (apply 'encode-time (org-parse-time-string ts))))
2855 neg (< s 0)
2856 s (abs s)
2857 h (floor (/ s 3600))
2858 s (- s (* 3600 h))
2859 m (floor (/ s 60))
2860 s (- s (* 60 s)))
2861 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2862 t))))))
2864 (defun org-check-running-clock ()
2865 "Check if the current buffer contains the running clock.
2866 If yes, offer to stop it and to save the buffer with the changes."
2867 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2868 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2869 (buffer-name))))
2870 (org-clock-out)
2871 (when (y-or-n-p "Save changed buffer?")
2872 (save-buffer))))
2874 (defun org-clocktable-try-shift (dir n)
2875 "Check if this line starts a clock table, if yes, shift the time block."
2876 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2877 (org-clocktable-shift dir n)))
2879 ;; Autoload org-timer.el
2881 ;(declare-function org-timer "org-timer")
2883 (eval-and-compile
2884 (org-autoload
2885 "org-timer"
2886 '(org-timer-start org-timer org-timer-item
2887 org-timer-change-times-in-region)))
2890 ;; Autoload archiving code
2891 ;; The stuff that is needed for cycling and tags has to be defined here.
2893 (defgroup org-archive nil
2894 "Options concerning archiving in Org-mode."
2895 :tag "Org Archive"
2896 :group 'org-structure)
2898 (defcustom org-archive-location "%s_archive::"
2899 "The location where subtrees should be archived.
2901 The value of this variable is a string, consisting of two parts,
2902 separated by a double-colon. The first part is a filename and
2903 the second part is a headline.
2905 When the filename is omitted, archiving happens in the same file.
2906 %s in the filename will be replaced by the current file
2907 name (without the directory part). Archiving to a different file
2908 is useful to keep archived entries from contributing to the
2909 Org-mode Agenda.
2911 The archived entries will be filed as subtrees of the specified
2912 headline. When the headline is omitted, the subtrees are simply
2913 filed away at the end of the file, as top-level entries. Also in
2914 the heading you can use %s to represent the file name, this can be
2915 useful when using the same archive for a number of different files.
2917 Here are a few examples:
2918 \"%s_archive::\"
2919 If the current file is Projects.org, archive in file
2920 Projects.org_archive, as top-level trees. This is the default.
2922 \"::* Archived Tasks\"
2923 Archive in the current file, under the top-level headline
2924 \"* Archived Tasks\".
2926 \"~/org/archive.org::\"
2927 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2929 \"~/org/archive.org::From %s\"
2930 Archive in file ~/org/archive.org (absolute path), und headlines
2931 \"From FILENAME\" where file name is the current file name.
2933 \"basement::** Finished Tasks\"
2934 Archive in file ./basement (relative path), as level 3 trees
2935 below the level 2 heading \"** Finished Tasks\".
2937 You may set this option on a per-file basis by adding to the buffer a
2938 line like
2940 #+ARCHIVE: basement::** Finished Tasks
2942 You may also define it locally for a subtree by setting an ARCHIVE property
2943 in the entry. If such a property is found in an entry, or anywhere up
2944 the hierarchy, it will be used."
2945 :group 'org-archive
2946 :type 'string)
2948 (defcustom org-archive-tag "ARCHIVE"
2949 "The tag that marks a subtree as archived.
2950 An archived subtree does not open during visibility cycling, and does
2951 not contribute to the agenda listings.
2952 After changing this, font-lock must be restarted in the relevant buffers to
2953 get the proper fontification."
2954 :group 'org-archive
2955 :group 'org-keywords
2956 :type 'string)
2958 (defcustom org-agenda-skip-archived-trees t
2959 "Non-nil means, the agenda will skip any items located in archived trees.
2960 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2961 variable is no longer recommended, you should leave it at the value t.
2962 Instead, use the key `v' to cycle the archives-mode in the agenda."
2963 :group 'org-archive
2964 :group 'org-agenda-skip
2965 :type 'boolean)
2967 (defcustom org-cycle-open-archived-trees nil
2968 "Non-nil means, `org-cycle' will open archived trees.
2969 An archived tree is a tree marked with the tag ARCHIVE.
2970 When nil, archived trees will stay folded. You can still open them with
2971 normal outline commands like `show-all', but not with the cycling commands."
2972 :group 'org-archive
2973 :group 'org-cycle
2974 :type 'boolean)
2976 (defcustom org-sparse-tree-open-archived-trees nil
2977 "Non-nil means sparse tree construction shows matches in archived trees.
2978 When nil, matches in these trees are highlighted, but the trees are kept in
2979 collapsed state."
2980 :group 'org-archive
2981 :group 'org-sparse-trees
2982 :type 'boolean)
2984 (defun org-cycle-hide-archived-subtrees (state)
2985 "Re-hide all archived subtrees after a visibility state change."
2986 (when (and (not org-cycle-open-archived-trees)
2987 (not (memq state '(overview folded))))
2988 (save-excursion
2989 (let* ((globalp (memq state '(contents all)))
2990 (beg (if globalp (point-min) (point)))
2991 (end (if globalp (point-max) (org-end-of-subtree t))))
2992 (org-hide-archived-subtrees beg end)
2993 (goto-char beg)
2994 (if (looking-at (concat ".*:" org-archive-tag ":"))
2995 (message "%s" (substitute-command-keys
2996 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2998 (defun org-force-cycle-archived ()
2999 "Cycle subtree even if it is archived."
3000 (interactive)
3001 (setq this-command 'org-cycle)
3002 (let ((org-cycle-open-archived-trees t))
3003 (call-interactively 'org-cycle)))
3005 (defun org-hide-archived-subtrees (beg end)
3006 "Re-hide all archived subtrees after a visibility state change."
3007 (save-excursion
3008 (let* ((re (concat ":" org-archive-tag ":")))
3009 (goto-char beg)
3010 (while (re-search-forward re end t)
3011 (and (org-on-heading-p) (hide-subtree))
3012 (org-end-of-subtree t)))))
3014 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3016 (eval-and-compile
3017 (org-autoload "org-archive"
3018 '(org-add-archive-files org-archive-subtree
3019 org-archive-to-archive-sibling org-toggle-archive-tag)))
3021 ;; Autoload Column View Code
3023 (declare-function org-columns-number-to-string "org-colview")
3024 (declare-function org-columns-get-format-and-top-level "org-colview")
3025 (declare-function org-columns-compute "org-colview")
3027 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3028 '(org-columns-number-to-string org-columns-get-format-and-top-level
3029 org-columns-compute org-agenda-columns org-columns-remove-overlays
3030 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3032 ;; Autoload ID code
3034 (declare-function org-id-store-link "org-id")
3035 (org-autoload "org-id"
3036 '(org-id-get-create org-id-new org-id-copy org-id-get
3037 org-id-get-with-outline-path-completion
3038 org-id-get-with-outline-drilling
3039 org-id-goto org-id-find org-id-store-link))
3041 ;;; Variables for pre-computed regular expressions, all buffer local
3043 (defvar org-drawer-regexp nil
3044 "Matches first line of a hidden block.")
3045 (make-variable-buffer-local 'org-drawer-regexp)
3046 (defvar org-todo-regexp nil
3047 "Matches any of the TODO state keywords.")
3048 (make-variable-buffer-local 'org-todo-regexp)
3049 (defvar org-not-done-regexp nil
3050 "Matches any of the TODO state keywords except the last one.")
3051 (make-variable-buffer-local 'org-not-done-regexp)
3052 (defvar org-todo-line-regexp nil
3053 "Matches a headline and puts TODO state into group 2 if present.")
3054 (make-variable-buffer-local 'org-todo-line-regexp)
3055 (defvar org-complex-heading-regexp nil
3056 "Matches a headline and puts everything into groups:
3057 group 1: the stars
3058 group 2: The todo keyword, maybe
3059 group 3: Priority cookie
3060 group 4: True headline
3061 group 5: Tags")
3062 (make-variable-buffer-local 'org-complex-heading-regexp)
3063 (defvar org-todo-line-tags-regexp nil
3064 "Matches a headline and puts TODO state into group 2 if present.
3065 Also put tags into group 4 if tags are present.")
3066 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3067 (defvar org-nl-done-regexp nil
3068 "Matches newline followed by a headline with the DONE keyword.")
3069 (make-variable-buffer-local 'org-nl-done-regexp)
3070 (defvar org-looking-at-done-regexp nil
3071 "Matches the DONE keyword a point.")
3072 (make-variable-buffer-local 'org-looking-at-done-regexp)
3073 (defvar org-ds-keyword-length 12
3074 "Maximum length of the Deadline and SCHEDULED keywords.")
3075 (make-variable-buffer-local 'org-ds-keyword-length)
3076 (defvar org-deadline-regexp nil
3077 "Matches the DEADLINE keyword.")
3078 (make-variable-buffer-local 'org-deadline-regexp)
3079 (defvar org-deadline-time-regexp nil
3080 "Matches the DEADLINE keyword together with a time stamp.")
3081 (make-variable-buffer-local 'org-deadline-time-regexp)
3082 (defvar org-deadline-line-regexp nil
3083 "Matches the DEADLINE keyword and the rest of the line.")
3084 (make-variable-buffer-local 'org-deadline-line-regexp)
3085 (defvar org-scheduled-regexp nil
3086 "Matches the SCHEDULED keyword.")
3087 (make-variable-buffer-local 'org-scheduled-regexp)
3088 (defvar org-scheduled-time-regexp nil
3089 "Matches the SCHEDULED keyword together with a time stamp.")
3090 (make-variable-buffer-local 'org-scheduled-time-regexp)
3091 (defvar org-closed-time-regexp nil
3092 "Matches the CLOSED keyword together with a time stamp.")
3093 (make-variable-buffer-local 'org-closed-time-regexp)
3095 (defvar org-keyword-time-regexp nil
3096 "Matches any of the 4 keywords, together with the time stamp.")
3097 (make-variable-buffer-local 'org-keyword-time-regexp)
3098 (defvar org-keyword-time-not-clock-regexp nil
3099 "Matches any of the 3 keywords, together with the time stamp.")
3100 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3101 (defvar org-maybe-keyword-time-regexp nil
3102 "Matches a timestamp, possibly preceeded by a keyword.")
3103 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3104 (defvar org-planning-or-clock-line-re nil
3105 "Matches a line with planning or clock info.")
3106 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3108 (defconst org-plain-time-of-day-regexp
3109 (concat
3110 "\\(\\<[012]?[0-9]"
3111 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3112 "\\(--?"
3113 "\\(\\<[012]?[0-9]"
3114 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3115 "\\)?")
3116 "Regular expression to match a plain time or time range.
3117 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3118 groups carry important information:
3119 0 the full match
3120 1 the first time, range or not
3121 8 the second time, if it is a range.")
3123 (defconst org-plain-time-extension-regexp
3124 (concat
3125 "\\(\\<[012]?[0-9]"
3126 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3127 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3128 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3129 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3130 groups carry important information:
3131 0 the full match
3132 7 hours of duration
3133 9 minutes of duration")
3135 (defconst org-stamp-time-of-day-regexp
3136 (concat
3137 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3138 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3139 "\\(--?"
3140 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3141 "Regular expression to match a timestamp time or time range.
3142 After a match, the following groups carry important information:
3143 0 the full match
3144 1 date plus weekday, for backreferencing to make sure both times on same day
3145 2 the first time, range or not
3146 4 the second time, if it is a range.")
3148 (defconst org-startup-options
3149 '(("fold" org-startup-folded t)
3150 ("overview" org-startup-folded t)
3151 ("nofold" org-startup-folded nil)
3152 ("showall" org-startup-folded nil)
3153 ("content" org-startup-folded content)
3154 ("hidestars" org-hide-leading-stars t)
3155 ("showstars" org-hide-leading-stars nil)
3156 ("odd" org-odd-levels-only t)
3157 ("oddeven" org-odd-levels-only nil)
3158 ("align" org-startup-align-all-tables t)
3159 ("noalign" org-startup-align-all-tables nil)
3160 ("customtime" org-display-custom-times t)
3161 ("logdone" org-log-done time)
3162 ("lognotedone" org-log-done note)
3163 ("nologdone" org-log-done nil)
3164 ("lognoteclock-out" org-log-note-clock-out t)
3165 ("nolognoteclock-out" org-log-note-clock-out nil)
3166 ("logrepeat" org-log-repeat state)
3167 ("lognoterepeat" org-log-repeat note)
3168 ("nologrepeat" org-log-repeat nil)
3169 ("fninline" org-footnote-define-inline t)
3170 ("nofninline" org-footnote-define-inline nil)
3171 ("fnlocal" org-footnote-section nil)
3172 ("fnauto" org-footnote-auto-label t)
3173 ("fnprompt" org-footnote-auto-label nil)
3174 ("fnconfirm" org-footnote-auto-label confirm)
3175 ("fnplain" org-footnote-auto-label plain)
3176 ("constcgs" constants-unit-system cgs)
3177 ("constSI" constants-unit-system SI))
3178 "Variable associated with STARTUP options for org-mode.
3179 Each element is a list of three items: The startup options as written
3180 in the #+STARTUP line, the corresponding variable, and the value to
3181 set this variable to if the option is found. An optional forth element PUSH
3182 means to push this value onto the list in the variable.")
3184 (defun org-set-regexps-and-options ()
3185 "Precompute regular expressions for current buffer."
3186 (when (org-mode-p)
3187 (org-set-local 'org-todo-kwd-alist nil)
3188 (org-set-local 'org-todo-key-alist nil)
3189 (org-set-local 'org-todo-key-trigger nil)
3190 (org-set-local 'org-todo-keywords-1 nil)
3191 (org-set-local 'org-done-keywords nil)
3192 (org-set-local 'org-todo-heads nil)
3193 (org-set-local 'org-todo-sets nil)
3194 (org-set-local 'org-todo-log-states nil)
3195 (org-set-local 'org-file-properties nil)
3196 (org-set-local 'org-file-tags nil)
3197 (let ((re (org-make-options-regexp
3198 '("CATEGORY" "TODO" "COLUMNS"
3199 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3200 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3201 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3202 (splitre "[ \t]+")
3203 kwds kws0 kwsa key log value cat arch tags const links hw dws
3204 tail sep kws1 prio props ftags drawers
3205 ext-setup-or-nil setup-contents (start 0))
3206 (save-excursion
3207 (save-restriction
3208 (widen)
3209 (goto-char (point-min))
3210 (while (or (and ext-setup-or-nil
3211 (string-match re ext-setup-or-nil start)
3212 (setq start (match-end 0)))
3213 (and (setq ext-setup-or-nil nil start 0)
3214 (re-search-forward re nil t)))
3215 (setq key (upcase (match-string 1 ext-setup-or-nil))
3216 value (org-match-string-no-properties 2 ext-setup-or-nil))
3217 (cond
3218 ((equal key "CATEGORY")
3219 (if (string-match "[ \t]+$" value)
3220 (setq value (replace-match "" t t value)))
3221 (setq cat value))
3222 ((member key '("SEQ_TODO" "TODO"))
3223 (push (cons 'sequence (org-split-string value splitre)) kwds))
3224 ((equal key "TYP_TODO")
3225 (push (cons 'type (org-split-string value splitre)) kwds))
3226 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3227 ;; general TODO-like setup
3228 (push (cons (intern (downcase (match-string 1 key)))
3229 (org-split-string value splitre)) kwds))
3230 ((equal key "TAGS")
3231 (setq tags (append tags (org-split-string value splitre))))
3232 ((equal key "COLUMNS")
3233 (org-set-local 'org-columns-default-format value))
3234 ((equal key "LINK")
3235 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3236 (push (cons (match-string 1 value)
3237 (org-trim (match-string 2 value)))
3238 links)))
3239 ((equal key "PRIORITIES")
3240 (setq prio (org-split-string value " +")))
3241 ((equal key "PROPERTY")
3242 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3243 (push (cons (match-string 1 value) (match-string 2 value))
3244 props)))
3245 ((equal key "FILETAGS")
3246 (when (string-match "\\S-" value)
3247 (setq ftags
3248 (append
3249 ftags
3250 (apply 'append
3251 (mapcar (lambda (x) (org-split-string x ":"))
3252 (org-split-string value)))))))
3253 ((equal key "DRAWERS")
3254 (setq drawers (org-split-string value splitre)))
3255 ((equal key "CONSTANTS")
3256 (setq const (append const (org-split-string value splitre))))
3257 ((equal key "STARTUP")
3258 (let ((opts (org-split-string value splitre))
3259 l var val)
3260 (while (setq l (pop opts))
3261 (when (setq l (assoc l org-startup-options))
3262 (setq var (nth 1 l) val (nth 2 l))
3263 (if (not (nth 3 l))
3264 (set (make-local-variable var) val)
3265 (if (not (listp (symbol-value var)))
3266 (set (make-local-variable var) nil))
3267 (set (make-local-variable var) (symbol-value var))
3268 (add-to-list var val))))))
3269 ((equal key "ARCHIVE")
3270 (string-match " *$" value)
3271 (setq arch (replace-match "" t t value))
3272 (remove-text-properties 0 (length arch)
3273 '(face t fontified t) arch))
3274 ((equal key "SETUPFILE")
3275 (setq setup-contents (org-file-contents
3276 (expand-file-name
3277 (org-remove-double-quotes value))
3278 'noerror))
3279 (if (not ext-setup-or-nil)
3280 (setq ext-setup-or-nil setup-contents start 0)
3281 (setq ext-setup-or-nil
3282 (concat (substring ext-setup-or-nil 0 start)
3283 "\n" setup-contents "\n"
3284 (substring ext-setup-or-nil start)))))
3285 ))))
3286 (when cat
3287 (org-set-local 'org-category (intern cat))
3288 (push (cons "CATEGORY" cat) props))
3289 (when prio
3290 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3291 (setq prio (mapcar 'string-to-char prio))
3292 (org-set-local 'org-highest-priority (nth 0 prio))
3293 (org-set-local 'org-lowest-priority (nth 1 prio))
3294 (org-set-local 'org-default-priority (nth 2 prio)))
3295 (and props (org-set-local 'org-file-properties (nreverse props)))
3296 (and ftags (org-set-local 'org-file-tags ftags))
3297 (and drawers (org-set-local 'org-drawers drawers))
3298 (and arch (org-set-local 'org-archive-location arch))
3299 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3300 ;; Process the TODO keywords
3301 (unless kwds
3302 ;; Use the global values as if they had been given locally.
3303 (setq kwds (default-value 'org-todo-keywords))
3304 (if (stringp (car kwds))
3305 (setq kwds (list (cons org-todo-interpretation
3306 (default-value 'org-todo-keywords)))))
3307 (setq kwds (reverse kwds)))
3308 (setq kwds (nreverse kwds))
3309 (let (inter kws kw)
3310 (while (setq kws (pop kwds))
3311 (let ((kws (or
3312 (run-hook-with-args-until-success
3313 'org-todo-setup-filter-hook kws)
3314 kws)))
3315 (setq inter (pop kws) sep (member "|" kws)
3316 kws0 (delete "|" (copy-sequence kws))
3317 kwsa nil
3318 kws1 (mapcar
3319 (lambda (x)
3320 ;; 1 2
3321 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3322 (progn
3323 (setq kw (match-string 1 x)
3324 key (and (match-end 2) (match-string 2 x))
3325 log (org-extract-log-state-settings x))
3326 (push (cons kw (and key (string-to-char key))) kwsa)
3327 (and log (push log org-todo-log-states))
3329 (error "Invalid TODO keyword %s" x)))
3330 kws0)
3331 kwsa (if kwsa (append '((:startgroup))
3332 (nreverse kwsa)
3333 '((:endgroup))))
3334 hw (car kws1)
3335 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3336 tail (list inter hw (car dws) (org-last dws))))
3337 (add-to-list 'org-todo-heads hw 'append)
3338 (push kws1 org-todo-sets)
3339 (setq org-done-keywords (append org-done-keywords dws nil))
3340 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3341 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3342 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3343 (setq org-todo-sets (nreverse org-todo-sets)
3344 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3345 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3346 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3347 ;; Process the constants
3348 (when const
3349 (let (e cst)
3350 (while (setq e (pop const))
3351 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3352 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3353 (setq org-table-formula-constants-local cst)))
3355 ;; Process the tags.
3356 (when tags
3357 (let (e tgs)
3358 (while (setq e (pop tags))
3359 (cond
3360 ((equal e "{") (push '(:startgroup) tgs))
3361 ((equal e "}") (push '(:endgroup) tgs))
3362 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3363 (push (cons (match-string 1 e)
3364 (string-to-char (match-string 2 e)))
3365 tgs))
3366 (t (push (list e) tgs))))
3367 (org-set-local 'org-tag-alist nil)
3368 (while (setq e (pop tgs))
3369 (or (and (stringp (car e))
3370 (assoc (car e) org-tag-alist))
3371 (push e org-tag-alist)))))
3373 ;; Compute the regular expressions and other local variables
3374 (if (not org-done-keywords)
3375 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3376 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3377 (length org-scheduled-string)
3378 (length org-clock-string)
3379 (length org-closed-string)))
3380 org-drawer-regexp
3381 (concat "^[ \t]*:\\("
3382 (mapconcat 'regexp-quote org-drawers "\\|")
3383 "\\):[ \t]*$")
3384 org-not-done-keywords
3385 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3386 org-todo-regexp
3387 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3388 "\\|") "\\)\\>")
3389 org-not-done-regexp
3390 (concat "\\<\\("
3391 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3392 "\\)\\>")
3393 org-todo-line-regexp
3394 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3395 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3396 "\\)\\>\\)?[ \t]*\\(.*\\)")
3397 org-complex-heading-regexp
3398 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3399 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3400 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3401 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3402 org-nl-done-regexp
3403 (concat "\n\\*+[ \t]+"
3404 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3405 "\\)" "\\>")
3406 org-todo-line-tags-regexp
3407 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3408 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3409 (org-re
3410 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3411 org-looking-at-done-regexp
3412 (concat "^" "\\(?:"
3413 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3414 "\\>")
3415 org-deadline-regexp (concat "\\<" org-deadline-string)
3416 org-deadline-time-regexp
3417 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3418 org-deadline-line-regexp
3419 (concat "\\<\\(" org-deadline-string "\\).*")
3420 org-scheduled-regexp
3421 (concat "\\<" org-scheduled-string)
3422 org-scheduled-time-regexp
3423 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3424 org-closed-time-regexp
3425 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3426 org-keyword-time-regexp
3427 (concat "\\<\\(" org-scheduled-string
3428 "\\|" org-deadline-string
3429 "\\|" org-closed-string
3430 "\\|" org-clock-string "\\)"
3431 " *[[<]\\([^]>]+\\)[]>]")
3432 org-keyword-time-not-clock-regexp
3433 (concat "\\<\\(" org-scheduled-string
3434 "\\|" org-deadline-string
3435 "\\|" org-closed-string
3436 "\\)"
3437 " *[[<]\\([^]>]+\\)[]>]")
3438 org-maybe-keyword-time-regexp
3439 (concat "\\(\\<\\(" org-scheduled-string
3440 "\\|" org-deadline-string
3441 "\\|" org-closed-string
3442 "\\|" org-clock-string "\\)\\)?"
3443 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3444 org-planning-or-clock-line-re
3445 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3446 "\\|" org-deadline-string
3447 "\\|" org-closed-string "\\|" org-clock-string
3448 "\\)\\>\\)")
3450 (org-compute-latex-and-specials-regexp)
3451 (org-set-font-lock-defaults))))
3453 (defun org-file-contents (file &optional noerror)
3454 "Return the contents of FILE, as a string."
3455 (if (or (not file)
3456 (not (file-readable-p file)))
3457 (if noerror
3458 (progn
3459 (message "Cannot read file %s" file)
3460 (ding) (sit-for 2)
3462 (error "Cannot read file %s" file))
3463 (with-temp-buffer
3464 (insert-file-contents file)
3465 (buffer-string))))
3467 (defun org-extract-log-state-settings (x)
3468 "Extract the log state setting from a TODO keyword string.
3469 This will extract info from a string like \"WAIT(w@/!)\"."
3470 (let (kw key log1 log2)
3471 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3472 (setq kw (match-string 1 x)
3473 key (and (match-end 2) (match-string 2 x))
3474 log1 (and (match-end 3) (match-string 3 x))
3475 log2 (and (match-end 4) (match-string 4 x)))
3476 (and (or log1 log2)
3477 (list kw
3478 (and log1 (if (equal log1 "!") 'time 'note))
3479 (and log2 (if (equal log2 "!") 'time 'note)))))))
3481 (defun org-remove-keyword-keys (list)
3482 "Remove a pair of parenthesis at the end of each string in LIST."
3483 (mapcar (lambda (x)
3484 (if (string-match "(.*)$" x)
3485 (substring x 0 (match-beginning 0))
3487 list))
3489 ;; FIXME: this could be done much better, using second characters etc.
3490 (defun org-assign-fast-keys (alist)
3491 "Assign fast keys to a keyword-key alist.
3492 Respect keys that are already there."
3493 (let (new e k c c1 c2 (char ?a))
3494 (while (setq e (pop alist))
3495 (cond
3496 ((equal e '(:startgroup)) (push e new))
3497 ((equal e '(:endgroup)) (push e new))
3499 (setq k (car e) c2 nil)
3500 (if (cdr e)
3501 (setq c (cdr e))
3502 ;; automatically assign a character.
3503 (setq c1 (string-to-char
3504 (downcase (substring
3505 k (if (= (string-to-char k) ?@) 1 0)))))
3506 (if (or (rassoc c1 new) (rassoc c1 alist))
3507 (while (or (rassoc char new) (rassoc char alist))
3508 (setq char (1+ char)))
3509 (setq c2 c1))
3510 (setq c (or c2 char)))
3511 (push (cons k c) new))))
3512 (nreverse new)))
3514 ;;; Some variables used in various places
3516 (defvar org-window-configuration nil
3517 "Used in various places to store a window configuration.")
3518 (defvar org-finish-function nil
3519 "Function to be called when `C-c C-c' is used.
3520 This is for getting out of special buffers like remember.")
3523 ;; FIXME: Occasionally check by commenting these, to make sure
3524 ;; no other functions uses these, forgetting to let-bind them.
3525 (defvar entry)
3526 (defvar state)
3527 (defvar last-state)
3528 (defvar date)
3529 (defvar description)
3531 ;; Defined somewhere in this file, but used before definition.
3532 (defvar org-html-entities)
3533 (defvar org-struct-menu)
3534 (defvar org-org-menu)
3535 (defvar org-tbl-menu)
3536 (defvar org-agenda-keymap)
3538 ;;;; Define the Org-mode
3540 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3541 (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."))
3544 ;; We use a before-change function to check if a table might need
3545 ;; an update.
3546 (defvar org-table-may-need-update t
3547 "Indicates that a table might need an update.
3548 This variable is set by `org-before-change-function'.
3549 `org-table-align' sets it back to nil.")
3550 (defun org-before-change-function (beg end)
3551 "Every change indicates that a table might need an update."
3552 (setq org-table-may-need-update t))
3553 (defvar org-mode-map)
3554 (defvar org-mode-hook nil
3555 "Mode hook for Org-mode, run after the mode was turned on.")
3556 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3557 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3558 (defvar org-table-buffer-is-an nil)
3559 (defconst org-outline-regexp "\\*+ ")
3561 ;;;###autoload
3562 (define-derived-mode org-mode outline-mode "Org"
3563 "Outline-based notes management and organizer, alias
3564 \"Carsten's outline-mode for keeping track of everything.\"
3566 Org-mode develops organizational tasks around a NOTES file which
3567 contains information about projects as plain text. Org-mode is
3568 implemented on top of outline-mode, which is ideal to keep the content
3569 of large files well structured. It supports ToDo items, deadlines and
3570 time stamps, which magically appear in the diary listing of the Emacs
3571 calendar. Tables are easily created with a built-in table editor.
3572 Plain text URL-like links connect to websites, emails (VM), Usenet
3573 messages (Gnus), BBDB entries, and any files related to the project.
3574 For printing and sharing of notes, an Org-mode file (or a part of it)
3575 can be exported as a structured ASCII or HTML file.
3577 The following commands are available:
3579 \\{org-mode-map}"
3581 ;; Get rid of Outline menus, they are not needed
3582 ;; Need to do this here because define-derived-mode sets up
3583 ;; the keymap so late. Still, it is a waste to call this each time
3584 ;; we switch another buffer into org-mode.
3585 (if (featurep 'xemacs)
3586 (when (boundp 'outline-mode-menu-heading)
3587 ;; Assume this is Greg's port, it used easymenu
3588 (easy-menu-remove outline-mode-menu-heading)
3589 (easy-menu-remove outline-mode-menu-show)
3590 (easy-menu-remove outline-mode-menu-hide))
3591 (define-key org-mode-map [menu-bar headings] 'undefined)
3592 (define-key org-mode-map [menu-bar hide] 'undefined)
3593 (define-key org-mode-map [menu-bar show] 'undefined))
3595 (org-load-modules-maybe)
3596 (easy-menu-add org-org-menu)
3597 (easy-menu-add org-tbl-menu)
3598 (org-install-agenda-files-menu)
3599 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3600 (org-add-to-invisibility-spec '(org-cwidth))
3601 (when (featurep 'xemacs)
3602 (org-set-local 'line-move-ignore-invisible t))
3603 (org-set-local 'outline-regexp org-outline-regexp)
3604 (org-set-local 'outline-level 'org-outline-level)
3605 (when (and org-ellipsis
3606 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3607 (fboundp 'make-glyph-code))
3608 (unless org-display-table
3609 (setq org-display-table (make-display-table)))
3610 (set-display-table-slot
3611 org-display-table 4
3612 (vconcat (mapcar
3613 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3614 org-ellipsis)))
3615 (if (stringp org-ellipsis) org-ellipsis "..."))))
3616 (setq buffer-display-table org-display-table))
3617 (org-set-regexps-and-options)
3618 (when (and org-tag-faces (not org-tags-special-faces-re))
3619 ;; tag faces set outside customize.... force initialization.
3620 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3621 ;; Calc embedded
3622 (org-set-local 'calc-embedded-open-mode "# ")
3623 (modify-syntax-entry ?# "<")
3624 (modify-syntax-entry ?@ "w")
3625 (if org-startup-truncated (setq truncate-lines t))
3626 (org-set-local 'font-lock-unfontify-region-function
3627 'org-unfontify-region)
3628 ;; Activate before-change-function
3629 (org-set-local 'org-table-may-need-update t)
3630 (org-add-hook 'before-change-functions 'org-before-change-function nil
3631 'local)
3632 ;; Check for running clock before killing a buffer
3633 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3634 ;; Paragraphs and auto-filling
3635 (org-set-autofill-regexps)
3636 (setq indent-line-function 'org-indent-line-function)
3637 (org-update-radio-target-regexp)
3638 ;; Make sure dependence stuff works reliably, even for users who set it
3639 ;; too late :-(
3640 (if org-enforce-todo-dependencies
3641 (add-hook 'org-blocker-hook
3642 'org-block-todo-from-children-or-siblings)
3643 (remove-hook 'org-blocker-hook
3644 'org-block-todo-from-children-or-siblings))
3645 (if org-enforce-todo-checkbox-dependencies
3646 (add-hook 'org-blocker-hook
3647 'org-block-todo-from-checkboxes)
3648 (remove-hook 'org-blocker-hook
3649 'org-block-todo-from-checkboxes))
3651 ;; Comment characters
3652 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3653 (org-set-local 'comment-padding " ")
3655 ;; Align options lines
3656 (org-set-local
3657 'align-mode-rules-list
3658 '((org-in-buffer-settings
3659 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3660 (modes . '(org-mode)))))
3662 ;; Imenu
3663 (org-set-local 'imenu-create-index-function
3664 'org-imenu-get-tree)
3666 ;; Make isearch reveal context
3667 (if (or (featurep 'xemacs)
3668 (not (boundp 'outline-isearch-open-invisible-function)))
3669 ;; Emacs 21 and XEmacs make use of the hook
3670 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3671 ;; Emacs 22 deals with this through a special variable
3672 (org-set-local 'outline-isearch-open-invisible-function
3673 (lambda (&rest ignore) (org-show-context 'isearch))))
3675 ;; If empty file that did not turn on org-mode automatically, make it to.
3676 (if (and org-insert-mode-line-in-empty-file
3677 (interactive-p)
3678 (= (point-min) (point-max)))
3679 (insert "# -*- mode: org -*-\n\n"))
3681 (unless org-inhibit-startup
3682 (when org-startup-align-all-tables
3683 (let ((bmp (buffer-modified-p)))
3684 (org-table-map-tables 'org-table-align)
3685 (set-buffer-modified-p bmp)))
3686 (org-set-startup-visibility)))
3688 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3690 (defun org-current-time ()
3691 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3692 (if (> (car org-time-stamp-rounding-minutes) 1)
3693 (let ((r (car org-time-stamp-rounding-minutes))
3694 (time (decode-time)))
3695 (apply 'encode-time
3696 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3697 (nthcdr 2 time))))
3698 (current-time)))
3700 ;;;; Font-Lock stuff, including the activators
3702 (defvar org-mouse-map (make-sparse-keymap))
3703 (org-defkey org-mouse-map
3704 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3705 (org-defkey org-mouse-map
3706 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3707 (when org-mouse-1-follows-link
3708 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3709 (when org-tab-follows-link
3710 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3711 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3713 (require 'font-lock)
3715 (defconst org-non-link-chars "]\t\n\r<>")
3716 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3717 "shell" "elisp"))
3718 (defvar org-link-types-re nil
3719 "Matches a link that has a url-like prefix like \"http:\"")
3720 (defvar org-link-re-with-space nil
3721 "Matches a link with spaces, optional angular brackets around it.")
3722 (defvar org-link-re-with-space2 nil
3723 "Matches a link with spaces, optional angular brackets around it.")
3724 (defvar org-link-re-with-space3 nil
3725 "Matches a link with spaces, only for internal part in bracket links.")
3726 (defvar org-angle-link-re nil
3727 "Matches link with angular brackets, spaces are allowed.")
3728 (defvar org-plain-link-re nil
3729 "Matches plain link, without spaces.")
3730 (defvar org-bracket-link-regexp nil
3731 "Matches a link in double brackets.")
3732 (defvar org-bracket-link-analytic-regexp nil
3733 "Regular expression used to analyze links.
3734 Here is what the match groups contain after a match:
3735 1: http:
3736 2: http
3737 3: path
3738 4: [desc]
3739 5: desc")
3740 (defvar org-bracket-link-analytic-regexp++ nil
3741 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3742 (defvar org-any-link-re nil
3743 "Regular expression matching any link.")
3745 (defun org-make-link-regexps ()
3746 "Update the link regular expressions.
3747 This should be called after the variable `org-link-types' has changed."
3748 (setq org-link-types-re
3749 (concat
3750 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3751 org-link-re-with-space
3752 (concat
3753 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3754 "\\([^" org-non-link-chars " ]"
3755 "[^" org-non-link-chars "]*"
3756 "[^" org-non-link-chars " ]\\)>?")
3757 org-link-re-with-space2
3758 (concat
3759 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3760 "\\([^" org-non-link-chars " ]"
3761 "[^\t\n\r]*"
3762 "[^" org-non-link-chars " ]\\)>?")
3763 org-link-re-with-space3
3764 (concat
3765 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3766 "\\([^" org-non-link-chars " ]"
3767 "[^\t\n\r]*\\)")
3768 org-angle-link-re
3769 (concat
3770 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3771 "\\([^" org-non-link-chars " ]"
3772 "[^" org-non-link-chars "]*"
3773 "\\)>")
3774 org-plain-link-re
3775 (concat
3776 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3777 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3778 org-bracket-link-regexp
3779 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3780 org-bracket-link-analytic-regexp
3781 (concat
3782 "\\[\\["
3783 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3784 "\\([^]]+\\)"
3785 "\\]"
3786 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3787 "\\]")
3788 org-bracket-link-analytic-regexp++
3789 (concat
3790 "\\[\\["
3791 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3792 "\\([^]]+\\)"
3793 "\\]"
3794 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3795 "\\]")
3796 org-any-link-re
3797 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3798 org-angle-link-re "\\)\\|\\("
3799 org-plain-link-re "\\)")))
3801 (org-make-link-regexps)
3803 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3804 "Regular expression for fast time stamp matching.")
3805 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3806 "Regular expression for fast time stamp matching.")
3807 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3808 "Regular expression matching time strings for analysis.
3809 This one does not require the space after the date, so it can be used
3810 on a string that terminates immediately after the date.")
3811 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3812 "Regular expression matching time strings for analysis.")
3813 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3814 "Regular expression matching time stamps, with groups.")
3815 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3816 "Regular expression matching time stamps (also [..]), with groups.")
3817 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3818 "Regular expression matching a time stamp range.")
3819 (defconst org-tr-regexp-both
3820 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3821 "Regular expression matching a time stamp range.")
3822 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3823 org-ts-regexp "\\)?")
3824 "Regular expression matching a time stamp or time stamp range.")
3825 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3826 org-ts-regexp-both "\\)?")
3827 "Regular expression matching a time stamp or time stamp range.
3828 The time stamps may be either active or inactive.")
3830 (defvar org-emph-face nil)
3832 (defun org-do-emphasis-faces (limit)
3833 "Run through the buffer and add overlays to links."
3834 (let (rtn)
3835 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3836 (if (not (= (char-after (match-beginning 3))
3837 (char-after (match-beginning 4))))
3838 (progn
3839 (setq rtn t)
3840 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3841 'face
3842 (nth 1 (assoc (match-string 3)
3843 org-emphasis-alist)))
3844 (add-text-properties (match-beginning 2) (match-end 2)
3845 '(font-lock-multiline t))
3846 (when org-hide-emphasis-markers
3847 (add-text-properties (match-end 4) (match-beginning 5)
3848 '(invisible org-link))
3849 (add-text-properties (match-beginning 3) (match-end 3)
3850 '(invisible org-link)))))
3851 (backward-char 1))
3852 rtn))
3854 (defun org-emphasize (&optional char)
3855 "Insert or change an emphasis, i.e. a font like bold or italic.
3856 If there is an active region, change that region to a new emphasis.
3857 If there is no region, just insert the marker characters and position
3858 the cursor between them.
3859 CHAR should be either the marker character, or the first character of the
3860 HTML tag associated with that emphasis. If CHAR is a space, the means
3861 to remove the emphasis of the selected region.
3862 If char is not given (for example in an interactive call) it
3863 will be prompted for."
3864 (interactive)
3865 (let ((eal org-emphasis-alist) e det
3866 (erc org-emphasis-regexp-components)
3867 (prompt "")
3868 (string "") beg end move tag c s)
3869 (if (org-region-active-p)
3870 (setq beg (region-beginning) end (region-end)
3871 string (buffer-substring beg end))
3872 (setq move t))
3874 (while (setq e (pop eal))
3875 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3876 c (aref tag 0))
3877 (push (cons c (string-to-char (car e))) det)
3878 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3879 (substring tag 1)))))
3880 (setq det (nreverse det))
3881 (unless char
3882 (message "%s" (concat "Emphasis marker or tag:" prompt))
3883 (setq char (read-char-exclusive)))
3884 (setq char (or (cdr (assoc char det)) char))
3885 (if (equal char ?\ )
3886 (setq s "" move nil)
3887 (unless (assoc (char-to-string char) org-emphasis-alist)
3888 (error "No such emphasis marker: \"%c\"" char))
3889 (setq s (char-to-string char)))
3890 (while (and (> (length string) 1)
3891 (equal (substring string 0 1) (substring string -1))
3892 (assoc (substring string 0 1) org-emphasis-alist))
3893 (setq string (substring string 1 -1)))
3894 (setq string (concat s string s))
3895 (if beg (delete-region beg end))
3896 (unless (or (bolp)
3897 (string-match (concat "[" (nth 0 erc) "\n]")
3898 (char-to-string (char-before (point)))))
3899 (insert " "))
3900 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3901 (char-to-string (char-after (point))))
3902 (insert " ") (backward-char 1))
3903 (insert string)
3904 (and move (backward-char 1))))
3906 (defconst org-nonsticky-props
3907 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3910 (defun org-activate-plain-links (limit)
3911 "Run through the buffer and add overlays to links."
3912 (catch 'exit
3913 (let (f)
3914 (while (re-search-forward org-plain-link-re limit t)
3915 (setq f (get-text-property (match-beginning 0) 'face))
3916 (if (or (eq f 'org-tag)
3917 (and (listp f) (memq 'org-tag f)))
3919 (add-text-properties (match-beginning 0) (match-end 0)
3920 (list 'mouse-face 'highlight
3921 'rear-nonsticky org-nonsticky-props
3922 'keymap org-mouse-map
3924 (throw 'exit t))))))
3926 (defun org-activate-code (limit)
3927 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3928 (progn
3929 (remove-text-properties (match-beginning 0) (match-end 0)
3930 '(display t invisible t intangible t))
3931 t)))
3933 (defun org-activate-angle-links (limit)
3934 "Run through the buffer and add overlays to links."
3935 (if (re-search-forward org-angle-link-re limit t)
3936 (progn
3937 (add-text-properties (match-beginning 0) (match-end 0)
3938 (list 'mouse-face 'highlight
3939 'rear-nonsticky org-nonsticky-props
3940 'keymap org-mouse-map
3942 t)))
3944 (defun org-activate-footnote-links (limit)
3945 "Run through the buffer and add overlays to links."
3946 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3947 limit t)
3948 (progn
3949 (add-text-properties (match-beginning 2) (match-end 2)
3950 (list 'mouse-face 'highlight
3951 'rear-nonsticky org-nonsticky-props
3952 'keymap org-mouse-map
3953 'help-echo
3954 (if (= (point-at-bol) (match-beginning 2))
3955 "Footnote definition"
3956 "Footnote reference")
3958 t)))
3960 (defun org-activate-bracket-links (limit)
3961 "Run through the buffer and add overlays to bracketed links."
3962 (if (re-search-forward org-bracket-link-regexp limit t)
3963 (let* ((help (concat "LINK: "
3964 (org-match-string-no-properties 1)))
3965 ;; FIXME: above we should remove the escapes.
3966 ;; but that requires another match, protecting match data,
3967 ;; a lot of overhead for font-lock.
3968 (ip (org-maybe-intangible
3969 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3970 'keymap org-mouse-map 'mouse-face 'highlight
3971 'font-lock-multiline t 'help-echo help)))
3972 (vp (list 'rear-nonsticky org-nonsticky-props
3973 'keymap org-mouse-map 'mouse-face 'highlight
3974 ' font-lock-multiline t 'help-echo help)))
3975 ;; We need to remove the invisible property here. Table narrowing
3976 ;; may have made some of this invisible.
3977 (remove-text-properties (match-beginning 0) (match-end 0)
3978 '(invisible nil))
3979 (if (match-end 3)
3980 (progn
3981 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3982 (add-text-properties (match-beginning 3) (match-end 3) vp)
3983 (add-text-properties (match-end 3) (match-end 0) ip))
3984 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3985 (add-text-properties (match-beginning 1) (match-end 1) vp)
3986 (add-text-properties (match-end 1) (match-end 0) ip))
3987 t)))
3989 (defun org-activate-dates (limit)
3990 "Run through the buffer and add overlays to dates."
3991 (if (re-search-forward org-tsr-regexp-both limit t)
3992 (progn
3993 (add-text-properties (match-beginning 0) (match-end 0)
3994 (list 'mouse-face 'highlight
3995 'rear-nonsticky org-nonsticky-props
3996 'keymap org-mouse-map))
3997 (when org-display-custom-times
3998 (if (match-end 3)
3999 (org-display-custom-time (match-beginning 3) (match-end 3)))
4000 (org-display-custom-time (match-beginning 1) (match-end 1)))
4001 t)))
4003 (defvar org-target-link-regexp nil
4004 "Regular expression matching radio targets in plain text.")
4005 (make-variable-buffer-local 'org-target-link-regexp)
4006 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4007 "Regular expression matching a link target.")
4008 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4009 "Regular expression matching a radio target.")
4010 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4011 "Regular expression matching any target.")
4013 (defun org-activate-target-links (limit)
4014 "Run through the buffer and add overlays to target matches."
4015 (when org-target-link-regexp
4016 (let ((case-fold-search t))
4017 (if (re-search-forward org-target-link-regexp limit t)
4018 (progn
4019 (add-text-properties (match-beginning 0) (match-end 0)
4020 (list 'mouse-face 'highlight
4021 'rear-nonsticky org-nonsticky-props
4022 'keymap org-mouse-map
4023 'help-echo "Radio target link"
4024 'org-linked-text t))
4025 t)))))
4027 (defun org-update-radio-target-regexp ()
4028 "Find all radio targets in this file and update the regular expression."
4029 (interactive)
4030 (when (memq 'radio org-activate-links)
4031 (setq org-target-link-regexp
4032 (org-make-target-link-regexp (org-all-targets 'radio)))
4033 (org-restart-font-lock)))
4035 (defun org-hide-wide-columns (limit)
4036 (let (s e)
4037 (setq s (text-property-any (point) (or limit (point-max))
4038 'org-cwidth t))
4039 (when s
4040 (setq e (next-single-property-change s 'org-cwidth))
4041 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4042 (goto-char e)
4043 t)))
4045 (defvar org-latex-and-specials-regexp nil
4046 "Regular expression for highlighting export special stuff.")
4047 (defvar org-match-substring-regexp)
4048 (defvar org-match-substring-with-braces-regexp)
4049 (defvar org-export-html-special-string-regexps)
4051 (defun org-compute-latex-and-specials-regexp ()
4052 "Compute regular expression for stuff treated specially by exporters."
4053 (if (not org-highlight-latex-fragments-and-specials)
4054 (org-set-local 'org-latex-and-specials-regexp nil)
4055 (require 'org-exp)
4056 (let*
4057 ((matchers (plist-get org-format-latex-options :matchers))
4058 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4059 org-latex-regexps)))
4060 (options (org-combine-plists (org-default-export-plist)
4061 (org-infile-export-plist)))
4062 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4063 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4064 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4065 (org-export-html-expand (plist-get options :expand-quoted-html))
4066 (org-export-with-special-strings (plist-get options :special-strings))
4067 (re-sub
4068 (cond
4069 ((equal org-export-with-sub-superscripts '{})
4070 (list org-match-substring-with-braces-regexp))
4071 (org-export-with-sub-superscripts
4072 (list org-match-substring-regexp))
4073 (t nil)))
4074 (re-latex
4075 (if org-export-with-LaTeX-fragments
4076 (mapcar (lambda (x) (nth 1 x)) latexs)))
4077 (re-macros
4078 (if org-export-with-TeX-macros
4079 (list (concat "\\\\"
4080 (regexp-opt
4081 (append (mapcar 'car org-html-entities)
4082 (if (boundp 'org-latex-entities)
4083 org-latex-entities nil))
4084 'words))) ; FIXME
4086 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4087 (re-special (if org-export-with-special-strings
4088 (mapcar (lambda (x) (car x))
4089 org-export-html-special-string-regexps)))
4090 (re-rest
4091 (delq nil
4092 (list
4093 (if org-export-html-expand "@<[^>\n]+>")
4094 ))))
4095 (org-set-local
4096 'org-latex-and-specials-regexp
4097 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4098 re-rest) "\\|")))))
4100 (defun org-do-latex-and-special-faces (limit)
4101 "Run through the buffer and add overlays to links."
4102 (when org-latex-and-specials-regexp
4103 (let (rtn d)
4104 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4105 limit t))
4106 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4107 'face))
4108 '(org-code org-verbatim underline)))
4109 (progn
4110 (setq rtn t
4111 d (cond ((member (char-after (1+ (match-beginning 0)))
4112 '(?_ ?^)) 1)
4113 (t 0)))
4114 (font-lock-prepend-text-property
4115 (+ d (match-beginning 0)) (match-end 0)
4116 'face 'org-latex-and-export-specials)
4117 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4118 '(font-lock-multiline t)))))
4119 rtn)))
4121 (defun org-restart-font-lock ()
4122 "Restart font-lock-mode, to force refontification."
4123 (when (and (boundp 'font-lock-mode) font-lock-mode)
4124 (font-lock-mode -1)
4125 (font-lock-mode 1)))
4127 (defun org-all-targets (&optional radio)
4128 "Return a list of all targets in this file.
4129 With optional argument RADIO, only find radio targets."
4130 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4131 rtn)
4132 (save-excursion
4133 (goto-char (point-min))
4134 (while (re-search-forward re nil t)
4135 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4136 rtn)))
4138 (defun org-make-target-link-regexp (targets)
4139 "Make regular expression matching all strings in TARGETS.
4140 The regular expression finds the targets also if there is a line break
4141 between words."
4142 (and targets
4143 (concat
4144 "\\<\\("
4145 (mapconcat
4146 (lambda (x)
4147 (while (string-match " +" x)
4148 (setq x (replace-match "\\s-+" t t x)))
4150 targets
4151 "\\|")
4152 "\\)\\>")))
4154 (defun org-activate-tags (limit)
4155 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4156 (progn
4157 (add-text-properties (match-beginning 1) (match-end 1)
4158 (list 'mouse-face 'highlight
4159 'rear-nonsticky org-nonsticky-props
4160 'keymap org-mouse-map))
4161 t)))
4163 (defun org-outline-level ()
4164 (save-excursion
4165 (looking-at outline-regexp)
4166 (if (match-beginning 1)
4167 (+ (org-get-string-indentation (match-string 1)) 1000)
4168 (1- (- (match-end 0) (match-beginning 0))))))
4170 (defvar org-font-lock-keywords nil)
4172 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4173 "Regular expression matching a property line.")
4175 (defvar org-font-lock-hook nil
4176 "Functions to be called for special font lock stuff.")
4178 (defun org-font-lock-hook (limit)
4179 (run-hook-with-args 'org-font-lock-hook limit))
4181 (defun org-set-font-lock-defaults ()
4182 (let* ((em org-fontify-emphasized-text)
4183 (lk org-activate-links)
4184 (org-font-lock-extra-keywords
4185 (list
4186 ;; Call the hook
4187 '(org-font-lock-hook)
4188 ;; Headlines
4189 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4190 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4191 ;; Table lines
4192 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4193 (1 'org-table t))
4194 ;; Table internals
4195 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4196 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4197 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4198 ;; Drawers
4199 (list org-drawer-regexp '(0 'org-special-keyword t))
4200 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4201 ;; Properties
4202 (list org-property-re
4203 '(1 'org-special-keyword t)
4204 '(3 'org-property-value t))
4205 (if org-format-transports-properties-p
4206 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4207 ;; Links
4208 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4209 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4210 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4211 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4212 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4213 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4214 (if (memq 'footnote lk) '(org-activate-footnote-links
4215 (2 'org-footnote t)))
4216 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4217 '(org-hide-wide-columns (0 nil append))
4218 ;; TODO lines
4219 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4220 '(1 (org-get-todo-face 1) t))
4221 ;; DONE
4222 (if org-fontify-done-headline
4223 (list (concat "^[*]+ +\\<\\("
4224 (mapconcat 'regexp-quote org-done-keywords "\\|")
4225 "\\)\\(.*\\)")
4226 '(2 'org-headline-done t))
4227 nil)
4228 ;; Priorities
4229 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4230 ;; Tags
4231 '(org-font-lock-add-tag-faces)
4232 ;; Special keywords
4233 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4234 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4235 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4236 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4237 ;; Emphasis
4238 (if em
4239 (if (featurep 'xemacs)
4240 '(org-do-emphasis-faces (0 nil append))
4241 '(org-do-emphasis-faces)))
4242 ;; Checkboxes
4243 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4244 2 'bold prepend)
4245 (if org-provide-checkbox-statistics
4246 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4247 (0 (org-get-checkbox-statistics-face) t)))
4248 ;; Description list items
4249 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4250 2 'bold prepend)
4251 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4252 '(1 'org-archived prepend))
4253 ;; Specials
4254 '(org-do-latex-and-special-faces)
4255 ;; Code
4256 '(org-activate-code (1 'org-code t))
4257 ;; COMMENT
4258 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4259 "\\|" org-quote-string "\\)\\>")
4260 '(1 'org-special-keyword t))
4261 '("^#.*" (0 'font-lock-comment-face t))
4263 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4264 ;; Now set the full font-lock-keywords
4265 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4266 (org-set-local 'font-lock-defaults
4267 '(org-font-lock-keywords t nil nil backward-paragraph))
4268 (kill-local-variable 'font-lock-keywords) nil))
4270 (defvar org-m nil)
4271 (defvar org-l nil)
4272 (defvar org-f nil)
4273 (defun org-get-level-face (n)
4274 "Get the right face for match N in font-lock matching of headlines."
4275 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4276 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4277 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4278 (cond
4279 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4280 ((eq n 2) org-f)
4281 (t (if org-level-color-stars-only nil org-f))))
4283 (defun org-get-todo-face (kwd)
4284 "Get the right face for a TODO keyword KWD.
4285 If KWD is a number, get the corresponding match group."
4286 (if (numberp kwd) (setq kwd (match-string kwd)))
4287 (or (cdr (assoc kwd org-todo-keyword-faces))
4288 (and (member kwd org-done-keywords) 'org-done)
4289 'org-todo))
4291 (defun org-font-lock-add-tag-faces (limit)
4292 "Add the special tag faces."
4293 (when (and org-tag-faces org-tags-special-faces-re)
4294 (while (re-search-forward org-tags-special-faces-re limit t)
4295 (add-text-properties (match-beginning 1) (match-end 1)
4296 (list 'face (org-get-tag-face 1)
4297 'font-lock-fontified t))
4298 (backward-char 1))))
4300 (defun org-get-tag-face (kwd)
4301 "Get the right face for a TODO keyword KWD.
4302 If KWD is a number, get the corresponding match group."
4303 (if (numberp kwd) (setq kwd (match-string kwd)))
4304 (or (cdr (assoc kwd org-tag-faces))
4305 'org-tag))
4307 (defun org-unfontify-region (beg end &optional maybe_loudly)
4308 "Remove fontification and activation overlays from links."
4309 (font-lock-default-unfontify-region beg end)
4310 (let* ((buffer-undo-list t)
4311 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4312 (inhibit-modification-hooks t)
4313 deactivate-mark buffer-file-name buffer-file-truename)
4314 (remove-text-properties beg end
4315 '(mouse-face t keymap t org-linked-text t
4316 invisible t intangible t))))
4318 ;;;; Visibility cycling, including org-goto and indirect buffer
4320 ;;; Cycling
4322 (defvar org-cycle-global-status nil)
4323 (make-variable-buffer-local 'org-cycle-global-status)
4324 (defvar org-cycle-subtree-status nil)
4325 (make-variable-buffer-local 'org-cycle-subtree-status)
4327 ;;;###autoload
4328 (defun org-cycle (&optional arg)
4329 "Visibility cycling for Org-mode.
4331 - When this function is called with a prefix argument, rotate the entire
4332 buffer through 3 states (global cycling)
4333 1. OVERVIEW: Show only top-level headlines.
4334 2. CONTENTS: Show all headlines of all levels, but no body text.
4335 3. SHOW ALL: Show everything.
4336 When called with two C-u C-u prefixes, switch to the startup visibility,
4337 determined by the variable `org-startup-folded', and by any VISIBILITY
4338 properties in the buffer.
4339 When called with three C-u C-u C-u prefixed, show the entire buffer,
4340 including drawers.
4342 - When point is at the beginning of a headline, rotate the subtree started
4343 by this line through 3 different states (local cycling)
4344 1. FOLDED: Only the main headline is shown.
4345 2. CHILDREN: The main headline and the direct children are shown.
4346 From this state, you can move to one of the children
4347 and zoom in further.
4348 3. SUBTREE: Show the entire subtree, including body text.
4350 - When there is a numeric prefix, go up to a heading with level ARG, do
4351 a `show-subtree' and return to the previous cursor position. If ARG
4352 is negative, go up that many levels.
4354 - When point is not at the beginning of a headline, execute the global
4355 binding for TAB, which is re-indenting the line. See the option
4356 `org-cycle-emulate-tab' for details.
4358 - Special case: if point is at the beginning of the buffer and there is
4359 no headline in line 1, this function will act as if called with prefix arg.
4360 But only if also the variable `org-cycle-global-at-bob' is t."
4361 (interactive "P")
4362 (org-load-modules-maybe)
4363 (let* ((outline-regexp
4364 (if (and (org-mode-p) org-cycle-include-plain-lists)
4365 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4366 outline-regexp))
4367 (bob-special (and org-cycle-global-at-bob (bobp)
4368 (not (looking-at outline-regexp))))
4369 (org-cycle-hook
4370 (if bob-special
4371 (delq 'org-optimize-window-after-visibility-change
4372 (copy-sequence org-cycle-hook))
4373 org-cycle-hook))
4374 (pos (point)))
4376 (if (or bob-special (equal arg '(4)))
4377 ;; special case: use global cycling
4378 (setq arg t))
4380 (cond
4382 ((equal arg '(16))
4383 (org-set-startup-visibility)
4384 (message "Startup visibility, plus VISIBILITY properties"))
4386 ((equal arg '(64))
4387 (show-all)
4388 (message "Entire buffer visible, including drawers"))
4390 ((org-at-table-p 'any)
4391 ;; Enter the table or move to the next field in the table
4392 (or (org-table-recognize-table.el)
4393 (progn
4394 (if arg (org-table-edit-field t)
4395 (org-table-justify-field-maybe)
4396 (call-interactively 'org-table-next-field)))))
4398 ((eq arg t) ;; Global cycling
4400 (cond
4401 ((and (eq last-command this-command)
4402 (eq org-cycle-global-status 'overview))
4403 ;; We just created the overview - now do table of contents
4404 ;; This can be slow in very large buffers, so indicate action
4405 (message "CONTENTS...")
4406 (org-content)
4407 (message "CONTENTS...done")
4408 (setq org-cycle-global-status 'contents)
4409 (run-hook-with-args 'org-cycle-hook 'contents))
4411 ((and (eq last-command this-command)
4412 (eq org-cycle-global-status 'contents))
4413 ;; We just showed the table of contents - now show everything
4414 (show-all)
4415 (message "SHOW ALL")
4416 (setq org-cycle-global-status 'all)
4417 (run-hook-with-args 'org-cycle-hook 'all))
4420 ;; Default action: go to overview
4421 (org-overview)
4422 (message "OVERVIEW")
4423 (setq org-cycle-global-status 'overview)
4424 (run-hook-with-args 'org-cycle-hook 'overview))))
4426 ((and org-drawers org-drawer-regexp
4427 (save-excursion
4428 (beginning-of-line 1)
4429 (looking-at org-drawer-regexp)))
4430 ;; Toggle block visibility
4431 (org-flag-drawer
4432 (not (get-char-property (match-end 0) 'invisible))))
4434 ((integerp arg)
4435 ;; Show-subtree, ARG levels up from here.
4436 (save-excursion
4437 (org-back-to-heading)
4438 (outline-up-heading (if (< arg 0) (- arg)
4439 (- (funcall outline-level) arg)))
4440 (org-show-subtree)))
4442 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4443 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4444 ;; At a heading: rotate between three different views
4445 (org-back-to-heading)
4446 (let ((goal-column 0) eoh eol eos)
4447 ;; First, some boundaries
4448 (save-excursion
4449 (org-back-to-heading)
4450 (save-excursion
4451 (beginning-of-line 2)
4452 (while (and (not (eobp)) ;; this is like `next-line'
4453 (get-char-property (1- (point)) 'invisible))
4454 (beginning-of-line 2)) (setq eol (point)))
4455 (outline-end-of-heading) (setq eoh (point))
4456 (org-end-of-subtree t)
4457 (unless (eobp)
4458 (skip-chars-forward " \t\n")
4459 (beginning-of-line 1) ; in case this is an item
4461 (setq eos (1- (point))))
4462 ;; Find out what to do next and set `this-command'
4463 (cond
4464 ((= eos eoh)
4465 ;; Nothing is hidden behind this heading
4466 (message "EMPTY ENTRY")
4467 (setq org-cycle-subtree-status nil)
4468 (save-excursion
4469 (goto-char eos)
4470 (outline-next-heading)
4471 (if (org-invisible-p) (org-flag-heading nil))))
4472 ((or (>= eol eos)
4473 (not (string-match "\\S-" (buffer-substring eol eos))))
4474 ;; Entire subtree is hidden in one line: open it
4475 (org-show-entry)
4476 (show-children)
4477 (message "CHILDREN")
4478 (save-excursion
4479 (goto-char eos)
4480 (outline-next-heading)
4481 (if (org-invisible-p) (org-flag-heading nil)))
4482 (setq org-cycle-subtree-status 'children)
4483 (run-hook-with-args 'org-cycle-hook 'children))
4484 ((and (eq last-command this-command)
4485 (eq org-cycle-subtree-status 'children))
4486 ;; We just showed the children, now show everything.
4487 (org-show-subtree)
4488 (message "SUBTREE")
4489 (setq org-cycle-subtree-status 'subtree)
4490 (run-hook-with-args 'org-cycle-hook 'subtree))
4492 ;; Default action: hide the subtree.
4493 (hide-subtree)
4494 (message "FOLDED")
4495 (setq org-cycle-subtree-status 'folded)
4496 (run-hook-with-args 'org-cycle-hook 'folded)))))
4498 ;; TAB emulation and template completion
4499 (buffer-read-only (org-back-to-heading))
4501 ((org-try-structure-completion))
4503 ((org-try-cdlatex-tab))
4505 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4506 (or (not (bolp))
4507 (not (looking-at outline-regexp))))
4508 (call-interactively (global-key-binding "\t")))
4510 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4511 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4512 (or (and (eq org-cycle-emulate-tab 'white)
4513 (= (match-end 0) (point-at-eol)))
4514 (and (eq org-cycle-emulate-tab 'whitestart)
4515 (>= (match-end 0) pos))))
4517 (eq org-cycle-emulate-tab t))
4518 (call-interactively (global-key-binding "\t")))
4520 (t (save-excursion
4521 (org-back-to-heading)
4522 (org-cycle))))))
4524 ;;;###autoload
4525 (defun org-global-cycle (&optional arg)
4526 "Cycle the global visibility. For details see `org-cycle'.
4527 With C-u prefix arg, switch to startup visibility.
4528 With a numeric prefix, show all headlines up to that level."
4529 (interactive "P")
4530 (let ((org-cycle-include-plain-lists
4531 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4532 (cond
4533 ((integerp arg)
4534 (show-all)
4535 (hide-sublevels arg)
4536 (setq org-cycle-global-status 'contents))
4537 ((equal arg '(4))
4538 (org-set-startup-visibility)
4539 (message "Startup visibility, plus VISIBILITY properties."))
4541 (org-cycle '(4))))))
4543 (defun org-set-startup-visibility ()
4544 "Set the visibility required by startup options and properties."
4545 (cond
4546 ((eq org-startup-folded t)
4547 (org-cycle '(4)))
4548 ((eq org-startup-folded 'content)
4549 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4550 (org-cycle '(4)) (org-cycle '(4)))))
4551 (org-set-visibility-according-to-property 'no-cleanup)
4552 (org-cycle-hide-archived-subtrees 'all)
4553 (org-cycle-hide-drawers 'all)
4554 (org-cycle-show-empty-lines 'all))
4556 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4557 "Switch subtree visibilities according to :VISIBILITY: property."
4558 (interactive)
4559 (let (org-show-entry-below state)
4560 (save-excursion
4561 (goto-char (point-min))
4562 (while (re-search-forward
4563 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4564 nil t)
4565 (setq state (match-string 1))
4566 (save-excursion
4567 (org-back-to-heading t)
4568 (hide-subtree)
4569 (org-reveal)
4570 (cond
4571 ((equal state '("fold" "folded"))
4572 (hide-subtree))
4573 ((equal state "children")
4574 (org-show-hidden-entry)
4575 (show-children))
4576 ((equal state "content")
4577 (save-excursion
4578 (save-restriction
4579 (org-narrow-to-subtree)
4580 (org-content))))
4581 ((member state '("all" "showall"))
4582 (show-subtree)))))
4583 (unless no-cleanup
4584 (org-cycle-hide-archived-subtrees 'all)
4585 (org-cycle-hide-drawers 'all)
4586 (org-cycle-show-empty-lines 'all)))))
4588 (defun org-overview ()
4589 "Switch to overview mode, showing only top-level headlines.
4590 Really, this shows all headlines with level equal or greater than the level
4591 of the first headline in the buffer. This is important, because if the
4592 first headline is not level one, then (hide-sublevels 1) gives confusing
4593 results."
4594 (interactive)
4595 (let ((level (save-excursion
4596 (goto-char (point-min))
4597 (if (re-search-forward (concat "^" outline-regexp) nil t)
4598 (progn
4599 (goto-char (match-beginning 0))
4600 (funcall outline-level))))))
4601 (and level (hide-sublevels level))))
4603 (defun org-content (&optional arg)
4604 "Show all headlines in the buffer, like a table of contents.
4605 With numerical argument N, show content up to level N."
4606 (interactive "P")
4607 (save-excursion
4608 ;; Visit all headings and show their offspring
4609 (and (integerp arg) (org-overview))
4610 (goto-char (point-max))
4611 (catch 'exit
4612 (while (and (progn (condition-case nil
4613 (outline-previous-visible-heading 1)
4614 (error (goto-char (point-min))))
4616 (looking-at outline-regexp))
4617 (if (integerp arg)
4618 (show-children (1- arg))
4619 (show-branches))
4620 (if (bobp) (throw 'exit nil))))))
4623 (defun org-optimize-window-after-visibility-change (state)
4624 "Adjust the window after a change in outline visibility.
4625 This function is the default value of the hook `org-cycle-hook'."
4626 (when (get-buffer-window (current-buffer))
4627 (cond
4628 ; ((eq state 'overview) (org-first-headline-recenter 1))
4629 ; ((eq state 'overview) (org-beginning-of-line))
4630 ((eq state 'content) nil)
4631 ((eq state 'all) nil)
4632 ((eq state 'folded) nil)
4633 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4634 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4636 (defun org-compact-display-after-subtree-move ()
4637 "Show a compacter version of the tree of the entry's parent."
4638 (save-excursion
4639 (if (org-up-heading-safe)
4640 (progn
4641 (hide-subtree)
4642 (show-entry)
4643 (show-children)
4644 (org-cycle-show-empty-lines 'children)
4645 (org-cycle-hide-drawers 'children))
4646 (org-overview))))
4648 (defun org-cycle-show-empty-lines (state)
4649 "Show empty lines above all visible headlines.
4650 The region to be covered depends on STATE when called through
4651 `org-cycle-hook'. Lisp program can use t for STATE to get the
4652 entire buffer covered. Note that an empty line is only shown if there
4653 are at least `org-cycle-separator-lines' empty lines before the headline."
4654 (when (> org-cycle-separator-lines 0)
4655 (save-excursion
4656 (let* ((n org-cycle-separator-lines)
4657 (re (cond
4658 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4659 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4660 (t (let ((ns (number-to-string (- n 2))))
4661 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4662 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4663 beg end)
4664 (cond
4665 ((memq state '(overview contents t))
4666 (setq beg (point-min) end (point-max)))
4667 ((memq state '(children folded))
4668 (setq beg (point) end (progn (org-end-of-subtree t t)
4669 (beginning-of-line 2)
4670 (point)))))
4671 (when beg
4672 (goto-char beg)
4673 (while (re-search-forward re end t)
4674 (if (not (get-char-property (match-end 1) 'invisible))
4675 (outline-flag-region
4676 (match-beginning 1) (match-end 1) nil)))))))
4677 ;; Never hide empty lines at the end of the file.
4678 (save-excursion
4679 (goto-char (point-max))
4680 (outline-previous-heading)
4681 (outline-end-of-heading)
4682 (if (and (looking-at "[ \t\n]+")
4683 (= (match-end 0) (point-max)))
4684 (outline-flag-region (point) (match-end 0) nil))))
4686 (defun org-show-empty-lines-in-parent ()
4687 "Move to the parent and re-show empty lines before visible headlines."
4688 (save-excursion
4689 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4690 (org-cycle-show-empty-lines context))))
4692 (defun org-cycle-hide-drawers (state)
4693 "Re-hide all drawers after a visibility state change."
4694 (when (and (org-mode-p)
4695 (not (memq state '(overview folded))))
4696 (save-excursion
4697 (let* ((globalp (memq state '(contents all)))
4698 (beg (if globalp (point-min) (point)))
4699 (end (if globalp (point-max) (org-end-of-subtree t))))
4700 (goto-char beg)
4701 (while (re-search-forward org-drawer-regexp end t)
4702 (org-flag-drawer t))))))
4704 (defun org-flag-drawer (flag)
4705 (save-excursion
4706 (beginning-of-line 1)
4707 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4708 (let ((b (match-end 0))
4709 (outline-regexp org-outline-regexp))
4710 (if (re-search-forward
4711 "^[ \t]*:END:"
4712 (save-excursion (outline-next-heading) (point)) t)
4713 (outline-flag-region b (point-at-eol) flag)
4714 (error ":END: line missing"))))))
4716 (defun org-subtree-end-visible-p ()
4717 "Is the end of the current subtree visible?"
4718 (pos-visible-in-window-p
4719 (save-excursion (org-end-of-subtree t) (point))))
4721 (defun org-first-headline-recenter (&optional N)
4722 "Move cursor to the first headline and recenter the headline.
4723 Optional argument N means, put the headline into the Nth line of the window."
4724 (goto-char (point-min))
4725 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4726 (beginning-of-line)
4727 (recenter (prefix-numeric-value N))))
4729 ;;; Org-goto
4731 (defvar org-goto-window-configuration nil)
4732 (defvar org-goto-marker nil)
4733 (defvar org-goto-map
4734 (let ((map (make-sparse-keymap)))
4735 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4736 (while (setq cmd (pop cmds))
4737 (substitute-key-definition cmd cmd map global-map)))
4738 (suppress-keymap map)
4739 (org-defkey map "\C-m" 'org-goto-ret)
4740 (org-defkey map [(return)] 'org-goto-ret)
4741 (org-defkey map [(left)] 'org-goto-left)
4742 (org-defkey map [(right)] 'org-goto-right)
4743 (org-defkey map [(control ?g)] 'org-goto-quit)
4744 (org-defkey map "\C-i" 'org-cycle)
4745 (org-defkey map [(tab)] 'org-cycle)
4746 (org-defkey map [(down)] 'outline-next-visible-heading)
4747 (org-defkey map [(up)] 'outline-previous-visible-heading)
4748 (if org-goto-auto-isearch
4749 (if (fboundp 'define-key-after)
4750 (define-key-after map [t] 'org-goto-local-auto-isearch)
4751 nil)
4752 (org-defkey map "q" 'org-goto-quit)
4753 (org-defkey map "n" 'outline-next-visible-heading)
4754 (org-defkey map "p" 'outline-previous-visible-heading)
4755 (org-defkey map "f" 'outline-forward-same-level)
4756 (org-defkey map "b" 'outline-backward-same-level)
4757 (org-defkey map "u" 'outline-up-heading))
4758 (org-defkey map "/" 'org-occur)
4759 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4760 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4761 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4762 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4763 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4764 map))
4766 (defconst org-goto-help
4767 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4768 RET=jump to location [Q]uit and return to previous location
4769 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4771 (defvar org-goto-start-pos) ; dynamically scoped parameter
4773 ;; FIXME: Docstring doe not mention both interfaces
4774 (defun org-goto (&optional alternative-interface)
4775 "Look up a different location in the current file, keeping current visibility.
4777 When you want look-up or go to a different location in a document, the
4778 fastest way is often to fold the entire buffer and then dive into the tree.
4779 This method has the disadvantage, that the previous location will be folded,
4780 which may not be what you want.
4782 This command works around this by showing a copy of the current buffer
4783 in an indirect buffer, in overview mode. You can dive into the tree in
4784 that copy, use org-occur and incremental search to find a location.
4785 When pressing RET or `Q', the command returns to the original buffer in
4786 which the visibility is still unchanged. After RET is will also jump to
4787 the location selected in the indirect buffer and expose the
4788 the headline hierarchy above."
4789 (interactive "P")
4790 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4791 (org-refile-use-outline-path t)
4792 (interface
4793 (if (not alternative-interface)
4794 org-goto-interface
4795 (if (eq org-goto-interface 'outline)
4796 'outline-path-completion
4797 'outline)))
4798 (org-goto-start-pos (point))
4799 (selected-point
4800 (if (eq interface 'outline)
4801 (car (org-get-location (current-buffer) org-goto-help))
4802 (nth 3 (org-refile-get-location "Goto: ")))))
4803 (if selected-point
4804 (progn
4805 (org-mark-ring-push org-goto-start-pos)
4806 (goto-char selected-point)
4807 (if (or (org-invisible-p) (org-invisible-p2))
4808 (org-show-context 'org-goto)))
4809 (message "Quit"))))
4811 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4812 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4813 (defvar org-goto-local-auto-isearch-map) ; defined below
4815 (defun org-get-location (buf help)
4816 "Let the user select a location in the Org-mode buffer BUF.
4817 This function uses a recursive edit. It returns the selected position
4818 or nil."
4819 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4820 (isearch-hide-immediately nil)
4821 (isearch-search-fun-function
4822 (lambda () 'org-goto-local-search-headings))
4823 (org-goto-selected-point org-goto-exit-command))
4824 (save-excursion
4825 (save-window-excursion
4826 (delete-other-windows)
4827 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4828 (switch-to-buffer
4829 (condition-case nil
4830 (make-indirect-buffer (current-buffer) "*org-goto*")
4831 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4832 (with-output-to-temp-buffer "*Help*"
4833 (princ help))
4834 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4835 (setq buffer-read-only nil)
4836 (let ((org-startup-truncated t)
4837 (org-startup-folded nil)
4838 (org-startup-align-all-tables nil))
4839 (org-mode)
4840 (org-overview))
4841 (setq buffer-read-only t)
4842 (if (and (boundp 'org-goto-start-pos)
4843 (integer-or-marker-p org-goto-start-pos))
4844 (let ((org-show-hierarchy-above t)
4845 (org-show-siblings t)
4846 (org-show-following-heading t))
4847 (goto-char org-goto-start-pos)
4848 (and (org-invisible-p) (org-show-context)))
4849 (goto-char (point-min)))
4850 (org-beginning-of-line)
4851 (message "Select location and press RET")
4852 (use-local-map org-goto-map)
4853 (recursive-edit)
4855 (kill-buffer "*org-goto*")
4856 (cons org-goto-selected-point org-goto-exit-command)))
4858 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4859 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4860 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4861 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4863 (defun org-goto-local-search-headings (string bound noerror)
4864 "Search and make sure that any matches are in headlines."
4865 (catch 'return
4866 (while (if isearch-forward
4867 (search-forward string bound noerror)
4868 (search-backward string bound noerror))
4869 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4870 (and (member :headline context)
4871 (not (member :tags context))))
4872 (throw 'return (point))))))
4874 (defun org-goto-local-auto-isearch ()
4875 "Start isearch."
4876 (interactive)
4877 (goto-char (point-min))
4878 (let ((keys (this-command-keys)))
4879 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4880 (isearch-mode t)
4881 (isearch-process-search-char (string-to-char keys)))))
4883 (defun org-goto-ret (&optional arg)
4884 "Finish `org-goto' by going to the new location."
4885 (interactive "P")
4886 (setq org-goto-selected-point (point)
4887 org-goto-exit-command 'return)
4888 (throw 'exit nil))
4890 (defun org-goto-left ()
4891 "Finish `org-goto' by going to the new location."
4892 (interactive)
4893 (if (org-on-heading-p)
4894 (progn
4895 (beginning-of-line 1)
4896 (setq org-goto-selected-point (point)
4897 org-goto-exit-command 'left)
4898 (throw 'exit nil))
4899 (error "Not on a heading")))
4901 (defun org-goto-right ()
4902 "Finish `org-goto' by going to the new location."
4903 (interactive)
4904 (if (org-on-heading-p)
4905 (progn
4906 (setq org-goto-selected-point (point)
4907 org-goto-exit-command 'right)
4908 (throw 'exit nil))
4909 (error "Not on a heading")))
4911 (defun org-goto-quit ()
4912 "Finish `org-goto' without cursor motion."
4913 (interactive)
4914 (setq org-goto-selected-point nil)
4915 (setq org-goto-exit-command 'quit)
4916 (throw 'exit nil))
4918 ;;; Indirect buffer display of subtrees
4920 (defvar org-indirect-dedicated-frame nil
4921 "This is the frame being used for indirect tree display.")
4922 (defvar org-last-indirect-buffer nil)
4924 (defun org-tree-to-indirect-buffer (&optional arg)
4925 "Create indirect buffer and narrow it to current subtree.
4926 With numerical prefix ARG, go up to this level and then take that tree.
4927 If ARG is negative, go up that many levels.
4928 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4929 indirect buffer previously made with this command, to avoid proliferation of
4930 indirect buffers. However, when you call the command with a `C-u' prefix, or
4931 when `org-indirect-buffer-display' is `new-frame', the last buffer
4932 is kept so that you can work with several indirect buffers at the same time.
4933 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4934 requests that a new frame be made for the new buffer, so that the dedicated
4935 frame is not changed."
4936 (interactive "P")
4937 (let ((cbuf (current-buffer))
4938 (cwin (selected-window))
4939 (pos (point))
4940 beg end level heading ibuf)
4941 (save-excursion
4942 (org-back-to-heading t)
4943 (when (numberp arg)
4944 (setq level (org-outline-level))
4945 (if (< arg 0) (setq arg (+ level arg)))
4946 (while (> (setq level (org-outline-level)) arg)
4947 (outline-up-heading 1 t)))
4948 (setq beg (point)
4949 heading (org-get-heading))
4950 (org-end-of-subtree t) (setq end (point)))
4951 (if (and (buffer-live-p org-last-indirect-buffer)
4952 (not (eq org-indirect-buffer-display 'new-frame))
4953 (not arg))
4954 (kill-buffer org-last-indirect-buffer))
4955 (setq ibuf (org-get-indirect-buffer cbuf)
4956 org-last-indirect-buffer ibuf)
4957 (cond
4958 ((or (eq org-indirect-buffer-display 'new-frame)
4959 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4960 (select-frame (make-frame))
4961 (delete-other-windows)
4962 (switch-to-buffer ibuf)
4963 (org-set-frame-title heading))
4964 ((eq org-indirect-buffer-display 'dedicated-frame)
4965 (raise-frame
4966 (select-frame (or (and org-indirect-dedicated-frame
4967 (frame-live-p org-indirect-dedicated-frame)
4968 org-indirect-dedicated-frame)
4969 (setq org-indirect-dedicated-frame (make-frame)))))
4970 (delete-other-windows)
4971 (switch-to-buffer ibuf)
4972 (org-set-frame-title (concat "Indirect: " heading)))
4973 ((eq org-indirect-buffer-display 'current-window)
4974 (switch-to-buffer ibuf))
4975 ((eq org-indirect-buffer-display 'other-window)
4976 (pop-to-buffer ibuf))
4977 (t (error "Invalid value.")))
4978 (if (featurep 'xemacs)
4979 (save-excursion (org-mode) (turn-on-font-lock)))
4980 (narrow-to-region beg end)
4981 (show-all)
4982 (goto-char pos)
4983 (and (window-live-p cwin) (select-window cwin))))
4985 (defun org-get-indirect-buffer (&optional buffer)
4986 (setq buffer (or buffer (current-buffer)))
4987 (let ((n 1) (base (buffer-name buffer)) bname)
4988 (while (buffer-live-p
4989 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4990 (setq n (1+ n)))
4991 (condition-case nil
4992 (make-indirect-buffer buffer bname 'clone)
4993 (error (make-indirect-buffer buffer bname)))))
4995 (defun org-set-frame-title (title)
4996 "Set the title of the current frame to the string TITLE."
4997 ;; FIXME: how to name a single frame in XEmacs???
4998 (unless (featurep 'xemacs)
4999 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5001 ;;;; Structure editing
5003 ;;; Inserting headlines
5005 (defun org-previous-line-empty-p ()
5006 (save-excursion
5007 (and (not (bobp))
5008 (or (beginning-of-line 0) t)
5009 (save-match-data
5010 (looking-at "[ \t]*$")))))
5012 (defun org-insert-heading (&optional force-heading)
5013 "Insert a new heading or item with same depth at point.
5014 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5015 If point is at the beginning of a headline, insert a sibling before the
5016 current headline. If point is not at the beginning, do not split the line,
5017 but create the new headline after the current line."
5018 (interactive "P")
5019 (if (= (buffer-size) 0)
5020 (insert "\n* ")
5021 (when (or force-heading (not (org-insert-item)))
5022 (let* ((empty-line-p nil)
5023 (head (save-excursion
5024 (condition-case nil
5025 (progn
5026 (org-back-to-heading)
5027 (setq empty-line-p (org-previous-line-empty-p))
5028 (match-string 0))
5029 (error "*"))))
5030 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5031 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5032 pos hide-previous previous-pos)
5033 (cond
5034 ((and (org-on-heading-p) (bolp)
5035 (or (bobp)
5036 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5037 ;; insert before the current line
5038 (open-line (if blank 2 1)))
5039 ((and (bolp)
5040 (or (bobp)
5041 (save-excursion
5042 (backward-char 1) (not (org-invisible-p)))))
5043 ;; insert right here
5044 nil)
5046 ;; somewhere in the line
5047 (save-excursion
5048 (setq previous-pos (point-at-bol))
5049 (end-of-line)
5050 (setq hide-previous (org-invisible-p)))
5051 (and org-insert-heading-respect-content (org-show-subtree))
5052 (let ((split
5053 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5054 (save-excursion
5055 (let ((p (point)))
5056 (goto-char (point-at-bol))
5057 (and (looking-at org-complex-heading-regexp)
5058 (> p (match-beginning 4)))))))
5059 tags pos)
5060 (cond
5061 (org-insert-heading-respect-content
5062 (org-end-of-subtree nil t)
5063 (or (bolp) (newline))
5064 (or (org-previous-line-empty-p)
5065 (and blank (newline)))
5066 (open-line 1))
5067 ((org-on-heading-p)
5068 (when hide-previous
5069 (show-children)
5070 (org-show-entry))
5071 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5072 (setq tags (and (match-end 2) (match-string 2)))
5073 (and (match-end 1)
5074 (delete-region (match-beginning 1) (match-end 1)))
5075 (setq pos (point-at-bol))
5076 (or split (end-of-line 1))
5077 (delete-horizontal-space)
5078 (newline (if blank 2 1))
5079 (when tags
5080 (save-excursion
5081 (goto-char pos)
5082 (end-of-line 1)
5083 (insert " " tags)
5084 (org-set-tags nil 'align))))
5086 (or split (end-of-line 1))
5087 (newline (if blank 2 1)))))))
5088 (insert head) (just-one-space)
5089 (setq pos (point))
5090 (end-of-line 1)
5091 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5092 (when (and org-insert-heading-respect-content hide-previous)
5093 (save-excursion
5094 (goto-char previous-pos)
5095 (hide-subtree)))
5096 (run-hooks 'org-insert-heading-hook)))))
5098 (defun org-get-heading (&optional no-tags)
5099 "Return the heading of the current entry, without the stars."
5100 (save-excursion
5101 (org-back-to-heading t)
5102 (if (looking-at
5103 (if no-tags
5104 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5105 "\\*+[ \t]+\\([^\r\n]*\\)"))
5106 (match-string 1) "")))
5108 (defun org-heading-components ()
5109 "Return the components of the current heading.
5110 This is a list with the following elements:
5111 - the level as an integer
5112 - the reduced level, different if `org-odd-levels-only' is set.
5113 - the TODO keyword, or nil
5114 - the priority character, like ?A, or nil if no priority is given
5115 - the headline text itself, or the tags string if no headline text
5116 - the tags string, or nil."
5117 (save-excursion
5118 (org-back-to-heading t)
5119 (if (looking-at org-complex-heading-regexp)
5120 (list (length (match-string 1))
5121 (org-reduced-level (length (match-string 1)))
5122 (org-match-string-no-properties 2)
5123 (and (match-end 3) (aref (match-string 3) 2))
5124 (org-match-string-no-properties 4)
5125 (org-match-string-no-properties 5)))))
5127 (defun org-insert-heading-after-current ()
5128 "Insert a new heading with same level as current, after current subtree."
5129 (interactive)
5130 (org-back-to-heading)
5131 (org-insert-heading)
5132 (org-move-subtree-down)
5133 (end-of-line 1))
5135 (defun org-insert-heading-respect-content ()
5136 (interactive)
5137 (let ((org-insert-heading-respect-content t))
5138 (org-insert-heading t)))
5140 (defun org-insert-todo-heading-respect-content (&optional force-state)
5141 (interactive "P")
5142 (let ((org-insert-heading-respect-content t))
5143 (org-insert-todo-heading force-state t)))
5145 (defun org-insert-todo-heading (arg &optional force-heading)
5146 "Insert a new heading with the same level and TODO state as current heading.
5147 If the heading has no TODO state, or if the state is DONE, use the first
5148 state (TODO by default). Also with prefix arg, force first state."
5149 (interactive "P")
5150 (when (or force-heading (not (org-insert-item 'checkbox)))
5151 (org-insert-heading force-heading)
5152 (save-excursion
5153 (org-back-to-heading)
5154 (outline-previous-heading)
5155 (looking-at org-todo-line-regexp))
5156 (let*
5157 ((new-mark-x
5158 (if (or arg
5159 (not (match-beginning 2))
5160 (member (match-string 2) org-done-keywords))
5161 (car org-todo-keywords-1)
5162 (match-string 2)))
5163 (new-mark
5165 (run-hook-with-args-until-success
5166 'org-todo-get-default-hook new-mark-x nil)
5167 new-mark-x)))
5168 (insert new-mark " "))
5169 (when org-provide-todo-statistics
5170 (org-update-parent-todo-statistics))))
5172 (defun org-insert-subheading (arg)
5173 "Insert a new subheading and demote it.
5174 Works for outline headings and for plain lists alike."
5175 (interactive "P")
5176 (org-insert-heading arg)
5177 (cond
5178 ((org-on-heading-p) (org-do-demote))
5179 ((org-at-item-p) (org-indent-item 1))))
5181 (defun org-insert-todo-subheading (arg)
5182 "Insert a new subheading with TODO keyword or checkbox and demote it.
5183 Works for outline headings and for plain lists alike."
5184 (interactive "P")
5185 (org-insert-todo-heading arg)
5186 (cond
5187 ((org-on-heading-p) (org-do-demote))
5188 ((org-at-item-p) (org-indent-item 1))))
5190 ;;; Promotion and Demotion
5192 (defun org-promote-subtree ()
5193 "Promote the entire subtree.
5194 See also `org-promote'."
5195 (interactive)
5196 (save-excursion
5197 (org-map-tree 'org-promote))
5198 (org-fix-position-after-promote))
5200 (defun org-demote-subtree ()
5201 "Demote the entire subtree. See `org-demote'.
5202 See also `org-promote'."
5203 (interactive)
5204 (save-excursion
5205 (org-map-tree 'org-demote))
5206 (org-fix-position-after-promote))
5209 (defun org-do-promote ()
5210 "Promote the current heading higher up the tree.
5211 If the region is active in `transient-mark-mode', promote all headings
5212 in the region."
5213 (interactive)
5214 (save-excursion
5215 (if (org-region-active-p)
5216 (org-map-region 'org-promote (region-beginning) (region-end))
5217 (org-promote)))
5218 (org-fix-position-after-promote))
5220 (defun org-do-demote ()
5221 "Demote the current heading lower down the tree.
5222 If the region is active in `transient-mark-mode', demote all headings
5223 in the region."
5224 (interactive)
5225 (save-excursion
5226 (if (org-region-active-p)
5227 (org-map-region 'org-demote (region-beginning) (region-end))
5228 (org-demote)))
5229 (org-fix-position-after-promote))
5231 (defun org-fix-position-after-promote ()
5232 "Make sure that after pro/demotion cursor position is right."
5233 (let ((pos (point)))
5234 (when (save-excursion
5235 (beginning-of-line 1)
5236 (looking-at org-todo-line-regexp)
5237 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5238 (cond ((eobp) (insert " "))
5239 ((eolp) (insert " "))
5240 ((equal (char-after) ?\ ) (forward-char 1))))))
5242 (defun org-reduced-level (l)
5243 "Compute the effective level of a heading.
5244 This takes into account the setting of `org-odd-levels-only'."
5245 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5247 (defun org-get-valid-level (level &optional change)
5248 "Rectify a level change under the influence of `org-odd-levels-only'
5249 LEVEL is a current level, CHANGE is by how much the level should be
5250 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5251 even level numbers will become the next higher odd number."
5252 (if org-odd-levels-only
5253 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5254 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5255 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5256 (max 1 (+ level change))))
5258 (if (boundp 'define-obsolete-function-alias)
5259 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5260 (define-obsolete-function-alias 'org-get-legal-level
5261 'org-get-valid-level)
5262 (define-obsolete-function-alias 'org-get-legal-level
5263 'org-get-valid-level "23.1")))
5265 (defun org-promote ()
5266 "Promote the current heading higher up the tree.
5267 If the region is active in `transient-mark-mode', promote all headings
5268 in the region."
5269 (org-back-to-heading t)
5270 (let* ((level (save-match-data (funcall outline-level)))
5271 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5272 (diff (abs (- level (length up-head) -1))))
5273 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5274 (replace-match up-head nil t)
5275 ;; Fixup tag positioning
5276 (and org-auto-align-tags (org-set-tags nil t))
5277 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5279 (defun org-demote ()
5280 "Demote the current heading lower down the tree.
5281 If the region is active in `transient-mark-mode', demote all headings
5282 in the region."
5283 (org-back-to-heading t)
5284 (let* ((level (save-match-data (funcall outline-level)))
5285 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5286 (diff (abs (- level (length down-head) -1))))
5287 (replace-match down-head nil t)
5288 ;; Fixup tag positioning
5289 (and org-auto-align-tags (org-set-tags nil t))
5290 (if org-adapt-indentation (org-fixup-indentation diff))))
5292 (defun org-map-tree (fun)
5293 "Call FUN for every heading underneath the current one."
5294 (org-back-to-heading)
5295 (let ((level (funcall outline-level)))
5296 (save-excursion
5297 (funcall fun)
5298 (while (and (progn
5299 (outline-next-heading)
5300 (> (funcall outline-level) level))
5301 (not (eobp)))
5302 (funcall fun)))))
5304 (defun org-map-region (fun beg end)
5305 "Call FUN for every heading between BEG and END."
5306 (let ((org-ignore-region t))
5307 (save-excursion
5308 (setq end (copy-marker end))
5309 (goto-char beg)
5310 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5311 (< (point) end))
5312 (funcall fun))
5313 (while (and (progn
5314 (outline-next-heading)
5315 (< (point) end))
5316 (not (eobp)))
5317 (funcall fun)))))
5319 (defun org-fixup-indentation (diff)
5320 "Change the indentation in the current entry by DIFF
5321 However, if any line in the current entry has no indentation, or if it
5322 would end up with no indentation after the change, nothing at all is done."
5323 (save-excursion
5324 (let ((end (save-excursion (outline-next-heading)
5325 (point-marker)))
5326 (prohibit (if (> diff 0)
5327 "^\\S-"
5328 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5329 col)
5330 (unless (save-excursion (end-of-line 1)
5331 (re-search-forward prohibit end t))
5332 (while (and (< (point) end)
5333 (re-search-forward "^[ \t]+" end t))
5334 (goto-char (match-end 0))
5335 (setq col (current-column))
5336 (if (< diff 0) (replace-match ""))
5337 (org-indent-to-column (+ diff col))))
5338 (move-marker end nil))))
5340 (defun org-convert-to-odd-levels ()
5341 "Convert an org-mode file with all levels allowed to one with odd levels.
5342 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5343 level 5 etc."
5344 (interactive)
5345 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5346 (let ((org-odd-levels-only nil) n)
5347 (save-excursion
5348 (goto-char (point-min))
5349 (while (re-search-forward "^\\*\\*+ " nil t)
5350 (setq n (- (length (match-string 0)) 2))
5351 (while (>= (setq n (1- n)) 0)
5352 (org-demote))
5353 (end-of-line 1))))))
5356 (defun org-convert-to-oddeven-levels ()
5357 "Convert an org-mode file with only odd levels to one with odd and even levels.
5358 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5359 section with an even level, conversion would destroy the structure of the file. An error
5360 is signaled in this case."
5361 (interactive)
5362 (goto-char (point-min))
5363 ;; First check if there are no even levels
5364 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5365 (org-show-context t)
5366 (error "Not all levels are odd in this file. Conversion not possible."))
5367 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5368 (let ((org-odd-levels-only nil) n)
5369 (save-excursion
5370 (goto-char (point-min))
5371 (while (re-search-forward "^\\*\\*+ " nil t)
5372 (setq n (/ (1- (length (match-string 0))) 2))
5373 (while (>= (setq n (1- n)) 0)
5374 (org-promote))
5375 (end-of-line 1))))))
5377 (defun org-tr-level (n)
5378 "Make N odd if required."
5379 (if org-odd-levels-only (1+ (/ n 2)) n))
5381 ;;; Vertical tree motion, cutting and pasting of subtrees
5383 (defun org-move-subtree-up (&optional arg)
5384 "Move the current subtree up past ARG headlines of the same level."
5385 (interactive "p")
5386 (org-move-subtree-down (- (prefix-numeric-value arg))))
5388 (defun org-move-subtree-down (&optional arg)
5389 "Move the current subtree down past ARG headlines of the same level."
5390 (interactive "p")
5391 (setq arg (prefix-numeric-value arg))
5392 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5393 'outline-get-last-sibling))
5394 (ins-point (make-marker))
5395 (cnt (abs arg))
5396 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5397 ;; Select the tree
5398 (org-back-to-heading)
5399 (setq beg0 (point))
5400 (save-excursion
5401 (setq ne-beg (org-back-over-empty-lines))
5402 (setq beg (point)))
5403 (save-match-data
5404 (save-excursion (outline-end-of-heading)
5405 (setq folded (org-invisible-p)))
5406 (outline-end-of-subtree))
5407 (outline-next-heading)
5408 (setq ne-end (org-back-over-empty-lines))
5409 (setq end (point))
5410 (goto-char beg0)
5411 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5412 ;; include less whitespace
5413 (save-excursion
5414 (goto-char beg)
5415 (forward-line (- ne-beg ne-end))
5416 (setq beg (point))))
5417 ;; Find insertion point, with error handling
5418 (while (> cnt 0)
5419 (or (and (funcall movfunc) (looking-at outline-regexp))
5420 (progn (goto-char beg0)
5421 (error "Cannot move past superior level or buffer limit")))
5422 (setq cnt (1- cnt)))
5423 (if (> arg 0)
5424 ;; Moving forward - still need to move over subtree
5425 (progn (org-end-of-subtree t t)
5426 (save-excursion
5427 (org-back-over-empty-lines)
5428 (or (bolp) (newline)))))
5429 (setq ne-ins (org-back-over-empty-lines))
5430 (move-marker ins-point (point))
5431 (setq txt (buffer-substring beg end))
5432 (org-save-markers-in-region beg end)
5433 (delete-region beg end)
5434 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5435 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5436 (let ((bbb (point)))
5437 (insert-before-markers txt)
5438 (org-reinstall-markers-in-region bbb)
5439 (move-marker ins-point bbb))
5440 (or (bolp) (insert "\n"))
5441 (setq ins-end (point))
5442 (goto-char ins-point)
5443 (org-skip-whitespace)
5444 (when (and (< arg 0)
5445 (org-first-sibling-p)
5446 (> ne-ins ne-beg))
5447 ;; Move whitespace back to beginning
5448 (save-excursion
5449 (goto-char ins-end)
5450 (let ((kill-whole-line t))
5451 (kill-line (- ne-ins ne-beg)) (point)))
5452 (insert (make-string (- ne-ins ne-beg) ?\n)))
5453 (move-marker ins-point nil)
5454 (org-compact-display-after-subtree-move)
5455 (org-show-empty-lines-in-parent)
5456 (unless folded
5457 (org-show-entry)
5458 (show-children)
5459 (org-cycle-hide-drawers 'children))))
5461 (defvar org-subtree-clip ""
5462 "Clipboard for cut and paste of subtrees.
5463 This is actually only a copy of the kill, because we use the normal kill
5464 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5466 (defvar org-subtree-clip-folded nil
5467 "Was the last copied subtree folded?
5468 This is used to fold the tree back after pasting.")
5470 (defun org-cut-subtree (&optional n)
5471 "Cut the current subtree into the clipboard.
5472 With prefix arg N, cut this many sequential subtrees.
5473 This is a short-hand for marking the subtree and then cutting it."
5474 (interactive "p")
5475 (org-copy-subtree n 'cut))
5477 (defun org-copy-subtree (&optional n cut force-store-markers)
5478 "Cut the current subtree into the clipboard.
5479 With prefix arg N, cut this many sequential subtrees.
5480 This is a short-hand for marking the subtree and then copying it.
5481 If CUT is non-nil, actually cut the subtree.
5482 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5483 of some markers in the region, even if CUT is non-nil. This is
5484 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5485 (interactive "p")
5486 (let (beg end folded (beg0 (point)))
5487 (if (interactive-p)
5488 (org-back-to-heading nil) ; take what looks like a subtree
5489 (org-back-to-heading t)) ; take what is really there
5490 (org-back-over-empty-lines)
5491 (setq beg (point))
5492 (skip-chars-forward " \t\r\n")
5493 (save-match-data
5494 (save-excursion (outline-end-of-heading)
5495 (setq folded (org-invisible-p)))
5496 (condition-case nil
5497 (outline-forward-same-level (1- n))
5498 (error nil))
5499 (org-end-of-subtree t t))
5500 (org-back-over-empty-lines)
5501 (setq end (point))
5502 (goto-char beg0)
5503 (when (> end beg)
5504 (setq org-subtree-clip-folded folded)
5505 (when (or cut force-store-markers)
5506 (org-save-markers-in-region beg end))
5507 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5508 (setq org-subtree-clip (current-kill 0))
5509 (message "%s: Subtree(s) with %d characters"
5510 (if cut "Cut" "Copied")
5511 (length org-subtree-clip)))))
5513 (defun org-paste-subtree (&optional level tree for-yank)
5514 "Paste the clipboard as a subtree, with modification of headline level.
5515 The entire subtree is promoted or demoted in order to match a new headline
5516 level.
5518 If the cursor is at the beginning of a headline, the same level as
5519 that headline is used to paste the tree
5521 If not, the new level is derived from the *visible* headings
5522 before and after the insertion point, and taken to be the inferior headline
5523 level of the two. So if the previous visible heading is level 3 and the
5524 next is level 4 (or vice versa), level 4 will be used for insertion.
5525 This makes sure that the subtree remains an independent subtree and does
5526 not swallow low level entries.
5528 You can also force a different level, either by using a numeric prefix
5529 argument, or by inserting the heading marker by hand. For example, if the
5530 cursor is after \"*****\", then the tree will be shifted to level 5.
5532 If optional TREE is given, use this text instead of the kill ring.
5534 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5535 move back over whitespace before inserting, and move point to the end of
5536 the inserted text when done."
5537 (interactive "P")
5538 (unless (org-kill-is-subtree-p tree)
5539 (error "%s"
5540 (substitute-command-keys
5541 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5542 (let* ((visp (not (org-invisible-p)))
5543 (txt (or tree (and kill-ring (current-kill 0))))
5544 (^re (concat "^\\(" outline-regexp "\\)"))
5545 (re (concat "\\(" outline-regexp "\\)"))
5546 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5548 (old-level (if (string-match ^re txt)
5549 (- (match-end 0) (match-beginning 0) 1)
5550 -1))
5551 (force-level (cond (level (prefix-numeric-value level))
5552 ((and (looking-at "[ \t]*$")
5553 (string-match
5554 ^re_ (buffer-substring
5555 (point-at-bol) (point))))
5556 (- (match-end 1) (match-beginning 1)))
5557 ((and (bolp)
5558 (looking-at org-outline-regexp))
5559 (- (match-end 0) (point) 1))
5560 (t nil)))
5561 (previous-level (save-excursion
5562 (condition-case nil
5563 (progn
5564 (outline-previous-visible-heading 1)
5565 (if (looking-at re)
5566 (- (match-end 0) (match-beginning 0) 1)
5568 (error 1))))
5569 (next-level (save-excursion
5570 (condition-case nil
5571 (progn
5572 (or (looking-at outline-regexp)
5573 (outline-next-visible-heading 1))
5574 (if (looking-at re)
5575 (- (match-end 0) (match-beginning 0) 1)
5577 (error 1))))
5578 (new-level (or force-level (max previous-level next-level)))
5579 (shift (if (or (= old-level -1)
5580 (= new-level -1)
5581 (= old-level new-level))
5583 (- new-level old-level)))
5584 (delta (if (> shift 0) -1 1))
5585 (func (if (> shift 0) 'org-demote 'org-promote))
5586 (org-odd-levels-only nil)
5587 beg end newend)
5588 ;; Remove the forced level indicator
5589 (if force-level
5590 (delete-region (point-at-bol) (point)))
5591 ;; Paste
5592 (beginning-of-line 1)
5593 (unless for-yank (org-back-over-empty-lines))
5594 (setq beg (point))
5595 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5596 (insert-before-markers txt)
5597 (unless (string-match "\n\\'" txt) (insert "\n"))
5598 (setq newend (point))
5599 (org-reinstall-markers-in-region beg)
5600 (setq end (point))
5601 (goto-char beg)
5602 (skip-chars-forward " \t\n\r")
5603 (setq beg (point))
5604 (if (and (org-invisible-p) visp)
5605 (save-excursion (outline-show-heading)))
5606 ;; Shift if necessary
5607 (unless (= shift 0)
5608 (save-restriction
5609 (narrow-to-region beg end)
5610 (while (not (= shift 0))
5611 (org-map-region func (point-min) (point-max))
5612 (setq shift (+ delta shift)))
5613 (goto-char (point-min))
5614 (setq newend (point-max))))
5615 (when (or (interactive-p) for-yank)
5616 (message "Clipboard pasted as level %d subtree" new-level))
5617 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5618 kill-ring
5619 (eq org-subtree-clip (current-kill 0))
5620 org-subtree-clip-folded)
5621 ;; The tree was folded before it was killed/copied
5622 (hide-subtree))
5623 (and for-yank (goto-char newend))))
5625 (defun org-kill-is-subtree-p (&optional txt)
5626 "Check if the current kill is an outline subtree, or a set of trees.
5627 Returns nil if kill does not start with a headline, or if the first
5628 headline level is not the largest headline level in the tree.
5629 So this will actually accept several entries of equal levels as well,
5630 which is OK for `org-paste-subtree'.
5631 If optional TXT is given, check this string instead of the current kill."
5632 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5633 (start-level (and kill
5634 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5635 org-outline-regexp "\\)")
5636 kill)
5637 (- (match-end 2) (match-beginning 2) 1)))
5638 (re (concat "^" org-outline-regexp))
5639 (start (1+ (or (match-beginning 2) -1))))
5640 (if (not start-level)
5641 (progn
5642 nil) ;; does not even start with a heading
5643 (catch 'exit
5644 (while (setq start (string-match re kill (1+ start)))
5645 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5646 (throw 'exit nil)))
5647 t))))
5649 (defvar org-markers-to-move nil
5650 "Markers that should be moved with a cut-and-paste operation.
5651 Those markers are stored together with their positions relative to
5652 the start of the region.")
5654 (defun org-save-markers-in-region (beg end)
5655 "Check markers in region.
5656 If these markers are between BEG and END, record their position relative
5657 to BEG, so that after moving the block of text, we can put the markers back
5658 into place.
5659 This function gets called just before an entry or tree gets cut from the
5660 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5661 called immediately, to move the markers with the entries."
5662 (setq org-markers-to-move nil)
5663 (when (featurep 'org-clock)
5664 (org-clock-save-markers-for-cut-and-paste beg end))
5665 (when (featurep 'org-agenda)
5666 (org-agenda-save-markers-for-cut-and-paste beg end)))
5668 (defun org-check-and-save-marker (marker beg end)
5669 "Check if MARKER is between BEG and END.
5670 If yes, remember the marker and the distance to BEG."
5671 (when (and (marker-buffer marker)
5672 (equal (marker-buffer marker) (current-buffer)))
5673 (if (and (>= marker beg) (< marker end))
5674 (push (cons marker (- marker beg)) org-markers-to-move))))
5676 (defun org-reinstall-markers-in-region (beg)
5677 "Move all remembered markers to their position relative to BEG."
5678 (mapc (lambda (x)
5679 (move-marker (car x) (+ beg (cdr x))))
5680 org-markers-to-move)
5681 (setq org-markers-to-move nil))
5683 (defun org-narrow-to-subtree ()
5684 "Narrow buffer to the current subtree."
5685 (interactive)
5686 (save-excursion
5687 (save-match-data
5688 (narrow-to-region
5689 (progn (org-back-to-heading) (point))
5690 (progn (org-end-of-subtree t) (point))))))
5693 ;;; Outline Sorting
5695 (defun org-sort (with-case)
5696 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5697 Optional argument WITH-CASE means sort case-sensitively."
5698 (interactive "P")
5699 (if (org-at-table-p)
5700 (org-call-with-arg 'org-table-sort-lines with-case)
5701 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5703 (defun org-sort-remove-invisible (s)
5704 (remove-text-properties 0 (length s) org-rm-props s)
5705 (while (string-match org-bracket-link-regexp s)
5706 (setq s (replace-match (if (match-end 2)
5707 (match-string 3 s)
5708 (match-string 1 s)) t t s)))
5711 (defvar org-priority-regexp) ; defined later in the file
5713 (defun org-sort-entries-or-items
5714 (&optional with-case sorting-type getkey-func compare-func property)
5715 "Sort entries on a certain level of an outline tree.
5716 If there is an active region, the entries in the region are sorted.
5717 Else, if the cursor is before the first entry, sort the top-level items.
5718 Else, the children of the entry at point are sorted.
5720 Sorting can be alphabetically, numerically, and by date/time as given by
5721 the first time stamp in the entry. The command prompts for the sorting
5722 type unless it has been given to the function through the SORTING-TYPE
5723 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5724 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5725 called with point at the beginning of the record. It must return either
5726 a string or a number that should serve as the sorting key for that record.
5728 Comparing entries ignores case by default. However, with an optional argument
5729 WITH-CASE, the sorting considers case as well."
5730 (interactive "P")
5731 (let ((case-func (if with-case 'identity 'downcase))
5732 start beg end stars re re2
5733 txt what tmp plain-list-p)
5734 ;; Find beginning and end of region to sort
5735 (cond
5736 ((org-region-active-p)
5737 ;; we will sort the region
5738 (setq end (region-end)
5739 what "region")
5740 (goto-char (region-beginning))
5741 (if (not (org-on-heading-p)) (outline-next-heading))
5742 (setq start (point)))
5743 ((org-at-item-p)
5744 ;; we will sort this plain list
5745 (org-beginning-of-item-list) (setq start (point))
5746 (org-end-of-item-list) (setq end (point))
5747 (goto-char start)
5748 (setq plain-list-p t
5749 what "plain list"))
5750 ((or (org-on-heading-p)
5751 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5752 ;; we will sort the children of the current headline
5753 (org-back-to-heading)
5754 (setq start (point)
5755 end (progn (org-end-of-subtree t t)
5756 (org-back-over-empty-lines)
5757 (point))
5758 what "children")
5759 (goto-char start)
5760 (show-subtree)
5761 (outline-next-heading))
5763 ;; we will sort the top-level entries in this file
5764 (goto-char (point-min))
5765 (or (org-on-heading-p) (outline-next-heading))
5766 (setq start (point) end (point-max) what "top-level")
5767 (goto-char start)
5768 (show-all)))
5770 (setq beg (point))
5771 (if (>= beg end) (error "Nothing to sort"))
5773 (unless plain-list-p
5774 (looking-at "\\(\\*+\\)")
5775 (setq stars (match-string 1)
5776 re (concat "^" (regexp-quote stars) " +")
5777 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5778 txt (buffer-substring beg end))
5779 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5780 (if (and (not (equal stars "*")) (string-match re2 txt))
5781 (error "Region to sort contains a level above the first entry")))
5783 (unless sorting-type
5784 (message
5785 (if plain-list-p
5786 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5787 "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:")
5788 what)
5789 (setq sorting-type (read-char-exclusive))
5791 (and (= (downcase sorting-type) ?f)
5792 (setq getkey-func
5793 (org-ido-completing-read "Sort using function: "
5794 obarray 'fboundp t nil nil))
5795 (setq getkey-func (intern getkey-func)))
5797 (and (= (downcase sorting-type) ?r)
5798 (setq property
5799 (org-ido-completing-read "Property: "
5800 (mapcar 'list (org-buffer-property-keys t))
5801 nil t))))
5803 (message "Sorting entries...")
5805 (save-restriction
5806 (narrow-to-region start end)
5808 (let ((dcst (downcase sorting-type))
5809 (now (current-time)))
5810 (sort-subr
5811 (/= dcst sorting-type)
5812 ;; This function moves to the beginning character of the "record" to
5813 ;; be sorted.
5814 (if plain-list-p
5815 (lambda nil
5816 (if (org-at-item-p) t (goto-char (point-max))))
5817 (lambda nil
5818 (if (re-search-forward re nil t)
5819 (goto-char (match-beginning 0))
5820 (goto-char (point-max)))))
5821 ;; This function moves to the last character of the "record" being
5822 ;; sorted.
5823 (if plain-list-p
5824 'org-end-of-item
5825 (lambda nil
5826 (save-match-data
5827 (condition-case nil
5828 (outline-forward-same-level 1)
5829 (error
5830 (goto-char (point-max)))))))
5832 ;; This function returns the value that gets sorted against.
5833 (if plain-list-p
5834 (lambda nil
5835 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5836 (cond
5837 ((= dcst ?n)
5838 (string-to-number (buffer-substring (match-end 0)
5839 (point-at-eol))))
5840 ((= dcst ?a)
5841 (buffer-substring (match-end 0) (point-at-eol)))
5842 ((= dcst ?t)
5843 (if (re-search-forward org-ts-regexp
5844 (point-at-eol) t)
5845 (org-time-string-to-time (match-string 0))
5846 now))
5847 ((= dcst ?f)
5848 (if getkey-func
5849 (progn
5850 (setq tmp (funcall getkey-func))
5851 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5852 tmp)
5853 (error "Invalid key function `%s'" getkey-func)))
5854 (t (error "Invalid sorting type `%c'" sorting-type)))))
5855 (lambda nil
5856 (cond
5857 ((= dcst ?n)
5858 (if (looking-at org-complex-heading-regexp)
5859 (string-to-number (match-string 4))
5860 nil))
5861 ((= dcst ?a)
5862 (if (looking-at org-complex-heading-regexp)
5863 (funcall case-func (match-string 4))
5864 nil))
5865 ((= dcst ?t)
5866 (if (re-search-forward org-ts-regexp
5867 (save-excursion
5868 (forward-line 2)
5869 (point)) t)
5870 (org-time-string-to-time (match-string 0))
5871 now))
5872 ((= dcst ?p)
5873 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5874 (string-to-char (match-string 2))
5875 org-default-priority))
5876 ((= dcst ?r)
5877 (or (org-entry-get nil property) ""))
5878 ((= dcst ?o)
5879 (if (looking-at org-complex-heading-regexp)
5880 (- 9999 (length (member (match-string 2)
5881 org-todo-keywords-1)))))
5882 ((= dcst ?f)
5883 (if getkey-func
5884 (progn
5885 (setq tmp (funcall getkey-func))
5886 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5887 tmp)
5888 (error "Invalid key function `%s'" getkey-func)))
5889 (t (error "Invalid sorting type `%c'" sorting-type)))))
5891 (cond
5892 ((= dcst ?a) 'string<)
5893 ((= dcst ?t) 'time-less-p)
5894 ((= dcst ?f) compare-func)
5895 (t nil)))))
5896 (message "Sorting entries...done")))
5898 (defun org-do-sort (table what &optional with-case sorting-type)
5899 "Sort TABLE of WHAT according to SORTING-TYPE.
5900 The user will be prompted for the SORTING-TYPE if the call to this
5901 function does not specify it. WHAT is only for the prompt, to indicate
5902 what is being sorted. The sorting key will be extracted from
5903 the car of the elements of the table.
5904 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5905 (unless sorting-type
5906 (message
5907 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5908 what)
5909 (setq sorting-type (read-char-exclusive)))
5910 (let ((dcst (downcase sorting-type))
5911 extractfun comparefun)
5912 ;; Define the appropriate functions
5913 (cond
5914 ((= dcst ?n)
5915 (setq extractfun 'string-to-number
5916 comparefun (if (= dcst sorting-type) '< '>)))
5917 ((= dcst ?a)
5918 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5919 (lambda(x) (downcase (org-sort-remove-invisible x))))
5920 comparefun (if (= dcst sorting-type)
5921 'string<
5922 (lambda (a b) (and (not (string< a b))
5923 (not (string= a b)))))))
5924 ((= dcst ?t)
5925 (setq extractfun
5926 (lambda (x)
5927 (if (or (string-match org-ts-regexp x)
5928 (string-match org-ts-regexp-both x))
5929 (time-to-seconds
5930 (org-time-string-to-time (match-string 0 x)))
5932 comparefun (if (= dcst sorting-type) '< '>)))
5933 (t (error "Invalid sorting type `%c'" sorting-type)))
5935 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5936 table)
5937 (lambda (a b) (funcall comparefun (car a) (car b))))))
5939 ;;; Editing source examples
5941 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5942 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5943 (defvar org-edit-src-force-single-line nil)
5944 (defvar org-edit-src-from-org-mode nil)
5945 (defvar org-edit-src-picture nil)
5947 (define-minor-mode org-exit-edit-mode
5948 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5950 (defun org-edit-src-code ()
5951 "Edit the source code example at point.
5952 An indirect buffer is created, and that buffer is then narrowed to the
5953 example at point and switched to the correct language mode. When done,
5954 exit by killing the buffer with \\[org-edit-src-exit]."
5955 (interactive)
5956 (let ((line (org-current-line))
5957 (case-fold-search t)
5958 (msg (substitute-command-keys
5959 "Edit, then exit with C-c ' (C-c and single quote)"))
5960 (info (org-edit-src-find-region-and-lang))
5961 (org-mode-p (eq major-mode 'org-mode))
5962 beg end lang lang-f single lfmt)
5963 (if (not info)
5965 (setq beg (nth 0 info)
5966 end (nth 1 info)
5967 lang (nth 2 info)
5968 single (nth 3 info)
5969 lfmt (nth 4 info)
5970 lang-f (intern (concat lang "-mode")))
5971 (unless (functionp lang-f)
5972 (error "No such language mode: %s" lang-f))
5973 (goto-line line)
5974 (if (get-buffer "*Org Edit Src Example*")
5975 (kill-buffer "*Org Edit Src Example*"))
5976 (switch-to-buffer (make-indirect-buffer (current-buffer)
5977 "*Org Edit Src Example*"))
5978 (narrow-to-region beg end)
5979 (remove-text-properties beg end '(display nil invisible nil
5980 intangible nil))
5981 (let ((org-inhibit-startup t))
5982 (funcall lang-f))
5983 (set (make-local-variable 'org-edit-src-force-single-line) single)
5984 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5985 (when lfmt
5986 (set (make-local-variable 'org-coderef-label-format) lfmt))
5987 (when org-mode-p
5988 (goto-char (point-min))
5989 (while (re-search-forward "^," nil t)
5990 (replace-match "")))
5991 (goto-line line)
5992 (org-exit-edit-mode)
5993 (org-set-local 'header-line-format msg)
5994 (message "%s" msg)
5995 t)))
5997 (defun org-edit-fixed-width-region ()
5998 "Edit the fixed-width ascii drawing at point.
5999 This must be a region where each line starts with a colon followed by
6000 a space character.
6001 An indirect buffer is created, and that buffer is then narrowed to the
6002 example at point and switched to artist-mode. When done,
6003 exit by killing the buffer with \\[org-edit-src-exit]."
6004 (interactive)
6005 (let ((line (org-current-line))
6006 (case-fold-search t)
6007 (msg (substitute-command-keys
6008 "Edit, then exit with C-c ' (C-c and single quote)"))
6009 (org-mode-p (eq major-mode 'org-mode))
6010 beg end)
6011 (beginning-of-line 1)
6012 (if (looking-at "[ \t]*[^:\n \t]")
6014 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6015 (setq beg (point) end beg)
6016 (save-excursion
6017 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6018 (setq beg (point-at-bol 2))
6019 (setq beg (point))))
6020 (save-excursion
6021 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6022 (setq end (1- (match-beginning 0)))
6023 (setq end (point))))
6024 (goto-line line))
6025 (if (get-buffer "*Org Edit Picture*")
6026 (kill-buffer "*Org Edit Picture*"))
6027 (switch-to-buffer (make-indirect-buffer (current-buffer)
6028 "*Org Edit Picture*"))
6029 (narrow-to-region beg end)
6030 (remove-text-properties beg end '(display nil invisible nil
6031 intangible nil))
6032 (when (fboundp 'font-lock-unfontify-region)
6033 (font-lock-unfontify-region (point-min) (point-max)))
6034 (cond
6035 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6036 (fundamental-mode)
6037 (artist-mode 1))
6038 (t (funcall org-edit-fixed-width-region-mode)))
6039 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6040 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6041 (set (make-local-variable 'org-edit-src-picture) t)
6042 (goto-char (point-min))
6043 (while (re-search-forward "^[ \t]*: ?" nil t)
6044 (replace-match ""))
6045 (goto-line line)
6046 (org-exit-edit-mode)
6047 (org-set-local 'header-line-format msg)
6048 (message "%s" msg)
6049 t)))
6052 (defun org-edit-src-find-region-and-lang ()
6053 "Find the region and language for a local edit.
6054 Return a list with beginning and end of the region, a string representing
6055 the language, a switch telling of the content should be in a single line."
6056 (let ((re-list
6057 (append
6058 org-edit-src-region-extra
6060 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6061 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6062 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6063 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6064 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6065 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6066 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6067 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6068 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6069 ("^#\\+html:" "\n" "html" single-line)
6070 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6071 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6072 ("^#\\+latex:" "\n" "latex" single-line)
6073 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6074 ("^#\\+ascii:" "\n" "ascii" single-line)
6076 (pos (point))
6077 re1 re2 single beg end lang lfmt match-re1)
6078 (catch 'exit
6079 (while (setq entry (pop re-list))
6080 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6081 single (nth 3 entry))
6082 (save-excursion
6083 (if (or (looking-at re1)
6084 (re-search-backward re1 nil t))
6085 (progn
6086 (setq match-re1 (match-string 0))
6087 (setq beg (match-end 0)
6088 lang (org-edit-src-get-lang lang)
6089 lfmt (org-edit-src-get-label-format match-re1))
6090 (if (and (re-search-forward re2 nil t)
6091 (>= (match-end 0) pos))
6092 (throw 'exit (list beg (match-beginning 0)
6093 lang single lfmt))))
6094 (if (or (looking-at re2)
6095 (re-search-forward re2 nil t))
6096 (progn
6097 (setq end (match-beginning 0))
6098 (if (and (re-search-backward re1 nil t)
6099 (<= (match-beginning 0) pos))
6100 (progn
6101 (setq lfmt (org-edit-src-get-label-format
6102 (match-string 0)))
6103 (throw 'exit
6104 (list (match-end 0) end
6105 (org-edit-src-get-lang lang)
6106 single lfmt))))))))))))
6108 (defun org-edit-src-get-lang (lang)
6109 "Extract the src language."
6110 (let ((m (match-string 0)))
6111 (cond
6112 ((stringp lang) lang)
6113 ((integerp lang) (match-string lang))
6114 ((and (eq lang 'lang)
6115 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6116 (match-string 1 m))
6117 ((and (eq lang 'style)
6118 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6119 (match-string 1 m))
6120 (t "fundamental"))))
6122 (defun org-edit-src-get-label-format (s)
6123 "Extract the label format."
6124 (save-match-data
6125 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6126 (match-string 1 s))))
6128 (defun org-edit-src-exit ()
6129 "Exit special edit and protect problematic lines."
6130 (interactive)
6131 (unless (buffer-base-buffer (current-buffer))
6132 (error "This is not an indirect buffer, something is wrong..."))
6133 (unless (> (point-min) 1)
6134 (error "This buffer is not narrowed, something is wrong..."))
6135 (goto-char (point-min))
6136 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6137 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6138 (when (org-bound-and-true-p org-edit-src-force-single-line)
6139 (goto-char (point-min))
6140 (while (re-search-forward "\n" nil t)
6141 (replace-match " "))
6142 (goto-char (point-min))
6143 (if (looking-at "\\s-*") (replace-match " "))
6144 (if (re-search-forward "\\s-+\\'" nil t)
6145 (replace-match "")))
6146 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6147 (goto-char (point-min))
6148 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6149 (replace-match ",\\1"))
6150 (when font-lock-mode
6151 (font-lock-unfontify-region (point-min) (point-max)))
6152 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6153 (when (org-bound-and-true-p org-edit-src-picture)
6154 (untabify (point-min) (point-max))
6155 (goto-char (point-min))
6156 (while (re-search-forward "^" nil t)
6157 (replace-match ": "))
6158 (when font-lock-mode
6159 (font-lock-unfontify-region (point-min) (point-max)))
6160 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6161 (kill-buffer (current-buffer))
6162 (and (org-mode-p) (org-restart-font-lock)))
6165 ;;; The orgstruct minor mode
6167 ;; Define a minor mode which can be used in other modes in order to
6168 ;; integrate the org-mode structure editing commands.
6170 ;; This is really a hack, because the org-mode structure commands use
6171 ;; keys which normally belong to the major mode. Here is how it
6172 ;; works: The minor mode defines all the keys necessary to operate the
6173 ;; structure commands, but wraps the commands into a function which
6174 ;; tests if the cursor is currently at a headline or a plain list
6175 ;; item. If that is the case, the structure command is used,
6176 ;; temporarily setting many Org-mode variables like regular
6177 ;; expressions for filling etc. However, when any of those keys is
6178 ;; used at a different location, function uses `key-binding' to look
6179 ;; up if the key has an associated command in another currently active
6180 ;; keymap (minor modes, major mode, global), and executes that
6181 ;; command. There might be problems if any of the keys is otherwise
6182 ;; used as a prefix key.
6184 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6185 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6186 ;; addresses this by checking explicitly for both bindings.
6188 (defvar orgstruct-mode-map (make-sparse-keymap)
6189 "Keymap for the minor `orgstruct-mode'.")
6191 (defvar org-local-vars nil
6192 "List of local variables, for use by `orgstruct-mode'")
6194 ;;;###autoload
6195 (define-minor-mode orgstruct-mode
6196 "Toggle the minor more `orgstruct-mode'.
6197 This mode is for using Org-mode structure commands in other modes.
6198 The following key behave as if Org-mode was active, if the cursor
6199 is on a headline, or on a plain list item (both in the definition
6200 of Org-mode).
6202 M-up Move entry/item up
6203 M-down Move entry/item down
6204 M-left Promote
6205 M-right Demote
6206 M-S-up Move entry/item up
6207 M-S-down Move entry/item down
6208 M-S-left Promote subtree
6209 M-S-right Demote subtree
6210 M-q Fill paragraph and items like in Org-mode
6211 C-c ^ Sort entries
6212 C-c - Cycle list bullet
6213 TAB Cycle item visibility
6214 M-RET Insert new heading/item
6215 S-M-RET Insert new TODO heading / Checkbox item
6216 C-c C-c Set tags / toggle checkbox"
6217 nil " OrgStruct" nil
6218 (org-load-modules-maybe)
6219 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6221 ;;;###autoload
6222 (defun turn-on-orgstruct ()
6223 "Unconditionally turn on `orgstruct-mode'."
6224 (orgstruct-mode 1))
6226 ;;;###autoload
6227 (defun turn-on-orgstruct++ ()
6228 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6229 In addition to setting orgstruct-mode, this also exports all indentation and
6230 autofilling variables from org-mode into the buffer. Note that turning
6231 off orgstruct-mode will *not* remove these additional settings."
6232 (orgstruct-mode 1)
6233 (let (var val)
6234 (mapc
6235 (lambda (x)
6236 (when (string-match
6237 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6238 (symbol-name (car x)))
6239 (setq var (car x) val (nth 1 x))
6240 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6241 org-local-vars)))
6243 (defun orgstruct-error ()
6244 "Error when there is no default binding for a structure key."
6245 (interactive)
6246 (error "This key has no function outside structure elements"))
6248 (defun orgstruct-setup ()
6249 "Setup orgstruct keymaps."
6250 (let ((nfunc 0)
6251 (bindings
6252 (list
6253 '([(meta up)] org-metaup)
6254 '([(meta down)] org-metadown)
6255 '([(meta left)] org-metaleft)
6256 '([(meta right)] org-metaright)
6257 '([(meta shift up)] org-shiftmetaup)
6258 '([(meta shift down)] org-shiftmetadown)
6259 '([(meta shift left)] org-shiftmetaleft)
6260 '([(meta shift right)] org-shiftmetaright)
6261 '([(shift up)] org-shiftup)
6262 '([(shift down)] org-shiftdown)
6263 '([(shift left)] org-shiftleft)
6264 '([(shift right)] org-shiftright)
6265 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6266 '("\M-q" fill-paragraph)
6267 '("\C-c^" org-sort)
6268 '("\C-c-" org-cycle-list-bullet)))
6269 elt key fun cmd)
6270 (while (setq elt (pop bindings))
6271 (setq nfunc (1+ nfunc))
6272 (setq key (org-key (car elt))
6273 fun (nth 1 elt)
6274 cmd (orgstruct-make-binding fun nfunc key))
6275 (org-defkey orgstruct-mode-map key cmd))
6277 ;; Special treatment needed for TAB and RET
6278 (org-defkey orgstruct-mode-map [(tab)]
6279 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6280 (org-defkey orgstruct-mode-map "\C-i"
6281 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6283 (org-defkey orgstruct-mode-map "\M-\C-m"
6284 (orgstruct-make-binding 'org-insert-heading 105
6285 "\M-\C-m" [(meta return)]))
6286 (org-defkey orgstruct-mode-map [(meta return)]
6287 (orgstruct-make-binding 'org-insert-heading 106
6288 [(meta return)] "\M-\C-m"))
6290 (org-defkey orgstruct-mode-map [(shift meta return)]
6291 (orgstruct-make-binding 'org-insert-todo-heading 107
6292 [(meta return)] "\M-\C-m"))
6294 (unless org-local-vars
6295 (setq org-local-vars (org-get-local-variables)))
6299 (defun orgstruct-make-binding (fun n &rest keys)
6300 "Create a function for binding in the structure minor mode.
6301 FUN is the command to call inside a table. N is used to create a unique
6302 command name. KEYS are keys that should be checked in for a command
6303 to execute outside of tables."
6304 (eval
6305 (list 'defun
6306 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6307 '(arg)
6308 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6309 "Outside of structure, run the binding of `"
6310 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6311 "'.")
6312 '(interactive "p")
6313 (list 'if
6314 '(org-context-p 'headline 'item)
6315 (list 'org-run-like-in-org-mode (list 'quote fun))
6316 (list 'let '(orgstruct-mode)
6317 (list 'call-interactively
6318 (append '(or)
6319 (mapcar (lambda (k)
6320 (list 'key-binding k))
6321 keys)
6322 '('orgstruct-error))))))))
6324 (defun org-context-p (&rest contexts)
6325 "Check if local context is any of CONTEXTS.
6326 Possible values in the list of contexts are `table', `headline', and `item'."
6327 (let ((pos (point)))
6328 (goto-char (point-at-bol))
6329 (prog1 (or (and (memq 'table contexts)
6330 (looking-at "[ \t]*|"))
6331 (and (memq 'headline contexts)
6332 ;;????????? (looking-at "\\*+"))
6333 (looking-at outline-regexp))
6334 (and (memq 'item contexts)
6335 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6336 (goto-char pos))))
6338 (defun org-get-local-variables ()
6339 "Return a list of all local variables in an org-mode buffer."
6340 (let (varlist)
6341 (with-current-buffer (get-buffer-create "*Org tmp*")
6342 (erase-buffer)
6343 (org-mode)
6344 (setq varlist (buffer-local-variables)))
6345 (kill-buffer "*Org tmp*")
6346 (delq nil
6347 (mapcar
6348 (lambda (x)
6349 (setq x
6350 (if (symbolp x)
6351 (list x)
6352 (list (car x) (list 'quote (cdr x)))))
6353 (if (string-match
6354 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6355 (symbol-name (car x)))
6356 x nil))
6357 varlist))))
6359 ;;;###autoload
6360 (defun org-run-like-in-org-mode (cmd)
6361 (org-load-modules-maybe)
6362 (unless org-local-vars
6363 (setq org-local-vars (org-get-local-variables)))
6364 (eval (list 'let org-local-vars
6365 (list 'call-interactively (list 'quote cmd)))))
6367 ;;;; Archiving
6369 (defun org-get-category (&optional pos)
6370 "Get the category applying to position POS."
6371 (get-text-property (or pos (point)) 'org-category))
6373 (defun org-refresh-category-properties ()
6374 "Refresh category text properties in the buffer."
6375 (let ((def-cat (cond
6376 ((null org-category)
6377 (if buffer-file-name
6378 (file-name-sans-extension
6379 (file-name-nondirectory buffer-file-name))
6380 "???"))
6381 ((symbolp org-category) (symbol-name org-category))
6382 (t org-category)))
6383 beg end cat pos optionp)
6384 (org-unmodified
6385 (save-excursion
6386 (save-restriction
6387 (widen)
6388 (goto-char (point-min))
6389 (put-text-property (point) (point-max) 'org-category def-cat)
6390 (while (re-search-forward
6391 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6392 (setq pos (match-end 0)
6393 optionp (equal (char-after (match-beginning 0)) ?#)
6394 cat (org-trim (match-string 2)))
6395 (if optionp
6396 (setq beg (point-at-bol) end (point-max))
6397 (org-back-to-heading t)
6398 (setq beg (point) end (org-end-of-subtree t t)))
6399 (put-text-property beg end 'org-category cat)
6400 (goto-char pos)))))))
6403 ;;;; Link Stuff
6405 ;;; Link abbreviations
6407 (defun org-link-expand-abbrev (link)
6408 "Apply replacements as defined in `org-link-abbrev-alist."
6409 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6410 (let* ((key (match-string 1 link))
6411 (as (or (assoc key org-link-abbrev-alist-local)
6412 (assoc key org-link-abbrev-alist)))
6413 (tag (and (match-end 2) (match-string 3 link)))
6414 rpl)
6415 (if (not as)
6416 link
6417 (setq rpl (cdr as))
6418 (cond
6419 ((symbolp rpl) (funcall rpl tag))
6420 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6421 ((string-match "%h" rpl)
6422 (replace-match (url-hexify-string (or tag "")) t t rpl))
6423 (t (concat rpl tag)))))
6424 link))
6426 ;;; Storing and inserting links
6428 (defvar org-insert-link-history nil
6429 "Minibuffer history for links inserted with `org-insert-link'.")
6431 (defvar org-stored-links nil
6432 "Contains the links stored with `org-store-link'.")
6434 (defvar org-store-link-plist nil
6435 "Plist with info about the most recently link created with `org-store-link'.")
6437 (defvar org-link-protocols nil
6438 "Link protocols added to Org-mode using `org-add-link-type'.")
6440 (defvar org-store-link-functions nil
6441 "List of functions that are called to create and store a link.
6442 Each function will be called in turn until one returns a non-nil
6443 value. Each function should check if it is responsible for creating
6444 this link (for example by looking at the major mode).
6445 If not, it must exit and return nil.
6446 If yes, it should return a non-nil value after a calling
6447 `org-store-link-props' with a list of properties and values.
6448 Special properties are:
6450 :type The link prefix. like \"http\". This must be given.
6451 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6452 This is obligatory as well.
6453 :description Optional default description for the second pair
6454 of brackets in an Org-mode link. The user can still change
6455 this when inserting this link into an Org-mode buffer.
6457 In addition to these, any additional properties can be specified
6458 and then used in remember templates.")
6460 (defun org-add-link-type (type &optional follow export)
6461 "Add TYPE to the list of `org-link-types'.
6462 Re-compute all regular expressions depending on `org-link-types'
6464 FOLLOW and EXPORT are two functions.
6466 FOLLOW should take the link path as the single argument and do whatever
6467 is necessary to follow the link, for example find a file or display
6468 a mail message.
6470 EXPORT should format the link path for export to one of the export formats.
6471 It should be a function accepting three arguments:
6473 path the path of the link, the text after the prefix (like \"http:\")
6474 desc the description of the link, if any, nil if there was no description
6475 format the export format, a symbol like `html' or `latex'.
6477 The function may use the FORMAT information to return different values
6478 depending on the format. The return value will be put literally into
6479 the exported file.
6480 Org-mode has a built-in default for exporting links. If you are happy with
6481 this default, there is no need to define an export function for the link
6482 type. For a simple example of an export function, see `org-bbdb.el'."
6483 (add-to-list 'org-link-types type t)
6484 (org-make-link-regexps)
6485 (if (assoc type org-link-protocols)
6486 (setcdr (assoc type org-link-protocols) (list follow export))
6487 (push (list type follow export) org-link-protocols)))
6489 ;;;###autoload
6490 (defun org-store-link (arg)
6491 "\\<org-mode-map>Store an org-link to the current location.
6492 This link is added to `org-stored-links' and can later be inserted
6493 into an org-buffer with \\[org-insert-link].
6495 For some link types, a prefix arg is interpreted:
6496 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6497 For file links, arg negates `org-context-in-file-links'."
6498 (interactive "P")
6499 (org-load-modules-maybe)
6500 (setq org-store-link-plist nil) ; reset
6501 (let (link cpltxt desc description search txt)
6502 (cond
6504 ((run-hook-with-args-until-success 'org-store-link-functions)
6505 (setq link (plist-get org-store-link-plist :link)
6506 desc (or (plist-get org-store-link-plist :description) link)))
6508 ((equal (buffer-name) "*Org Edit Src Example*")
6509 (let (label gc)
6510 (while (or (not label)
6511 (save-excursion
6512 (save-restriction
6513 (widen)
6514 (goto-char (point-min))
6515 (re-search-forward
6516 (regexp-quote (format org-coderef-label-format label))
6517 nil t))))
6518 (when label (message "Label exists already") (sit-for 2))
6519 (setq label (read-string "Code line label: " label)))
6520 (end-of-line 1)
6521 (setq link (format org-coderef-label-format label))
6522 (setq gc (- 79 (length link)))
6523 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6524 (insert link)
6525 (setq link (concat "(" label ")") desc nil)))
6527 ((eq major-mode 'calendar-mode)
6528 (let ((cd (calendar-cursor-to-date)))
6529 (setq link
6530 (format-time-string
6531 (car org-time-stamp-formats)
6532 (apply 'encode-time
6533 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6534 nil nil nil))))
6535 (org-store-link-props :type "calendar" :date cd)))
6537 ((eq major-mode 'w3-mode)
6538 (setq cpltxt (url-view-url t)
6539 link (org-make-link cpltxt))
6540 (org-store-link-props :type "w3" :url (url-view-url t)))
6542 ((eq major-mode 'w3m-mode)
6543 (setq cpltxt (or w3m-current-title w3m-current-url)
6544 link (org-make-link w3m-current-url))
6545 (org-store-link-props :type "w3m" :url (url-view-url t)))
6547 ((setq search (run-hook-with-args-until-success
6548 'org-create-file-search-functions))
6549 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6550 "::" search))
6551 (setq cpltxt (or description link)))
6553 ((eq major-mode 'image-mode)
6554 (setq cpltxt (concat "file:"
6555 (abbreviate-file-name buffer-file-name))
6556 link (org-make-link cpltxt))
6557 (org-store-link-props :type "image" :file buffer-file-name))
6559 ((eq major-mode 'dired-mode)
6560 ;; link to the file in the current line
6561 (setq cpltxt (concat "file:"
6562 (abbreviate-file-name
6563 (expand-file-name
6564 (dired-get-filename nil t))))
6565 link (org-make-link cpltxt)))
6567 ((and buffer-file-name (org-mode-p))
6568 (cond
6569 ((org-in-regexp "<<\\(.*?\\)>>")
6570 (setq cpltxt
6571 (concat "file:"
6572 (abbreviate-file-name buffer-file-name)
6573 "::" (match-string 1))
6574 link (org-make-link cpltxt)))
6575 ((and (featurep 'org-id)
6576 (or (eq org-link-to-org-use-id t)
6577 (and (eq org-link-to-org-use-id 'create-if-interactive)
6578 (interactive-p))
6579 (and org-link-to-org-use-id
6580 (condition-case nil
6581 (org-entry-get nil "ID")
6582 (error nil)))))
6583 ;; We can make a link using the ID.
6584 (setq link (condition-case nil
6585 (prog1 (org-id-store-link)
6586 (setq desc (plist-get org-store-link-plist
6587 :description)))
6588 (error
6589 ;; probably before first headline, link to file only
6590 (concat "file:"
6591 (abbreviate-file-name buffer-file-name))))))
6593 ;; Just link to current headline
6594 (setq cpltxt (concat "file:"
6595 (abbreviate-file-name buffer-file-name)))
6596 ;; Add a context search string
6597 (when (org-xor org-context-in-file-links arg)
6598 (setq txt (cond
6599 ((org-on-heading-p) nil)
6600 ((org-region-active-p)
6601 (buffer-substring (region-beginning) (region-end)))
6602 (t nil)))
6603 (when (or (null txt) (string-match "\\S-" txt))
6604 (setq cpltxt
6605 (concat cpltxt "::"
6606 (condition-case nil
6607 (org-make-org-heading-search-string txt)
6608 (error "")))
6609 desc "NONE")))
6610 (if (string-match "::\\'" cpltxt)
6611 (setq cpltxt (substring cpltxt 0 -2)))
6612 (setq link (org-make-link cpltxt)))))
6614 ((buffer-file-name (buffer-base-buffer))
6615 ;; Just link to this file here.
6616 (setq cpltxt (concat "file:"
6617 (abbreviate-file-name
6618 (buffer-file-name (buffer-base-buffer)))))
6619 ;; Add a context string
6620 (when (org-xor org-context-in-file-links arg)
6621 (setq txt (if (org-region-active-p)
6622 (buffer-substring (region-beginning) (region-end))
6623 (buffer-substring (point-at-bol) (point-at-eol))))
6624 ;; Only use search option if there is some text.
6625 (when (string-match "\\S-" txt)
6626 (setq cpltxt
6627 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6628 desc "NONE")))
6629 (setq link (org-make-link cpltxt)))
6631 ((interactive-p)
6632 (error "Cannot link to a buffer which is not visiting a file"))
6634 (t (setq link nil)))
6636 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6637 (setq link (or link cpltxt)
6638 desc (or desc cpltxt))
6639 (if (equal desc "NONE") (setq desc nil))
6641 (if (and (interactive-p) link)
6642 (progn
6643 (setq org-stored-links
6644 (cons (list link desc) org-stored-links))
6645 (message "Stored: %s" (or desc link)))
6646 (and link (org-make-link-string link desc)))))
6648 (defun org-store-link-props (&rest plist)
6649 "Store link properties, extract names and addresses."
6650 (let (x adr)
6651 (when (setq x (plist-get plist :from))
6652 (setq adr (mail-extract-address-components x))
6653 (setq plist (plist-put plist :fromname (car adr)))
6654 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6655 (when (setq x (plist-get plist :to))
6656 (setq adr (mail-extract-address-components x))
6657 (setq plist (plist-put plist :toname (car adr)))
6658 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6659 (let ((from (plist-get plist :from))
6660 (to (plist-get plist :to)))
6661 (when (and from to org-from-is-user-regexp)
6662 (setq plist
6663 (plist-put plist :fromto
6664 (if (string-match org-from-is-user-regexp from)
6665 (concat "to %t")
6666 (concat "from %f"))))))
6667 (setq org-store-link-plist plist))
6669 (defun org-add-link-props (&rest plist)
6670 "Add these properties to the link property list."
6671 (let (key value)
6672 (while plist
6673 (setq key (pop plist) value (pop plist))
6674 (setq org-store-link-plist
6675 (plist-put org-store-link-plist key value)))))
6677 (defun org-email-link-description (&optional fmt)
6678 "Return the description part of an email link.
6679 This takes information from `org-store-link-plist' and formats it
6680 according to FMT (default from `org-email-link-description-format')."
6681 (setq fmt (or fmt org-email-link-description-format))
6682 (let* ((p org-store-link-plist)
6683 (to (plist-get p :toaddress))
6684 (from (plist-get p :fromaddress))
6685 (table
6686 (list
6687 (cons "%c" (plist-get p :fromto))
6688 (cons "%F" (plist-get p :from))
6689 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6690 (cons "%T" (plist-get p :to))
6691 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6692 (cons "%s" (plist-get p :subject))
6693 (cons "%m" (plist-get p :message-id)))))
6694 (when (string-match "%c" fmt)
6695 ;; Check if the user wrote this message
6696 (if (and org-from-is-user-regexp from to
6697 (save-match-data (string-match org-from-is-user-regexp from)))
6698 (setq fmt (replace-match "to %t" t t fmt))
6699 (setq fmt (replace-match "from %f" t t fmt))))
6700 (org-replace-escapes fmt table)))
6702 (defun org-make-org-heading-search-string (&optional string heading)
6703 "Make search string for STRING or current headline."
6704 (interactive)
6705 (let ((s (or string (org-get-heading))))
6706 (unless (and string (not heading))
6707 ;; We are using a headline, clean up garbage in there.
6708 (if (string-match org-todo-regexp s)
6709 (setq s (replace-match "" t t s)))
6710 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6711 (setq s (replace-match "" t t s)))
6712 (setq s (org-trim s))
6713 (if (string-match (concat "^\\(" org-quote-string "\\|"
6714 org-comment-string "\\)") s)
6715 (setq s (replace-match "" t t s)))
6716 (while (string-match org-ts-regexp s)
6717 (setq s (replace-match "" t t s))))
6718 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6719 (setq s (replace-match " " t t s)))
6720 (or string (setq s (concat "*" s))) ; Add * for headlines
6721 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6723 (defun org-make-link (&rest strings)
6724 "Concatenate STRINGS."
6725 (apply 'concat strings))
6727 (defun org-make-link-string (link &optional description)
6728 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6729 (unless (string-match "\\S-" link)
6730 (error "Empty link"))
6731 (when (stringp description)
6732 ;; Remove brackets from the description, they are fatal.
6733 (while (string-match "\\[" description)
6734 (setq description (replace-match "{" t t description)))
6735 (while (string-match "\\]" description)
6736 (setq description (replace-match "}" t t description))))
6737 (when (equal (org-link-escape link) description)
6738 ;; No description needed, it is identical
6739 (setq description nil))
6740 (when (and (not description)
6741 (not (equal link (org-link-escape link))))
6742 (setq description (org-extract-attributes link)))
6743 (concat "[[" (org-link-escape link) "]"
6744 (if description (concat "[" description "]") "")
6745 "]"))
6747 (defconst org-link-escape-chars
6748 '((?\ . "%20")
6749 (?\[ . "%5B")
6750 (?\] . "%5D")
6751 (?\340 . "%E0") ; `a
6752 (?\342 . "%E2") ; ^a
6753 (?\347 . "%E7") ; ,c
6754 (?\350 . "%E8") ; `e
6755 (?\351 . "%E9") ; 'e
6756 (?\352 . "%EA") ; ^e
6757 (?\356 . "%EE") ; ^i
6758 (?\364 . "%F4") ; ^o
6759 (?\371 . "%F9") ; `u
6760 (?\373 . "%FB") ; ^u
6761 (?\; . "%3B")
6762 (?? . "%3F")
6763 (?= . "%3D")
6764 (?+ . "%2B")
6766 "Association list of escapes for some characters problematic in links.
6767 This is the list that is used for internal purposes.")
6769 (defconst org-link-escape-chars-browser
6770 '((?\ . "%20")) ; 32 for the SPC char
6771 "Association list of escapes for some characters problematic in links.
6772 This is the list that is used before handing over to the browser.")
6774 (defun org-link-escape (text &optional table)
6775 "Escape characters in TEXT that are problematic for links."
6776 (setq table (or table org-link-escape-chars))
6777 (when text
6778 (let ((re (mapconcat (lambda (x) (regexp-quote
6779 (char-to-string (car x))))
6780 table "\\|")))
6781 (while (string-match re text)
6782 (setq text
6783 (replace-match
6784 (cdr (assoc (string-to-char (match-string 0 text))
6785 table))
6786 t t text)))
6787 text)))
6789 (defun org-link-unescape (text &optional table)
6790 "Reverse the action of `org-link-escape'."
6791 (setq table (or table org-link-escape-chars))
6792 (when text
6793 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6794 table "\\|")))
6795 (while (string-match re text)
6796 (setq text
6797 (replace-match
6798 (char-to-string (car (rassoc (match-string 0 text) table)))
6799 t t text)))
6800 text)))
6802 (defun org-xor (a b)
6803 "Exclusive or."
6804 (if a (not b) b))
6806 (defun org-fixup-message-id-for-http (s)
6807 "Replace special characters in a message id, so it can be used in an http query."
6808 (while (string-match "<" s)
6809 (setq s (replace-match "%3C" t t s)))
6810 (while (string-match ">" s)
6811 (setq s (replace-match "%3E" t t s)))
6812 (while (string-match "@" s)
6813 (setq s (replace-match "%40" t t s)))
6816 ;;;###autoload
6817 (defun org-insert-link-global ()
6818 "Insert a link like Org-mode does.
6819 This command can be called in any mode to insert a link in Org-mode syntax."
6820 (interactive)
6821 (org-load-modules-maybe)
6822 (org-run-like-in-org-mode 'org-insert-link))
6824 (defun org-insert-link (&optional complete-file link-location)
6825 "Insert a link. At the prompt, enter the link.
6827 Completion can be used to insert any of the link protocol prefixes like
6828 http or ftp in use.
6830 The history can be used to select a link previously stored with
6831 `org-store-link'. When the empty string is entered (i.e. if you just
6832 press RET at the prompt), the link defaults to the most recently
6833 stored link. As SPC triggers completion in the minibuffer, you need to
6834 use M-SPC or C-q SPC to force the insertion of a space character.
6836 You will also be prompted for a description, and if one is given, it will
6837 be displayed in the buffer instead of the link.
6839 If there is already a link at point, this command will allow you to edit link
6840 and description parts.
6842 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6843 be selected using completion. The path to the file will be relative to the
6844 current directory if the file is in the current directory or a subdirectory.
6845 Otherwise, the link will be the absolute path as completed in the minibuffer
6846 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6847 option `org-link-file-path-type'.
6849 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6850 the current directory or below.
6852 With three \\[universal-argument] prefixes, negate the meaning of
6853 `org-keep-stored-link-after-insertion'.
6855 If `org-make-link-description-function' is non-nil, this function will be
6856 called with the link target, and the result will be the default
6857 link description.
6859 If the LINK-LOCATION parameter is non-nil, this value will be
6860 used as the link location instead of reading one interactively."
6861 (interactive "P")
6862 (let* ((wcf (current-window-configuration))
6863 (region (if (org-region-active-p)
6864 (buffer-substring (region-beginning) (region-end))))
6865 (remove (and region (list (region-beginning) (region-end))))
6866 (desc region)
6867 tmphist ; byte-compile incorrectly complains about this
6868 (link link-location)
6869 entry file)
6870 (cond
6871 (link-location) ; specified by arg, just use it.
6872 ((org-in-regexp org-bracket-link-regexp 1)
6873 ;; We do have a link at point, and we are going to edit it.
6874 (setq remove (list (match-beginning 0) (match-end 0)))
6875 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6876 (setq link (read-string "Link: "
6877 (org-link-unescape
6878 (org-match-string-no-properties 1)))))
6879 ((or (org-in-regexp org-angle-link-re)
6880 (org-in-regexp org-plain-link-re))
6881 ;; Convert to bracket link
6882 (setq remove (list (match-beginning 0) (match-end 0))
6883 link (read-string "Link: "
6884 (org-remove-angle-brackets (match-string 0)))))
6885 ((member complete-file '((4) (16)))
6886 ;; Completing read for file names.
6887 (setq file (read-file-name "File: "))
6888 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6889 (pwd1 (file-name-as-directory (abbreviate-file-name
6890 (expand-file-name ".")))))
6891 (cond
6892 ((equal complete-file '(16))
6893 (setq link (org-make-link
6894 "file:"
6895 (abbreviate-file-name (expand-file-name file)))))
6896 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6897 (setq link (org-make-link "file:" (match-string 1 file))))
6898 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6899 (expand-file-name file))
6900 (setq link (org-make-link
6901 "file:" (match-string 1 (expand-file-name file)))))
6902 (t (setq link (org-make-link "file:" file))))))
6904 ;; Read link, with completion for stored links.
6905 (with-output-to-temp-buffer "*Org Links*"
6906 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6907 (when org-stored-links
6908 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6909 (princ (mapconcat
6910 (lambda (x)
6911 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6912 (reverse org-stored-links) "\n"))))
6913 (let ((cw (selected-window)))
6914 (select-window (get-buffer-window "*Org Links*"))
6915 (setq truncate-lines t)
6916 (org-fit-window-to-buffer)
6917 (select-window cw))
6918 ;; Fake a link history, containing the stored links.
6919 (setq tmphist (append (mapcar 'car org-stored-links)
6920 org-insert-link-history))
6921 (unwind-protect
6922 (setq link
6923 (let ((org-completion-use-ido nil))
6924 (org-completing-read
6925 "Link: "
6926 (append
6927 (mapcar (lambda (x) (list (concat (car x) ":")))
6928 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6929 (mapcar (lambda (x) (list (concat x ":")))
6930 org-link-types))
6931 nil nil nil
6932 'tmphist
6933 (or (car (car org-stored-links))))))
6934 (set-window-configuration wcf)
6935 (kill-buffer "*Org Links*"))
6936 (setq entry (assoc link org-stored-links))
6937 (or entry (push link org-insert-link-history))
6938 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6939 (not org-keep-stored-link-after-insertion))
6940 (setq org-stored-links (delq (assoc link org-stored-links)
6941 org-stored-links)))
6942 (setq desc (or desc (nth 1 entry)))))
6944 (if (string-match org-plain-link-re link)
6945 ;; URL-like link, normalize the use of angular brackets.
6946 (setq link (org-make-link (org-remove-angle-brackets link))))
6948 ;; Check if we are linking to the current file with a search option
6949 ;; If yes, simplify the link by using only the search option.
6950 (when (and buffer-file-name
6951 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6952 (let* ((path (match-string 1 link))
6953 (case-fold-search nil)
6954 (search (match-string 2 link)))
6955 (save-match-data
6956 (if (equal (file-truename buffer-file-name) (file-truename path))
6957 ;; We are linking to this same file, with a search option
6958 (setq link search)))))
6960 ;; Check if we can/should use a relative path. If yes, simplify the link
6961 (when (string-match "^file:\\(.*\\)" link)
6962 (let* ((path (match-string 1 link))
6963 (origpath path)
6964 (case-fold-search nil))
6965 (cond
6966 ((or (eq org-link-file-path-type 'absolute)
6967 (equal complete-file '(16)))
6968 (setq path (abbreviate-file-name (expand-file-name path))))
6969 ((eq org-link-file-path-type 'noabbrev)
6970 (setq path (expand-file-name path)))
6971 ((eq org-link-file-path-type 'relative)
6972 (setq path (file-relative-name path)))
6974 (save-match-data
6975 (if (string-match (concat "^" (regexp-quote
6976 (file-name-as-directory
6977 (expand-file-name "."))))
6978 (expand-file-name path))
6979 ;; We are linking a file with relative path name.
6980 (setq path (substring (expand-file-name path)
6981 (match-end 0)))
6982 (setq path (abbreviate-file-name (expand-file-name path)))))))
6983 (setq link (concat "file:" path))
6984 (if (equal desc origpath)
6985 (setq desc path))))
6987 (if org-make-link-description-function
6988 (setq desc (funcall org-make-link-description-function link desc)))
6990 (setq desc (read-string "Description: " desc))
6991 (unless (string-match "\\S-" desc) (setq desc nil))
6992 (if remove (apply 'delete-region remove))
6993 (insert (org-make-link-string link desc))))
6995 (defun org-completing-read (&rest args)
6996 "Completing-read with SPACE being a normal character."
6997 (let ((minibuffer-local-completion-map
6998 (copy-keymap minibuffer-local-completion-map)))
6999 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7000 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7001 (apply 'org-ido-completing-read args)))
7003 (defun org-ido-completing-read (&rest args)
7004 "Completing-read using `ido-mode' speedups if available"
7005 (if (and org-completion-use-ido
7006 (fboundp 'ido-completing-read)
7007 (boundp 'ido-mode) ido-mode
7008 (listp (second args)))
7009 (apply 'ido-completing-read (concat (car args)) (cdr args))
7010 (apply 'completing-read args)))
7012 (defun org-extract-attributes (s)
7013 "Extract the attributes cookie from a string and set as text property."
7014 (let (a attr (start 0) key value)
7015 (save-match-data
7016 (when (string-match "{{\\([^}]+\\)}}$" s)
7017 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7018 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7019 (setq key (match-string 1 a) value (match-string 2 a)
7020 start (match-end 0)
7021 attr (plist-put attr (intern key) value))))
7022 (org-add-props s nil 'org-attr attr))
7025 (defun org-attributes-to-string (plist)
7026 "Format a property list into an HTML attribute list."
7027 (let ((s "") key value)
7028 (while plist
7029 (setq key (pop plist) value (pop plist))
7030 (and value
7031 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7034 ;;; Opening/following a link
7036 (defvar org-link-search-failed nil)
7038 (defun org-next-link ()
7039 "Move forward to the next link.
7040 If the link is in hidden text, expose it."
7041 (interactive)
7042 (when (and org-link-search-failed (eq this-command last-command))
7043 (goto-char (point-min))
7044 (message "Link search wrapped back to beginning of buffer"))
7045 (setq org-link-search-failed nil)
7046 (let* ((pos (point))
7047 (ct (org-context))
7048 (a (assoc :link ct)))
7049 (if a (goto-char (nth 2 a)))
7050 (if (re-search-forward org-any-link-re nil t)
7051 (progn
7052 (goto-char (match-beginning 0))
7053 (if (org-invisible-p) (org-show-context)))
7054 (goto-char pos)
7055 (setq org-link-search-failed t)
7056 (error "No further link found"))))
7058 (defun org-previous-link ()
7059 "Move backward to the previous link.
7060 If the link is in hidden text, expose it."
7061 (interactive)
7062 (when (and org-link-search-failed (eq this-command last-command))
7063 (goto-char (point-max))
7064 (message "Link search wrapped back to end of buffer"))
7065 (setq org-link-search-failed nil)
7066 (let* ((pos (point))
7067 (ct (org-context))
7068 (a (assoc :link ct)))
7069 (if a (goto-char (nth 1 a)))
7070 (if (re-search-backward org-any-link-re nil t)
7071 (progn
7072 (goto-char (match-beginning 0))
7073 (if (org-invisible-p) (org-show-context)))
7074 (goto-char pos)
7075 (setq org-link-search-failed t)
7076 (error "No further link found"))))
7078 (defun org-translate-link (s)
7079 "Translate a link string if a translation function has been defined."
7080 (if (and org-link-translation-function
7081 (fboundp org-link-translation-function)
7082 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7083 (progn
7084 (setq s (funcall org-link-translation-function
7085 (match-string 1) (match-string 2)))
7086 (concat (car s) ":" (cdr s)))
7089 (defun org-translate-link-from-planner (type path)
7090 "Translate a link from Emacs Planner syntax so that Org can follow it.
7091 This is still an experimental function, your mileage may vary."
7092 (cond
7093 ((member type '("http" "https" "news" "ftp"))
7094 ;; standard Internet links are the same.
7095 nil)
7096 ((and (equal type "irc") (string-match "^//" path))
7097 ;; Planner has two / at the beginning of an irc link, we have 1.
7098 ;; We should have zero, actually....
7099 (setq path (substring path 1)))
7100 ((and (equal type "lisp") (string-match "^/" path))
7101 ;; Planner has a slash, we do not.
7102 (setq type "elisp" path (substring path 1)))
7103 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7104 ;; A typical message link. Planner has the id after the fina slash,
7105 ;; we separate it with a hash mark
7106 (setq path (concat (match-string 1 path) "#"
7107 (org-remove-angle-brackets (match-string 2 path)))))
7109 (cons type path))
7111 (defun org-find-file-at-mouse (ev)
7112 "Open file link or URL at mouse."
7113 (interactive "e")
7114 (mouse-set-point ev)
7115 (org-open-at-point 'in-emacs))
7117 (defun org-open-at-mouse (ev)
7118 "Open file link or URL at mouse."
7119 (interactive "e")
7120 (mouse-set-point ev)
7121 (if (eq major-mode 'org-agenda-mode)
7122 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7123 (org-open-at-point))
7125 (defvar org-window-config-before-follow-link nil
7126 "The window configuration before following a link.
7127 This is saved in case the need arises to restore it.")
7129 (defvar org-open-link-marker (make-marker)
7130 "Marker pointing to the location where `org-open-at-point; was called.")
7132 ;;;###autoload
7133 (defun org-open-at-point-global ()
7134 "Follow a link like Org-mode does.
7135 This command can be called in any mode to follow a link that has
7136 Org-mode syntax."
7137 (interactive)
7138 (org-run-like-in-org-mode 'org-open-at-point))
7140 ;;;###autoload
7141 (defun org-open-link-from-string (s &optional arg)
7142 "Open a link in the string S, as if it was in Org-mode."
7143 (interactive "sLink: \nP")
7144 (with-temp-buffer
7145 (let ((org-inhibit-startup t))
7146 (org-mode)
7147 (insert s)
7148 (goto-char (point-min))
7149 (org-open-at-point arg))))
7151 (defun org-open-at-point (&optional in-emacs)
7152 "Open link at or after point.
7153 If there is no link at point, this function will search forward up to
7154 the end of the current subtree.
7155 Normally, files will be opened by an appropriate application. If the
7156 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7157 With a double prefix argument, try to open outside of Emacs, in the
7158 application the system uses for this file type."
7159 (interactive "P")
7160 (org-load-modules-maybe)
7161 (move-marker org-open-link-marker (point))
7162 (setq org-window-config-before-follow-link (current-window-configuration))
7163 (org-remove-occur-highlights nil nil t)
7164 (cond
7165 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7166 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7167 (org-footnote-action))
7169 (let (type path link line search (pos (point)))
7170 (catch 'match
7171 (save-excursion
7172 (skip-chars-forward "^]\n\r")
7173 (when (org-in-regexp org-bracket-link-regexp)
7174 (setq link (org-extract-attributes
7175 (org-link-unescape (org-match-string-no-properties 1))))
7176 (while (string-match " *\n *" link)
7177 (setq link (replace-match " " t t link)))
7178 (setq link (org-link-expand-abbrev link))
7179 (cond
7180 ((or (file-name-absolute-p link)
7181 (string-match "^\\.\\.?/" link))
7182 (setq type "file" path link))
7183 ((string-match org-link-re-with-space3 link)
7184 (setq type (match-string 1 link) path (match-string 2 link)))
7185 (t (setq type "thisfile" path link)))
7186 (throw 'match t)))
7188 (when (get-text-property (point) 'org-linked-text)
7189 (setq type "thisfile"
7190 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7191 (1+ (point)) (point))
7192 path (buffer-substring
7193 (previous-single-property-change pos 'org-linked-text)
7194 (next-single-property-change pos 'org-linked-text)))
7195 (throw 'match t))
7197 (save-excursion
7198 (when (or (org-in-regexp org-angle-link-re)
7199 (org-in-regexp org-plain-link-re))
7200 (setq type (match-string 1) path (match-string 2))
7201 (throw 'match t)))
7202 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7203 (setq type "tree-match"
7204 path (match-string 1))
7205 (throw 'match t))
7206 (save-excursion
7207 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7208 (setq type "tags"
7209 path (match-string 1))
7210 (while (string-match ":" path)
7211 (setq path (replace-match "+" t t path)))
7212 (throw 'match t))))
7213 (unless path
7214 (error "No link found"))
7215 ;; Remove any trailing spaces in path
7216 (if (string-match " +\\'" path)
7217 (setq path (replace-match "" t t path)))
7218 (if (and org-link-translation-function
7219 (fboundp org-link-translation-function))
7220 ;; Check if we need to translate the link
7221 (let ((tmp (funcall org-link-translation-function type path)))
7222 (setq type (car tmp) path (cdr tmp))))
7224 (cond
7226 ((assoc type org-link-protocols)
7227 (funcall (nth 1 (assoc type org-link-protocols)) path))
7229 ((equal type "mailto")
7230 (let ((cmd (car org-link-mailto-program))
7231 (args (cdr org-link-mailto-program)) args1
7232 (address path) (subject "") a)
7233 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7234 (setq address (match-string 1 path)
7235 subject (org-link-escape (match-string 2 path))))
7236 (while args
7237 (cond
7238 ((not (stringp (car args))) (push (pop args) args1))
7239 (t (setq a (pop args))
7240 (if (string-match "%a" a)
7241 (setq a (replace-match address t t a)))
7242 (if (string-match "%s" a)
7243 (setq a (replace-match subject t t a)))
7244 (push a args1))))
7245 (apply cmd (nreverse args1))))
7247 ((member type '("http" "https" "ftp" "news"))
7248 (browse-url (concat type ":" (org-link-escape
7249 path org-link-escape-chars-browser))))
7251 ((member type '("message"))
7252 (browse-url (concat type ":" path)))
7254 ((string= type "tags")
7255 (org-tags-view in-emacs path))
7256 ((string= type "thisfile")
7257 (if in-emacs
7258 (switch-to-buffer-other-window
7259 (org-get-buffer-for-internal-link (current-buffer)))
7260 (org-mark-ring-push))
7261 (let ((cmd `(org-link-search
7262 ,path
7263 ,(cond ((equal in-emacs '(4)) 'occur)
7264 ((equal in-emacs '(16)) 'org-occur)
7265 (t nil))
7266 ,pos)))
7267 (condition-case nil (eval cmd)
7268 (error (progn (widen) (eval cmd))))))
7270 ((string= type "tree-match")
7271 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7273 ((string= type "file")
7274 (if (string-match "::\\([0-9]+\\)\\'" path)
7275 (setq line (string-to-number (match-string 1 path))
7276 path (substring path 0 (match-beginning 0)))
7277 (if (string-match "::\\(.+\\)\\'" path)
7278 (setq search (match-string 1 path)
7279 path (substring path 0 (match-beginning 0)))))
7280 (if (string-match "[*?{]" (file-name-nondirectory path))
7281 (dired path)
7282 (org-open-file path in-emacs line search)))
7284 ((string= type "news")
7285 (require 'org-gnus)
7286 (org-gnus-follow-link path))
7288 ((string= type "shell")
7289 (let ((cmd path))
7290 (if (or (not org-confirm-shell-link-function)
7291 (funcall org-confirm-shell-link-function
7292 (format "Execute \"%s\" in shell? "
7293 (org-add-props cmd nil
7294 'face 'org-warning))))
7295 (progn
7296 (message "Executing %s" cmd)
7297 (shell-command cmd))
7298 (error "Abort"))))
7300 ((string= type "elisp")
7301 (let ((cmd path))
7302 (if (or (not org-confirm-elisp-link-function)
7303 (funcall org-confirm-elisp-link-function
7304 (format "Execute \"%s\" as elisp? "
7305 (org-add-props cmd nil
7306 'face 'org-warning))))
7307 (message "%s => %s" cmd
7308 (if (equal (string-to-char cmd) ?\()
7309 (eval (read cmd))
7310 (call-interactively (read cmd))))
7311 (error "Abort"))))
7314 (browse-url-at-point))))))
7315 (move-marker org-open-link-marker nil)
7316 (run-hook-with-args 'org-follow-link-hook))
7318 ;;;; Time estimates
7320 (defun org-get-effort (&optional pom)
7321 "Get the effort estimate for the current entry."
7322 (org-entry-get pom org-effort-property))
7324 ;;; File search
7326 (defvar org-create-file-search-functions nil
7327 "List of functions to construct the right search string for a file link.
7328 These functions are called in turn with point at the location to
7329 which the link should point.
7331 A function in the hook should first test if it would like to
7332 handle this file type, for example by checking the major-mode or
7333 the file extension. If it decides not to handle this file, it
7334 should just return nil to give other functions a chance. If it
7335 does handle the file, it must return the search string to be used
7336 when following the link. The search string will be part of the
7337 file link, given after a double colon, and `org-open-at-point'
7338 will automatically search for it. If special measures must be
7339 taken to make the search successful, another function should be
7340 added to the companion hook `org-execute-file-search-functions',
7341 which see.
7343 A function in this hook may also use `setq' to set the variable
7344 `description' to provide a suggestion for the descriptive text to
7345 be used for this link when it gets inserted into an Org-mode
7346 buffer with \\[org-insert-link].")
7348 (defvar org-execute-file-search-functions nil
7349 "List of functions to execute a file search triggered by a link.
7351 Functions added to this hook must accept a single argument, the
7352 search string that was part of the file link, the part after the
7353 double colon. The function must first check if it would like to
7354 handle this search, for example by checking the major-mode or the
7355 file extension. If it decides not to handle this search, it
7356 should just return nil to give other functions a chance. If it
7357 does handle the search, it must return a non-nil value to keep
7358 other functions from trying.
7360 Each function can access the current prefix argument through the
7361 variable `current-prefix-argument'. Note that a single prefix is
7362 used to force opening a link in Emacs, so it may be good to only
7363 use a numeric or double prefix to guide the search function.
7365 In case this is needed, a function in this hook can also restore
7366 the window configuration before `org-open-at-point' was called using:
7368 (set-window-configuration org-window-config-before-follow-link)")
7370 (defun org-link-search (s &optional type avoid-pos)
7371 "Search for a link search option.
7372 If S is surrounded by forward slashes, it is interpreted as a
7373 regular expression. In org-mode files, this will create an `org-occur'
7374 sparse tree. In ordinary files, `occur' will be used to list matches.
7375 If the current buffer is in `dired-mode', grep will be used to search
7376 in all files. If AVOID-POS is given, ignore matches near that position."
7377 (let ((case-fold-search t)
7378 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7379 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7380 (append '(("") (" ") ("\t") ("\n"))
7381 org-emphasis-alist)
7382 "\\|") "\\)"))
7383 (pos (point))
7384 (pre nil) (post nil)
7385 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7386 (cond
7387 ;; First check if there are any special
7388 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7389 ;; Now try the builtin stuff
7390 ((save-excursion
7391 (goto-char (point-min))
7392 (and
7393 (re-search-forward
7394 (concat "<<" (regexp-quote s0) ">>") nil t)
7395 (setq type 'dedicated
7396 pos (match-beginning 0))))
7397 ;; There is an exact target for this
7398 (goto-char pos))
7399 ((and (string-match "^(\\(.*\\))$" s0)
7400 (save-excursion
7401 (goto-char (point-min))
7402 (and
7403 (re-search-forward
7404 (concat "[^[]" (regexp-quote
7405 (format org-coderef-label-format
7406 (match-string 1 s0))))
7407 nil t)
7408 (setq type 'dedicated
7409 pos (1+ (match-beginning 0))))))
7410 ;; There is a coderef target for this
7411 (goto-char pos))
7412 ((string-match "^/\\(.*\\)/$" s)
7413 ;; A regular expression
7414 (cond
7415 ((org-mode-p)
7416 (org-occur (match-string 1 s)))
7417 ;;((eq major-mode 'dired-mode)
7418 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7419 (t (org-do-occur (match-string 1 s)))))
7421 ;; A normal search strings
7422 (when (equal (string-to-char s) ?*)
7423 ;; Anchor on headlines, post may include tags.
7424 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7425 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7426 s (substring s 1)))
7427 (remove-text-properties
7428 0 (length s)
7429 '(face nil mouse-face nil keymap nil fontified nil) s)
7430 ;; Make a series of regular expressions to find a match
7431 (setq words (org-split-string s "[ \n\r\t]+")
7433 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7434 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7435 "\\)" markers)
7436 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7437 re2a (concat "[ \t\r\n]" re2a_)
7438 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7439 re4 (concat "[^a-zA-Z_]" re4_)
7441 re1 (concat pre re2 post)
7442 re3 (concat pre (if pre re4_ re4) post)
7443 re5 (concat pre ".*" re4)
7444 re2 (concat pre re2)
7445 re2a (concat pre (if pre re2a_ re2a))
7446 re4 (concat pre (if pre re4_ re4))
7447 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7448 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7449 re5 "\\)"
7451 (cond
7452 ((eq type 'org-occur) (org-occur reall))
7453 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7454 (t (goto-char (point-min))
7455 (setq type 'fuzzy)
7456 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7457 (org-search-not-self 1 re1 nil t)
7458 (org-search-not-self 1 re2 nil t)
7459 (org-search-not-self 1 re2a nil t)
7460 (org-search-not-self 1 re3 nil t)
7461 (org-search-not-self 1 re4 nil t)
7462 (org-search-not-self 1 re5 nil t)
7464 (goto-char (match-beginning 1))
7465 (goto-char pos)
7466 (error "No match")))))
7468 ;; Normal string-search
7469 (goto-char (point-min))
7470 (if (search-forward s nil t)
7471 (goto-char (match-beginning 0))
7472 (error "No match"))))
7473 (and (org-mode-p) (org-show-context 'link-search))
7474 type))
7476 (defun org-search-not-self (group &rest args)
7477 "Execute `re-search-forward', but only accept matches that do not
7478 enclose the position of `org-open-link-marker'."
7479 (let ((m org-open-link-marker))
7480 (catch 'exit
7481 (while (apply 're-search-forward args)
7482 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7483 (goto-char (match-end group))
7484 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7485 (> (match-beginning 0) (marker-position m))
7486 (< (match-end 0) (marker-position m)))
7487 (save-match-data
7488 (or (not (org-in-regexp
7489 org-bracket-link-analytic-regexp 1))
7490 (not (match-end 4)) ; no description
7491 (and (<= (match-beginning 4) (point))
7492 (>= (match-end 4) (point))))))
7493 (throw 'exit (point))))))))
7495 (defun org-get-buffer-for-internal-link (buffer)
7496 "Return a buffer to be used for displaying the link target of internal links."
7497 (cond
7498 ((not org-display-internal-link-with-indirect-buffer)
7499 buffer)
7500 ((string-match "(Clone)$" (buffer-name buffer))
7501 (message "Buffer is already a clone, not making another one")
7502 ;; we also do not modify visibility in this case
7503 buffer)
7504 (t ; make a new indirect buffer for displaying the link
7505 (let* ((bn (buffer-name buffer))
7506 (ibn (concat bn "(Clone)"))
7507 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7508 (with-current-buffer ib (org-overview))
7509 ib))))
7511 (defun org-do-occur (regexp &optional cleanup)
7512 "Call the Emacs command `occur'.
7513 If CLEANUP is non-nil, remove the printout of the regular expression
7514 in the *Occur* buffer. This is useful if the regex is long and not useful
7515 to read."
7516 (occur regexp)
7517 (when cleanup
7518 (let ((cwin (selected-window)) win beg end)
7519 (when (setq win (get-buffer-window "*Occur*"))
7520 (select-window win))
7521 (goto-char (point-min))
7522 (when (re-search-forward "match[a-z]+" nil t)
7523 (setq beg (match-end 0))
7524 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7525 (setq end (1- (match-beginning 0)))))
7526 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7527 (goto-char (point-min))
7528 (select-window cwin))))
7530 ;;; The mark ring for links jumps
7532 (defvar org-mark-ring nil
7533 "Mark ring for positions before jumps in Org-mode.")
7534 (defvar org-mark-ring-last-goto nil
7535 "Last position in the mark ring used to go back.")
7536 ;; Fill and close the ring
7537 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7538 (loop for i from 1 to org-mark-ring-length do
7539 (push (make-marker) org-mark-ring))
7540 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7541 org-mark-ring)
7543 (defun org-mark-ring-push (&optional pos buffer)
7544 "Put the current position or POS into the mark ring and rotate it."
7545 (interactive)
7546 (setq pos (or pos (point)))
7547 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7548 (move-marker (car org-mark-ring)
7549 (or pos (point))
7550 (or buffer (current-buffer)))
7551 (message "%s"
7552 (substitute-command-keys
7553 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7555 (defun org-mark-ring-goto (&optional n)
7556 "Jump to the previous position in the mark ring.
7557 With prefix arg N, jump back that many stored positions. When
7558 called several times in succession, walk through the entire ring.
7559 Org-mode commands jumping to a different position in the current file,
7560 or to another Org-mode file, automatically push the old position
7561 onto the ring."
7562 (interactive "p")
7563 (let (p m)
7564 (if (eq last-command this-command)
7565 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7566 (setq p org-mark-ring))
7567 (setq org-mark-ring-last-goto p)
7568 (setq m (car p))
7569 (switch-to-buffer (marker-buffer m))
7570 (goto-char m)
7571 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7573 (defun org-remove-angle-brackets (s)
7574 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7575 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7577 (defun org-add-angle-brackets (s)
7578 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7579 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7581 (defun org-remove-double-quotes (s)
7582 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7583 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7586 ;;; Following specific links
7588 (defun org-follow-timestamp-link ()
7589 (cond
7590 ((org-at-date-range-p t)
7591 (let ((org-agenda-start-on-weekday)
7592 (t1 (match-string 1))
7593 (t2 (match-string 2)))
7594 (setq t1 (time-to-days (org-time-string-to-time t1))
7595 t2 (time-to-days (org-time-string-to-time t2)))
7596 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7597 ((org-at-timestamp-p t)
7598 (org-agenda-list nil (time-to-days (org-time-string-to-time
7599 (substring (match-string 1) 0 10)))
7601 (t (error "This should not happen"))))
7604 ;;; Following file links
7605 (defvar org-wait nil)
7606 (defun org-open-file (path &optional in-emacs line search)
7607 "Open the file at PATH.
7608 First, this expands any special file name abbreviations. Then the
7609 configuration variable `org-file-apps' is checked if it contains an
7610 entry for this file type, and if yes, the corresponding command is launched.
7612 If no application is found, Emacs simply visits the file.
7614 With optional prefix argument IN-EMACS, Emacs will visit the file.
7615 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7616 and o use an external application to visit the file.
7618 Optional LINE specifies a line to go to, optional SEARCH a string to
7619 search for. If LINE or SEARCH is given, the file will always be
7620 opened in Emacs.
7621 If the file does not exist, an error is thrown."
7622 (setq in-emacs (or in-emacs line search))
7623 (let* ((file (if (equal path "")
7624 buffer-file-name
7625 (substitute-in-file-name (expand-file-name path))))
7626 (apps (append org-file-apps (org-default-apps)))
7627 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7628 (dirp (if remp nil (file-directory-p file)))
7629 (file (if (and dirp org-open-directory-means-index-dot-org)
7630 (concat (file-name-as-directory file) "index.org")
7631 file))
7632 (a-m-a-p (assq 'auto-mode apps))
7633 (dfile (downcase file))
7634 (old-buffer (current-buffer))
7635 (old-pos (point))
7636 (old-mode major-mode)
7637 ext cmd)
7638 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7639 (setq ext (match-string 1 dfile))
7640 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7641 (setq ext (match-string 1 dfile))))
7642 (cond
7643 ((equal in-emacs '(16))
7644 (setq cmd (cdr (assoc 'system apps))))
7645 (in-emacs (setq cmd 'emacs))
7647 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7648 (and dirp (cdr (assoc 'directory apps)))
7649 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7650 'string-match)
7651 (cdr (assoc ext apps))
7652 (cdr (assoc t apps))))))
7653 (when (eq cmd 'system)
7654 (setq cmd (cdr (assoc 'system apps))))
7655 (when (eq cmd 'default)
7656 (setq cmd (cdr (assoc t apps))))
7657 (when (eq cmd 'mailcap)
7658 (require 'mailcap)
7659 (mailcap-parse-mailcaps)
7660 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7661 (command (mailcap-mime-info mime-type)))
7662 (if (stringp command)
7663 (setq cmd command)
7664 (setq cmd 'emacs))))
7665 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7666 (not (file-exists-p file))
7667 (not org-open-non-existing-files))
7668 (error "No such file: %s" file))
7669 (cond
7670 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7671 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7672 (while (string-match "['\"]%s['\"]" cmd)
7673 (setq cmd (replace-match "%s" t t cmd)))
7674 (while (string-match "%s" cmd)
7675 (setq cmd (replace-match
7676 (save-match-data
7677 (shell-quote-argument
7678 (convert-standard-filename file)))
7679 t t cmd)))
7680 (save-window-excursion
7681 (start-process-shell-command cmd nil cmd)
7682 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7684 ((or (stringp cmd)
7685 (eq cmd 'emacs))
7686 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7687 (widen)
7688 (if line (goto-line line)
7689 (if search (org-link-search search))))
7690 ((consp cmd)
7691 (let ((file (convert-standard-filename file)))
7692 (eval cmd)))
7693 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7694 (and (org-mode-p) (eq old-mode 'org-mode)
7695 (or (not (equal old-buffer (current-buffer)))
7696 (not (equal old-pos (point))))
7697 (org-mark-ring-push old-pos old-buffer))))
7699 (defun org-default-apps ()
7700 "Return the default applications for this operating system."
7701 (cond
7702 ((eq system-type 'darwin)
7703 org-file-apps-defaults-macosx)
7704 ((eq system-type 'windows-nt)
7705 org-file-apps-defaults-windowsnt)
7706 (t org-file-apps-defaults-gnu)))
7708 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7709 "Convert extensions to regular expressions in the cars of LIST.
7710 Also, weed out any non-string entries, because the return value is used
7711 only for regexp matching.
7712 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7713 point to the symbol `emacs', indicating that the file should
7714 be opened in Emacs."
7715 (append
7716 (delq nil
7717 (mapcar (lambda (x)
7718 (if (not (stringp (car x)))
7720 (if (string-match "\\W" (car x))
7722 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7723 list))
7724 (if add-auto-mode
7725 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7727 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7728 (defun org-file-remote-p (file)
7729 "Test whether FILE specifies a location on a remote system.
7730 Return non-nil if the location is indeed remote.
7732 For example, the filename \"/user@host:/foo\" specifies a location
7733 on the system \"/user@host:\"."
7734 (cond ((fboundp 'file-remote-p)
7735 (file-remote-p file))
7736 ((fboundp 'tramp-handle-file-remote-p)
7737 (tramp-handle-file-remote-p file))
7738 ((and (boundp 'ange-ftp-name-format)
7739 (string-match (car ange-ftp-name-format) file))
7741 (t nil)))
7744 ;;;; Refiling
7746 (defun org-get-org-file ()
7747 "Read a filename, with default directory `org-directory'."
7748 (let ((default (or org-default-notes-file remember-data-file)))
7749 (read-file-name (format "File name [%s]: " default)
7750 (file-name-as-directory org-directory)
7751 default)))
7753 (defun org-notes-order-reversed-p ()
7754 "Check if the current file should receive notes in reversed order."
7755 (cond
7756 ((not org-reverse-note-order) nil)
7757 ((eq t org-reverse-note-order) t)
7758 ((not (listp org-reverse-note-order)) nil)
7759 (t (catch 'exit
7760 (let ((all org-reverse-note-order)
7761 entry)
7762 (while (setq entry (pop all))
7763 (if (string-match (car entry) buffer-file-name)
7764 (throw 'exit (cdr entry))))
7765 nil)))))
7767 (defvar org-refile-target-table nil
7768 "The list of refile targets, created by `org-refile'.")
7770 (defvar org-agenda-new-buffers nil
7771 "Buffers created to visit agenda files.")
7773 (defun org-get-refile-targets (&optional default-buffer)
7774 "Produce a table with refile targets."
7775 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7776 targets txt re files f desc descre fast-path-p level)
7777 (message "Getting targets...")
7778 (with-current-buffer (or default-buffer (current-buffer))
7779 (while (setq entry (pop entries))
7780 (setq files (car entry) desc (cdr entry))
7781 (setq fast-path-p nil)
7782 (cond
7783 ((null files) (setq files (list (current-buffer))))
7784 ((eq files 'org-agenda-files)
7785 (setq files (org-agenda-files 'unrestricted)))
7786 ((and (symbolp files) (fboundp files))
7787 (setq files (funcall files)))
7788 ((and (symbolp files) (boundp files))
7789 (setq files (symbol-value files))))
7790 (if (stringp files) (setq files (list files)))
7791 (cond
7792 ((eq (car desc) :tag)
7793 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7794 ((eq (car desc) :todo)
7795 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7796 ((eq (car desc) :regexp)
7797 (setq descre (cdr desc)))
7798 ((eq (car desc) :level)
7799 (setq descre (concat "^\\*\\{" (number-to-string
7800 (if org-odd-levels-only
7801 (1- (* 2 (cdr desc)))
7802 (cdr desc)))
7803 "\\}[ \t]")))
7804 ((eq (car desc) :maxlevel)
7805 (setq fast-path-p t)
7806 (setq descre (concat "^\\*\\{1," (number-to-string
7807 (if org-odd-levels-only
7808 (1- (* 2 (cdr desc)))
7809 (cdr desc)))
7810 "\\}[ \t]")))
7811 (t (error "Bad refiling target description %s" desc)))
7812 (while (setq f (pop files))
7813 (save-excursion
7814 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7815 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7816 (setq f (expand-file-name f))
7817 (save-excursion
7818 (save-restriction
7819 (widen)
7820 (goto-char (point-min))
7821 (while (re-search-forward descre nil t)
7822 (goto-char (point-at-bol))
7823 (when (looking-at org-complex-heading-regexp)
7824 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7825 txt (org-link-display-format (match-string 4))
7826 re (concat "^" (regexp-quote
7827 (buffer-substring (match-beginning 1)
7828 (match-end 4)))))
7829 (if (match-end 5) (setq re (concat re "[ \t]+"
7830 (regexp-quote
7831 (match-string 5)))))
7832 (setq re (concat re "[ \t]*$"))
7833 (when org-refile-use-outline-path
7834 (setq txt (mapconcat 'org-protect-slash
7835 (append
7836 (if (eq org-refile-use-outline-path 'file)
7837 (list (file-name-nondirectory
7838 (buffer-file-name (buffer-base-buffer))))
7839 (if (eq org-refile-use-outline-path 'full-file-path)
7840 (list (buffer-file-name (buffer-base-buffer)))))
7841 (org-get-outline-path fast-path-p level txt)
7842 (list txt))
7843 "/")))
7844 (push (list txt f re (point)) targets))
7845 (goto-char (point-at-eol))))))))
7846 (message "Getting targets...done")
7847 (nreverse targets))))
7849 (defun org-protect-slash (s)
7850 (while (string-match "/" s)
7851 (setq s (replace-match "\\" t t s)))
7854 (defvar org-olpa (make-vector 20 nil))
7856 (defun org-get-outline-path (&optional fastp level heading)
7857 "Return the outline path to the current entry, as a list."
7858 (if fastp
7859 (progn
7860 (if (> level 19)
7861 (error "Outline path failure, more than 19 levels."))
7862 (loop for i from level upto 19 do
7863 (aset org-olpa i nil))
7864 (prog1
7865 (delq nil (append org-olpa nil))
7866 (aset org-olpa level heading)))
7867 (let (rtn)
7868 (save-excursion
7869 (while (org-up-heading-safe)
7870 (when (looking-at org-complex-heading-regexp)
7871 (push (org-match-string-no-properties 4) rtn)))
7872 rtn))))
7874 (defvar org-refile-history nil
7875 "History for refiling operations.")
7877 (defun org-refile (&optional goto default-buffer)
7878 "Move the entry at point to another heading.
7879 The list of target headings is compiled using the information in
7880 `org-refile-targets', which see. This list is created before each use
7881 and will therefore always be up-to-date.
7883 At the target location, the entry is filed as a subitem of the target heading.
7884 Depending on `org-reverse-note-order', the new subitem will either be the
7885 first or the last subitem.
7887 If there is an active region, all entries in that region will be moved.
7888 However, the region must fulfil the requirement that the first heading
7889 is the first one sets the top-level of the moved text - at most siblings
7890 below it are allowed.
7892 With prefix arg GOTO, the command will only visit the target location,
7893 not actually move anything.
7894 With a double prefix `C-u C-u', go to the location where the last refiling
7895 operation has put the subtree."
7896 (interactive "P")
7897 (let* ((cbuf (current-buffer))
7898 (regionp (org-region-active-p))
7899 (region-start (and regionp (region-beginning)))
7900 (region-end (and regionp (region-end)))
7901 (region-length (and regionp (- region-end region-start)))
7902 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7903 pos it nbuf file re level reversed)
7904 (when regionp (goto-char region-start)
7905 (unless (org-kill-is-subtree-p
7906 (buffer-substring region-start region-end))
7907 (error "The region is not a (sequence of) subtree(s)")))
7908 (if (equal goto '(16))
7909 (org-refile-goto-last-stored)
7910 (when (setq it (org-refile-get-location
7911 (if goto "Goto: " "Refile to: ") default-buffer))
7912 (setq file (nth 1 it)
7913 re (nth 2 it)
7914 pos (nth 3 it))
7915 (if (and (equal (buffer-file-name) file)
7916 (if regionp
7917 (and (>= pos region-start)
7918 (<= pos region-end))
7919 (and (>= pos (point))
7920 (< pos (save-excursion
7921 (org-end-of-subtree t t))))))
7922 (error "Cannot refile to position inside the tree or region"))
7924 (setq nbuf (or (find-buffer-visiting file)
7925 (find-file-noselect file)))
7926 (if goto
7927 (progn
7928 (switch-to-buffer nbuf)
7929 (goto-char pos)
7930 (org-show-context 'org-goto))
7931 (if regionp
7932 (progn
7933 (kill-new (buffer-substring region-start region-end))
7934 (org-save-markers-in-region region-start region-end))
7935 (org-copy-subtree 1 nil t))
7936 (save-excursion
7937 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7938 (find-file-noselect file))))
7939 (setq reversed (org-notes-order-reversed-p))
7940 (save-excursion
7941 (save-restriction
7942 (widen)
7943 (goto-char pos)
7944 (looking-at outline-regexp)
7945 (setq level (org-get-valid-level (funcall outline-level) 1))
7946 (goto-char
7947 (if reversed
7948 (or (outline-next-heading) (point-max))
7949 (or (save-excursion (outline-get-next-sibling))
7950 (org-end-of-subtree t t)
7951 (point-max))))
7952 (if (not (bolp)) (newline))
7953 (bookmark-set "org-refile-last-stored")
7954 (org-paste-subtree level))))
7955 (if regionp
7956 (delete-region (point) (+ (point) region-length))
7957 (org-cut-subtree))
7958 (setq org-markers-to-move nil)
7959 (message "Refiled to \"%s\"" (car it)))))))
7961 (defun org-refile-goto-last-stored ()
7962 "Go to the location where the last refile was stored."
7963 (interactive)
7964 (bookmark-jump "org-refile-last-stored")
7965 (message "This is the location of the last refile"))
7967 (defun org-refile-get-location (&optional prompt default-buffer)
7968 "Prompt the user for a refile location, using PROMPT."
7969 (let ((org-refile-targets org-refile-targets)
7970 (org-refile-use-outline-path org-refile-use-outline-path))
7971 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7972 (unless org-refile-target-table
7973 (error "No refile targets"))
7974 (let* ((cbuf (current-buffer))
7975 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7976 (cfunc (if (and org-refile-use-outline-path
7977 org-outline-path-complete-in-steps)
7978 'org-olpath-completing-read
7979 'org-ido-completing-read))
7980 (extra (if org-refile-use-outline-path "/" ""))
7981 (filename (and cfn (expand-file-name cfn)))
7982 (tbl (mapcar
7983 (lambda (x)
7984 (if (not (equal filename (nth 1 x)))
7985 (cons (concat (car x) extra " ("
7986 (file-name-nondirectory (nth 1 x)) ")")
7987 (cdr x))
7988 (cons (concat (car x) extra) (cdr x))))
7989 org-refile-target-table))
7990 (completion-ignore-case t))
7991 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7992 tbl)))
7994 (defun org-olpath-completing-read (prompt collection &rest args)
7995 "Read an outline path like a file name."
7996 (let ((thetable collection))
7997 (apply
7998 'org-ido-completing-read prompt
7999 (lambda (string predicate &optional flag)
8000 (let (rtn r f (l (length string)))
8001 (cond
8002 ((eq flag nil)
8003 ;; try completion
8004 (try-completion string thetable))
8005 ((eq flag t)
8006 ;; all-completions
8007 (setq rtn (all-completions string thetable predicate))
8008 (mapcar
8009 (lambda (x)
8010 (setq r (substring x l))
8011 (if (string-match " ([^)]*)$" x)
8012 (setq f (match-string 0 x))
8013 (setq f ""))
8014 (if (string-match "/" r)
8015 (concat string (substring r 0 (match-end 0)) f)
8017 rtn))
8018 ((eq flag 'lambda)
8019 ;; exact match?
8020 (assoc string thetable)))
8022 args)))
8024 ;;;; Dynamic blocks
8026 (defun org-find-dblock (name)
8027 "Find the first dynamic block with name NAME in the buffer.
8028 If not found, stay at current position and return nil."
8029 (let (pos)
8030 (save-excursion
8031 (goto-char (point-min))
8032 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8033 nil t)
8034 (match-beginning 0))))
8035 (if pos (goto-char pos))
8036 pos))
8038 (defconst org-dblock-start-re
8039 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8040 "Matches the startline of a dynamic block, with parameters.")
8042 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8043 "Matches the end of a dynamic block.")
8045 (defun org-create-dblock (plist)
8046 "Create a dynamic block section, with parameters taken from PLIST.
8047 PLIST must contain a :name entry which is used as name of the block."
8048 (unless (bolp) (newline))
8049 (let ((name (plist-get plist :name)))
8050 (insert "#+BEGIN: " name)
8051 (while plist
8052 (if (eq (car plist) :name)
8053 (setq plist (cddr plist))
8054 (insert " " (prin1-to-string (pop plist)))))
8055 (insert "\n\n#+END:\n")
8056 (beginning-of-line -2)))
8058 (defun org-prepare-dblock ()
8059 "Prepare dynamic block for refresh.
8060 This empties the block, puts the cursor at the insert position and returns
8061 the property list including an extra property :name with the block name."
8062 (unless (looking-at org-dblock-start-re)
8063 (error "Not at a dynamic block"))
8064 (let* ((begdel (1+ (match-end 0)))
8065 (name (org-no-properties (match-string 1)))
8066 (params (append (list :name name)
8067 (read (concat "(" (match-string 3) ")")))))
8068 (unless (re-search-forward org-dblock-end-re nil t)
8069 (error "Dynamic block not terminated"))
8070 (setq params
8071 (append params
8072 (list :content (buffer-substring
8073 begdel (match-beginning 0)))))
8074 (delete-region begdel (match-beginning 0))
8075 (goto-char begdel)
8076 (open-line 1)
8077 params))
8079 (defun org-map-dblocks (&optional command)
8080 "Apply COMMAND to all dynamic blocks in the current buffer.
8081 If COMMAND is not given, use `org-update-dblock'."
8082 (let ((cmd (or command 'org-update-dblock))
8083 pos)
8084 (save-excursion
8085 (goto-char (point-min))
8086 (while (re-search-forward org-dblock-start-re nil t)
8087 (goto-char (setq pos (match-beginning 0)))
8088 (condition-case nil
8089 (funcall cmd)
8090 (error (message "Error during update of dynamic block")))
8091 (goto-char pos)
8092 (unless (re-search-forward org-dblock-end-re nil t)
8093 (error "Dynamic block not terminated"))))))
8095 (defun org-dblock-update (&optional arg)
8096 "User command for updating dynamic blocks.
8097 Update the dynamic block at point. With prefix ARG, update all dynamic
8098 blocks in the buffer."
8099 (interactive "P")
8100 (if arg
8101 (org-update-all-dblocks)
8102 (or (looking-at org-dblock-start-re)
8103 (org-beginning-of-dblock))
8104 (org-update-dblock)))
8106 (defun org-update-dblock ()
8107 "Update the dynamic block at point
8108 This means to empty the block, parse for parameters and then call
8109 the correct writing function."
8110 (save-window-excursion
8111 (let* ((pos (point))
8112 (line (org-current-line))
8113 (params (org-prepare-dblock))
8114 (name (plist-get params :name))
8115 (cmd (intern (concat "org-dblock-write:" name))))
8116 (message "Updating dynamic block `%s' at line %d..." name line)
8117 (funcall cmd params)
8118 (message "Updating dynamic block `%s' at line %d...done" name line)
8119 (goto-char pos))))
8121 (defun org-beginning-of-dblock ()
8122 "Find the beginning of the dynamic block at point.
8123 Error if there is no such block at point."
8124 (let ((pos (point))
8125 beg)
8126 (end-of-line 1)
8127 (if (and (re-search-backward org-dblock-start-re nil t)
8128 (setq beg (match-beginning 0))
8129 (re-search-forward org-dblock-end-re nil t)
8130 (> (match-end 0) pos))
8131 (goto-char beg)
8132 (goto-char pos)
8133 (error "Not in a dynamic block"))))
8135 (defun org-update-all-dblocks ()
8136 "Update all dynamic blocks in the buffer.
8137 This function can be used in a hook."
8138 (when (org-mode-p)
8139 (org-map-dblocks 'org-update-dblock)))
8142 ;;;; Completion
8144 (defconst org-additional-option-like-keywords
8145 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8146 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8147 "BEGIN_EXAMPLE" "END_EXAMPLE"
8148 "BEGIN_QUOTE" "END_QUOTE"
8149 "BEGIN_VERSE" "END_VERSE"
8150 "BEGIN_SRC" "END_SRC"
8151 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8153 (defcustom org-structure-template-alist
8155 ("s" "#+begin_src ?\n\n#+end_src"
8156 "<src lang=\"?\">\n\n</src>")
8157 ("e" "#+begin_example\n?\n#+end_example"
8158 "<example>\n?\n</example>")
8159 ("q" "#+begin_quote\n?\n#+end_quote"
8160 "<quote>\n?\n</quote>")
8161 ("v" "#+begin_verse\n?\n#+end_verse"
8162 "<verse>\n?\n/verse>")
8163 ("l" "#+begin_latex\n?\n#+end_latex"
8164 "<literal style=\"latex\">\n?\n</literal>")
8165 ("L" "#+latex: "
8166 "<literal style=\"latex\">?</literal>")
8167 ("h" "#+begin_html\n?\n#+end_html"
8168 "<literal style=\"html\">\n?\n</literal>")
8169 ("H" "#+html: "
8170 "<literal style=\"html\">?</literal>")
8171 ("a" "#+begin_ascii\n?\n#+end_ascii")
8172 ("A" "#+ascii: ")
8173 ("i" "#+include %file ?"
8174 "<include file=%file markup=\"?\">")
8176 "Structure completion elements.
8177 This is a list of abbreviation keys and values. The value gets inserted
8178 it you type @samp{.} followed by the key and then the completion key,
8179 usually `M-TAB'. %file will be replaced by a file name after prompting
8180 for the file using completion.
8181 There are two templates for each key, the first uses the original Org syntax,
8182 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8183 the default when the /org-mtags.el/ module has been loaded. See also the
8184 variable `org-mtags-prefer-muse-templates'.
8185 This is an experimental feature, it is undecided if it is going to stay in."
8186 :group 'org-completion
8187 :type '(repeat
8188 (string :tag "Key")
8189 (string :tag "Template")
8190 (string :tag "Muse Template")))
8192 (defun org-try-structure-completion ()
8193 "Try to complete a structure template before point.
8194 This looks for strings like \"<e\" on an otherwise empty line and
8195 expands them."
8196 (let ((l (buffer-substring (point-at-bol) (point)))
8198 (when (and (looking-at "[ \t]*$")
8199 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8200 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8201 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8202 (match-beginning 1)) a)
8203 t)))
8205 (defun org-complete-expand-structure-template (start cell)
8206 "Expand a structure template."
8207 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8208 (rpl (nth (if musep 2 1) cell)))
8209 (delete-region start (point))
8210 (when (string-match "\\`#\\+" rpl)
8211 (cond
8212 ((bolp))
8213 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8214 (delete-region (point-at-bol) (point)))
8215 (t (newline))))
8216 (setq start (point))
8217 (if (string-match "%file" rpl)
8218 (setq rpl (replace-match
8219 (concat
8220 "\""
8221 (save-match-data
8222 (abbreviate-file-name (read-file-name "Include file: ")))
8223 "\"")
8224 t t rpl)))
8225 (insert rpl)
8226 (if (re-search-backward "\\?" start t) (delete-char 1))))
8229 (defun org-complete (&optional arg)
8230 "Perform completion on word at point.
8231 At the beginning of a headline, this completes TODO keywords as given in
8232 `org-todo-keywords'.
8233 If the current word is preceded by a backslash, completes the TeX symbols
8234 that are supported for HTML support.
8235 If the current word is preceded by \"#+\", completes special words for
8236 setting file options.
8237 In the line after \"#+STARTUP:, complete valid keywords.\"
8238 At all other locations, this simply calls the value of
8239 `org-completion-fallback-command'."
8240 (interactive "P")
8241 (org-without-partial-completion
8242 (catch 'exit
8243 (let* ((a nil)
8244 (end (point))
8245 (beg1 (save-excursion
8246 (skip-chars-backward (org-re "[:alnum:]_@"))
8247 (point)))
8248 (beg (save-excursion
8249 (skip-chars-backward "a-zA-Z0-9_:$")
8250 (point)))
8251 (confirm (lambda (x) (stringp (car x))))
8252 (searchhead (equal (char-before beg) ?*))
8253 (struct
8254 (when (and (member (char-before beg1) '(?. ?<))
8255 (setq a (assoc (buffer-substring beg1 (point))
8256 org-structure-template-alist)))
8257 (org-complete-expand-structure-template (1- beg1) a)
8258 (throw 'exit t)))
8259 (tag (and (equal (char-before beg1) ?:)
8260 (equal (char-after (point-at-bol)) ?*)))
8261 (prop (and (equal (char-before beg1) ?:)
8262 (not (equal (char-after (point-at-bol)) ?*))))
8263 (texp (equal (char-before beg) ?\\))
8264 (link (equal (char-before beg) ?\[))
8265 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8266 beg)
8267 "#+"))
8268 (startup (string-match "^#\\+STARTUP:.*"
8269 (buffer-substring (point-at-bol) (point))))
8270 (completion-ignore-case opt)
8271 (type nil)
8272 (tbl nil)
8273 (table (cond
8274 (opt
8275 (setq type :opt)
8276 (require 'org-exp)
8277 (append
8278 (mapcar
8279 (lambda (x)
8280 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8281 (cons (match-string 2 x) (match-string 1 x)))
8282 (org-split-string (org-get-current-options) "\n"))
8283 (mapcar 'list org-additional-option-like-keywords)))
8284 (startup
8285 (setq type :startup)
8286 org-startup-options)
8287 (link (append org-link-abbrev-alist-local
8288 org-link-abbrev-alist))
8289 (texp
8290 (setq type :tex)
8291 org-html-entities)
8292 ((string-match "\\`\\*+[ \t]+\\'"
8293 (buffer-substring (point-at-bol) beg))
8294 (setq type :todo)
8295 (mapcar 'list org-todo-keywords-1))
8296 (searchhead
8297 (setq type :searchhead)
8298 (save-excursion
8299 (goto-char (point-min))
8300 (while (re-search-forward org-todo-line-regexp nil t)
8301 (push (list
8302 (org-make-org-heading-search-string
8303 (match-string 3) t))
8304 tbl)))
8305 tbl)
8306 (tag (setq type :tag beg beg1)
8307 (or org-tag-alist (org-get-buffer-tags)))
8308 (prop (setq type :prop beg beg1)
8309 (mapcar 'list (org-buffer-property-keys nil t t)))
8310 (t (progn
8311 (call-interactively org-completion-fallback-command)
8312 (throw 'exit nil)))))
8313 (pattern (buffer-substring-no-properties beg end))
8314 (completion (try-completion pattern table confirm)))
8315 (cond ((eq completion t)
8316 (if (not (assoc (upcase pattern) table))
8317 (message "Already complete")
8318 (if (and (equal type :opt)
8319 (not (member (car (assoc (upcase pattern) table))
8320 org-additional-option-like-keywords)))
8321 (insert (substring (cdr (assoc (upcase pattern) table))
8322 (length pattern)))
8323 (if (memq type '(:tag :prop)) (insert ":")))))
8324 ((null completion)
8325 (message "Can't find completion for \"%s\"" pattern)
8326 (ding))
8327 ((not (string= pattern completion))
8328 (delete-region beg end)
8329 (if (string-match " +$" completion)
8330 (setq completion (replace-match "" t t completion)))
8331 (insert completion)
8332 (if (get-buffer-window "*Completions*")
8333 (delete-window (get-buffer-window "*Completions*")))
8334 (if (assoc completion table)
8335 (if (eq type :todo) (insert " ")
8336 (if (memq type '(:tag :prop)) (insert ":"))))
8337 (if (and (equal type :opt) (assoc completion table))
8338 (message "%s" (substitute-command-keys
8339 "Press \\[org-complete] again to insert example settings"))))
8341 (message "Making completion list...")
8342 (let ((list (sort (all-completions pattern table confirm)
8343 'string<)))
8344 (with-output-to-temp-buffer "*Completions*"
8345 (condition-case nil
8346 ;; Protection needed for XEmacs and emacs 21
8347 (display-completion-list list pattern)
8348 (error (display-completion-list list)))))
8349 (message "Making completion list...%s" "done")))))))
8351 ;;;; TODO, DEADLINE, Comments
8353 (defun org-toggle-comment ()
8354 "Change the COMMENT state of an entry."
8355 (interactive)
8356 (save-excursion
8357 (org-back-to-heading)
8358 (let (case-fold-search)
8359 (if (looking-at (concat outline-regexp
8360 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8361 (replace-match "" t t nil 1)
8362 (if (looking-at outline-regexp)
8363 (progn
8364 (goto-char (match-end 0))
8365 (insert org-comment-string " ")))))))
8367 (defvar org-last-todo-state-is-todo nil
8368 "This is non-nil when the last TODO state change led to a TODO state.
8369 If the last change removed the TODO tag or switched to DONE, then
8370 this is nil.")
8372 (defvar org-setting-tags nil) ; dynamically skipped
8374 (defun org-parse-local-options (string var)
8375 "Parse STRING for startup setting relevant for variable VAR."
8376 (let ((rtn (symbol-value var))
8377 e opts)
8378 (save-match-data
8379 (if (or (not string) (not (string-match "\\S-" string)))
8381 (setq opts (delq nil (mapcar (lambda (x)
8382 (setq e (assoc x org-startup-options))
8383 (if (eq (nth 1 e) var) e nil))
8384 (org-split-string string "[ \t]+"))))
8385 (if (not opts)
8387 (setq rtn nil)
8388 (while (setq e (pop opts))
8389 (if (not (nth 3 e))
8390 (setq rtn (nth 2 e))
8391 (if (not (listp rtn)) (setq rtn nil))
8392 (push (nth 2 e) rtn)))
8393 rtn)))))
8395 (defvar org-todo-setup-filter-hook nil
8396 "Hook for functions that pre-filter todo specs.
8398 Each function takes a todo spec and returns either `nil' or the spec
8399 transformed into canonical form." )
8401 (defvar org-todo-get-default-hook nil
8402 "Hook for functions that get a default item for todo.
8404 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8405 `nil' or a string to be used for the todo mark." )
8407 (defvar org-agenda-headline-snapshot-before-repeat)
8408 (defun org-todo (&optional arg)
8409 "Change the TODO state of an item.
8410 The state of an item is given by a keyword at the start of the heading,
8411 like
8412 *** TODO Write paper
8413 *** DONE Call mom
8415 The different keywords are specified in the variable `org-todo-keywords'.
8416 By default the available states are \"TODO\" and \"DONE\".
8417 So for this example: when the item starts with TODO, it is changed to DONE.
8418 When it starts with DONE, the DONE is removed. And when neither TODO nor
8419 DONE are present, add TODO at the beginning of the heading.
8421 With C-u prefix arg, use completion to determine the new state.
8422 With numeric prefix arg, switch to that state.
8423 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8424 With a tripple C-u prefix, circumvent any state blocking.
8426 For calling through lisp, arg is also interpreted in the following way:
8427 'none -> empty state
8428 \"\"(empty string) -> switch to empty state
8429 'done -> switch to DONE
8430 'nextset -> switch to the next set of keywords
8431 'previousset -> switch to the previous set of keywords
8432 \"WAITING\" -> switch to the specified keyword, but only if it
8433 really is a member of `org-todo-keywords'."
8434 (interactive "P")
8435 (if (equal arg '(16)) (setq arg 'nextset))
8436 (let ((org-blocker-hook org-blocker-hook))
8437 (when (equal arg '(64))
8438 (setq arg nil org-blocker-hook nil))
8439 (save-excursion
8440 (catch 'exit
8441 (org-back-to-heading)
8442 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8443 (or (looking-at (concat " +" org-todo-regexp " *"))
8444 (looking-at " *"))
8445 (let* ((match-data (match-data))
8446 (startpos (point-at-bol))
8447 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8448 (org-log-done org-log-done)
8449 (org-log-repeat org-log-repeat)
8450 (org-todo-log-states org-todo-log-states)
8451 (this (match-string 1))
8452 (hl-pos (match-beginning 0))
8453 (head (org-get-todo-sequence-head this))
8454 (ass (assoc head org-todo-kwd-alist))
8455 (interpret (nth 1 ass))
8456 (done-word (nth 3 ass))
8457 (final-done-word (nth 4 ass))
8458 (last-state (or this ""))
8459 (completion-ignore-case t)
8460 (member (member this org-todo-keywords-1))
8461 (tail (cdr member))
8462 (state (cond
8463 ((and org-todo-key-trigger
8464 (or (and (equal arg '(4))
8465 (eq org-use-fast-todo-selection 'prefix))
8466 (and (not arg) org-use-fast-todo-selection
8467 (not (eq org-use-fast-todo-selection
8468 'prefix)))))
8469 ;; Use fast selection
8470 (org-fast-todo-selection))
8471 ((and (equal arg '(4))
8472 (or (not org-use-fast-todo-selection)
8473 (not org-todo-key-trigger)))
8474 ;; Read a state with completion
8475 (org-ido-completing-read
8476 "State: " (mapcar (lambda(x) (list x))
8477 org-todo-keywords-1)
8478 nil t))
8479 ((eq arg 'right)
8480 (if this
8481 (if tail (car tail) nil)
8482 (car org-todo-keywords-1)))
8483 ((eq arg 'left)
8484 (if (equal member org-todo-keywords-1)
8486 (if this
8487 (nth (- (length org-todo-keywords-1)
8488 (length tail) 2)
8489 org-todo-keywords-1)
8490 (org-last org-todo-keywords-1))))
8491 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8492 (setq arg nil))) ; hack to fall back to cycling
8493 (arg
8494 ;; user or caller requests a specific state
8495 (cond
8496 ((equal arg "") nil)
8497 ((eq arg 'none) nil)
8498 ((eq arg 'done) (or done-word (car org-done-keywords)))
8499 ((eq arg 'nextset)
8500 (or (car (cdr (member head org-todo-heads)))
8501 (car org-todo-heads)))
8502 ((eq arg 'previousset)
8503 (let ((org-todo-heads (reverse org-todo-heads)))
8504 (or (car (cdr (member head org-todo-heads)))
8505 (car org-todo-heads))))
8506 ((car (member arg org-todo-keywords-1)))
8507 ((nth (1- (prefix-numeric-value arg))
8508 org-todo-keywords-1))))
8509 ((null member) (or head (car org-todo-keywords-1)))
8510 ((equal this final-done-word) nil) ;; -> make empty
8511 ((null tail) nil) ;; -> first entry
8512 ((memq interpret '(type priority))
8513 (if (eq this-command last-command)
8514 (car tail)
8515 (if (> (length tail) 0)
8516 (or done-word (car org-done-keywords))
8517 nil)))
8519 (car tail))))
8520 (state (or
8521 (run-hook-with-args-until-success
8522 'org-todo-get-default-hook state last-state)
8523 state))
8524 (next (if state (concat " " state " ") " "))
8525 (change-plist (list :type 'todo-state-change :from this :to state
8526 :position startpos))
8527 dolog now-done-p)
8528 (when org-blocker-hook
8529 (setq org-last-todo-state-is-todo
8530 (not (member this org-done-keywords)))
8531 (unless (save-excursion
8532 (save-match-data
8533 (run-hook-with-args-until-failure
8534 'org-blocker-hook change-plist)))
8535 (if (interactive-p)
8536 (error "TODO state change from %s to %s blocked" this state)
8537 ;; fail silently
8538 (message "TODO state change from %s to %s blocked" this state)
8539 (throw 'exit nil))))
8540 (store-match-data match-data)
8541 (replace-match next t t)
8542 (unless (pos-visible-in-window-p hl-pos)
8543 (message "TODO state changed to %s" (org-trim next)))
8544 (unless head
8545 (setq head (org-get-todo-sequence-head state)
8546 ass (assoc head org-todo-kwd-alist)
8547 interpret (nth 1 ass)
8548 done-word (nth 3 ass)
8549 final-done-word (nth 4 ass)))
8550 (when (memq arg '(nextset previousset))
8551 (message "Keyword-Set %d/%d: %s"
8552 (- (length org-todo-sets) -1
8553 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8554 (length org-todo-sets)
8555 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8556 (setq org-last-todo-state-is-todo
8557 (not (member state org-done-keywords)))
8558 (setq now-done-p (and (member state org-done-keywords)
8559 (not (member this org-done-keywords))))
8560 (and logging (org-local-logging logging))
8561 (when (and (or org-todo-log-states org-log-done)
8562 (not (memq arg '(nextset previousset))))
8563 ;; we need to look at recording a time and note
8564 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8565 (nth 2 (assoc this org-todo-log-states))))
8566 (when (and state
8567 (member state org-not-done-keywords)
8568 (not (member this org-not-done-keywords)))
8569 ;; This is now a todo state and was not one before
8570 ;; If there was a CLOSED time stamp, get rid of it.
8571 (org-add-planning-info nil nil 'closed))
8572 (when (and now-done-p org-log-done)
8573 ;; It is now done, and it was not done before
8574 (org-add-planning-info 'closed (org-current-time))
8575 (if (and (not dolog) (eq 'note org-log-done))
8576 (org-add-log-setup 'done state 'findpos 'note)))
8577 (when (and state dolog)
8578 ;; This is a non-nil state, and we need to log it
8579 (org-add-log-setup 'state state 'findpos dolog)))
8580 ;; Fixup tag positioning
8581 (org-todo-trigger-tag-changes state)
8582 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8583 (when org-provide-todo-statistics
8584 (org-update-parent-todo-statistics))
8585 (run-hooks 'org-after-todo-state-change-hook)
8586 (if (and arg (not (member state org-done-keywords)))
8587 (setq head (org-get-todo-sequence-head state)))
8588 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8589 ;; Do we need to trigger a repeat?
8590 (when now-done-p
8591 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8592 ;; This is for the agenda, take a snapshot of the headline.
8593 (save-match-data
8594 (setq org-agenda-headline-snapshot-before-repeat
8595 (org-get-heading))))
8596 (org-auto-repeat-maybe state))
8597 ;; Fixup cursor location if close to the keyword
8598 (if (and (outline-on-heading-p)
8599 (not (bolp))
8600 (save-excursion (beginning-of-line 1)
8601 (looking-at org-todo-line-regexp))
8602 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8603 (progn
8604 (goto-char (or (match-end 2) (match-end 1)))
8605 (just-one-space)))
8606 (when org-trigger-hook
8607 (save-excursion
8608 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8610 (defun org-block-todo-from-children-or-siblings (change-plist)
8611 "Block turning an entry into a TODO, using the hierarchy.
8612 This checks whether the current task should be blocked from state
8613 changes. Such blocking occurs when:
8615 1. The task has children which are not all in a completed state.
8617 2. A task has a parent with the property :ORDERED:, and there
8618 are siblings prior to the current task with incomplete
8619 status."
8620 (catch 'dont-block
8621 ;; If this is not a todo state change, or if this entry is already DONE,
8622 ;; do not block
8623 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8624 (member (plist-get change-plist :from)
8625 (cons 'done org-done-keywords))
8626 (member (plist-get change-plist :to)
8627 (cons 'todo org-not-done-keywords)))
8628 (throw 'dont-block t))
8629 ;; If this task has children, and any are undone, it's blocked
8630 (save-excursion
8631 (org-back-to-heading t)
8632 (let ((this-level (funcall outline-level)))
8633 (outline-next-heading)
8634 (let ((child-level (funcall outline-level)))
8635 (while (and (not (eobp))
8636 (> child-level this-level))
8637 ;; this todo has children, check whether they are all
8638 ;; completed
8639 (if (and (not (org-entry-is-done-p))
8640 (org-entry-is-todo-p))
8641 (throw 'dont-block nil))
8642 (outline-next-heading)
8643 (setq child-level (funcall outline-level))))))
8644 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8645 ;; any previous siblings are undone, it's blocked
8646 (save-excursion
8647 (org-back-to-heading t)
8648 (when (save-excursion
8649 (ignore-errors
8650 (outline-up-heading 1)
8651 (org-entry-get (point) "ORDERED")))
8652 (let* ((this-level (funcall outline-level))
8653 (current-level this-level))
8654 (while (and (not (bobp))
8655 (= current-level this-level))
8656 (outline-previous-heading)
8657 (setq current-level (funcall outline-level))
8658 (if (= current-level this-level)
8659 ;; this todo has children, check whether they are all
8660 ;; completed
8661 (if (and (not (org-entry-is-done-p))
8662 (org-entry-is-todo-p))
8663 (throw 'dont-block nil)))))))
8664 t)) ; don't block
8666 (defun org-toggle-ordered-property ()
8667 "Toggle the ORDERED property of the current entry."
8668 (interactive)
8669 (save-excursion
8670 (org-back-to-heading)
8671 (if (org-entry-get nil "ORDERED")
8672 (progn
8673 (org-delete-property "ORDERED")
8674 (message "Subtasks can be completed in arbitrary order or parallel"))
8675 (org-entry-put nil "ORDERED" "t")
8676 (message "Subtasks must be completed in sequence"))))
8678 (defun org-block-todo-from-checkboxes (change-plist)
8679 "Block turning an entry into a TODO, using checkboxes.
8680 This checks whether the current task should be blocked from state
8681 changes because there are uncheckd boxes in this entry."
8682 (catch 'dont-block
8683 ;; If this is not a todo state change, or if this entry is already DONE,
8684 ;; do not block
8685 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8686 (member (plist-get change-plist :from)
8687 (cons 'done org-done-keywords))
8688 (member (plist-get change-plist :to)
8689 (cons 'todo org-not-done-keywords)))
8690 (throw 'dont-block t))
8691 ;; If this task has checkboxes that are not checked, it's blocked
8692 (save-excursion
8693 (org-back-to-heading t)
8694 (let ((beg (point)) end)
8695 (outline-next-heading)
8696 (setq end (point))
8697 (goto-char beg)
8698 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8699 end t)
8700 (throw 'dont-block nil))))
8701 t)) ; do not block
8703 (defun org-update-parent-todo-statistics ()
8704 "Update any statistics cookie in the parent of the current headline."
8705 (interactive)
8706 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8707 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
8708 (catch 'exit
8709 (save-excursion
8710 (setq level (org-up-heading-safe))
8711 (unless level
8712 (throw 'exit nil))
8713 (while (re-search-forward box-re (point-at-eol) t)
8714 (setq cnt-all 0 cnt-done 0 cookie-present t)
8715 (setq is-percent (match-end 2))
8716 (save-match-data
8717 (unless (outline-next-heading) (throw 'exit nil))
8718 (while (looking-at org-todo-line-regexp)
8719 (setq kwd (match-string 2))
8720 (and kwd (setq cnt-all (1+ cnt-all)))
8721 (and (member kwd org-done-keywords)
8722 (setq cnt-done (1+ cnt-done)))
8723 (condition-case nil
8724 (org-forward-same-level 1)
8725 (error (end-of-line 1)))))
8726 (replace-match
8727 (if is-percent
8728 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8729 (format "[%d/%d]" cnt-done cnt-all))))
8730 (when cookie-present
8731 (run-hook-with-args 'org-after-todo-statistics-hook
8732 cnt-done (- cnt-all cnt-done)))))))
8734 (defvar org-after-todo-statistics-hook nil
8735 "Hook that is called after a TODO statistics cookie has been updated.
8736 Each function is called with two arguments: the number of not-done entries
8737 and the number of done entries.
8739 For example, the following function, when added to this hook, will switch
8740 an entry to DONE when all children are done, and back to TODO when new
8741 entries are set to a TODO status. Note that this hook is only called
8742 when there is a statistics cookie in the headline!
8744 (defun org-summary-todo (n-done n-not-done)
8745 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8746 (let (org-log-done org-log-states) ; turn off logging
8747 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8750 (defun org-todo-trigger-tag-changes (state)
8751 "Apply the changes defined in `org-todo-state-tags-triggers'."
8752 (let ((l org-todo-state-tags-triggers)
8753 changes)
8754 (when (or (not state) (equal state ""))
8755 (setq changes (append changes (cdr (assoc "" l)))))
8756 (when (and (stringp state) (> (length state) 0))
8757 (setq changes (append changes (cdr (assoc state l)))))
8758 (when (member state org-not-done-keywords)
8759 (setq changes (append changes (cdr (assoc 'todo l)))))
8760 (when (member state org-done-keywords)
8761 (setq changes (append changes (cdr (assoc 'done l)))))
8762 (dolist (c changes)
8763 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8765 (defun org-local-logging (value)
8766 "Get logging settings from a property VALUE."
8767 (let* (words w a)
8768 ;; directly set the variables, they are already local.
8769 (setq org-log-done nil
8770 org-log-repeat nil
8771 org-todo-log-states nil)
8772 (setq words (org-split-string value))
8773 (while (setq w (pop words))
8774 (cond
8775 ((setq a (assoc w org-startup-options))
8776 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8777 (set (nth 1 a) (nth 2 a))))
8778 ((setq a (org-extract-log-state-settings w))
8779 (and (member (car a) org-todo-keywords-1)
8780 (push a org-todo-log-states)))))))
8782 (defun org-get-todo-sequence-head (kwd)
8783 "Return the head of the TODO sequence to which KWD belongs.
8784 If KWD is not set, check if there is a text property remembering the
8785 right sequence."
8786 (let (p)
8787 (cond
8788 ((not kwd)
8789 (or (get-text-property (point-at-bol) 'org-todo-head)
8790 (progn
8791 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8792 nil (point-at-eol)))
8793 (get-text-property p 'org-todo-head))))
8794 ((not (member kwd org-todo-keywords-1))
8795 (car org-todo-keywords-1))
8796 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8798 (defun org-fast-todo-selection ()
8799 "Fast TODO keyword selection with single keys.
8800 Returns the new TODO keyword, or nil if no state change should occur."
8801 (let* ((fulltable org-todo-key-alist)
8802 (done-keywords org-done-keywords) ;; needed for the faces.
8803 (maxlen (apply 'max (mapcar
8804 (lambda (x)
8805 (if (stringp (car x)) (string-width (car x)) 0))
8806 fulltable)))
8807 (expert nil)
8808 (fwidth (+ maxlen 3 1 3))
8809 (ncol (/ (- (window-width) 4) fwidth))
8810 tg cnt e c tbl
8811 groups ingroup)
8812 (save-excursion
8813 (save-window-excursion
8814 (if expert
8815 (set-buffer (get-buffer-create " *Org todo*"))
8816 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8817 (erase-buffer)
8818 (org-set-local 'org-done-keywords done-keywords)
8819 (setq tbl fulltable cnt 0)
8820 (while (setq e (pop tbl))
8821 (cond
8822 ((equal e '(:startgroup))
8823 (push '() groups) (setq ingroup t)
8824 (when (not (= cnt 0))
8825 (setq cnt 0)
8826 (insert "\n"))
8827 (insert "{ "))
8828 ((equal e '(:endgroup))
8829 (setq ingroup nil cnt 0)
8830 (insert "}\n"))
8832 (setq tg (car e) c (cdr e))
8833 (if ingroup (push tg (car groups)))
8834 (setq tg (org-add-props tg nil 'face
8835 (org-get-todo-face tg)))
8836 (if (and (= cnt 0) (not ingroup)) (insert " "))
8837 (insert "[" c "] " tg (make-string
8838 (- fwidth 4 (length tg)) ?\ ))
8839 (when (= (setq cnt (1+ cnt)) ncol)
8840 (insert "\n")
8841 (if ingroup (insert " "))
8842 (setq cnt 0)))))
8843 (insert "\n")
8844 (goto-char (point-min))
8845 (if (not expert) (org-fit-window-to-buffer))
8846 (message "[a-z..]:Set [SPC]:clear")
8847 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8848 (cond
8849 ((or (= c ?\C-g)
8850 (and (= c ?q) (not (rassoc c fulltable))))
8851 (setq quit-flag t))
8852 ((= c ?\ ) nil)
8853 ((setq e (rassoc c fulltable) tg (car e))
8855 (t (setq quit-flag t)))))))
8857 (defun org-entry-is-todo-p ()
8858 (member (org-get-todo-state) org-not-done-keywords))
8860 (defun org-entry-is-done-p ()
8861 (member (org-get-todo-state) org-done-keywords))
8863 (defun org-get-todo-state ()
8864 (save-excursion
8865 (org-back-to-heading t)
8866 (and (looking-at org-todo-line-regexp)
8867 (match-end 2)
8868 (match-string 2))))
8870 (defun org-at-date-range-p (&optional inactive-ok)
8871 "Is the cursor inside a date range?"
8872 (interactive)
8873 (save-excursion
8874 (catch 'exit
8875 (let ((pos (point)))
8876 (skip-chars-backward "^[<\r\n")
8877 (skip-chars-backward "<[")
8878 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8879 (>= (match-end 0) pos)
8880 (throw 'exit t))
8881 (skip-chars-backward "^<[\r\n")
8882 (skip-chars-backward "<[")
8883 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8884 (>= (match-end 0) pos)
8885 (throw 'exit t)))
8886 nil)))
8888 (defun org-get-repeat ()
8889 "Check if there is a deadline/schedule with repeater in this entry."
8890 (save-match-data
8891 (save-excursion
8892 (org-back-to-heading t)
8893 (if (re-search-forward
8894 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8895 (match-string 1)))))
8897 (defvar org-last-changed-timestamp)
8898 (defvar org-last-inserted-timestamp)
8899 (defvar org-log-post-message)
8900 (defvar org-log-note-purpose)
8901 (defvar org-log-note-how)
8902 (defvar org-log-note-extra)
8903 (defun org-auto-repeat-maybe (done-word)
8904 "Check if the current headline contains a repeated deadline/schedule.
8905 If yes, set TODO state back to what it was and change the base date
8906 of repeating deadline/scheduled time stamps to new date.
8907 This function is run automatically after each state change to a DONE state."
8908 ;; last-state is dynamically scoped into this function
8909 (let* ((repeat (org-get-repeat))
8910 (aa (assoc last-state org-todo-kwd-alist))
8911 (interpret (nth 1 aa))
8912 (head (nth 2 aa))
8913 (whata '(("d" . day) ("m" . month) ("y" . year)))
8914 (msg "Entry repeats: ")
8915 (org-log-done nil)
8916 (org-todo-log-states nil)
8917 (nshiftmax 10) (nshift 0)
8918 re type n what ts time)
8919 (when repeat
8920 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8921 (org-todo (if (eq interpret 'type) last-state head))
8922 (when org-log-repeat
8923 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8924 (memq 'org-add-log-note post-command-hook))
8925 ;; OK, we are already setup for some record
8926 (if (eq org-log-repeat 'note)
8927 ;; make sure we take a note, not only a time stamp
8928 (setq org-log-note-how 'note))
8929 ;; Set up for taking a record
8930 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8931 'findpos org-log-repeat)))
8932 (org-back-to-heading t)
8933 (org-add-planning-info nil nil 'closed)
8934 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8935 org-deadline-time-regexp "\\)\\|\\("
8936 org-ts-regexp "\\)"))
8937 (while (re-search-forward
8938 re (save-excursion (outline-next-heading) (point)) t)
8939 (setq type (if (match-end 1) org-scheduled-string
8940 (if (match-end 3) org-deadline-string "Plain:"))
8941 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
8942 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8943 (setq n (string-to-number (match-string 2 ts))
8944 what (match-string 3 ts))
8945 (if (equal what "w") (setq n (* n 7) what "d"))
8946 ;; Preparation, see if we need to modify the start date for the change
8947 (when (match-end 1)
8948 (setq time (save-match-data (org-time-string-to-time ts)))
8949 (cond
8950 ((equal (match-string 1 ts) ".")
8951 ;; Shift starting date to today
8952 (org-timestamp-change
8953 (- (time-to-days (current-time)) (time-to-days time))
8954 'day))
8955 ((equal (match-string 1 ts) "+")
8956 (while (or (= nshift 0)
8957 (<= (time-to-days time) (time-to-days (current-time))))
8958 (when (= (incf nshift) nshiftmax)
8959 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8960 (error "Abort")))
8961 (org-timestamp-change n (cdr (assoc what whata)))
8962 (org-at-timestamp-p t)
8963 (setq ts (match-string 1))
8964 (setq time (save-match-data (org-time-string-to-time ts))))
8965 (org-timestamp-change (- n) (cdr (assoc what whata)))
8966 ;; rematch, so that we have everything in place for the real shift
8967 (org-at-timestamp-p t)
8968 (setq ts (match-string 1))
8969 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8970 (org-timestamp-change n (cdr (assoc what whata)))
8971 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8972 (setq org-log-post-message msg)
8973 (message "%s" msg))))
8975 (defun org-show-todo-tree (arg)
8976 "Make a compact tree which shows all headlines marked with TODO.
8977 The tree will show the lines where the regexp matches, and all higher
8978 headlines above the match.
8979 With a \\[universal-argument] prefix, also show the DONE entries.
8980 With a numeric prefix N, construct a sparse tree for the Nth element
8981 of `org-todo-keywords-1'."
8982 (interactive "P")
8983 (let ((case-fold-search nil)
8984 (kwd-re
8985 (cond ((null arg) org-not-done-regexp)
8986 ((equal arg '(4))
8987 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8988 (mapcar 'list org-todo-keywords-1))))
8989 (concat "\\("
8990 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8991 "\\)\\>")))
8992 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8993 (regexp-quote (nth (1- (prefix-numeric-value arg))
8994 org-todo-keywords-1)))
8995 (t (error "Invalid prefix argument: %s" arg)))))
8996 (message "%d TODO entries found"
8997 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8999 (defun org-deadline (&optional remove time)
9000 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9001 With argument REMOVE, remove any deadline from the item.
9002 When TIME is set, it should be an internal time specification, and the
9003 scheduling will use the corresponding date."
9004 (interactive "P")
9005 (if remove
9006 (progn
9007 (org-remove-timestamp-with-keyword org-deadline-string)
9008 (message "Item no longer has a deadline."))
9009 (if (org-get-repeat)
9010 (error "Cannot change deadline on task with repeater, please do that by hand")
9011 (org-add-planning-info 'deadline time 'closed)
9012 (message "Deadline on %s" org-last-inserted-timestamp))))
9014 (defun org-schedule (&optional remove time)
9015 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9016 With argument REMOVE, remove any scheduling date from the item.
9017 When TIME is set, it should be an internal time specification, and the
9018 scheduling will use the corresponding date."
9019 (interactive "P")
9020 (if remove
9021 (progn
9022 (org-remove-timestamp-with-keyword org-scheduled-string)
9023 (message "Item is no longer scheduled."))
9024 (if (org-get-repeat)
9025 (error "Cannot reschedule task with repeater, please do that by hand")
9026 (org-add-planning-info 'scheduled time 'closed)
9027 (message "Scheduled to %s" org-last-inserted-timestamp))))
9029 (defun org-get-scheduled-time (pom &optional inherit)
9030 "Get the scheduled time as a time tuple, of a format suitable
9031 for calling org-schedule with, or if there is no scheduling,
9032 returns nil."
9033 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9034 (when time
9035 (apply 'encode-time (org-parse-time-string time)))))
9037 (defun org-get-deadline-time (pom &optional inherit)
9038 "Get the deadine as a time tuple, of a format suitable for
9039 calling org-deadlin with, or if there is no scheduling, returns
9040 nil."
9041 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9042 (when time
9043 (apply 'encode-time (org-parse-time-string time)))))
9045 (defun org-remove-timestamp-with-keyword (keyword)
9046 "Remove all time stamps with KEYWORD in the current entry."
9047 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9048 beg)
9049 (save-excursion
9050 (org-back-to-heading t)
9051 (setq beg (point))
9052 (org-end-of-subtree t t)
9053 (while (re-search-backward re beg t)
9054 (replace-match "")
9055 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9056 (equal (char-before) ?\ ))
9057 (backward-delete-char 1)
9058 (if (string-match "^[ \t]*$" (buffer-substring
9059 (point-at-bol) (point-at-eol)))
9060 (delete-region (point-at-bol)
9061 (min (point-max) (1+ (point-at-eol))))))))))
9063 (defun org-add-planning-info (what &optional time &rest remove)
9064 "Insert new timestamp with keyword in the line directly after the headline.
9065 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9066 If non is given, the user is prompted for a date.
9067 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9068 be removed."
9069 (interactive)
9070 (let (org-time-was-given org-end-time-was-given ts
9071 end default-time default-input)
9073 (when (and (not time) (memq what '(scheduled deadline)))
9074 ;; Try to get a default date/time from existing timestamp
9075 (save-excursion
9076 (org-back-to-heading t)
9077 (setq end (save-excursion (outline-next-heading) (point)))
9078 (when (re-search-forward (if (eq what 'scheduled)
9079 org-scheduled-time-regexp
9080 org-deadline-time-regexp)
9081 end t)
9082 (setq ts (match-string 1)
9083 default-time
9084 (apply 'encode-time (org-parse-time-string ts))
9085 default-input (and ts (org-get-compact-tod ts))))))
9086 (when what
9087 ;; If necessary, get the time from the user
9088 (setq time (or time (org-read-date nil 'to-time nil nil
9089 default-time default-input))))
9091 (when (and org-insert-labeled-timestamps-at-point
9092 (member what '(scheduled deadline)))
9093 (insert
9094 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9095 (org-insert-time-stamp time org-time-was-given
9096 nil nil nil (list org-end-time-was-given))
9097 (setq what nil))
9098 (save-excursion
9099 (save-restriction
9100 (let (col list elt ts buffer-invisibility-spec)
9101 (org-back-to-heading t)
9102 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9103 (goto-char (match-end 1))
9104 (setq col (current-column))
9105 (goto-char (match-end 0))
9106 (if (eobp) (insert "\n") (forward-char 1))
9107 (if (and (not (looking-at outline-regexp))
9108 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9109 "[^\r\n]*"))
9110 (not (equal (match-string 1) org-clock-string)))
9111 (narrow-to-region (match-beginning 0) (match-end 0))
9112 (insert-before-markers "\n")
9113 (backward-char 1)
9114 (narrow-to-region (point) (point))
9115 (and org-adapt-indentation (org-indent-to-column col)))
9116 ;; Check if we have to remove something.
9117 (setq list (cons what remove))
9118 (while list
9119 (setq elt (pop list))
9120 (goto-char (point-min))
9121 (when (or (and (eq elt 'scheduled)
9122 (re-search-forward org-scheduled-time-regexp nil t))
9123 (and (eq elt 'deadline)
9124 (re-search-forward org-deadline-time-regexp nil t))
9125 (and (eq elt 'closed)
9126 (re-search-forward org-closed-time-regexp nil t)))
9127 (replace-match "")
9128 (if (looking-at "--+<[^>]+>") (replace-match ""))
9129 (if (looking-at " +") (replace-match ""))))
9130 (goto-char (point-max))
9131 (when what
9132 (insert
9133 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9134 (cond ((eq what 'scheduled) org-scheduled-string)
9135 ((eq what 'deadline) org-deadline-string)
9136 ((eq what 'closed) org-closed-string))
9137 " ")
9138 (setq ts (org-insert-time-stamp
9139 time
9140 (or org-time-was-given
9141 (and (eq what 'closed) org-log-done-with-time))
9142 (eq what 'closed)
9143 nil nil (list org-end-time-was-given)))
9144 (end-of-line 1))
9145 (goto-char (point-min))
9146 (widen)
9147 (if (and (looking-at "[ \t]+\n")
9148 (equal (char-before) ?\n))
9149 (delete-region (1- (point)) (point-at-eol)))
9150 ts)))))
9152 (defvar org-log-note-marker (make-marker))
9153 (defvar org-log-note-purpose nil)
9154 (defvar org-log-note-state nil)
9155 (defvar org-log-note-how nil)
9156 (defvar org-log-note-extra nil)
9157 (defvar org-log-note-window-configuration nil)
9158 (defvar org-log-note-return-to (make-marker))
9159 (defvar org-log-post-message nil
9160 "Message to be displayed after a log note has been stored.
9161 The auto-repeater uses this.")
9163 (defun org-add-note ()
9164 "Add a note to the current entry.
9165 This is done in the same way as adding a state change note."
9166 (interactive)
9167 (org-add-log-setup 'note nil 'findpos nil))
9169 (defvar org-property-end-re)
9170 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
9171 "Set up the post command hook to take a note.
9172 If this is about to TODO state change, the new state is expected in STATE.
9173 When FINDPOS is non-nil, find the correct position for the note in
9174 the current entry. If not, assume that it can be inserted at point.
9175 HOW is an indicator what kind of note should be created.
9176 EXTRA is additional text that will be inserted into the notes buffer."
9177 (save-restriction
9178 (save-excursion
9179 (when findpos
9180 (org-back-to-heading t)
9181 (narrow-to-region (point) (save-excursion
9182 (outline-next-heading) (point)))
9183 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9184 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9185 "[^\r\n]*\\)?"))
9186 (goto-char (match-end 0))
9187 (when (and org-log-state-notes-insert-after-drawers
9188 (save-excursion
9189 (forward-line) (looking-at org-drawer-regexp)))
9190 (progn (forward-line)
9191 (while (looking-at org-drawer-regexp)
9192 (goto-char (match-end 0))
9193 (re-search-forward org-property-end-re (point-max) t)
9194 (forward-line))
9195 (forward-line -1)))
9196 (unless org-log-states-order-reversed
9197 (and (= (char-after) ?\n) (forward-char 1))
9198 (org-skip-over-state-notes)
9199 (skip-chars-backward " \t\n\r")))
9200 (move-marker org-log-note-marker (point))
9201 (setq org-log-note-purpose purpose
9202 org-log-note-state state
9203 org-log-note-how how
9204 org-log-note-extra extra)
9205 (add-hook 'post-command-hook 'org-add-log-note 'append))))
9207 (defun org-skip-over-state-notes ()
9208 "Skip past the list of State notes in an entry."
9209 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9210 (while (looking-at "[ \t]*- State")
9211 (condition-case nil
9212 (org-next-item)
9213 (error (org-end-of-item)))))
9215 (defun org-add-log-note (&optional purpose)
9216 "Pop up a window for taking a note, and add this note later at point."
9217 (remove-hook 'post-command-hook 'org-add-log-note)
9218 (setq org-log-note-window-configuration (current-window-configuration))
9219 (delete-other-windows)
9220 (move-marker org-log-note-return-to (point))
9221 (switch-to-buffer (marker-buffer org-log-note-marker))
9222 (goto-char org-log-note-marker)
9223 (org-switch-to-buffer-other-window "*Org Note*")
9224 (erase-buffer)
9225 (if (memq org-log-note-how '(time state))
9226 (let (current-prefix-arg) (org-store-log-note))
9227 (let ((org-inhibit-startup t)) (org-mode))
9228 (insert (format "# Insert note for %s.
9229 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9230 (cond
9231 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9232 ((eq org-log-note-purpose 'done) "closed todo item")
9233 ((eq org-log-note-purpose 'state)
9234 (format "state change to \"%s\"" org-log-note-state))
9235 ((eq org-log-note-purpose 'note)
9236 "this entry")
9237 (t (error "This should not happen")))))
9238 (if org-log-note-extra (insert org-log-note-extra))
9239 (org-set-local 'org-finish-function 'org-store-log-note)))
9241 (defvar org-note-abort nil) ; dynamically scoped
9242 (defun org-store-log-note ()
9243 "Finish taking a log note, and insert it to where it belongs."
9244 (let ((txt (buffer-string))
9245 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9246 lines ind)
9247 (kill-buffer (current-buffer))
9248 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9249 (setq txt (replace-match "" t t txt)))
9250 (if (string-match "\\s-+\\'" txt)
9251 (setq txt (replace-match "" t t txt)))
9252 (setq lines (org-split-string txt "\n"))
9253 (when (and note (string-match "\\S-" note))
9254 (setq note
9255 (org-replace-escapes
9256 note
9257 (list (cons "%u" (user-login-name))
9258 (cons "%U" user-full-name)
9259 (cons "%t" (format-time-string
9260 (org-time-stamp-format 'long 'inactive)
9261 (current-time)))
9262 (cons "%s" (if org-log-note-state
9263 (concat "\"" org-log-note-state "\"")
9264 "")))))
9265 (if lines (setq note (concat note " \\\\")))
9266 (push note lines))
9267 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9268 (when lines
9269 (save-excursion
9270 (set-buffer (marker-buffer org-log-note-marker))
9271 (save-excursion
9272 (goto-char org-log-note-marker)
9273 (move-marker org-log-note-marker nil)
9274 (end-of-line 1)
9275 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9276 (indent-relative nil)
9277 (insert "- " (pop lines))
9278 (org-indent-line-function)
9279 (beginning-of-line 1)
9280 (looking-at "[ \t]*")
9281 (setq ind (concat (match-string 0) " "))
9282 (end-of-line 1)
9283 (while lines (insert "\n" ind (pop lines)))))))
9284 (set-window-configuration org-log-note-window-configuration)
9285 (with-current-buffer (marker-buffer org-log-note-return-to)
9286 (goto-char org-log-note-return-to))
9287 (move-marker org-log-note-return-to nil)
9288 (and org-log-post-message (message "%s" org-log-post-message)))
9290 (defun org-sparse-tree (&optional arg)
9291 "Create a sparse tree, prompt for the details.
9292 This command can create sparse trees. You first need to select the type
9293 of match used to create the tree:
9295 t Show entries with a specific TODO keyword.
9296 T Show entries selected by a tags match.
9297 p Enter a property name and its value (both with completion on existing
9298 names/values) and show entries with that property.
9299 r Show entries matching a regular expression
9300 d Show deadlines due within `org-deadline-warning-days'."
9301 (interactive "P")
9302 (let (ans kwd value)
9303 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9304 (setq ans (read-char-exclusive))
9305 (cond
9306 ((equal ans ?d)
9307 (call-interactively 'org-check-deadlines))
9308 ((equal ans ?b)
9309 (call-interactively 'org-check-before-date))
9310 ((equal ans ?t)
9311 (org-show-todo-tree '(4)))
9312 ((equal ans ?T)
9313 (call-interactively 'org-tags-sparse-tree))
9314 ((member ans '(?p ?P))
9315 (setq kwd (org-ido-completing-read "Property: "
9316 (mapcar 'list (org-buffer-property-keys))))
9317 (setq value (org-ido-completing-read "Value: "
9318 (mapcar 'list (org-property-values kwd))))
9319 (unless (string-match "\\`{.*}\\'" value)
9320 (setq value (concat "\"" value "\"")))
9321 (org-tags-sparse-tree arg (concat kwd "=" value)))
9322 ((member ans '(?r ?R ?/))
9323 (call-interactively 'org-occur))
9324 (t (error "No such sparse tree command \"%c\"" ans)))))
9326 (defvar org-occur-highlights nil
9327 "List of overlays used for occur matches.")
9328 (make-variable-buffer-local 'org-occur-highlights)
9329 (defvar org-occur-parameters nil
9330 "Parameters of the active org-occur calls.
9331 This is a list, each call to org-occur pushes as cons cell,
9332 containing the regular expression and the callback, onto the list.
9333 The list can contain several entries if `org-occur' has been called
9334 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9335 will only contain one set of parameters. When the highlights are
9336 removed (for example with `C-c C-c', or with the next edit (depending
9337 on `org-remove-highlights-with-change'), this variable is emptied
9338 as well.")
9339 (make-variable-buffer-local 'org-occur-parameters)
9341 (defun org-occur (regexp &optional keep-previous callback)
9342 "Make a compact tree which shows all matches of REGEXP.
9343 The tree will show the lines where the regexp matches, and all higher
9344 headlines above the match. It will also show the heading after the match,
9345 to make sure editing the matching entry is easy.
9346 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9347 call to `org-occur' will be kept, to allow stacking of calls to this
9348 command.
9349 If CALLBACK is non-nil, it is a function which is called to confirm
9350 that the match should indeed be shown."
9351 (interactive "sRegexp: \nP")
9352 (unless keep-previous
9353 (org-remove-occur-highlights nil nil t))
9354 (push (cons regexp callback) org-occur-parameters)
9355 (let ((cnt 0))
9356 (save-excursion
9357 (goto-char (point-min))
9358 (if (or (not keep-previous) ; do not want to keep
9359 (not org-occur-highlights)) ; no previous matches
9360 ;; hide everything
9361 (org-overview))
9362 (while (re-search-forward regexp nil t)
9363 (when (or (not callback)
9364 (save-match-data (funcall callback)))
9365 (setq cnt (1+ cnt))
9366 (when org-highlight-sparse-tree-matches
9367 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9368 (org-show-context 'occur-tree))))
9369 (when org-remove-highlights-with-change
9370 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9371 nil 'local))
9372 (unless org-sparse-tree-open-archived-trees
9373 (org-hide-archived-subtrees (point-min) (point-max)))
9374 (run-hooks 'org-occur-hook)
9375 (if (interactive-p)
9376 (message "%d match(es) for regexp %s" cnt regexp))
9377 cnt))
9379 (defun org-show-context (&optional key)
9380 "Make sure point and context and visible.
9381 How much context is shown depends upon the variables
9382 `org-show-hierarchy-above', `org-show-following-heading'. and
9383 `org-show-siblings'."
9384 (let ((heading-p (org-on-heading-p t))
9385 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9386 (following-p (org-get-alist-option org-show-following-heading key))
9387 (entry-p (org-get-alist-option org-show-entry-below key))
9388 (siblings-p (org-get-alist-option org-show-siblings key)))
9389 (catch 'exit
9390 ;; Show heading or entry text
9391 (if (and heading-p (not entry-p))
9392 (org-flag-heading nil) ; only show the heading
9393 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9394 (org-show-hidden-entry))) ; show entire entry
9395 (when following-p
9396 ;; Show next sibling, or heading below text
9397 (save-excursion
9398 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9399 (org-flag-heading nil))))
9400 (when siblings-p (org-show-siblings))
9401 (when hierarchy-p
9402 ;; show all higher headings, possibly with siblings
9403 (save-excursion
9404 (while (and (condition-case nil
9405 (progn (org-up-heading-all 1) t)
9406 (error nil))
9407 (not (bobp)))
9408 (org-flag-heading nil)
9409 (when siblings-p (org-show-siblings))))))))
9411 (defun org-reveal (&optional siblings)
9412 "Show current entry, hierarchy above it, and the following headline.
9413 This can be used to show a consistent set of context around locations
9414 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9415 not t for the search context.
9417 With optional argument SIBLINGS, on each level of the hierarchy all
9418 siblings are shown. This repairs the tree structure to what it would
9419 look like when opened with hierarchical calls to `org-cycle'."
9420 (interactive "P")
9421 (let ((org-show-hierarchy-above t)
9422 (org-show-following-heading t)
9423 (org-show-siblings (if siblings t org-show-siblings)))
9424 (org-show-context nil)))
9426 (defun org-highlight-new-match (beg end)
9427 "Highlight from BEG to END and mark the highlight is an occur headline."
9428 (let ((ov (org-make-overlay beg end)))
9429 (org-overlay-put ov 'face 'secondary-selection)
9430 (push ov org-occur-highlights)))
9432 (defun org-remove-occur-highlights (&optional beg end noremove)
9433 "Remove the occur highlights from the buffer.
9434 BEG and END are ignored. If NOREMOVE is nil, remove this function
9435 from the `before-change-functions' in the current buffer."
9436 (interactive)
9437 (unless org-inhibit-highlight-removal
9438 (mapc 'org-delete-overlay org-occur-highlights)
9439 (setq org-occur-highlights nil)
9440 (setq org-occur-parameters nil)
9441 (unless noremove
9442 (remove-hook 'before-change-functions
9443 'org-remove-occur-highlights 'local))))
9445 ;;;; Priorities
9447 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9448 "Regular expression matching the priority indicator.")
9450 (defvar org-remove-priority-next-time nil)
9452 (defun org-priority-up ()
9453 "Increase the priority of the current item."
9454 (interactive)
9455 (org-priority 'up))
9457 (defun org-priority-down ()
9458 "Decrease the priority of the current item."
9459 (interactive)
9460 (org-priority 'down))
9462 (defun org-priority (&optional action)
9463 "Change the priority of an item by ARG.
9464 ACTION can be `set', `up', `down', or a character."
9465 (interactive)
9466 (setq action (or action 'set))
9467 (let (current new news have remove)
9468 (save-excursion
9469 (org-back-to-heading)
9470 (if (looking-at org-priority-regexp)
9471 (setq current (string-to-char (match-string 2))
9472 have t)
9473 (setq current org-default-priority))
9474 (cond
9475 ((or (eq action 'set)
9476 (if (featurep 'xemacs) (characterp action) (integerp action)))
9477 (if (not (eq action 'set))
9478 (setq new action)
9479 (message "Priority %c-%c, SPC to remove: "
9480 org-highest-priority org-lowest-priority)
9481 (setq new (read-char-exclusive)))
9482 (if (and (= (upcase org-highest-priority) org-highest-priority)
9483 (= (upcase org-lowest-priority) org-lowest-priority))
9484 (setq new (upcase new)))
9485 (cond ((equal new ?\ ) (setq remove t))
9486 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9487 (error "Priority must be between `%c' and `%c'"
9488 org-highest-priority org-lowest-priority))))
9489 ((eq action 'up)
9490 (if (and (not have) (eq last-command this-command))
9491 (setq new org-lowest-priority)
9492 (setq new (if (and org-priority-start-cycle-with-default (not have))
9493 org-default-priority (1- current)))))
9494 ((eq action 'down)
9495 (if (and (not have) (eq last-command this-command))
9496 (setq new org-highest-priority)
9497 (setq new (if (and org-priority-start-cycle-with-default (not have))
9498 org-default-priority (1+ current)))))
9499 (t (error "Invalid action")))
9500 (if (or (< (upcase new) org-highest-priority)
9501 (> (upcase new) org-lowest-priority))
9502 (setq remove t))
9503 (setq news (format "%c" new))
9504 (if have
9505 (if remove
9506 (replace-match "" t t nil 1)
9507 (replace-match news t t nil 2))
9508 (if remove
9509 (error "No priority cookie found in line")
9510 (looking-at org-todo-line-regexp)
9511 (if (match-end 2)
9512 (progn
9513 (goto-char (match-end 2))
9514 (insert " [#" news "]"))
9515 (goto-char (match-beginning 3))
9516 (insert "[#" news "] ")))))
9517 (org-preserve-lc (org-set-tags nil 'align))
9518 (if remove
9519 (message "Priority removed")
9520 (message "Priority of current item set to %s" news))))
9523 (defun org-get-priority (s)
9524 "Find priority cookie and return priority."
9525 (save-match-data
9526 (if (not (string-match org-priority-regexp s))
9527 (* 1000 (- org-lowest-priority org-default-priority))
9528 (* 1000 (- org-lowest-priority
9529 (string-to-char (match-string 2 s)))))))
9531 ;;;; Tags
9533 (defvar org-agenda-archives-mode)
9534 (defun org-scan-tags (action matcher &optional todo-only)
9535 "Scan headline tags with inheritance and produce output ACTION.
9537 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9538 or `agenda' to produce an entry list for an agenda view. It can also be
9539 a Lisp form or a function that should be called at each matched headline, in
9540 this case the return value is a list of all return values from these calls.
9542 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9543 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9544 only lines with a TODO keyword are included in the output."
9545 (require 'org-agenda)
9546 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9547 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9548 (org-re
9549 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9550 (props (list 'face 'default
9551 'done-face 'org-done
9552 'undone-face 'default
9553 'mouse-face 'highlight
9554 'org-not-done-regexp org-not-done-regexp
9555 'org-todo-regexp org-todo-regexp
9556 'keymap org-agenda-keymap
9557 'help-echo
9558 (format "mouse-2 or RET jump to org file %s"
9559 (abbreviate-file-name
9560 (or (buffer-file-name (buffer-base-buffer))
9561 (buffer-name (buffer-base-buffer)))))))
9562 (case-fold-search nil)
9563 lspos tags tags-list
9564 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9565 (llast 0) rtn rtn1 level category i txt
9566 todo marker entry priority)
9567 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9568 (setq action (list 'lambda nil action)))
9569 (save-excursion
9570 (goto-char (point-min))
9571 (when (eq action 'sparse-tree)
9572 (org-overview)
9573 (org-remove-occur-highlights))
9574 (while (re-search-forward re nil t)
9575 (catch :skip
9576 (setq todo (if (match-end 1) (match-string 2))
9577 tags (if (match-end 4) (match-string 4)))
9578 (goto-char (setq lspos (1+ (match-beginning 0))))
9579 (setq level (org-reduced-level (funcall outline-level))
9580 category (org-get-category))
9581 (setq i llast llast level)
9582 ;; remove tag lists from same and sublevels
9583 (while (>= i level)
9584 (when (setq entry (assoc i tags-alist))
9585 (setq tags-alist (delete entry tags-alist)))
9586 (setq i (1- i)))
9587 ;; add the next tags
9588 (when tags
9589 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9590 tags-alist
9591 (cons (cons level tags) tags-alist)))
9592 ;; compile tags for current headline
9593 (setq tags-list
9594 (if org-use-tag-inheritance
9595 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9596 tags))
9597 (when org-use-tag-inheritance
9598 (setcdr (car tags-alist)
9599 (mapcar (lambda (x)
9600 (setq x (copy-sequence x))
9601 (org-add-prop-inherited x))
9602 (cdar tags-alist))))
9603 (when (and tags org-use-tag-inheritance
9604 (not (eq t org-use-tag-inheritance)))
9605 ;; selective inheritance, remove uninherited ones
9606 (setcdr (car tags-alist)
9607 (org-remove-uniherited-tags (cdar tags-alist))))
9608 (when (and (or (not todo-only)
9609 (and (member todo org-not-done-keywords)
9610 (or (not org-agenda-tags-todo-honor-ignore-options)
9611 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9612 (let ((case-fold-search t)) (eval matcher))
9614 (not (member org-archive-tag tags-list))
9615 ;; we have an archive tag, should we use this anyway?
9616 (or (not org-agenda-skip-archived-trees)
9617 (and (eq action 'agenda) org-agenda-archives-mode))))
9618 (unless (eq action 'sparse-tree) (org-agenda-skip))
9620 ;; select this headline
9622 (cond
9623 ((eq action 'sparse-tree)
9624 (and org-highlight-sparse-tree-matches
9625 (org-get-heading) (match-end 0)
9626 (org-highlight-new-match
9627 (match-beginning 0) (match-beginning 1)))
9628 (org-show-context 'tags-tree))
9629 ((eq action 'agenda)
9630 (setq txt (org-format-agenda-item
9632 (concat
9633 (if org-tags-match-list-sublevels
9634 (make-string (1- level) ?.) "")
9635 (org-get-heading))
9636 category (org-get-tags-at))
9637 priority (org-get-priority txt))
9638 (goto-char lspos)
9639 (setq marker (org-agenda-new-marker))
9640 (org-add-props txt props
9641 'org-marker marker 'org-hd-marker marker 'org-category category
9642 'priority priority 'type "tagsmatch")
9643 (push txt rtn))
9644 ((functionp action)
9645 (save-excursion
9646 (setq rtn1 (funcall action))
9647 (push rtn1 rtn))
9648 (goto-char (point-at-eol)))
9649 (t (error "Invalid action")))
9651 ;; if we are to skip sublevels, jump to end of subtree
9652 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9653 (when (and (eq action 'sparse-tree)
9654 (not org-sparse-tree-open-archived-trees))
9655 (org-hide-archived-subtrees (point-min) (point-max)))
9656 (nreverse rtn)))
9658 (defun org-remove-uniherited-tags (tags)
9659 "Remove all tags that are not inherited from the list TAGS."
9660 (cond
9661 ((eq org-use-tag-inheritance t)
9662 (if org-tags-exclude-from-inheritance
9663 (org-delete-all org-tags-exclude-from-inheritance tags)
9664 tags))
9665 ((not org-use-tag-inheritance) nil)
9666 ((stringp org-use-tag-inheritance)
9667 (delq nil (mapcar
9668 (lambda (x)
9669 (if (and (string-match org-use-tag-inheritance x)
9670 (not (member x org-tags-exclude-from-inheritance)))
9671 x nil))
9672 tags)))
9673 ((listp org-use-tag-inheritance)
9674 (delq nil (mapcar
9675 (lambda (x)
9676 (if (member x org-use-tag-inheritance) x nil))
9677 tags)))))
9679 (defvar todo-only) ;; dynamically scoped
9681 (defun org-tags-sparse-tree (&optional todo-only match)
9682 "Create a sparse tree according to tags string MATCH.
9683 MATCH can contain positive and negative selection of tags, like
9684 \"+WORK+URGENT-WITHBOSS\".
9685 If optional argument TODO-ONLY is non-nil, only select lines that are
9686 also TODO lines."
9687 (interactive "P")
9688 (org-prepare-agenda-buffers (list (current-buffer)))
9689 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9691 (defvar org-cached-props nil)
9692 (defun org-cached-entry-get (pom property)
9693 (if (or (eq t org-use-property-inheritance)
9694 (and (stringp org-use-property-inheritance)
9695 (string-match org-use-property-inheritance property))
9696 (and (listp org-use-property-inheritance)
9697 (member property org-use-property-inheritance)))
9698 ;; Caching is not possible, check it directly
9699 (org-entry-get pom property 'inherit)
9700 ;; Get all properties, so that we can do complicated checks easily
9701 (cdr (assoc property (or org-cached-props
9702 (setq org-cached-props
9703 (org-entry-properties pom)))))))
9705 (defun org-global-tags-completion-table (&optional files)
9706 "Return the list of all tags in all agenda buffer/files."
9707 (save-excursion
9708 (org-uniquify
9709 (delq nil
9710 (apply 'append
9711 (mapcar
9712 (lambda (file)
9713 (set-buffer (find-file-noselect file))
9714 (append (org-get-buffer-tags)
9715 (mapcar (lambda (x) (if (stringp (car-safe x))
9716 (list (car-safe x)) nil))
9717 org-tag-alist)))
9718 (if (and files (car files))
9719 files
9720 (org-agenda-files))))))))
9722 (defun org-make-tags-matcher (match)
9723 "Create the TAGS//TODO matcher form for the selection string MATCH."
9724 ;; todo-only is scoped dynamically into this function, and the function
9725 ;; may change it if the matcher asks for it.
9726 (unless match
9727 ;; Get a new match request, with completion
9728 (let ((org-last-tags-completion-table
9729 (org-global-tags-completion-table)))
9730 (setq match (org-completing-read
9731 "Match: " 'org-tags-completion-function nil nil nil
9732 'org-tags-history))))
9734 ;; Parse the string and create a lisp form
9735 (let ((match0 match)
9736 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9737 minus tag mm
9738 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9739 orterms term orlist re-p str-p level-p level-op time-p
9740 prop-p pn pv po cat-p gv rest)
9741 (if (string-match "/+" match)
9742 ;; match contains also a todo-matching request
9743 (progn
9744 (setq tagsmatch (substring match 0 (match-beginning 0))
9745 todomatch (substring match (match-end 0)))
9746 (if (string-match "^!" todomatch)
9747 (setq todo-only t todomatch (substring todomatch 1)))
9748 (if (string-match "^\\s-*$" todomatch)
9749 (setq todomatch nil)))
9750 ;; only matching tags
9751 (setq tagsmatch match todomatch nil))
9753 ;; Make the tags matcher
9754 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9755 (setq tagsmatcher t)
9756 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9757 (while (setq term (pop orterms))
9758 (while (and (equal (substring term -1) "\\") orterms)
9759 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9760 (while (string-match re term)
9761 (setq rest (substring term (match-end 0))
9762 minus (and (match-end 1)
9763 (equal (match-string 1 term) "-"))
9764 tag (match-string 2 term)
9765 re-p (equal (string-to-char tag) ?{)
9766 level-p (match-end 4)
9767 prop-p (match-end 5)
9768 mm (cond
9769 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9770 (level-p
9771 (setq level-op (org-op-to-function (match-string 3 term)))
9772 `(,level-op level ,(string-to-number
9773 (match-string 4 term))))
9774 (prop-p
9775 (setq pn (match-string 5 term)
9776 po (match-string 6 term)
9777 pv (match-string 7 term)
9778 cat-p (equal pn "CATEGORY")
9779 re-p (equal (string-to-char pv) ?{)
9780 str-p (equal (string-to-char pv) ?\")
9781 time-p (save-match-data
9782 (string-match "^\"[[<].*[]>]\"$" pv))
9783 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9784 (if time-p (setq pv (org-matcher-time pv)))
9785 (setq po (org-op-to-function po (if time-p 'time str-p)))
9786 (cond
9787 ((equal pn "CATEGORY")
9788 (setq gv '(get-text-property (point) 'org-category)))
9789 ((equal pn "TODO")
9790 (setq gv 'todo))
9792 (setq gv `(org-cached-entry-get nil ,pn))))
9793 (if re-p
9794 (if (eq po 'org<>)
9795 `(not (string-match ,pv (or ,gv "")))
9796 `(string-match ,pv (or ,gv "")))
9797 (if str-p
9798 `(,po (or ,gv "") ,pv)
9799 `(,po (string-to-number (or ,gv ""))
9800 ,(string-to-number pv) ))))
9801 (t `(member ,(downcase tag) tags-list)))
9802 mm (if minus (list 'not mm) mm)
9803 term rest)
9804 (push mm tagsmatcher))
9805 (push (if (> (length tagsmatcher) 1)
9806 (cons 'and tagsmatcher)
9807 (car tagsmatcher))
9808 orlist)
9809 (setq tagsmatcher nil))
9810 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9811 (setq tagsmatcher
9812 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9813 ;; Make the todo matcher
9814 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9815 (setq todomatcher t)
9816 (setq orterms (org-split-string todomatch "|") orlist nil)
9817 (while (setq term (pop orterms))
9818 (while (string-match re term)
9819 (setq minus (and (match-end 1)
9820 (equal (match-string 1 term) "-"))
9821 kwd (match-string 2 term)
9822 re-p (equal (string-to-char kwd) ?{)
9823 term (substring term (match-end 0))
9824 mm (if re-p
9825 `(string-match ,(substring kwd 1 -1) todo)
9826 (list 'equal 'todo kwd))
9827 mm (if minus (list 'not mm) mm))
9828 (push mm todomatcher))
9829 (push (if (> (length todomatcher) 1)
9830 (cons 'and todomatcher)
9831 (car todomatcher))
9832 orlist)
9833 (setq todomatcher nil))
9834 (setq todomatcher (if (> (length orlist) 1)
9835 (cons 'or orlist) (car orlist))))
9837 ;; Return the string and lisp forms of the matcher
9838 (setq matcher (if todomatcher
9839 (list 'and tagsmatcher todomatcher)
9840 tagsmatcher))
9841 (cons match0 matcher)))
9843 (defun org-op-to-function (op &optional stringp)
9844 "Turn an operator into the appropriate function."
9845 (setq op
9846 (cond
9847 ((equal op "<" ) '(< string< org-time<))
9848 ((equal op ">" ) '(> org-string> org-time>))
9849 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9850 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9851 ((member op '("=" "==")) '(= string= org-time=))
9852 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9853 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9855 (defun org<> (a b) (not (= a b)))
9856 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9857 (defun org-string>= (a b) (not (string< a b)))
9858 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9859 (defun org-string<> (a b) (not (string= a b)))
9860 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9861 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9862 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9863 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9864 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9865 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9866 (defun org-2ft (s)
9867 "Convert S to a floating point time.
9868 If S is already a number, just return it. If it is a string, parse
9869 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9870 (cond
9871 ((numberp s) s)
9872 ((stringp s)
9873 (condition-case nil
9874 (float-time (apply 'encode-time (org-parse-time-string s)))
9875 (error 0.)))
9876 (t 0.)))
9878 (defun org-time-today ()
9879 "Time in seconds today at 0:00.
9880 Returns the float number of seconds since the beginning of the
9881 epoch to the beginning of today (00:00)."
9882 (float-time (apply 'encode-time
9883 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9885 (defun org-matcher-time (s)
9886 "Interpret a time comparison value."
9887 (save-match-data
9888 (cond
9889 ((string= s "<now>") (float-time))
9890 ((string= s "<today>") (org-time-today))
9891 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9892 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9893 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9894 (+ (org-time-today)
9895 (* (string-to-number (match-string 1 s))
9896 (cdr (assoc (match-string 2 s)
9897 '(("d" . 86400.0) ("w" . 604800.0)
9898 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9899 (t (org-2ft s)))))
9901 (defun org-match-any-p (re list)
9902 "Does re match any element of list?"
9903 (setq list (mapcar (lambda (x) (string-match re x)) list))
9904 (delq nil list))
9906 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9907 (defvar org-tags-overlay (org-make-overlay 1 1))
9908 (org-detach-overlay org-tags-overlay)
9910 (defun org-get-local-tags-at (&optional pos)
9911 "Get a list of tags defined in the current headline."
9912 (org-get-tags-at pos 'local))
9914 (defun org-get-local-tags ()
9915 "Get a list of tags defined in the current headline."
9916 (org-get-tags-at nil 'local))
9918 (defun org-get-tags-at (&optional pos local)
9919 "Get a list of all headline tags applicable at POS.
9920 POS defaults to point. If tags are inherited, the list contains
9921 the targets in the same sequence as the headlines appear, i.e.
9922 the tags of the current headline come last.
9923 When LOCAL is non-nil, only return tags from the current headline,
9924 ignore inherited ones."
9925 (interactive)
9926 (let (tags ltags lastpos parent)
9927 (save-excursion
9928 (save-restriction
9929 (widen)
9930 (goto-char (or pos (point)))
9931 (save-match-data
9932 (catch 'done
9933 (condition-case nil
9934 (progn
9935 (org-back-to-heading t)
9936 (while (not (equal lastpos (point)))
9937 (setq lastpos (point))
9938 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9939 (setq ltags (org-split-string
9940 (org-match-string-no-properties 1) ":"))
9941 (when parent
9942 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9943 (setq tags (append
9944 (if parent
9945 (org-remove-uniherited-tags ltags)
9946 ltags)
9947 tags)))
9948 (or org-use-tag-inheritance (throw 'done t))
9949 (if local (throw 'done t))
9950 (org-up-heading-all 1)
9951 (setq parent t)))
9952 (error nil)))))
9953 (append (org-remove-uniherited-tags org-file-tags) tags))))
9955 (defun org-add-prop-inherited (s)
9956 (add-text-properties 0 (length s) '(inherited t) s)
9959 (defun org-toggle-tag (tag &optional onoff)
9960 "Toggle the tag TAG for the current line.
9961 If ONOFF is `on' or `off', don't toggle but set to this state."
9962 (let (res current)
9963 (save-excursion
9964 (org-back-to-heading t)
9965 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9966 (point-at-eol) t)
9967 (progn
9968 (setq current (match-string 1))
9969 (replace-match ""))
9970 (setq current ""))
9971 (setq current (nreverse (org-split-string current ":")))
9972 (cond
9973 ((eq onoff 'on)
9974 (setq res t)
9975 (or (member tag current) (push tag current)))
9976 ((eq onoff 'off)
9977 (or (not (member tag current)) (setq current (delete tag current))))
9978 (t (if (member tag current)
9979 (setq current (delete tag current))
9980 (setq res t)
9981 (push tag current))))
9982 (end-of-line 1)
9983 (if current
9984 (progn
9985 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9986 (org-set-tags nil t))
9987 (delete-horizontal-space))
9988 (run-hooks 'org-after-tags-change-hook))
9989 res))
9991 (defun org-align-tags-here (to-col)
9992 ;; Assumes that this is a headline
9993 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9994 (beginning-of-line 1)
9995 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9996 (< pos (match-beginning 2)))
9997 (progn
9998 (setq tags-l (- (match-end 2) (match-beginning 2)))
9999 (goto-char (match-beginning 1))
10000 (insert " ")
10001 (delete-region (point) (1+ (match-beginning 2)))
10002 (setq ncol (max (1+ (current-column))
10003 (1+ col)
10004 (if (> to-col 0)
10005 to-col
10006 (- (abs to-col) tags-l))))
10007 (setq p (point))
10008 (insert (make-string (- ncol (current-column)) ?\ ))
10009 (setq ncol (current-column))
10010 (when indent-tabs-mode (tabify p (point-at-eol)))
10011 (org-move-to-column (min ncol col) t))
10012 (goto-char pos))))
10014 (defun org-set-tags-command (&optional arg just-align)
10015 "Call the set-tags command for the current entry."
10016 (interactive "P")
10017 (if (org-on-heading-p)
10018 (org-set-tags arg just-align)
10019 (save-excursion
10020 (org-back-to-heading t)
10021 (org-set-tags arg just-align))))
10023 (defun org-set-tags (&optional arg just-align)
10024 "Set the tags for the current headline.
10025 With prefix ARG, realign all tags in headings in the current buffer."
10026 (interactive "P")
10027 (let* ((re (concat "^" outline-regexp))
10028 (current (org-get-tags-string))
10029 (col (current-column))
10030 (org-setting-tags t)
10031 table current-tags inherited-tags ; computed below when needed
10032 tags p0 c0 c1 rpl)
10033 (if arg
10034 (save-excursion
10035 (goto-char (point-min))
10036 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10037 (while (re-search-forward re nil t)
10038 (org-set-tags nil t)
10039 (end-of-line 1)))
10040 (message "All tags realigned to column %d" org-tags-column))
10041 (if just-align
10042 (setq tags current)
10043 ;; Get a new set of tags from the user
10044 (save-excursion
10045 (setq table (or org-tag-alist (org-get-buffer-tags))
10046 org-last-tags-completion-table table
10047 current-tags (org-split-string current ":")
10048 inherited-tags (nreverse
10049 (nthcdr (length current-tags)
10050 (nreverse (org-get-tags-at))))
10051 tags
10052 (if (or (eq t org-use-fast-tag-selection)
10053 (and org-use-fast-tag-selection
10054 (delq nil (mapcar 'cdr table))))
10055 (org-fast-tag-selection
10056 current-tags inherited-tags table
10057 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10058 (let ((org-add-colon-after-tag-completion t))
10059 (org-trim
10060 (org-without-partial-completion
10061 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10062 nil nil current 'org-tags-history)))))))
10063 (while (string-match "[-+&]+" tags)
10064 ;; No boolean logic, just a list
10065 (setq tags (replace-match ":" t t tags))))
10067 (if (string-match "\\`[\t ]*\\'" tags)
10068 (setq tags "")
10069 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10070 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10072 ;; Insert new tags at the correct column
10073 (beginning-of-line 1)
10074 (cond
10075 ((and (equal current "") (equal tags "")))
10076 ((re-search-forward
10077 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10078 (point-at-eol) t)
10079 (if (equal tags "")
10080 (setq rpl "")
10081 (goto-char (match-beginning 0))
10082 (setq c0 (current-column) p0 (point)
10083 c1 (max (1+ c0) (if (> org-tags-column 0)
10084 org-tags-column
10085 (- (- org-tags-column) (length tags))))
10086 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10087 (replace-match rpl t t)
10088 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10089 tags)
10090 (t (error "Tags alignment failed")))
10091 (org-move-to-column col)
10092 (unless just-align
10093 (run-hooks 'org-after-tags-change-hook)))))
10095 (defun org-change-tag-in-region (beg end tag off)
10096 "Add or remove TAG for each entry in the region.
10097 This works in the agenda, and also in an org-mode buffer."
10098 (interactive
10099 (list (region-beginning) (region-end)
10100 (let ((org-last-tags-completion-table
10101 (if (org-mode-p)
10102 (org-get-buffer-tags)
10103 (org-global-tags-completion-table))))
10104 (org-ido-completing-read
10105 "Tag: " 'org-tags-completion-function nil nil nil
10106 'org-tags-history))
10107 (progn
10108 (message "[s]et or [r]emove? ")
10109 (equal (read-char-exclusive) ?r))))
10110 (if (fboundp 'deactivate-mark) (deactivate-mark))
10111 (let ((agendap (equal major-mode 'org-agenda-mode))
10112 l1 l2 m buf pos newhead (cnt 0))
10113 (goto-char end)
10114 (setq l2 (1- (org-current-line)))
10115 (goto-char beg)
10116 (setq l1 (org-current-line))
10117 (loop for l from l1 to l2 do
10118 (goto-line l)
10119 (setq m (get-text-property (point) 'org-hd-marker))
10120 (when (or (and (org-mode-p) (org-on-heading-p))
10121 (and agendap m))
10122 (setq buf (if agendap (marker-buffer m) (current-buffer))
10123 pos (if agendap m (point)))
10124 (with-current-buffer buf
10125 (save-excursion
10126 (save-restriction
10127 (goto-char pos)
10128 (setq cnt (1+ cnt))
10129 (org-toggle-tag tag (if off 'off 'on))
10130 (setq newhead (org-get-heading)))))
10131 (and agendap (org-agenda-change-all-lines newhead m))))
10132 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10134 (defun org-tags-completion-function (string predicate &optional flag)
10135 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10136 (confirm (lambda (x) (stringp (car x)))))
10137 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10138 (setq s1 (match-string 1 string)
10139 s2 (match-string 2 string))
10140 (setq s1 "" s2 string))
10141 (cond
10142 ((eq flag nil)
10143 ;; try completion
10144 (setq rtn (try-completion s2 ctable confirm))
10145 (if (stringp rtn)
10146 (setq rtn
10147 (concat s1 s2 (substring rtn (length s2))
10148 (if (and org-add-colon-after-tag-completion
10149 (assoc rtn ctable))
10150 ":" ""))))
10151 rtn)
10152 ((eq flag t)
10153 ;; all-completions
10154 (all-completions s2 ctable confirm)
10156 ((eq flag 'lambda)
10157 ;; exact match?
10158 (assoc s2 ctable)))
10161 (defun org-fast-tag-insert (kwd tags face &optional end)
10162 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10163 (insert (format "%-12s" (concat kwd ":"))
10164 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10165 (or end "")))
10167 (defun org-fast-tag-show-exit (flag)
10168 (save-excursion
10169 (goto-line 3)
10170 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10171 (replace-match ""))
10172 (when flag
10173 (end-of-line 1)
10174 (org-move-to-column (- (window-width) 19) t)
10175 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10177 (defun org-set-current-tags-overlay (current prefix)
10178 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10179 (if (featurep 'xemacs)
10180 (org-overlay-display org-tags-overlay (concat prefix s)
10181 'secondary-selection)
10182 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10183 (org-overlay-display org-tags-overlay (concat prefix s)))))
10185 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10186 "Fast tag selection with single keys.
10187 CURRENT is the current list of tags in the headline, INHERITED is the
10188 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10189 possibly with grouping information. TODO-TABLE is a similar table with
10190 TODO keywords, should these have keys assigned to them.
10191 If the keys are nil, a-z are automatically assigned.
10192 Returns the new tags string, or nil to not change the current settings."
10193 (let* ((fulltable (append table todo-table))
10194 (maxlen (apply 'max (mapcar
10195 (lambda (x)
10196 (if (stringp (car x)) (string-width (car x)) 0))
10197 fulltable)))
10198 (buf (current-buffer))
10199 (expert (eq org-fast-tag-selection-single-key 'expert))
10200 (buffer-tags nil)
10201 (fwidth (+ maxlen 3 1 3))
10202 (ncol (/ (- (window-width) 4) fwidth))
10203 (i-face 'org-done)
10204 (c-face 'org-todo)
10205 tg cnt e c char c1 c2 ntable tbl rtn
10206 ov-start ov-end ov-prefix
10207 (exit-after-next org-fast-tag-selection-single-key)
10208 (done-keywords org-done-keywords)
10209 groups ingroup)
10210 (save-excursion
10211 (beginning-of-line 1)
10212 (if (looking-at
10213 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10214 (setq ov-start (match-beginning 1)
10215 ov-end (match-end 1)
10216 ov-prefix "")
10217 (setq ov-start (1- (point-at-eol))
10218 ov-end (1+ ov-start))
10219 (skip-chars-forward "^\n\r")
10220 (setq ov-prefix
10221 (concat
10222 (buffer-substring (1- (point)) (point))
10223 (if (> (current-column) org-tags-column)
10225 (make-string (- org-tags-column (current-column)) ?\ ))))))
10226 (org-move-overlay org-tags-overlay ov-start ov-end)
10227 (save-window-excursion
10228 (if expert
10229 (set-buffer (get-buffer-create " *Org tags*"))
10230 (delete-other-windows)
10231 (split-window-vertically)
10232 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10233 (erase-buffer)
10234 (org-set-local 'org-done-keywords done-keywords)
10235 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10236 (org-fast-tag-insert "Current" current c-face "\n\n")
10237 (org-fast-tag-show-exit exit-after-next)
10238 (org-set-current-tags-overlay current ov-prefix)
10239 (setq tbl fulltable char ?a cnt 0)
10240 (while (setq e (pop tbl))
10241 (cond
10242 ((equal e '(:startgroup))
10243 (push '() groups) (setq ingroup t)
10244 (when (not (= cnt 0))
10245 (setq cnt 0)
10246 (insert "\n"))
10247 (insert "{ "))
10248 ((equal e '(:endgroup))
10249 (setq ingroup nil cnt 0)
10250 (insert "}\n"))
10252 (setq tg (car e) c2 nil)
10253 (if (cdr e)
10254 (setq c (cdr e))
10255 ;; automatically assign a character.
10256 (setq c1 (string-to-char
10257 (downcase (substring
10258 tg (if (= (string-to-char tg) ?@) 1 0)))))
10259 (if (or (rassoc c1 ntable) (rassoc c1 table))
10260 (while (or (rassoc char ntable) (rassoc char table))
10261 (setq char (1+ char)))
10262 (setq c2 c1))
10263 (setq c (or c2 char)))
10264 (if ingroup (push tg (car groups)))
10265 (setq tg (org-add-props tg nil 'face
10266 (cond
10267 ((not (assoc tg table))
10268 (org-get-todo-face tg))
10269 ((member tg current) c-face)
10270 ((member tg inherited) i-face)
10271 (t nil))))
10272 (if (and (= cnt 0) (not ingroup)) (insert " "))
10273 (insert "[" c "] " tg (make-string
10274 (- fwidth 4 (length tg)) ?\ ))
10275 (push (cons tg c) ntable)
10276 (when (= (setq cnt (1+ cnt)) ncol)
10277 (insert "\n")
10278 (if ingroup (insert " "))
10279 (setq cnt 0)))))
10280 (setq ntable (nreverse ntable))
10281 (insert "\n")
10282 (goto-char (point-min))
10283 (if (not expert) (org-fit-window-to-buffer))
10284 (setq rtn
10285 (catch 'exit
10286 (while t
10287 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10288 (if groups " [!] no groups" " [!]groups")
10289 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10290 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10291 (cond
10292 ((= c ?\r) (throw 'exit t))
10293 ((= c ?!)
10294 (setq groups (not groups))
10295 (goto-char (point-min))
10296 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10297 ((= c ?\C-c)
10298 (if (not expert)
10299 (org-fast-tag-show-exit
10300 (setq exit-after-next (not exit-after-next)))
10301 (setq expert nil)
10302 (delete-other-windows)
10303 (split-window-vertically)
10304 (org-switch-to-buffer-other-window " *Org tags*")
10305 (org-fit-window-to-buffer)))
10306 ((or (= c ?\C-g)
10307 (and (= c ?q) (not (rassoc c ntable))))
10308 (org-detach-overlay org-tags-overlay)
10309 (setq quit-flag t))
10310 ((= c ?\ )
10311 (setq current nil)
10312 (if exit-after-next (setq exit-after-next 'now)))
10313 ((= c ?\t)
10314 (condition-case nil
10315 (setq tg (org-ido-completing-read
10316 "Tag: "
10317 (or buffer-tags
10318 (with-current-buffer buf
10319 (org-get-buffer-tags)))))
10320 (quit (setq tg "")))
10321 (when (string-match "\\S-" tg)
10322 (add-to-list 'buffer-tags (list tg))
10323 (if (member tg current)
10324 (setq current (delete tg current))
10325 (push tg current)))
10326 (if exit-after-next (setq exit-after-next 'now)))
10327 ((setq e (rassoc c todo-table) tg (car e))
10328 (with-current-buffer buf
10329 (save-excursion (org-todo tg)))
10330 (if exit-after-next (setq exit-after-next 'now)))
10331 ((setq e (rassoc c ntable) tg (car e))
10332 (if (member tg current)
10333 (setq current (delete tg current))
10334 (loop for g in groups do
10335 (if (member tg g)
10336 (mapc (lambda (x)
10337 (setq current (delete x current)))
10338 g)))
10339 (push tg current))
10340 (if exit-after-next (setq exit-after-next 'now))))
10342 ;; Create a sorted list
10343 (setq current
10344 (sort current
10345 (lambda (a b)
10346 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10347 (if (eq exit-after-next 'now) (throw 'exit t))
10348 (goto-char (point-min))
10349 (beginning-of-line 2)
10350 (delete-region (point) (point-at-eol))
10351 (org-fast-tag-insert "Current" current c-face)
10352 (org-set-current-tags-overlay current ov-prefix)
10353 (while (re-search-forward
10354 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10355 (setq tg (match-string 1))
10356 (add-text-properties
10357 (match-beginning 1) (match-end 1)
10358 (list 'face
10359 (cond
10360 ((member tg current) c-face)
10361 ((member tg inherited) i-face)
10362 (t (get-text-property (match-beginning 1) 'face))))))
10363 (goto-char (point-min)))))
10364 (org-detach-overlay org-tags-overlay)
10365 (if rtn
10366 (mapconcat 'identity current ":")
10367 nil))))
10369 (defun org-get-tags-string ()
10370 "Get the TAGS string in the current headline."
10371 (unless (org-on-heading-p t)
10372 (error "Not on a heading"))
10373 (save-excursion
10374 (beginning-of-line 1)
10375 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10376 (org-match-string-no-properties 1)
10377 "")))
10379 (defun org-get-tags ()
10380 "Get the list of tags specified in the current headline."
10381 (org-split-string (org-get-tags-string) ":"))
10383 (defun org-get-buffer-tags ()
10384 "Get a table of all tags used in the buffer, for completion."
10385 (let (tags)
10386 (save-excursion
10387 (goto-char (point-min))
10388 (while (re-search-forward
10389 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10390 (when (equal (char-after (point-at-bol 0)) ?*)
10391 (mapc (lambda (x) (add-to-list 'tags x))
10392 (org-split-string (org-match-string-no-properties 1) ":")))))
10393 (mapcar 'list tags)))
10395 ;;;; The mapping API
10397 ;;;###autoload
10398 (defun org-map-entries (func &optional match scope &rest skip)
10399 "Call FUNC at each headline selected by MATCH in SCOPE.
10401 FUNC is a function or a lisp form. The function will be called without
10402 arguments, with the cursor positioned at the beginning of the headline.
10403 The return values of all calls to the function will be collected and
10404 returned as a list.
10406 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10407 Only headlines that are matched by this query will be considered during
10408 the iteration. When MATCH is nil or t, all headlines will be
10409 visited by the iteration.
10411 SCOPE determines the scope of this command. It can be any of:
10413 nil The current buffer, respecting the restriction if any
10414 tree The subtree started with the entry at point
10415 file The current buffer, without restriction
10416 file-with-archives
10417 The current buffer, and any archives associated with it
10418 agenda All agenda files
10419 agenda-with-archives
10420 All agenda files with any archive files associated with them
10421 \(file1 file2 ...)
10422 If this is a list, all files in the list will be scanned
10424 The remaining args are treated as settings for the skipping facilities of
10425 the scanner. The following items can be given here:
10427 archive skip trees with the archive tag.
10428 comment skip trees with the COMMENT keyword
10429 function or Emacs Lisp form:
10430 will be used as value for `org-agenda-skip-function', so whenever
10431 the the function returns t, FUNC will not be called for that
10432 entry and search will continue from the point where the
10433 function leaves it."
10434 (let* ((org-agenda-archives-mode nil) ; just to make sure
10435 (org-agenda-skip-archived-trees (memq 'archive skip))
10436 (org-agenda-skip-comment-trees (memq 'comment skip))
10437 (org-agenda-skip-function
10438 (car (org-delete-all '(comment archive) skip)))
10439 (org-tags-match-list-sublevels t)
10440 matcher file res
10441 org-todo-keywords-for-agenda
10442 org-done-keywords-for-agenda
10443 org-todo-keyword-alist-for-agenda
10444 org-tag-alist-for-agenda)
10446 (cond
10447 ((eq match t) (setq matcher t))
10448 ((eq match nil) (setq matcher t))
10449 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10451 (save-excursion
10452 (save-restriction
10453 (when (eq scope 'tree)
10454 (org-back-to-heading t)
10455 (org-narrow-to-subtree)
10456 (setq scope nil))
10458 (if (not scope)
10459 (progn
10460 (org-prepare-agenda-buffers
10461 (list (buffer-file-name (current-buffer))))
10462 (setq res (org-scan-tags func matcher)))
10463 ;; Get the right scope
10464 (cond
10465 ((and scope (listp scope) (symbolp (car scope)))
10466 (setq scope (eval scope)))
10467 ((eq scope 'agenda)
10468 (setq scope (org-agenda-files t)))
10469 ((eq scope 'agenda-with-archives)
10470 (setq scope (org-agenda-files t))
10471 (setq scope (org-add-archive-files scope)))
10472 ((eq scope 'file)
10473 (setq scope (list (buffer-file-name))))
10474 ((eq scope 'file-with-archives)
10475 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10476 (org-prepare-agenda-buffers scope)
10477 (while (setq file (pop scope))
10478 (with-current-buffer (org-find-base-buffer-visiting file)
10479 (save-excursion
10480 (save-restriction
10481 (widen)
10482 (goto-char (point-min))
10483 (setq res (append res (org-scan-tags func matcher))))))))))
10484 res))
10486 ;;;; Properties
10488 ;;; Setting and retrieving properties
10490 (defconst org-special-properties
10491 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10492 "TIMESTAMP" "TIMESTAMP_IA")
10493 "The special properties valid in Org-mode.
10495 These are properties that are not defined in the property drawer,
10496 but in some other way.")
10498 (defconst org-default-properties
10499 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10500 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10501 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10502 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10503 "Some properties that are used by Org-mode for various purposes.
10504 Being in this list makes sure that they are offered for completion.")
10506 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10507 "Regular expression matching the first line of a property drawer.")
10509 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10510 "Regular expression matching the first line of a property drawer.")
10512 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10513 "Regular expression matching the first line of a property drawer.")
10515 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10516 "Regular expression matching the first line of a property drawer.")
10518 (defconst org-property-drawer-re
10519 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10520 org-property-end-re "\\)\n?")
10521 "Matches an entire property drawer.")
10523 (defconst org-clock-drawer-re
10524 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10525 org-property-end-re "\\)\n?")
10526 "Matches an entire clock drawer.")
10528 (defun org-property-action ()
10529 "Do an action on properties."
10530 (interactive)
10531 (let (c)
10532 (org-at-property-p)
10533 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10534 (setq c (read-char-exclusive))
10535 (cond
10536 ((equal c ?s)
10537 (call-interactively 'org-set-property))
10538 ((equal c ?d)
10539 (call-interactively 'org-delete-property))
10540 ((equal c ?D)
10541 (call-interactively 'org-delete-property-globally))
10542 ((equal c ?c)
10543 (call-interactively 'org-compute-property-at-point))
10544 (t (error "No such property action %c" c)))))
10546 (defun org-at-property-p ()
10547 "Is the cursor in a property line?"
10548 ;; FIXME: Does not check if we are actually in the drawer.
10549 ;; FIXME: also returns true on any drawers.....
10550 ;; This is used by C-c C-c for property action.
10551 (save-excursion
10552 (beginning-of-line 1)
10553 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10555 (defun org-get-property-block (&optional beg end force)
10556 "Return the (beg . end) range of the body of the property drawer.
10557 BEG and END can be beginning and end of subtree, if not given
10558 they will be found.
10559 If the drawer does not exist and FORCE is non-nil, create the drawer."
10560 (catch 'exit
10561 (save-excursion
10562 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10563 (end (or end (progn (outline-next-heading) (point)))))
10564 (goto-char beg)
10565 (if (re-search-forward org-property-start-re end t)
10566 (setq beg (1+ (match-end 0)))
10567 (if force
10568 (save-excursion
10569 (org-insert-property-drawer)
10570 (setq end (progn (outline-next-heading) (point))))
10571 (throw 'exit nil))
10572 (goto-char beg)
10573 (if (re-search-forward org-property-start-re end t)
10574 (setq beg (1+ (match-end 0)))))
10575 (if (re-search-forward org-property-end-re end t)
10576 (setq end (match-beginning 0))
10577 (or force (throw 'exit nil))
10578 (goto-char beg)
10579 (setq end beg)
10580 (org-indent-line-function)
10581 (insert ":END:\n"))
10582 (cons beg end)))))
10584 (defun org-entry-properties (&optional pom which)
10585 "Get all properties of the entry at point-or-marker POM.
10586 This includes the TODO keyword, the tags, time strings for deadline,
10587 scheduled, and clocking, and any additional properties defined in the
10588 entry. The return value is an alist, keys may occur multiple times
10589 if the property key was used several times.
10590 POM may also be nil, in which case the current entry is used.
10591 If WHICH is nil or `all', get all properties. If WHICH is
10592 `special' or `standard', only get that subclass."
10593 (setq which (or which 'all))
10594 (org-with-point-at pom
10595 (let ((clockstr (substring org-clock-string 0 -1))
10596 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10597 beg end range props sum-props key value string clocksum)
10598 (save-excursion
10599 (when (condition-case nil
10600 (and (org-mode-p) (org-back-to-heading t))
10601 (error nil))
10602 (setq beg (point))
10603 (setq sum-props (get-text-property (point) 'org-summaries))
10604 (setq clocksum (get-text-property (point) :org-clock-minutes))
10605 (outline-next-heading)
10606 (setq end (point))
10607 (when (memq which '(all special))
10608 ;; Get the special properties, like TODO and tags
10609 (goto-char beg)
10610 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10611 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10612 (when (looking-at org-priority-regexp)
10613 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10614 (when (and (setq value (org-get-tags-string))
10615 (string-match "\\S-" value))
10616 (push (cons "TAGS" value) props))
10617 (when (setq value (org-get-tags-at))
10618 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10619 props))
10620 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10621 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10622 string (if (equal key clockstr)
10623 (org-no-properties
10624 (org-trim
10625 (buffer-substring
10626 (match-beginning 3) (goto-char (point-at-eol)))))
10627 (substring (org-match-string-no-properties 3) 1 -1)))
10628 (unless key
10629 (if (= (char-after (match-beginning 3)) ?\[)
10630 (setq key "TIMESTAMP_IA")
10631 (setq key "TIMESTAMP")))
10632 (when (or (equal key clockstr) (not (assoc key props)))
10633 (push (cons key string) props)))
10637 (when (memq which '(all standard))
10638 ;; Get the standard properties, like :PORP: ...
10639 (setq range (org-get-property-block beg end))
10640 (when range
10641 (goto-char (car range))
10642 (while (re-search-forward
10643 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10644 (cdr range) t)
10645 (setq key (org-match-string-no-properties 1)
10646 value (org-trim (or (org-match-string-no-properties 2) "")))
10647 (unless (member key excluded)
10648 (push (cons key (or value "")) props)))))
10649 (if clocksum
10650 (push (cons "CLOCKSUM"
10651 (org-columns-number-to-string (/ (float clocksum) 60.)
10652 'add_times))
10653 props))
10654 (unless (assoc "CATEGORY" props)
10655 (setq value (or (org-get-category)
10656 (progn (org-refresh-category-properties)
10657 (org-get-category))))
10658 (push (cons "CATEGORY" value) props))
10659 (append sum-props (nreverse props)))))))
10661 (defun org-entry-get (pom property &optional inherit)
10662 "Get value of PROPERTY for entry at point-or-marker POM.
10663 If INHERIT is non-nil and the entry does not have the property,
10664 then also check higher levels of the hierarchy.
10665 If INHERIT is the symbol `selective', use inheritance only if the setting
10666 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10667 If the property is present but empty, the return value is the empty string.
10668 If the property is not present at all, nil is returned."
10669 (org-with-point-at pom
10670 (if (and inherit (if (eq inherit 'selective)
10671 (org-property-inherit-p property)
10673 (org-entry-get-with-inheritance property)
10674 (if (member property org-special-properties)
10675 ;; We need a special property. Use brute force, get all properties.
10676 (cdr (assoc property (org-entry-properties nil 'special)))
10677 (let ((range (org-get-property-block)))
10678 (if (and range
10679 (goto-char (car range))
10680 (re-search-forward
10681 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10682 (cdr range) t))
10683 ;; Found the property, return it.
10684 (if (match-end 1)
10685 (org-match-string-no-properties 1)
10686 "")))))))
10688 (defun org-property-or-variable-value (var &optional inherit)
10689 "Check if there is a property fixing the value of VAR.
10690 If yes, return this value. If not, return the current value of the variable."
10691 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10692 (if (and prop (stringp prop) (string-match "\\S-" prop))
10693 (read prop)
10694 (symbol-value var))))
10696 (defun org-entry-delete (pom property)
10697 "Delete the property PROPERTY from entry at point-or-marker POM."
10698 (org-with-point-at pom
10699 (if (member property org-special-properties)
10700 nil ; cannot delete these properties.
10701 (let ((range (org-get-property-block)))
10702 (if (and range
10703 (goto-char (car range))
10704 (re-search-forward
10705 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10706 (cdr range) t))
10707 (progn
10708 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10710 nil)))))
10712 ;; Multi-values properties are properties that contain multiple values
10713 ;; These values are assumed to be single words, separated by whitespace.
10714 (defun org-entry-add-to-multivalued-property (pom property value)
10715 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10716 (let* ((old (org-entry-get pom property))
10717 (values (and old (org-split-string old "[ \t]"))))
10718 (setq value (org-entry-protect-space value))
10719 (unless (member value values)
10720 (setq values (cons value values))
10721 (org-entry-put pom property
10722 (mapconcat 'identity values " ")))))
10724 (defun org-entry-remove-from-multivalued-property (pom property value)
10725 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10726 (let* ((old (org-entry-get pom property))
10727 (values (and old (org-split-string old "[ \t]"))))
10728 (setq value (org-entry-protect-space value))
10729 (when (member value values)
10730 (setq values (delete value values))
10731 (org-entry-put pom property
10732 (mapconcat 'identity values " ")))))
10734 (defun org-entry-member-in-multivalued-property (pom property value)
10735 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10736 (let* ((old (org-entry-get pom property))
10737 (values (and old (org-split-string old "[ \t]"))))
10738 (setq value (org-entry-protect-space value))
10739 (member value values)))
10741 (defun org-entry-get-multivalued-property (pom property)
10742 "Return a list of values in a multivalued property."
10743 (let* ((value (org-entry-get pom property))
10744 (values (and value (org-split-string value "[ \t]"))))
10745 (mapcar 'org-entry-restore-space values)))
10747 (defun org-entry-put-multivalued-property (pom property &rest values)
10748 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10749 VALUES should be a list of strings. Spaces will be protected."
10750 (org-entry-put pom property
10751 (mapconcat 'org-entry-protect-space values " "))
10752 (let* ((value (org-entry-get pom property))
10753 (values (and value (org-split-string value "[ \t]"))))
10754 (mapcar 'org-entry-restore-space values)))
10756 (defun org-entry-protect-space (s)
10757 "Protect spaces and newline in string S."
10758 (while (string-match " " s)
10759 (setq s (replace-match "%20" t t s)))
10760 (while (string-match "\n" s)
10761 (setq s (replace-match "%0A" t t s)))
10764 (defun org-entry-restore-space (s)
10765 "Restore spaces and newline in string S."
10766 (while (string-match "%20" s)
10767 (setq s (replace-match " " t t s)))
10768 (while (string-match "%0A" s)
10769 (setq s (replace-match "\n" t t s)))
10772 (defvar org-entry-property-inherited-from (make-marker)
10773 "Marker pointing to the entry from where a property was inherited.
10774 Each call to `org-entry-get-with-inheritance' will set this marker to the
10775 location of the entry where the inheritance search matched. If there was
10776 no match, the marker will point nowhere.
10777 Note that also `org-entry-get' calls this function, if the INHERIT flag
10778 is set.")
10780 (defun org-entry-get-with-inheritance (property)
10781 "Get entry property, and search higher levels if not present."
10782 (move-marker org-entry-property-inherited-from nil)
10783 (let (tmp)
10784 (save-excursion
10785 (save-restriction
10786 (widen)
10787 (catch 'ex
10788 (while t
10789 (when (setq tmp (org-entry-get nil property))
10790 (org-back-to-heading t)
10791 (move-marker org-entry-property-inherited-from (point))
10792 (throw 'ex tmp))
10793 (or (org-up-heading-safe) (throw 'ex nil)))))
10794 (or tmp
10795 (cdr (assoc property org-file-properties))
10796 (cdr (assoc property org-global-properties))
10797 (cdr (assoc property org-global-properties-fixed))))))
10799 (defun org-entry-put (pom property value)
10800 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10801 (org-with-point-at pom
10802 (org-back-to-heading t)
10803 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10804 range)
10805 (cond
10806 ((equal property "TODO")
10807 (when (and (stringp value) (string-match "\\S-" value)
10808 (not (member value org-todo-keywords-1)))
10809 (error "\"%s\" is not a valid TODO state" value))
10810 (if (or (not value)
10811 (not (string-match "\\S-" value)))
10812 (setq value 'none))
10813 (org-todo value)
10814 (org-set-tags nil 'align))
10815 ((equal property "PRIORITY")
10816 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10817 (string-to-char value) ?\ ))
10818 (org-set-tags nil 'align))
10819 ((equal property "SCHEDULED")
10820 (if (re-search-forward org-scheduled-time-regexp end t)
10821 (cond
10822 ((eq value 'earlier) (org-timestamp-change -1 'day))
10823 ((eq value 'later) (org-timestamp-change 1 'day))
10824 (t (call-interactively 'org-schedule)))
10825 (call-interactively 'org-schedule)))
10826 ((equal property "DEADLINE")
10827 (if (re-search-forward org-deadline-time-regexp end t)
10828 (cond
10829 ((eq value 'earlier) (org-timestamp-change -1 'day))
10830 ((eq value 'later) (org-timestamp-change 1 'day))
10831 (t (call-interactively 'org-deadline)))
10832 (call-interactively 'org-deadline)))
10833 ((member property org-special-properties)
10834 (error "The %s property can not yet be set with `org-entry-put'"
10835 property))
10836 (t ; a non-special property
10837 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10838 (setq range (org-get-property-block beg end 'force))
10839 (goto-char (car range))
10840 (if (re-search-forward
10841 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10842 (progn
10843 (delete-region (match-beginning 1) (match-end 1))
10844 (goto-char (match-beginning 1)))
10845 (goto-char (cdr range))
10846 (insert "\n")
10847 (backward-char 1)
10848 (org-indent-line-function)
10849 (insert ":" property ":"))
10850 (and value (insert " " value))
10851 (org-indent-line-function)))))))
10853 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10854 "Get all property keys in the current buffer.
10855 With INCLUDE-SPECIALS, also list the special properties that reflect things
10856 like tags and TODO state.
10857 With INCLUDE-DEFAULTS, also include properties that has special meaning
10858 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10859 With INCLUDE-COLUMNS, also include property names given in COLUMN
10860 formats in the current buffer."
10861 (let (rtn range cfmt s p)
10862 (save-excursion
10863 (save-restriction
10864 (widen)
10865 (goto-char (point-min))
10866 (while (re-search-forward org-property-start-re nil t)
10867 (setq range (org-get-property-block))
10868 (goto-char (car range))
10869 (while (re-search-forward
10870 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10871 (cdr range) t)
10872 (add-to-list 'rtn (org-match-string-no-properties 1)))
10873 (outline-next-heading))))
10875 (when include-specials
10876 (setq rtn (append org-special-properties rtn)))
10878 (when include-defaults
10879 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10881 (when include-columns
10882 (save-excursion
10883 (save-restriction
10884 (widen)
10885 (goto-char (point-min))
10886 (while (re-search-forward
10887 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10888 nil t)
10889 (setq cfmt (match-string 2) s 0)
10890 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10891 cfmt s)
10892 (setq s (match-end 0)
10893 p (match-string 1 cfmt))
10894 (unless (or (equal p "ITEM")
10895 (member p org-special-properties))
10896 (add-to-list 'rtn (match-string 1 cfmt))))))))
10898 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10900 (defun org-property-values (key)
10901 "Return a list of all values of property KEY."
10902 (save-excursion
10903 (save-restriction
10904 (widen)
10905 (goto-char (point-min))
10906 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10907 values)
10908 (while (re-search-forward re nil t)
10909 (add-to-list 'values (org-trim (match-string 1))))
10910 (delete "" values)))))
10912 (defun org-insert-property-drawer ()
10913 "Insert a property drawer into the current entry."
10914 (interactive)
10915 (org-back-to-heading t)
10916 (looking-at outline-regexp)
10917 (let ((indent (- (match-end 0)(match-beginning 0)))
10918 (beg (point))
10919 (re (concat "^[ \t]*" org-keyword-time-regexp))
10920 end hiddenp)
10921 (outline-next-heading)
10922 (setq end (point))
10923 (goto-char beg)
10924 (while (re-search-forward re end t))
10925 (setq hiddenp (org-invisible-p))
10926 (end-of-line 1)
10927 (and (equal (char-after) ?\n) (forward-char 1))
10928 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10929 (beginning-of-line 2))
10930 (org-skip-over-state-notes)
10931 (skip-chars-backward " \t\n\r")
10932 (if (eq (char-before) ?*) (forward-char 1))
10933 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10934 (beginning-of-line 0)
10935 (org-indent-to-column indent)
10936 (beginning-of-line 2)
10937 (org-indent-to-column indent)
10938 (beginning-of-line 0)
10939 (if hiddenp
10940 (save-excursion
10941 (org-back-to-heading t)
10942 (hide-entry))
10943 (org-flag-drawer t))))
10945 (defun org-set-property (property value)
10946 "In the current entry, set PROPERTY to VALUE.
10947 When called interactively, this will prompt for a property name, offering
10948 completion on existing and default properties. And then it will prompt
10949 for a value, offering completion either on allowed values (via an inherited
10950 xxx_ALL property) or on existing values in other instances of this property
10951 in the current file."
10952 (interactive
10953 (let* ((completion-ignore-case t)
10954 (keys (org-buffer-property-keys nil t t))
10955 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10956 (prop (if (member prop0 keys)
10957 prop0
10958 (or (cdr (assoc (downcase prop0)
10959 (mapcar (lambda (x) (cons (downcase x) x))
10960 keys)))
10961 prop0)))
10962 (cur (org-entry-get nil prop))
10963 (allowed (org-property-get-allowed-values nil prop 'table))
10964 (existing (mapcar 'list (org-property-values prop)))
10965 (val (if allowed
10966 (org-completing-read "Value: " allowed nil 'req-match)
10967 (org-completing-read
10968 (concat "Value" (if (and cur (string-match "\\S-" cur))
10969 (concat "[" cur "]") "")
10970 ": ")
10971 existing nil nil "" nil cur))))
10972 (list prop (if (equal val "") cur val))))
10973 (unless (equal (org-entry-get nil property) value)
10974 (org-entry-put nil property value)))
10976 (defun org-delete-property (property)
10977 "In the current entry, delete PROPERTY."
10978 (interactive
10979 (let* ((completion-ignore-case t)
10980 (prop (org-ido-completing-read
10981 "Property: " (org-entry-properties nil 'standard))))
10982 (list prop)))
10983 (message "Property %s %s" property
10984 (if (org-entry-delete nil property)
10985 "deleted"
10986 "was not present in the entry")))
10988 (defun org-delete-property-globally (property)
10989 "Remove PROPERTY globally, from all entries."
10990 (interactive
10991 (let* ((completion-ignore-case t)
10992 (prop (org-ido-completing-read
10993 "Globally remove property: "
10994 (mapcar 'list (org-buffer-property-keys)))))
10995 (list prop)))
10996 (save-excursion
10997 (save-restriction
10998 (widen)
10999 (goto-char (point-min))
11000 (let ((cnt 0))
11001 (while (re-search-forward
11002 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11003 nil t)
11004 (setq cnt (1+ cnt))
11005 (replace-match ""))
11006 (message "Property \"%s\" removed from %d entries" property cnt)))))
11008 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11010 (defun org-compute-property-at-point ()
11011 "Compute the property at point.
11012 This looks for an enclosing column format, extracts the operator and
11013 then applies it to the property in the column format's scope."
11014 (interactive)
11015 (unless (org-at-property-p)
11016 (error "Not at a property"))
11017 (let ((prop (org-match-string-no-properties 2)))
11018 (org-columns-get-format-and-top-level)
11019 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11020 (error "No operator defined for property %s" prop))
11021 (org-columns-compute prop)))
11023 (defun org-property-get-allowed-values (pom property &optional table)
11024 "Get allowed values for the property PROPERTY.
11025 When TABLE is non-nil, return an alist that can directly be used for
11026 completion."
11027 (let (vals)
11028 (cond
11029 ((equal property "TODO")
11030 (setq vals (org-with-point-at pom
11031 (append org-todo-keywords-1 '("")))))
11032 ((equal property "PRIORITY")
11033 (let ((n org-lowest-priority))
11034 (while (>= n org-highest-priority)
11035 (push (char-to-string n) vals)
11036 (setq n (1- n)))))
11037 ((member property org-special-properties))
11039 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11041 (when (and vals (string-match "\\S-" vals))
11042 (setq vals (car (read-from-string (concat "(" vals ")"))))
11043 (setq vals (mapcar (lambda (x)
11044 (cond ((stringp x) x)
11045 ((numberp x) (number-to-string x))
11046 ((symbolp x) (symbol-name x))
11047 (t "???")))
11048 vals)))))
11049 (if table (mapcar 'list vals) vals)))
11051 (defun org-property-previous-allowed-value (&optional previous)
11052 "Switch to the next allowed value for this property."
11053 (interactive)
11054 (org-property-next-allowed-value t))
11056 (defun org-property-next-allowed-value (&optional previous)
11057 "Switch to the next allowed value for this property."
11058 (interactive)
11059 (unless (org-at-property-p)
11060 (error "Not at a property"))
11061 (let* ((key (match-string 2))
11062 (value (match-string 3))
11063 (allowed (or (org-property-get-allowed-values (point) key)
11064 (and (member value '("[ ]" "[-]" "[X]"))
11065 '("[ ]" "[X]"))))
11066 nval)
11067 (unless allowed
11068 (error "Allowed values for this property have not been defined"))
11069 (if previous (setq allowed (reverse allowed)))
11070 (if (member value allowed)
11071 (setq nval (car (cdr (member value allowed)))))
11072 (setq nval (or nval (car allowed)))
11073 (if (equal nval value)
11074 (error "Only one allowed value for this property"))
11075 (org-at-property-p)
11076 (replace-match (concat " :" key ": " nval) t t)
11077 (org-indent-line-function)
11078 (beginning-of-line 1)
11079 (skip-chars-forward " \t")))
11081 (defun org-find-entry-with-id (ident)
11082 "Locate the entry that contains the ID property with exact value IDENT.
11083 IDENT can be a string, a symbol or a number, this function will search for
11084 the string representation of it.
11085 Return the position where this entry starts, or nil if there is no such entry."
11086 (interactive "sID: ")
11087 (let ((id (cond
11088 ((stringp ident) ident)
11089 ((symbol-name ident) (symbol-name ident))
11090 ((numberp ident) (number-to-string ident))
11091 (t (error "IDENT %s must be a string, symbol or number" ident))))
11092 (case-fold-search nil))
11093 (save-excursion
11094 (save-restriction
11095 (widen)
11096 (goto-char (point-min))
11097 (when (re-search-forward
11098 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11099 nil t)
11100 (org-back-to-heading)
11101 (point))))))
11103 ;;;; Timestamps
11105 (defvar org-last-changed-timestamp nil)
11106 (defvar org-last-inserted-timestamp nil
11107 "The last time stamp inserted with `org-insert-time-stamp'.")
11108 (defvar org-time-was-given) ; dynamically scoped parameter
11109 (defvar org-end-time-was-given) ; dynamically scoped parameter
11110 (defvar org-ts-what) ; dynamically scoped parameter
11112 (defun org-time-stamp (arg &optional inactive)
11113 "Prompt for a date/time and insert a time stamp.
11114 If the user specifies a time like HH:MM, or if this command is called
11115 with a prefix argument, the time stamp will contain date and time.
11116 Otherwise, only the date will be included. All parts of a date not
11117 specified by the user will be filled in from the current date/time.
11118 So if you press just return without typing anything, the time stamp
11119 will represent the current date/time. If there is already a timestamp
11120 at the cursor, it will be modified."
11121 (interactive "P")
11122 (let* ((ts nil)
11123 (default-time
11124 ;; Default time is either today, or, when entering a range,
11125 ;; the range start.
11126 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11127 (save-excursion
11128 (re-search-backward
11129 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11130 (- (point) 20) t)))
11131 (apply 'encode-time (org-parse-time-string (match-string 1)))
11132 (current-time)))
11133 (default-input (and ts (org-get-compact-tod ts)))
11134 org-time-was-given org-end-time-was-given time)
11135 (cond
11136 ((and (org-at-timestamp-p t)
11137 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11138 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11139 (insert "--")
11140 (setq time (let ((this-command this-command))
11141 (org-read-date arg 'totime nil nil
11142 default-time default-input)))
11143 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11144 ((org-at-timestamp-p t)
11145 (setq time (let ((this-command this-command))
11146 (org-read-date arg 'totime nil nil default-time default-input)))
11147 (when (org-at-timestamp-p t) ; just to get the match data
11148 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11149 (replace-match "")
11150 (setq org-last-changed-timestamp
11151 (org-insert-time-stamp
11152 time (or org-time-was-given arg)
11153 inactive nil nil (list org-end-time-was-given))))
11154 (message "Timestamp updated"))
11156 (setq time (let ((this-command this-command))
11157 (org-read-date arg 'totime nil nil default-time default-input)))
11158 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11159 nil nil (list org-end-time-was-given))))))
11161 ;; FIXME: can we use this for something else, like computing time differences?
11162 (defun org-get-compact-tod (s)
11163 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11164 (let* ((t1 (match-string 1 s))
11165 (h1 (string-to-number (match-string 2 s)))
11166 (m1 (string-to-number (match-string 3 s)))
11167 (t2 (and (match-end 4) (match-string 5 s)))
11168 (h2 (and t2 (string-to-number (match-string 6 s))))
11169 (m2 (and t2 (string-to-number (match-string 7 s))))
11170 dh dm)
11171 (if (not t2)
11173 (setq dh (- h2 h1) dm (- m2 m1))
11174 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11175 (concat t1 "+" (number-to-string dh)
11176 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11178 (defun org-time-stamp-inactive (&optional arg)
11179 "Insert an inactive time stamp.
11180 An inactive time stamp is enclosed in square brackets instead of angle
11181 brackets. It is inactive in the sense that it does not trigger agenda entries,
11182 does not link to the calendar and cannot be changed with the S-cursor keys.
11183 So these are more for recording a certain time/date."
11184 (interactive "P")
11185 (org-time-stamp arg 'inactive))
11187 (defvar org-date-ovl (org-make-overlay 1 1))
11188 (org-overlay-put org-date-ovl 'face 'org-warning)
11189 (org-detach-overlay org-date-ovl)
11191 (defvar org-ans1) ; dynamically scoped parameter
11192 (defvar org-ans2) ; dynamically scoped parameter
11194 (defvar org-plain-time-of-day-regexp) ; defined below
11196 (defvar org-overriding-default-time nil) ; dynamically scoped
11197 (defvar org-read-date-overlay nil)
11198 (defvar org-dcst nil) ; dynamically scoped
11200 (defun org-read-date (&optional with-time to-time from-string prompt
11201 default-time default-input)
11202 "Read a date, possibly a time, and make things smooth for the user.
11203 The prompt will suggest to enter an ISO date, but you can also enter anything
11204 which will at least partially be understood by `parse-time-string'.
11205 Unrecognized parts of the date will default to the current day, month, year,
11206 hour and minute. If this command is called to replace a timestamp at point,
11207 of to enter the second timestamp of a range, the default time is taken from the
11208 existing stamp. For example,
11209 3-2-5 --> 2003-02-05
11210 feb 15 --> currentyear-02-15
11211 sep 12 9 --> 2009-09-12
11212 12:45 --> today 12:45
11213 22 sept 0:34 --> currentyear-09-22 0:34
11214 12 --> currentyear-currentmonth-12
11215 Fri --> nearest Friday (today or later)
11216 etc.
11218 Furthermore you can specify a relative date by giving, as the *first* thing
11219 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11220 change in days weeks, months, years.
11221 With a single plus or minus, the date is relative to today. With a double
11222 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11223 +4d --> four days from today
11224 +4 --> same as above
11225 +2w --> two weeks from today
11226 ++5 --> five days from default date
11228 The function understands only English month and weekday abbreviations,
11229 but this can be configured with the variables `parse-time-months' and
11230 `parse-time-weekdays'.
11232 While prompting, a calendar is popped up - you can also select the
11233 date with the mouse (button 1). The calendar shows a period of three
11234 months. To scroll it to other months, use the keys `>' and `<'.
11235 If you don't like the calendar, turn it off with
11236 \(setq org-read-date-popup-calendar nil)
11238 With optional argument TO-TIME, the date will immediately be converted
11239 to an internal time.
11240 With an optional argument WITH-TIME, the prompt will suggest to also
11241 insert a time. Note that when WITH-TIME is not set, you can still
11242 enter a time, and this function will inform the calling routine about
11243 this change. The calling routine may then choose to change the format
11244 used to insert the time stamp into the buffer to include the time.
11245 With optional argument FROM-STRING, read from this string instead from
11246 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11247 the time/date that is used for everything that is not specified by the
11248 user."
11249 (require 'parse-time)
11250 (let* ((org-time-stamp-rounding-minutes
11251 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11252 (org-dcst org-display-custom-times)
11253 (ct (org-current-time))
11254 (def (or org-overriding-default-time default-time ct))
11255 (defdecode (decode-time def))
11256 (dummy (progn
11257 (when (< (nth 2 defdecode) org-extend-today-until)
11258 (setcar (nthcdr 2 defdecode) -1)
11259 (setcar (nthcdr 1 defdecode) 59)
11260 (setq def (apply 'encode-time defdecode)
11261 defdecode (decode-time def)))))
11262 (calendar-move-hook nil)
11263 (calendar-view-diary-initially-flag nil)
11264 (view-diary-entries-initially nil)
11265 (calendar-view-holidays-initially-flag nil)
11266 (view-calendar-holidays-initially nil)
11267 (timestr (format-time-string
11268 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11269 (prompt (concat (if prompt (concat prompt " ") "")
11270 (format "Date+time [%s]: " timestr)))
11271 ans (org-ans0 "") org-ans1 org-ans2 final)
11273 (cond
11274 (from-string (setq ans from-string))
11275 (org-read-date-popup-calendar
11276 (save-excursion
11277 (save-window-excursion
11278 (calendar)
11279 (calendar-forward-day (- (time-to-days def)
11280 (calendar-absolute-from-gregorian
11281 (calendar-current-date))))
11282 (org-eval-in-calendar nil t)
11283 (let* ((old-map (current-local-map))
11284 (map (copy-keymap calendar-mode-map))
11285 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11286 (org-defkey map (kbd "RET") 'org-calendar-select)
11287 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11288 'org-calendar-select-mouse)
11289 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11290 'org-calendar-select-mouse)
11291 (org-defkey minibuffer-local-map [(meta shift left)]
11292 (lambda () (interactive)
11293 (org-eval-in-calendar '(calendar-backward-month 1))))
11294 (org-defkey minibuffer-local-map [(meta shift right)]
11295 (lambda () (interactive)
11296 (org-eval-in-calendar '(calendar-forward-month 1))))
11297 (org-defkey minibuffer-local-map [(meta shift up)]
11298 (lambda () (interactive)
11299 (org-eval-in-calendar '(calendar-backward-year 1))))
11300 (org-defkey minibuffer-local-map [(meta shift down)]
11301 (lambda () (interactive)
11302 (org-eval-in-calendar '(calendar-forward-year 1))))
11303 (org-defkey minibuffer-local-map [(shift up)]
11304 (lambda () (interactive)
11305 (org-eval-in-calendar '(calendar-backward-week 1))))
11306 (org-defkey minibuffer-local-map [(shift down)]
11307 (lambda () (interactive)
11308 (org-eval-in-calendar '(calendar-forward-week 1))))
11309 (org-defkey minibuffer-local-map [(shift left)]
11310 (lambda () (interactive)
11311 (org-eval-in-calendar '(calendar-backward-day 1))))
11312 (org-defkey minibuffer-local-map [(shift right)]
11313 (lambda () (interactive)
11314 (org-eval-in-calendar '(calendar-forward-day 1))))
11315 (org-defkey minibuffer-local-map ">"
11316 (lambda () (interactive)
11317 (org-eval-in-calendar '(scroll-calendar-left 1))))
11318 (org-defkey minibuffer-local-map "<"
11319 (lambda () (interactive)
11320 (org-eval-in-calendar '(scroll-calendar-right 1))))
11321 (unwind-protect
11322 (progn
11323 (use-local-map map)
11324 (add-hook 'post-command-hook 'org-read-date-display)
11325 (setq org-ans0 (read-string prompt default-input nil nil))
11326 ;; org-ans0: from prompt
11327 ;; org-ans1: from mouse click
11328 ;; org-ans2: from calendar motion
11329 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11330 (remove-hook 'post-command-hook 'org-read-date-display)
11331 (use-local-map old-map)
11332 (when org-read-date-overlay
11333 (org-delete-overlay org-read-date-overlay)
11334 (setq org-read-date-overlay nil)))))))
11336 (t ; Naked prompt only
11337 (unwind-protect
11338 (setq ans (read-string prompt default-input nil timestr))
11339 (when org-read-date-overlay
11340 (org-delete-overlay org-read-date-overlay)
11341 (setq org-read-date-overlay nil)))))
11343 (setq final (org-read-date-analyze ans def defdecode))
11345 (if to-time
11346 (apply 'encode-time final)
11347 (if (and (boundp 'org-time-was-given) org-time-was-given)
11348 (format "%04d-%02d-%02d %02d:%02d"
11349 (nth 5 final) (nth 4 final) (nth 3 final)
11350 (nth 2 final) (nth 1 final))
11351 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11352 (defvar def)
11353 (defvar defdecode)
11354 (defvar with-time)
11355 (defun org-read-date-display ()
11356 "Display the current date prompt interpretation in the minibuffer."
11357 (when org-read-date-display-live
11358 (when org-read-date-overlay
11359 (org-delete-overlay org-read-date-overlay))
11360 (let ((p (point)))
11361 (end-of-line 1)
11362 (while (not (equal (buffer-substring
11363 (max (point-min) (- (point) 4)) (point))
11364 " "))
11365 (insert " "))
11366 (goto-char p))
11367 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11368 " " (or org-ans1 org-ans2)))
11369 (org-end-time-was-given nil)
11370 (f (org-read-date-analyze ans def defdecode))
11371 (fmts (if org-dcst
11372 org-time-stamp-custom-formats
11373 org-time-stamp-formats))
11374 (fmt (if (or with-time
11375 (and (boundp 'org-time-was-given) org-time-was-given))
11376 (cdr fmts)
11377 (car fmts)))
11378 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11379 (when (and org-end-time-was-given
11380 (string-match org-plain-time-of-day-regexp txt))
11381 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11382 org-end-time-was-given
11383 (substring txt (match-end 0)))))
11384 (setq org-read-date-overlay
11385 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11386 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11388 (defun org-read-date-analyze (ans def defdecode)
11389 "Analyse the combined answer of the date prompt."
11390 ;; FIXME: cleanup and comment
11391 (let (delta deltan deltaw deltadef year month day
11392 hour minute second wday pm h2 m2 tl wday1
11393 iso-year iso-weekday iso-week iso-year iso-date)
11395 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11396 (setq ans "+0"))
11398 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11399 (setq ans (replace-match "" t t ans)
11400 deltan (car delta)
11401 deltaw (nth 1 delta)
11402 deltadef (nth 2 delta)))
11404 ;; Check if there is an iso week date in there
11405 ;; If yes, sore the info and postpone interpreting it until the rest
11406 ;; of the parsing is done
11407 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11408 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11409 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11410 iso-week (string-to-number (match-string 2 ans)))
11411 (setq ans (replace-match "" t t ans)))
11413 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11414 (when (string-match
11415 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11416 (setq year (if (match-end 2)
11417 (string-to-number (match-string 2 ans))
11418 (string-to-number (format-time-string "%Y")))
11419 month (string-to-number (match-string 3 ans))
11420 day (string-to-number (match-string 4 ans)))
11421 (if (< year 100) (setq year (+ 2000 year)))
11422 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11423 t nil ans)))
11424 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11425 ;; If there is a time with am/pm, and *no* time without it, we convert
11426 ;; so that matching will be successful.
11427 (loop for i from 1 to 2 do ; twice, for end time as well
11428 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11429 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11430 (setq hour (string-to-number (match-string 1 ans))
11431 minute (if (match-end 3)
11432 (string-to-number (match-string 3 ans))
11434 pm (equal ?p
11435 (string-to-char (downcase (match-string 4 ans)))))
11436 (if (and (= hour 12) (not pm))
11437 (setq hour 0)
11438 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11439 (setq ans (replace-match (format "%02d:%02d" hour minute)
11440 t t ans))))
11442 ;; Check if a time range is given as a duration
11443 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11444 (setq hour (string-to-number (match-string 1 ans))
11445 h2 (+ hour (string-to-number (match-string 3 ans)))
11446 minute (string-to-number (match-string 2 ans))
11447 m2 (+ minute (if (match-end 5) (string-to-number
11448 (match-string 5 ans))0)))
11449 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11450 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11451 t t ans)))
11453 ;; Check if there is a time range
11454 (when (boundp 'org-end-time-was-given)
11455 (setq org-time-was-given nil)
11456 (when (and (string-match org-plain-time-of-day-regexp ans)
11457 (match-end 8))
11458 (setq org-end-time-was-given (match-string 8 ans))
11459 (setq ans (concat (substring ans 0 (match-beginning 7))
11460 (substring ans (match-end 7))))))
11462 (setq tl (parse-time-string ans)
11463 day (or (nth 3 tl) (nth 3 defdecode))
11464 month (or (nth 4 tl)
11465 (if (and org-read-date-prefer-future
11466 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11467 (1+ (nth 4 defdecode))
11468 (nth 4 defdecode)))
11469 year (or (nth 5 tl)
11470 (if (and org-read-date-prefer-future
11471 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11472 (1+ (nth 5 defdecode))
11473 (nth 5 defdecode)))
11474 hour (or (nth 2 tl) (nth 2 defdecode))
11475 minute (or (nth 1 tl) (nth 1 defdecode))
11476 second (or (nth 0 tl) 0)
11477 wday (nth 6 tl))
11479 ;; Special date definitions below
11480 (cond
11481 (iso-week
11482 ;; There was an iso week
11483 (setq year (or iso-year year)
11484 day (or iso-weekday wday 1)
11485 wday nil ; to make sure that the trigger below does not match
11486 iso-date (calendar-gregorian-from-absolute
11487 (calendar-absolute-from-iso
11488 (list iso-week day year))))
11489 ; FIXME: Should we also push ISO weeks into the future?
11490 ; (when (and org-read-date-prefer-future
11491 ; (not iso-year)
11492 ; (< (calendar-absolute-from-gregorian iso-date)
11493 ; (time-to-days (current-time))))
11494 ; (setq year (1+ year)
11495 ; iso-date (calendar-gregorian-from-absolute
11496 ; (calendar-absolute-from-iso
11497 ; (list iso-week day year)))))
11498 (setq month (car iso-date)
11499 year (nth 2 iso-date)
11500 day (nth 1 iso-date)))
11501 (deltan
11502 (unless deltadef
11503 (let ((now (decode-time (current-time))))
11504 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11505 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11506 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11507 ((equal deltaw "m") (setq month (+ month deltan)))
11508 ((equal deltaw "y") (setq year (+ year deltan)))))
11509 ((and wday (not (nth 3 tl)))
11510 ;; Weekday was given, but no day, so pick that day in the week
11511 ;; on or after the derived date.
11512 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11513 (unless (equal wday wday1)
11514 (setq day (+ day (% (- wday wday1 -7) 7))))))
11515 (if (and (boundp 'org-time-was-given)
11516 (nth 2 tl))
11517 (setq org-time-was-given t))
11518 (if (< year 100) (setq year (+ 2000 year)))
11519 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11520 (list second minute hour day month year)))
11522 (defvar parse-time-weekdays)
11524 (defun org-read-date-get-relative (s today default)
11525 "Check string S for special relative date string.
11526 TODAY and DEFAULT are internal times, for today and for a default.
11527 Return shift list (N what def-flag)
11528 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11529 N is the number of WHATs to shift.
11530 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11531 the DEFAULT date rather than TODAY."
11532 (when (and
11533 (string-match
11534 (concat
11535 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11536 "\\([0-9]+\\)?"
11537 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11538 "\\([ \t]\\|$\\)") s)
11539 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11540 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11541 (string-to-char (substring (match-string 1 s) -1))
11542 ?+))
11543 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11544 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11545 (what (if (match-end 3) (match-string 3 s) "d"))
11546 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11547 (date (if rel default today))
11548 (wday (nth 6 (decode-time date)))
11549 delta)
11550 (if wday1
11551 (progn
11552 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11553 (if (= dir ?-) (setq delta (- delta 7)))
11554 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11555 (list delta "d" rel))
11556 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11558 (defun org-eval-in-calendar (form &optional keepdate)
11559 "Eval FORM in the calendar window and return to current window.
11560 Also, store the cursor date in variable org-ans2."
11561 (let ((sw (selected-window)))
11562 (select-window (get-buffer-window "*Calendar*"))
11563 (eval form)
11564 (when (and (not keepdate) (calendar-cursor-to-date))
11565 (let* ((date (calendar-cursor-to-date))
11566 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11567 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11568 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11569 (select-window sw)))
11571 (defun org-calendar-select ()
11572 "Return to `org-read-date' with the date currently selected.
11573 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11574 (interactive)
11575 (when (calendar-cursor-to-date)
11576 (let* ((date (calendar-cursor-to-date))
11577 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11578 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11579 (if (active-minibuffer-window) (exit-minibuffer))))
11581 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11582 "Insert a date stamp for the date given by the internal TIME.
11583 WITH-HM means, use the stamp format that includes the time of the day.
11584 INACTIVE means use square brackets instead of angular ones, so that the
11585 stamp will not contribute to the agenda.
11586 PRE and POST are optional strings to be inserted before and after the
11587 stamp.
11588 The command returns the inserted time stamp."
11589 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11590 stamp)
11591 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11592 (insert-before-markers (or pre ""))
11593 (insert-before-markers (setq stamp (format-time-string fmt time)))
11594 (when (listp extra)
11595 (setq extra (car extra))
11596 (if (and (stringp extra)
11597 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11598 (setq extra (format "-%02d:%02d"
11599 (string-to-number (match-string 1 extra))
11600 (string-to-number (match-string 2 extra))))
11601 (setq extra nil)))
11602 (when extra
11603 (backward-char 1)
11604 (insert-before-markers extra)
11605 (forward-char 1))
11606 (insert-before-markers (or post ""))
11607 (setq org-last-inserted-timestamp stamp)))
11609 (defun org-toggle-time-stamp-overlays ()
11610 "Toggle the use of custom time stamp formats."
11611 (interactive)
11612 (setq org-display-custom-times (not org-display-custom-times))
11613 (unless org-display-custom-times
11614 (let ((p (point-min)) (bmp (buffer-modified-p)))
11615 (while (setq p (next-single-property-change p 'display))
11616 (if (and (get-text-property p 'display)
11617 (eq (get-text-property p 'face) 'org-date))
11618 (remove-text-properties
11619 p (setq p (next-single-property-change p 'display))
11620 '(display t))))
11621 (set-buffer-modified-p bmp)))
11622 (if (featurep 'xemacs)
11623 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11624 (org-restart-font-lock)
11625 (setq org-table-may-need-update t)
11626 (if org-display-custom-times
11627 (message "Time stamps are overlayed with custom format")
11628 (message "Time stamp overlays removed")))
11630 (defun org-display-custom-time (beg end)
11631 "Overlay modified time stamp format over timestamp between BEG and END."
11632 (let* ((ts (buffer-substring beg end))
11633 t1 w1 with-hm tf time str w2 (off 0))
11634 (save-match-data
11635 (setq t1 (org-parse-time-string ts t))
11636 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11637 (setq off (- (match-end 0) (match-beginning 0)))))
11638 (setq end (- end off))
11639 (setq w1 (- end beg)
11640 with-hm (and (nth 1 t1) (nth 2 t1))
11641 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11642 time (org-fix-decoded-time t1)
11643 str (org-add-props
11644 (format-time-string
11645 (substring tf 1 -1) (apply 'encode-time time))
11646 nil 'mouse-face 'highlight)
11647 w2 (length str))
11648 (if (not (= w2 w1))
11649 (add-text-properties (1+ beg) (+ 2 beg)
11650 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11651 (if (featurep 'xemacs)
11652 (progn
11653 (put-text-property beg end 'invisible t)
11654 (put-text-property beg end 'end-glyph (make-glyph str)))
11655 (put-text-property beg end 'display str))))
11657 (defun org-translate-time (string)
11658 "Translate all timestamps in STRING to custom format.
11659 But do this only if the variable `org-display-custom-times' is set."
11660 (when org-display-custom-times
11661 (save-match-data
11662 (let* ((start 0)
11663 (re org-ts-regexp-both)
11664 t1 with-hm inactive tf time str beg end)
11665 (while (setq start (string-match re string start))
11666 (setq beg (match-beginning 0)
11667 end (match-end 0)
11668 t1 (save-match-data
11669 (org-parse-time-string (substring string beg end) t))
11670 with-hm (and (nth 1 t1) (nth 2 t1))
11671 inactive (equal (substring string beg (1+ beg)) "[")
11672 tf (funcall (if with-hm 'cdr 'car)
11673 org-time-stamp-custom-formats)
11674 time (org-fix-decoded-time t1)
11675 str (format-time-string
11676 (concat
11677 (if inactive "[" "<") (substring tf 1 -1)
11678 (if inactive "]" ">"))
11679 (apply 'encode-time time))
11680 string (replace-match str t t string)
11681 start (+ start (length str)))))))
11682 string)
11684 (defun org-fix-decoded-time (time)
11685 "Set 0 instead of nil for the first 6 elements of time.
11686 Don't touch the rest."
11687 (let ((n 0))
11688 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11690 (defun org-days-to-time (timestamp-string)
11691 "Difference between TIMESTAMP-STRING and now in days."
11692 (- (time-to-days (org-time-string-to-time timestamp-string))
11693 (time-to-days (current-time))))
11695 (defun org-deadline-close (timestamp-string &optional ndays)
11696 "Is the time in TIMESTAMP-STRING close to the current date?"
11697 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11698 (and (< (org-days-to-time timestamp-string) ndays)
11699 (not (org-entry-is-done-p))))
11701 (defun org-get-wdays (ts)
11702 "Get the deadline lead time appropriate for timestring TS."
11703 (cond
11704 ((<= org-deadline-warning-days 0)
11705 ;; 0 or negative, enforce this value no matter what
11706 (- org-deadline-warning-days))
11707 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11708 ;; lead time is specified.
11709 (floor (* (string-to-number (match-string 1 ts))
11710 (cdr (assoc (match-string 2 ts)
11711 '(("d" . 1) ("w" . 7)
11712 ("m" . 30.4) ("y" . 365.25)))))))
11713 ;; go for the default.
11714 (t org-deadline-warning-days)))
11716 (defun org-calendar-select-mouse (ev)
11717 "Return to `org-read-date' with the date currently selected.
11718 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11719 (interactive "e")
11720 (mouse-set-point ev)
11721 (when (calendar-cursor-to-date)
11722 (let* ((date (calendar-cursor-to-date))
11723 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11724 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11725 (if (active-minibuffer-window) (exit-minibuffer))))
11727 (defun org-check-deadlines (ndays)
11728 "Check if there are any deadlines due or past due.
11729 A deadline is considered due if it happens within `org-deadline-warning-days'
11730 days from today's date. If the deadline appears in an entry marked DONE,
11731 it is not shown. The prefix arg NDAYS can be used to test that many
11732 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11733 (interactive "P")
11734 (let* ((org-warn-days
11735 (cond
11736 ((equal ndays '(4)) 100000)
11737 (ndays (prefix-numeric-value ndays))
11738 (t (abs org-deadline-warning-days))))
11739 (case-fold-search nil)
11740 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11741 (callback
11742 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11744 (message "%d deadlines past-due or due within %d days"
11745 (org-occur regexp nil callback)
11746 org-warn-days)))
11748 (defun org-check-before-date (date)
11749 "Check if there are deadlines or scheduled entries before DATE."
11750 (interactive (list (org-read-date)))
11751 (let ((case-fold-search nil)
11752 (regexp (concat "\\<\\(" org-deadline-string
11753 "\\|" org-scheduled-string
11754 "\\) *<\\([^>]+\\)>"))
11755 (callback
11756 (lambda () (time-less-p
11757 (org-time-string-to-time (match-string 2))
11758 (org-time-string-to-time date)))))
11759 (message "%d entries before %s"
11760 (org-occur regexp nil callback) date)))
11762 (defun org-evaluate-time-range (&optional to-buffer)
11763 "Evaluate a time range by computing the difference between start and end.
11764 Normally the result is just printed in the echo area, but with prefix arg
11765 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11766 If the time range is actually in a table, the result is inserted into the
11767 next column.
11768 For time difference computation, a year is assumed to be exactly 365
11769 days in order to avoid rounding problems."
11770 (interactive "P")
11772 (org-clock-update-time-maybe)
11773 (save-excursion
11774 (unless (org-at-date-range-p t)
11775 (goto-char (point-at-bol))
11776 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11777 (if (not (org-at-date-range-p t))
11778 (error "Not at a time-stamp range, and none found in current line")))
11779 (let* ((ts1 (match-string 1))
11780 (ts2 (match-string 2))
11781 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11782 (match-end (match-end 0))
11783 (time1 (org-time-string-to-time ts1))
11784 (time2 (org-time-string-to-time ts2))
11785 (t1 (time-to-seconds time1))
11786 (t2 (time-to-seconds time2))
11787 (diff (abs (- t2 t1)))
11788 (negative (< (- t2 t1) 0))
11789 ;; (ys (floor (* 365 24 60 60)))
11790 (ds (* 24 60 60))
11791 (hs (* 60 60))
11792 (fy "%dy %dd %02d:%02d")
11793 (fy1 "%dy %dd")
11794 (fd "%dd %02d:%02d")
11795 (fd1 "%dd")
11796 (fh "%02d:%02d")
11797 y d h m align)
11798 (if havetime
11799 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11801 d (floor (/ diff ds)) diff (mod diff ds)
11802 h (floor (/ diff hs)) diff (mod diff hs)
11803 m (floor (/ diff 60)))
11804 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11806 d (floor (+ (/ diff ds) 0.5))
11807 h 0 m 0))
11808 (if (not to-buffer)
11809 (message "%s" (org-make-tdiff-string y d h m))
11810 (if (org-at-table-p)
11811 (progn
11812 (goto-char match-end)
11813 (setq align t)
11814 (and (looking-at " *|") (goto-char (match-end 0))))
11815 (goto-char match-end))
11816 (if (looking-at
11817 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11818 (replace-match ""))
11819 (if negative (insert " -"))
11820 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11821 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11822 (insert " " (format fh h m))))
11823 (if align (org-table-align))
11824 (message "Time difference inserted")))))
11826 (defun org-make-tdiff-string (y d h m)
11827 (let ((fmt "")
11828 (l nil))
11829 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11830 l (push y l)))
11831 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11832 l (push d l)))
11833 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11834 l (push h l)))
11835 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11836 l (push m l)))
11837 (apply 'format fmt (nreverse l))))
11839 (defun org-time-string-to-time (s)
11840 (apply 'encode-time (org-parse-time-string s)))
11842 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11843 "Convert a time stamp to an absolute day number.
11844 If there is a specifyer for a cyclic time stamp, get the closest date to
11845 DAYNR.
11846 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11847 (cond
11848 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11849 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11850 daynr
11851 (+ daynr 1000)))
11852 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11853 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11854 (time-to-days (current-time))) (match-string 0 s)
11855 prefer show-all))
11856 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11858 (defun org-days-to-iso-week (days)
11859 "Return the iso week number."
11860 (require 'cal-iso)
11861 (car (calendar-iso-from-absolute days)))
11863 (defun org-small-year-to-year (year)
11864 "Convert 2-digit years into 4-digit years.
11865 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11866 The year 2000 cannot be abbreviated. Any year larger than 99
11867 is returned unchanged."
11868 (if (< year 38)
11869 (setq year (+ 2000 year))
11870 (if (< year 100)
11871 (setq year (+ 1900 year))))
11872 year)
11874 (defun org-time-from-absolute (d)
11875 "Return the time corresponding to date D.
11876 D may be an absolute day number, or a calendar-type list (month day year)."
11877 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11878 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11880 (defun org-calendar-holiday ()
11881 "List of holidays, for Diary display in Org-mode."
11882 (require 'holidays)
11883 (let ((hl (funcall
11884 (if (fboundp 'calendar-check-holidays)
11885 'calendar-check-holidays 'check-calendar-holidays) date)))
11886 (if hl (mapconcat 'identity hl "; "))))
11888 (defun org-diary-sexp-entry (sexp entry date)
11889 "Process a SEXP diary ENTRY for DATE."
11890 (require 'diary-lib)
11891 (let ((result (if calendar-debug-sexp
11892 (let ((stack-trace-on-error t))
11893 (eval (car (read-from-string sexp))))
11894 (condition-case nil
11895 (eval (car (read-from-string sexp)))
11896 (error
11897 (beep)
11898 (message "Bad sexp at line %d in %s: %s"
11899 (org-current-line)
11900 (buffer-file-name) sexp)
11901 (sleep-for 2))))))
11902 (cond ((stringp result) result)
11903 ((and (consp result)
11904 (stringp (cdr result))) (cdr result))
11905 (result entry)
11906 (t nil))))
11908 (defun org-diary-to-ical-string (frombuf)
11909 "Get iCalendar entries from diary entries in buffer FROMBUF.
11910 This uses the icalendar.el library."
11911 (let* ((tmpdir (if (featurep 'xemacs)
11912 (temp-directory)
11913 temporary-file-directory))
11914 (tmpfile (make-temp-name
11915 (expand-file-name "orgics" tmpdir)))
11916 buf rtn b e)
11917 (save-excursion
11918 (set-buffer frombuf)
11919 (icalendar-export-region (point-min) (point-max) tmpfile)
11920 (setq buf (find-buffer-visiting tmpfile))
11921 (set-buffer buf)
11922 (goto-char (point-min))
11923 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11924 (setq b (match-beginning 0)))
11925 (goto-char (point-max))
11926 (if (re-search-backward "^END:VEVENT" nil t)
11927 (setq e (match-end 0)))
11928 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11929 (kill-buffer buf)
11930 (delete-file tmpfile)
11931 rtn))
11933 (defun org-closest-date (start current change prefer show-all)
11934 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11935 When PREFER is `past' return a date that is either CURRENT or past.
11936 When PREFER is `future', return a date that is either CURRENT or future.
11937 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11938 ;; Make the proper lists from the dates
11939 (catch 'exit
11940 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11941 dn dw sday cday n1 n2 n0
11942 d m y y1 y2 date1 date2 nmonths nm ny m2)
11944 (setq start (org-date-to-gregorian start)
11945 current (org-date-to-gregorian
11946 (if show-all
11947 current
11948 (time-to-days (current-time))))
11949 sday (calendar-absolute-from-gregorian start)
11950 cday (calendar-absolute-from-gregorian current))
11952 (if (<= cday sday) (throw 'exit sday))
11954 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11955 (setq dn (string-to-number (match-string 1 change))
11956 dw (cdr (assoc (match-string 2 change) a1)))
11957 (error "Invalid change specifyer: %s" change))
11958 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11959 (cond
11960 ((eq dw 'day)
11961 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11962 n2 (+ n1 dn)))
11963 ((eq dw 'year)
11964 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11965 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11966 (setq date1 (list m d y1)
11967 n1 (calendar-absolute-from-gregorian date1)
11968 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11969 n2 (calendar-absolute-from-gregorian date2)))
11970 ((eq dw 'month)
11971 ;; approx number of month between the two dates
11972 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11973 ;; How often does dn fit in there?
11974 (setq d (nth 1 start) m (car start) y (nth 2 start)
11975 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11976 m (+ m nm)
11977 ny (floor (/ m 12))
11978 y (+ y ny)
11979 m (- m (* ny 12)))
11980 (while (> m 12) (setq m (- m 12) y (1+ y)))
11981 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11982 (setq m2 (+ m dn) y2 y)
11983 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11984 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11985 (while (<= n2 cday)
11986 (setq n1 n2 m m2 y y2)
11987 (setq m2 (+ m dn) y2 y)
11988 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11989 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11990 ;; Make sure n1 is the earlier date
11991 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11992 (if show-all
11993 (cond
11994 ((eq prefer 'past) n1)
11995 ((eq prefer 'future) (if (= cday n1) n1 n2))
11996 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11997 (cond
11998 ((eq prefer 'past) n1)
11999 ((eq prefer 'future) (if (= cday n1) n1 n2))
12000 (t (if (= cday n1) n1 n2)))))))
12002 (defun org-date-to-gregorian (date)
12003 "Turn any specification of DATE into a gregorian date for the calendar."
12004 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12005 ((and (listp date) (= (length date) 3)) date)
12006 ((stringp date)
12007 (setq date (org-parse-time-string date))
12008 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12009 ((listp date)
12010 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12012 (defun org-parse-time-string (s &optional nodefault)
12013 "Parse the standard Org-mode time string.
12014 This should be a lot faster than the normal `parse-time-string'.
12015 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12016 hour and minute fields will be nil if not given."
12017 (if (string-match org-ts-regexp0 s)
12018 (list 0
12019 (if (or (match-beginning 8) (not nodefault))
12020 (string-to-number (or (match-string 8 s) "0")))
12021 (if (or (match-beginning 7) (not nodefault))
12022 (string-to-number (or (match-string 7 s) "0")))
12023 (string-to-number (match-string 4 s))
12024 (string-to-number (match-string 3 s))
12025 (string-to-number (match-string 2 s))
12026 nil nil nil)
12027 (make-list 9 0)))
12029 (defun org-timestamp-up (&optional arg)
12030 "Increase the date item at the cursor by one.
12031 If the cursor is on the year, change the year. If it is on the month or
12032 the day, change that.
12033 With prefix ARG, change by that many units."
12034 (interactive "p")
12035 (org-timestamp-change (prefix-numeric-value arg)))
12037 (defun org-timestamp-down (&optional arg)
12038 "Decrease the date item at the cursor by one.
12039 If the cursor is on the year, change the year. If it is on the month or
12040 the day, change that.
12041 With prefix ARG, change by that many units."
12042 (interactive "p")
12043 (org-timestamp-change (- (prefix-numeric-value arg))))
12045 (defun org-timestamp-up-day (&optional arg)
12046 "Increase the date in the time stamp by one day.
12047 With prefix ARG, change that many days."
12048 (interactive "p")
12049 (if (and (not (org-at-timestamp-p t))
12050 (org-on-heading-p))
12051 (org-todo 'up)
12052 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12054 (defun org-timestamp-down-day (&optional arg)
12055 "Decrease the date in the time stamp by one day.
12056 With prefix ARG, change that many days."
12057 (interactive "p")
12058 (if (and (not (org-at-timestamp-p t))
12059 (org-on-heading-p))
12060 (org-todo 'down)
12061 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12063 (defun org-at-timestamp-p (&optional inactive-ok)
12064 "Determine if the cursor is in or at a timestamp."
12065 (interactive)
12066 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12067 (pos (point))
12068 (ans (or (looking-at tsr)
12069 (save-excursion
12070 (skip-chars-backward "^[<\n\r\t")
12071 (if (> (point) (point-min)) (backward-char 1))
12072 (and (looking-at tsr)
12073 (> (- (match-end 0) pos) -1))))))
12074 (and ans
12075 (boundp 'org-ts-what)
12076 (setq org-ts-what
12077 (cond
12078 ((= pos (match-beginning 0)) 'bracket)
12079 ((= pos (1- (match-end 0))) 'bracket)
12080 ((org-pos-in-match-range pos 2) 'year)
12081 ((org-pos-in-match-range pos 3) 'month)
12082 ((org-pos-in-match-range pos 7) 'hour)
12083 ((org-pos-in-match-range pos 8) 'minute)
12084 ((or (org-pos-in-match-range pos 4)
12085 (org-pos-in-match-range pos 5)) 'day)
12086 ((and (> pos (or (match-end 8) (match-end 5)))
12087 (< pos (match-end 0)))
12088 (- pos (or (match-end 8) (match-end 5))))
12089 (t 'day))))
12090 ans))
12092 (defun org-toggle-timestamp-type ()
12093 "Toggle the type (<active> or [inactive]) of a time stamp."
12094 (interactive)
12095 (when (org-at-timestamp-p t)
12096 (let ((beg (match-beginning 0)) (end (match-end 0))
12097 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12098 (save-excursion
12099 (goto-char beg)
12100 (while (re-search-forward "[][<>]" end t)
12101 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12102 t t)))
12103 (message "Timestamp is now %sactive"
12104 (if (equal (char-after beg) ?<) "" "in")))))
12106 (defun org-timestamp-change (n &optional what)
12107 "Change the date in the time stamp at point.
12108 The date will be changed by N times WHAT. WHAT can be `day', `month',
12109 `year', `minute', `second'. If WHAT is not given, the cursor position
12110 in the timestamp determines what will be changed."
12111 (let ((pos (point))
12112 with-hm inactive
12113 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12114 org-ts-what
12115 extra rem
12116 ts time time0)
12117 (if (not (org-at-timestamp-p t))
12118 (error "Not at a timestamp"))
12119 (if (and (not what) (eq org-ts-what 'bracket))
12120 (org-toggle-timestamp-type)
12121 (if (and (not what) (not (eq org-ts-what 'day))
12122 org-display-custom-times
12123 (get-text-property (point) 'display)
12124 (not (get-text-property (1- (point)) 'display)))
12125 (setq org-ts-what 'day))
12126 (setq org-ts-what (or what org-ts-what)
12127 inactive (= (char-after (match-beginning 0)) ?\[)
12128 ts (match-string 0))
12129 (replace-match "")
12130 (if (string-match
12131 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12133 (setq extra (match-string 1 ts)))
12134 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12135 (setq with-hm t))
12136 (setq time0 (org-parse-time-string ts))
12137 (when (and (eq org-ts-what 'minute)
12138 (eq current-prefix-arg nil))
12139 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12140 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12141 (setcar (cdr time0) (+ (nth 1 time0)
12142 (if (> n 0) (- rem) (- dm rem))))))
12143 (setq time
12144 (encode-time (or (car time0) 0)
12145 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12146 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12147 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12148 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12149 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12150 (nthcdr 6 time0)))
12151 (when (integerp org-ts-what)
12152 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12153 (if (eq what 'calendar)
12154 (let ((cal-date (org-get-date-from-calendar)))
12155 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12156 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12157 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12158 (setcar time0 (or (car time0) 0))
12159 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12160 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12161 (setq time (apply 'encode-time time0))))
12162 (setq org-last-changed-timestamp
12163 (org-insert-time-stamp time with-hm inactive nil nil extra))
12164 (org-clock-update-time-maybe)
12165 (goto-char pos)
12166 ;; Try to recenter the calendar window, if any
12167 (if (and org-calendar-follow-timestamp-change
12168 (get-buffer-window "*Calendar*" t)
12169 (memq org-ts-what '(day month year)))
12170 (org-recenter-calendar (time-to-days time))))))
12172 (defun org-modify-ts-extra (s pos n dm)
12173 "Change the different parts of the lead-time and repeat fields in timestamp."
12174 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12175 ng h m new rem)
12176 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12177 (cond
12178 ((or (org-pos-in-match-range pos 2)
12179 (org-pos-in-match-range pos 3))
12180 (setq m (string-to-number (match-string 3 s))
12181 h (string-to-number (match-string 2 s)))
12182 (if (org-pos-in-match-range pos 2)
12183 (setq h (+ h n))
12184 (setq n (* dm (org-no-warnings (signum n))))
12185 (when (not (= 0 (setq rem (% m dm))))
12186 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12187 (setq m (+ m n)))
12188 (if (< m 0) (setq m (+ m 60) h (1- h)))
12189 (if (> m 59) (setq m (- m 60) h (1+ h)))
12190 (setq h (min 24 (max 0 h)))
12191 (setq ng 1 new (format "-%02d:%02d" h m)))
12192 ((org-pos-in-match-range pos 6)
12193 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12194 ((org-pos-in-match-range pos 5)
12195 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12197 ((org-pos-in-match-range pos 9)
12198 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12199 ((org-pos-in-match-range pos 8)
12200 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12202 (when ng
12203 (setq s (concat
12204 (substring s 0 (match-beginning ng))
12206 (substring s (match-end ng))))))
12209 (defun org-recenter-calendar (date)
12210 "If the calendar is visible, recenter it to DATE."
12211 (let* ((win (selected-window))
12212 (cwin (get-buffer-window "*Calendar*" t))
12213 (calendar-move-hook nil))
12214 (when cwin
12215 (select-window cwin)
12216 (calendar-goto-date (if (listp date) date
12217 (calendar-gregorian-from-absolute date)))
12218 (select-window win))))
12220 (defun org-goto-calendar (&optional arg)
12221 "Go to the Emacs calendar at the current date.
12222 If there is a time stamp in the current line, go to that date.
12223 A prefix ARG can be used to force the current date."
12224 (interactive "P")
12225 (let ((tsr org-ts-regexp) diff
12226 (calendar-move-hook nil)
12227 (calendar-view-holidays-initially-flag nil)
12228 (view-calendar-holidays-initially nil)
12229 (calendar-view-diary-initially-flag nil)
12230 (view-diary-entries-initially nil))
12231 (if (or (org-at-timestamp-p)
12232 (save-excursion
12233 (beginning-of-line 1)
12234 (looking-at (concat ".*" tsr))))
12235 (let ((d1 (time-to-days (current-time)))
12236 (d2 (time-to-days
12237 (org-time-string-to-time (match-string 1)))))
12238 (setq diff (- d2 d1))))
12239 (calendar)
12240 (calendar-goto-today)
12241 (if (and diff (not arg)) (calendar-forward-day diff))))
12243 (defun org-get-date-from-calendar ()
12244 "Return a list (month day year) of date at point in calendar."
12245 (with-current-buffer "*Calendar*"
12246 (save-match-data
12247 (calendar-cursor-to-date))))
12249 (defun org-date-from-calendar ()
12250 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12251 If there is already a time stamp at the cursor position, update it."
12252 (interactive)
12253 (if (org-at-timestamp-p t)
12254 (org-timestamp-change 0 'calendar)
12255 (let ((cal-date (org-get-date-from-calendar)))
12256 (org-insert-time-stamp
12257 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12259 (defun org-minutes-to-hh:mm-string (m)
12260 "Compute H:MM from a number of minutes."
12261 (let ((h (/ m 60)))
12262 (setq m (- m (* 60 h)))
12263 (format org-time-clocksum-format h m)))
12265 (defun org-hh:mm-string-to-minutes (s)
12266 "Convert a string H:MM to a number of minutes."
12267 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12268 (+ (* (string-to-number (match-string 1 s)) 60)
12269 (string-to-number (match-string 2 s)))
12272 ;;;; Agenda files
12274 ;;;###autoload
12275 (defun org-iswitchb (&optional arg)
12276 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12277 With a prefix argument, restrict available to files.
12278 With two prefix arguments, restrict available buffers to agenda files.
12280 Due to some yet unresolved reason, the global function
12281 `iswitchb-mode' needs to be active for this function to work."
12282 (interactive "P")
12283 (require 'iswitchb)
12284 (let ((enabled iswitchb-mode) blist)
12285 (or enabled (iswitchb-mode 1))
12286 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12287 ((equal arg '(16)) (org-buffer-list 'agenda))
12288 (t (org-buffer-list))))
12289 (unwind-protect
12290 (let ((iswitchb-make-buflist-hook
12291 (lambda ()
12292 (setq iswitchb-temp-buflist
12293 (mapcar 'buffer-name blist)))))
12294 (switch-to-buffer
12295 (iswitchb-read-buffer
12296 "Switch-to: " nil t))
12297 (or enabled (iswitchb-mode -1))))))
12299 ;;;###autoload
12300 (defun org-ido-switchb (&optional arg)
12301 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12302 With a prefix argument, restrict available to files.
12303 With two prefix arguments, restrict available buffers to agenda files."
12304 (interactive "P")
12305 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12306 ((equal arg '(16)) (org-buffer-list 'agenda))
12307 (t (org-buffer-list)))))
12308 (switch-to-buffer
12309 (org-ido-completing-read "Org buffer: "
12310 (mapcar 'buffer-name blist)
12311 nil t))))
12313 (defun org-buffer-list (&optional predicate exclude-tmp)
12314 "Return a list of Org buffers.
12315 PREDICATE can be `export', `files' or `agenda'.
12317 export restrict the list to Export buffers.
12318 files restrict the list to buffers visiting Org files.
12319 agenda restrict the list to buffers visiting agenda files.
12321 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12322 (let* ((bfn nil)
12323 (agenda-files (and (eq predicate 'agenda)
12324 (mapcar 'file-truename (org-agenda-files t))))
12325 (filter
12326 (cond
12327 ((eq predicate 'files)
12328 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12329 ((eq predicate 'export)
12330 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12331 ((eq predicate 'agenda)
12332 (lambda (b)
12333 (with-current-buffer b
12334 (and (eq major-mode 'org-mode)
12335 (setq bfn (buffer-file-name b))
12336 (member (file-truename bfn) agenda-files)))))
12337 (t (lambda (b) (with-current-buffer b
12338 (or (eq major-mode 'org-mode)
12339 (string-match "\*Org .*Export"
12340 (buffer-name b)))))))))
12341 (delq nil
12342 (mapcar
12343 (lambda(b)
12344 (if (and (funcall filter b)
12345 (or (not exclude-tmp)
12346 (not (string-match "tmp" (buffer-name b)))))
12348 nil))
12349 (buffer-list)))))
12351 (defun org-agenda-files (&optional unrestricted archives)
12352 "Get the list of agenda files.
12353 Optional UNRESTRICTED means return the full list even if a restriction
12354 is currently in place.
12355 When ARCHIVES is t, include all archive files hat are really being
12356 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12357 `org-agenda-archives-mode' is t."
12358 (let ((files
12359 (cond
12360 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12361 ((stringp org-agenda-files) (org-read-agenda-file-list))
12362 ((listp org-agenda-files) org-agenda-files)
12363 (t (error "Invalid value of `org-agenda-files'")))))
12364 (setq files (apply 'append
12365 (mapcar (lambda (f)
12366 (if (file-directory-p f)
12367 (directory-files
12368 f t org-agenda-file-regexp)
12369 (list f)))
12370 files)))
12371 (when org-agenda-skip-unavailable-files
12372 (setq files (delq nil
12373 (mapcar (function
12374 (lambda (file)
12375 (and (file-readable-p file) file)))
12376 files))))
12377 (when (or (eq archives t)
12378 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12379 (setq files (org-add-archive-files files)))
12380 files))
12382 (defun org-edit-agenda-file-list ()
12383 "Edit the list of agenda files.
12384 Depending on setup, this either uses customize to edit the variable
12385 `org-agenda-files', or it visits the file that is holding the list. In the
12386 latter case, the buffer is set up in a way that saving it automatically kills
12387 the buffer and restores the previous window configuration."
12388 (interactive)
12389 (if (stringp org-agenda-files)
12390 (let ((cw (current-window-configuration)))
12391 (find-file org-agenda-files)
12392 (org-set-local 'org-window-configuration cw)
12393 (org-add-hook 'after-save-hook
12394 (lambda ()
12395 (set-window-configuration
12396 (prog1 org-window-configuration
12397 (kill-buffer (current-buffer))))
12398 (org-install-agenda-files-menu)
12399 (message "New agenda file list installed"))
12400 nil 'local)
12401 (message "%s" (substitute-command-keys
12402 "Edit list and finish with \\[save-buffer]")))
12403 (customize-variable 'org-agenda-files)))
12405 (defun org-store-new-agenda-file-list (list)
12406 "Set new value for the agenda file list and save it correctly."
12407 (if (stringp org-agenda-files)
12408 (let ((f org-agenda-files) b)
12409 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12410 (with-temp-file f
12411 (insert (mapconcat 'identity list "\n") "\n")))
12412 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12413 (setq org-agenda-files list)
12414 (customize-save-variable 'org-agenda-files org-agenda-files))))
12416 (defun org-read-agenda-file-list ()
12417 "Read the list of agenda files from a file."
12418 (when (file-directory-p org-agenda-files)
12419 (error "`org-agenda-files' cannot be a single directory"))
12420 (when (stringp org-agenda-files)
12421 (with-temp-buffer
12422 (insert-file-contents org-agenda-files)
12423 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12426 ;;;###autoload
12427 (defun org-cycle-agenda-files ()
12428 "Cycle through the files in `org-agenda-files'.
12429 If the current buffer visits an agenda file, find the next one in the list.
12430 If the current buffer does not, find the first agenda file."
12431 (interactive)
12432 (let* ((fs (org-agenda-files t))
12433 (files (append fs (list (car fs))))
12434 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12435 file)
12436 (unless files (error "No agenda files"))
12437 (catch 'exit
12438 (while (setq file (pop files))
12439 (if (equal (file-truename file) tcf)
12440 (when (car files)
12441 (find-file (car files))
12442 (throw 'exit t))))
12443 (find-file (car fs)))
12444 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12446 (defun org-agenda-file-to-front (&optional to-end)
12447 "Move/add the current file to the top of the agenda file list.
12448 If the file is not present in the list, it is added to the front. If it is
12449 present, it is moved there. With optional argument TO-END, add/move to the
12450 end of the list."
12451 (interactive "P")
12452 (let ((org-agenda-skip-unavailable-files nil)
12453 (file-alist (mapcar (lambda (x)
12454 (cons (file-truename x) x))
12455 (org-agenda-files t)))
12456 (ctf (file-truename buffer-file-name))
12457 x had)
12458 (setq x (assoc ctf file-alist) had x)
12460 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12461 (if to-end
12462 (setq file-alist (append (delq x file-alist) (list x)))
12463 (setq file-alist (cons x (delq x file-alist))))
12464 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12465 (org-install-agenda-files-menu)
12466 (message "File %s to %s of agenda file list"
12467 (if had "moved" "added") (if to-end "end" "front"))))
12469 (defun org-remove-file (&optional file)
12470 "Remove current file from the list of files in variable `org-agenda-files'.
12471 These are the files which are being checked for agenda entries.
12472 Optional argument FILE means, use this file instead of the current."
12473 (interactive)
12474 (let* ((org-agenda-skip-unavailable-files nil)
12475 (file (or file buffer-file-name))
12476 (true-file (file-truename file))
12477 (afile (abbreviate-file-name file))
12478 (files (delq nil (mapcar
12479 (lambda (x)
12480 (if (equal true-file
12481 (file-truename x))
12482 nil x))
12483 (org-agenda-files t)))))
12484 (if (not (= (length files) (length (org-agenda-files t))))
12485 (progn
12486 (org-store-new-agenda-file-list files)
12487 (org-install-agenda-files-menu)
12488 (message "Removed file: %s" afile))
12489 (message "File was not in list: %s (not removed)" afile))))
12491 (defun org-file-menu-entry (file)
12492 (vector file (list 'find-file file) t))
12494 (defun org-check-agenda-file (file)
12495 "Make sure FILE exists. If not, ask user what to do."
12496 (when (not (file-exists-p file))
12497 (message "non-existent file %s. [R]emove from list or [A]bort?"
12498 (abbreviate-file-name file))
12499 (let ((r (downcase (read-char-exclusive))))
12500 (cond
12501 ((equal r ?r)
12502 (org-remove-file file)
12503 (throw 'nextfile t))
12504 (t (error "Abort"))))))
12506 (defun org-get-agenda-file-buffer (file)
12507 "Get a buffer visiting FILE. If the buffer needs to be created, add
12508 it to the list of buffers which might be released later."
12509 (let ((buf (org-find-base-buffer-visiting file)))
12510 (if buf
12511 buf ; just return it
12512 ;; Make a new buffer and remember it
12513 (setq buf (find-file-noselect file))
12514 (if buf (push buf org-agenda-new-buffers))
12515 buf)))
12517 (defun org-release-buffers (blist)
12518 "Release all buffers in list, asking the user for confirmation when needed.
12519 When a buffer is unmodified, it is just killed. When modified, it is saved
12520 \(if the user agrees) and then killed."
12521 (let (buf file)
12522 (while (setq buf (pop blist))
12523 (setq file (buffer-file-name buf))
12524 (when (and (buffer-modified-p buf)
12525 file
12526 (y-or-n-p (format "Save file %s? " file)))
12527 (with-current-buffer buf (save-buffer)))
12528 (kill-buffer buf))))
12530 (defun org-prepare-agenda-buffers (files)
12531 "Create buffers for all agenda files, protect archived trees and comments."
12532 (interactive)
12533 (let ((pa '(:org-archived t))
12534 (pc '(:org-comment t))
12535 (pall '(:org-archived t :org-comment t))
12536 (inhibit-read-only t)
12537 (rea (concat ":" org-archive-tag ":"))
12538 bmp file re)
12539 (save-excursion
12540 (save-restriction
12541 (while (setq file (pop files))
12542 (if (bufferp file)
12543 (set-buffer file)
12544 (org-check-agenda-file file)
12545 (set-buffer (org-get-agenda-file-buffer file)))
12546 (widen)
12547 (setq bmp (buffer-modified-p))
12548 (org-refresh-category-properties)
12549 (setq org-todo-keywords-for-agenda
12550 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12551 (setq org-done-keywords-for-agenda
12552 (append org-done-keywords-for-agenda org-done-keywords))
12553 (setq org-todo-keyword-alist-for-agenda
12554 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12555 (setq org-tag-alist-for-agenda
12556 (append org-tag-alist-for-agenda org-tag-alist))
12558 (save-excursion
12559 (remove-text-properties (point-min) (point-max) pall)
12560 (when org-agenda-skip-archived-trees
12561 (goto-char (point-min))
12562 (while (re-search-forward rea nil t)
12563 (if (org-on-heading-p t)
12564 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12565 (goto-char (point-min))
12566 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12567 (while (re-search-forward re nil t)
12568 (add-text-properties
12569 (match-beginning 0) (org-end-of-subtree t) pc)))
12570 (set-buffer-modified-p bmp))))
12571 (setq org-todo-keyword-alist-for-agenda
12572 (org-uniquify org-todo-keyword-alist-for-agenda)
12573 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12575 ;;;; Embedded LaTeX
12577 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12578 "Keymap for the minor `org-cdlatex-mode'.")
12580 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12581 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12582 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12583 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12584 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12586 (defvar org-cdlatex-texmathp-advice-is-done nil
12587 "Flag remembering if we have applied the advice to texmathp already.")
12589 (define-minor-mode org-cdlatex-mode
12590 "Toggle the minor `org-cdlatex-mode'.
12591 This mode supports entering LaTeX environment and math in LaTeX fragments
12592 in Org-mode.
12593 \\{org-cdlatex-mode-map}"
12594 nil " OCDL" nil
12595 (when org-cdlatex-mode (require 'cdlatex))
12596 (unless org-cdlatex-texmathp-advice-is-done
12597 (setq org-cdlatex-texmathp-advice-is-done t)
12598 (defadvice texmathp (around org-math-always-on activate)
12599 "Always return t in org-mode buffers.
12600 This is because we want to insert math symbols without dollars even outside
12601 the LaTeX math segments. If Orgmode thinks that point is actually inside
12602 an embedded LaTeX fragment, let texmathp do its job.
12603 \\[org-cdlatex-mode-map]"
12604 (interactive)
12605 (let (p)
12606 (cond
12607 ((not (org-mode-p)) ad-do-it)
12608 ((eq this-command 'cdlatex-math-symbol)
12609 (setq ad-return-value t
12610 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12612 (let ((p (org-inside-LaTeX-fragment-p)))
12613 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12614 (setq ad-return-value t
12615 texmathp-why '("Org-mode embedded math" . 0))
12616 (if p ad-do-it)))))))))
12618 (defun turn-on-org-cdlatex ()
12619 "Unconditionally turn on `org-cdlatex-mode'."
12620 (org-cdlatex-mode 1))
12622 (defun org-inside-LaTeX-fragment-p ()
12623 "Test if point is inside a LaTeX fragment.
12624 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12625 sequence appearing also before point.
12626 Even though the matchers for math are configurable, this function assumes
12627 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12628 delimiters are skipped when they have been removed by customization.
12629 The return value is nil, or a cons cell with the delimiter and
12630 and the position of this delimiter.
12632 This function does a reasonably good job, but can locally be fooled by
12633 for example currency specifications. For example it will assume being in
12634 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12635 fragments that are properly closed, but during editing, we have to live
12636 with the uncertainty caused by missing closing delimiters. This function
12637 looks only before point, not after."
12638 (catch 'exit
12639 (let ((pos (point))
12640 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12641 (lim (progn
12642 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12643 (point)))
12644 dd-on str (start 0) m re)
12645 (goto-char pos)
12646 (when dodollar
12647 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12648 re (nth 1 (assoc "$" org-latex-regexps)))
12649 (while (string-match re str start)
12650 (cond
12651 ((= (match-end 0) (length str))
12652 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12653 ((= (match-end 0) (- (length str) 5))
12654 (throw 'exit nil))
12655 (t (setq start (match-end 0))))))
12656 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12657 (goto-char pos)
12658 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12659 (and (match-beginning 2) (throw 'exit nil))
12660 ;; count $$
12661 (while (re-search-backward "\\$\\$" lim t)
12662 (setq dd-on (not dd-on)))
12663 (goto-char pos)
12664 (if dd-on (cons "$$" m))))))
12667 (defun org-try-cdlatex-tab ()
12668 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12669 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12670 - inside a LaTeX fragment, or
12671 - after the first word in a line, where an abbreviation expansion could
12672 insert a LaTeX environment."
12673 (when org-cdlatex-mode
12674 (cond
12675 ((save-excursion
12676 (skip-chars-backward "a-zA-Z0-9*")
12677 (skip-chars-backward " \t")
12678 (bolp))
12679 (cdlatex-tab) t)
12680 ((org-inside-LaTeX-fragment-p)
12681 (cdlatex-tab) t)
12682 (t nil))))
12684 (defun org-cdlatex-underscore-caret (&optional arg)
12685 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12686 Revert to the normal definition outside of these fragments."
12687 (interactive "P")
12688 (if (org-inside-LaTeX-fragment-p)
12689 (call-interactively 'cdlatex-sub-superscript)
12690 (let (org-cdlatex-mode)
12691 (call-interactively (key-binding (vector last-input-event))))))
12693 (defun org-cdlatex-math-modify (&optional arg)
12694 "Execute `cdlatex-math-modify' in LaTeX fragments.
12695 Revert to the normal definition outside of these fragments."
12696 (interactive "P")
12697 (if (org-inside-LaTeX-fragment-p)
12698 (call-interactively 'cdlatex-math-modify)
12699 (let (org-cdlatex-mode)
12700 (call-interactively (key-binding (vector last-input-event))))))
12702 (defvar org-latex-fragment-image-overlays nil
12703 "List of overlays carrying the images of latex fragments.")
12704 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12706 (defun org-remove-latex-fragment-image-overlays ()
12707 "Remove all overlays with LaTeX fragment images in current buffer."
12708 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12709 (setq org-latex-fragment-image-overlays nil))
12711 (defun org-preview-latex-fragment (&optional subtree)
12712 "Preview the LaTeX fragment at point, or all locally or globally.
12713 If the cursor is in a LaTeX fragment, create the image and overlay
12714 it over the source code. If there is no fragment at point, display
12715 all fragments in the current text, from one headline to the next. With
12716 prefix SUBTREE, display all fragments in the current subtree. With a
12717 double prefix `C-u C-u', or when the cursor is before the first headline,
12718 display all fragments in the buffer.
12719 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12720 (interactive "P")
12721 (org-remove-latex-fragment-image-overlays)
12722 (save-excursion
12723 (save-restriction
12724 (let (beg end at msg)
12725 (cond
12726 ((or (equal subtree '(16))
12727 (not (save-excursion
12728 (re-search-backward (concat "^" outline-regexp) nil t))))
12729 (setq beg (point-min) end (point-max)
12730 msg "Creating images for buffer...%s"))
12731 ((equal subtree '(4))
12732 (org-back-to-heading)
12733 (setq beg (point) end (org-end-of-subtree t)
12734 msg "Creating images for subtree...%s"))
12736 (if (setq at (org-inside-LaTeX-fragment-p))
12737 (goto-char (max (point-min) (- (cdr at) 2)))
12738 (org-back-to-heading))
12739 (setq beg (point) end (progn (outline-next-heading) (point))
12740 msg (if at "Creating image...%s"
12741 "Creating images for entry...%s"))))
12742 (message msg "")
12743 (narrow-to-region beg end)
12744 (goto-char beg)
12745 (org-format-latex
12746 (concat "ltxpng/" (file-name-sans-extension
12747 (file-name-nondirectory
12748 buffer-file-name)))
12749 default-directory 'overlays msg at 'forbuffer)
12750 (message msg "done. Use `C-c C-c' to remove images.")))))
12752 (defvar org-latex-regexps
12753 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12754 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12755 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12756 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12757 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12758 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12759 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12760 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12761 "Regular expressions for matching embedded LaTeX.")
12763 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12764 "Replace LaTeX fragments with links to an image, and produce images."
12765 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12766 (let* ((prefixnodir (file-name-nondirectory prefix))
12767 (absprefix (expand-file-name prefix dir))
12768 (todir (file-name-directory absprefix))
12769 (opt org-format-latex-options)
12770 (matchers (plist-get opt :matchers))
12771 (re-list org-latex-regexps)
12772 (cnt 0) txt link beg end re e checkdir
12773 m n block linkfile movefile ov)
12774 ;; Check if there are old images files with this prefix, and remove them
12775 (when (file-directory-p todir)
12776 (mapc 'delete-file
12777 (directory-files
12778 todir 'full
12779 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12780 ;; Check the different regular expressions
12781 (while (setq e (pop re-list))
12782 (setq m (car e) re (nth 1 e) n (nth 2 e)
12783 block (if (nth 3 e) "\n\n" ""))
12784 (when (member m matchers)
12785 (goto-char (point-min))
12786 (while (re-search-forward re nil t)
12787 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
12788 (not (get-text-property (match-beginning n)
12789 'org-protected)))
12790 (setq txt (match-string n)
12791 beg (match-beginning n) end (match-end n)
12792 cnt (1+ cnt)
12793 linkfile (format "%s_%04d.png" prefix cnt)
12794 movefile (format "%s_%04d.png" absprefix cnt)
12795 link (concat block "[[file:" linkfile "]]" block))
12796 (if msg (message msg cnt))
12797 (goto-char beg)
12798 (unless checkdir ; make sure the directory exists
12799 (setq checkdir t)
12800 (or (file-directory-p todir) (make-directory todir)))
12801 (org-create-formula-image
12802 txt movefile opt forbuffer)
12803 (if overlays
12804 (progn
12805 (setq ov (org-make-overlay beg end))
12806 (if (featurep 'xemacs)
12807 (progn
12808 (org-overlay-put ov 'invisible t)
12809 (org-overlay-put
12810 ov 'end-glyph
12811 (make-glyph (vector 'png :file movefile))))
12812 (org-overlay-put
12813 ov 'display
12814 (list 'image :type 'png :file movefile :ascent 'center)))
12815 (push ov org-latex-fragment-image-overlays)
12816 (goto-char end))
12817 (delete-region beg end)
12818 (insert link))))))))
12820 ;; This function borrows from Ganesh Swami's latex2png.el
12821 (defun org-create-formula-image (string tofile options buffer)
12822 (let* ((tmpdir (if (featurep 'xemacs)
12823 (temp-directory)
12824 temporary-file-directory))
12825 (texfilebase (make-temp-name
12826 (expand-file-name "orgtex" tmpdir)))
12827 (texfile (concat texfilebase ".tex"))
12828 (dvifile (concat texfilebase ".dvi"))
12829 (pngfile (concat texfilebase ".png"))
12830 (fnh (if (featurep 'xemacs)
12831 (font-height (get-face-font 'default))
12832 (face-attribute 'default :height nil)))
12833 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12834 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12835 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12836 "Black"))
12837 (bg (or (plist-get options (if buffer :background :html-background))
12838 "Transparent")))
12839 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12840 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12841 (with-temp-file texfile
12842 (insert org-format-latex-header
12843 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12844 (let ((dir default-directory))
12845 (condition-case nil
12846 (progn
12847 (cd tmpdir)
12848 (call-process "latex" nil nil nil texfile))
12849 (error nil))
12850 (cd dir))
12851 (if (not (file-exists-p dvifile))
12852 (progn (message "Failed to create dvi file from %s" texfile) nil)
12853 (condition-case nil
12854 (call-process "dvipng" nil nil nil
12855 "-E" "-fg" fg "-bg" bg
12856 "-D" dpi
12857 ;;"-x" scale "-y" scale
12858 "-T" "tight"
12859 "-o" pngfile
12860 dvifile)
12861 (error nil))
12862 (if (not (file-exists-p pngfile))
12863 (progn (message "Failed to create png file from %s" texfile) nil)
12864 ;; Use the requested file name and clean up
12865 (copy-file pngfile tofile 'replace)
12866 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12867 (delete-file (concat texfilebase e)))
12868 pngfile))))
12870 (defun org-dvipng-color (attr)
12871 "Return an rgb color specification for dvipng."
12872 (apply 'format "rgb %s %s %s"
12873 (mapcar 'org-normalize-color
12874 (color-values (face-attribute 'default attr nil)))))
12876 (defun org-normalize-color (value)
12877 "Return string to be used as color value for an RGB component."
12878 (format "%g" (/ value 65535.0)))
12880 ;;;; Key bindings
12882 ;; Make `C-c C-x' a prefix key
12883 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12885 ;; TAB key with modifiers
12886 (org-defkey org-mode-map "\C-i" 'org-cycle)
12887 (org-defkey org-mode-map [(tab)] 'org-cycle)
12888 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12889 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12890 (org-defkey org-mode-map "\M-\t" 'org-complete)
12891 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12892 ;; The following line is necessary under Suse GNU/Linux
12893 (unless (featurep 'xemacs)
12894 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12895 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12896 (define-key org-mode-map [backtab] 'org-shifttab)
12898 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12899 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12900 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12902 ;; Cursor keys with modifiers
12903 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12904 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12905 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12906 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12908 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12909 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12910 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12911 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12913 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12914 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12915 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12916 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12918 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12919 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12921 ;;; Extra keys for tty access.
12922 ;; We only set them when really needed because otherwise the
12923 ;; menus don't show the simple keys
12925 (when (or org-use-extra-keys
12926 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12927 (not window-system))
12928 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12929 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12930 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12931 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12932 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12933 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12934 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12935 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12936 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12937 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12938 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12939 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12940 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12941 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12942 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12943 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12944 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12945 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12946 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12947 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12948 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12949 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12951 ;; All the other keys
12953 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12954 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12955 (if (boundp 'narrow-map)
12956 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12957 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12958 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12959 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12960 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12961 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12962 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12963 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12964 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12965 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12966 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12967 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12968 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12969 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12970 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12971 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12972 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12973 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12974 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12975 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12976 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12977 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12978 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12979 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12980 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12981 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12982 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12983 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12984 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12985 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12986 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12987 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12988 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12989 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12990 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12991 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12992 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12993 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12994 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12995 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12996 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12997 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12998 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12999 (org-defkey org-mode-map "\C-c^" 'org-sort)
13000 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13001 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13002 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13003 (org-defkey org-mode-map "\C-m" 'org-return)
13004 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13005 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13006 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13007 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13008 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13009 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13010 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13011 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13012 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13013 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13014 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13015 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13016 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13017 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13018 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13019 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13020 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13022 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13023 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13024 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13025 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13027 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13028 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13029 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13030 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13031 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13032 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13033 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13034 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13035 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13036 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13037 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13038 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13039 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13041 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13042 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13043 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13044 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13046 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13048 (when (featurep 'xemacs)
13049 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13051 (defvar org-table-auto-blank-field) ; defined in org-table.el
13052 (defun org-self-insert-command (N)
13053 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13054 If the cursor is in a table looking at whitespace, the whitespace is
13055 overwritten, and the table is not marked as requiring realignment."
13056 (interactive "p")
13057 (if (and (org-table-p)
13058 (progn
13059 ;; check if we blank the field, and if that triggers align
13060 (and (featurep 'org-table) org-table-auto-blank-field
13061 (member last-command
13062 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13063 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13064 ;; got extra space, this field does not determine column width
13065 (let (org-table-may-need-update) (org-table-blank-field))
13066 ;; no extra space, this field may determine column width
13067 (org-table-blank-field)))
13069 (eq N 1)
13070 (looking-at "[^|\n]* |"))
13071 (let (org-table-may-need-update)
13072 (goto-char (1- (match-end 0)))
13073 (delete-backward-char 1)
13074 (goto-char (match-beginning 0))
13075 (self-insert-command N))
13076 (setq org-table-may-need-update t)
13077 (self-insert-command N)
13078 (org-fix-tags-on-the-fly)))
13080 (defun org-fix-tags-on-the-fly ()
13081 (when (and (equal (char-after (point-at-bol)) ?*)
13082 (org-on-heading-p))
13083 (org-align-tags-here org-tags-column)))
13085 (defun org-delete-backward-char (N)
13086 "Like `delete-backward-char', insert whitespace at field end in tables.
13087 When deleting backwards, in tables this function will insert whitespace in
13088 front of the next \"|\" separator, to keep the table aligned. The table will
13089 still be marked for re-alignment if the field did fill the entire column,
13090 because, in this case the deletion might narrow the column."
13091 (interactive "p")
13092 (if (and (org-table-p)
13093 (eq N 1)
13094 (string-match "|" (buffer-substring (point-at-bol) (point)))
13095 (looking-at ".*?|"))
13096 (let ((pos (point))
13097 (noalign (looking-at "[^|\n\r]* |"))
13098 (c org-table-may-need-update))
13099 (backward-delete-char N)
13100 (skip-chars-forward "^|")
13101 (insert " ")
13102 (goto-char (1- pos))
13103 ;; noalign: if there were two spaces at the end, this field
13104 ;; does not determine the width of the column.
13105 (if noalign (setq org-table-may-need-update c)))
13106 (backward-delete-char N)
13107 (org-fix-tags-on-the-fly)))
13109 (defun org-delete-char (N)
13110 "Like `delete-char', but insert whitespace at field end in tables.
13111 When deleting characters, in tables this function will insert whitespace in
13112 front of the next \"|\" separator, to keep the table aligned. The table will
13113 still be marked for re-alignment if the field did fill the entire column,
13114 because, in this case the deletion might narrow the column."
13115 (interactive "p")
13116 (if (and (org-table-p)
13117 (not (bolp))
13118 (not (= (char-after) ?|))
13119 (eq N 1))
13120 (if (looking-at ".*?|")
13121 (let ((pos (point))
13122 (noalign (looking-at "[^|\n\r]* |"))
13123 (c org-table-may-need-update))
13124 (replace-match (concat
13125 (substring (match-string 0) 1 -1)
13126 " |"))
13127 (goto-char pos)
13128 ;; noalign: if there were two spaces at the end, this field
13129 ;; does not determine the width of the column.
13130 (if noalign (setq org-table-may-need-update c)))
13131 (delete-char N))
13132 (delete-char N)
13133 (org-fix-tags-on-the-fly)))
13135 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13136 (put 'org-self-insert-command 'delete-selection t)
13137 (put 'orgtbl-self-insert-command 'delete-selection t)
13138 (put 'org-delete-char 'delete-selection 'supersede)
13139 (put 'org-delete-backward-char 'delete-selection 'supersede)
13140 (put 'org-yank 'delete-selection 'yank)
13142 ;; Make `flyspell-mode' delay after some commands
13143 (put 'org-self-insert-command 'flyspell-delayed t)
13144 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13145 (put 'org-delete-char 'flyspell-delayed t)
13146 (put 'org-delete-backward-char 'flyspell-delayed t)
13148 ;; Make pabbrev-mode expand after org-mode commands
13149 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13150 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13152 ;; How to do this: Measure non-white length of current string
13153 ;; If equal to column width, we should realign.
13155 (defun org-remap (map &rest commands)
13156 "In MAP, remap the functions given in COMMANDS.
13157 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13158 (let (new old)
13159 (while commands
13160 (setq old (pop commands) new (pop commands))
13161 (if (fboundp 'command-remapping)
13162 (org-defkey map (vector 'remap old) new)
13163 (substitute-key-definition old new map global-map)))))
13165 (when (eq org-enable-table-editor 'optimized)
13166 ;; If the user wants maximum table support, we need to hijack
13167 ;; some standard editing functions
13168 (org-remap org-mode-map
13169 'self-insert-command 'org-self-insert-command
13170 'delete-char 'org-delete-char
13171 'delete-backward-char 'org-delete-backward-char)
13172 (org-defkey org-mode-map "|" 'org-force-self-insert))
13174 (defun org-modifier-cursor-error ()
13175 "Throw an error, a modified cursor command was applied in wrong context."
13176 (error "This command is active in special context like tables, headlines or items"))
13178 (defun org-shiftselect-error ()
13179 "Throw an error because Shift-Cursor command was applied in wrong context."
13180 (if (and (boundp 'shift-select-mode) shift-select-mode)
13181 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13182 (error "This command works only in special context like headlines or timestamps.")))
13184 (defun org-call-for-shift-select (cmd)
13185 (let ((this-command-keys-shift-translated t))
13186 (call-interactively cmd)))
13188 (defun org-shifttab (&optional arg)
13189 "Global visibility cycling or move to previous table field.
13190 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13191 on context.
13192 See the individual commands for more information."
13193 (interactive "P")
13194 (cond
13195 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13196 ((integerp arg)
13197 (message "Content view to level: %d" arg)
13198 (org-content (prefix-numeric-value arg))
13199 (setq org-cycle-global-status 'overview))
13200 (t (call-interactively 'org-global-cycle))))
13202 (defun org-shiftmetaleft ()
13203 "Promote subtree or delete table column.
13204 Calls `org-promote-subtree', `org-outdent-item',
13205 or `org-table-delete-column', depending on context.
13206 See the individual commands for more information."
13207 (interactive)
13208 (cond
13209 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13210 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13211 ((org-at-item-p) (call-interactively 'org-outdent-item))
13212 (t (org-modifier-cursor-error))))
13214 (defun org-shiftmetaright ()
13215 "Demote subtree or insert table column.
13216 Calls `org-demote-subtree', `org-indent-item',
13217 or `org-table-insert-column', depending on context.
13218 See the individual commands for more information."
13219 (interactive)
13220 (cond
13221 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13222 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13223 ((org-at-item-p) (call-interactively 'org-indent-item))
13224 (t (org-modifier-cursor-error))))
13226 (defun org-shiftmetaup (&optional arg)
13227 "Move subtree up or kill table row.
13228 Calls `org-move-subtree-up' or `org-table-kill-row' or
13229 `org-move-item-up' depending on context. See the individual commands
13230 for more information."
13231 (interactive "P")
13232 (cond
13233 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13234 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13235 ((org-at-item-p) (call-interactively 'org-move-item-up))
13236 (t (org-modifier-cursor-error))))
13237 (defun org-shiftmetadown (&optional arg)
13238 "Move subtree down or insert table row.
13239 Calls `org-move-subtree-down' or `org-table-insert-row' or
13240 `org-move-item-down', depending on context. See the individual
13241 commands for more information."
13242 (interactive "P")
13243 (cond
13244 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13245 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13246 ((org-at-item-p) (call-interactively 'org-move-item-down))
13247 (t (org-modifier-cursor-error))))
13249 (defun org-metaleft (&optional arg)
13250 "Promote heading or move table column to left.
13251 Calls `org-do-promote' or `org-table-move-column', depending on context.
13252 With no specific context, calls the Emacs default `backward-word'.
13253 See the individual commands for more information."
13254 (interactive "P")
13255 (cond
13256 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13257 ((or (org-on-heading-p) (org-region-active-p))
13258 (call-interactively 'org-do-promote))
13259 ((org-at-item-p) (call-interactively 'org-outdent-item))
13260 (t (call-interactively 'backward-word))))
13262 (defun org-metaright (&optional arg)
13263 "Demote subtree or move table column to right.
13264 Calls `org-do-demote' or `org-table-move-column', depending on context.
13265 With no specific context, calls the Emacs default `forward-word'.
13266 See the individual commands for more information."
13267 (interactive "P")
13268 (cond
13269 ((org-at-table-p) (call-interactively 'org-table-move-column))
13270 ((or (org-on-heading-p) (org-region-active-p))
13271 (call-interactively 'org-do-demote))
13272 ((org-at-item-p) (call-interactively 'org-indent-item))
13273 (t (call-interactively 'forward-word))))
13275 (defun org-metaup (&optional arg)
13276 "Move subtree up or move table row up.
13277 Calls `org-move-subtree-up' or `org-table-move-row' or
13278 `org-move-item-up', depending on context. See the individual commands
13279 for more information."
13280 (interactive "P")
13281 (cond
13282 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13283 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13284 ((org-at-item-p) (call-interactively 'org-move-item-up))
13285 (t (transpose-lines 1) (beginning-of-line -1))))
13287 (defun org-metadown (&optional arg)
13288 "Move subtree down or move table row down.
13289 Calls `org-move-subtree-down' or `org-table-move-row' or
13290 `org-move-item-down', depending on context. See the individual
13291 commands for more information."
13292 (interactive "P")
13293 (cond
13294 ((org-at-table-p) (call-interactively 'org-table-move-row))
13295 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13296 ((org-at-item-p) (call-interactively 'org-move-item-down))
13297 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13299 (defun org-shiftup (&optional arg)
13300 "Increase item in timestamp or increase priority of current headline.
13301 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13302 depending on context. See the individual commands for more information."
13303 (interactive "P")
13304 (cond
13305 ((and org-support-shift-select (org-region-active-p))
13306 (org-call-for-shift-select 'previous-line))
13307 ((org-at-timestamp-p t)
13308 (call-interactively (if org-edit-timestamp-down-means-later
13309 'org-timestamp-down 'org-timestamp-up)))
13310 ((and (not (eq org-support-shift-select 'always))
13311 (org-on-heading-p))
13312 (call-interactively 'org-priority-up))
13313 ((and (not org-support-shift-select) (org-at-item-p))
13314 (call-interactively 'org-previous-item))
13315 ((org-clocktable-try-shift 'up arg))
13316 (org-support-shift-select
13317 (org-call-for-shift-select 'previous-line))
13318 (t (org-shiftselect-error))))
13320 (defun org-shiftdown (&optional arg)
13321 "Decrease item in timestamp or decrease priority of current headline.
13322 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13323 depending on context. See the individual commands for more information."
13324 (interactive "P")
13325 (cond
13326 ((and org-support-shift-select (org-region-active-p))
13327 (org-call-for-shift-select 'next-line))
13328 ((org-at-timestamp-p t)
13329 (call-interactively (if org-edit-timestamp-down-means-later
13330 'org-timestamp-up 'org-timestamp-down)))
13331 ((and (not (eq org-support-shift-select 'always))
13332 (org-on-heading-p))
13333 (call-interactively 'org-priority-down))
13334 ((and (not org-support-shift-select) (org-at-item-p))
13335 (call-interactively 'org-next-item))
13336 ((org-clocktable-try-shift 'down arg))
13337 (org-support-shift-select
13338 (org-call-for-shift-select 'next-line))
13339 (t (org-shiftselect-error))))
13341 (defun org-shiftright (&optional arg)
13342 "Cycle the thing at point or in the current line, depending on context.
13343 Depending on context, this does one of the following:
13345 - switch a timestamp at point one day into the future
13346 - on a headline, switch to the next TODO keyword.
13347 - on an item, switch entire list to the next bullet type
13348 - on a property line, switch to the next allowed value
13349 - on a clocktable definition line, move time block into the future"
13350 (interactive "P")
13351 (cond
13352 ((and org-support-shift-select (org-region-active-p))
13353 (org-call-for-shift-select 'forward-char))
13354 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13355 ((and (not (eq org-support-shift-select 'always))
13356 (org-on-heading-p))
13357 (org-call-with-arg 'org-todo 'right))
13358 ((or (and org-support-shift-select
13359 (not (eq org-support-shift-select 'always))
13360 (org-at-item-bullet-p))
13361 (and (not org-support-shift-select) (org-at-item-p)))
13362 (org-call-with-arg 'org-cycle-list-bullet nil))
13363 ((and (not (eq org-support-shift-select 'always))
13364 (org-at-property-p))
13365 (call-interactively 'org-property-next-allowed-value))
13366 ((org-clocktable-try-shift 'right arg))
13367 (org-support-shift-select
13368 (org-call-for-shift-select 'forward-char))
13369 (t (org-shiftselect-error))))
13371 (defun org-shiftleft (&optional arg)
13372 "Cycle the thing at point or in the current line, depending on context.
13373 Depending on context, this does one of the following:
13375 - switch a timestamp at point one day into the past
13376 - on a headline, switch to the previous TODO keyword.
13377 - on an item, switch entire list to the previous bullet type
13378 - on a property line, switch to the previous allowed value
13379 - on a clocktable definition line, move time block into the past"
13380 (interactive "P")
13381 (cond
13382 ((and org-support-shift-select (org-region-active-p))
13383 (org-call-for-shift-select 'backward-char))
13384 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13385 ((and (not (eq org-support-shift-select 'always))
13386 (org-on-heading-p))
13387 (org-call-with-arg 'org-todo 'left))
13388 ((or (and org-support-shift-select
13389 (not (eq org-support-shift-select 'always))
13390 (org-at-item-bullet-p))
13391 (and (not org-support-shift-select) (org-at-item-p)))
13392 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13393 ((and (not (eq org-support-shift-select 'always))
13394 (org-at-property-p))
13395 (call-interactively 'org-property-previous-allowed-value))
13396 ((org-clocktable-try-shift 'left arg))
13397 (org-support-shift-select
13398 (org-call-for-shift-select 'backward-char))
13399 (t (org-shiftselect-error))))
13401 (defun org-shiftcontrolright ()
13402 "Switch to next TODO set."
13403 (interactive)
13404 (cond
13405 ((and org-support-shift-select (org-region-active-p))
13406 (org-call-for-shift-select 'forward-word))
13407 ((and (not (eq org-support-shift-select 'always))
13408 (org-on-heading-p))
13409 (org-call-with-arg 'org-todo 'nextset))
13410 (org-support-shift-select
13411 (org-call-for-shift-select 'forward-word))
13412 (t (org-shiftselect-error))))
13414 (defun org-shiftcontrolleft ()
13415 "Switch to previous TODO set."
13416 (interactive)
13417 (cond
13418 ((and org-support-shift-select (org-region-active-p))
13419 (org-call-for-shift-select 'backward-word))
13420 ((and (not (eq org-support-shift-select 'always))
13421 (org-on-heading-p))
13422 (org-call-with-arg 'org-todo 'previousset))
13423 (org-support-shift-select
13424 (org-call-for-shift-select 'backward-word))
13425 (t (org-shiftselect-error))))
13427 (defun org-ctrl-c-ret ()
13428 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13429 (interactive)
13430 (cond
13431 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13432 (t (call-interactively 'org-insert-heading))))
13434 (defun org-copy-special ()
13435 "Copy region in table or copy current subtree.
13436 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13437 See the individual commands for more information."
13438 (interactive)
13439 (call-interactively
13440 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13442 (defun org-cut-special ()
13443 "Cut region in table or cut current subtree.
13444 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13445 See the individual commands for more information."
13446 (interactive)
13447 (call-interactively
13448 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13450 (defun org-paste-special (arg)
13451 "Paste rectangular region into table, or past subtree relative to level.
13452 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13453 See the individual commands for more information."
13454 (interactive "P")
13455 (if (org-at-table-p)
13456 (org-table-paste-rectangle)
13457 (org-paste-subtree arg)))
13459 (defun org-edit-special ()
13460 "Call a special editor for the stuff at point.
13461 When at a table, call the formula editor with `org-table-edit-formulas'.
13462 When at the first line of an src example, call `org-edit-src-code'.
13463 When in an #+include line, visit the include file. Otherwise call
13464 `ffap' to visit the file at point."
13465 (interactive)
13466 (cond
13467 ((org-at-table-p)
13468 (call-interactively 'org-table-edit-formulas))
13469 ((save-excursion
13470 (beginning-of-line 1)
13471 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13472 (find-file (org-trim (match-string 1))))
13473 ((org-edit-src-code))
13474 ((org-edit-fixed-width-region))
13475 (t (call-interactively 'ffap))))
13477 (defun org-ctrl-c-ctrl-c (&optional arg)
13478 "Set tags in headline, or update according to changed information at point.
13480 This command does many different things, depending on context:
13482 - If the cursor is in a headline, prompt for tags and insert them
13483 into the current line, aligned to `org-tags-column'. When called
13484 with prefix arg, realign all tags in the current buffer.
13486 - If the cursor is in one of the special #+KEYWORD lines, this
13487 triggers scanning the buffer for these lines and updating the
13488 information.
13490 - If the cursor is inside a table, realign the table. This command
13491 works even if the automatic table editor has been turned off.
13493 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13494 the entire table.
13496 - If the cursor is at a footnote reference or definition, jump to
13497 the corresponding definition or references, respectively.
13499 - If the cursor is a the beginning of a dynamic block, update it.
13501 - If the cursor is inside a table created by the table.el package,
13502 activate that table.
13504 - If the current buffer is a remember buffer, close note and file
13505 it. A prefix argument of 1 files to the default location
13506 without further interaction. A prefix argument of 2 files to
13507 the currently clocking task.
13509 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13510 links in this buffer.
13512 - If the cursor is on a numbered item in a plain list, renumber the
13513 ordered list.
13515 - If the cursor is on a checkbox, toggle it."
13516 (interactive "P")
13517 (let ((org-enable-table-editor t))
13518 (cond
13519 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13520 org-occur-highlights
13521 org-latex-fragment-image-overlays)
13522 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13523 (org-remove-occur-highlights)
13524 (org-remove-latex-fragment-image-overlays)
13525 (message "Temporary highlights/overlays removed from current buffer"))
13526 ((and (local-variable-p 'org-finish-function (current-buffer))
13527 (fboundp org-finish-function))
13528 (funcall org-finish-function))
13529 ((org-at-property-p)
13530 (call-interactively 'org-property-action))
13531 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13532 ((org-on-heading-p) (call-interactively 'org-set-tags))
13533 ((org-at-table.el-p)
13534 (require 'table)
13535 (beginning-of-line 1)
13536 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13537 (call-interactively 'table-recognize-table))
13538 ((org-at-table-p)
13539 (org-table-maybe-eval-formula)
13540 (if arg
13541 (call-interactively 'org-table-recalculate)
13542 (org-table-maybe-recalculate-line))
13543 (call-interactively 'org-table-align))
13544 ((or (org-footnote-at-reference-p)
13545 (org-footnote-at-definition-p))
13546 (call-interactively 'org-footnote-action))
13547 ((org-at-item-checkbox-p)
13548 (call-interactively 'org-toggle-checkbox))
13549 ((org-at-item-p)
13550 (call-interactively 'org-maybe-renumber-ordered-list))
13551 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13552 ;; Dynamic block
13553 (beginning-of-line 1)
13554 (save-excursion (org-update-dblock)))
13555 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13556 (cond
13557 ((equal (match-string 1) "TBLFM")
13558 ;; Recalculate the table before this line
13559 (save-excursion
13560 (beginning-of-line 1)
13561 (skip-chars-backward " \r\n\t")
13562 (if (org-at-table-p)
13563 (org-call-with-arg 'org-table-recalculate t))))
13565 ; (org-set-regexps-and-options)
13566 ; (org-restart-font-lock)
13567 (let ((org-inhibit-startup t)) (org-mode-restart))
13568 (message "Local setup has been refreshed"))))
13569 (t (error "C-c C-c can do nothing useful at this location.")))))
13571 (defun org-mode-restart ()
13572 "Restart Org-mode, to scan again for special lines.
13573 Also updates the keyword regular expressions."
13574 (interactive)
13575 (org-mode)
13576 (message "Org-mode restarted"))
13578 (defun org-kill-note-or-show-branches ()
13579 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13580 (interactive)
13581 (if (not org-finish-function)
13582 (call-interactively 'show-branches)
13583 (let ((org-note-abort t))
13584 (funcall org-finish-function))))
13586 (defun org-return (&optional indent)
13587 "Goto next table row or insert a newline.
13588 Calls `org-table-next-row' or `newline', depending on context.
13589 See the individual commands for more information."
13590 (interactive)
13591 (cond
13592 ((bobp) (if indent (newline-and-indent) (newline)))
13593 ((org-at-table-p)
13594 (org-table-justify-field-maybe)
13595 (call-interactively 'org-table-next-row))
13596 ((and org-return-follows-link
13597 (eq (get-text-property (point) 'face) 'org-link))
13598 (call-interactively 'org-open-at-point))
13599 ((and (org-at-heading-p)
13600 (looking-at
13601 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13602 (org-show-entry)
13603 (end-of-line 1)
13604 (newline))
13605 (t (if indent (newline-and-indent) (newline)))))
13607 (defun org-return-indent ()
13608 "Goto next table row or insert a newline and indent.
13609 Calls `org-table-next-row' or `newline-and-indent', depending on
13610 context. See the individual commands for more information."
13611 (interactive)
13612 (org-return t))
13614 (defun org-ctrl-c-star ()
13615 "Compute table, or change heading status of lines.
13616 Calls `org-table-recalculate' or `org-toggle-heading',
13617 depending on context."
13618 (interactive)
13619 (cond
13620 ((org-at-table-p)
13621 (call-interactively 'org-table-recalculate))
13623 ;; Convert all lines in region to list items
13624 (call-interactively 'org-toggle-heading))))
13626 (defun org-ctrl-c-minus ()
13627 "Insert separator line in table or modify bullet status of line.
13628 Also turns a plain line or a region of lines into list items.
13629 Calls `org-table-insert-hline', `org-toggle-item', or
13630 `org-cycle-list-bullet', depending on context."
13631 (interactive)
13632 (cond
13633 ((org-at-table-p)
13634 (call-interactively 'org-table-insert-hline))
13635 ((org-region-active-p)
13636 (call-interactively 'org-toggle-item))
13637 ((org-in-item-p)
13638 (call-interactively 'org-cycle-list-bullet))
13640 (call-interactively 'org-toggle-item))))
13642 (defun org-toggle-item ()
13643 "Convert headings or normal lines to items, items to normal lines.
13644 If there is no active region, only the current line is considered.
13646 If the first line in the region is a headline, convert all headlines to items.
13648 If the first line in the region is an item, convert all items to normal lines.
13650 If the first line is normal text, add an item bullet to each line."
13651 (interactive)
13652 (let (l2 l beg end)
13653 (if (org-region-active-p)
13654 (setq beg (region-beginning) end (region-end))
13655 (setq beg (point-at-bol)
13656 end (min (1+ (point-at-eol)) (point-max))))
13657 (save-excursion
13658 (goto-char end)
13659 (setq l2 (org-current-line))
13660 (goto-char beg)
13661 (beginning-of-line 1)
13662 (setq l (1- (org-current-line)))
13663 (if (org-at-item-p)
13664 ;; We already have items, de-itemize
13665 (while (< (setq l (1+ l)) l2)
13666 (when (org-at-item-p)
13667 (goto-char (match-beginning 2))
13668 (delete-region (match-beginning 2) (match-end 2))
13669 (and (looking-at "[ \t]+") (replace-match "")))
13670 (beginning-of-line 2))
13671 (if (org-on-heading-p)
13672 ;; Headings, convert to items
13673 (while (< (setq l (1+ l)) l2)
13674 (if (looking-at org-outline-regexp)
13675 (replace-match "- " t t))
13676 (beginning-of-line 2))
13677 ;; normal lines, turn them into items
13678 (while (< (setq l (1+ l)) l2)
13679 (unless (org-at-item-p)
13680 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13681 (replace-match "\\1- \\2")))
13682 (beginning-of-line 2)))))))
13684 (defun org-toggle-heading (&optional nstars)
13685 "Convert headings to normal text, or items or text to headings.
13686 If there is no active region, only the current line is considered.
13688 If the first line is a heading, remove the stars from all headlines
13689 in the region.
13691 If the first line is a plain list item, turn all plain list items into
13692 headings.
13694 If the first line is a normal line, turn each and every line in the region
13695 into a heading.
13697 When converting a line into a heading, the number of stars is chosen
13698 such that the lines become children of the current entry. However, when
13699 a prefix argument is given, its value determines the number of stars to add."
13700 (interactive "P")
13701 (let (l2 l itemp beg end)
13702 (if (org-region-active-p)
13703 (setq beg (region-beginning) end (region-end))
13704 (setq beg (point-at-bol)
13705 end (min (1+ (point-at-eol)) (point-max))))
13706 (save-excursion
13707 (goto-char end)
13708 (setq l2 (org-current-line))
13709 (goto-char beg)
13710 (beginning-of-line 1)
13711 (setq l (1- (org-current-line)))
13712 (if (org-on-heading-p)
13713 ;; We already have headlines, de-star them
13714 (while (< (setq l (1+ l)) l2)
13715 (when (org-on-heading-p t)
13716 (and (looking-at outline-regexp) (replace-match "")))
13717 (beginning-of-line 2))
13718 (setq itemp (org-at-item-p))
13719 (let* ((stars
13720 (if nstars
13721 (make-string (prefix-numeric-value current-prefix-arg)
13723 (save-excursion
13724 (re-search-backward org-complex-heading-regexp nil t)
13725 (or (match-string 1) "*"))))
13726 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13727 (rpl (concat stars add-stars " ")))
13728 (while (< (setq l (1+ l)) l2)
13729 (if itemp
13730 (and (org-at-item-p) (replace-match rpl t t))
13731 (unless (org-on-heading-p)
13732 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13733 (replace-match (concat rpl (match-string 2))))))
13734 (beginning-of-line 2)))))))
13736 (defun org-meta-return (&optional arg)
13737 "Insert a new heading or wrap a region in a table.
13738 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13739 See the individual commands for more information."
13740 (interactive "P")
13741 (cond
13742 ((org-at-table-p)
13743 (call-interactively 'org-table-wrap-region))
13744 (t (call-interactively 'org-insert-heading))))
13746 ;;; Menu entries
13748 ;; Define the Org-mode menus
13749 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13750 '("Tbl"
13751 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13752 ["Next Field" org-cycle (org-at-table-p)]
13753 ["Previous Field" org-shifttab (org-at-table-p)]
13754 ["Next Row" org-return (org-at-table-p)]
13755 "--"
13756 ["Blank Field" org-table-blank-field (org-at-table-p)]
13757 ["Edit Field" org-table-edit-field (org-at-table-p)]
13758 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13759 "--"
13760 ("Column"
13761 ["Move Column Left" org-metaleft (org-at-table-p)]
13762 ["Move Column Right" org-metaright (org-at-table-p)]
13763 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13764 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13765 ("Row"
13766 ["Move Row Up" org-metaup (org-at-table-p)]
13767 ["Move Row Down" org-metadown (org-at-table-p)]
13768 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13769 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13770 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13771 "--"
13772 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13773 ("Rectangle"
13774 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13775 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13776 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13777 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13778 "--"
13779 ("Calculate"
13780 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13781 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13782 ["Edit Formulas" org-edit-special (org-at-table-p)]
13783 "--"
13784 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13785 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13786 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13787 "--"
13788 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13789 "--"
13790 ["Sum Column/Rectangle" org-table-sum
13791 (or (org-at-table-p) (org-region-active-p))]
13792 ["Which Column?" org-table-current-column (org-at-table-p)])
13793 ["Debug Formulas"
13794 org-table-toggle-formula-debugger
13795 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13796 ["Show Col/Row Numbers"
13797 org-table-toggle-coordinate-overlays
13798 :style toggle
13799 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13800 "--"
13801 ["Create" org-table-create (and (not (org-at-table-p))
13802 org-enable-table-editor)]
13803 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13804 ["Import from File" org-table-import (not (org-at-table-p))]
13805 ["Export to File" org-table-export (org-at-table-p)]
13806 "--"
13807 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13809 (easy-menu-define org-org-menu org-mode-map "Org menu"
13810 '("Org"
13811 ("Show/Hide"
13812 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13813 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13814 ["Sparse Tree..." org-sparse-tree t]
13815 ["Reveal Context" org-reveal t]
13816 ["Show All" show-all t]
13817 "--"
13818 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13819 "--"
13820 ["New Heading" org-insert-heading t]
13821 ("Navigate Headings"
13822 ["Up" outline-up-heading t]
13823 ["Next" outline-next-visible-heading t]
13824 ["Previous" outline-previous-visible-heading t]
13825 ["Next Same Level" outline-forward-same-level t]
13826 ["Previous Same Level" outline-backward-same-level t]
13827 "--"
13828 ["Jump" org-goto t])
13829 ("Edit Structure"
13830 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13831 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13832 "--"
13833 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13834 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13835 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13836 "--"
13837 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13838 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13839 ["Demote Heading" org-metaright (not (org-at-table-p))]
13840 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13841 "--"
13842 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13843 "--"
13844 ["Convert to odd levels" org-convert-to-odd-levels t]
13845 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13846 ("Editing"
13847 ["Emphasis..." org-emphasize t]
13848 ["Edit Source Example" org-edit-special t]
13849 "--"
13850 ["Footnote new/jump" org-footnote-action t]
13851 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13852 ("Archive"
13853 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13854 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13855 ; :active t :keys "C-u C-c C-x C-a"]
13856 ["Sparse trees open ARCHIVE trees"
13857 (setq org-sparse-tree-open-archived-trees
13858 (not org-sparse-tree-open-archived-trees))
13859 :style toggle :selected org-sparse-tree-open-archived-trees]
13860 ["Cycling opens ARCHIVE trees"
13861 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13862 :style toggle :selected org-cycle-open-archived-trees]
13863 "--"
13864 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13865 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13866 ; ["Check and Move Children" (org-archive-subtree '(4))
13867 ; :active t :keys "C-u C-c C-x C-s"]
13869 "--"
13870 ("TODO Lists"
13871 ["TODO/DONE/-" org-todo t]
13872 ("Select keyword"
13873 ["Next keyword" org-shiftright (org-on-heading-p)]
13874 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13875 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13876 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13877 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13878 ["Show TODO Tree" org-show-todo-tree t]
13879 ["Global TODO list" org-todo-list t]
13880 "--"
13881 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
13882 :selected org-enforce-todo-dependencies :style toggle :active t]
13883 "Settings for tree at point"
13884 ["Do Children sequentially" org-toggle-ordered-property :style radio
13885 :selected (ignore-errors (org-entry-get nil "ORDERED"))
13886 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13887 ["Do Children parallel" org-toggle-ordered-property :style radio
13888 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
13889 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13890 "--"
13891 ["Set Priority" org-priority t]
13892 ["Priority Up" org-shiftup t]
13893 ["Priority Down" org-shiftdown t])
13894 ("TAGS and Properties"
13895 ["Set Tags" org-set-tags-command t]
13896 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13897 "--"
13898 ["Set property" org-set-property t]
13899 ["Column view of properties" org-columns t]
13900 ["Insert Column View DBlock" org-insert-columns-dblock t])
13901 ("Dates and Scheduling"
13902 ["Timestamp" org-time-stamp t]
13903 ["Timestamp (inactive)" org-time-stamp-inactive t]
13904 ("Change Date"
13905 ["1 Day Later" org-shiftright t]
13906 ["1 Day Earlier" org-shiftleft t]
13907 ["1 ... Later" org-shiftup t]
13908 ["1 ... Earlier" org-shiftdown t])
13909 ["Compute Time Range" org-evaluate-time-range t]
13910 ["Schedule Item" org-schedule t]
13911 ["Deadline" org-deadline t]
13912 "--"
13913 ["Custom time format" org-toggle-time-stamp-overlays
13914 :style radio :selected org-display-custom-times]
13915 "--"
13916 ["Goto Calendar" org-goto-calendar t]
13917 ["Date from Calendar" org-date-from-calendar t]
13918 "--"
13919 ["Start/Restart Timer" org-timer-start t]
13920 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13921 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13922 ["Insert Timer String" org-timer t]
13923 ["Insert Timer Item" org-timer-item t])
13924 ("Logging work"
13925 ["Clock in" org-clock-in t]
13926 ["Clock out" org-clock-out t]
13927 ["Clock cancel" org-clock-cancel t]
13928 ["Goto running clock" org-clock-goto t]
13929 ["Display times" org-clock-display t]
13930 ["Create clock table" org-clock-report t]
13931 "--"
13932 ["Record DONE time"
13933 (progn (setq org-log-done (not org-log-done))
13934 (message "Switching to %s will %s record a timestamp"
13935 (car org-done-keywords)
13936 (if org-log-done "automatically" "not")))
13937 :style toggle :selected org-log-done])
13938 "--"
13939 ["Agenda Command..." org-agenda t]
13940 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13941 ("File List for Agenda")
13942 ("Special views current file"
13943 ["TODO Tree" org-show-todo-tree t]
13944 ["Check Deadlines" org-check-deadlines t]
13945 ["Timeline" org-timeline t]
13946 ["Tags Tree" org-tags-sparse-tree t])
13947 "--"
13948 ("Hyperlinks"
13949 ["Store Link (Global)" org-store-link t]
13950 ["Insert Link" org-insert-link t]
13951 ["Follow Link" org-open-at-point t]
13952 "--"
13953 ["Next link" org-next-link t]
13954 ["Previous link" org-previous-link t]
13955 "--"
13956 ["Descriptive Links"
13957 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13958 :style radio
13959 :selected (member '(org-link) buffer-invisibility-spec)]
13960 ["Literal Links"
13961 (progn
13962 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13963 :style radio
13964 :selected (not (member '(org-link) buffer-invisibility-spec))])
13965 "--"
13966 ["Export/Publish..." org-export t]
13967 ("LaTeX"
13968 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13969 :selected org-cdlatex-mode]
13970 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13971 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13972 ["Modify math symbol" org-cdlatex-math-modify
13973 (org-inside-LaTeX-fragment-p)]
13974 ["Export LaTeX fragments as images"
13975 (if (featurep 'org-exp)
13976 (setq org-export-with-LaTeX-fragments
13977 (not org-export-with-LaTeX-fragments))
13978 (require 'org-exp))
13979 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13980 org-export-with-LaTeX-fragments)])
13981 "--"
13982 ("Documentation"
13983 ["Show Version" org-version t]
13984 ["Info Documentation" org-info t])
13985 ("Customize"
13986 ["Browse Org Group" org-customize t]
13987 "--"
13988 ["Expand This Menu" org-create-customize-menu
13989 (fboundp 'customize-menu-create)])
13990 "--"
13991 ["Refresh setup" org-mode-restart t]
13994 (defun org-info (&optional node)
13995 "Read documentation for Org-mode in the info system.
13996 With optional NODE, go directly to that node."
13997 (interactive)
13998 (info (format "(org)%s" (or node ""))))
14000 (defun org-install-agenda-files-menu ()
14001 (let ((bl (buffer-list)))
14002 (save-excursion
14003 (while bl
14004 (set-buffer (pop bl))
14005 (if (org-mode-p) (setq bl nil)))
14006 (when (org-mode-p)
14007 (easy-menu-change
14008 '("Org") "File List for Agenda"
14009 (append
14010 (list
14011 ["Edit File List" (org-edit-agenda-file-list) t]
14012 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14013 ["Remove Current File from List" org-remove-file t]
14014 ["Cycle through agenda files" org-cycle-agenda-files t]
14015 ["Occur in all agenda files" org-occur-in-agenda-files t]
14016 "--")
14017 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14019 ;;;; Documentation
14021 ;;;###autoload
14022 (defun org-require-autoloaded-modules ()
14023 (interactive)
14024 (mapc 'require
14025 '(org-agenda org-archive org-attach org-clock org-colview
14026 org-exp org-id org-export-latex org-publish
14027 org-remember org-table org-timer)))
14029 ;;;###autoload
14030 (defun org-customize ()
14031 "Call the customize function with org as argument."
14032 (interactive)
14033 (org-load-modules-maybe)
14034 (org-require-autoloaded-modules)
14035 (customize-browse 'org))
14037 (defun org-create-customize-menu ()
14038 "Create a full customization menu for Org-mode, insert it into the menu."
14039 (interactive)
14040 (org-load-modules-maybe)
14041 (org-require-autoloaded-modules)
14042 (if (fboundp 'customize-menu-create)
14043 (progn
14044 (easy-menu-change
14045 '("Org") "Customize"
14046 `(["Browse Org group" org-customize t]
14047 "--"
14048 ,(customize-menu-create 'org)
14049 ["Set" Custom-set t]
14050 ["Save" Custom-save t]
14051 ["Reset to Current" Custom-reset-current t]
14052 ["Reset to Saved" Custom-reset-saved t]
14053 ["Reset to Standard Settings" Custom-reset-standard t]))
14054 (message "\"Org\"-menu now contains full customization menu"))
14055 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14057 ;;;; Miscellaneous stuff
14059 ;;; Generally useful functions
14061 (defun org-find-text-property-in-string (prop s)
14062 "Return the first non-nil value of property PROP in string S."
14063 (or (get-text-property 0 prop s)
14064 (get-text-property (or (next-single-property-change 0 prop s) 0)
14065 prop s)))
14067 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14068 "Display the given MESSAGE as a warning."
14069 (if (fboundp 'display-warning)
14070 (display-warning 'org message
14071 (if (featurep 'xemacs)
14072 'warning
14073 :warning))
14074 (let ((buf (get-buffer-create "*Org warnings*")))
14075 (with-current-buffer buf
14076 (goto-char (point-max))
14077 (insert "Warning (Org): " message)
14078 (unless (bolp)
14079 (newline)))
14080 (display-buffer buf)
14081 (sit-for 0))))
14083 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14084 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14085 (if (and marker (marker-buffer marker)
14086 (buffer-live-p (marker-buffer marker)))
14087 (progn
14088 (switch-to-buffer (marker-buffer marker))
14089 (if (or (> marker (point-max)) (< marker (point-min)))
14090 (widen))
14091 (goto-char marker)
14092 (org-show-context 'org-goto))
14093 (if bookmark
14094 (bookmark-jump bookmark)
14095 (error "Cannot find location"))))
14097 (defun org-quote-csv-field (s)
14098 "Quote field for inclusion in CSV material."
14099 (if (string-match "[\",]" s)
14100 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14103 (defun org-plist-delete (plist property)
14104 "Delete PROPERTY from PLIST.
14105 This is in contrast to merely setting it to 0."
14106 (let (p)
14107 (while plist
14108 (if (not (eq property (car plist)))
14109 (setq p (plist-put p (car plist) (nth 1 plist))))
14110 (setq plist (cddr plist)))
14113 (defun org-force-self-insert (N)
14114 "Needed to enforce self-insert under remapping."
14115 (interactive "p")
14116 (self-insert-command N))
14118 (defun org-string-width (s)
14119 "Compute width of string, ignoring invisible characters.
14120 This ignores character with invisibility property `org-link', and also
14121 characters with property `org-cwidth', because these will become invisible
14122 upon the next fontification round."
14123 (let (b l)
14124 (when (or (eq t buffer-invisibility-spec)
14125 (assq 'org-link buffer-invisibility-spec))
14126 (while (setq b (text-property-any 0 (length s)
14127 'invisible 'org-link s))
14128 (setq s (concat (substring s 0 b)
14129 (substring s (or (next-single-property-change
14130 b 'invisible s) (length s)))))))
14131 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14132 (setq s (concat (substring s 0 b)
14133 (substring s (or (next-single-property-change
14134 b 'org-cwidth s) (length s))))))
14135 (setq l (string-width s) b -1)
14136 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14137 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14140 (defun org-get-indentation (&optional line)
14141 "Get the indentation of the current line, interpreting tabs.
14142 When LINE is given, assume it represents a line and compute its indentation."
14143 (if line
14144 (if (string-match "^ *" (org-remove-tabs line))
14145 (match-end 0))
14146 (save-excursion
14147 (beginning-of-line 1)
14148 (skip-chars-forward " \t")
14149 (current-column))))
14151 (defun org-remove-tabs (s &optional width)
14152 "Replace tabulators in S with spaces.
14153 Assumes that s is a single line, starting in column 0."
14154 (setq width (or width tab-width))
14155 (while (string-match "\t" s)
14156 (setq s (replace-match
14157 (make-string
14158 (- (* width (/ (+ (match-beginning 0) width) width))
14159 (match-beginning 0)) ?\ )
14160 t t s)))
14163 (defun org-fix-indentation (line ind)
14164 "Fix indentation in LINE.
14165 IND is a cons cell with target and minimum indentation.
14166 If the current indentation in LINE is smaller than the minimum,
14167 leave it alone. If it is larger than ind, set it to the target."
14168 (let* ((l (org-remove-tabs line))
14169 (i (org-get-indentation l))
14170 (i1 (car ind)) (i2 (cdr ind)))
14171 (if (>= i i2) (setq l (substring line i2)))
14172 (if (> i1 0)
14173 (concat (make-string i1 ?\ ) l)
14174 l)))
14176 (defun org-base-buffer (buffer)
14177 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14178 (if (not buffer)
14179 buffer
14180 (or (buffer-base-buffer buffer)
14181 buffer)))
14183 (defun org-trim (s)
14184 "Remove whitespace at beginning and end of string."
14185 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14186 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14189 (defun org-wrap (string &optional width lines)
14190 "Wrap string to either a number of lines, or a width in characters.
14191 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14192 that costs. If there is a word longer than WIDTH, the text is actually
14193 wrapped to the length of that word.
14194 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14195 many lines, whatever width that takes.
14196 The return value is a list of lines, without newlines at the end."
14197 (let* ((words (org-split-string string "[ \t\n]+"))
14198 (maxword (apply 'max (mapcar 'org-string-width words)))
14199 w ll)
14200 (cond (width
14201 (org-do-wrap words (max maxword width)))
14202 (lines
14203 (setq w maxword)
14204 (setq ll (org-do-wrap words maxword))
14205 (if (<= (length ll) lines)
14207 (setq ll words)
14208 (while (> (length ll) lines)
14209 (setq w (1+ w))
14210 (setq ll (org-do-wrap words w)))
14211 ll))
14212 (t (error "Cannot wrap this")))))
14214 (defun org-do-wrap (words width)
14215 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14216 (let (lines line)
14217 (while words
14218 (setq line (pop words))
14219 (while (and words (< (+ (length line) (length (car words))) width))
14220 (setq line (concat line " " (pop words))))
14221 (setq lines (push line lines)))
14222 (nreverse lines)))
14224 (defun org-split-string (string &optional separators)
14225 "Splits STRING into substrings at SEPARATORS.
14226 No empty strings are returned if there are matches at the beginning
14227 and end of string."
14228 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14229 (start 0)
14230 notfirst
14231 (list nil))
14232 (while (and (string-match rexp string
14233 (if (and notfirst
14234 (= start (match-beginning 0))
14235 (< start (length string)))
14236 (1+ start) start))
14237 (< (match-beginning 0) (length string)))
14238 (setq notfirst t)
14239 (or (eq (match-beginning 0) 0)
14240 (and (eq (match-beginning 0) (match-end 0))
14241 (eq (match-beginning 0) start))
14242 (setq list
14243 (cons (substring string start (match-beginning 0))
14244 list)))
14245 (setq start (match-end 0)))
14246 (or (eq start (length string))
14247 (setq list
14248 (cons (substring string start)
14249 list)))
14250 (nreverse list)))
14252 (defun org-context ()
14253 "Return a list of contexts of the current cursor position.
14254 If several contexts apply, all are returned.
14255 Each context entry is a list with a symbol naming the context, and
14256 two positions indicating start and end of the context. Possible
14257 contexts are:
14259 :headline anywhere in a headline
14260 :headline-stars on the leading stars in a headline
14261 :todo-keyword on a TODO keyword (including DONE) in a headline
14262 :tags on the TAGS in a headline
14263 :priority on the priority cookie in a headline
14264 :item on the first line of a plain list item
14265 :item-bullet on the bullet/number of a plain list item
14266 :checkbox on the checkbox in a plain list item
14267 :table in an org-mode table
14268 :table-special on a special filed in a table
14269 :table-table in a table.el table
14270 :link on a hyperlink
14271 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14272 :target on a <<target>>
14273 :radio-target on a <<<radio-target>>>
14274 :latex-fragment on a LaTeX fragment
14275 :latex-preview on a LaTeX fragment with overlayed preview image
14277 This function expects the position to be visible because it uses font-lock
14278 faces as a help to recognize the following contexts: :table-special, :link,
14279 and :keyword."
14280 (let* ((f (get-text-property (point) 'face))
14281 (faces (if (listp f) f (list f)))
14282 (p (point)) clist o)
14283 ;; First the large context
14284 (cond
14285 ((org-on-heading-p t)
14286 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14287 (when (progn
14288 (beginning-of-line 1)
14289 (looking-at org-todo-line-tags-regexp))
14290 (push (org-point-in-group p 1 :headline-stars) clist)
14291 (push (org-point-in-group p 2 :todo-keyword) clist)
14292 (push (org-point-in-group p 4 :tags) clist))
14293 (goto-char p)
14294 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14295 (if (looking-at "\\[#[A-Z0-9]\\]")
14296 (push (org-point-in-group p 0 :priority) clist)))
14298 ((org-at-item-p)
14299 (push (org-point-in-group p 2 :item-bullet) clist)
14300 (push (list :item (point-at-bol)
14301 (save-excursion (org-end-of-item) (point)))
14302 clist)
14303 (and (org-at-item-checkbox-p)
14304 (push (org-point-in-group p 0 :checkbox) clist)))
14306 ((org-at-table-p)
14307 (push (list :table (org-table-begin) (org-table-end)) clist)
14308 (if (memq 'org-formula faces)
14309 (push (list :table-special
14310 (previous-single-property-change p 'face)
14311 (next-single-property-change p 'face)) clist)))
14312 ((org-at-table-p 'any)
14313 (push (list :table-table) clist)))
14314 (goto-char p)
14316 ;; Now the small context
14317 (cond
14318 ((org-at-timestamp-p)
14319 (push (org-point-in-group p 0 :timestamp) clist))
14320 ((memq 'org-link faces)
14321 (push (list :link
14322 (previous-single-property-change p 'face)
14323 (next-single-property-change p 'face)) clist))
14324 ((memq 'org-special-keyword faces)
14325 (push (list :keyword
14326 (previous-single-property-change p 'face)
14327 (next-single-property-change p 'face)) clist))
14328 ((org-on-target-p)
14329 (push (org-point-in-group p 0 :target) clist)
14330 (goto-char (1- (match-beginning 0)))
14331 (if (looking-at org-radio-target-regexp)
14332 (push (org-point-in-group p 0 :radio-target) clist))
14333 (goto-char p))
14334 ((setq o (car (delq nil
14335 (mapcar
14336 (lambda (x)
14337 (if (memq x org-latex-fragment-image-overlays) x))
14338 (org-overlays-at (point))))))
14339 (push (list :latex-fragment
14340 (org-overlay-start o) (org-overlay-end o)) clist)
14341 (push (list :latex-preview
14342 (org-overlay-start o) (org-overlay-end o)) clist))
14343 ((org-inside-LaTeX-fragment-p)
14344 ;; FIXME: positions wrong.
14345 (push (list :latex-fragment (point) (point)) clist)))
14347 (setq clist (nreverse (delq nil clist)))
14348 clist))
14350 ;; FIXME: Compare with at-regexp-p Do we need both?
14351 (defun org-in-regexp (re &optional nlines visually)
14352 "Check if point is inside a match of regexp.
14353 Normally only the current line is checked, but you can include NLINES extra
14354 lines both before and after point into the search.
14355 If VISUALLY is set, require that the cursor is not after the match but
14356 really on, so that the block visually is on the match."
14357 (catch 'exit
14358 (let ((pos (point))
14359 (eol (point-at-eol (+ 1 (or nlines 0))))
14360 (inc (if visually 1 0)))
14361 (save-excursion
14362 (beginning-of-line (- 1 (or nlines 0)))
14363 (while (re-search-forward re eol t)
14364 (if (and (<= (match-beginning 0) pos)
14365 (>= (+ inc (match-end 0)) pos))
14366 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14368 (defun org-at-regexp-p (regexp)
14369 "Is point inside a match of REGEXP in the current line?"
14370 (catch 'exit
14371 (save-excursion
14372 (let ((pos (point)) (end (point-at-eol)))
14373 (beginning-of-line 1)
14374 (while (re-search-forward regexp end t)
14375 (if (and (<= (match-beginning 0) pos)
14376 (>= (match-end 0) pos))
14377 (throw 'exit t)))
14378 nil))))
14380 (defun org-occur-in-agenda-files (regexp &optional nlines)
14381 "Call `multi-occur' with buffers for all agenda files."
14382 (interactive "sOrg-files matching: \np")
14383 (let* ((files (org-agenda-files))
14384 (tnames (mapcar 'file-truename files))
14385 (extra org-agenda-text-search-extra-files)
14387 (when (eq (car extra) 'agenda-archives)
14388 (setq extra (cdr extra))
14389 (setq files (org-add-archive-files files)))
14390 (while (setq f (pop extra))
14391 (unless (member (file-truename f) tnames)
14392 (add-to-list 'files f 'append)
14393 (add-to-list 'tnames (file-truename f) 'append)))
14394 (multi-occur
14395 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14396 regexp)))
14398 (if (boundp 'occur-mode-find-occurrence-hook)
14399 ;; Emacs 23
14400 (add-hook 'occur-mode-find-occurrence-hook
14401 (lambda ()
14402 (when (org-mode-p)
14403 (org-reveal))))
14404 ;; Emacs 22
14405 (defadvice occur-mode-goto-occurrence
14406 (after org-occur-reveal activate)
14407 (and (org-mode-p) (org-reveal)))
14408 (defadvice occur-mode-goto-occurrence-other-window
14409 (after org-occur-reveal activate)
14410 (and (org-mode-p) (org-reveal)))
14411 (defadvice occur-mode-display-occurrence
14412 (after org-occur-reveal activate)
14413 (when (org-mode-p)
14414 (let ((pos (occur-mode-find-occurrence)))
14415 (with-current-buffer (marker-buffer pos)
14416 (save-excursion
14417 (goto-char pos)
14418 (org-reveal)))))))
14420 (defun org-uniquify (list)
14421 "Remove duplicate elements from LIST."
14422 (let (res)
14423 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14424 res))
14426 (defun org-delete-all (elts list)
14427 "Remove all elements in ELTS from LIST."
14428 (while elts
14429 (setq list (delete (pop elts) list)))
14430 list)
14432 (defun org-back-over-empty-lines ()
14433 "Move backwards over whitespace, to the beginning of the first empty line.
14434 Returns the number of empty lines passed."
14435 (let ((pos (point)))
14436 (skip-chars-backward " \t\n\r")
14437 (beginning-of-line 2)
14438 (goto-char (min (point) pos))
14439 (count-lines (point) pos)))
14441 (defun org-skip-whitespace ()
14442 (skip-chars-forward " \t\n\r"))
14444 (defun org-point-in-group (point group &optional context)
14445 "Check if POINT is in match-group GROUP.
14446 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14447 match. If the match group does ot exist or point is not inside it,
14448 return nil."
14449 (and (match-beginning group)
14450 (>= point (match-beginning group))
14451 (<= point (match-end group))
14452 (if context
14453 (list context (match-beginning group) (match-end group))
14454 t)))
14456 (defun org-switch-to-buffer-other-window (&rest args)
14457 "Switch to buffer in a second window on the current frame.
14458 In particular, do not allow pop-up frames."
14459 (let (pop-up-frames special-display-buffer-names special-display-regexps
14460 special-display-function)
14461 (apply 'switch-to-buffer-other-window args)))
14463 (defun org-combine-plists (&rest plists)
14464 "Create a single property list from all plists in PLISTS.
14465 The process starts by copying the first list, and then setting properties
14466 from the other lists. Settings in the last list are the most significant
14467 ones and overrule settings in the other lists."
14468 (let ((rtn (copy-sequence (pop plists)))
14469 p v ls)
14470 (while plists
14471 (setq ls (pop plists))
14472 (while ls
14473 (setq p (pop ls) v (pop ls))
14474 (setq rtn (plist-put rtn p v))))
14475 rtn))
14477 (defun org-move-line-down (arg)
14478 "Move the current line down. With prefix argument, move it past ARG lines."
14479 (interactive "p")
14480 (let ((col (current-column))
14481 beg end pos)
14482 (beginning-of-line 1) (setq beg (point))
14483 (beginning-of-line 2) (setq end (point))
14484 (beginning-of-line (+ 1 arg))
14485 (setq pos (move-marker (make-marker) (point)))
14486 (insert (delete-and-extract-region beg end))
14487 (goto-char pos)
14488 (org-move-to-column col)))
14490 (defun org-move-line-up (arg)
14491 "Move the current line up. With prefix argument, move it past ARG lines."
14492 (interactive "p")
14493 (let ((col (current-column))
14494 beg end pos)
14495 (beginning-of-line 1) (setq beg (point))
14496 (beginning-of-line 2) (setq end (point))
14497 (beginning-of-line (- arg))
14498 (setq pos (move-marker (make-marker) (point)))
14499 (insert (delete-and-extract-region beg end))
14500 (goto-char pos)
14501 (org-move-to-column col)))
14503 (defun org-replace-escapes (string table)
14504 "Replace %-escapes in STRING with values in TABLE.
14505 TABLE is an association list with keys like \"%a\" and string values.
14506 The sequences in STRING may contain normal field width and padding information,
14507 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14508 so values can contain further %-escapes if they are define later in TABLE."
14509 (let ((case-fold-search nil)
14510 e re rpl)
14511 (while (setq e (pop table))
14512 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14513 (while (string-match re string)
14514 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14515 (cdr e)))
14516 (setq string (replace-match rpl t t string))))
14517 string))
14520 (defun org-sublist (list start end)
14521 "Return a section of LIST, from START to END.
14522 Counting starts at 1."
14523 (let (rtn (c start))
14524 (setq list (nthcdr (1- start) list))
14525 (while (and list (<= c end))
14526 (push (pop list) rtn)
14527 (setq c (1+ c)))
14528 (nreverse rtn)))
14530 (defun org-find-base-buffer-visiting (file)
14531 "Like `find-buffer-visiting' but alway return the base buffer and
14532 not an indirect buffer."
14533 (let ((buf (find-buffer-visiting file)))
14534 (if buf
14535 (or (buffer-base-buffer buf) buf)
14536 nil)))
14538 (defun org-image-file-name-regexp (&optional extensions)
14539 "Return regexp matching the file names of images.
14540 If EXTENSIONS is given, only match these."
14541 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14542 (image-file-name-regexp)
14543 (let ((image-file-name-extensions
14544 (or extensions
14545 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14546 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14547 (concat "\\."
14548 (regexp-opt (nconc (mapcar 'upcase
14549 image-file-name-extensions)
14550 image-file-name-extensions)
14552 "\\'"))))
14554 (defun org-file-image-p (file &optional extensions)
14555 "Return non-nil if FILE is an image."
14556 (save-match-data
14557 (string-match (org-image-file-name-regexp extensions) file)))
14559 (defun org-get-cursor-date ()
14560 "Return the date at cursor in as a time.
14561 This works in the calendar and in the agenda, anywhere else it just
14562 returns the current time."
14563 (let (date day defd)
14564 (cond
14565 ((eq major-mode 'calendar-mode)
14566 (setq date (calendar-cursor-to-date)
14567 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14568 ((eq major-mode 'org-agenda-mode)
14569 (setq day (get-text-property (point) 'day))
14570 (if day
14571 (setq date (calendar-gregorian-from-absolute day)
14572 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14573 (nth 2 date))))))
14574 (or defd (current-time))))
14576 (defvar org-agenda-action-marker (make-marker)
14577 "Marker pointing to the entry for the next agenda action.")
14579 (defun org-mark-entry-for-agenda-action ()
14580 "Mark the current entry as target of an agenda action.
14581 Agenda actions are actions executed from the agenda with the key `k',
14582 which make use of the date at the cursor."
14583 (interactive)
14584 (move-marker org-agenda-action-marker
14585 (save-excursion (org-back-to-heading t) (point))
14586 (current-buffer))
14587 (message
14588 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14590 ;;; Paragraph filling stuff.
14591 ;; We want this to be just right, so use the full arsenal.
14593 (defun org-indent-line-function ()
14594 "Indent line like previous, but further if previous was headline or item."
14595 (interactive)
14596 (let* ((pos (point))
14597 (itemp (org-at-item-p))
14598 column bpos bcol tpos tcol bullet btype bullet-type)
14599 ;; Find the previous relevant line
14600 (beginning-of-line 1)
14601 (cond
14602 ((looking-at "#") (setq column 0))
14603 ((looking-at "\\*+ ") (setq column 0))
14605 (beginning-of-line 0)
14606 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14607 (beginning-of-line 0))
14608 (cond
14609 ((looking-at "\\*+[ \t]+")
14610 (if (not org-adapt-indentation)
14611 (setq column 0)
14612 (goto-char (match-end 0))
14613 (setq column (current-column))))
14614 ((org-in-item-p)
14615 (org-beginning-of-item)
14616 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14617 (setq bpos (match-beginning 1) tpos (match-end 0)
14618 bcol (progn (goto-char bpos) (current-column))
14619 tcol (progn (goto-char tpos) (current-column))
14620 bullet (match-string 1)
14621 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14622 (if (> tcol (+ bcol org-description-max-indent))
14623 (setq tcol (+ bcol 5)))
14624 (if (not itemp)
14625 (setq column tcol)
14626 (goto-char pos)
14627 (beginning-of-line 1)
14628 (if (looking-at "\\S-")
14629 (progn
14630 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14631 (setq bullet (match-string 1)
14632 btype (if (string-match "[0-9]" bullet) "n" bullet))
14633 (setq column (if (equal btype bullet-type) bcol tcol)))
14634 (setq column (org-get-indentation)))))
14635 (t (setq column (org-get-indentation))))))
14636 (goto-char pos)
14637 (if (<= (current-column) (current-indentation))
14638 (org-indent-line-to column)
14639 (save-excursion (org-indent-line-to column)))
14640 (setq column (current-column))
14641 (beginning-of-line 1)
14642 (if (looking-at
14643 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14644 (replace-match (concat "\\1" (format org-property-format
14645 (match-string 2) (match-string 3)))
14646 t nil))
14647 (org-move-to-column column)))
14649 (defun org-set-autofill-regexps ()
14650 (interactive)
14651 ;; In the paragraph separator we include headlines, because filling
14652 ;; text in a line directly attached to a headline would otherwise
14653 ;; fill the headline as well.
14654 (org-set-local 'comment-start-skip "^#+[ \t]*")
14655 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14656 ;; The paragraph starter includes hand-formatted lists.
14657 (org-set-local 'paragraph-start
14658 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14659 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14660 ;; But only if the user has not turned off tables or fixed-width regions
14661 (org-set-local
14662 'auto-fill-inhibit-regexp
14663 (concat "\\*+ \\|#\\+"
14664 "\\|[ \t]*" org-keyword-time-regexp
14665 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14666 (concat
14667 "\\|[ \t]*["
14668 (if org-enable-table-editor "|" "")
14669 (if org-enable-fixed-width-editor ":" "")
14670 "]"))))
14671 ;; We use our own fill-paragraph function, to make sure that tables
14672 ;; and fixed-width regions are not wrapped. That function will pass
14673 ;; through to `fill-paragraph' when appropriate.
14674 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14675 ; Adaptive filling: To get full control, first make sure that
14676 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14677 (org-set-local 'adaptive-fill-regexp "\000")
14678 (org-set-local 'adaptive-fill-function
14679 'org-adaptive-fill-function)
14680 (org-set-local
14681 'align-mode-rules-list
14682 '((org-in-buffer-settings
14683 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14684 (modes . '(org-mode))))))
14686 (defun org-fill-paragraph (&optional justify)
14687 "Re-align a table, pass through to fill-paragraph if no table."
14688 (let ((table-p (org-at-table-p))
14689 (table.el-p (org-at-table.el-p)))
14690 (cond ((and (equal (char-after (point-at-bol)) ?*)
14691 (save-excursion (goto-char (point-at-bol))
14692 (looking-at outline-regexp)))
14693 t) ; skip headlines
14694 (table.el-p t) ; skip table.el tables
14695 (table-p (org-table-align) t) ; align org-mode tables
14696 (t nil)))) ; call paragraph-fill
14698 ;; For reference, this is the default value of adaptive-fill-regexp
14699 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14701 (defun org-adaptive-fill-function ()
14702 "Return a fill prefix for org-mode files.
14703 In particular, this makes sure hanging paragraphs for hand-formatted lists
14704 work correctly."
14705 (cond ((looking-at "#[ \t]+")
14706 (match-string 0))
14707 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14708 (save-excursion
14709 (if (> (match-end 1) (+ (match-beginning 1)
14710 org-description-max-indent))
14711 (goto-char (+ (match-beginning 1) 5))
14712 (goto-char (match-end 0)))
14713 (make-string (current-column) ?\ )))
14714 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14715 (save-excursion
14716 (goto-char (match-end 0))
14717 (make-string (current-column) ?\ )))
14718 (t nil)))
14720 ;;; Other stuff.
14722 (defun org-toggle-fixed-width-section (arg)
14723 "Toggle the fixed-width export.
14724 If there is no active region, the QUOTE keyword at the current headline is
14725 inserted or removed. When present, it causes the text between this headline
14726 and the next to be exported as fixed-width text, and unmodified.
14727 If there is an active region, this command adds or removes a colon as the
14728 first character of this line. If the first character of a line is a colon,
14729 this line is also exported in fixed-width font."
14730 (interactive "P")
14731 (let* ((cc 0)
14732 (regionp (org-region-active-p))
14733 (beg (if regionp (region-beginning) (point)))
14734 (end (if regionp (region-end)))
14735 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14736 (case-fold-search nil)
14737 (re "[ \t]*\\(:\\)")
14738 off)
14739 (if regionp
14740 (save-excursion
14741 (goto-char beg)
14742 (setq cc (current-column))
14743 (beginning-of-line 1)
14744 (setq off (looking-at re))
14745 (while (> nlines 0)
14746 (setq nlines (1- nlines))
14747 (beginning-of-line 1)
14748 (cond
14749 (arg
14750 (org-move-to-column cc t)
14751 (insert ":\n")
14752 (forward-line -1))
14753 ((and off (looking-at re))
14754 (replace-match "" t t nil 1))
14755 ((not off) (org-move-to-column cc t) (insert ":")))
14756 (forward-line 1)))
14757 (save-excursion
14758 (org-back-to-heading)
14759 (if (looking-at (concat outline-regexp
14760 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14761 (replace-match "" t t nil 1)
14762 (if (looking-at outline-regexp)
14763 (progn
14764 (goto-char (match-end 0))
14765 (insert org-quote-string " "))))))))
14767 ;;;; Functions extending outline functionality
14769 (defun org-beginning-of-line (&optional arg)
14770 "Go to the beginning of the current line. If that is invisible, continue
14771 to a visible line beginning. This makes the function of C-a more intuitive.
14772 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14773 first attempt, and only move to after the tags when the cursor is already
14774 beyond the end of the headline."
14775 (interactive "P")
14776 (let ((pos (point)) refpos)
14777 (beginning-of-line 1)
14778 (if (bobp)
14780 (backward-char 1)
14781 (if (org-invisible-p)
14782 (while (and (not (bobp)) (org-invisible-p))
14783 (backward-char 1)
14784 (beginning-of-line 1))
14785 (forward-char 1)))
14786 (when org-special-ctrl-a/e
14787 (cond
14788 ((and (looking-at org-complex-heading-regexp)
14789 (= (char-after (match-end 1)) ?\ ))
14790 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14791 (point-at-eol)))
14792 (goto-char
14793 (if (eq org-special-ctrl-a/e t)
14794 (cond ((> pos refpos) refpos)
14795 ((= pos (point)) refpos)
14796 (t (point)))
14797 (cond ((> pos (point)) (point))
14798 ((not (eq last-command this-command)) (point))
14799 (t refpos)))))
14800 ((org-at-item-p)
14801 (goto-char
14802 (if (eq org-special-ctrl-a/e t)
14803 (cond ((> pos (match-end 4)) (match-end 4))
14804 ((= pos (point)) (match-end 4))
14805 (t (point)))
14806 (cond ((> pos (point)) (point))
14807 ((not (eq last-command this-command)) (point))
14808 (t (match-end 4))))))))
14809 (org-no-warnings
14810 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14812 (defun org-end-of-line (&optional arg)
14813 "Go to the end of the line.
14814 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14815 first attempt, and only move to after the tags when the cursor is already
14816 beyond the end of the headline."
14817 (interactive "P")
14818 (if (or (not org-special-ctrl-a/e)
14819 (not (org-on-heading-p)))
14820 (end-of-line arg)
14821 (let ((pos (point)))
14822 (beginning-of-line 1)
14823 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14824 (if (eq org-special-ctrl-a/e t)
14825 (if (or (< pos (match-beginning 1))
14826 (= pos (match-end 0)))
14827 (goto-char (match-beginning 1))
14828 (goto-char (match-end 0)))
14829 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14830 (goto-char (match-end 0))
14831 (goto-char (match-beginning 1))))
14832 (end-of-line arg))))
14833 (org-no-warnings
14834 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14837 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14838 (define-key org-mode-map "\C-e" 'org-end-of-line)
14840 (defun org-kill-line (&optional arg)
14841 "Kill line, to tags or end of line."
14842 (interactive "P")
14843 (cond
14844 ((or (not org-special-ctrl-k)
14845 (bolp)
14846 (not (org-on-heading-p)))
14847 (call-interactively 'kill-line))
14848 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14849 (kill-region (point) (match-beginning 1))
14850 (org-set-tags nil t))
14851 (t (kill-region (point) (point-at-eol)))))
14853 (define-key org-mode-map "\C-k" 'org-kill-line)
14855 (defun org-yank (&optional arg)
14856 "Yank. If the kill is a subtree, treat it specially.
14857 This command will look at the current kill and check if is a single
14858 subtree, or a series of subtrees[1]. If it passes the test, and if the
14859 cursor is at the beginning of a line or after the stars of a currently
14860 empty headline, then the yank is handled specially. How exactly depends
14861 on the value of the following variables, both set by default.
14863 org-yank-folded-subtrees
14864 When set, the subtree(s) will be folded after insertion, but only
14865 if doing so would now swallow text after the yanked text.
14867 org-yank-adjusted-subtrees
14868 When set, the subtree will be promoted or demoted in order to
14869 fit into the local outline tree structure, which means that the level
14870 will be adjusted so that it becomes the smaller one of the two
14871 *visible* surrounding headings.
14873 Any prefix to this command will cause `yank' to be called directly with
14874 no special treatment. In particular, a simple `C-u' prefix will just
14875 plainly yank the text as it is.
14877 \[1] Basically, the test checks if the first non-white line is a heading
14878 and if there are no other headings with fewer stars."
14879 (interactive "P")
14880 (setq this-command 'yank)
14881 (if arg
14882 (call-interactively 'yank)
14883 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14884 (and (org-kill-is-subtree-p)
14885 (or (bolp)
14886 (and (looking-at "[ \t]*$")
14887 (string-match
14888 "\\`\\*+\\'"
14889 (buffer-substring (point-at-bol) (point)))))))
14890 swallowp)
14891 (cond
14892 ((and subtreep org-yank-folded-subtrees)
14893 (let ((beg (point))
14894 end)
14895 (if (and subtreep org-yank-adjusted-subtrees)
14896 (org-paste-subtree nil nil 'for-yank)
14897 (call-interactively 'yank))
14898 (setq end (point))
14899 (goto-char beg)
14900 (when (and (bolp) subtreep
14901 (not (setq swallowp
14902 (org-yank-folding-would-swallow-text beg end))))
14903 (or (looking-at outline-regexp)
14904 (re-search-forward (concat "^" outline-regexp) end t))
14905 (while (and (< (point) end) (looking-at outline-regexp))
14906 (hide-subtree)
14907 (org-cycle-show-empty-lines 'folded)
14908 (condition-case nil
14909 (outline-forward-same-level 1)
14910 (error (goto-char end)))))
14911 (when swallowp
14912 (message
14913 "Yanked text not folded because that would swallow text"))
14914 (goto-char end)
14915 (skip-chars-forward " \t\n\r")
14916 (beginning-of-line 1)
14917 (push-mark beg 'nomsg)))
14918 ((and subtreep org-yank-adjusted-subtrees)
14919 (let ((beg (point-at-bol)))
14920 (org-paste-subtree nil nil 'for-yank)
14921 (push-mark beg 'nomsg)))
14923 (call-interactively 'yank))))))
14925 (defun org-yank-folding-would-swallow-text (beg end)
14926 "Would hide-subtree at BEG swallow any text after END?"
14927 (let (level)
14928 (save-excursion
14929 (goto-char beg)
14930 (when (or (looking-at outline-regexp)
14931 (re-search-forward (concat "^" outline-regexp) end t))
14932 (setq level (org-outline-level)))
14933 (goto-char end)
14934 (skip-chars-forward " \t\r\n\v\f")
14935 (if (or (eobp)
14936 (and (bolp) (looking-at org-outline-regexp)
14937 (<= (org-outline-level) level)))
14938 nil ; Nothing would be swallowed
14939 t)))) ; something would swallow
14941 (define-key org-mode-map "\C-y" 'org-yank)
14943 (defun org-invisible-p ()
14944 "Check if point is at a character currently not visible."
14945 ;; Early versions of noutline don't have `outline-invisible-p'.
14946 (if (fboundp 'outline-invisible-p)
14947 (outline-invisible-p)
14948 (get-char-property (point) 'invisible)))
14950 (defun org-invisible-p2 ()
14951 "Check if point is at a character currently not visible."
14952 (save-excursion
14953 (if (and (eolp) (not (bobp))) (backward-char 1))
14954 ;; Early versions of noutline don't have `outline-invisible-p'.
14955 (if (fboundp 'outline-invisible-p)
14956 (outline-invisible-p)
14957 (get-char-property (point) 'invisible))))
14959 (defun org-back-to-heading (&optional invisible-ok)
14960 "Call `outline-back-to-heading', but provide a better error message."
14961 (condition-case nil
14962 (outline-back-to-heading invisible-ok)
14963 (error (error "Before first headline at position %d in buffer %s"
14964 (point) (current-buffer)))))
14966 (defun org-before-first-heading-p ()
14967 "Before first heading?"
14968 (save-excursion
14969 (null (re-search-backward "^\\*+ " nil t))))
14971 (defalias 'org-on-heading-p 'outline-on-heading-p)
14972 (defalias 'org-at-heading-p 'outline-on-heading-p)
14973 (defun org-at-heading-or-item-p ()
14974 (or (org-on-heading-p) (org-at-item-p)))
14976 (defun org-on-target-p ()
14977 (or (org-in-regexp org-radio-target-regexp)
14978 (org-in-regexp org-target-regexp)))
14980 (defun org-up-heading-all (arg)
14981 "Move to the heading line of which the present line is a subheading.
14982 This function considers both visible and invisible heading lines.
14983 With argument, move up ARG levels."
14984 (if (fboundp 'outline-up-heading-all)
14985 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14986 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14988 (defun org-up-heading-safe ()
14989 "Move to the heading line of which the present line is a subheading.
14990 This version will not throw an error. It will return the level of the
14991 headline found, or nil if no higher level is found."
14992 (let (start-level re)
14993 (org-back-to-heading t)
14994 (setq start-level (funcall outline-level))
14995 (if (equal start-level 1)
14997 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14998 (if (re-search-backward re nil t)
14999 (funcall outline-level)))))
15001 (defun org-first-sibling-p ()
15002 "Is this heading the first child of its parents?"
15003 (interactive)
15004 (let ((re (concat "^" outline-regexp))
15005 level l)
15006 (unless (org-at-heading-p t)
15007 (error "Not at a heading"))
15008 (setq level (funcall outline-level))
15009 (save-excursion
15010 (if (not (re-search-backward re nil t))
15012 (setq l (funcall outline-level))
15013 (< l level)))))
15015 (defun org-goto-sibling (&optional previous)
15016 "Goto the next sibling, even if it is invisible.
15017 When PREVIOUS is set, go to the previous sibling instead. Returns t
15018 when a sibling was found. When none is found, return nil and don't
15019 move point."
15020 (let ((fun (if previous 're-search-backward 're-search-forward))
15021 (pos (point))
15022 (re (concat "^" outline-regexp))
15023 level l)
15024 (when (condition-case nil (org-back-to-heading t) (error nil))
15025 (setq level (funcall outline-level))
15026 (catch 'exit
15027 (or previous (forward-char 1))
15028 (while (funcall fun re nil t)
15029 (setq l (funcall outline-level))
15030 (when (< l level) (goto-char pos) (throw 'exit nil))
15031 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15032 (goto-char pos)
15033 nil))))
15035 (defun org-show-siblings ()
15036 "Show all siblings of the current headline."
15037 (save-excursion
15038 (while (org-goto-sibling) (org-flag-heading nil)))
15039 (save-excursion
15040 (while (org-goto-sibling 'previous)
15041 (org-flag-heading nil))))
15043 (defun org-show-hidden-entry ()
15044 "Show an entry where even the heading is hidden."
15045 (save-excursion
15046 (org-show-entry)))
15048 (defun org-flag-heading (flag &optional entry)
15049 "Flag the current heading. FLAG non-nil means make invisible.
15050 When ENTRY is non-nil, show the entire entry."
15051 (save-excursion
15052 (org-back-to-heading t)
15053 ;; Check if we should show the entire entry
15054 (if entry
15055 (progn
15056 (org-show-entry)
15057 (save-excursion
15058 (and (outline-next-heading)
15059 (org-flag-heading nil))))
15060 (outline-flag-region (max (point-min) (1- (point)))
15061 (save-excursion (outline-end-of-heading) (point))
15062 flag))))
15064 (defun org-forward-same-level (arg)
15065 "Move forward to the ARG'th subheading at same level as this one.
15066 Stop at the first and last subheadings of a superior heading.
15067 This is like outline-forward-same-level, but invisible headings are ok."
15068 (interactive "p")
15069 (org-back-to-heading t)
15070 (while (> arg 0)
15071 (let ((point-to-move-to (save-excursion
15072 (org-get-next-sibling))))
15073 (if point-to-move-to
15074 (progn
15075 (goto-char point-to-move-to)
15076 (setq arg (1- arg)))
15077 (progn
15078 (setq arg 0)
15079 (error "No following same-level heading"))))))
15081 (defun org-get-next-sibling ()
15082 "Move to next heading of the same level, and return point.
15083 If there is no such heading, return nil.
15084 This is like outline-next-sibling, but invisible headings are ok."
15085 (let ((level (funcall outline-level)))
15086 (outline-next-heading)
15087 (while (and (not (eobp)) (> (funcall outline-level) level))
15088 (outline-next-heading))
15089 (if (or (eobp) (< (funcall outline-level) level))
15091 (point))))
15093 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15094 ;; This is an exact copy of the original function, but it uses
15095 ;; `org-back-to-heading', to make it work also in invisible
15096 ;; trees. And is uses an invisible-OK argument.
15097 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15098 (org-back-to-heading invisible-OK)
15099 (let ((first t)
15100 (level (funcall outline-level)))
15101 (while (and (not (eobp))
15102 (or first (> (funcall outline-level) level)))
15103 (setq first nil)
15104 (outline-next-heading))
15105 (unless to-heading
15106 (if (memq (preceding-char) '(?\n ?\^M))
15107 (progn
15108 ;; Go to end of line before heading
15109 (forward-char -1)
15110 (if (memq (preceding-char) '(?\n ?\^M))
15111 ;; leave blank line before heading
15112 (forward-char -1))))))
15113 (point))
15115 (defun org-show-subtree ()
15116 "Show everything after this heading at deeper levels."
15117 (outline-flag-region
15118 (point)
15119 (save-excursion
15120 (outline-end-of-subtree) (outline-next-heading) (point))
15121 nil))
15123 (defun org-show-entry ()
15124 "Show the body directly following this heading.
15125 Show the heading too, if it is currently invisible."
15126 (interactive)
15127 (save-excursion
15128 (condition-case nil
15129 (progn
15130 (org-back-to-heading t)
15131 (outline-flag-region
15132 (max (point-min) (1- (point)))
15133 (save-excursion
15134 (re-search-forward
15135 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
15136 (or (match-beginning 1) (point-max)))
15137 nil))
15138 (error nil))))
15140 (defun org-make-options-regexp (kwds &optional extra)
15141 "Make a regular expression for keyword lines."
15142 (concat
15144 "#?[ \t]*\\+\\("
15145 (mapconcat 'regexp-quote kwds "\\|")
15146 (if extra (concat "\\|" extra))
15147 "\\):[ \t]*"
15148 "\\(.+\\)"))
15150 ;; Make isearch reveal the necessary context
15151 (defun org-isearch-end ()
15152 "Reveal context after isearch exits."
15153 (when isearch-success ; only if search was successful
15154 (if (featurep 'xemacs)
15155 ;; Under XEmacs, the hook is run in the correct place,
15156 ;; we directly show the context.
15157 (org-show-context 'isearch)
15158 ;; In Emacs the hook runs *before* restoring the overlays.
15159 ;; So we have to use a one-time post-command-hook to do this.
15160 ;; (Emacs 22 has a special variable, see function `org-mode')
15161 (unless (and (boundp 'isearch-mode-end-hook-quit)
15162 isearch-mode-end-hook-quit)
15163 ;; Only when the isearch was not quitted.
15164 (org-add-hook 'post-command-hook 'org-isearch-post-command
15165 'append 'local)))))
15167 (defun org-isearch-post-command ()
15168 "Remove self from hook, and show context."
15169 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15170 (org-show-context 'isearch))
15173 ;;;; Integration with and fixes for other packages
15175 ;;; Imenu support
15177 (defvar org-imenu-markers nil
15178 "All markers currently used by Imenu.")
15179 (make-variable-buffer-local 'org-imenu-markers)
15181 (defun org-imenu-new-marker (&optional pos)
15182 "Return a new marker for use by Imenu, and remember the marker."
15183 (let ((m (make-marker)))
15184 (move-marker m (or pos (point)))
15185 (push m org-imenu-markers)
15188 (defun org-imenu-get-tree ()
15189 "Produce the index for Imenu."
15190 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15191 (setq org-imenu-markers nil)
15192 (let* ((n org-imenu-depth)
15193 (re (concat "^" outline-regexp))
15194 (subs (make-vector (1+ n) nil))
15195 (last-level 0)
15196 m level head)
15197 (save-excursion
15198 (save-restriction
15199 (widen)
15200 (goto-char (point-max))
15201 (while (re-search-backward re nil t)
15202 (setq level (org-reduced-level (funcall outline-level)))
15203 (when (<= level n)
15204 (looking-at org-complex-heading-regexp)
15205 (setq head (org-link-display-format
15206 (org-match-string-no-properties 4))
15207 m (org-imenu-new-marker))
15208 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15209 (if (>= level last-level)
15210 (push (cons head m) (aref subs level))
15211 (push (cons head (aref subs (1+ level))) (aref subs level))
15212 (loop for i from (1+ level) to n do (aset subs i nil)))
15213 (setq last-level level)))))
15214 (aref subs 1)))
15216 (eval-after-load "imenu"
15217 '(progn
15218 (add-hook 'imenu-after-jump-hook
15219 (lambda ()
15220 (if (eq major-mode 'org-mode)
15221 (org-show-context 'org-goto))))))
15223 (defun org-link-display-format (link)
15224 "Replace a link with either the description, or the link target
15225 if no description is present"
15226 (save-match-data
15227 (if (string-match org-bracket-link-analytic-regexp link)
15228 (replace-match (or (match-string 5 link)
15229 (concat (match-string 1 link)
15230 (match-string 3 link)))
15231 nil nil link)
15232 link)))
15234 ;; Speedbar support
15236 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15237 "Overlay marking the agenda restriction line in speedbar.")
15238 (org-overlay-put org-speedbar-restriction-lock-overlay
15239 'face 'org-agenda-restriction-lock)
15240 (org-overlay-put org-speedbar-restriction-lock-overlay
15241 'help-echo "Agendas are currently limited to this item.")
15242 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15244 (defun org-speedbar-set-agenda-restriction ()
15245 "Restrict future agenda commands to the location at point in speedbar.
15246 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15247 (interactive)
15248 (require 'org-agenda)
15249 (let (p m tp np dir txt)
15250 (cond
15251 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15252 'org-imenu t))
15253 (setq m (get-text-property p 'org-imenu-marker))
15254 (save-excursion
15255 (save-restriction
15256 (set-buffer (marker-buffer m))
15257 (goto-char m)
15258 (org-agenda-set-restriction-lock 'subtree))))
15259 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15260 'speedbar-function 'speedbar-find-file))
15261 (setq tp (previous-single-property-change
15262 (1+ p) 'speedbar-function)
15263 np (next-single-property-change
15264 tp 'speedbar-function)
15265 dir (speedbar-line-directory)
15266 txt (buffer-substring-no-properties (or tp (point-min))
15267 (or np (point-max))))
15268 (save-excursion
15269 (save-restriction
15270 (set-buffer (find-file-noselect
15271 (let ((default-directory dir))
15272 (expand-file-name txt))))
15273 (unless (org-mode-p)
15274 (error "Cannot restrict to non-Org-mode file"))
15275 (org-agenda-set-restriction-lock 'file))))
15276 (t (error "Don't know how to restrict Org-mode's agenda")))
15277 (org-move-overlay org-speedbar-restriction-lock-overlay
15278 (point-at-bol) (point-at-eol))
15279 (setq current-prefix-arg nil)
15280 (org-agenda-maybe-redo)))
15282 (eval-after-load "speedbar"
15283 '(progn
15284 (speedbar-add-supported-extension ".org")
15285 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15286 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15287 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15288 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15289 (add-hook 'speedbar-visiting-tag-hook
15290 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15293 ;;; Fixes and Hacks for problems with other packages
15295 ;; Make flyspell not check words in links, to not mess up our keymap
15296 (defun org-mode-flyspell-verify ()
15297 "Don't let flyspell put overlays at active buttons."
15298 (not (get-text-property (point) 'keymap)))
15300 ;; Make `bookmark-jump' show the jump location if it was hidden.
15301 (eval-after-load "bookmark"
15302 '(if (boundp 'bookmark-after-jump-hook)
15303 ;; We can use the hook
15304 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15305 ;; Hook not available, use advice
15306 (defadvice bookmark-jump (after org-make-visible activate)
15307 "Make the position visible."
15308 (org-bookmark-jump-unhide))))
15310 ;; Make sure saveplace show the location if it was hidden
15311 (eval-after-load "saveplace"
15312 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15313 "Make the position visible."
15314 (org-bookmark-jump-unhide)))
15316 (defun org-bookmark-jump-unhide ()
15317 "Unhide the current position, to show the bookmark location."
15318 (and (org-mode-p)
15319 (or (org-invisible-p)
15320 (save-excursion (goto-char (max (point-min) (1- (point))))
15321 (org-invisible-p)))
15322 (org-show-context 'bookmark-jump)))
15324 ;; Make session.el ignore our circular variable
15325 (eval-after-load "session"
15326 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15328 ;;;; Experimental code
15330 (defun org-closed-in-range ()
15331 "Sparse tree of items closed in a certain time range.
15332 Still experimental, may disappear in the future."
15333 (interactive)
15334 ;; Get the time interval from the user.
15335 (let* ((time1 (time-to-seconds
15336 (org-read-date nil 'to-time nil "Starting date: ")))
15337 (time2 (time-to-seconds
15338 (org-read-date nil 'to-time nil "End date:")))
15339 ;; callback function
15340 (callback (lambda ()
15341 (let ((time
15342 (time-to-seconds
15343 (apply 'encode-time
15344 (org-parse-time-string
15345 (match-string 1))))))
15346 ;; check if time in interval
15347 (and (>= time time1) (<= time time2))))))
15348 ;; make tree, check each match with the callback
15349 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15352 ;;;; Finish up
15354 (provide 'org)
15356 (run-hooks 'org-load-hook)
15358 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15360 ;;; org.el ends here