Deadlines: Deal with "incorrect" positioning of warning period
[org-mode.git] / lisp / org.el
blobc74e6c041f07e51e644df90f4592dbb905c5536f
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.22trans
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.22trans"
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" "LOGBOOK")
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 Note that, when `org-odd-levels-only' is set, level corresponds to
1438 order in hierarchy, not to the number of stars.
1439 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1440 Note that, when `org-odd-levels-only' is set, level corresponds to
1441 order in hierarchy, not to the number of stars.
1443 When this variable is nil, all top-level headlines in the current buffer
1444 are used, equivalent to the value `((nil . (:level . 1))'."
1445 :group 'org-refile
1446 :type '(repeat
1447 (cons
1448 (choice :value org-agenda-files
1449 (const :tag "All agenda files" org-agenda-files)
1450 (const :tag "Current buffer" nil)
1451 (function) (variable) (file))
1452 (choice :tag "Identify target headline by"
1453 (cons :tag "Specific tag" (const :value :tag) (string))
1454 (cons :tag "TODO keyword" (const :value :todo) (string))
1455 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1456 (cons :tag "Level number" (const :value :level) (integer))
1457 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1459 (defcustom org-refile-use-outline-path nil
1460 "Non-nil means, provide refile targets as paths.
1461 So a level 3 headline will be available as level1/level2/level3.
1462 When the value is `file', also include the file name (without directory)
1463 into the path. When `full-file-path', include the full file path."
1464 :group 'org-refile
1465 :type '(choice
1466 (const :tag "Not" nil)
1467 (const :tag "Yes" t)
1468 (const :tag "Start with file name" file)
1469 (const :tag "Start with full file path" full-file-path)))
1471 (defcustom org-outline-path-complete-in-steps t
1472 "Non-nil means, complete the outline path in hierarchical steps.
1473 When Org-mode uses the refile interface to select an outline path
1474 \(see variable `org-refile-use-outline-path'), the completion of
1475 the path can be done is a single go, or if can be done in steps down
1476 the headline hierarchy. Going in steps is probably the best if you
1477 do not use a special completion package like `ido' or `icicles'.
1478 However, when using these packages, going in one step can be very
1479 fast, while still showing the whole path to the entry."
1480 :group 'org-refile
1481 :type 'boolean)
1483 (defgroup org-todo nil
1484 "Options concerning TODO items in Org-mode."
1485 :tag "Org TODO"
1486 :group 'org)
1488 (defgroup org-progress nil
1489 "Options concerning Progress logging in Org-mode."
1490 :tag "Org Progress"
1491 :group 'org-time)
1493 (defvar org-todo-interpretation-widgets
1495 (:tag "Sequence (cycling hits every state)" sequence)
1496 (:tag "Type (cycling directly to DONE)" type))
1497 "The available interpretation symbols for customizing
1498 `org-todo-keywords'.
1499 Interested libraries should add to this list.")
1501 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1502 "List of TODO entry keyword sequences and their interpretation.
1503 \\<org-mode-map>This is a list of sequences.
1505 Each sequence starts with a symbol, either `sequence' or `type',
1506 indicating if the keywords should be interpreted as a sequence of
1507 action steps, or as different types of TODO items. The first
1508 keywords are states requiring action - these states will select a headline
1509 for inclusion into the global TODO list Org-mode produces. If one of
1510 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1511 signify that no further action is necessary. If \"|\" is not found,
1512 the last keyword is treated as the only DONE state of the sequence.
1514 The command \\[org-todo] cycles an entry through these states, and one
1515 additional state where no keyword is present. For details about this
1516 cycling, see the manual.
1518 TODO keywords and interpretation can also be set on a per-file basis with
1519 the special #+SEQ_TODO and #+TYP_TODO lines.
1521 Each keyword can optionally specify a character for fast state selection
1522 \(in combination with the variable `org-use-fast-todo-selection')
1523 and specifiers for state change logging, using the same syntax
1524 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1525 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1526 indicates to record a time stamp each time this state is selected.
1528 Each keyword may also specify if a timestamp or a note should be
1529 recorded when entering or leaving the state, by adding additional
1530 characters in the parenthesis after the keyword. This looks like this:
1531 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1532 record only the time of the state change. With X and Y being either
1533 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1534 Y when leaving the state if and only if the *target* state does not
1535 define X. You may omit any of the fast-selection key or X or /Y,
1536 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1538 For backward compatibility, this variable may also be just a list
1539 of keywords - in this case the interpretation (sequence or type) will be
1540 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1541 :group 'org-todo
1542 :group 'org-keywords
1543 :type '(choice
1544 (repeat :tag "Old syntax, just keywords"
1545 (string :tag "Keyword"))
1546 (repeat :tag "New syntax"
1547 (cons
1548 (choice
1549 :tag "Interpretation"
1550 ;;Quick and dirty way to see
1551 ;;`org-todo-interpretations'. This takes the
1552 ;;place of item arguments
1553 :convert-widget
1554 (lambda (widget)
1555 (widget-put widget
1556 :args (mapcar
1557 #'(lambda (x)
1558 (widget-convert
1559 (cons 'const x)))
1560 org-todo-interpretation-widgets))
1561 widget))
1562 (repeat
1563 (string :tag "Keyword"))))))
1565 (defvar org-todo-keywords-1 nil
1566 "All TODO and DONE keywords active in a buffer.")
1567 (make-variable-buffer-local 'org-todo-keywords-1)
1568 (defvar org-todo-keywords-for-agenda nil)
1569 (defvar org-done-keywords-for-agenda nil)
1570 (defvar org-todo-keyword-alist-for-agenda nil)
1571 (defvar org-tag-alist-for-agenda nil)
1572 (defvar org-agenda-contributing-files nil)
1573 (defvar org-not-done-keywords nil)
1574 (make-variable-buffer-local 'org-not-done-keywords)
1575 (defvar org-done-keywords nil)
1576 (make-variable-buffer-local 'org-done-keywords)
1577 (defvar org-todo-heads nil)
1578 (make-variable-buffer-local 'org-todo-heads)
1579 (defvar org-todo-sets nil)
1580 (make-variable-buffer-local 'org-todo-sets)
1581 (defvar org-todo-log-states nil)
1582 (make-variable-buffer-local 'org-todo-log-states)
1583 (defvar org-todo-kwd-alist nil)
1584 (make-variable-buffer-local 'org-todo-kwd-alist)
1585 (defvar org-todo-key-alist nil)
1586 (make-variable-buffer-local 'org-todo-key-alist)
1587 (defvar org-todo-key-trigger nil)
1588 (make-variable-buffer-local 'org-todo-key-trigger)
1590 (defcustom org-todo-interpretation 'sequence
1591 "Controls how TODO keywords are interpreted.
1592 This variable is in principle obsolete and is only used for
1593 backward compatibility, if the interpretation of todo keywords is
1594 not given already in `org-todo-keywords'. See that variable for
1595 more information."
1596 :group 'org-todo
1597 :group 'org-keywords
1598 :type '(choice (const sequence)
1599 (const type)))
1601 (defcustom org-use-fast-todo-selection t
1602 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1603 This variable describes if and under what circumstances the cycling
1604 mechanism for TODO keywords will be replaced by a single-key, direct
1605 selection scheme.
1607 When nil, fast selection is never used.
1609 When the symbol `prefix', it will be used when `org-todo' is called with
1610 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1611 in an agenda buffer.
1613 When t, fast selection is used by default. In this case, the prefix
1614 argument forces cycling instead.
1616 In all cases, the special interface is only used if access keys have actually
1617 been assigned by the user, i.e. if keywords in the configuration are followed
1618 by a letter in parenthesis, like TODO(t)."
1619 :group 'org-todo
1620 :type '(choice
1621 (const :tag "Never" nil)
1622 (const :tag "By default" t)
1623 (const :tag "Only with C-u C-c C-t" prefix)))
1625 (defcustom org-provide-todo-statistics t
1626 "Non-nil means, update todo statistics after insert and toggle.
1627 When this is set, todo statistics is updated in the parent of the current
1628 entry each time a todo state is changed."
1629 :group 'org-todo
1630 :type 'boolean)
1632 (defcustom org-after-todo-state-change-hook nil
1633 "Hook which is run after the state of a TODO item was changed.
1634 The new state (a string with a TODO keyword, or nil) is available in the
1635 Lisp variable `state'."
1636 :group 'org-todo
1637 :type 'hook)
1639 (defvar org-blocker-hook nil
1640 "Hook for functions that are allowed to block a state change.
1642 Each function gets as its single argument a property list, see
1643 `org-trigger-hook' for more information about this list.
1645 If any of the functions in this hook returns nil, the state change
1646 is blocked.")
1648 (defvar org-trigger-hook nil
1649 "Hook for functions that are triggered by a state change.
1651 Each function gets as its single argument a property list with at least
1652 the following elements:
1654 (:type type-of-change :position pos-at-entry-start
1655 :from old-state :to new-state)
1657 Depending on the type, more properties may be present.
1659 This mechanism is currently implemented for:
1661 TODO state changes
1662 ------------------
1663 :type todo-state-change
1664 :from previous state (keyword as a string), or nil, or a symbol
1665 'todo' or 'done', to indicate the general type of state.
1666 :to new state, like in :from")
1668 (defcustom org-enforce-todo-dependencies nil
1669 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1670 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1671 be blocked if any prior sibling is not yet done.
1672 This variable needs to be set before org.el is loaded, and you need to
1673 restart Emacs after a change to make the change effective. The only way
1674 to change is while Emacs is running is through the customize interface."
1675 :set (lambda (var val)
1676 (set var val)
1677 (if val
1678 (add-hook 'org-blocker-hook
1679 'org-block-todo-from-children-or-siblings)
1680 (remove-hook 'org-blocker-hook
1681 'org-block-todo-from-children-or-siblings)))
1682 :group 'org-todo
1683 :type 'boolean)
1685 (defcustom org-enforce-todo-checkbox-dependencies nil
1686 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1687 When this is nil, checkboxes have no influence on switching TODO states.
1688 When non-nil, you first need to check off all check boxes before the TODO
1689 entry can be switched to DONE.
1690 This variable needs to be set before org.el is loaded, and you need to
1691 restart Emacs after a change to make the change effective. The only way
1692 to change is while Emacs is running is through the customize interface."
1693 :set (lambda (var val)
1694 (set var val)
1695 (if val
1696 (add-hook 'org-blocker-hook
1697 'org-block-todo-from-checkboxes)
1698 (remove-hook 'org-blocker-hook
1699 'org-block-todo-from-checkboxes)))
1700 :group 'org-todo
1701 :type 'boolean)
1703 (defcustom org-todo-state-tags-triggers nil
1704 "Tag changes that should be triggered by TODO state changes.
1705 This is a list. Each entry is
1707 (state-change (tag . flag) .......)
1709 State-change can be a string with a state, and empty string to indicate the
1710 state that has no TODO keyword, or it can be one of the symbols `todo'
1711 or `done', meaning any not-done or done state, respectively."
1712 :group 'org-todo
1713 :group 'org-tags
1714 :type '(repeat
1715 (cons (choice :tag "When changing to"
1716 (const :tag "Not-done state" todo)
1717 (const :tag "Done state" done)
1718 (string :tag "State"))
1719 (repeat
1720 (cons :tag "Tag action"
1721 (string :tag "Tag")
1722 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1724 (defcustom org-log-done nil
1725 "Information to record when a task moves to the DONE state.
1727 Possible values are:
1729 nil Don't add anything, just change the keyword
1730 time Add a time stamp to the task
1731 note Prompt a closing note and add it with template `org-log-note-headings'
1733 This option can also be set with on a per-file-basis with
1735 #+STARTUP: nologdone
1736 #+STARTUP: logdone
1737 #+STARTUP: lognotedone
1739 You can have local logging settings for a subtree by setting the LOGGING
1740 property to one or more of these keywords."
1741 :group 'org-todo
1742 :group 'org-progress
1743 :type '(choice
1744 (const :tag "No logging" nil)
1745 (const :tag "Record CLOSED timestamp" time)
1746 (const :tag "Record CLOSED timestamp with closing note." note)))
1748 ;; Normalize old uses of org-log-done.
1749 (cond
1750 ((eq org-log-done t) (setq org-log-done 'time))
1751 ((and (listp org-log-done) (memq 'done org-log-done))
1752 (setq org-log-done 'note)))
1754 (defcustom org-log-note-clock-out nil
1755 "Non-nil means, record a note when clocking out of an item.
1756 This can also be configured on a per-file basis by adding one of
1757 the following lines anywhere in the buffer:
1759 #+STARTUP: lognoteclock-out
1760 #+STARTUP: nolognoteclock-out"
1761 :group 'org-todo
1762 :group 'org-progress
1763 :type 'boolean)
1765 (defcustom org-log-done-with-time t
1766 "Non-nil means, the CLOSED time stamp will contain date and time.
1767 When nil, only the date will be recorded."
1768 :group 'org-progress
1769 :type 'boolean)
1771 (defcustom org-log-note-headings
1772 '((done . "CLOSING NOTE %t")
1773 (state . "State %-12s from %-12S %t")
1774 (note . "Note taken on %t")
1775 (clock-out . ""))
1776 "Headings for notes added to entries.
1777 The value is an alist, with the car being a symbol indicating the note
1778 context, and the cdr is the heading to be used. The heading may also be the
1779 empty string.
1780 %t in the heading will be replaced by a time stamp.
1781 %s will be replaced by the new TODO state, in double quotes.
1782 %S will be replaced by the old TODO state, in double quotes.
1783 %u will be replaced by the user name.
1784 %U will be replaced by the full user name."
1785 :group 'org-todo
1786 :group 'org-progress
1787 :type '(list :greedy t
1788 (cons (const :tag "Heading when closing an item" done) string)
1789 (cons (const :tag
1790 "Heading when changing todo state (todo sequence only)"
1791 state) string)
1792 (cons (const :tag "Heading when just taking a note" note) string)
1793 (cons (const :tag "Heading when clocking out" clock-out) string)))
1795 (unless (assq 'note org-log-note-headings)
1796 (push '(note . "%t") org-log-note-headings))
1798 (defcustom org-log-into-drawer nil
1799 "Non-nil means, insert state change notes and time stamps into a drawer.
1800 When nil, state changes notes will be inserted after the headline and
1801 any scheduling and clock lines, but not inside a drawer.
1803 The value of this variable should be the name of the drawer to use.
1804 LOGBOOK is proposed at the default drawer for this purpose, you can
1805 also set this to a string to define the drawer of your choice.
1807 A value of t is also allowed, representing \"LOGBOOK\".
1809 If this variable is set, `org-log-state-notes-insert-after-drawers'
1810 will be ognored."
1811 :group 'org-todo
1812 :group 'org-progress
1813 :type '(choice
1814 (const :tag "Not into a drawer" nil)
1815 (const :tag "LOGBOOK" t)
1816 (string :tag "Other")))
1818 (if (fboundp 'defvaralias)
1819 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1821 (defcustom org-log-state-notes-insert-after-drawers nil
1822 "Non-nil means, insert state change notes after any drawers in entry.
1823 Only the drawers that *immediately* follow the headline and the
1824 deadline/scheduled line are skipped.
1825 When nil, insert notes right after the heading and perhaps the line
1826 with deadline/scheduling if present.
1828 This variable will have no effect if `org-log-into-drawer' is
1829 set."
1830 :group 'org-todo
1831 :group 'org-progress
1832 :type 'boolean)
1834 (defcustom org-log-states-order-reversed t
1835 "Non-nil means, the latest state change note will be directly after heading.
1836 When nil, the notes will be orderer according to time."
1837 :group 'org-todo
1838 :group 'org-progress
1839 :type 'boolean)
1841 (defcustom org-log-repeat 'time
1842 "Non-nil means, record moving through the DONE state when triggering repeat.
1843 An auto-repeating tasks is immediately switched back to TODO when marked
1844 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1845 the TODO keyword definition, or recording a closing note by setting
1846 `org-log-done', there will be no record of the task moving through DONE.
1847 This variable forces taking a note anyway. Possible values are:
1849 nil Don't force a record
1850 time Record a time stamp
1851 note Record a note
1853 This option can also be set with on a per-file-basis with
1855 #+STARTUP: logrepeat
1856 #+STARTUP: lognoterepeat
1857 #+STARTUP: nologrepeat
1859 You can have local logging settings for a subtree by setting the LOGGING
1860 property to one or more of these keywords."
1861 :group 'org-todo
1862 :group 'org-progress
1863 :type '(choice
1864 (const :tag "Don't force a record" nil)
1865 (const :tag "Force recording the DONE state" time)
1866 (const :tag "Force recording a note with the DONE state" note)))
1869 (defgroup org-priorities nil
1870 "Priorities in Org-mode."
1871 :tag "Org Priorities"
1872 :group 'org-todo)
1874 (defcustom org-highest-priority ?A
1875 "The highest priority of TODO items. A character like ?A, ?B etc.
1876 Must have a smaller ASCII number than `org-lowest-priority'."
1877 :group 'org-priorities
1878 :type 'character)
1880 (defcustom org-lowest-priority ?C
1881 "The lowest priority of TODO items. A character like ?A, ?B etc.
1882 Must have a larger ASCII number than `org-highest-priority'."
1883 :group 'org-priorities
1884 :type 'character)
1886 (defcustom org-default-priority ?B
1887 "The default priority of TODO items.
1888 This is the priority an item get if no explicit priority is given."
1889 :group 'org-priorities
1890 :type 'character)
1892 (defcustom org-priority-start-cycle-with-default t
1893 "Non-nil means, start with default priority when starting to cycle.
1894 When this is nil, the first step in the cycle will be (depending on the
1895 command used) one higher or lower that the default priority."
1896 :group 'org-priorities
1897 :type 'boolean)
1899 (defgroup org-time nil
1900 "Options concerning time stamps and deadlines in Org-mode."
1901 :tag "Org Time"
1902 :group 'org)
1904 (defcustom org-insert-labeled-timestamps-at-point nil
1905 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1906 When nil, these labeled time stamps are forces into the second line of an
1907 entry, just after the headline. When scheduling from the global TODO list,
1908 the time stamp will always be forced into the second line."
1909 :group 'org-time
1910 :type 'boolean)
1912 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1913 "Formats for `format-time-string' which are used for time stamps.
1914 It is not recommended to change this constant.")
1916 (defcustom org-time-stamp-rounding-minutes '(0 5)
1917 "Number of minutes to round time stamps to.
1918 These are two values, the first applies when first creating a time stamp.
1919 The second applies when changing it with the commands `S-up' and `S-down'.
1920 When changing the time stamp, this means that it will change in steps
1921 of N minutes, as given by the second value.
1923 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1924 numbers should be factors of 60, so for example 5, 10, 15.
1926 When this is larger than 1, you can still force an exact time-stamp by using
1927 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1928 and by using a prefix arg to `S-up/down' to specify the exact number
1929 of minutes to shift."
1930 :group 'org-time
1931 :get '(lambda (var) ; Make sure all entries have 5 elements
1932 (if (integerp (default-value var))
1933 (list (default-value var) 5)
1934 (default-value var)))
1935 :type '(list
1936 (integer :tag "when inserting times")
1937 (integer :tag "when modifying times")))
1939 ;; Normalize old customizations of this variable.
1940 (when (integerp org-time-stamp-rounding-minutes)
1941 (setq org-time-stamp-rounding-minutes
1942 (list org-time-stamp-rounding-minutes
1943 org-time-stamp-rounding-minutes)))
1945 (defcustom org-display-custom-times nil
1946 "Non-nil means, overlay custom formats over all time stamps.
1947 The formats are defined through the variable `org-time-stamp-custom-formats'.
1948 To turn this on on a per-file basis, insert anywhere in the file:
1949 #+STARTUP: customtime"
1950 :group 'org-time
1951 :set 'set-default
1952 :type 'sexp)
1953 (make-variable-buffer-local 'org-display-custom-times)
1955 (defcustom org-time-stamp-custom-formats
1956 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1957 "Custom formats for time stamps. See `format-time-string' for the syntax.
1958 These are overlayed over the default ISO format if the variable
1959 `org-display-custom-times' is set. Time like %H:%M should be at the
1960 end of the second format."
1961 :group 'org-time
1962 :type 'sexp)
1964 (defun org-time-stamp-format (&optional long inactive)
1965 "Get the right format for a time string."
1966 (let ((f (if long (cdr org-time-stamp-formats)
1967 (car org-time-stamp-formats))))
1968 (if inactive
1969 (concat "[" (substring f 1 -1) "]")
1970 f)))
1972 (defcustom org-time-clocksum-format "%d:%02d"
1973 "The format string used when creating CLOCKSUM lines, or when
1974 org-mode generates a time duration."
1975 :group 'org-time
1976 :type 'string)
1978 (defcustom org-deadline-warning-days 14
1979 "No. of days before expiration during which a deadline becomes active.
1980 This variable governs the display in sparse trees and in the agenda.
1981 When 0 or negative, it means use this number (the absolute value of it)
1982 even if a deadline has a different individual lead time specified."
1983 :group 'org-time
1984 :group 'org-agenda-daily/weekly
1985 :type 'number)
1987 (defcustom org-read-date-prefer-future t
1988 "Non-nil means, assume future for incomplete date input from user.
1989 This affects the following situations:
1990 1. The user gives a day, but no month.
1991 For example, if today is the 15th, and you enter \"3\", Org-mode will
1992 read this as the third of *next* month. However, if you enter \"17\",
1993 it will be considered as *this* month.
1994 2. The user gives a month but not a year.
1995 For example, if it is april and you enter \"feb 2\", this will be read
1996 as feb 2, *next* year. \"May 5\", however, will be this year.
1998 Currently this does not work for ISO week specifications.
2000 When this option is nil, the current month and year will always be used
2001 as defaults."
2002 :group 'org-time
2003 :type 'boolean)
2005 (defcustom org-read-date-display-live t
2006 "Non-nil means, display current interpretation of date prompt live.
2007 This display will be in an overlay, in the minibuffer."
2008 :group 'org-time
2009 :type 'boolean)
2011 (defcustom org-read-date-popup-calendar t
2012 "Non-nil means, pop up a calendar when prompting for a date.
2013 In the calendar, the date can be selected with mouse-1. However, the
2014 minibuffer will also be active, and you can simply enter the date as well.
2015 When nil, only the minibuffer will be available."
2016 :group 'org-time
2017 :type 'boolean)
2018 (if (fboundp 'defvaralias)
2019 (defvaralias 'org-popup-calendar-for-date-prompt
2020 'org-read-date-popup-calendar))
2022 (defcustom org-extend-today-until 0
2023 "The hour when your day really ends. Must be an integer.
2024 This has influence for the following applications:
2025 - When switching the agenda to \"today\". It it is still earlier than
2026 the time given here, the day recognized as TODAY is actually yesterday.
2027 - When a date is read from the user and it is still before the time given
2028 here, the current date and time will be assumed to be yesterday, 23:59.
2029 Also, timestamps inserted in remember templates follow this rule.
2031 IMPORTANT: This is a feature whose implementation is and likely will
2032 remain incomplete. Really, it is only here because past midnight seems to
2033 be the favorite working time of John Wiegley :-)"
2034 :group 'org-time
2035 :type 'number)
2037 (defcustom org-edit-timestamp-down-means-later nil
2038 "Non-nil means, S-down will increase the time in a time stamp.
2039 When nil, S-up will increase."
2040 :group 'org-time
2041 :type 'boolean)
2043 (defcustom org-calendar-follow-timestamp-change t
2044 "Non-nil means, make the calendar window follow timestamp changes.
2045 When a timestamp is modified and the calendar window is visible, it will be
2046 moved to the new date."
2047 :group 'org-time
2048 :type 'boolean)
2050 (defgroup org-tags nil
2051 "Options concerning tags in Org-mode."
2052 :tag "Org Tags"
2053 :group 'org)
2055 (defcustom org-tag-alist nil
2056 "List of tags allowed in Org-mode files.
2057 When this list is nil, Org-mode will base TAG input on what is already in the
2058 buffer.
2059 The value of this variable is an alist, the car of each entry must be a
2060 keyword as a string, the cdr may be a character that is used to select
2061 that tag through the fast-tag-selection interface.
2062 See the manual for details."
2063 :group 'org-tags
2064 :type '(repeat
2065 (choice
2066 (cons (string :tag "Tag name")
2067 (character :tag "Access char"))
2068 (const :tag "Start radio group" (:startgroup))
2069 (const :tag "End radio group" (:endgroup)))))
2071 (defvar org-file-tags nil
2072 "List of tags that can be inherited by all entries in the file.
2073 The tags will be inherited if the variable `org-use-tag-inheritance'
2074 says they should be.
2075 This variable is populated from #+TAG lines.")
2077 (defcustom org-use-fast-tag-selection 'auto
2078 "Non-nil means, use fast tag selection scheme.
2079 This is a special interface to select and deselect tags with single keys.
2080 When nil, fast selection is never used.
2081 When the symbol `auto', fast selection is used if and only if selection
2082 characters for tags have been configured, either through the variable
2083 `org-tag-alist' or through a #+TAGS line in the buffer.
2084 When t, fast selection is always used and selection keys are assigned
2085 automatically if necessary."
2086 :group 'org-tags
2087 :type '(choice
2088 (const :tag "Always" t)
2089 (const :tag "Never" nil)
2090 (const :tag "When selection characters are configured" 'auto)))
2092 (defcustom org-fast-tag-selection-single-key nil
2093 "Non-nil means, fast tag selection exits after first change.
2094 When nil, you have to press RET to exit it.
2095 During fast tag selection, you can toggle this flag with `C-c'.
2096 This variable can also have the value `expert'. In this case, the window
2097 displaying the tags menu is not even shown, until you press C-c again."
2098 :group 'org-tags
2099 :type '(choice
2100 (const :tag "No" nil)
2101 (const :tag "Yes" t)
2102 (const :tag "Expert" expert)))
2104 (defvar org-fast-tag-selection-include-todo nil
2105 "Non-nil means, fast tags selection interface will also offer TODO states.
2106 This is an undocumented feature, you should not rely on it.")
2108 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2109 "The column to which tags should be indented in a headline.
2110 If this number is positive, it specifies the column. If it is negative,
2111 it means that the tags should be flushright to that column. For example,
2112 -80 works well for a normal 80 character screen."
2113 :group 'org-tags
2114 :type 'integer)
2116 (defcustom org-auto-align-tags t
2117 "Non-nil means, realign tags after pro/demotion of TODO state change.
2118 These operations change the length of a headline and therefore shift
2119 the tags around. With this options turned on, after each such operation
2120 the tags are again aligned to `org-tags-column'."
2121 :group 'org-tags
2122 :type 'boolean)
2124 (defcustom org-use-tag-inheritance t
2125 "Non-nil means, tags in levels apply also for sublevels.
2126 When nil, only the tags directly given in a specific line apply there.
2127 This may also be a list of tags that should be inherited, or a regexp that
2128 matches tags that should be inherited. Additional control is possible
2129 with the variable `org-tags-exclude-from-inheritance' which gives an
2130 explicit list of tags to be excluded from inheritance., even if the value of
2131 `org-use-tag-inheritance' would select it for inheritance.
2133 If this option is t, a match early-on in a tree can lead to a large
2134 number of matches in the subtree when constructing the agenda or creating
2135 a sparse tree. If you only want to see the first match in a tree during
2136 a search, check out the variable `org-tags-match-list-sublevels'."
2137 :group 'org-tags
2138 :type '(choice
2139 (const :tag "Not" nil)
2140 (const :tag "Always" t)
2141 (repeat :tag "Specific tags" (string :tag "Tag"))
2142 (regexp :tag "Tags matched by regexp")))
2144 (defcustom org-tags-exclude-from-inheritance nil
2145 "List of tags that should never be inherited.
2146 This is a way to exclude a few tags from inheritance. For way to do
2147 the opposite, to actively allow inheritance for selected tags,
2148 see the variable `org-use-tag-inheritance'."
2149 :group 'org-tags
2150 :type '(repeat (string :tag "Tag")))
2152 (defun org-tag-inherit-p (tag)
2153 "Check if TAG is one that should be inherited."
2154 (cond
2155 ((member tag org-tags-exclude-from-inheritance) nil)
2156 ((eq org-use-tag-inheritance t) t)
2157 ((not org-use-tag-inheritance) nil)
2158 ((stringp org-use-tag-inheritance)
2159 (string-match org-use-tag-inheritance tag))
2160 ((listp org-use-tag-inheritance)
2161 (member tag org-use-tag-inheritance))
2162 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2164 (defcustom org-tags-match-list-sublevels t
2165 "Non-nil means list also sublevels of headlines matching tag search.
2166 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2167 the sublevels of a headline matching a tag search often also match
2168 the same search. Listing all of them can create very long lists.
2169 Setting this variable to nil causes subtrees of a match to be skipped.
2170 This option is off by default, because inheritance in on. If you turn
2171 inheritance off, you very likely want to turn this option on.
2173 As a special case, if the tag search is restricted to TODO items, the
2174 value of this variable is ignored and sublevels are always checked, to
2175 make sure all corresponding TODO items find their way into the list.
2177 This variable is semi-obsolete and probably should always be true. It
2178 is better to limit inheritance to certain tags using the variables
2179 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2180 :group 'org-tags
2181 :type 'boolean)
2183 (defvar org-tags-history nil
2184 "History of minibuffer reads for tags.")
2185 (defvar org-last-tags-completion-table nil
2186 "The last used completion table for tags.")
2187 (defvar org-after-tags-change-hook nil
2188 "Hook that is run after the tags in a line have changed.")
2190 (defgroup org-properties nil
2191 "Options concerning properties in Org-mode."
2192 :tag "Org Properties"
2193 :group 'org)
2195 (defcustom org-property-format "%-10s %s"
2196 "How property key/value pairs should be formatted by `indent-line'.
2197 When `indent-line' hits a property definition, it will format the line
2198 according to this format, mainly to make sure that the values are
2199 lined-up with respect to each other."
2200 :group 'org-properties
2201 :type 'string)
2203 (defcustom org-use-property-inheritance nil
2204 "Non-nil means, properties apply also for sublevels.
2206 This setting is chiefly used during property searches. Turning it on can
2207 cause significant overhead when doing a search, which is why it is not
2208 on by default.
2210 When nil, only the properties directly given in the current entry count.
2211 When t, every property is inherited. The value may also be a list of
2212 properties that should have inheritance, or a regular expression matching
2213 properties that should be inherited.
2215 However, note that some special properties use inheritance under special
2216 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2217 and the properties ending in \"_ALL\" when they are used as descriptor
2218 for valid values of a property.
2220 Note for programmers:
2221 When querying an entry with `org-entry-get', you can control if inheritance
2222 should be used. By default, `org-entry-get' looks only at the local
2223 properties. You can request inheritance by setting the inherit argument
2224 to t (to force inheritance) or to `selective' (to respect the setting
2225 in this variable)."
2226 :group 'org-properties
2227 :type '(choice
2228 (const :tag "Not" nil)
2229 (const :tag "Always" t)
2230 (repeat :tag "Specific properties" (string :tag "Property"))
2231 (regexp :tag "Properties matched by regexp")))
2233 (defun org-property-inherit-p (property)
2234 "Check if PROPERTY is one that should be inherited."
2235 (cond
2236 ((eq org-use-property-inheritance t) t)
2237 ((not org-use-property-inheritance) nil)
2238 ((stringp org-use-property-inheritance)
2239 (string-match org-use-property-inheritance property))
2240 ((listp org-use-property-inheritance)
2241 (member property org-use-property-inheritance))
2242 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2244 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2245 "The default column format, if no other format has been defined.
2246 This variable can be set on the per-file basis by inserting a line
2248 #+COLUMNS: %25ITEM ....."
2249 :group 'org-properties
2250 :type 'string)
2252 (defcustom org-columns-ellipses ".."
2253 "The ellipses to be used when a field in column view is truncated.
2254 When this is the empty string, as many characters as possible are shown,
2255 but then there will be no visual indication that the field has been truncated.
2256 When this is a string of length N, the last N characters of a truncated
2257 field are replaced by this string. If the column is narrower than the
2258 ellipses string, only part of the ellipses string will be shown."
2259 :group 'org-properties
2260 :type 'string)
2262 (defcustom org-columns-modify-value-for-display-function nil
2263 "Function that modifies values for display in column view.
2264 For example, it can be used to cut out a certain part from a time stamp.
2265 The function must take 2 arguments:
2267 column-title The title of the column (*not* the property name)
2268 value The value that should be modified.
2270 The function should return the value that should be displayed,
2271 or nil if the normal value should be used."
2272 :group 'org-properties
2273 :type 'function)
2275 (defcustom org-effort-property "Effort"
2276 "The property that is being used to keep track of effort estimates.
2277 Effort estimates given in this property need to have the format H:MM."
2278 :group 'org-properties
2279 :group 'org-progress
2280 :type '(string :tag "Property"))
2282 (defconst org-global-properties-fixed
2283 '(("VISIBILITY_ALL" . "folded children content all"))
2284 "List of property/value pairs that can be inherited by any entry.
2285 These are fixed values, for the preset properties.")
2288 (defcustom org-global-properties nil
2289 "List of property/value pairs that can be inherited by any entry.
2290 You can set buffer-local values for the same purpose in the variable
2291 `org-file-properties' this by adding lines like
2293 #+PROPERTY: NAME VALUE"
2294 :group 'org-properties
2295 :type '(repeat
2296 (cons (string :tag "Property")
2297 (string :tag "Value"))))
2299 (defvar org-file-properties nil
2300 "List of property/value pairs that can be inherited by any entry.
2301 Valid for the current buffer.
2302 This variable is populated from #+PROPERTY lines.")
2303 (make-variable-buffer-local 'org-file-properties)
2305 (defgroup org-agenda nil
2306 "Options concerning agenda views in Org-mode."
2307 :tag "Org Agenda"
2308 :group 'org)
2310 (defvar org-category nil
2311 "Variable used by org files to set a category for agenda display.
2312 Such files should use a file variable to set it, for example
2314 # -*- mode: org; org-category: \"ELisp\"
2316 or contain a special line
2318 #+CATEGORY: ELisp
2320 If the file does not specify a category, then file's base name
2321 is used instead.")
2322 (make-variable-buffer-local 'org-category)
2323 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2325 (defcustom org-agenda-files nil
2326 "The files to be used for agenda display.
2327 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2328 \\[org-remove-file]. You can also use customize to edit the list.
2330 If an entry is a directory, all files in that directory that are matched by
2331 `org-agenda-file-regexp' will be part of the file list.
2333 If the value of the variable is not a list but a single file name, then
2334 the list of agenda files is actually stored and maintained in that file, one
2335 agenda file per line."
2336 :group 'org-agenda
2337 :type '(choice
2338 (repeat :tag "List of files and directories" file)
2339 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2341 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2342 "Regular expression to match files for `org-agenda-files'.
2343 If any element in the list in that variable contains a directory instead
2344 of a normal file, all files in that directory that are matched by this
2345 regular expression will be included."
2346 :group 'org-agenda
2347 :type 'regexp)
2349 (defcustom org-agenda-text-search-extra-files nil
2350 "List of extra files to be searched by text search commands.
2351 These files will be search in addition to the agenda files by the
2352 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2353 Note that these files will only be searched for text search commands,
2354 not for the other agenda views like todo lists, tag searches or the weekly
2355 agenda. This variable is intended to list notes and possibly archive files
2356 that should also be searched by these two commands.
2357 In fact, if the first element in the list is the symbol `agenda-archives',
2358 than all archive files of all agenda files will be added to the search
2359 scope."
2360 :group 'org-agenda
2361 :type '(set :greedy t
2362 (const :tag "Agenda Archives" agenda-archives)
2363 (repeat :inline t (file))))
2365 (if (fboundp 'defvaralias)
2366 (defvaralias 'org-agenda-multi-occur-extra-files
2367 'org-agenda-text-search-extra-files))
2369 (defcustom org-agenda-skip-unavailable-files nil
2370 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2371 A nil value means to remove them, after a query, from the list."
2372 :group 'org-agenda
2373 :type 'boolean)
2375 (defcustom org-calendar-to-agenda-key [?c]
2376 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2377 The command `org-calendar-goto-agenda' will be bound to this key. The
2378 default is the character `c' because then `c' can be used to switch back and
2379 forth between agenda and calendar."
2380 :group 'org-agenda
2381 :type 'sexp)
2383 (defcustom org-calendar-agenda-action-key [?k]
2384 "The key to be installed in `calendar-mode-map' for agenda-action.
2385 The command `org-agenda-action' will be bound to this key. The
2386 default is the character `k' because we use the same key in the agenda."
2387 :group 'org-agenda
2388 :type 'sexp)
2390 (eval-after-load "calendar"
2391 '(progn
2392 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2393 'org-calendar-goto-agenda)
2394 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2395 'org-agenda-action)))
2397 (defgroup org-latex nil
2398 "Options for embedding LaTeX code into Org-mode."
2399 :tag "Org LaTeX"
2400 :group 'org)
2402 (defcustom org-format-latex-options
2403 '(:foreground default :background default :scale 1.0
2404 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2405 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2406 "Options for creating images from LaTeX fragments.
2407 This is a property list with the following properties:
2408 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2409 `default' means use the foreground of the default face.
2410 :background the background color, or \"Transparent\".
2411 `default' means use the background of the default face.
2412 :scale a scaling factor for the size of the images.
2413 :html-foreground, :html-background, :html-scale
2414 the same numbers for HTML export.
2415 :matchers a list indicating which matchers should be used to
2416 find LaTeX fragments. Valid members of this list are:
2417 \"begin\" find environments
2418 \"$1\" find single characters surrounded by $.$
2419 \"$\" find math expressions surrounded by $...$
2420 \"$$\" find math expressions surrounded by $$....$$
2421 \"\\(\" find math expressions surrounded by \\(...\\)
2422 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2423 :group 'org-latex
2424 :type 'plist)
2426 (defcustom org-format-latex-header "\\documentclass{article}
2427 \\usepackage{fullpage} % do not remove
2428 \\usepackage{amssymb}
2429 \\usepackage[usenames]{color}
2430 \\usepackage{amsmath}
2431 \\usepackage{latexsym}
2432 \\usepackage[mathscr]{eucal}
2433 \\pagestyle{empty} % do not remove"
2434 "The document header used for processing LaTeX fragments."
2435 :group 'org-latex
2436 :type 'string)
2439 (defgroup org-font-lock nil
2440 "Font-lock settings for highlighting in Org-mode."
2441 :tag "Org Font Lock"
2442 :group 'org)
2444 (defcustom org-level-color-stars-only nil
2445 "Non-nil means fontify only the stars in each headline.
2446 When nil, the entire headline is fontified.
2447 Changing it requires restart of `font-lock-mode' to become effective
2448 also in regions already fontified."
2449 :group 'org-font-lock
2450 :type 'boolean)
2452 (defcustom org-hide-leading-stars nil
2453 "Non-nil means, hide the first N-1 stars in a headline.
2454 This works by using the face `org-hide' for these stars. This
2455 face is white for a light background, and black for a dark
2456 background. You may have to customize the face `org-hide' to
2457 make this work.
2458 Changing it requires restart of `font-lock-mode' to become effective
2459 also in regions already fontified.
2460 You may also set this on a per-file basis by adding one of the following
2461 lines to the buffer:
2463 #+STARTUP: hidestars
2464 #+STARTUP: showstars"
2465 :group 'org-font-lock
2466 :type 'boolean)
2468 (defcustom org-fontify-done-headline nil
2469 "Non-nil means, change the face of a headline if it is marked DONE.
2470 Normally, only the TODO/DONE keyword indicates the state of a headline.
2471 When this is non-nil, the headline after the keyword is set to the
2472 `org-headline-done' as an additional indication."
2473 :group 'org-font-lock
2474 :type 'boolean)
2476 (defcustom org-fontify-emphasized-text t
2477 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2478 Changing this variable requires a restart of Emacs to take effect."
2479 :group 'org-font-lock
2480 :type 'boolean)
2482 (defcustom org-highlight-latex-fragments-and-specials nil
2483 "Non-nil means, fontify what is treated specially by the exporters."
2484 :group 'org-font-lock
2485 :type 'boolean)
2487 (defcustom org-hide-emphasis-markers nil
2488 "Non-nil mean font-lock should hide the emphasis marker characters."
2489 :group 'org-font-lock
2490 :type 'boolean)
2492 (defvar org-emph-re nil
2493 "Regular expression for matching emphasis.")
2494 (defvar org-verbatim-re nil
2495 "Regular expression for matching verbatim text.")
2496 (defvar org-emphasis-regexp-components) ; defined just below
2497 (defvar org-emphasis-alist) ; defined just below
2498 (defun org-set-emph-re (var val)
2499 "Set variable and compute the emphasis regular expression."
2500 (set var val)
2501 (when (and (boundp 'org-emphasis-alist)
2502 (boundp 'org-emphasis-regexp-components)
2503 org-emphasis-alist org-emphasis-regexp-components)
2504 (let* ((e org-emphasis-regexp-components)
2505 (pre (car e))
2506 (post (nth 1 e))
2507 (border (nth 2 e))
2508 (body (nth 3 e))
2509 (nl (nth 4 e))
2510 (body1 (concat body "*?"))
2511 (markers (mapconcat 'car org-emphasis-alist ""))
2512 (vmarkers (mapconcat
2513 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2514 org-emphasis-alist "")))
2515 ;; make sure special characters appear at the right position in the class
2516 (if (string-match "\\^" markers)
2517 (setq markers (concat (replace-match "" t t markers) "^")))
2518 (if (string-match "-" markers)
2519 (setq markers (concat (replace-match "" t t markers) "-")))
2520 (if (string-match "\\^" vmarkers)
2521 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2522 (if (string-match "-" vmarkers)
2523 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2524 (if (> nl 0)
2525 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2526 (int-to-string nl) "\\}")))
2527 ;; Make the regexp
2528 (setq org-emph-re
2529 (concat "\\([" pre "]\\|^\\)"
2530 "\\("
2531 "\\([" markers "]\\)"
2532 "\\("
2533 "[^" border "]\\|"
2534 "[^" border "]"
2535 body1
2536 "[^" border "]"
2537 "\\)"
2538 "\\3\\)"
2539 "\\([" post "]\\|$\\)"))
2540 (setq org-verbatim-re
2541 (concat "\\([" pre "]\\|^\\)"
2542 "\\("
2543 "\\([" vmarkers "]\\)"
2544 "\\("
2545 "[^" border "]\\|"
2546 "[^" border "]"
2547 body1
2548 "[^" border "]"
2549 "\\)"
2550 "\\3\\)"
2551 "\\([" post "]\\|$\\)")))))
2553 (defcustom org-emphasis-regexp-components
2554 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2555 "Components used to build the regular expression for emphasis.
2556 This is a list with 6 entries. Terminology: In an emphasis string
2557 like \" *strong word* \", we call the initial space PREMATCH, the final
2558 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2559 and \"trong wor\" is the body. The different components in this variable
2560 specify what is allowed/forbidden in each part:
2562 pre Chars allowed as prematch. Beginning of line will be allowed too.
2563 post Chars allowed as postmatch. End of line will be allowed too.
2564 border The chars *forbidden* as border characters.
2565 body-regexp A regexp like \".\" to match a body character. Don't use
2566 non-shy groups here, and don't allow newline here.
2567 newline The maximum number of newlines allowed in an emphasis exp.
2569 Use customize to modify this, or restart Emacs after changing it."
2570 :group 'org-font-lock
2571 :set 'org-set-emph-re
2572 :type '(list
2573 (sexp :tag "Allowed chars in pre ")
2574 (sexp :tag "Allowed chars in post ")
2575 (sexp :tag "Forbidden chars in border ")
2576 (sexp :tag "Regexp for body ")
2577 (integer :tag "number of newlines allowed")
2578 (option (boolean :tag "Please ignore this button"))))
2580 (defcustom org-emphasis-alist
2581 `(("*" bold "<b>" "</b>")
2582 ("/" italic "<i>" "</i>")
2583 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2584 ("=" org-code "<code>" "</code>" verbatim)
2585 ("~" org-verbatim "<code>" "</code>" verbatim)
2586 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2587 "<del>" "</del>")
2589 "Special syntax for emphasized text.
2590 Text starting and ending with a special character will be emphasized, for
2591 example *bold*, _underlined_ and /italic/. This variable sets the marker
2592 characters, the face to be used by font-lock for highlighting in Org-mode
2593 Emacs buffers, and the HTML tags to be used for this.
2594 Use customize to modify this, or restart Emacs after changing it."
2595 :group 'org-font-lock
2596 :set 'org-set-emph-re
2597 :type '(repeat
2598 (list
2599 (string :tag "Marker character")
2600 (choice
2601 (face :tag "Font-lock-face")
2602 (plist :tag "Face property list"))
2603 (string :tag "HTML start tag")
2604 (string :tag "HTML end tag")
2605 (option (const verbatim)))))
2607 ;;; Miscellaneous options
2609 (defgroup org-completion nil
2610 "Completion in Org-mode."
2611 :tag "Org Completion"
2612 :group 'org)
2614 (defcustom org-completion-use-ido nil
2615 "Non-nil means, use ido completion wherever possible.
2616 Note that `ido-mode' must be active for this variable to be relevant.
2617 If you decide to turn this variable on, you might well want to turn off
2618 `org-outline-path-complete-in-steps'."
2619 :group 'org-completion
2620 :type 'boolean)
2622 (defcustom org-completion-fallback-command 'hippie-expand
2623 "The expansion command called by \\[org-complete] in normal context.
2624 Normal means, no org-mode-specific context."
2625 :group 'org-completion
2626 :type 'function)
2628 ;;; Functions and variables from ther packages
2629 ;; Declared here to avoid compiler warnings
2631 ;; XEmacs only
2632 (defvar outline-mode-menu-heading)
2633 (defvar outline-mode-menu-show)
2634 (defvar outline-mode-menu-hide)
2635 (defvar zmacs-regions) ; XEmacs regions
2637 ;; Emacs only
2638 (defvar mark-active)
2640 ;; Various packages
2641 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2642 (declare-function calendar-forward-day "cal-move" (arg))
2643 (declare-function calendar-goto-date "cal-move" (date))
2644 (declare-function calendar-goto-today "cal-move" ())
2645 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2646 (defvar calc-embedded-close-formula)
2647 (defvar calc-embedded-open-formula)
2648 (declare-function cdlatex-tab "ext:cdlatex" ())
2649 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2650 (defvar font-lock-unfontify-region-function)
2651 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2652 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2653 (defvar iswitchb-temp-buflist)
2654 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2655 (defvar org-agenda-tags-todo-honor-ignore-options)
2656 (declare-function org-agenda-skip "org-agenda" ())
2657 (declare-function org-format-agenda-item "org-agenda"
2658 (extra txt &optional category tags dotime noprefix remove-re))
2659 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2660 (declare-function org-agenda-change-all-lines "org-agenda"
2661 (newhead hdmarker &optional fixface just-this))
2662 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2663 (declare-function org-agenda-maybe-redo "org-agenda" ())
2664 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2665 (beg end))
2666 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2667 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2668 "org-agenda" (&optional end))
2670 (declare-function parse-time-string "parse-time" (string))
2671 (declare-function remember "remember" (&optional initial))
2672 (declare-function remember-buffer-desc "remember" ())
2673 (declare-function remember-finalize "remember" ())
2674 (defvar remember-save-after-remembering)
2675 (defvar remember-data-file)
2676 (defvar remember-register)
2677 (defvar remember-buffer)
2678 (defvar remember-handler-functions)
2679 (defvar remember-annotation-functions)
2680 (defvar texmathp-why)
2681 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2682 (declare-function table--at-cell-p "table" (position &optional object at-column))
2684 (defvar w3m-current-url)
2685 (defvar w3m-current-title)
2687 (defvar org-latex-regexps)
2689 ;;; Autoload and prepare some org modules
2691 ;; Some table stuff that needs to be defined here, because it is used
2692 ;; by the functions setting up org-mode or checking for table context.
2694 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2695 "Detects an org-type or table-type table.")
2696 (defconst org-table-line-regexp "^[ \t]*|"
2697 "Detects an org-type table line.")
2698 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2699 "Detects an org-type table line.")
2700 (defconst org-table-hline-regexp "^[ \t]*|-"
2701 "Detects an org-type table hline.")
2702 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2703 "Detects a table-type table hline.")
2704 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2705 "Searching from within a table (any type) this finds the first line
2706 outside the table.")
2708 ;; Autoload the functions in org-table.el that are needed by functions here.
2710 (eval-and-compile
2711 (org-autoload "org-table"
2712 '(org-table-align org-table-begin org-table-blank-field
2713 org-table-convert org-table-convert-region org-table-copy-down
2714 org-table-copy-region org-table-create
2715 org-table-create-or-convert-from-region
2716 org-table-create-with-table.el org-table-current-dline
2717 org-table-cut-region org-table-delete-column org-table-edit-field
2718 org-table-edit-formulas org-table-end org-table-eval-formula
2719 org-table-export org-table-field-info
2720 org-table-get-stored-formulas org-table-goto-column
2721 org-table-hline-and-move org-table-import org-table-insert-column
2722 org-table-insert-hline org-table-insert-row org-table-iterate
2723 org-table-justify-field-maybe org-table-kill-row
2724 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2725 org-table-move-column org-table-move-column-left
2726 org-table-move-column-right org-table-move-row
2727 org-table-move-row-down org-table-move-row-up
2728 org-table-next-field org-table-next-row org-table-paste-rectangle
2729 org-table-previous-field org-table-recalculate
2730 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2731 org-table-toggle-coordinate-overlays
2732 org-table-toggle-formula-debugger org-table-wrap-region
2733 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2735 (defun org-at-table-p (&optional table-type)
2736 "Return t if the cursor is inside an org-type table.
2737 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2738 (if org-enable-table-editor
2739 (save-excursion
2740 (beginning-of-line 1)
2741 (looking-at (if table-type org-table-any-line-regexp
2742 org-table-line-regexp)))
2743 nil))
2744 (defsubst org-table-p () (org-at-table-p))
2746 (defun org-at-table.el-p ()
2747 "Return t if and only if we are at a table.el table."
2748 (and (org-at-table-p 'any)
2749 (save-excursion
2750 (goto-char (org-table-begin 'any))
2751 (looking-at org-table1-hline-regexp))))
2752 (defun org-table-recognize-table.el ()
2753 "If there is a table.el table nearby, recognize it and move into it."
2754 (if org-table-tab-recognizes-table.el
2755 (if (org-at-table.el-p)
2756 (progn
2757 (beginning-of-line 1)
2758 (if (looking-at org-table-dataline-regexp)
2760 (if (looking-at org-table1-hline-regexp)
2761 (progn
2762 (beginning-of-line 2)
2763 (if (looking-at org-table-any-border-regexp)
2764 (beginning-of-line -1)))))
2765 (if (re-search-forward "|" (org-table-end t) t)
2766 (progn
2767 (require 'table)
2768 (if (table--at-cell-p (point))
2770 (message "recognizing table.el table...")
2771 (table-recognize-table)
2772 (message "recognizing table.el table...done")))
2773 (error "This should not happen..."))
2775 nil)
2776 nil))
2778 (defun org-at-table-hline-p ()
2779 "Return t if the cursor is inside a hline in a table."
2780 (if org-enable-table-editor
2781 (save-excursion
2782 (beginning-of-line 1)
2783 (looking-at org-table-hline-regexp))
2784 nil))
2786 (defvar org-table-clean-did-remove-column nil)
2788 (defun org-table-map-tables (function)
2789 "Apply FUNCTION to the start of all tables in the buffer."
2790 (save-excursion
2791 (save-restriction
2792 (widen)
2793 (goto-char (point-min))
2794 (while (re-search-forward org-table-any-line-regexp nil t)
2795 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2796 (beginning-of-line 1)
2797 (if (looking-at org-table-line-regexp)
2798 (save-excursion (funcall function)))
2799 (re-search-forward org-table-any-border-regexp nil 1))))
2800 (message "Mapping tables: done"))
2802 ;; Declare and autoload functions from org-exp.el
2804 (declare-function org-default-export-plist "org-exp")
2805 (declare-function org-infile-export-plist "org-exp")
2806 (declare-function org-get-current-options "org-exp")
2807 (eval-and-compile
2808 (org-autoload "org-exp"
2809 '(org-export org-export-as-ascii org-export-visible
2810 org-insert-export-options-template org-export-as-html-and-open
2811 org-export-as-html-batch org-export-as-html-to-buffer
2812 org-replace-region-by-html org-export-region-as-html
2813 org-export-as-html org-export-icalendar-this-file
2814 org-export-icalendar-all-agenda-files
2815 org-table-clean-before-export
2816 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2818 ;; Declare and autoload functions from org-agenda.el
2820 (eval-and-compile
2821 (org-autoload "org-agenda"
2822 '(org-agenda org-agenda-list org-search-view
2823 org-todo-list org-tags-view org-agenda-list-stuck-projects
2824 org-diary org-agenda-to-appt
2825 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2827 ;; Autoload org-remember
2829 (eval-and-compile
2830 (org-autoload "org-remember"
2831 '(org-remember-insinuate org-remember-annotation
2832 org-remember-apply-template org-remember org-remember-handler)))
2834 ;; Autoload org-clock.el
2837 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2838 (beg end))
2839 (declare-function org-clock-update-mode-line "org-clock" ())
2840 (defvar org-clock-start-time)
2841 (defvar org-clock-marker (make-marker)
2842 "Marker recording the last clock-in.")
2844 (eval-and-compile
2845 (org-autoload
2846 "org-clock"
2847 '(org-clock-in org-clock-out org-clock-cancel
2848 org-clock-goto org-clock-sum org-clock-display
2849 org-clock-remove-overlays org-clock-report
2850 org-clocktable-shift org-dblock-write:clocktable
2851 org-get-clocktable)))
2853 (defun org-clock-update-time-maybe ()
2854 "If this is a CLOCK line, update it and return t.
2855 Otherwise, return nil."
2856 (interactive)
2857 (save-excursion
2858 (beginning-of-line 1)
2859 (skip-chars-forward " \t")
2860 (when (looking-at org-clock-string)
2861 (let ((re (concat "[ \t]*" org-clock-string
2862 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2863 "\\([ \t]*=>.*\\)?\\)?"))
2864 ts te h m s neg)
2865 (cond
2866 ((not (looking-at re))
2867 nil)
2868 ((not (match-end 2))
2869 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2870 (> org-clock-marker (point))
2871 (<= org-clock-marker (point-at-eol)))
2872 ;; The clock is running here
2873 (setq org-clock-start-time
2874 (apply 'encode-time
2875 (org-parse-time-string (match-string 1))))
2876 (org-clock-update-mode-line)))
2878 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2879 (end-of-line 1)
2880 (setq ts (match-string 1)
2881 te (match-string 3))
2882 (setq s (- (time-to-seconds
2883 (apply 'encode-time (org-parse-time-string te)))
2884 (time-to-seconds
2885 (apply 'encode-time (org-parse-time-string ts))))
2886 neg (< s 0)
2887 s (abs s)
2888 h (floor (/ s 3600))
2889 s (- s (* 3600 h))
2890 m (floor (/ s 60))
2891 s (- s (* 60 s)))
2892 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2893 t))))))
2895 (defun org-check-running-clock ()
2896 "Check if the current buffer contains the running clock.
2897 If yes, offer to stop it and to save the buffer with the changes."
2898 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2899 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2900 (buffer-name))))
2901 (org-clock-out)
2902 (when (y-or-n-p "Save changed buffer?")
2903 (save-buffer))))
2905 (defun org-clocktable-try-shift (dir n)
2906 "Check if this line starts a clock table, if yes, shift the time block."
2907 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2908 (org-clocktable-shift dir n)))
2910 ;; Autoload org-timer.el
2912 ;(declare-function org-timer "org-timer")
2914 (eval-and-compile
2915 (org-autoload
2916 "org-timer"
2917 '(org-timer-start org-timer org-timer-item
2918 org-timer-change-times-in-region)))
2921 ;; Autoload archiving code
2922 ;; The stuff that is needed for cycling and tags has to be defined here.
2924 (defgroup org-archive nil
2925 "Options concerning archiving in Org-mode."
2926 :tag "Org Archive"
2927 :group 'org-structure)
2929 (defcustom org-archive-location "%s_archive::"
2930 "The location where subtrees should be archived.
2932 The value of this variable is a string, consisting of two parts,
2933 separated by a double-colon. The first part is a filename and
2934 the second part is a headline.
2936 When the filename is omitted, archiving happens in the same file.
2937 %s in the filename will be replaced by the current file
2938 name (without the directory part). Archiving to a different file
2939 is useful to keep archived entries from contributing to the
2940 Org-mode Agenda.
2942 The archived entries will be filed as subtrees of the specified
2943 headline. When the headline is omitted, the subtrees are simply
2944 filed away at the end of the file, as top-level entries. Also in
2945 the heading you can use %s to represent the file name, this can be
2946 useful when using the same archive for a number of different files.
2948 Here are a few examples:
2949 \"%s_archive::\"
2950 If the current file is Projects.org, archive in file
2951 Projects.org_archive, as top-level trees. This is the default.
2953 \"::* Archived Tasks\"
2954 Archive in the current file, under the top-level headline
2955 \"* Archived Tasks\".
2957 \"~/org/archive.org::\"
2958 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2960 \"~/org/archive.org::From %s\"
2961 Archive in file ~/org/archive.org (absolute path), und headlines
2962 \"From FILENAME\" where file name is the current file name.
2964 \"basement::** Finished Tasks\"
2965 Archive in file ./basement (relative path), as level 3 trees
2966 below the level 2 heading \"** Finished Tasks\".
2968 You may set this option on a per-file basis by adding to the buffer a
2969 line like
2971 #+ARCHIVE: basement::** Finished Tasks
2973 You may also define it locally for a subtree by setting an ARCHIVE property
2974 in the entry. If such a property is found in an entry, or anywhere up
2975 the hierarchy, it will be used."
2976 :group 'org-archive
2977 :type 'string)
2979 (defcustom org-archive-tag "ARCHIVE"
2980 "The tag that marks a subtree as archived.
2981 An archived subtree does not open during visibility cycling, and does
2982 not contribute to the agenda listings.
2983 After changing this, font-lock must be restarted in the relevant buffers to
2984 get the proper fontification."
2985 :group 'org-archive
2986 :group 'org-keywords
2987 :type 'string)
2989 (defcustom org-agenda-skip-archived-trees t
2990 "Non-nil means, the agenda will skip any items located in archived trees.
2991 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2992 variable is no longer recommended, you should leave it at the value t.
2993 Instead, use the key `v' to cycle the archives-mode in the agenda."
2994 :group 'org-archive
2995 :group 'org-agenda-skip
2996 :type 'boolean)
2998 (defcustom org-cycle-open-archived-trees nil
2999 "Non-nil means, `org-cycle' will open archived trees.
3000 An archived tree is a tree marked with the tag ARCHIVE.
3001 When nil, archived trees will stay folded. You can still open them with
3002 normal outline commands like `show-all', but not with the cycling commands."
3003 :group 'org-archive
3004 :group 'org-cycle
3005 :type 'boolean)
3007 (defcustom org-sparse-tree-open-archived-trees nil
3008 "Non-nil means sparse tree construction shows matches in archived trees.
3009 When nil, matches in these trees are highlighted, but the trees are kept in
3010 collapsed state."
3011 :group 'org-archive
3012 :group 'org-sparse-trees
3013 :type 'boolean)
3015 (defun org-cycle-hide-archived-subtrees (state)
3016 "Re-hide all archived subtrees after a visibility state change."
3017 (when (and (not org-cycle-open-archived-trees)
3018 (not (memq state '(overview folded))))
3019 (save-excursion
3020 (let* ((globalp (memq state '(contents all)))
3021 (beg (if globalp (point-min) (point)))
3022 (end (if globalp (point-max) (org-end-of-subtree t))))
3023 (org-hide-archived-subtrees beg end)
3024 (goto-char beg)
3025 (if (looking-at (concat ".*:" org-archive-tag ":"))
3026 (message "%s" (substitute-command-keys
3027 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3029 (defun org-force-cycle-archived ()
3030 "Cycle subtree even if it is archived."
3031 (interactive)
3032 (setq this-command 'org-cycle)
3033 (let ((org-cycle-open-archived-trees t))
3034 (call-interactively 'org-cycle)))
3036 (defun org-hide-archived-subtrees (beg end)
3037 "Re-hide all archived subtrees after a visibility state change."
3038 (save-excursion
3039 (let* ((re (concat ":" org-archive-tag ":")))
3040 (goto-char beg)
3041 (while (re-search-forward re end t)
3042 (and (org-on-heading-p) (hide-subtree))
3043 (org-end-of-subtree t)))))
3045 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3047 (eval-and-compile
3048 (org-autoload "org-archive"
3049 '(org-add-archive-files org-archive-subtree
3050 org-archive-to-archive-sibling org-toggle-archive-tag)))
3052 ;; Autoload Column View Code
3054 (declare-function org-columns-number-to-string "org-colview")
3055 (declare-function org-columns-get-format-and-top-level "org-colview")
3056 (declare-function org-columns-compute "org-colview")
3058 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3059 '(org-columns-number-to-string org-columns-get-format-and-top-level
3060 org-columns-compute org-agenda-columns org-columns-remove-overlays
3061 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3063 ;; Autoload ID code
3065 (declare-function org-id-store-link "org-id")
3066 (declare-function org-id-locations-load "org-id")
3067 (declare-function org-id-locations-save "org-id")
3068 (defvar org-id-track-globally)
3069 (org-autoload "org-id"
3070 '(org-id-get-create org-id-new org-id-copy org-id-get
3071 org-id-get-with-outline-path-completion
3072 org-id-get-with-outline-drilling
3073 org-id-goto org-id-find org-id-store-link))
3075 ;; Autoload Plotting Code
3077 (org-autoload "org-plot"
3078 '(org-plot/gnuplot))
3080 ;;; Variables for pre-computed regular expressions, all buffer local
3082 (defvar org-drawer-regexp nil
3083 "Matches first line of a hidden block.")
3084 (make-variable-buffer-local 'org-drawer-regexp)
3085 (defvar org-todo-regexp nil
3086 "Matches any of the TODO state keywords.")
3087 (make-variable-buffer-local 'org-todo-regexp)
3088 (defvar org-not-done-regexp nil
3089 "Matches any of the TODO state keywords except the last one.")
3090 (make-variable-buffer-local 'org-not-done-regexp)
3091 (defvar org-todo-line-regexp nil
3092 "Matches a headline and puts TODO state into group 2 if present.")
3093 (make-variable-buffer-local 'org-todo-line-regexp)
3094 (defvar org-complex-heading-regexp nil
3095 "Matches a headline and puts everything into groups:
3096 group 1: the stars
3097 group 2: The todo keyword, maybe
3098 group 3: Priority cookie
3099 group 4: True headline
3100 group 5: Tags")
3101 (make-variable-buffer-local 'org-complex-heading-regexp)
3102 (defvar org-todo-line-tags-regexp nil
3103 "Matches a headline and puts TODO state into group 2 if present.
3104 Also put tags into group 4 if tags are present.")
3105 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3106 (defvar org-nl-done-regexp nil
3107 "Matches newline followed by a headline with the DONE keyword.")
3108 (make-variable-buffer-local 'org-nl-done-regexp)
3109 (defvar org-looking-at-done-regexp nil
3110 "Matches the DONE keyword a point.")
3111 (make-variable-buffer-local 'org-looking-at-done-regexp)
3112 (defvar org-ds-keyword-length 12
3113 "Maximum length of the Deadline and SCHEDULED keywords.")
3114 (make-variable-buffer-local 'org-ds-keyword-length)
3115 (defvar org-deadline-regexp nil
3116 "Matches the DEADLINE keyword.")
3117 (make-variable-buffer-local 'org-deadline-regexp)
3118 (defvar org-deadline-time-regexp nil
3119 "Matches the DEADLINE keyword together with a time stamp.")
3120 (make-variable-buffer-local 'org-deadline-time-regexp)
3121 (defvar org-deadline-line-regexp nil
3122 "Matches the DEADLINE keyword and the rest of the line.")
3123 (make-variable-buffer-local 'org-deadline-line-regexp)
3124 (defvar org-scheduled-regexp nil
3125 "Matches the SCHEDULED keyword.")
3126 (make-variable-buffer-local 'org-scheduled-regexp)
3127 (defvar org-scheduled-time-regexp nil
3128 "Matches the SCHEDULED keyword together with a time stamp.")
3129 (make-variable-buffer-local 'org-scheduled-time-regexp)
3130 (defvar org-closed-time-regexp nil
3131 "Matches the CLOSED keyword together with a time stamp.")
3132 (make-variable-buffer-local 'org-closed-time-regexp)
3134 (defvar org-keyword-time-regexp nil
3135 "Matches any of the 4 keywords, together with the time stamp.")
3136 (make-variable-buffer-local 'org-keyword-time-regexp)
3137 (defvar org-keyword-time-not-clock-regexp nil
3138 "Matches any of the 3 keywords, together with the time stamp.")
3139 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3140 (defvar org-maybe-keyword-time-regexp nil
3141 "Matches a timestamp, possibly preceeded by a keyword.")
3142 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3143 (defvar org-planning-or-clock-line-re nil
3144 "Matches a line with planning or clock info.")
3145 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3147 (defconst org-plain-time-of-day-regexp
3148 (concat
3149 "\\(\\<[012]?[0-9]"
3150 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3151 "\\(--?"
3152 "\\(\\<[012]?[0-9]"
3153 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3154 "\\)?")
3155 "Regular expression to match a plain time or time range.
3156 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3157 groups carry important information:
3158 0 the full match
3159 1 the first time, range or not
3160 8 the second time, if it is a range.")
3162 (defconst org-plain-time-extension-regexp
3163 (concat
3164 "\\(\\<[012]?[0-9]"
3165 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3166 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3167 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3168 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3169 groups carry important information:
3170 0 the full match
3171 7 hours of duration
3172 9 minutes of duration")
3174 (defconst org-stamp-time-of-day-regexp
3175 (concat
3176 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3177 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3178 "\\(--?"
3179 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3180 "Regular expression to match a timestamp time or time range.
3181 After a match, the following groups carry important information:
3182 0 the full match
3183 1 date plus weekday, for backreferencing to make sure both times on same day
3184 2 the first time, range or not
3185 4 the second time, if it is a range.")
3187 (defconst org-startup-options
3188 '(("fold" org-startup-folded t)
3189 ("overview" org-startup-folded t)
3190 ("nofold" org-startup-folded nil)
3191 ("showall" org-startup-folded nil)
3192 ("content" org-startup-folded content)
3193 ("hidestars" org-hide-leading-stars t)
3194 ("showstars" org-hide-leading-stars nil)
3195 ("odd" org-odd-levels-only t)
3196 ("oddeven" org-odd-levels-only nil)
3197 ("align" org-startup-align-all-tables t)
3198 ("noalign" org-startup-align-all-tables nil)
3199 ("customtime" org-display-custom-times t)
3200 ("logdone" org-log-done time)
3201 ("lognotedone" org-log-done note)
3202 ("nologdone" org-log-done nil)
3203 ("lognoteclock-out" org-log-note-clock-out t)
3204 ("nolognoteclock-out" org-log-note-clock-out nil)
3205 ("logrepeat" org-log-repeat state)
3206 ("lognoterepeat" org-log-repeat note)
3207 ("nologrepeat" org-log-repeat nil)
3208 ("fninline" org-footnote-define-inline t)
3209 ("nofninline" org-footnote-define-inline nil)
3210 ("fnlocal" org-footnote-section nil)
3211 ("fnauto" org-footnote-auto-label t)
3212 ("fnprompt" org-footnote-auto-label nil)
3213 ("fnconfirm" org-footnote-auto-label confirm)
3214 ("fnplain" org-footnote-auto-label plain)
3215 ("constcgs" constants-unit-system cgs)
3216 ("constSI" constants-unit-system SI))
3217 "Variable associated with STARTUP options for org-mode.
3218 Each element is a list of three items: The startup options as written
3219 in the #+STARTUP line, the corresponding variable, and the value to
3220 set this variable to if the option is found. An optional forth element PUSH
3221 means to push this value onto the list in the variable.")
3223 (defun org-set-regexps-and-options ()
3224 "Precompute regular expressions for current buffer."
3225 (when (org-mode-p)
3226 (org-set-local 'org-todo-kwd-alist nil)
3227 (org-set-local 'org-todo-key-alist nil)
3228 (org-set-local 'org-todo-key-trigger nil)
3229 (org-set-local 'org-todo-keywords-1 nil)
3230 (org-set-local 'org-done-keywords nil)
3231 (org-set-local 'org-todo-heads nil)
3232 (org-set-local 'org-todo-sets nil)
3233 (org-set-local 'org-todo-log-states nil)
3234 (org-set-local 'org-file-properties nil)
3235 (org-set-local 'org-file-tags nil)
3236 (let ((re (org-make-options-regexp
3237 '("CATEGORY" "TODO" "COLUMNS"
3238 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3239 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3240 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3241 (splitre "[ \t]+")
3242 kwds kws0 kwsa key log value cat arch tags const links hw dws
3243 tail sep kws1 prio props ftags drawers
3244 ext-setup-or-nil setup-contents (start 0))
3245 (save-excursion
3246 (save-restriction
3247 (widen)
3248 (goto-char (point-min))
3249 (while (or (and ext-setup-or-nil
3250 (string-match re ext-setup-or-nil start)
3251 (setq start (match-end 0)))
3252 (and (setq ext-setup-or-nil nil start 0)
3253 (re-search-forward re nil t)))
3254 (setq key (upcase (match-string 1 ext-setup-or-nil))
3255 value (org-match-string-no-properties 2 ext-setup-or-nil))
3256 (cond
3257 ((equal key "CATEGORY")
3258 (if (string-match "[ \t]+$" value)
3259 (setq value (replace-match "" t t value)))
3260 (setq cat value))
3261 ((member key '("SEQ_TODO" "TODO"))
3262 (push (cons 'sequence (org-split-string value splitre)) kwds))
3263 ((equal key "TYP_TODO")
3264 (push (cons 'type (org-split-string value splitre)) kwds))
3265 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3266 ;; general TODO-like setup
3267 (push (cons (intern (downcase (match-string 1 key)))
3268 (org-split-string value splitre)) kwds))
3269 ((equal key "TAGS")
3270 (setq tags (append tags (org-split-string value splitre))))
3271 ((equal key "COLUMNS")
3272 (org-set-local 'org-columns-default-format value))
3273 ((equal key "LINK")
3274 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3275 (push (cons (match-string 1 value)
3276 (org-trim (match-string 2 value)))
3277 links)))
3278 ((equal key "PRIORITIES")
3279 (setq prio (org-split-string value " +")))
3280 ((equal key "PROPERTY")
3281 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3282 (push (cons (match-string 1 value) (match-string 2 value))
3283 props)))
3284 ((equal key "FILETAGS")
3285 (when (string-match "\\S-" value)
3286 (setq ftags
3287 (append
3288 ftags
3289 (apply 'append
3290 (mapcar (lambda (x) (org-split-string x ":"))
3291 (org-split-string value)))))))
3292 ((equal key "DRAWERS")
3293 (setq drawers (org-split-string value splitre)))
3294 ((equal key "CONSTANTS")
3295 (setq const (append const (org-split-string value splitre))))
3296 ((equal key "STARTUP")
3297 (let ((opts (org-split-string value splitre))
3298 l var val)
3299 (while (setq l (pop opts))
3300 (when (setq l (assoc l org-startup-options))
3301 (setq var (nth 1 l) val (nth 2 l))
3302 (if (not (nth 3 l))
3303 (set (make-local-variable var) val)
3304 (if (not (listp (symbol-value var)))
3305 (set (make-local-variable var) nil))
3306 (set (make-local-variable var) (symbol-value var))
3307 (add-to-list var val))))))
3308 ((equal key "ARCHIVE")
3309 (string-match " *$" value)
3310 (setq arch (replace-match "" t t value))
3311 (remove-text-properties 0 (length arch)
3312 '(face t fontified t) arch))
3313 ((equal key "SETUPFILE")
3314 (setq setup-contents (org-file-contents
3315 (expand-file-name
3316 (org-remove-double-quotes value))
3317 'noerror))
3318 (if (not ext-setup-or-nil)
3319 (setq ext-setup-or-nil setup-contents start 0)
3320 (setq ext-setup-or-nil
3321 (concat (substring ext-setup-or-nil 0 start)
3322 "\n" setup-contents "\n"
3323 (substring ext-setup-or-nil start)))))
3324 ))))
3325 (when cat
3326 (org-set-local 'org-category (intern cat))
3327 (push (cons "CATEGORY" cat) props))
3328 (when prio
3329 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3330 (setq prio (mapcar 'string-to-char prio))
3331 (org-set-local 'org-highest-priority (nth 0 prio))
3332 (org-set-local 'org-lowest-priority (nth 1 prio))
3333 (org-set-local 'org-default-priority (nth 2 prio)))
3334 (and props (org-set-local 'org-file-properties (nreverse props)))
3335 (and ftags (org-set-local 'org-file-tags ftags))
3336 (and drawers (org-set-local 'org-drawers drawers))
3337 (and arch (org-set-local 'org-archive-location arch))
3338 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3339 ;; Process the TODO keywords
3340 (unless kwds
3341 ;; Use the global values as if they had been given locally.
3342 (setq kwds (default-value 'org-todo-keywords))
3343 (if (stringp (car kwds))
3344 (setq kwds (list (cons org-todo-interpretation
3345 (default-value 'org-todo-keywords)))))
3346 (setq kwds (reverse kwds)))
3347 (setq kwds (nreverse kwds))
3348 (let (inter kws kw)
3349 (while (setq kws (pop kwds))
3350 (let ((kws (or
3351 (run-hook-with-args-until-success
3352 'org-todo-setup-filter-hook kws)
3353 kws)))
3354 (setq inter (pop kws) sep (member "|" kws)
3355 kws0 (delete "|" (copy-sequence kws))
3356 kwsa nil
3357 kws1 (mapcar
3358 (lambda (x)
3359 ;; 1 2
3360 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3361 (progn
3362 (setq kw (match-string 1 x)
3363 key (and (match-end 2) (match-string 2 x))
3364 log (org-extract-log-state-settings x))
3365 (push (cons kw (and key (string-to-char key))) kwsa)
3366 (and log (push log org-todo-log-states))
3368 (error "Invalid TODO keyword %s" x)))
3369 kws0)
3370 kwsa (if kwsa (append '((:startgroup))
3371 (nreverse kwsa)
3372 '((:endgroup))))
3373 hw (car kws1)
3374 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3375 tail (list inter hw (car dws) (org-last dws))))
3376 (add-to-list 'org-todo-heads hw 'append)
3377 (push kws1 org-todo-sets)
3378 (setq org-done-keywords (append org-done-keywords dws nil))
3379 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3380 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3381 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3382 (setq org-todo-sets (nreverse org-todo-sets)
3383 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3384 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3385 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3386 ;; Process the constants
3387 (when const
3388 (let (e cst)
3389 (while (setq e (pop const))
3390 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3391 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3392 (setq org-table-formula-constants-local cst)))
3394 ;; Process the tags.
3395 (when tags
3396 (let (e tgs)
3397 (while (setq e (pop tags))
3398 (cond
3399 ((equal e "{") (push '(:startgroup) tgs))
3400 ((equal e "}") (push '(:endgroup) tgs))
3401 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3402 (push (cons (match-string 1 e)
3403 (string-to-char (match-string 2 e)))
3404 tgs))
3405 (t (push (list e) tgs))))
3406 (org-set-local 'org-tag-alist nil)
3407 (while (setq e (pop tgs))
3408 (or (and (stringp (car e))
3409 (assoc (car e) org-tag-alist))
3410 (push e org-tag-alist)))))
3412 ;; Compute the regular expressions and other local variables
3413 (if (not org-done-keywords)
3414 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3415 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3416 (length org-scheduled-string)
3417 (length org-clock-string)
3418 (length org-closed-string)))
3419 org-drawer-regexp
3420 (concat "^[ \t]*:\\("
3421 (mapconcat 'regexp-quote org-drawers "\\|")
3422 "\\):[ \t]*$")
3423 org-not-done-keywords
3424 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3425 org-todo-regexp
3426 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3427 "\\|") "\\)\\>")
3428 org-not-done-regexp
3429 (concat "\\<\\("
3430 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3431 "\\)\\>")
3432 org-todo-line-regexp
3433 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3434 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3435 "\\)\\>\\)?[ \t]*\\(.*\\)")
3436 org-complex-heading-regexp
3437 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3438 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3439 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3440 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3441 org-nl-done-regexp
3442 (concat "\n\\*+[ \t]+"
3443 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3444 "\\)" "\\>")
3445 org-todo-line-tags-regexp
3446 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3447 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3448 (org-re
3449 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3450 org-looking-at-done-regexp
3451 (concat "^" "\\(?:"
3452 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3453 "\\>")
3454 org-deadline-regexp (concat "\\<" org-deadline-string)
3455 org-deadline-time-regexp
3456 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3457 org-deadline-line-regexp
3458 (concat "\\<\\(" org-deadline-string "\\).*")
3459 org-scheduled-regexp
3460 (concat "\\<" org-scheduled-string)
3461 org-scheduled-time-regexp
3462 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3463 org-closed-time-regexp
3464 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3465 org-keyword-time-regexp
3466 (concat "\\<\\(" org-scheduled-string
3467 "\\|" org-deadline-string
3468 "\\|" org-closed-string
3469 "\\|" org-clock-string "\\)"
3470 " *[[<]\\([^]>]+\\)[]>]")
3471 org-keyword-time-not-clock-regexp
3472 (concat "\\<\\(" org-scheduled-string
3473 "\\|" org-deadline-string
3474 "\\|" org-closed-string
3475 "\\)"
3476 " *[[<]\\([^]>]+\\)[]>]")
3477 org-maybe-keyword-time-regexp
3478 (concat "\\(\\<\\(" org-scheduled-string
3479 "\\|" org-deadline-string
3480 "\\|" org-closed-string
3481 "\\|" org-clock-string "\\)\\)?"
3482 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3483 org-planning-or-clock-line-re
3484 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3485 "\\|" org-deadline-string
3486 "\\|" org-closed-string "\\|" org-clock-string
3487 "\\)\\>\\)")
3489 (org-compute-latex-and-specials-regexp)
3490 (org-set-font-lock-defaults))))
3492 (defun org-file-contents (file &optional noerror)
3493 "Return the contents of FILE, as a string."
3494 (if (or (not file)
3495 (not (file-readable-p file)))
3496 (if noerror
3497 (progn
3498 (message "Cannot read file %s" file)
3499 (ding) (sit-for 2)
3501 (error "Cannot read file %s" file))
3502 (with-temp-buffer
3503 (insert-file-contents file)
3504 (buffer-string))))
3506 (defun org-extract-log-state-settings (x)
3507 "Extract the log state setting from a TODO keyword string.
3508 This will extract info from a string like \"WAIT(w@/!)\"."
3509 (let (kw key log1 log2)
3510 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3511 (setq kw (match-string 1 x)
3512 key (and (match-end 2) (match-string 2 x))
3513 log1 (and (match-end 3) (match-string 3 x))
3514 log2 (and (match-end 4) (match-string 4 x)))
3515 (and (or log1 log2)
3516 (list kw
3517 (and log1 (if (equal log1 "!") 'time 'note))
3518 (and log2 (if (equal log2 "!") 'time 'note)))))))
3520 (defun org-remove-keyword-keys (list)
3521 "Remove a pair of parenthesis at the end of each string in LIST."
3522 (mapcar (lambda (x)
3523 (if (string-match "(.*)$" x)
3524 (substring x 0 (match-beginning 0))
3526 list))
3528 ;; FIXME: this could be done much better, using second characters etc.
3529 (defun org-assign-fast-keys (alist)
3530 "Assign fast keys to a keyword-key alist.
3531 Respect keys that are already there."
3532 (let (new e k c c1 c2 (char ?a))
3533 (while (setq e (pop alist))
3534 (cond
3535 ((equal e '(:startgroup)) (push e new))
3536 ((equal e '(:endgroup)) (push e new))
3538 (setq k (car e) c2 nil)
3539 (if (cdr e)
3540 (setq c (cdr e))
3541 ;; automatically assign a character.
3542 (setq c1 (string-to-char
3543 (downcase (substring
3544 k (if (= (string-to-char k) ?@) 1 0)))))
3545 (if (or (rassoc c1 new) (rassoc c1 alist))
3546 (while (or (rassoc char new) (rassoc char alist))
3547 (setq char (1+ char)))
3548 (setq c2 c1))
3549 (setq c (or c2 char)))
3550 (push (cons k c) new))))
3551 (nreverse new)))
3553 ;;; Some variables used in various places
3555 (defvar org-window-configuration nil
3556 "Used in various places to store a window configuration.")
3557 (defvar org-finish-function nil
3558 "Function to be called when `C-c C-c' is used.
3559 This is for getting out of special buffers like remember.")
3562 ;; FIXME: Occasionally check by commenting these, to make sure
3563 ;; no other functions uses these, forgetting to let-bind them.
3564 (defvar entry)
3565 (defvar state)
3566 (defvar last-state)
3567 (defvar date)
3568 (defvar description)
3570 ;; Defined somewhere in this file, but used before definition.
3571 (defvar org-html-entities)
3572 (defvar org-struct-menu)
3573 (defvar org-org-menu)
3574 (defvar org-tbl-menu)
3575 (defvar org-agenda-keymap)
3577 ;;;; Define the Org-mode
3579 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3580 (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."))
3583 ;; We use a before-change function to check if a table might need
3584 ;; an update.
3585 (defvar org-table-may-need-update t
3586 "Indicates that a table might need an update.
3587 This variable is set by `org-before-change-function'.
3588 `org-table-align' sets it back to nil.")
3589 (defun org-before-change-function (beg end)
3590 "Every change indicates that a table might need an update."
3591 (setq org-table-may-need-update t))
3592 (defvar org-mode-map)
3593 (defvar org-mode-hook nil
3594 "Mode hook for Org-mode, run after the mode was turned on.")
3595 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3596 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3597 (defvar org-table-buffer-is-an nil)
3598 (defconst org-outline-regexp "\\*+ ")
3600 ;;;###autoload
3601 (define-derived-mode org-mode outline-mode "Org"
3602 "Outline-based notes management and organizer, alias
3603 \"Carsten's outline-mode for keeping track of everything.\"
3605 Org-mode develops organizational tasks around a NOTES file which
3606 contains information about projects as plain text. Org-mode is
3607 implemented on top of outline-mode, which is ideal to keep the content
3608 of large files well structured. It supports ToDo items, deadlines and
3609 time stamps, which magically appear in the diary listing of the Emacs
3610 calendar. Tables are easily created with a built-in table editor.
3611 Plain text URL-like links connect to websites, emails (VM), Usenet
3612 messages (Gnus), BBDB entries, and any files related to the project.
3613 For printing and sharing of notes, an Org-mode file (or a part of it)
3614 can be exported as a structured ASCII or HTML file.
3616 The following commands are available:
3618 \\{org-mode-map}"
3620 ;; Get rid of Outline menus, they are not needed
3621 ;; Need to do this here because define-derived-mode sets up
3622 ;; the keymap so late. Still, it is a waste to call this each time
3623 ;; we switch another buffer into org-mode.
3624 (if (featurep 'xemacs)
3625 (when (boundp 'outline-mode-menu-heading)
3626 ;; Assume this is Greg's port, it used easymenu
3627 (easy-menu-remove outline-mode-menu-heading)
3628 (easy-menu-remove outline-mode-menu-show)
3629 (easy-menu-remove outline-mode-menu-hide))
3630 (define-key org-mode-map [menu-bar headings] 'undefined)
3631 (define-key org-mode-map [menu-bar hide] 'undefined)
3632 (define-key org-mode-map [menu-bar show] 'undefined))
3634 (org-load-modules-maybe)
3635 (easy-menu-add org-org-menu)
3636 (easy-menu-add org-tbl-menu)
3637 (org-install-agenda-files-menu)
3638 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3639 (org-add-to-invisibility-spec '(org-cwidth))
3640 (when (featurep 'xemacs)
3641 (org-set-local 'line-move-ignore-invisible t))
3642 (org-set-local 'outline-regexp org-outline-regexp)
3643 (org-set-local 'outline-level 'org-outline-level)
3644 (when (and org-ellipsis
3645 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3646 (fboundp 'make-glyph-code))
3647 (unless org-display-table
3648 (setq org-display-table (make-display-table)))
3649 (set-display-table-slot
3650 org-display-table 4
3651 (vconcat (mapcar
3652 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3653 org-ellipsis)))
3654 (if (stringp org-ellipsis) org-ellipsis "..."))))
3655 (setq buffer-display-table org-display-table))
3656 (org-set-regexps-and-options)
3657 (when (and org-tag-faces (not org-tags-special-faces-re))
3658 ;; tag faces set outside customize.... force initialization.
3659 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3660 ;; Calc embedded
3661 (org-set-local 'calc-embedded-open-mode "# ")
3662 (modify-syntax-entry ?# "<")
3663 (modify-syntax-entry ?@ "w")
3664 (if org-startup-truncated (setq truncate-lines t))
3665 (org-set-local 'font-lock-unfontify-region-function
3666 'org-unfontify-region)
3667 ;; Activate before-change-function
3668 (org-set-local 'org-table-may-need-update t)
3669 (org-add-hook 'before-change-functions 'org-before-change-function nil
3670 'local)
3671 ;; Check for running clock before killing a buffer
3672 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3673 ;; Paragraphs and auto-filling
3674 (org-set-autofill-regexps)
3675 (setq indent-line-function 'org-indent-line-function)
3676 (org-update-radio-target-regexp)
3677 ;; Make sure dependence stuff works reliably, even for users who set it
3678 ;; too late :-(
3679 (if org-enforce-todo-dependencies
3680 (add-hook 'org-blocker-hook
3681 'org-block-todo-from-children-or-siblings)
3682 (remove-hook 'org-blocker-hook
3683 'org-block-todo-from-children-or-siblings))
3684 (if org-enforce-todo-checkbox-dependencies
3685 (add-hook 'org-blocker-hook
3686 'org-block-todo-from-checkboxes)
3687 (remove-hook 'org-blocker-hook
3688 'org-block-todo-from-checkboxes))
3690 ;; Comment characters
3691 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3692 (org-set-local 'comment-padding " ")
3694 ;; Align options lines
3695 (org-set-local
3696 'align-mode-rules-list
3697 '((org-in-buffer-settings
3698 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3699 (modes . '(org-mode)))))
3701 ;; Imenu
3702 (org-set-local 'imenu-create-index-function
3703 'org-imenu-get-tree)
3705 ;; Make isearch reveal context
3706 (if (or (featurep 'xemacs)
3707 (not (boundp 'outline-isearch-open-invisible-function)))
3708 ;; Emacs 21 and XEmacs make use of the hook
3709 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3710 ;; Emacs 22 deals with this through a special variable
3711 (org-set-local 'outline-isearch-open-invisible-function
3712 (lambda (&rest ignore) (org-show-context 'isearch))))
3714 ;; If empty file that did not turn on org-mode automatically, make it to.
3715 (if (and org-insert-mode-line-in-empty-file
3716 (interactive-p)
3717 (= (point-min) (point-max)))
3718 (insert "# -*- mode: org -*-\n\n"))
3720 (unless org-inhibit-startup
3721 (when org-startup-align-all-tables
3722 (let ((bmp (buffer-modified-p)))
3723 (org-table-map-tables 'org-table-align)
3724 (set-buffer-modified-p bmp)))
3725 (org-set-startup-visibility)))
3727 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3729 (defun org-current-time ()
3730 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3731 (if (> (car org-time-stamp-rounding-minutes) 1)
3732 (let ((r (car org-time-stamp-rounding-minutes))
3733 (time (decode-time)))
3734 (apply 'encode-time
3735 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3736 (nthcdr 2 time))))
3737 (current-time)))
3739 ;;;; Font-Lock stuff, including the activators
3741 (defvar org-mouse-map (make-sparse-keymap))
3742 (org-defkey org-mouse-map
3743 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3744 (org-defkey org-mouse-map
3745 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3746 (when org-mouse-1-follows-link
3747 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3748 (when org-tab-follows-link
3749 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3750 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3752 (require 'font-lock)
3754 (defconst org-non-link-chars "]\t\n\r<>")
3755 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3756 "shell" "elisp"))
3757 (defvar org-link-types-re nil
3758 "Matches a link that has a url-like prefix like \"http:\"")
3759 (defvar org-link-re-with-space nil
3760 "Matches a link with spaces, optional angular brackets around it.")
3761 (defvar org-link-re-with-space2 nil
3762 "Matches a link with spaces, optional angular brackets around it.")
3763 (defvar org-link-re-with-space3 nil
3764 "Matches a link with spaces, only for internal part in bracket links.")
3765 (defvar org-angle-link-re nil
3766 "Matches link with angular brackets, spaces are allowed.")
3767 (defvar org-plain-link-re nil
3768 "Matches plain link, without spaces.")
3769 (defvar org-bracket-link-regexp nil
3770 "Matches a link in double brackets.")
3771 (defvar org-bracket-link-analytic-regexp nil
3772 "Regular expression used to analyze links.
3773 Here is what the match groups contain after a match:
3774 1: http:
3775 2: http
3776 3: path
3777 4: [desc]
3778 5: desc")
3779 (defvar org-bracket-link-analytic-regexp++ nil
3780 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3781 (defvar org-any-link-re nil
3782 "Regular expression matching any link.")
3784 (defun org-make-link-regexps ()
3785 "Update the link regular expressions.
3786 This should be called after the variable `org-link-types' has changed."
3787 (setq org-link-types-re
3788 (concat
3789 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3790 org-link-re-with-space
3791 (concat
3792 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3793 "\\([^" org-non-link-chars " ]"
3794 "[^" org-non-link-chars "]*"
3795 "[^" org-non-link-chars " ]\\)>?")
3796 org-link-re-with-space2
3797 (concat
3798 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3799 "\\([^" org-non-link-chars " ]"
3800 "[^\t\n\r]*"
3801 "[^" org-non-link-chars " ]\\)>?")
3802 org-link-re-with-space3
3803 (concat
3804 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3805 "\\([^" org-non-link-chars " ]"
3806 "[^\t\n\r]*\\)")
3807 org-angle-link-re
3808 (concat
3809 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3810 "\\([^" org-non-link-chars " ]"
3811 "[^" org-non-link-chars "]*"
3812 "\\)>")
3813 org-plain-link-re
3814 (concat
3815 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3816 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3817 org-bracket-link-regexp
3818 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3819 org-bracket-link-analytic-regexp
3820 (concat
3821 "\\[\\["
3822 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3823 "\\([^]]+\\)"
3824 "\\]"
3825 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3826 "\\]")
3827 org-bracket-link-analytic-regexp++
3828 (concat
3829 "\\[\\["
3830 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3831 "\\([^]]+\\)"
3832 "\\]"
3833 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3834 "\\]")
3835 org-any-link-re
3836 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3837 org-angle-link-re "\\)\\|\\("
3838 org-plain-link-re "\\)")))
3840 (org-make-link-regexps)
3842 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3843 "Regular expression for fast time stamp matching.")
3844 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3845 "Regular expression for fast time stamp matching.")
3846 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3847 "Regular expression matching time strings for analysis.
3848 This one does not require the space after the date, so it can be used
3849 on a string that terminates immediately after the date.")
3850 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3851 "Regular expression matching time strings for analysis.")
3852 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3853 "Regular expression matching time stamps, with groups.")
3854 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3855 "Regular expression matching time stamps (also [..]), with groups.")
3856 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3857 "Regular expression matching a time stamp range.")
3858 (defconst org-tr-regexp-both
3859 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3860 "Regular expression matching a time stamp range.")
3861 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3862 org-ts-regexp "\\)?")
3863 "Regular expression matching a time stamp or time stamp range.")
3864 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3865 org-ts-regexp-both "\\)?")
3866 "Regular expression matching a time stamp or time stamp range.
3867 The time stamps may be either active or inactive.")
3869 (defvar org-emph-face nil)
3871 (defun org-do-emphasis-faces (limit)
3872 "Run through the buffer and add overlays to links."
3873 (let (rtn)
3874 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3875 (if (not (= (char-after (match-beginning 3))
3876 (char-after (match-beginning 4))))
3877 (progn
3878 (setq rtn t)
3879 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3880 'face
3881 (nth 1 (assoc (match-string 3)
3882 org-emphasis-alist)))
3883 (add-text-properties (match-beginning 2) (match-end 2)
3884 '(font-lock-multiline t))
3885 (when org-hide-emphasis-markers
3886 (add-text-properties (match-end 4) (match-beginning 5)
3887 '(invisible org-link))
3888 (add-text-properties (match-beginning 3) (match-end 3)
3889 '(invisible org-link)))))
3890 (backward-char 1))
3891 rtn))
3893 (defun org-emphasize (&optional char)
3894 "Insert or change an emphasis, i.e. a font like bold or italic.
3895 If there is an active region, change that region to a new emphasis.
3896 If there is no region, just insert the marker characters and position
3897 the cursor between them.
3898 CHAR should be either the marker character, or the first character of the
3899 HTML tag associated with that emphasis. If CHAR is a space, the means
3900 to remove the emphasis of the selected region.
3901 If char is not given (for example in an interactive call) it
3902 will be prompted for."
3903 (interactive)
3904 (let ((eal org-emphasis-alist) e det
3905 (erc org-emphasis-regexp-components)
3906 (prompt "")
3907 (string "") beg end move tag c s)
3908 (if (org-region-active-p)
3909 (setq beg (region-beginning) end (region-end)
3910 string (buffer-substring beg end))
3911 (setq move t))
3913 (while (setq e (pop eal))
3914 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3915 c (aref tag 0))
3916 (push (cons c (string-to-char (car e))) det)
3917 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3918 (substring tag 1)))))
3919 (setq det (nreverse det))
3920 (unless char
3921 (message "%s" (concat "Emphasis marker or tag:" prompt))
3922 (setq char (read-char-exclusive)))
3923 (setq char (or (cdr (assoc char det)) char))
3924 (if (equal char ?\ )
3925 (setq s "" move nil)
3926 (unless (assoc (char-to-string char) org-emphasis-alist)
3927 (error "No such emphasis marker: \"%c\"" char))
3928 (setq s (char-to-string char)))
3929 (while (and (> (length string) 1)
3930 (equal (substring string 0 1) (substring string -1))
3931 (assoc (substring string 0 1) org-emphasis-alist))
3932 (setq string (substring string 1 -1)))
3933 (setq string (concat s string s))
3934 (if beg (delete-region beg end))
3935 (unless (or (bolp)
3936 (string-match (concat "[" (nth 0 erc) "\n]")
3937 (char-to-string (char-before (point)))))
3938 (insert " "))
3939 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3940 (char-to-string (char-after (point))))
3941 (insert " ") (backward-char 1))
3942 (insert string)
3943 (and move (backward-char 1))))
3945 (defconst org-nonsticky-props
3946 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3949 (defun org-activate-plain-links (limit)
3950 "Run through the buffer and add overlays to links."
3951 (catch 'exit
3952 (let (f)
3953 (while (re-search-forward org-plain-link-re limit t)
3954 (setq f (get-text-property (match-beginning 0) 'face))
3955 (if (or (eq f 'org-tag)
3956 (and (listp f) (memq 'org-tag f)))
3958 (add-text-properties (match-beginning 0) (match-end 0)
3959 (list 'mouse-face 'highlight
3960 'rear-nonsticky org-nonsticky-props
3961 'keymap org-mouse-map
3963 (throw 'exit t))))))
3965 (defun org-activate-code (limit)
3966 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3967 (progn
3968 (remove-text-properties (match-beginning 0) (match-end 0)
3969 '(display t invisible t intangible t))
3970 t)))
3972 (defun org-activate-angle-links (limit)
3973 "Run through the buffer and add overlays to links."
3974 (if (re-search-forward org-angle-link-re limit t)
3975 (progn
3976 (add-text-properties (match-beginning 0) (match-end 0)
3977 (list 'mouse-face 'highlight
3978 'rear-nonsticky org-nonsticky-props
3979 'keymap org-mouse-map
3981 t)))
3983 (defun org-activate-footnote-links (limit)
3984 "Run through the buffer and add overlays to links."
3985 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3986 limit t)
3987 (progn
3988 (add-text-properties (match-beginning 2) (match-end 2)
3989 (list 'mouse-face 'highlight
3990 'rear-nonsticky org-nonsticky-props
3991 'keymap org-mouse-map
3992 'help-echo
3993 (if (= (point-at-bol) (match-beginning 2))
3994 "Footnote definition"
3995 "Footnote reference")
3997 t)))
3999 (defun org-activate-bracket-links (limit)
4000 "Run through the buffer and add overlays to bracketed links."
4001 (if (re-search-forward org-bracket-link-regexp limit t)
4002 (let* ((help (concat "LINK: "
4003 (org-match-string-no-properties 1)))
4004 ;; FIXME: above we should remove the escapes.
4005 ;; but that requires another match, protecting match data,
4006 ;; a lot of overhead for font-lock.
4007 (ip (org-maybe-intangible
4008 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4009 'keymap org-mouse-map 'mouse-face 'highlight
4010 'font-lock-multiline t 'help-echo help)))
4011 (vp (list 'rear-nonsticky org-nonsticky-props
4012 'keymap org-mouse-map 'mouse-face 'highlight
4013 ' font-lock-multiline t 'help-echo help)))
4014 ;; We need to remove the invisible property here. Table narrowing
4015 ;; may have made some of this invisible.
4016 (remove-text-properties (match-beginning 0) (match-end 0)
4017 '(invisible nil))
4018 (if (match-end 3)
4019 (progn
4020 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4021 (add-text-properties (match-beginning 3) (match-end 3) vp)
4022 (add-text-properties (match-end 3) (match-end 0) ip))
4023 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4024 (add-text-properties (match-beginning 1) (match-end 1) vp)
4025 (add-text-properties (match-end 1) (match-end 0) ip))
4026 t)))
4028 (defun org-activate-dates (limit)
4029 "Run through the buffer and add overlays to dates."
4030 (if (re-search-forward org-tsr-regexp-both limit t)
4031 (progn
4032 (add-text-properties (match-beginning 0) (match-end 0)
4033 (list 'mouse-face 'highlight
4034 'rear-nonsticky org-nonsticky-props
4035 'keymap org-mouse-map))
4036 (when org-display-custom-times
4037 (if (match-end 3)
4038 (org-display-custom-time (match-beginning 3) (match-end 3)))
4039 (org-display-custom-time (match-beginning 1) (match-end 1)))
4040 t)))
4042 (defvar org-target-link-regexp nil
4043 "Regular expression matching radio targets in plain text.")
4044 (make-variable-buffer-local 'org-target-link-regexp)
4045 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4046 "Regular expression matching a link target.")
4047 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4048 "Regular expression matching a radio target.")
4049 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4050 "Regular expression matching any target.")
4052 (defun org-activate-target-links (limit)
4053 "Run through the buffer and add overlays to target matches."
4054 (when org-target-link-regexp
4055 (let ((case-fold-search t))
4056 (if (re-search-forward org-target-link-regexp limit t)
4057 (progn
4058 (add-text-properties (match-beginning 0) (match-end 0)
4059 (list 'mouse-face 'highlight
4060 'rear-nonsticky org-nonsticky-props
4061 'keymap org-mouse-map
4062 'help-echo "Radio target link"
4063 'org-linked-text t))
4064 t)))))
4066 (defun org-update-radio-target-regexp ()
4067 "Find all radio targets in this file and update the regular expression."
4068 (interactive)
4069 (when (memq 'radio org-activate-links)
4070 (setq org-target-link-regexp
4071 (org-make-target-link-regexp (org-all-targets 'radio)))
4072 (org-restart-font-lock)))
4074 (defun org-hide-wide-columns (limit)
4075 (let (s e)
4076 (setq s (text-property-any (point) (or limit (point-max))
4077 'org-cwidth t))
4078 (when s
4079 (setq e (next-single-property-change s 'org-cwidth))
4080 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4081 (goto-char e)
4082 t)))
4084 (defvar org-latex-and-specials-regexp nil
4085 "Regular expression for highlighting export special stuff.")
4086 (defvar org-match-substring-regexp)
4087 (defvar org-match-substring-with-braces-regexp)
4088 (defvar org-export-html-special-string-regexps)
4090 (defun org-compute-latex-and-specials-regexp ()
4091 "Compute regular expression for stuff treated specially by exporters."
4092 (if (not org-highlight-latex-fragments-and-specials)
4093 (org-set-local 'org-latex-and-specials-regexp nil)
4094 (require 'org-exp)
4095 (let*
4096 ((matchers (plist-get org-format-latex-options :matchers))
4097 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4098 org-latex-regexps)))
4099 (options (org-combine-plists (org-default-export-plist)
4100 (org-infile-export-plist)))
4101 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4102 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4103 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4104 (org-export-html-expand (plist-get options :expand-quoted-html))
4105 (org-export-with-special-strings (plist-get options :special-strings))
4106 (re-sub
4107 (cond
4108 ((equal org-export-with-sub-superscripts '{})
4109 (list org-match-substring-with-braces-regexp))
4110 (org-export-with-sub-superscripts
4111 (list org-match-substring-regexp))
4112 (t nil)))
4113 (re-latex
4114 (if org-export-with-LaTeX-fragments
4115 (mapcar (lambda (x) (nth 1 x)) latexs)))
4116 (re-macros
4117 (if org-export-with-TeX-macros
4118 (list (concat "\\\\"
4119 (regexp-opt
4120 (append (mapcar 'car org-html-entities)
4121 (if (boundp 'org-latex-entities)
4122 org-latex-entities nil))
4123 'words))) ; FIXME
4125 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4126 (re-special (if org-export-with-special-strings
4127 (mapcar (lambda (x) (car x))
4128 org-export-html-special-string-regexps)))
4129 (re-rest
4130 (delq nil
4131 (list
4132 (if org-export-html-expand "@<[^>\n]+>")
4133 ))))
4134 (org-set-local
4135 'org-latex-and-specials-regexp
4136 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4137 re-rest) "\\|")))))
4139 (defun org-do-latex-and-special-faces (limit)
4140 "Run through the buffer and add overlays to links."
4141 (when org-latex-and-specials-regexp
4142 (let (rtn d)
4143 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4144 limit t))
4145 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4146 'face))
4147 '(org-code org-verbatim underline)))
4148 (progn
4149 (setq rtn t
4150 d (cond ((member (char-after (1+ (match-beginning 0)))
4151 '(?_ ?^)) 1)
4152 (t 0)))
4153 (font-lock-prepend-text-property
4154 (+ d (match-beginning 0)) (match-end 0)
4155 'face 'org-latex-and-export-specials)
4156 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4157 '(font-lock-multiline t)))))
4158 rtn)))
4160 (defun org-restart-font-lock ()
4161 "Restart font-lock-mode, to force refontification."
4162 (when (and (boundp 'font-lock-mode) font-lock-mode)
4163 (font-lock-mode -1)
4164 (font-lock-mode 1)))
4166 (defun org-all-targets (&optional radio)
4167 "Return a list of all targets in this file.
4168 With optional argument RADIO, only find radio targets."
4169 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4170 rtn)
4171 (save-excursion
4172 (goto-char (point-min))
4173 (while (re-search-forward re nil t)
4174 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4175 rtn)))
4177 (defun org-make-target-link-regexp (targets)
4178 "Make regular expression matching all strings in TARGETS.
4179 The regular expression finds the targets also if there is a line break
4180 between words."
4181 (and targets
4182 (concat
4183 "\\<\\("
4184 (mapconcat
4185 (lambda (x)
4186 (while (string-match " +" x)
4187 (setq x (replace-match "\\s-+" t t x)))
4189 targets
4190 "\\|")
4191 "\\)\\>")))
4193 (defun org-activate-tags (limit)
4194 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4195 (progn
4196 (add-text-properties (match-beginning 1) (match-end 1)
4197 (list 'mouse-face 'highlight
4198 'rear-nonsticky org-nonsticky-props
4199 'keymap org-mouse-map))
4200 t)))
4202 (defun org-outline-level ()
4203 (save-excursion
4204 (looking-at outline-regexp)
4205 (if (match-beginning 1)
4206 (+ (org-get-string-indentation (match-string 1)) 1000)
4207 (1- (- (match-end 0) (match-beginning 0))))))
4209 (defvar org-font-lock-keywords nil)
4211 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4212 "Regular expression matching a property line.")
4214 (defvar org-font-lock-hook nil
4215 "Functions to be called for special font lock stuff.")
4217 (defun org-font-lock-hook (limit)
4218 (run-hook-with-args 'org-font-lock-hook limit))
4220 (defun org-set-font-lock-defaults ()
4221 (let* ((em org-fontify-emphasized-text)
4222 (lk org-activate-links)
4223 (org-font-lock-extra-keywords
4224 (list
4225 ;; Call the hook
4226 '(org-font-lock-hook)
4227 ;; Headlines
4228 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4229 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4230 ;; Table lines
4231 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4232 (1 'org-table t))
4233 ;; Table internals
4234 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4235 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4236 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4237 ;; Drawers
4238 (list org-drawer-regexp '(0 'org-special-keyword t))
4239 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4240 ;; Properties
4241 (list org-property-re
4242 '(1 'org-special-keyword t)
4243 '(3 'org-property-value t))
4244 (if org-format-transports-properties-p
4245 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4246 ;; Links
4247 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4248 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4249 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4250 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4251 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4252 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4253 (if (memq 'footnote lk) '(org-activate-footnote-links
4254 (2 'org-footnote t)))
4255 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4256 '(org-hide-wide-columns (0 nil append))
4257 ;; TODO lines
4258 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4259 '(1 (org-get-todo-face 1) t))
4260 ;; DONE
4261 (if org-fontify-done-headline
4262 (list (concat "^[*]+ +\\<\\("
4263 (mapconcat 'regexp-quote org-done-keywords "\\|")
4264 "\\)\\(.*\\)")
4265 '(2 'org-headline-done t))
4266 nil)
4267 ;; Priorities
4268 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4269 ;; Tags
4270 '(org-font-lock-add-tag-faces)
4271 ;; Special keywords
4272 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4273 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4274 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4275 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4276 ;; Emphasis
4277 (if em
4278 (if (featurep 'xemacs)
4279 '(org-do-emphasis-faces (0 nil append))
4280 '(org-do-emphasis-faces)))
4281 ;; Checkboxes
4282 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4283 2 'bold prepend)
4284 (if org-provide-checkbox-statistics
4285 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4286 (0 (org-get-checkbox-statistics-face) t)))
4287 ;; Description list items
4288 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4289 2 'bold prepend)
4290 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4291 '(1 'org-archived prepend))
4292 ;; Specials
4293 '(org-do-latex-and-special-faces)
4294 ;; Code
4295 '(org-activate-code (1 'org-code t))
4296 ;; COMMENT
4297 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4298 "\\|" org-quote-string "\\)\\>")
4299 '(1 'org-special-keyword t))
4300 '("^#.*" (0 'font-lock-comment-face t))
4302 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4303 ;; Now set the full font-lock-keywords
4304 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4305 (org-set-local 'font-lock-defaults
4306 '(org-font-lock-keywords t nil nil backward-paragraph))
4307 (kill-local-variable 'font-lock-keywords) nil))
4309 (defvar org-m nil)
4310 (defvar org-l nil)
4311 (defvar org-f nil)
4312 (defun org-get-level-face (n)
4313 "Get the right face for match N in font-lock matching of headlines."
4314 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4315 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4316 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4317 (cond
4318 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4319 ((eq n 2) org-f)
4320 (t (if org-level-color-stars-only nil org-f))))
4322 (defun org-get-todo-face (kwd)
4323 "Get the right face for a TODO keyword KWD.
4324 If KWD is a number, get the corresponding match group."
4325 (if (numberp kwd) (setq kwd (match-string kwd)))
4326 (or (cdr (assoc kwd org-todo-keyword-faces))
4327 (and (member kwd org-done-keywords) 'org-done)
4328 'org-todo))
4330 (defun org-font-lock-add-tag-faces (limit)
4331 "Add the special tag faces."
4332 (when (and org-tag-faces org-tags-special-faces-re)
4333 (while (re-search-forward org-tags-special-faces-re limit t)
4334 (add-text-properties (match-beginning 1) (match-end 1)
4335 (list 'face (org-get-tag-face 1)
4336 'font-lock-fontified t))
4337 (backward-char 1))))
4339 (defun org-get-tag-face (kwd)
4340 "Get the right face for a TODO keyword KWD.
4341 If KWD is a number, get the corresponding match group."
4342 (if (numberp kwd) (setq kwd (match-string kwd)))
4343 (or (cdr (assoc kwd org-tag-faces))
4344 'org-tag))
4346 (defun org-unfontify-region (beg end &optional maybe_loudly)
4347 "Remove fontification and activation overlays from links."
4348 (font-lock-default-unfontify-region beg end)
4349 (let* ((buffer-undo-list t)
4350 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4351 (inhibit-modification-hooks t)
4352 deactivate-mark buffer-file-name buffer-file-truename)
4353 (remove-text-properties beg end
4354 '(mouse-face t keymap t org-linked-text t
4355 invisible t intangible t))))
4357 ;;;; Visibility cycling, including org-goto and indirect buffer
4359 ;;; Cycling
4361 (defvar org-cycle-global-status nil)
4362 (make-variable-buffer-local 'org-cycle-global-status)
4363 (defvar org-cycle-subtree-status nil)
4364 (make-variable-buffer-local 'org-cycle-subtree-status)
4366 ;;;###autoload
4367 (defun org-cycle (&optional arg)
4368 "Visibility cycling for Org-mode.
4370 - When this function is called with a prefix argument, rotate the entire
4371 buffer through 3 states (global cycling)
4372 1. OVERVIEW: Show only top-level headlines.
4373 2. CONTENTS: Show all headlines of all levels, but no body text.
4374 3. SHOW ALL: Show everything.
4375 When called with two C-u C-u prefixes, switch to the startup visibility,
4376 determined by the variable `org-startup-folded', and by any VISIBILITY
4377 properties in the buffer.
4378 When called with three C-u C-u C-u prefixed, show the entire buffer,
4379 including drawers.
4381 - When point is at the beginning of a headline, rotate the subtree started
4382 by this line through 3 different states (local cycling)
4383 1. FOLDED: Only the main headline is shown.
4384 2. CHILDREN: The main headline and the direct children are shown.
4385 From this state, you can move to one of the children
4386 and zoom in further.
4387 3. SUBTREE: Show the entire subtree, including body text.
4389 - When there is a numeric prefix, go up to a heading with level ARG, do
4390 a `show-subtree' and return to the previous cursor position. If ARG
4391 is negative, go up that many levels.
4393 - When point is not at the beginning of a headline, execute the global
4394 binding for TAB, which is re-indenting the line. See the option
4395 `org-cycle-emulate-tab' for details.
4397 - Special case: if point is at the beginning of the buffer and there is
4398 no headline in line 1, this function will act as if called with prefix arg.
4399 But only if also the variable `org-cycle-global-at-bob' is t."
4400 (interactive "P")
4401 (org-load-modules-maybe)
4402 (let* ((outline-regexp
4403 (if (and (org-mode-p) org-cycle-include-plain-lists)
4404 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4405 outline-regexp))
4406 (bob-special (and org-cycle-global-at-bob (bobp)
4407 (not (looking-at outline-regexp))))
4408 (org-cycle-hook
4409 (if bob-special
4410 (delq 'org-optimize-window-after-visibility-change
4411 (copy-sequence org-cycle-hook))
4412 org-cycle-hook))
4413 (pos (point)))
4415 (if (or bob-special (equal arg '(4)))
4416 ;; special case: use global cycling
4417 (setq arg t))
4419 (cond
4421 ((equal arg '(16))
4422 (org-set-startup-visibility)
4423 (message "Startup visibility, plus VISIBILITY properties"))
4425 ((equal arg '(64))
4426 (show-all)
4427 (message "Entire buffer visible, including drawers"))
4429 ((org-at-table-p 'any)
4430 ;; Enter the table or move to the next field in the table
4431 (or (org-table-recognize-table.el)
4432 (progn
4433 (if arg (org-table-edit-field t)
4434 (org-table-justify-field-maybe)
4435 (call-interactively 'org-table-next-field)))))
4437 ((eq arg t) ;; Global cycling
4439 (cond
4440 ((and (eq last-command this-command)
4441 (eq org-cycle-global-status 'overview))
4442 ;; We just created the overview - now do table of contents
4443 ;; This can be slow in very large buffers, so indicate action
4444 (message "CONTENTS...")
4445 (org-content)
4446 (message "CONTENTS...done")
4447 (setq org-cycle-global-status 'contents)
4448 (run-hook-with-args 'org-cycle-hook 'contents))
4450 ((and (eq last-command this-command)
4451 (eq org-cycle-global-status 'contents))
4452 ;; We just showed the table of contents - now show everything
4453 (show-all)
4454 (message "SHOW ALL")
4455 (setq org-cycle-global-status 'all)
4456 (run-hook-with-args 'org-cycle-hook 'all))
4459 ;; Default action: go to overview
4460 (org-overview)
4461 (message "OVERVIEW")
4462 (setq org-cycle-global-status 'overview)
4463 (run-hook-with-args 'org-cycle-hook 'overview))))
4465 ((and org-drawers org-drawer-regexp
4466 (save-excursion
4467 (beginning-of-line 1)
4468 (looking-at org-drawer-regexp)))
4469 ;; Toggle block visibility
4470 (org-flag-drawer
4471 (not (get-char-property (match-end 0) 'invisible))))
4473 ((integerp arg)
4474 ;; Show-subtree, ARG levels up from here.
4475 (save-excursion
4476 (org-back-to-heading)
4477 (outline-up-heading (if (< arg 0) (- arg)
4478 (- (funcall outline-level) arg)))
4479 (org-show-subtree)))
4481 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4482 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4483 ;; At a heading: rotate between three different views
4484 (org-back-to-heading)
4485 (let ((goal-column 0) eoh eol eos)
4486 ;; First, some boundaries
4487 (save-excursion
4488 (org-back-to-heading)
4489 (save-excursion
4490 (beginning-of-line 2)
4491 (while (and (not (eobp)) ;; this is like `next-line'
4492 (get-char-property (1- (point)) 'invisible))
4493 (beginning-of-line 2)) (setq eol (point)))
4494 (outline-end-of-heading) (setq eoh (point))
4495 (org-end-of-subtree t)
4496 (unless (eobp)
4497 (skip-chars-forward " \t\n")
4498 (beginning-of-line 1) ; in case this is an item
4500 (setq eos (1- (point))))
4501 ;; Find out what to do next and set `this-command'
4502 (cond
4503 ((= eos eoh)
4504 ;; Nothing is hidden behind this heading
4505 (message "EMPTY ENTRY")
4506 (setq org-cycle-subtree-status nil)
4507 (save-excursion
4508 (goto-char eos)
4509 (outline-next-heading)
4510 (if (org-invisible-p) (org-flag-heading nil))))
4511 ((or (>= eol eos)
4512 (not (string-match "\\S-" (buffer-substring eol eos))))
4513 ;; Entire subtree is hidden in one line: open it
4514 (org-show-entry)
4515 (show-children)
4516 (message "CHILDREN")
4517 (save-excursion
4518 (goto-char eos)
4519 (outline-next-heading)
4520 (if (org-invisible-p) (org-flag-heading nil)))
4521 (setq org-cycle-subtree-status 'children)
4522 (run-hook-with-args 'org-cycle-hook 'children))
4523 ((and (eq last-command this-command)
4524 (eq org-cycle-subtree-status 'children))
4525 ;; We just showed the children, now show everything.
4526 (org-show-subtree)
4527 (message "SUBTREE")
4528 (setq org-cycle-subtree-status 'subtree)
4529 (run-hook-with-args 'org-cycle-hook 'subtree))
4531 ;; Default action: hide the subtree.
4532 (hide-subtree)
4533 (message "FOLDED")
4534 (setq org-cycle-subtree-status 'folded)
4535 (run-hook-with-args 'org-cycle-hook 'folded)))))
4537 ;; TAB emulation and template completion
4538 (buffer-read-only (org-back-to-heading))
4540 ((org-try-structure-completion))
4542 ((org-try-cdlatex-tab))
4544 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4545 (or (not (bolp))
4546 (not (looking-at outline-regexp))))
4547 (call-interactively (global-key-binding "\t")))
4549 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4550 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4551 (or (and (eq org-cycle-emulate-tab 'white)
4552 (= (match-end 0) (point-at-eol)))
4553 (and (eq org-cycle-emulate-tab 'whitestart)
4554 (>= (match-end 0) pos))))
4556 (eq org-cycle-emulate-tab t))
4557 (call-interactively (global-key-binding "\t")))
4559 (t (save-excursion
4560 (org-back-to-heading)
4561 (org-cycle))))))
4563 ;;;###autoload
4564 (defun org-global-cycle (&optional arg)
4565 "Cycle the global visibility. For details see `org-cycle'.
4566 With C-u prefix arg, switch to startup visibility.
4567 With a numeric prefix, show all headlines up to that level."
4568 (interactive "P")
4569 (let ((org-cycle-include-plain-lists
4570 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4571 (cond
4572 ((integerp arg)
4573 (show-all)
4574 (hide-sublevels arg)
4575 (setq org-cycle-global-status 'contents))
4576 ((equal arg '(4))
4577 (org-set-startup-visibility)
4578 (message "Startup visibility, plus VISIBILITY properties."))
4580 (org-cycle '(4))))))
4582 (defun org-set-startup-visibility ()
4583 "Set the visibility required by startup options and properties."
4584 (cond
4585 ((eq org-startup-folded t)
4586 (org-cycle '(4)))
4587 ((eq org-startup-folded 'content)
4588 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4589 (org-cycle '(4)) (org-cycle '(4)))))
4590 (org-set-visibility-according-to-property 'no-cleanup)
4591 (org-cycle-hide-archived-subtrees 'all)
4592 (org-cycle-hide-drawers 'all)
4593 (org-cycle-show-empty-lines 'all))
4595 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4596 "Switch subtree visibilities according to :VISIBILITY: property."
4597 (interactive)
4598 (let (org-show-entry-below state)
4599 (save-excursion
4600 (goto-char (point-min))
4601 (while (re-search-forward
4602 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4603 nil t)
4604 (setq state (match-string 1))
4605 (save-excursion
4606 (org-back-to-heading t)
4607 (hide-subtree)
4608 (org-reveal)
4609 (cond
4610 ((equal state '("fold" "folded"))
4611 (hide-subtree))
4612 ((equal state "children")
4613 (org-show-hidden-entry)
4614 (show-children))
4615 ((equal state "content")
4616 (save-excursion
4617 (save-restriction
4618 (org-narrow-to-subtree)
4619 (org-content))))
4620 ((member state '("all" "showall"))
4621 (show-subtree)))))
4622 (unless no-cleanup
4623 (org-cycle-hide-archived-subtrees 'all)
4624 (org-cycle-hide-drawers 'all)
4625 (org-cycle-show-empty-lines 'all)))))
4627 (defun org-overview ()
4628 "Switch to overview mode, showing only top-level headlines.
4629 Really, this shows all headlines with level equal or greater than the level
4630 of the first headline in the buffer. This is important, because if the
4631 first headline is not level one, then (hide-sublevels 1) gives confusing
4632 results."
4633 (interactive)
4634 (let ((level (save-excursion
4635 (goto-char (point-min))
4636 (if (re-search-forward (concat "^" outline-regexp) nil t)
4637 (progn
4638 (goto-char (match-beginning 0))
4639 (funcall outline-level))))))
4640 (and level (hide-sublevels level))))
4642 (defun org-content (&optional arg)
4643 "Show all headlines in the buffer, like a table of contents.
4644 With numerical argument N, show content up to level N."
4645 (interactive "P")
4646 (save-excursion
4647 ;; Visit all headings and show their offspring
4648 (and (integerp arg) (org-overview))
4649 (goto-char (point-max))
4650 (catch 'exit
4651 (while (and (progn (condition-case nil
4652 (outline-previous-visible-heading 1)
4653 (error (goto-char (point-min))))
4655 (looking-at outline-regexp))
4656 (if (integerp arg)
4657 (show-children (1- arg))
4658 (show-branches))
4659 (if (bobp) (throw 'exit nil))))))
4662 (defun org-optimize-window-after-visibility-change (state)
4663 "Adjust the window after a change in outline visibility.
4664 This function is the default value of the hook `org-cycle-hook'."
4665 (when (get-buffer-window (current-buffer))
4666 (cond
4667 ((eq state 'content) nil)
4668 ((eq state 'all) nil)
4669 ((eq state 'folded) nil)
4670 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4671 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4673 (defun org-compact-display-after-subtree-move ()
4674 "Show a compacter version of the tree of the entry's parent."
4675 (save-excursion
4676 (if (org-up-heading-safe)
4677 (progn
4678 (hide-subtree)
4679 (show-entry)
4680 (show-children)
4681 (org-cycle-show-empty-lines 'children)
4682 (org-cycle-hide-drawers 'children))
4683 (org-overview))))
4685 (defun org-cycle-show-empty-lines (state)
4686 "Show empty lines above all visible headlines.
4687 The region to be covered depends on STATE when called through
4688 `org-cycle-hook'. Lisp program can use t for STATE to get the
4689 entire buffer covered. Note that an empty line is only shown if there
4690 are at least `org-cycle-separator-lines' empty lines before the headline."
4691 (when (> org-cycle-separator-lines 0)
4692 (save-excursion
4693 (let* ((n org-cycle-separator-lines)
4694 (re (cond
4695 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4696 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4697 (t (let ((ns (number-to-string (- n 2))))
4698 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4699 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4700 beg end)
4701 (cond
4702 ((memq state '(overview contents t))
4703 (setq beg (point-min) end (point-max)))
4704 ((memq state '(children folded))
4705 (setq beg (point) end (progn (org-end-of-subtree t t)
4706 (beginning-of-line 2)
4707 (point)))))
4708 (when beg
4709 (goto-char beg)
4710 (while (re-search-forward re end t)
4711 (if (not (get-char-property (match-end 1) 'invisible))
4712 (outline-flag-region
4713 (match-beginning 1) (match-end 1) nil)))))))
4714 ;; Never hide empty lines at the end of the file.
4715 (save-excursion
4716 (goto-char (point-max))
4717 (outline-previous-heading)
4718 (outline-end-of-heading)
4719 (if (and (looking-at "[ \t\n]+")
4720 (= (match-end 0) (point-max)))
4721 (outline-flag-region (point) (match-end 0) nil))))
4723 (defun org-show-empty-lines-in-parent ()
4724 "Move to the parent and re-show empty lines before visible headlines."
4725 (save-excursion
4726 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4727 (org-cycle-show-empty-lines context))))
4729 (defun org-cycle-hide-drawers (state)
4730 "Re-hide all drawers after a visibility state change."
4731 (when (and (org-mode-p)
4732 (not (memq state '(overview folded))))
4733 (save-excursion
4734 (let* ((globalp (memq state '(contents all)))
4735 (beg (if globalp (point-min) (point)))
4736 (end (if globalp (point-max) (org-end-of-subtree t))))
4737 (goto-char beg)
4738 (while (re-search-forward org-drawer-regexp end t)
4739 (org-flag-drawer t))))))
4741 (defun org-flag-drawer (flag)
4742 (save-excursion
4743 (beginning-of-line 1)
4744 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4745 (let ((b (match-end 0))
4746 (outline-regexp org-outline-regexp))
4747 (if (re-search-forward
4748 "^[ \t]*:END:"
4749 (save-excursion (outline-next-heading) (point)) t)
4750 (outline-flag-region b (point-at-eol) flag)
4751 (error ":END: line missing"))))))
4753 (defun org-subtree-end-visible-p ()
4754 "Is the end of the current subtree visible?"
4755 (pos-visible-in-window-p
4756 (save-excursion (org-end-of-subtree t) (point))))
4758 (defun org-first-headline-recenter (&optional N)
4759 "Move cursor to the first headline and recenter the headline.
4760 Optional argument N means, put the headline into the Nth line of the window."
4761 (goto-char (point-min))
4762 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4763 (beginning-of-line)
4764 (recenter (prefix-numeric-value N))))
4766 ;;; Org-goto
4768 (defvar org-goto-window-configuration nil)
4769 (defvar org-goto-marker nil)
4770 (defvar org-goto-map
4771 (let ((map (make-sparse-keymap)))
4772 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4773 (while (setq cmd (pop cmds))
4774 (substitute-key-definition cmd cmd map global-map)))
4775 (suppress-keymap map)
4776 (org-defkey map "\C-m" 'org-goto-ret)
4777 (org-defkey map [(return)] 'org-goto-ret)
4778 (org-defkey map [(left)] 'org-goto-left)
4779 (org-defkey map [(right)] 'org-goto-right)
4780 (org-defkey map [(control ?g)] 'org-goto-quit)
4781 (org-defkey map "\C-i" 'org-cycle)
4782 (org-defkey map [(tab)] 'org-cycle)
4783 (org-defkey map [(down)] 'outline-next-visible-heading)
4784 (org-defkey map [(up)] 'outline-previous-visible-heading)
4785 (if org-goto-auto-isearch
4786 (if (fboundp 'define-key-after)
4787 (define-key-after map [t] 'org-goto-local-auto-isearch)
4788 nil)
4789 (org-defkey map "q" 'org-goto-quit)
4790 (org-defkey map "n" 'outline-next-visible-heading)
4791 (org-defkey map "p" 'outline-previous-visible-heading)
4792 (org-defkey map "f" 'outline-forward-same-level)
4793 (org-defkey map "b" 'outline-backward-same-level)
4794 (org-defkey map "u" 'outline-up-heading))
4795 (org-defkey map "/" 'org-occur)
4796 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4797 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4798 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4799 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4800 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4801 map))
4803 (defconst org-goto-help
4804 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4805 RET=jump to location [Q]uit and return to previous location
4806 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4808 (defvar org-goto-start-pos) ; dynamically scoped parameter
4810 ;; FIXME: Docstring doe not mention both interfaces
4811 (defun org-goto (&optional alternative-interface)
4812 "Look up a different location in the current file, keeping current visibility.
4814 When you want look-up or go to a different location in a document, the
4815 fastest way is often to fold the entire buffer and then dive into the tree.
4816 This method has the disadvantage, that the previous location will be folded,
4817 which may not be what you want.
4819 This command works around this by showing a copy of the current buffer
4820 in an indirect buffer, in overview mode. You can dive into the tree in
4821 that copy, use org-occur and incremental search to find a location.
4822 When pressing RET or `Q', the command returns to the original buffer in
4823 which the visibility is still unchanged. After RET is will also jump to
4824 the location selected in the indirect buffer and expose the
4825 the headline hierarchy above."
4826 (interactive "P")
4827 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4828 (org-refile-use-outline-path t)
4829 (interface
4830 (if (not alternative-interface)
4831 org-goto-interface
4832 (if (eq org-goto-interface 'outline)
4833 'outline-path-completion
4834 'outline)))
4835 (org-goto-start-pos (point))
4836 (selected-point
4837 (if (eq interface 'outline)
4838 (car (org-get-location (current-buffer) org-goto-help))
4839 (nth 3 (org-refile-get-location "Goto: ")))))
4840 (if selected-point
4841 (progn
4842 (org-mark-ring-push org-goto-start-pos)
4843 (goto-char selected-point)
4844 (if (or (org-invisible-p) (org-invisible-p2))
4845 (org-show-context 'org-goto)))
4846 (message "Quit"))))
4848 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4849 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4850 (defvar org-goto-local-auto-isearch-map) ; defined below
4852 (defun org-get-location (buf help)
4853 "Let the user select a location in the Org-mode buffer BUF.
4854 This function uses a recursive edit. It returns the selected position
4855 or nil."
4856 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4857 (isearch-hide-immediately nil)
4858 (isearch-search-fun-function
4859 (lambda () 'org-goto-local-search-headings))
4860 (org-goto-selected-point org-goto-exit-command))
4861 (save-excursion
4862 (save-window-excursion
4863 (delete-other-windows)
4864 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4865 (switch-to-buffer
4866 (condition-case nil
4867 (make-indirect-buffer (current-buffer) "*org-goto*")
4868 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4869 (with-output-to-temp-buffer "*Help*"
4870 (princ help))
4871 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4872 (setq buffer-read-only nil)
4873 (let ((org-startup-truncated t)
4874 (org-startup-folded nil)
4875 (org-startup-align-all-tables nil))
4876 (org-mode)
4877 (org-overview))
4878 (setq buffer-read-only t)
4879 (if (and (boundp 'org-goto-start-pos)
4880 (integer-or-marker-p org-goto-start-pos))
4881 (let ((org-show-hierarchy-above t)
4882 (org-show-siblings t)
4883 (org-show-following-heading t))
4884 (goto-char org-goto-start-pos)
4885 (and (org-invisible-p) (org-show-context)))
4886 (goto-char (point-min)))
4887 (let (org-special-ctrl-a/e) (org-beginning-of-line))
4888 (message "Select location and press RET")
4889 (use-local-map org-goto-map)
4890 (recursive-edit)
4892 (kill-buffer "*org-goto*")
4893 (cons org-goto-selected-point org-goto-exit-command)))
4895 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4896 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4897 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4898 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4900 (defun org-goto-local-search-headings (string bound noerror)
4901 "Search and make sure that any matches are in headlines."
4902 (catch 'return
4903 (while (if isearch-forward
4904 (search-forward string bound noerror)
4905 (search-backward string bound noerror))
4906 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4907 (and (member :headline context)
4908 (not (member :tags context))))
4909 (throw 'return (point))))))
4911 (defun org-goto-local-auto-isearch ()
4912 "Start isearch."
4913 (interactive)
4914 (goto-char (point-min))
4915 (let ((keys (this-command-keys)))
4916 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4917 (isearch-mode t)
4918 (isearch-process-search-char (string-to-char keys)))))
4920 (defun org-goto-ret (&optional arg)
4921 "Finish `org-goto' by going to the new location."
4922 (interactive "P")
4923 (setq org-goto-selected-point (point)
4924 org-goto-exit-command 'return)
4925 (throw 'exit nil))
4927 (defun org-goto-left ()
4928 "Finish `org-goto' by going to the new location."
4929 (interactive)
4930 (if (org-on-heading-p)
4931 (progn
4932 (beginning-of-line 1)
4933 (setq org-goto-selected-point (point)
4934 org-goto-exit-command 'left)
4935 (throw 'exit nil))
4936 (error "Not on a heading")))
4938 (defun org-goto-right ()
4939 "Finish `org-goto' by going to the new location."
4940 (interactive)
4941 (if (org-on-heading-p)
4942 (progn
4943 (setq org-goto-selected-point (point)
4944 org-goto-exit-command 'right)
4945 (throw 'exit nil))
4946 (error "Not on a heading")))
4948 (defun org-goto-quit ()
4949 "Finish `org-goto' without cursor motion."
4950 (interactive)
4951 (setq org-goto-selected-point nil)
4952 (setq org-goto-exit-command 'quit)
4953 (throw 'exit nil))
4955 ;;; Indirect buffer display of subtrees
4957 (defvar org-indirect-dedicated-frame nil
4958 "This is the frame being used for indirect tree display.")
4959 (defvar org-last-indirect-buffer nil)
4961 (defun org-tree-to-indirect-buffer (&optional arg)
4962 "Create indirect buffer and narrow it to current subtree.
4963 With numerical prefix ARG, go up to this level and then take that tree.
4964 If ARG is negative, go up that many levels.
4965 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4966 indirect buffer previously made with this command, to avoid proliferation of
4967 indirect buffers. However, when you call the command with a `C-u' prefix, or
4968 when `org-indirect-buffer-display' is `new-frame', the last buffer
4969 is kept so that you can work with several indirect buffers at the same time.
4970 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4971 requests that a new frame be made for the new buffer, so that the dedicated
4972 frame is not changed."
4973 (interactive "P")
4974 (let ((cbuf (current-buffer))
4975 (cwin (selected-window))
4976 (pos (point))
4977 beg end level heading ibuf)
4978 (save-excursion
4979 (org-back-to-heading t)
4980 (when (numberp arg)
4981 (setq level (org-outline-level))
4982 (if (< arg 0) (setq arg (+ level arg)))
4983 (while (> (setq level (org-outline-level)) arg)
4984 (outline-up-heading 1 t)))
4985 (setq beg (point)
4986 heading (org-get-heading))
4987 (org-end-of-subtree t) (setq end (point)))
4988 (if (and (buffer-live-p org-last-indirect-buffer)
4989 (not (eq org-indirect-buffer-display 'new-frame))
4990 (not arg))
4991 (kill-buffer org-last-indirect-buffer))
4992 (setq ibuf (org-get-indirect-buffer cbuf)
4993 org-last-indirect-buffer ibuf)
4994 (cond
4995 ((or (eq org-indirect-buffer-display 'new-frame)
4996 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4997 (select-frame (make-frame))
4998 (delete-other-windows)
4999 (switch-to-buffer ibuf)
5000 (org-set-frame-title heading))
5001 ((eq org-indirect-buffer-display 'dedicated-frame)
5002 (raise-frame
5003 (select-frame (or (and org-indirect-dedicated-frame
5004 (frame-live-p org-indirect-dedicated-frame)
5005 org-indirect-dedicated-frame)
5006 (setq org-indirect-dedicated-frame (make-frame)))))
5007 (delete-other-windows)
5008 (switch-to-buffer ibuf)
5009 (org-set-frame-title (concat "Indirect: " heading)))
5010 ((eq org-indirect-buffer-display 'current-window)
5011 (switch-to-buffer ibuf))
5012 ((eq org-indirect-buffer-display 'other-window)
5013 (pop-to-buffer ibuf))
5014 (t (error "Invalid value.")))
5015 (if (featurep 'xemacs)
5016 (save-excursion (org-mode) (turn-on-font-lock)))
5017 (narrow-to-region beg end)
5018 (show-all)
5019 (goto-char pos)
5020 (and (window-live-p cwin) (select-window cwin))))
5022 (defun org-get-indirect-buffer (&optional buffer)
5023 (setq buffer (or buffer (current-buffer)))
5024 (let ((n 1) (base (buffer-name buffer)) bname)
5025 (while (buffer-live-p
5026 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5027 (setq n (1+ n)))
5028 (condition-case nil
5029 (make-indirect-buffer buffer bname 'clone)
5030 (error (make-indirect-buffer buffer bname)))))
5032 (defun org-set-frame-title (title)
5033 "Set the title of the current frame to the string TITLE."
5034 ;; FIXME: how to name a single frame in XEmacs???
5035 (unless (featurep 'xemacs)
5036 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5038 ;;;; Structure editing
5040 ;;; Inserting headlines
5042 (defun org-previous-line-empty-p ()
5043 (save-excursion
5044 (and (not (bobp))
5045 (or (beginning-of-line 0) t)
5046 (save-match-data
5047 (looking-at "[ \t]*$")))))
5049 (defun org-insert-heading (&optional force-heading)
5050 "Insert a new heading or item with same depth at point.
5051 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5052 If point is at the beginning of a headline, insert a sibling before the
5053 current headline. If point is not at the beginning, do not split the line,
5054 but create the new headline after the current line."
5055 (interactive "P")
5056 (if (= (buffer-size) 0)
5057 (insert "\n* ")
5058 (when (or force-heading (not (org-insert-item)))
5059 (let* ((empty-line-p nil)
5060 (head (save-excursion
5061 (condition-case nil
5062 (progn
5063 (org-back-to-heading)
5064 (setq empty-line-p (org-previous-line-empty-p))
5065 (match-string 0))
5066 (error "*"))))
5067 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5068 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5069 pos hide-previous previous-pos)
5070 (cond
5071 ((and (org-on-heading-p) (bolp)
5072 (or (bobp)
5073 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5074 ;; insert before the current line
5075 (open-line (if blank 2 1)))
5076 ((and (bolp)
5077 (or (bobp)
5078 (save-excursion
5079 (backward-char 1) (not (org-invisible-p)))))
5080 ;; insert right here
5081 nil)
5083 ;; somewhere in the line
5084 (save-excursion
5085 (setq previous-pos (point-at-bol))
5086 (end-of-line)
5087 (setq hide-previous (org-invisible-p)))
5088 (and org-insert-heading-respect-content (org-show-subtree))
5089 (let ((split
5090 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5091 (save-excursion
5092 (let ((p (point)))
5093 (goto-char (point-at-bol))
5094 (and (looking-at org-complex-heading-regexp)
5095 (> p (match-beginning 4)))))))
5096 tags pos)
5097 (cond
5098 (org-insert-heading-respect-content
5099 (org-end-of-subtree nil t)
5100 (or (bolp) (newline))
5101 (or (org-previous-line-empty-p)
5102 (and blank (newline)))
5103 (open-line 1))
5104 ((org-on-heading-p)
5105 (when hide-previous
5106 (show-children)
5107 (org-show-entry))
5108 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5109 (setq tags (and (match-end 2) (match-string 2)))
5110 (and (match-end 1)
5111 (delete-region (match-beginning 1) (match-end 1)))
5112 (setq pos (point-at-bol))
5113 (or split (end-of-line 1))
5114 (delete-horizontal-space)
5115 (newline (if blank 2 1))
5116 (when tags
5117 (save-excursion
5118 (goto-char pos)
5119 (end-of-line 1)
5120 (insert " " tags)
5121 (org-set-tags nil 'align))))
5123 (or split (end-of-line 1))
5124 (newline (if blank 2 1)))))))
5125 (insert head) (just-one-space)
5126 (setq pos (point))
5127 (end-of-line 1)
5128 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5129 (when (and org-insert-heading-respect-content hide-previous)
5130 (save-excursion
5131 (goto-char previous-pos)
5132 (hide-subtree)))
5133 (run-hooks 'org-insert-heading-hook)))))
5135 (defun org-get-heading (&optional no-tags)
5136 "Return the heading of the current entry, without the stars."
5137 (save-excursion
5138 (org-back-to-heading t)
5139 (if (looking-at
5140 (if no-tags
5141 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5142 "\\*+[ \t]+\\([^\r\n]*\\)"))
5143 (match-string 1) "")))
5145 (defun org-heading-components ()
5146 "Return the components of the current heading.
5147 This is a list with the following elements:
5148 - the level as an integer
5149 - the reduced level, different if `org-odd-levels-only' is set.
5150 - the TODO keyword, or nil
5151 - the priority character, like ?A, or nil if no priority is given
5152 - the headline text itself, or the tags string if no headline text
5153 - the tags string, or nil."
5154 (save-excursion
5155 (org-back-to-heading t)
5156 (if (looking-at org-complex-heading-regexp)
5157 (list (length (match-string 1))
5158 (org-reduced-level (length (match-string 1)))
5159 (org-match-string-no-properties 2)
5160 (and (match-end 3) (aref (match-string 3) 2))
5161 (org-match-string-no-properties 4)
5162 (org-match-string-no-properties 5)))))
5164 (defun org-insert-heading-after-current ()
5165 "Insert a new heading with same level as current, after current subtree."
5166 (interactive)
5167 (org-back-to-heading)
5168 (org-insert-heading)
5169 (org-move-subtree-down)
5170 (end-of-line 1))
5172 (defun org-insert-heading-respect-content ()
5173 (interactive)
5174 (let ((org-insert-heading-respect-content t))
5175 (org-insert-heading t)))
5177 (defun org-insert-todo-heading-respect-content (&optional force-state)
5178 (interactive "P")
5179 (let ((org-insert-heading-respect-content t))
5180 (org-insert-todo-heading force-state t)))
5182 (defun org-insert-todo-heading (arg &optional force-heading)
5183 "Insert a new heading with the same level and TODO state as current heading.
5184 If the heading has no TODO state, or if the state is DONE, use the first
5185 state (TODO by default). Also with prefix arg, force first state."
5186 (interactive "P")
5187 (when (or force-heading (not (org-insert-item 'checkbox)))
5188 (org-insert-heading force-heading)
5189 (save-excursion
5190 (org-back-to-heading)
5191 (outline-previous-heading)
5192 (looking-at org-todo-line-regexp))
5193 (let*
5194 ((new-mark-x
5195 (if (or arg
5196 (not (match-beginning 2))
5197 (member (match-string 2) org-done-keywords))
5198 (car org-todo-keywords-1)
5199 (match-string 2)))
5200 (new-mark
5202 (run-hook-with-args-until-success
5203 'org-todo-get-default-hook new-mark-x nil)
5204 new-mark-x)))
5205 (insert new-mark " "))
5206 (when org-provide-todo-statistics
5207 (org-update-parent-todo-statistics))))
5209 (defun org-insert-subheading (arg)
5210 "Insert a new subheading and demote it.
5211 Works for outline headings and for plain lists alike."
5212 (interactive "P")
5213 (org-insert-heading arg)
5214 (cond
5215 ((org-on-heading-p) (org-do-demote))
5216 ((org-at-item-p) (org-indent-item 1))))
5218 (defun org-insert-todo-subheading (arg)
5219 "Insert a new subheading with TODO keyword or checkbox and demote it.
5220 Works for outline headings and for plain lists alike."
5221 (interactive "P")
5222 (org-insert-todo-heading arg)
5223 (cond
5224 ((org-on-heading-p) (org-do-demote))
5225 ((org-at-item-p) (org-indent-item 1))))
5227 ;;; Promotion and Demotion
5229 (defun org-promote-subtree ()
5230 "Promote the entire subtree.
5231 See also `org-promote'."
5232 (interactive)
5233 (save-excursion
5234 (org-map-tree 'org-promote))
5235 (org-fix-position-after-promote))
5237 (defun org-demote-subtree ()
5238 "Demote the entire subtree. See `org-demote'.
5239 See also `org-promote'."
5240 (interactive)
5241 (save-excursion
5242 (org-map-tree 'org-demote))
5243 (org-fix-position-after-promote))
5246 (defun org-do-promote ()
5247 "Promote the current heading higher up the tree.
5248 If the region is active in `transient-mark-mode', promote all headings
5249 in the region."
5250 (interactive)
5251 (save-excursion
5252 (if (org-region-active-p)
5253 (org-map-region 'org-promote (region-beginning) (region-end))
5254 (org-promote)))
5255 (org-fix-position-after-promote))
5257 (defun org-do-demote ()
5258 "Demote the current heading lower down the tree.
5259 If the region is active in `transient-mark-mode', demote all headings
5260 in the region."
5261 (interactive)
5262 (save-excursion
5263 (if (org-region-active-p)
5264 (org-map-region 'org-demote (region-beginning) (region-end))
5265 (org-demote)))
5266 (org-fix-position-after-promote))
5268 (defun org-fix-position-after-promote ()
5269 "Make sure that after pro/demotion cursor position is right."
5270 (let ((pos (point)))
5271 (when (save-excursion
5272 (beginning-of-line 1)
5273 (looking-at org-todo-line-regexp)
5274 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5275 (cond ((eobp) (insert " "))
5276 ((eolp) (insert " "))
5277 ((equal (char-after) ?\ ) (forward-char 1))))))
5279 (defun org-reduced-level (l)
5280 "Compute the effective level of a heading.
5281 This takes into account the setting of `org-odd-levels-only'."
5282 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5284 (defun org-get-valid-level (level &optional change)
5285 "Rectify a level change under the influence of `org-odd-levels-only'
5286 LEVEL is a current level, CHANGE is by how much the level should be
5287 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5288 even level numbers will become the next higher odd number."
5289 (if org-odd-levels-only
5290 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5291 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5292 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5293 (max 1 (+ level change))))
5295 (if (boundp 'define-obsolete-function-alias)
5296 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5297 (define-obsolete-function-alias 'org-get-legal-level
5298 'org-get-valid-level)
5299 (define-obsolete-function-alias 'org-get-legal-level
5300 'org-get-valid-level "23.1")))
5302 (defun org-promote ()
5303 "Promote the current heading higher up the tree.
5304 If the region is active in `transient-mark-mode', promote all headings
5305 in the region."
5306 (org-back-to-heading t)
5307 (let* ((level (save-match-data (funcall outline-level)))
5308 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5309 (diff (abs (- level (length up-head) -1))))
5310 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5311 (replace-match up-head nil t)
5312 ;; Fixup tag positioning
5313 (and org-auto-align-tags (org-set-tags nil t))
5314 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5316 (defun org-demote ()
5317 "Demote the current heading lower down the tree.
5318 If the region is active in `transient-mark-mode', demote all headings
5319 in the region."
5320 (org-back-to-heading t)
5321 (let* ((level (save-match-data (funcall outline-level)))
5322 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5323 (diff (abs (- level (length down-head) -1))))
5324 (replace-match down-head nil t)
5325 ;; Fixup tag positioning
5326 (and org-auto-align-tags (org-set-tags nil t))
5327 (if org-adapt-indentation (org-fixup-indentation diff))))
5329 (defun org-map-tree (fun)
5330 "Call FUN for every heading underneath the current one."
5331 (org-back-to-heading)
5332 (let ((level (funcall outline-level)))
5333 (save-excursion
5334 (funcall fun)
5335 (while (and (progn
5336 (outline-next-heading)
5337 (> (funcall outline-level) level))
5338 (not (eobp)))
5339 (funcall fun)))))
5341 (defun org-map-region (fun beg end)
5342 "Call FUN for every heading between BEG and END."
5343 (let ((org-ignore-region t))
5344 (save-excursion
5345 (setq end (copy-marker end))
5346 (goto-char beg)
5347 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5348 (< (point) end))
5349 (funcall fun))
5350 (while (and (progn
5351 (outline-next-heading)
5352 (< (point) end))
5353 (not (eobp)))
5354 (funcall fun)))))
5356 (defun org-fixup-indentation (diff)
5357 "Change the indentation in the current entry by DIFF
5358 However, if any line in the current entry has no indentation, or if it
5359 would end up with no indentation after the change, nothing at all is done."
5360 (save-excursion
5361 (let ((end (save-excursion (outline-next-heading)
5362 (point-marker)))
5363 (prohibit (if (> diff 0)
5364 "^\\S-"
5365 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5366 col)
5367 (unless (save-excursion (end-of-line 1)
5368 (re-search-forward prohibit end t))
5369 (while (and (< (point) end)
5370 (re-search-forward "^[ \t]+" end t))
5371 (goto-char (match-end 0))
5372 (setq col (current-column))
5373 (if (< diff 0) (replace-match ""))
5374 (org-indent-to-column (+ diff col))))
5375 (move-marker end nil))))
5377 (defun org-convert-to-odd-levels ()
5378 "Convert an org-mode file with all levels allowed to one with odd levels.
5379 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5380 level 5 etc."
5381 (interactive)
5382 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5383 (let ((org-odd-levels-only nil) n)
5384 (save-excursion
5385 (goto-char (point-min))
5386 (while (re-search-forward "^\\*\\*+ " nil t)
5387 (setq n (- (length (match-string 0)) 2))
5388 (while (>= (setq n (1- n)) 0)
5389 (org-demote))
5390 (end-of-line 1))))))
5393 (defun org-convert-to-oddeven-levels ()
5394 "Convert an org-mode file with only odd levels to one with odd and even levels.
5395 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5396 section with an even level, conversion would destroy the structure of the file. An error
5397 is signaled in this case."
5398 (interactive)
5399 (goto-char (point-min))
5400 ;; First check if there are no even levels
5401 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5402 (org-show-context t)
5403 (error "Not all levels are odd in this file. Conversion not possible."))
5404 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5405 (let ((org-odd-levels-only nil) n)
5406 (save-excursion
5407 (goto-char (point-min))
5408 (while (re-search-forward "^\\*\\*+ " nil t)
5409 (setq n (/ (1- (length (match-string 0))) 2))
5410 (while (>= (setq n (1- n)) 0)
5411 (org-promote))
5412 (end-of-line 1))))))
5414 (defun org-tr-level (n)
5415 "Make N odd if required."
5416 (if org-odd-levels-only (1+ (/ n 2)) n))
5418 ;;; Vertical tree motion, cutting and pasting of subtrees
5420 (defun org-move-subtree-up (&optional arg)
5421 "Move the current subtree up past ARG headlines of the same level."
5422 (interactive "p")
5423 (org-move-subtree-down (- (prefix-numeric-value arg))))
5425 (defun org-move-subtree-down (&optional arg)
5426 "Move the current subtree down past ARG headlines of the same level."
5427 (interactive "p")
5428 (setq arg (prefix-numeric-value arg))
5429 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5430 'outline-get-last-sibling))
5431 (ins-point (make-marker))
5432 (cnt (abs arg))
5433 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5434 ;; Select the tree
5435 (org-back-to-heading)
5436 (setq beg0 (point))
5437 (save-excursion
5438 (setq ne-beg (org-back-over-empty-lines))
5439 (setq beg (point)))
5440 (save-match-data
5441 (save-excursion (outline-end-of-heading)
5442 (setq folded (org-invisible-p)))
5443 (outline-end-of-subtree))
5444 (outline-next-heading)
5445 (setq ne-end (org-back-over-empty-lines))
5446 (setq end (point))
5447 (goto-char beg0)
5448 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5449 ;; include less whitespace
5450 (save-excursion
5451 (goto-char beg)
5452 (forward-line (- ne-beg ne-end))
5453 (setq beg (point))))
5454 ;; Find insertion point, with error handling
5455 (while (> cnt 0)
5456 (or (and (funcall movfunc) (looking-at outline-regexp))
5457 (progn (goto-char beg0)
5458 (error "Cannot move past superior level or buffer limit")))
5459 (setq cnt (1- cnt)))
5460 (if (> arg 0)
5461 ;; Moving forward - still need to move over subtree
5462 (progn (org-end-of-subtree t t)
5463 (save-excursion
5464 (org-back-over-empty-lines)
5465 (or (bolp) (newline)))))
5466 (setq ne-ins (org-back-over-empty-lines))
5467 (move-marker ins-point (point))
5468 (setq txt (buffer-substring beg end))
5469 (org-save-markers-in-region beg end)
5470 (delete-region beg end)
5471 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5472 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5473 (let ((bbb (point)))
5474 (insert-before-markers txt)
5475 (org-reinstall-markers-in-region bbb)
5476 (move-marker ins-point bbb))
5477 (or (bolp) (insert "\n"))
5478 (setq ins-end (point))
5479 (goto-char ins-point)
5480 (org-skip-whitespace)
5481 (when (and (< arg 0)
5482 (org-first-sibling-p)
5483 (> ne-ins ne-beg))
5484 ;; Move whitespace back to beginning
5485 (save-excursion
5486 (goto-char ins-end)
5487 (let ((kill-whole-line t))
5488 (kill-line (- ne-ins ne-beg)) (point)))
5489 (insert (make-string (- ne-ins ne-beg) ?\n)))
5490 (move-marker ins-point nil)
5491 (org-compact-display-after-subtree-move)
5492 (org-show-empty-lines-in-parent)
5493 (unless folded
5494 (org-show-entry)
5495 (show-children)
5496 (org-cycle-hide-drawers 'children))))
5498 (defvar org-subtree-clip ""
5499 "Clipboard for cut and paste of subtrees.
5500 This is actually only a copy of the kill, because we use the normal kill
5501 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5503 (defvar org-subtree-clip-folded nil
5504 "Was the last copied subtree folded?
5505 This is used to fold the tree back after pasting.")
5507 (defun org-cut-subtree (&optional n)
5508 "Cut the current subtree into the clipboard.
5509 With prefix arg N, cut this many sequential subtrees.
5510 This is a short-hand for marking the subtree and then cutting it."
5511 (interactive "p")
5512 (org-copy-subtree n 'cut))
5514 (defun org-copy-subtree (&optional n cut force-store-markers)
5515 "Cut the current subtree into the clipboard.
5516 With prefix arg N, cut this many sequential subtrees.
5517 This is a short-hand for marking the subtree and then copying it.
5518 If CUT is non-nil, actually cut the subtree.
5519 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5520 of some markers in the region, even if CUT is non-nil. This is
5521 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5522 (interactive "p")
5523 (let (beg end folded (beg0 (point)))
5524 (if (interactive-p)
5525 (org-back-to-heading nil) ; take what looks like a subtree
5526 (org-back-to-heading t)) ; take what is really there
5527 (org-back-over-empty-lines)
5528 (setq beg (point))
5529 (skip-chars-forward " \t\r\n")
5530 (save-match-data
5531 (save-excursion (outline-end-of-heading)
5532 (setq folded (org-invisible-p)))
5533 (condition-case nil
5534 (outline-forward-same-level (1- n))
5535 (error nil))
5536 (org-end-of-subtree t t))
5537 (org-back-over-empty-lines)
5538 (setq end (point))
5539 (goto-char beg0)
5540 (when (> end beg)
5541 (setq org-subtree-clip-folded folded)
5542 (when (or cut force-store-markers)
5543 (org-save-markers-in-region beg end))
5544 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5545 (setq org-subtree-clip (current-kill 0))
5546 (message "%s: Subtree(s) with %d characters"
5547 (if cut "Cut" "Copied")
5548 (length org-subtree-clip)))))
5550 (defun org-paste-subtree (&optional level tree for-yank)
5551 "Paste the clipboard as a subtree, with modification of headline level.
5552 The entire subtree is promoted or demoted in order to match a new headline
5553 level.
5555 If the cursor is at the beginning of a headline, the same level as
5556 that headline is used to paste the tree
5558 If not, the new level is derived from the *visible* headings
5559 before and after the insertion point, and taken to be the inferior headline
5560 level of the two. So if the previous visible heading is level 3 and the
5561 next is level 4 (or vice versa), level 4 will be used for insertion.
5562 This makes sure that the subtree remains an independent subtree and does
5563 not swallow low level entries.
5565 You can also force a different level, either by using a numeric prefix
5566 argument, or by inserting the heading marker by hand. For example, if the
5567 cursor is after \"*****\", then the tree will be shifted to level 5.
5569 If optional TREE is given, use this text instead of the kill ring.
5571 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5572 move back over whitespace before inserting, and move point to the end of
5573 the inserted text when done."
5574 (interactive "P")
5575 (unless (org-kill-is-subtree-p tree)
5576 (error "%s"
5577 (substitute-command-keys
5578 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5579 (let* ((visp (not (org-invisible-p)))
5580 (txt (or tree (and kill-ring (current-kill 0))))
5581 (^re (concat "^\\(" outline-regexp "\\)"))
5582 (re (concat "\\(" outline-regexp "\\)"))
5583 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5585 (old-level (if (string-match ^re txt)
5586 (- (match-end 0) (match-beginning 0) 1)
5587 -1))
5588 (force-level (cond (level (prefix-numeric-value level))
5589 ((and (looking-at "[ \t]*$")
5590 (string-match
5591 ^re_ (buffer-substring
5592 (point-at-bol) (point))))
5593 (- (match-end 1) (match-beginning 1)))
5594 ((and (bolp)
5595 (looking-at org-outline-regexp))
5596 (- (match-end 0) (point) 1))
5597 (t nil)))
5598 (previous-level (save-excursion
5599 (condition-case nil
5600 (progn
5601 (outline-previous-visible-heading 1)
5602 (if (looking-at re)
5603 (- (match-end 0) (match-beginning 0) 1)
5605 (error 1))))
5606 (next-level (save-excursion
5607 (condition-case nil
5608 (progn
5609 (or (looking-at outline-regexp)
5610 (outline-next-visible-heading 1))
5611 (if (looking-at re)
5612 (- (match-end 0) (match-beginning 0) 1)
5614 (error 1))))
5615 (new-level (or force-level (max previous-level next-level)))
5616 (shift (if (or (= old-level -1)
5617 (= new-level -1)
5618 (= old-level new-level))
5620 (- new-level old-level)))
5621 (delta (if (> shift 0) -1 1))
5622 (func (if (> shift 0) 'org-demote 'org-promote))
5623 (org-odd-levels-only nil)
5624 beg end newend)
5625 ;; Remove the forced level indicator
5626 (if force-level
5627 (delete-region (point-at-bol) (point)))
5628 ;; Paste
5629 (beginning-of-line 1)
5630 (unless for-yank (org-back-over-empty-lines))
5631 (setq beg (point))
5632 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5633 (insert-before-markers txt)
5634 (unless (string-match "\n\\'" txt) (insert "\n"))
5635 (setq newend (point))
5636 (org-reinstall-markers-in-region beg)
5637 (setq end (point))
5638 (goto-char beg)
5639 (skip-chars-forward " \t\n\r")
5640 (setq beg (point))
5641 (if (and (org-invisible-p) visp)
5642 (save-excursion (outline-show-heading)))
5643 ;; Shift if necessary
5644 (unless (= shift 0)
5645 (save-restriction
5646 (narrow-to-region beg end)
5647 (while (not (= shift 0))
5648 (org-map-region func (point-min) (point-max))
5649 (setq shift (+ delta shift)))
5650 (goto-char (point-min))
5651 (setq newend (point-max))))
5652 (when (or (interactive-p) for-yank)
5653 (message "Clipboard pasted as level %d subtree" new-level))
5654 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5655 kill-ring
5656 (eq org-subtree-clip (current-kill 0))
5657 org-subtree-clip-folded)
5658 ;; The tree was folded before it was killed/copied
5659 (hide-subtree))
5660 (and for-yank (goto-char newend))))
5662 (defun org-kill-is-subtree-p (&optional txt)
5663 "Check if the current kill is an outline subtree, or a set of trees.
5664 Returns nil if kill does not start with a headline, or if the first
5665 headline level is not the largest headline level in the tree.
5666 So this will actually accept several entries of equal levels as well,
5667 which is OK for `org-paste-subtree'.
5668 If optional TXT is given, check this string instead of the current kill."
5669 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5670 (start-level (and kill
5671 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5672 org-outline-regexp "\\)")
5673 kill)
5674 (- (match-end 2) (match-beginning 2) 1)))
5675 (re (concat "^" org-outline-regexp))
5676 (start (1+ (or (match-beginning 2) -1))))
5677 (if (not start-level)
5678 (progn
5679 nil) ;; does not even start with a heading
5680 (catch 'exit
5681 (while (setq start (string-match re kill (1+ start)))
5682 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5683 (throw 'exit nil)))
5684 t))))
5686 (defvar org-markers-to-move nil
5687 "Markers that should be moved with a cut-and-paste operation.
5688 Those markers are stored together with their positions relative to
5689 the start of the region.")
5691 (defun org-save-markers-in-region (beg end)
5692 "Check markers in region.
5693 If these markers are between BEG and END, record their position relative
5694 to BEG, so that after moving the block of text, we can put the markers back
5695 into place.
5696 This function gets called just before an entry or tree gets cut from the
5697 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5698 called immediately, to move the markers with the entries."
5699 (setq org-markers-to-move nil)
5700 (when (featurep 'org-clock)
5701 (org-clock-save-markers-for-cut-and-paste beg end))
5702 (when (featurep 'org-agenda)
5703 (org-agenda-save-markers-for-cut-and-paste beg end)))
5705 (defun org-check-and-save-marker (marker beg end)
5706 "Check if MARKER is between BEG and END.
5707 If yes, remember the marker and the distance to BEG."
5708 (when (and (marker-buffer marker)
5709 (equal (marker-buffer marker) (current-buffer)))
5710 (if (and (>= marker beg) (< marker end))
5711 (push (cons marker (- marker beg)) org-markers-to-move))))
5713 (defun org-reinstall-markers-in-region (beg)
5714 "Move all remembered markers to their position relative to BEG."
5715 (mapc (lambda (x)
5716 (move-marker (car x) (+ beg (cdr x))))
5717 org-markers-to-move)
5718 (setq org-markers-to-move nil))
5720 (defun org-narrow-to-subtree ()
5721 "Narrow buffer to the current subtree."
5722 (interactive)
5723 (save-excursion
5724 (save-match-data
5725 (narrow-to-region
5726 (progn (org-back-to-heading) (point))
5727 (progn (org-end-of-subtree t) (point))))))
5730 ;;; Outline Sorting
5732 (defun org-sort (with-case)
5733 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5734 Optional argument WITH-CASE means sort case-sensitively.
5735 With a double prefix argument, also remove duplicate entries."
5736 (interactive "P")
5737 (if (org-at-table-p)
5738 (org-call-with-arg 'org-table-sort-lines with-case)
5739 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5741 (defun org-sort-remove-invisible (s)
5742 (remove-text-properties 0 (length s) org-rm-props s)
5743 (while (string-match org-bracket-link-regexp s)
5744 (setq s (replace-match (if (match-end 2)
5745 (match-string 3 s)
5746 (match-string 1 s)) t t s)))
5749 (defvar org-priority-regexp) ; defined later in the file
5751 (defun org-sort-entries-or-items
5752 (&optional with-case sorting-type getkey-func compare-func property)
5753 "Sort entries on a certain level of an outline tree.
5754 If there is an active region, the entries in the region are sorted.
5755 Else, if the cursor is before the first entry, sort the top-level items.
5756 Else, the children of the entry at point are sorted.
5758 Sorting can be alphabetically, numerically, and by date/time as given by
5759 the first time stamp in the entry. The command prompts for the sorting
5760 type unless it has been given to the function through the SORTING-TYPE
5761 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5762 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5763 called with point at the beginning of the record. It must return either
5764 a string or a number that should serve as the sorting key for that record.
5766 Comparing entries ignores case by default. However, with an optional argument
5767 WITH-CASE, the sorting considers case as well."
5768 (interactive "P")
5769 (let ((case-func (if with-case 'identity 'downcase))
5770 start beg end stars re re2
5771 txt what tmp plain-list-p)
5772 ;; Find beginning and end of region to sort
5773 (cond
5774 ((org-region-active-p)
5775 ;; we will sort the region
5776 (setq end (region-end)
5777 what "region")
5778 (goto-char (region-beginning))
5779 (if (not (org-on-heading-p)) (outline-next-heading))
5780 (setq start (point)))
5781 ((org-at-item-p)
5782 ;; we will sort this plain list
5783 (org-beginning-of-item-list) (setq start (point))
5784 (org-end-of-item-list) (setq end (point))
5785 (goto-char start)
5786 (setq plain-list-p t
5787 what "plain list"))
5788 ((or (org-on-heading-p)
5789 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5790 ;; we will sort the children of the current headline
5791 (org-back-to-heading)
5792 (setq start (point)
5793 end (progn (org-end-of-subtree t t)
5794 (org-back-over-empty-lines)
5795 (point))
5796 what "children")
5797 (goto-char start)
5798 (show-subtree)
5799 (outline-next-heading))
5801 ;; we will sort the top-level entries in this file
5802 (goto-char (point-min))
5803 (or (org-on-heading-p) (outline-next-heading))
5804 (setq start (point) end (point-max) what "top-level")
5805 (goto-char start)
5806 (show-all)))
5808 (setq beg (point))
5809 (if (>= beg end) (error "Nothing to sort"))
5811 (unless plain-list-p
5812 (looking-at "\\(\\*+\\)")
5813 (setq stars (match-string 1)
5814 re (concat "^" (regexp-quote stars) " +")
5815 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5816 txt (buffer-substring beg end))
5817 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5818 (if (and (not (equal stars "*")) (string-match re2 txt))
5819 (error "Region to sort contains a level above the first entry")))
5821 (unless sorting-type
5822 (message
5823 (if plain-list-p
5824 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5825 "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:")
5826 what)
5827 (setq sorting-type (read-char-exclusive))
5829 (and (= (downcase sorting-type) ?f)
5830 (setq getkey-func
5831 (org-ido-completing-read "Sort using function: "
5832 obarray 'fboundp t nil nil))
5833 (setq getkey-func (intern getkey-func)))
5835 (and (= (downcase sorting-type) ?r)
5836 (setq property
5837 (org-ido-completing-read "Property: "
5838 (mapcar 'list (org-buffer-property-keys t))
5839 nil t))))
5841 (message "Sorting entries...")
5843 (save-restriction
5844 (narrow-to-region start end)
5846 (let ((dcst (downcase sorting-type))
5847 (now (current-time)))
5848 (sort-subr
5849 (/= dcst sorting-type)
5850 ;; This function moves to the beginning character of the "record" to
5851 ;; be sorted.
5852 (if plain-list-p
5853 (lambda nil
5854 (if (org-at-item-p) t (goto-char (point-max))))
5855 (lambda nil
5856 (if (re-search-forward re nil t)
5857 (goto-char (match-beginning 0))
5858 (goto-char (point-max)))))
5859 ;; This function moves to the last character of the "record" being
5860 ;; sorted.
5861 (if plain-list-p
5862 'org-end-of-item
5863 (lambda nil
5864 (save-match-data
5865 (condition-case nil
5866 (outline-forward-same-level 1)
5867 (error
5868 (goto-char (point-max)))))))
5870 ;; This function returns the value that gets sorted against.
5871 (if plain-list-p
5872 (lambda nil
5873 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5874 (cond
5875 ((= dcst ?n)
5876 (string-to-number (buffer-substring (match-end 0)
5877 (point-at-eol))))
5878 ((= dcst ?a)
5879 (buffer-substring (match-end 0) (point-at-eol)))
5880 ((= dcst ?t)
5881 (if (re-search-forward org-ts-regexp
5882 (point-at-eol) t)
5883 (org-time-string-to-time (match-string 0))
5884 now))
5885 ((= dcst ?f)
5886 (if getkey-func
5887 (progn
5888 (setq tmp (funcall getkey-func))
5889 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5890 tmp)
5891 (error "Invalid key function `%s'" getkey-func)))
5892 (t (error "Invalid sorting type `%c'" sorting-type)))))
5893 (lambda nil
5894 (cond
5895 ((= dcst ?n)
5896 (if (looking-at org-complex-heading-regexp)
5897 (string-to-number (match-string 4))
5898 nil))
5899 ((= dcst ?a)
5900 (if (looking-at org-complex-heading-regexp)
5901 (funcall case-func (match-string 4))
5902 nil))
5903 ((= dcst ?t)
5904 (if (re-search-forward org-ts-regexp
5905 (save-excursion
5906 (forward-line 2)
5907 (point)) t)
5908 (org-time-string-to-time (match-string 0))
5909 now))
5910 ((= dcst ?p)
5911 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5912 (string-to-char (match-string 2))
5913 org-default-priority))
5914 ((= dcst ?r)
5915 (or (org-entry-get nil property) ""))
5916 ((= dcst ?o)
5917 (if (looking-at org-complex-heading-regexp)
5918 (- 9999 (length (member (match-string 2)
5919 org-todo-keywords-1)))))
5920 ((= dcst ?f)
5921 (if getkey-func
5922 (progn
5923 (setq tmp (funcall getkey-func))
5924 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5925 tmp)
5926 (error "Invalid key function `%s'" getkey-func)))
5927 (t (error "Invalid sorting type `%c'" sorting-type)))))
5929 (cond
5930 ((= dcst ?a) 'string<)
5931 ((= dcst ?t) 'time-less-p)
5932 ((= dcst ?f) compare-func)
5933 (t nil)))))
5934 (message "Sorting entries...done")))
5936 (defun org-do-sort (table what &optional with-case sorting-type)
5937 "Sort TABLE of WHAT according to SORTING-TYPE.
5938 The user will be prompted for the SORTING-TYPE if the call to this
5939 function does not specify it. WHAT is only for the prompt, to indicate
5940 what is being sorted. The sorting key will be extracted from
5941 the car of the elements of the table.
5942 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5943 (unless sorting-type
5944 (message
5945 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5946 what)
5947 (setq sorting-type (read-char-exclusive)))
5948 (let ((dcst (downcase sorting-type))
5949 extractfun comparefun)
5950 ;; Define the appropriate functions
5951 (cond
5952 ((= dcst ?n)
5953 (setq extractfun 'string-to-number
5954 comparefun (if (= dcst sorting-type) '< '>)))
5955 ((= dcst ?a)
5956 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5957 (lambda(x) (downcase (org-sort-remove-invisible x))))
5958 comparefun (if (= dcst sorting-type)
5959 'string<
5960 (lambda (a b) (and (not (string< a b))
5961 (not (string= a b)))))))
5962 ((= dcst ?t)
5963 (setq extractfun
5964 (lambda (x)
5965 (if (or (string-match org-ts-regexp x)
5966 (string-match org-ts-regexp-both x))
5967 (time-to-seconds
5968 (org-time-string-to-time (match-string 0 x)))
5970 comparefun (if (= dcst sorting-type) '< '>)))
5971 (t (error "Invalid sorting type `%c'" sorting-type)))
5973 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5974 table)
5975 (lambda (a b) (funcall comparefun (car a) (car b))))))
5977 ;;; Editing source examples
5979 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5980 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5981 (defvar org-edit-src-force-single-line nil)
5982 (defvar org-edit-src-from-org-mode nil)
5983 (defvar org-edit-src-picture nil)
5985 (define-minor-mode org-exit-edit-mode
5986 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5988 (defun org-edit-src-code ()
5989 "Edit the source code example at point.
5990 An indirect buffer is created, and that buffer is then narrowed to the
5991 example at point and switched to the correct language mode. When done,
5992 exit by killing the buffer with \\[org-edit-src-exit]."
5993 (interactive)
5994 (let ((line (org-current-line))
5995 (case-fold-search t)
5996 (msg (substitute-command-keys
5997 "Edit, then exit with C-c ' (C-c and single quote)"))
5998 (info (org-edit-src-find-region-and-lang))
5999 (org-mode-p (eq major-mode 'org-mode))
6000 beg end lang lang-f single lfmt)
6001 (if (not info)
6003 (setq beg (nth 0 info)
6004 end (nth 1 info)
6005 lang (nth 2 info)
6006 single (nth 3 info)
6007 lfmt (nth 4 info)
6008 lang-f (intern (concat lang "-mode")))
6009 (unless (functionp lang-f)
6010 (error "No such language mode: %s" lang-f))
6011 (goto-line line)
6012 (if (get-buffer "*Org Edit Src Example*")
6013 (kill-buffer "*Org Edit Src Example*"))
6014 (switch-to-buffer (make-indirect-buffer (current-buffer)
6015 "*Org Edit Src Example*"))
6016 (narrow-to-region beg end)
6017 (remove-text-properties beg end '(display nil invisible nil
6018 intangible nil))
6019 (let ((org-inhibit-startup t))
6020 (funcall lang-f))
6021 (set (make-local-variable 'org-edit-src-force-single-line) single)
6022 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6023 (when lfmt
6024 (set (make-local-variable 'org-coderef-label-format) lfmt))
6025 (when org-mode-p
6026 (goto-char (point-min))
6027 (while (re-search-forward "^," nil t)
6028 (replace-match "")))
6029 (goto-line line)
6030 (org-exit-edit-mode)
6031 (org-set-local 'header-line-format msg)
6032 (message "%s" msg)
6033 t)))
6035 (defun org-edit-fixed-width-region ()
6036 "Edit the fixed-width ascii drawing at point.
6037 This must be a region where each line starts with a colon followed by
6038 a space character.
6039 An indirect buffer is created, and that buffer is then narrowed to the
6040 example at point and switched to artist-mode. When done,
6041 exit by killing the buffer with \\[org-edit-src-exit]."
6042 (interactive)
6043 (let ((line (org-current-line))
6044 (case-fold-search t)
6045 (msg (substitute-command-keys
6046 "Edit, then exit with C-c ' (C-c and single quote)"))
6047 (org-mode-p (eq major-mode 'org-mode))
6048 beg end)
6049 (beginning-of-line 1)
6050 (if (looking-at "[ \t]*[^:\n \t]")
6052 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6053 (setq beg (point) end beg)
6054 (save-excursion
6055 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6056 (setq beg (point-at-bol 2))
6057 (setq beg (point))))
6058 (save-excursion
6059 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6060 (setq end (1- (match-beginning 0)))
6061 (setq end (point))))
6062 (goto-line line))
6063 (if (get-buffer "*Org Edit Picture*")
6064 (kill-buffer "*Org Edit Picture*"))
6065 (switch-to-buffer (make-indirect-buffer (current-buffer)
6066 "*Org Edit Picture*"))
6067 (narrow-to-region beg end)
6068 (remove-text-properties beg end '(display nil invisible nil
6069 intangible nil))
6070 (when (fboundp 'font-lock-unfontify-region)
6071 (font-lock-unfontify-region (point-min) (point-max)))
6072 (cond
6073 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6074 (fundamental-mode)
6075 (artist-mode 1))
6076 (t (funcall org-edit-fixed-width-region-mode)))
6077 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6078 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6079 (set (make-local-variable 'org-edit-src-picture) t)
6080 (goto-char (point-min))
6081 (while (re-search-forward "^[ \t]*: ?" nil t)
6082 (replace-match ""))
6083 (goto-line line)
6084 (org-exit-edit-mode)
6085 (org-set-local 'header-line-format msg)
6086 (message "%s" msg)
6087 t)))
6090 (defun org-edit-src-find-region-and-lang ()
6091 "Find the region and language for a local edit.
6092 Return a list with beginning and end of the region, a string representing
6093 the language, a switch telling of the content should be in a single line."
6094 (let ((re-list
6095 (append
6096 org-edit-src-region-extra
6098 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6099 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6100 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6101 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6102 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6103 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6104 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6105 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6106 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6107 ("^#\\+html:" "\n" "html" single-line)
6108 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6109 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6110 ("^#\\+latex:" "\n" "latex" single-line)
6111 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6112 ("^#\\+ascii:" "\n" "ascii" single-line)
6114 (pos (point))
6115 re1 re2 single beg end lang lfmt match-re1)
6116 (catch 'exit
6117 (while (setq entry (pop re-list))
6118 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6119 single (nth 3 entry))
6120 (save-excursion
6121 (if (or (looking-at re1)
6122 (re-search-backward re1 nil t))
6123 (progn
6124 (setq match-re1 (match-string 0))
6125 (setq beg (match-end 0)
6126 lang (org-edit-src-get-lang lang)
6127 lfmt (org-edit-src-get-label-format match-re1))
6128 (if (and (re-search-forward re2 nil t)
6129 (>= (match-end 0) pos))
6130 (throw 'exit (list beg (match-beginning 0)
6131 lang single lfmt))))
6132 (if (or (looking-at re2)
6133 (re-search-forward re2 nil t))
6134 (progn
6135 (setq end (match-beginning 0))
6136 (if (and (re-search-backward re1 nil t)
6137 (<= (match-beginning 0) pos))
6138 (progn
6139 (setq lfmt (org-edit-src-get-label-format
6140 (match-string 0)))
6141 (throw 'exit
6142 (list (match-end 0) end
6143 (org-edit-src-get-lang lang)
6144 single lfmt))))))))))))
6146 (defun org-edit-src-get-lang (lang)
6147 "Extract the src language."
6148 (let ((m (match-string 0)))
6149 (cond
6150 ((stringp lang) lang)
6151 ((integerp lang) (match-string lang))
6152 ((and (eq lang 'lang)
6153 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6154 (match-string 1 m))
6155 ((and (eq lang 'style)
6156 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6157 (match-string 1 m))
6158 (t "fundamental"))))
6160 (defun org-edit-src-get-label-format (s)
6161 "Extract the label format."
6162 (save-match-data
6163 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6164 (match-string 1 s))))
6166 (defun org-edit-src-exit ()
6167 "Exit special edit and protect problematic lines."
6168 (interactive)
6169 (unless (buffer-base-buffer (current-buffer))
6170 (error "This is not an indirect buffer, something is wrong..."))
6171 (unless (> (point-min) 1)
6172 (error "This buffer is not narrowed, something is wrong..."))
6173 (goto-char (point-min))
6174 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6175 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6176 (when (org-bound-and-true-p org-edit-src-force-single-line)
6177 (goto-char (point-min))
6178 (while (re-search-forward "\n" nil t)
6179 (replace-match " "))
6180 (goto-char (point-min))
6181 (if (looking-at "\\s-*") (replace-match " "))
6182 (if (re-search-forward "\\s-+\\'" nil t)
6183 (replace-match "")))
6184 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6185 (goto-char (point-min))
6186 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6187 (replace-match ",\\1"))
6188 (when font-lock-mode
6189 (font-lock-unfontify-region (point-min) (point-max)))
6190 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6191 (when (org-bound-and-true-p org-edit-src-picture)
6192 (untabify (point-min) (point-max))
6193 (goto-char (point-min))
6194 (while (re-search-forward "^" nil t)
6195 (replace-match ": "))
6196 (when font-lock-mode
6197 (font-lock-unfontify-region (point-min) (point-max)))
6198 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6199 (kill-buffer (current-buffer))
6200 (and (org-mode-p) (org-restart-font-lock)))
6203 ;;; The orgstruct minor mode
6205 ;; Define a minor mode which can be used in other modes in order to
6206 ;; integrate the org-mode structure editing commands.
6208 ;; This is really a hack, because the org-mode structure commands use
6209 ;; keys which normally belong to the major mode. Here is how it
6210 ;; works: The minor mode defines all the keys necessary to operate the
6211 ;; structure commands, but wraps the commands into a function which
6212 ;; tests if the cursor is currently at a headline or a plain list
6213 ;; item. If that is the case, the structure command is used,
6214 ;; temporarily setting many Org-mode variables like regular
6215 ;; expressions for filling etc. However, when any of those keys is
6216 ;; used at a different location, function uses `key-binding' to look
6217 ;; up if the key has an associated command in another currently active
6218 ;; keymap (minor modes, major mode, global), and executes that
6219 ;; command. There might be problems if any of the keys is otherwise
6220 ;; used as a prefix key.
6222 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6223 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6224 ;; addresses this by checking explicitly for both bindings.
6226 (defvar orgstruct-mode-map (make-sparse-keymap)
6227 "Keymap for the minor `orgstruct-mode'.")
6229 (defvar org-local-vars nil
6230 "List of local variables, for use by `orgstruct-mode'")
6232 ;;;###autoload
6233 (define-minor-mode orgstruct-mode
6234 "Toggle the minor more `orgstruct-mode'.
6235 This mode is for using Org-mode structure commands in other modes.
6236 The following key behave as if Org-mode was active, if the cursor
6237 is on a headline, or on a plain list item (both in the definition
6238 of Org-mode).
6240 M-up Move entry/item up
6241 M-down Move entry/item down
6242 M-left Promote
6243 M-right Demote
6244 M-S-up Move entry/item up
6245 M-S-down Move entry/item down
6246 M-S-left Promote subtree
6247 M-S-right Demote subtree
6248 M-q Fill paragraph and items like in Org-mode
6249 C-c ^ Sort entries
6250 C-c - Cycle list bullet
6251 TAB Cycle item visibility
6252 M-RET Insert new heading/item
6253 S-M-RET Insert new TODO heading / Checkbox item
6254 C-c C-c Set tags / toggle checkbox"
6255 nil " OrgStruct" nil
6256 (org-load-modules-maybe)
6257 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6259 ;;;###autoload
6260 (defun turn-on-orgstruct ()
6261 "Unconditionally turn on `orgstruct-mode'."
6262 (orgstruct-mode 1))
6264 ;;;###autoload
6265 (defun turn-on-orgstruct++ ()
6266 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6267 In addition to setting orgstruct-mode, this also exports all indentation and
6268 autofilling variables from org-mode into the buffer. Note that turning
6269 off orgstruct-mode will *not* remove these additional settings."
6270 (orgstruct-mode 1)
6271 (let (var val)
6272 (mapc
6273 (lambda (x)
6274 (when (string-match
6275 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6276 (symbol-name (car x)))
6277 (setq var (car x) val (nth 1 x))
6278 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6279 org-local-vars)))
6281 (defun orgstruct-error ()
6282 "Error when there is no default binding for a structure key."
6283 (interactive)
6284 (error "This key has no function outside structure elements"))
6286 (defun orgstruct-setup ()
6287 "Setup orgstruct keymaps."
6288 (let ((nfunc 0)
6289 (bindings
6290 (list
6291 '([(meta up)] org-metaup)
6292 '([(meta down)] org-metadown)
6293 '([(meta left)] org-metaleft)
6294 '([(meta right)] org-metaright)
6295 '([(meta shift up)] org-shiftmetaup)
6296 '([(meta shift down)] org-shiftmetadown)
6297 '([(meta shift left)] org-shiftmetaleft)
6298 '([(meta shift right)] org-shiftmetaright)
6299 '([(shift up)] org-shiftup)
6300 '([(shift down)] org-shiftdown)
6301 '([(shift left)] org-shiftleft)
6302 '([(shift right)] org-shiftright)
6303 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6304 '("\M-q" fill-paragraph)
6305 '("\C-c^" org-sort)
6306 '("\C-c-" org-cycle-list-bullet)))
6307 elt key fun cmd)
6308 (while (setq elt (pop bindings))
6309 (setq nfunc (1+ nfunc))
6310 (setq key (org-key (car elt))
6311 fun (nth 1 elt)
6312 cmd (orgstruct-make-binding fun nfunc key))
6313 (org-defkey orgstruct-mode-map key cmd))
6315 ;; Special treatment needed for TAB and RET
6316 (org-defkey orgstruct-mode-map [(tab)]
6317 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6318 (org-defkey orgstruct-mode-map "\C-i"
6319 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6321 (org-defkey orgstruct-mode-map "\M-\C-m"
6322 (orgstruct-make-binding 'org-insert-heading 105
6323 "\M-\C-m" [(meta return)]))
6324 (org-defkey orgstruct-mode-map [(meta return)]
6325 (orgstruct-make-binding 'org-insert-heading 106
6326 [(meta return)] "\M-\C-m"))
6328 (org-defkey orgstruct-mode-map [(shift meta return)]
6329 (orgstruct-make-binding 'org-insert-todo-heading 107
6330 [(meta return)] "\M-\C-m"))
6332 (unless org-local-vars
6333 (setq org-local-vars (org-get-local-variables)))
6337 (defun orgstruct-make-binding (fun n &rest keys)
6338 "Create a function for binding in the structure minor mode.
6339 FUN is the command to call inside a table. N is used to create a unique
6340 command name. KEYS are keys that should be checked in for a command
6341 to execute outside of tables."
6342 (eval
6343 (list 'defun
6344 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6345 '(arg)
6346 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6347 "Outside of structure, run the binding of `"
6348 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6349 "'.")
6350 '(interactive "p")
6351 (list 'if
6352 '(org-context-p 'headline 'item)
6353 (list 'org-run-like-in-org-mode (list 'quote fun))
6354 (list 'let '(orgstruct-mode)
6355 (list 'call-interactively
6356 (append '(or)
6357 (mapcar (lambda (k)
6358 (list 'key-binding k))
6359 keys)
6360 '('orgstruct-error))))))))
6362 (defun org-context-p (&rest contexts)
6363 "Check if local context is any of CONTEXTS.
6364 Possible values in the list of contexts are `table', `headline', and `item'."
6365 (let ((pos (point)))
6366 (goto-char (point-at-bol))
6367 (prog1 (or (and (memq 'table contexts)
6368 (looking-at "[ \t]*|"))
6369 (and (memq 'headline contexts)
6370 ;;????????? (looking-at "\\*+"))
6371 (looking-at outline-regexp))
6372 (and (memq 'item contexts)
6373 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6374 (goto-char pos))))
6376 (defun org-get-local-variables ()
6377 "Return a list of all local variables in an org-mode buffer."
6378 (let (varlist)
6379 (with-current-buffer (get-buffer-create "*Org tmp*")
6380 (erase-buffer)
6381 (org-mode)
6382 (setq varlist (buffer-local-variables)))
6383 (kill-buffer "*Org tmp*")
6384 (delq nil
6385 (mapcar
6386 (lambda (x)
6387 (setq x
6388 (if (symbolp x)
6389 (list x)
6390 (list (car x) (list 'quote (cdr x)))))
6391 (if (string-match
6392 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6393 (symbol-name (car x)))
6394 x nil))
6395 varlist))))
6397 ;;;###autoload
6398 (defun org-run-like-in-org-mode (cmd)
6399 (org-load-modules-maybe)
6400 (unless org-local-vars
6401 (setq org-local-vars (org-get-local-variables)))
6402 (eval (list 'let org-local-vars
6403 (list 'call-interactively (list 'quote cmd)))))
6405 ;;;; Archiving
6407 (defun org-get-category (&optional pos)
6408 "Get the category applying to position POS."
6409 (get-text-property (or pos (point)) 'org-category))
6411 (defun org-refresh-category-properties ()
6412 "Refresh category text properties in the buffer."
6413 (let ((def-cat (cond
6414 ((null org-category)
6415 (if buffer-file-name
6416 (file-name-sans-extension
6417 (file-name-nondirectory buffer-file-name))
6418 "???"))
6419 ((symbolp org-category) (symbol-name org-category))
6420 (t org-category)))
6421 beg end cat pos optionp)
6422 (org-unmodified
6423 (save-excursion
6424 (save-restriction
6425 (widen)
6426 (goto-char (point-min))
6427 (put-text-property (point) (point-max) 'org-category def-cat)
6428 (while (re-search-forward
6429 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6430 (setq pos (match-end 0)
6431 optionp (equal (char-after (match-beginning 0)) ?#)
6432 cat (org-trim (match-string 2)))
6433 (if optionp
6434 (setq beg (point-at-bol) end (point-max))
6435 (org-back-to-heading t)
6436 (setq beg (point) end (org-end-of-subtree t t)))
6437 (put-text-property beg end 'org-category cat)
6438 (goto-char pos)))))))
6441 ;;;; Link Stuff
6443 ;;; Link abbreviations
6445 (defun org-link-expand-abbrev (link)
6446 "Apply replacements as defined in `org-link-abbrev-alist."
6447 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6448 (let* ((key (match-string 1 link))
6449 (as (or (assoc key org-link-abbrev-alist-local)
6450 (assoc key org-link-abbrev-alist)))
6451 (tag (and (match-end 2) (match-string 3 link)))
6452 rpl)
6453 (if (not as)
6454 link
6455 (setq rpl (cdr as))
6456 (cond
6457 ((symbolp rpl) (funcall rpl tag))
6458 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6459 ((string-match "%h" rpl)
6460 (replace-match (url-hexify-string (or tag "")) t t rpl))
6461 (t (concat rpl tag)))))
6462 link))
6464 ;;; Storing and inserting links
6466 (defvar org-insert-link-history nil
6467 "Minibuffer history for links inserted with `org-insert-link'.")
6469 (defvar org-stored-links nil
6470 "Contains the links stored with `org-store-link'.")
6472 (defvar org-store-link-plist nil
6473 "Plist with info about the most recently link created with `org-store-link'.")
6475 (defvar org-link-protocols nil
6476 "Link protocols added to Org-mode using `org-add-link-type'.")
6478 (defvar org-store-link-functions nil
6479 "List of functions that are called to create and store a link.
6480 Each function will be called in turn until one returns a non-nil
6481 value. Each function should check if it is responsible for creating
6482 this link (for example by looking at the major mode).
6483 If not, it must exit and return nil.
6484 If yes, it should return a non-nil value after a calling
6485 `org-store-link-props' with a list of properties and values.
6486 Special properties are:
6488 :type The link prefix. like \"http\". This must be given.
6489 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6490 This is obligatory as well.
6491 :description Optional default description for the second pair
6492 of brackets in an Org-mode link. The user can still change
6493 this when inserting this link into an Org-mode buffer.
6495 In addition to these, any additional properties can be specified
6496 and then used in remember templates.")
6498 (defun org-add-link-type (type &optional follow export)
6499 "Add TYPE to the list of `org-link-types'.
6500 Re-compute all regular expressions depending on `org-link-types'
6502 FOLLOW and EXPORT are two functions.
6504 FOLLOW should take the link path as the single argument and do whatever
6505 is necessary to follow the link, for example find a file or display
6506 a mail message.
6508 EXPORT should format the link path for export to one of the export formats.
6509 It should be a function accepting three arguments:
6511 path the path of the link, the text after the prefix (like \"http:\")
6512 desc the description of the link, if any, nil if there was no description
6513 format the export format, a symbol like `html' or `latex'.
6515 The function may use the FORMAT information to return different values
6516 depending on the format. The return value will be put literally into
6517 the exported file.
6518 Org-mode has a built-in default for exporting links. If you are happy with
6519 this default, there is no need to define an export function for the link
6520 type. For a simple example of an export function, see `org-bbdb.el'."
6521 (add-to-list 'org-link-types type t)
6522 (org-make-link-regexps)
6523 (if (assoc type org-link-protocols)
6524 (setcdr (assoc type org-link-protocols) (list follow export))
6525 (push (list type follow export) org-link-protocols)))
6527 ;;;###autoload
6528 (defun org-store-link (arg)
6529 "\\<org-mode-map>Store an org-link to the current location.
6530 This link is added to `org-stored-links' and can later be inserted
6531 into an org-buffer with \\[org-insert-link].
6533 For some link types, a prefix arg is interpreted:
6534 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6535 For file links, arg negates `org-context-in-file-links'."
6536 (interactive "P")
6537 (org-load-modules-maybe)
6538 (setq org-store-link-plist nil) ; reset
6539 (let (link cpltxt desc description search txt)
6540 (cond
6542 ((run-hook-with-args-until-success 'org-store-link-functions)
6543 (setq link (plist-get org-store-link-plist :link)
6544 desc (or (plist-get org-store-link-plist :description) link)))
6546 ((equal (buffer-name) "*Org Edit Src Example*")
6547 (let (label gc)
6548 (while (or (not label)
6549 (save-excursion
6550 (save-restriction
6551 (widen)
6552 (goto-char (point-min))
6553 (re-search-forward
6554 (regexp-quote (format org-coderef-label-format label))
6555 nil t))))
6556 (when label (message "Label exists already") (sit-for 2))
6557 (setq label (read-string "Code line label: " label)))
6558 (end-of-line 1)
6559 (setq link (format org-coderef-label-format label))
6560 (setq gc (- 79 (length link)))
6561 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6562 (insert link)
6563 (setq link (concat "(" label ")") desc nil)))
6565 ((eq major-mode 'calendar-mode)
6566 (let ((cd (calendar-cursor-to-date)))
6567 (setq link
6568 (format-time-string
6569 (car org-time-stamp-formats)
6570 (apply 'encode-time
6571 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6572 nil nil nil))))
6573 (org-store-link-props :type "calendar" :date cd)))
6575 ((eq major-mode 'w3-mode)
6576 (setq cpltxt (url-view-url t)
6577 link (org-make-link cpltxt))
6578 (org-store-link-props :type "w3" :url (url-view-url t)))
6580 ((eq major-mode 'w3m-mode)
6581 (setq cpltxt (or w3m-current-title w3m-current-url)
6582 link (org-make-link w3m-current-url))
6583 (org-store-link-props :type "w3m" :url (url-view-url t)))
6585 ((setq search (run-hook-with-args-until-success
6586 'org-create-file-search-functions))
6587 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6588 "::" search))
6589 (setq cpltxt (or description link)))
6591 ((eq major-mode 'image-mode)
6592 (setq cpltxt (concat "file:"
6593 (abbreviate-file-name buffer-file-name))
6594 link (org-make-link cpltxt))
6595 (org-store-link-props :type "image" :file buffer-file-name))
6597 ((eq major-mode 'dired-mode)
6598 ;; link to the file in the current line
6599 (setq cpltxt (concat "file:"
6600 (abbreviate-file-name
6601 (expand-file-name
6602 (dired-get-filename nil t))))
6603 link (org-make-link cpltxt)))
6605 ((and buffer-file-name (org-mode-p))
6606 (cond
6607 ((org-in-regexp "<<\\(.*?\\)>>")
6608 (setq cpltxt
6609 (concat "file:"
6610 (abbreviate-file-name buffer-file-name)
6611 "::" (match-string 1))
6612 link (org-make-link cpltxt)))
6613 ((and (featurep 'org-id)
6614 (or (eq org-link-to-org-use-id t)
6615 (and (eq org-link-to-org-use-id 'create-if-interactive)
6616 (interactive-p))
6617 (and org-link-to-org-use-id
6618 (condition-case nil
6619 (org-entry-get nil "ID")
6620 (error nil)))))
6621 ;; We can make a link using the ID.
6622 (setq link (condition-case nil
6623 (prog1 (org-id-store-link)
6624 (setq desc (plist-get org-store-link-plist
6625 :description)))
6626 (error
6627 ;; probably before first headline, link to file only
6628 (concat "file:"
6629 (abbreviate-file-name buffer-file-name))))))
6631 ;; Just link to current headline
6632 (setq cpltxt (concat "file:"
6633 (abbreviate-file-name buffer-file-name)))
6634 ;; Add a context search string
6635 (when (org-xor org-context-in-file-links arg)
6636 (setq txt (cond
6637 ((org-on-heading-p) nil)
6638 ((org-region-active-p)
6639 (buffer-substring (region-beginning) (region-end)))
6640 (t nil)))
6641 (when (or (null txt) (string-match "\\S-" txt))
6642 (setq cpltxt
6643 (concat cpltxt "::"
6644 (condition-case nil
6645 (org-make-org-heading-search-string txt)
6646 (error "")))
6647 desc "NONE")))
6648 (if (string-match "::\\'" cpltxt)
6649 (setq cpltxt (substring cpltxt 0 -2)))
6650 (setq link (org-make-link cpltxt)))))
6652 ((buffer-file-name (buffer-base-buffer))
6653 ;; Just link to this file here.
6654 (setq cpltxt (concat "file:"
6655 (abbreviate-file-name
6656 (buffer-file-name (buffer-base-buffer)))))
6657 ;; Add a context string
6658 (when (org-xor org-context-in-file-links arg)
6659 (setq txt (if (org-region-active-p)
6660 (buffer-substring (region-beginning) (region-end))
6661 (buffer-substring (point-at-bol) (point-at-eol))))
6662 ;; Only use search option if there is some text.
6663 (when (string-match "\\S-" txt)
6664 (setq cpltxt
6665 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6666 desc "NONE")))
6667 (setq link (org-make-link cpltxt)))
6669 ((interactive-p)
6670 (error "Cannot link to a buffer which is not visiting a file"))
6672 (t (setq link nil)))
6674 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6675 (setq link (or link cpltxt)
6676 desc (or desc cpltxt))
6677 (if (equal desc "NONE") (setq desc nil))
6679 (if (and (interactive-p) link)
6680 (progn
6681 (setq org-stored-links
6682 (cons (list link desc) org-stored-links))
6683 (message "Stored: %s" (or desc link)))
6684 (and link (org-make-link-string link desc)))))
6686 (defun org-store-link-props (&rest plist)
6687 "Store link properties, extract names and addresses."
6688 (let (x adr)
6689 (when (setq x (plist-get plist :from))
6690 (setq adr (mail-extract-address-components x))
6691 (setq plist (plist-put plist :fromname (car adr)))
6692 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6693 (when (setq x (plist-get plist :to))
6694 (setq adr (mail-extract-address-components x))
6695 (setq plist (plist-put plist :toname (car adr)))
6696 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6697 (let ((from (plist-get plist :from))
6698 (to (plist-get plist :to)))
6699 (when (and from to org-from-is-user-regexp)
6700 (setq plist
6701 (plist-put plist :fromto
6702 (if (string-match org-from-is-user-regexp from)
6703 (concat "to %t")
6704 (concat "from %f"))))))
6705 (setq org-store-link-plist plist))
6707 (defun org-add-link-props (&rest plist)
6708 "Add these properties to the link property list."
6709 (let (key value)
6710 (while plist
6711 (setq key (pop plist) value (pop plist))
6712 (setq org-store-link-plist
6713 (plist-put org-store-link-plist key value)))))
6715 (defun org-email-link-description (&optional fmt)
6716 "Return the description part of an email link.
6717 This takes information from `org-store-link-plist' and formats it
6718 according to FMT (default from `org-email-link-description-format')."
6719 (setq fmt (or fmt org-email-link-description-format))
6720 (let* ((p org-store-link-plist)
6721 (to (plist-get p :toaddress))
6722 (from (plist-get p :fromaddress))
6723 (table
6724 (list
6725 (cons "%c" (plist-get p :fromto))
6726 (cons "%F" (plist-get p :from))
6727 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6728 (cons "%T" (plist-get p :to))
6729 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6730 (cons "%s" (plist-get p :subject))
6731 (cons "%m" (plist-get p :message-id)))))
6732 (when (string-match "%c" fmt)
6733 ;; Check if the user wrote this message
6734 (if (and org-from-is-user-regexp from to
6735 (save-match-data (string-match org-from-is-user-regexp from)))
6736 (setq fmt (replace-match "to %t" t t fmt))
6737 (setq fmt (replace-match "from %f" t t fmt))))
6738 (org-replace-escapes fmt table)))
6740 (defun org-make-org-heading-search-string (&optional string heading)
6741 "Make search string for STRING or current headline."
6742 (interactive)
6743 (let ((s (or string (org-get-heading))))
6744 (unless (and string (not heading))
6745 ;; We are using a headline, clean up garbage in there.
6746 (if (string-match org-todo-regexp s)
6747 (setq s (replace-match "" t t s)))
6748 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6749 (setq s (replace-match "" t t s)))
6750 (setq s (org-trim s))
6751 (if (string-match (concat "^\\(" org-quote-string "\\|"
6752 org-comment-string "\\)") s)
6753 (setq s (replace-match "" t t s)))
6754 (while (string-match org-ts-regexp s)
6755 (setq s (replace-match "" t t s))))
6756 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6757 (setq s (replace-match " " t t s)))
6758 (or string (setq s (concat "*" s))) ; Add * for headlines
6759 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6761 (defun org-make-link (&rest strings)
6762 "Concatenate STRINGS."
6763 (apply 'concat strings))
6765 (defun org-make-link-string (link &optional description)
6766 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6767 (unless (string-match "\\S-" link)
6768 (error "Empty link"))
6769 (when (stringp description)
6770 ;; Remove brackets from the description, they are fatal.
6771 (while (string-match "\\[" description)
6772 (setq description (replace-match "{" t t description)))
6773 (while (string-match "\\]" description)
6774 (setq description (replace-match "}" t t description))))
6775 (when (equal (org-link-escape link) description)
6776 ;; No description needed, it is identical
6777 (setq description nil))
6778 (when (and (not description)
6779 (not (equal link (org-link-escape link))))
6780 (setq description (org-extract-attributes link)))
6781 (concat "[[" (org-link-escape link) "]"
6782 (if description (concat "[" description "]") "")
6783 "]"))
6785 (defconst org-link-escape-chars
6786 '((?\ . "%20")
6787 (?\[ . "%5B")
6788 (?\] . "%5D")
6789 (?\340 . "%E0") ; `a
6790 (?\342 . "%E2") ; ^a
6791 (?\347 . "%E7") ; ,c
6792 (?\350 . "%E8") ; `e
6793 (?\351 . "%E9") ; 'e
6794 (?\352 . "%EA") ; ^e
6795 (?\356 . "%EE") ; ^i
6796 (?\364 . "%F4") ; ^o
6797 (?\371 . "%F9") ; `u
6798 (?\373 . "%FB") ; ^u
6799 (?\; . "%3B")
6800 (?? . "%3F")
6801 (?= . "%3D")
6802 (?+ . "%2B")
6804 "Association list of escapes for some characters problematic in links.
6805 This is the list that is used for internal purposes.")
6807 (defconst org-link-escape-chars-browser
6808 '((?\ . "%20")) ; 32 for the SPC char
6809 "Association list of escapes for some characters problematic in links.
6810 This is the list that is used before handing over to the browser.")
6812 (defun org-link-escape (text &optional table)
6813 "Escape characters in TEXT that are problematic for links."
6814 (setq table (or table org-link-escape-chars))
6815 (when text
6816 (let ((re (mapconcat (lambda (x) (regexp-quote
6817 (char-to-string (car x))))
6818 table "\\|")))
6819 (while (string-match re text)
6820 (setq text
6821 (replace-match
6822 (cdr (assoc (string-to-char (match-string 0 text))
6823 table))
6824 t t text)))
6825 text)))
6827 (defun org-link-unescape (text &optional table)
6828 "Reverse the action of `org-link-escape'."
6829 (setq table (or table org-link-escape-chars))
6830 (when text
6831 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6832 table "\\|")))
6833 (while (string-match re text)
6834 (setq text
6835 (replace-match
6836 (char-to-string (car (rassoc (match-string 0 text) table)))
6837 t t text)))
6838 text)))
6840 (defun org-xor (a b)
6841 "Exclusive or."
6842 (if a (not b) b))
6844 (defun org-fixup-message-id-for-http (s)
6845 "Replace special characters in a message id, so it can be used in an http query."
6846 (while (string-match "<" s)
6847 (setq s (replace-match "%3C" t t s)))
6848 (while (string-match ">" s)
6849 (setq s (replace-match "%3E" t t s)))
6850 (while (string-match "@" s)
6851 (setq s (replace-match "%40" t t s)))
6854 ;;;###autoload
6855 (defun org-insert-link-global ()
6856 "Insert a link like Org-mode does.
6857 This command can be called in any mode to insert a link in Org-mode syntax."
6858 (interactive)
6859 (org-load-modules-maybe)
6860 (org-run-like-in-org-mode 'org-insert-link))
6862 (defun org-insert-link (&optional complete-file link-location)
6863 "Insert a link. At the prompt, enter the link.
6865 Completion can be used to insert any of the link protocol prefixes like
6866 http or ftp in use.
6868 The history can be used to select a link previously stored with
6869 `org-store-link'. When the empty string is entered (i.e. if you just
6870 press RET at the prompt), the link defaults to the most recently
6871 stored link. As SPC triggers completion in the minibuffer, you need to
6872 use M-SPC or C-q SPC to force the insertion of a space character.
6874 You will also be prompted for a description, and if one is given, it will
6875 be displayed in the buffer instead of the link.
6877 If there is already a link at point, this command will allow you to edit link
6878 and description parts.
6880 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6881 be selected using completion. The path to the file will be relative to the
6882 current directory if the file is in the current directory or a subdirectory.
6883 Otherwise, the link will be the absolute path as completed in the minibuffer
6884 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6885 option `org-link-file-path-type'.
6887 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6888 the current directory or below.
6890 With three \\[universal-argument] prefixes, negate the meaning of
6891 `org-keep-stored-link-after-insertion'.
6893 If `org-make-link-description-function' is non-nil, this function will be
6894 called with the link target, and the result will be the default
6895 link description.
6897 If the LINK-LOCATION parameter is non-nil, this value will be
6898 used as the link location instead of reading one interactively."
6899 (interactive "P")
6900 (let* ((wcf (current-window-configuration))
6901 (region (if (org-region-active-p)
6902 (buffer-substring (region-beginning) (region-end))))
6903 (remove (and region (list (region-beginning) (region-end))))
6904 (desc region)
6905 tmphist ; byte-compile incorrectly complains about this
6906 (link link-location)
6907 entry file)
6908 (cond
6909 (link-location) ; specified by arg, just use it.
6910 ((org-in-regexp org-bracket-link-regexp 1)
6911 ;; We do have a link at point, and we are going to edit it.
6912 (setq remove (list (match-beginning 0) (match-end 0)))
6913 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6914 (setq link (read-string "Link: "
6915 (org-link-unescape
6916 (org-match-string-no-properties 1)))))
6917 ((or (org-in-regexp org-angle-link-re)
6918 (org-in-regexp org-plain-link-re))
6919 ;; Convert to bracket link
6920 (setq remove (list (match-beginning 0) (match-end 0))
6921 link (read-string "Link: "
6922 (org-remove-angle-brackets (match-string 0)))))
6923 ((member complete-file '((4) (16)))
6924 ;; Completing read for file names.
6925 (setq file (read-file-name "File: "))
6926 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6927 (pwd1 (file-name-as-directory (abbreviate-file-name
6928 (expand-file-name ".")))))
6929 (cond
6930 ((equal complete-file '(16))
6931 (setq link (org-make-link
6932 "file:"
6933 (abbreviate-file-name (expand-file-name file)))))
6934 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6935 (setq link (org-make-link "file:" (match-string 1 file))))
6936 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6937 (expand-file-name file))
6938 (setq link (org-make-link
6939 "file:" (match-string 1 (expand-file-name file)))))
6940 (t (setq link (org-make-link "file:" file))))))
6942 ;; Read link, with completion for stored links.
6943 (with-output-to-temp-buffer "*Org Links*"
6944 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6945 (when org-stored-links
6946 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6947 (princ (mapconcat
6948 (lambda (x)
6949 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6950 (reverse org-stored-links) "\n"))))
6951 (let ((cw (selected-window)))
6952 (select-window (get-buffer-window "*Org Links*"))
6953 (setq truncate-lines t)
6954 (org-fit-window-to-buffer)
6955 (select-window cw))
6956 ;; Fake a link history, containing the stored links.
6957 (setq tmphist (append (mapcar 'car org-stored-links)
6958 org-insert-link-history))
6959 (unwind-protect
6960 (setq link
6961 (let ((org-completion-use-ido nil))
6962 (org-completing-read
6963 "Link: "
6964 (append
6965 (mapcar (lambda (x) (list (concat (car x) ":")))
6966 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6967 (mapcar (lambda (x) (list (concat x ":")))
6968 org-link-types))
6969 nil nil nil
6970 'tmphist
6971 (or (car (car org-stored-links))))))
6972 (set-window-configuration wcf)
6973 (kill-buffer "*Org Links*"))
6974 (setq entry (assoc link org-stored-links))
6975 (or entry (push link org-insert-link-history))
6976 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6977 (not org-keep-stored-link-after-insertion))
6978 (setq org-stored-links (delq (assoc link org-stored-links)
6979 org-stored-links)))
6980 (setq desc (or desc (nth 1 entry)))))
6982 (if (string-match org-plain-link-re link)
6983 ;; URL-like link, normalize the use of angular brackets.
6984 (setq link (org-make-link (org-remove-angle-brackets link))))
6986 ;; Check if we are linking to the current file with a search option
6987 ;; If yes, simplify the link by using only the search option.
6988 (when (and buffer-file-name
6989 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6990 (let* ((path (match-string 1 link))
6991 (case-fold-search nil)
6992 (search (match-string 2 link)))
6993 (save-match-data
6994 (if (equal (file-truename buffer-file-name) (file-truename path))
6995 ;; We are linking to this same file, with a search option
6996 (setq link search)))))
6998 ;; Check if we can/should use a relative path. If yes, simplify the link
6999 (when (string-match "^file:\\(.*\\)" link)
7000 (let* ((path (match-string 1 link))
7001 (origpath path)
7002 (case-fold-search nil))
7003 (cond
7004 ((or (eq org-link-file-path-type 'absolute)
7005 (equal complete-file '(16)))
7006 (setq path (abbreviate-file-name (expand-file-name path))))
7007 ((eq org-link-file-path-type 'noabbrev)
7008 (setq path (expand-file-name path)))
7009 ((eq org-link-file-path-type 'relative)
7010 (setq path (file-relative-name path)))
7012 (save-match-data
7013 (if (string-match (concat "^" (regexp-quote
7014 (file-name-as-directory
7015 (expand-file-name "."))))
7016 (expand-file-name path))
7017 ;; We are linking a file with relative path name.
7018 (setq path (substring (expand-file-name path)
7019 (match-end 0)))
7020 (setq path (abbreviate-file-name (expand-file-name path)))))))
7021 (setq link (concat "file:" path))
7022 (if (equal desc origpath)
7023 (setq desc path))))
7025 (if org-make-link-description-function
7026 (setq desc (funcall org-make-link-description-function link desc)))
7028 (setq desc (read-string "Description: " desc))
7029 (unless (string-match "\\S-" desc) (setq desc nil))
7030 (if remove (apply 'delete-region remove))
7031 (insert (org-make-link-string link desc))))
7033 (defun org-completing-read (&rest args)
7034 "Completing-read with SPACE being a normal character."
7035 (let ((minibuffer-local-completion-map
7036 (copy-keymap minibuffer-local-completion-map)))
7037 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7038 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7039 (apply 'org-ido-completing-read args)))
7041 (defun org-ido-completing-read (&rest args)
7042 "Completing-read using `ido-mode' speedups if available"
7043 (if (and org-completion-use-ido
7044 (fboundp 'ido-completing-read)
7045 (boundp 'ido-mode) ido-mode
7046 (listp (second args)))
7047 (apply 'ido-completing-read (concat (car args)) (cdr args))
7048 (apply 'completing-read args)))
7050 (defun org-extract-attributes (s)
7051 "Extract the attributes cookie from a string and set as text property."
7052 (let (a attr (start 0) key value)
7053 (save-match-data
7054 (when (string-match "{{\\([^}]+\\)}}$" s)
7055 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7056 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7057 (setq key (match-string 1 a) value (match-string 2 a)
7058 start (match-end 0)
7059 attr (plist-put attr (intern key) value))))
7060 (org-add-props s nil 'org-attr attr))
7063 (defun org-attributes-to-string (plist)
7064 "Format a property list into an HTML attribute list."
7065 (let ((s "") key value)
7066 (while plist
7067 (setq key (pop plist) value (pop plist))
7068 (and value
7069 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7072 ;;; Opening/following a link
7074 (defvar org-link-search-failed nil)
7076 (defun org-next-link ()
7077 "Move forward to the next link.
7078 If the link is in hidden text, expose it."
7079 (interactive)
7080 (when (and org-link-search-failed (eq this-command last-command))
7081 (goto-char (point-min))
7082 (message "Link search wrapped back to beginning of buffer"))
7083 (setq org-link-search-failed nil)
7084 (let* ((pos (point))
7085 (ct (org-context))
7086 (a (assoc :link ct)))
7087 (if a (goto-char (nth 2 a)))
7088 (if (re-search-forward org-any-link-re nil t)
7089 (progn
7090 (goto-char (match-beginning 0))
7091 (if (org-invisible-p) (org-show-context)))
7092 (goto-char pos)
7093 (setq org-link-search-failed t)
7094 (error "No further link found"))))
7096 (defun org-previous-link ()
7097 "Move backward to the previous link.
7098 If the link is in hidden text, expose it."
7099 (interactive)
7100 (when (and org-link-search-failed (eq this-command last-command))
7101 (goto-char (point-max))
7102 (message "Link search wrapped back to end of buffer"))
7103 (setq org-link-search-failed nil)
7104 (let* ((pos (point))
7105 (ct (org-context))
7106 (a (assoc :link ct)))
7107 (if a (goto-char (nth 1 a)))
7108 (if (re-search-backward org-any-link-re nil t)
7109 (progn
7110 (goto-char (match-beginning 0))
7111 (if (org-invisible-p) (org-show-context)))
7112 (goto-char pos)
7113 (setq org-link-search-failed t)
7114 (error "No further link found"))))
7116 (defun org-translate-link (s)
7117 "Translate a link string if a translation function has been defined."
7118 (if (and org-link-translation-function
7119 (fboundp org-link-translation-function)
7120 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7121 (progn
7122 (setq s (funcall org-link-translation-function
7123 (match-string 1) (match-string 2)))
7124 (concat (car s) ":" (cdr s)))
7127 (defun org-translate-link-from-planner (type path)
7128 "Translate a link from Emacs Planner syntax so that Org can follow it.
7129 This is still an experimental function, your mileage may vary."
7130 (cond
7131 ((member type '("http" "https" "news" "ftp"))
7132 ;; standard Internet links are the same.
7133 nil)
7134 ((and (equal type "irc") (string-match "^//" path))
7135 ;; Planner has two / at the beginning of an irc link, we have 1.
7136 ;; We should have zero, actually....
7137 (setq path (substring path 1)))
7138 ((and (equal type "lisp") (string-match "^/" path))
7139 ;; Planner has a slash, we do not.
7140 (setq type "elisp" path (substring path 1)))
7141 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7142 ;; A typical message link. Planner has the id after the fina slash,
7143 ;; we separate it with a hash mark
7144 (setq path (concat (match-string 1 path) "#"
7145 (org-remove-angle-brackets (match-string 2 path)))))
7147 (cons type path))
7149 (defun org-find-file-at-mouse (ev)
7150 "Open file link or URL at mouse."
7151 (interactive "e")
7152 (mouse-set-point ev)
7153 (org-open-at-point 'in-emacs))
7155 (defun org-open-at-mouse (ev)
7156 "Open file link or URL at mouse."
7157 (interactive "e")
7158 (mouse-set-point ev)
7159 (if (eq major-mode 'org-agenda-mode)
7160 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7161 (org-open-at-point))
7163 (defvar org-window-config-before-follow-link nil
7164 "The window configuration before following a link.
7165 This is saved in case the need arises to restore it.")
7167 (defvar org-open-link-marker (make-marker)
7168 "Marker pointing to the location where `org-open-at-point; was called.")
7170 ;;;###autoload
7171 (defun org-open-at-point-global ()
7172 "Follow a link like Org-mode does.
7173 This command can be called in any mode to follow a link that has
7174 Org-mode syntax."
7175 (interactive)
7176 (org-run-like-in-org-mode 'org-open-at-point))
7178 ;;;###autoload
7179 (defun org-open-link-from-string (s &optional arg)
7180 "Open a link in the string S, as if it was in Org-mode."
7181 (interactive "sLink: \nP")
7182 (with-temp-buffer
7183 (let ((org-inhibit-startup t))
7184 (org-mode)
7185 (insert s)
7186 (goto-char (point-min))
7187 (org-open-at-point arg))))
7189 (defun org-open-at-point (&optional in-emacs)
7190 "Open link at or after point.
7191 If there is no link at point, this function will search forward up to
7192 the end of the current subtree.
7193 Normally, files will be opened by an appropriate application. If the
7194 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7195 With a double prefix argument, try to open outside of Emacs, in the
7196 application the system uses for this file type."
7197 (interactive "P")
7198 (org-load-modules-maybe)
7199 (move-marker org-open-link-marker (point))
7200 (setq org-window-config-before-follow-link (current-window-configuration))
7201 (org-remove-occur-highlights nil nil t)
7202 (cond
7203 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7204 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7205 (org-footnote-action))
7207 (let (type path link line search (pos (point)))
7208 (catch 'match
7209 (save-excursion
7210 (skip-chars-forward "^]\n\r")
7211 (when (org-in-regexp org-bracket-link-regexp)
7212 (setq link (org-extract-attributes
7213 (org-link-unescape (org-match-string-no-properties 1))))
7214 (while (string-match " *\n *" link)
7215 (setq link (replace-match " " t t link)))
7216 (setq link (org-link-expand-abbrev link))
7217 (cond
7218 ((or (file-name-absolute-p link)
7219 (string-match "^\\.\\.?/" link))
7220 (setq type "file" path link))
7221 ((string-match org-link-re-with-space3 link)
7222 (setq type (match-string 1 link) path (match-string 2 link)))
7223 (t (setq type "thisfile" path link)))
7224 (throw 'match t)))
7226 (when (get-text-property (point) 'org-linked-text)
7227 (setq type "thisfile"
7228 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7229 (1+ (point)) (point))
7230 path (buffer-substring
7231 (previous-single-property-change pos 'org-linked-text)
7232 (next-single-property-change pos 'org-linked-text)))
7233 (throw 'match t))
7235 (save-excursion
7236 (when (or (org-in-regexp org-angle-link-re)
7237 (org-in-regexp org-plain-link-re))
7238 (setq type (match-string 1) path (match-string 2))
7239 (throw 'match t)))
7240 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7241 (setq type "tree-match"
7242 path (match-string 1))
7243 (throw 'match t))
7244 (save-excursion
7245 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7246 (setq type "tags"
7247 path (match-string 1))
7248 (while (string-match ":" path)
7249 (setq path (replace-match "+" t t path)))
7250 (throw 'match t))))
7251 (unless path
7252 (error "No link found"))
7253 ;; Remove any trailing spaces in path
7254 (if (string-match " +\\'" path)
7255 (setq path (replace-match "" t t path)))
7256 (if (and org-link-translation-function
7257 (fboundp org-link-translation-function))
7258 ;; Check if we need to translate the link
7259 (let ((tmp (funcall org-link-translation-function type path)))
7260 (setq type (car tmp) path (cdr tmp))))
7262 (cond
7264 ((assoc type org-link-protocols)
7265 (funcall (nth 1 (assoc type org-link-protocols)) path))
7267 ((equal type "mailto")
7268 (let ((cmd (car org-link-mailto-program))
7269 (args (cdr org-link-mailto-program)) args1
7270 (address path) (subject "") a)
7271 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7272 (setq address (match-string 1 path)
7273 subject (org-link-escape (match-string 2 path))))
7274 (while args
7275 (cond
7276 ((not (stringp (car args))) (push (pop args) args1))
7277 (t (setq a (pop args))
7278 (if (string-match "%a" a)
7279 (setq a (replace-match address t t a)))
7280 (if (string-match "%s" a)
7281 (setq a (replace-match subject t t a)))
7282 (push a args1))))
7283 (apply cmd (nreverse args1))))
7285 ((member type '("http" "https" "ftp" "news"))
7286 (browse-url (concat type ":" (org-link-escape
7287 path org-link-escape-chars-browser))))
7289 ((member type '("message"))
7290 (browse-url (concat type ":" path)))
7292 ((string= type "tags")
7293 (org-tags-view in-emacs path))
7294 ((string= type "thisfile")
7295 (if in-emacs
7296 (switch-to-buffer-other-window
7297 (org-get-buffer-for-internal-link (current-buffer)))
7298 (org-mark-ring-push))
7299 (let ((cmd `(org-link-search
7300 ,path
7301 ,(cond ((equal in-emacs '(4)) 'occur)
7302 ((equal in-emacs '(16)) 'org-occur)
7303 (t nil))
7304 ,pos)))
7305 (condition-case nil (eval cmd)
7306 (error (progn (widen) (eval cmd))))))
7308 ((string= type "tree-match")
7309 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7311 ((string= type "file")
7312 (if (string-match "::\\([0-9]+\\)\\'" path)
7313 (setq line (string-to-number (match-string 1 path))
7314 path (substring path 0 (match-beginning 0)))
7315 (if (string-match "::\\(.+\\)\\'" path)
7316 (setq search (match-string 1 path)
7317 path (substring path 0 (match-beginning 0)))))
7318 (if (string-match "[*?{]" (file-name-nondirectory path))
7319 (dired path)
7320 (org-open-file path in-emacs line search)))
7322 ((string= type "news")
7323 (require 'org-gnus)
7324 (org-gnus-follow-link path))
7326 ((string= type "shell")
7327 (let ((cmd path))
7328 (if (or (not org-confirm-shell-link-function)
7329 (funcall org-confirm-shell-link-function
7330 (format "Execute \"%s\" in shell? "
7331 (org-add-props cmd nil
7332 'face 'org-warning))))
7333 (progn
7334 (message "Executing %s" cmd)
7335 (shell-command cmd))
7336 (error "Abort"))))
7338 ((string= type "elisp")
7339 (let ((cmd path))
7340 (if (or (not org-confirm-elisp-link-function)
7341 (funcall org-confirm-elisp-link-function
7342 (format "Execute \"%s\" as elisp? "
7343 (org-add-props cmd nil
7344 'face 'org-warning))))
7345 (message "%s => %s" cmd
7346 (if (equal (string-to-char cmd) ?\()
7347 (eval (read cmd))
7348 (call-interactively (read cmd))))
7349 (error "Abort"))))
7352 (browse-url-at-point))))))
7353 (move-marker org-open-link-marker nil)
7354 (run-hook-with-args 'org-follow-link-hook))
7356 ;;;; Time estimates
7358 (defun org-get-effort (&optional pom)
7359 "Get the effort estimate for the current entry."
7360 (org-entry-get pom org-effort-property))
7362 ;;; File search
7364 (defvar org-create-file-search-functions nil
7365 "List of functions to construct the right search string for a file link.
7366 These functions are called in turn with point at the location to
7367 which the link should point.
7369 A function in the hook should first test if it would like to
7370 handle this file type, for example by checking the major-mode or
7371 the file extension. If it decides not to handle this file, it
7372 should just return nil to give other functions a chance. If it
7373 does handle the file, it must return the search string to be used
7374 when following the link. The search string will be part of the
7375 file link, given after a double colon, and `org-open-at-point'
7376 will automatically search for it. If special measures must be
7377 taken to make the search successful, another function should be
7378 added to the companion hook `org-execute-file-search-functions',
7379 which see.
7381 A function in this hook may also use `setq' to set the variable
7382 `description' to provide a suggestion for the descriptive text to
7383 be used for this link when it gets inserted into an Org-mode
7384 buffer with \\[org-insert-link].")
7386 (defvar org-execute-file-search-functions nil
7387 "List of functions to execute a file search triggered by a link.
7389 Functions added to this hook must accept a single argument, the
7390 search string that was part of the file link, the part after the
7391 double colon. The function must first check if it would like to
7392 handle this search, for example by checking the major-mode or the
7393 file extension. If it decides not to handle this search, it
7394 should just return nil to give other functions a chance. If it
7395 does handle the search, it must return a non-nil value to keep
7396 other functions from trying.
7398 Each function can access the current prefix argument through the
7399 variable `current-prefix-argument'. Note that a single prefix is
7400 used to force opening a link in Emacs, so it may be good to only
7401 use a numeric or double prefix to guide the search function.
7403 In case this is needed, a function in this hook can also restore
7404 the window configuration before `org-open-at-point' was called using:
7406 (set-window-configuration org-window-config-before-follow-link)")
7408 (defun org-link-search (s &optional type avoid-pos)
7409 "Search for a link search option.
7410 If S is surrounded by forward slashes, it is interpreted as a
7411 regular expression. In org-mode files, this will create an `org-occur'
7412 sparse tree. In ordinary files, `occur' will be used to list matches.
7413 If the current buffer is in `dired-mode', grep will be used to search
7414 in all files. If AVOID-POS is given, ignore matches near that position."
7415 (let ((case-fold-search t)
7416 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7417 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7418 (append '(("") (" ") ("\t") ("\n"))
7419 org-emphasis-alist)
7420 "\\|") "\\)"))
7421 (pos (point))
7422 (pre nil) (post nil)
7423 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7424 (cond
7425 ;; First check if there are any special
7426 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7427 ;; Now try the builtin stuff
7428 ((save-excursion
7429 (goto-char (point-min))
7430 (and
7431 (re-search-forward
7432 (concat "<<" (regexp-quote s0) ">>") nil t)
7433 (setq type 'dedicated
7434 pos (match-beginning 0))))
7435 ;; There is an exact target for this
7436 (goto-char pos))
7437 ((and (string-match "^(\\(.*\\))$" s0)
7438 (save-excursion
7439 (goto-char (point-min))
7440 (and
7441 (re-search-forward
7442 (concat "[^[]" (regexp-quote
7443 (format org-coderef-label-format
7444 (match-string 1 s0))))
7445 nil t)
7446 (setq type 'dedicated
7447 pos (1+ (match-beginning 0))))))
7448 ;; There is a coderef target for this
7449 (goto-char pos))
7450 ((string-match "^/\\(.*\\)/$" s)
7451 ;; A regular expression
7452 (cond
7453 ((org-mode-p)
7454 (org-occur (match-string 1 s)))
7455 ;;((eq major-mode 'dired-mode)
7456 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7457 (t (org-do-occur (match-string 1 s)))))
7459 ;; A normal search strings
7460 (when (equal (string-to-char s) ?*)
7461 ;; Anchor on headlines, post may include tags.
7462 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7463 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7464 s (substring s 1)))
7465 (remove-text-properties
7466 0 (length s)
7467 '(face nil mouse-face nil keymap nil fontified nil) s)
7468 ;; Make a series of regular expressions to find a match
7469 (setq words (org-split-string s "[ \n\r\t]+")
7471 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7472 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7473 "\\)" markers)
7474 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7475 re2a (concat "[ \t\r\n]" re2a_)
7476 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7477 re4 (concat "[^a-zA-Z_]" re4_)
7479 re1 (concat pre re2 post)
7480 re3 (concat pre (if pre re4_ re4) post)
7481 re5 (concat pre ".*" re4)
7482 re2 (concat pre re2)
7483 re2a (concat pre (if pre re2a_ re2a))
7484 re4 (concat pre (if pre re4_ re4))
7485 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7486 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7487 re5 "\\)"
7489 (cond
7490 ((eq type 'org-occur) (org-occur reall))
7491 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7492 (t (goto-char (point-min))
7493 (setq type 'fuzzy)
7494 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7495 (org-search-not-self 1 re1 nil t)
7496 (org-search-not-self 1 re2 nil t)
7497 (org-search-not-self 1 re2a nil t)
7498 (org-search-not-self 1 re3 nil t)
7499 (org-search-not-self 1 re4 nil t)
7500 (org-search-not-self 1 re5 nil t)
7502 (goto-char (match-beginning 1))
7503 (goto-char pos)
7504 (error "No match")))))
7506 ;; Normal string-search
7507 (goto-char (point-min))
7508 (if (search-forward s nil t)
7509 (goto-char (match-beginning 0))
7510 (error "No match"))))
7511 (and (org-mode-p) (org-show-context 'link-search))
7512 type))
7514 (defun org-search-not-self (group &rest args)
7515 "Execute `re-search-forward', but only accept matches that do not
7516 enclose the position of `org-open-link-marker'."
7517 (let ((m org-open-link-marker))
7518 (catch 'exit
7519 (while (apply 're-search-forward args)
7520 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7521 (goto-char (match-end group))
7522 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7523 (> (match-beginning 0) (marker-position m))
7524 (< (match-end 0) (marker-position m)))
7525 (save-match-data
7526 (or (not (org-in-regexp
7527 org-bracket-link-analytic-regexp 1))
7528 (not (match-end 4)) ; no description
7529 (and (<= (match-beginning 4) (point))
7530 (>= (match-end 4) (point))))))
7531 (throw 'exit (point))))))))
7533 (defun org-get-buffer-for-internal-link (buffer)
7534 "Return a buffer to be used for displaying the link target of internal links."
7535 (cond
7536 ((not org-display-internal-link-with-indirect-buffer)
7537 buffer)
7538 ((string-match "(Clone)$" (buffer-name buffer))
7539 (message "Buffer is already a clone, not making another one")
7540 ;; we also do not modify visibility in this case
7541 buffer)
7542 (t ; make a new indirect buffer for displaying the link
7543 (let* ((bn (buffer-name buffer))
7544 (ibn (concat bn "(Clone)"))
7545 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7546 (with-current-buffer ib (org-overview))
7547 ib))))
7549 (defun org-do-occur (regexp &optional cleanup)
7550 "Call the Emacs command `occur'.
7551 If CLEANUP is non-nil, remove the printout of the regular expression
7552 in the *Occur* buffer. This is useful if the regex is long and not useful
7553 to read."
7554 (occur regexp)
7555 (when cleanup
7556 (let ((cwin (selected-window)) win beg end)
7557 (when (setq win (get-buffer-window "*Occur*"))
7558 (select-window win))
7559 (goto-char (point-min))
7560 (when (re-search-forward "match[a-z]+" nil t)
7561 (setq beg (match-end 0))
7562 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7563 (setq end (1- (match-beginning 0)))))
7564 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7565 (goto-char (point-min))
7566 (select-window cwin))))
7568 ;;; The mark ring for links jumps
7570 (defvar org-mark-ring nil
7571 "Mark ring for positions before jumps in Org-mode.")
7572 (defvar org-mark-ring-last-goto nil
7573 "Last position in the mark ring used to go back.")
7574 ;; Fill and close the ring
7575 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7576 (loop for i from 1 to org-mark-ring-length do
7577 (push (make-marker) org-mark-ring))
7578 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7579 org-mark-ring)
7581 (defun org-mark-ring-push (&optional pos buffer)
7582 "Put the current position or POS into the mark ring and rotate it."
7583 (interactive)
7584 (setq pos (or pos (point)))
7585 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7586 (move-marker (car org-mark-ring)
7587 (or pos (point))
7588 (or buffer (current-buffer)))
7589 (message "%s"
7590 (substitute-command-keys
7591 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7593 (defun org-mark-ring-goto (&optional n)
7594 "Jump to the previous position in the mark ring.
7595 With prefix arg N, jump back that many stored positions. When
7596 called several times in succession, walk through the entire ring.
7597 Org-mode commands jumping to a different position in the current file,
7598 or to another Org-mode file, automatically push the old position
7599 onto the ring."
7600 (interactive "p")
7601 (let (p m)
7602 (if (eq last-command this-command)
7603 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7604 (setq p org-mark-ring))
7605 (setq org-mark-ring-last-goto p)
7606 (setq m (car p))
7607 (switch-to-buffer (marker-buffer m))
7608 (goto-char m)
7609 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7611 (defun org-remove-angle-brackets (s)
7612 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7613 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7615 (defun org-add-angle-brackets (s)
7616 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7617 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7619 (defun org-remove-double-quotes (s)
7620 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7621 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7624 ;;; Following specific links
7626 (defun org-follow-timestamp-link ()
7627 (cond
7628 ((org-at-date-range-p t)
7629 (let ((org-agenda-start-on-weekday)
7630 (t1 (match-string 1))
7631 (t2 (match-string 2)))
7632 (setq t1 (time-to-days (org-time-string-to-time t1))
7633 t2 (time-to-days (org-time-string-to-time t2)))
7634 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7635 ((org-at-timestamp-p t)
7636 (org-agenda-list nil (time-to-days (org-time-string-to-time
7637 (substring (match-string 1) 0 10)))
7639 (t (error "This should not happen"))))
7642 ;;; Following file links
7643 (defvar org-wait nil)
7644 (defun org-open-file (path &optional in-emacs line search)
7645 "Open the file at PATH.
7646 First, this expands any special file name abbreviations. Then the
7647 configuration variable `org-file-apps' is checked if it contains an
7648 entry for this file type, and if yes, the corresponding command is launched.
7650 If no application is found, Emacs simply visits the file.
7652 With optional prefix argument IN-EMACS, Emacs will visit the file.
7653 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7654 and o use an external application to visit the file.
7656 Optional LINE specifies a line to go to, optional SEARCH a string to
7657 search for. If LINE or SEARCH is given, the file will always be
7658 opened in Emacs.
7659 If the file does not exist, an error is thrown."
7660 (setq in-emacs (or in-emacs line search))
7661 (let* ((file (if (equal path "")
7662 buffer-file-name
7663 (substitute-in-file-name (expand-file-name path))))
7664 (apps (append org-file-apps (org-default-apps)))
7665 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7666 (dirp (if remp nil (file-directory-p file)))
7667 (file (if (and dirp org-open-directory-means-index-dot-org)
7668 (concat (file-name-as-directory file) "index.org")
7669 file))
7670 (a-m-a-p (assq 'auto-mode apps))
7671 (dfile (downcase file))
7672 (old-buffer (current-buffer))
7673 (old-pos (point))
7674 (old-mode major-mode)
7675 ext cmd)
7676 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7677 (setq ext (match-string 1 dfile))
7678 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7679 (setq ext (match-string 1 dfile))))
7680 (cond
7681 ((equal in-emacs '(16))
7682 (setq cmd (cdr (assoc 'system apps))))
7683 (in-emacs (setq cmd 'emacs))
7685 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7686 (and dirp (cdr (assoc 'directory apps)))
7687 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7688 'string-match)
7689 (cdr (assoc ext apps))
7690 (cdr (assoc t apps))))))
7691 (when (eq cmd 'system)
7692 (setq cmd (cdr (assoc 'system apps))))
7693 (when (eq cmd 'default)
7694 (setq cmd (cdr (assoc t apps))))
7695 (when (eq cmd 'mailcap)
7696 (require 'mailcap)
7697 (mailcap-parse-mailcaps)
7698 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7699 (command (mailcap-mime-info mime-type)))
7700 (if (stringp command)
7701 (setq cmd command)
7702 (setq cmd 'emacs))))
7703 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7704 (not (file-exists-p file))
7705 (not org-open-non-existing-files))
7706 (error "No such file: %s" file))
7707 (cond
7708 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7709 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7710 (while (string-match "['\"]%s['\"]" cmd)
7711 (setq cmd (replace-match "%s" t t cmd)))
7712 (while (string-match "%s" cmd)
7713 (setq cmd (replace-match
7714 (save-match-data
7715 (shell-quote-argument
7716 (convert-standard-filename file)))
7717 t t cmd)))
7718 (save-window-excursion
7719 (start-process-shell-command cmd nil cmd)
7720 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7722 ((or (stringp cmd)
7723 (eq cmd 'emacs))
7724 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7725 (widen)
7726 (if line (goto-line line)
7727 (if search (org-link-search search))))
7728 ((consp cmd)
7729 (let ((file (convert-standard-filename file)))
7730 (eval cmd)))
7731 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7732 (and (org-mode-p) (eq old-mode 'org-mode)
7733 (or (not (equal old-buffer (current-buffer)))
7734 (not (equal old-pos (point))))
7735 (org-mark-ring-push old-pos old-buffer))))
7737 (defun org-default-apps ()
7738 "Return the default applications for this operating system."
7739 (cond
7740 ((eq system-type 'darwin)
7741 org-file-apps-defaults-macosx)
7742 ((eq system-type 'windows-nt)
7743 org-file-apps-defaults-windowsnt)
7744 (t org-file-apps-defaults-gnu)))
7746 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7747 "Convert extensions to regular expressions in the cars of LIST.
7748 Also, weed out any non-string entries, because the return value is used
7749 only for regexp matching.
7750 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7751 point to the symbol `emacs', indicating that the file should
7752 be opened in Emacs."
7753 (append
7754 (delq nil
7755 (mapcar (lambda (x)
7756 (if (not (stringp (car x)))
7758 (if (string-match "\\W" (car x))
7760 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7761 list))
7762 (if add-auto-mode
7763 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7765 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7766 (defun org-file-remote-p (file)
7767 "Test whether FILE specifies a location on a remote system.
7768 Return non-nil if the location is indeed remote.
7770 For example, the filename \"/user@host:/foo\" specifies a location
7771 on the system \"/user@host:\"."
7772 (cond ((fboundp 'file-remote-p)
7773 (file-remote-p file))
7774 ((fboundp 'tramp-handle-file-remote-p)
7775 (tramp-handle-file-remote-p file))
7776 ((and (boundp 'ange-ftp-name-format)
7777 (string-match (car ange-ftp-name-format) file))
7779 (t nil)))
7782 ;;;; Refiling
7784 (defun org-get-org-file ()
7785 "Read a filename, with default directory `org-directory'."
7786 (let ((default (or org-default-notes-file remember-data-file)))
7787 (read-file-name (format "File name [%s]: " default)
7788 (file-name-as-directory org-directory)
7789 default)))
7791 (defun org-notes-order-reversed-p ()
7792 "Check if the current file should receive notes in reversed order."
7793 (cond
7794 ((not org-reverse-note-order) nil)
7795 ((eq t org-reverse-note-order) t)
7796 ((not (listp org-reverse-note-order)) nil)
7797 (t (catch 'exit
7798 (let ((all org-reverse-note-order)
7799 entry)
7800 (while (setq entry (pop all))
7801 (if (string-match (car entry) buffer-file-name)
7802 (throw 'exit (cdr entry))))
7803 nil)))))
7805 (defvar org-refile-target-table nil
7806 "The list of refile targets, created by `org-refile'.")
7808 (defvar org-agenda-new-buffers nil
7809 "Buffers created to visit agenda files.")
7811 (defun org-get-refile-targets (&optional default-buffer)
7812 "Produce a table with refile targets."
7813 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7814 targets txt re files f desc descre fast-path-p level)
7815 (message "Getting targets...")
7816 (with-current-buffer (or default-buffer (current-buffer))
7817 (while (setq entry (pop entries))
7818 (setq files (car entry) desc (cdr entry))
7819 (setq fast-path-p nil)
7820 (cond
7821 ((null files) (setq files (list (current-buffer))))
7822 ((eq files 'org-agenda-files)
7823 (setq files (org-agenda-files 'unrestricted)))
7824 ((and (symbolp files) (fboundp files))
7825 (setq files (funcall files)))
7826 ((and (symbolp files) (boundp files))
7827 (setq files (symbol-value files))))
7828 (if (stringp files) (setq files (list files)))
7829 (cond
7830 ((eq (car desc) :tag)
7831 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7832 ((eq (car desc) :todo)
7833 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7834 ((eq (car desc) :regexp)
7835 (setq descre (cdr desc)))
7836 ((eq (car desc) :level)
7837 (setq descre (concat "^\\*\\{" (number-to-string
7838 (if org-odd-levels-only
7839 (1- (* 2 (cdr desc)))
7840 (cdr desc)))
7841 "\\}[ \t]")))
7842 ((eq (car desc) :maxlevel)
7843 (setq fast-path-p t)
7844 (setq descre (concat "^\\*\\{1," (number-to-string
7845 (if org-odd-levels-only
7846 (1- (* 2 (cdr desc)))
7847 (cdr desc)))
7848 "\\}[ \t]")))
7849 (t (error "Bad refiling target description %s" desc)))
7850 (while (setq f (pop files))
7851 (save-excursion
7852 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7853 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7854 (setq f (expand-file-name f))
7855 (save-excursion
7856 (save-restriction
7857 (widen)
7858 (goto-char (point-min))
7859 (while (re-search-forward descre nil t)
7860 (goto-char (point-at-bol))
7861 (when (looking-at org-complex-heading-regexp)
7862 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7863 txt (org-link-display-format (match-string 4))
7864 re (concat "^" (regexp-quote
7865 (buffer-substring (match-beginning 1)
7866 (match-end 4)))))
7867 (if (match-end 5) (setq re (concat re "[ \t]+"
7868 (regexp-quote
7869 (match-string 5)))))
7870 (setq re (concat re "[ \t]*$"))
7871 (when org-refile-use-outline-path
7872 (setq txt (mapconcat 'org-protect-slash
7873 (append
7874 (if (eq org-refile-use-outline-path 'file)
7875 (list (file-name-nondirectory
7876 (buffer-file-name (buffer-base-buffer))))
7877 (if (eq org-refile-use-outline-path 'full-file-path)
7878 (list (buffer-file-name (buffer-base-buffer)))))
7879 (org-get-outline-path fast-path-p level txt)
7880 (list txt))
7881 "/")))
7882 (push (list txt f re (point)) targets))
7883 (goto-char (point-at-eol))))))))
7884 (message "Getting targets...done")
7885 (nreverse targets))))
7887 (defun org-protect-slash (s)
7888 (while (string-match "/" s)
7889 (setq s (replace-match "\\" t t s)))
7892 (defvar org-olpa (make-vector 20 nil))
7894 (defun org-get-outline-path (&optional fastp level heading)
7895 "Return the outline path to the current entry, as a list."
7896 (if fastp
7897 (progn
7898 (if (> level 19)
7899 (error "Outline path failure, more than 19 levels."))
7900 (loop for i from level upto 19 do
7901 (aset org-olpa i nil))
7902 (prog1
7903 (delq nil (append org-olpa nil))
7904 (aset org-olpa level heading)))
7905 (let (rtn)
7906 (save-excursion
7907 (while (org-up-heading-safe)
7908 (when (looking-at org-complex-heading-regexp)
7909 (push (org-match-string-no-properties 4) rtn)))
7910 rtn))))
7912 (defvar org-refile-history nil
7913 "History for refiling operations.")
7915 (defun org-refile (&optional goto default-buffer)
7916 "Move the entry at point to another heading.
7917 The list of target headings is compiled using the information in
7918 `org-refile-targets', which see. This list is created before each use
7919 and will therefore always be up-to-date.
7921 At the target location, the entry is filed as a subitem of the target heading.
7922 Depending on `org-reverse-note-order', the new subitem will either be the
7923 first or the last subitem.
7925 If there is an active region, all entries in that region will be moved.
7926 However, the region must fulfil the requirement that the first heading
7927 is the first one sets the top-level of the moved text - at most siblings
7928 below it are allowed.
7930 With prefix arg GOTO, the command will only visit the target location,
7931 not actually move anything.
7932 With a double prefix `C-u C-u', go to the location where the last refiling
7933 operation has put the subtree."
7934 (interactive "P")
7935 (let* ((cbuf (current-buffer))
7936 (regionp (org-region-active-p))
7937 (region-start (and regionp (region-beginning)))
7938 (region-end (and regionp (region-end)))
7939 (region-length (and regionp (- region-end region-start)))
7940 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7941 pos it nbuf file re level reversed)
7942 (when regionp (goto-char region-start)
7943 (unless (org-kill-is-subtree-p
7944 (buffer-substring region-start region-end))
7945 (error "The region is not a (sequence of) subtree(s)")))
7946 (if (equal goto '(16))
7947 (org-refile-goto-last-stored)
7948 (when (setq it (org-refile-get-location
7949 (if goto "Goto: " "Refile to: ") default-buffer))
7950 (setq file (nth 1 it)
7951 re (nth 2 it)
7952 pos (nth 3 it))
7953 (if (and (equal (buffer-file-name) file)
7954 (if regionp
7955 (and (>= pos region-start)
7956 (<= pos region-end))
7957 (and (>= pos (point))
7958 (< pos (save-excursion
7959 (org-end-of-subtree t t))))))
7960 (error "Cannot refile to position inside the tree or region"))
7962 (setq nbuf (or (find-buffer-visiting file)
7963 (find-file-noselect file)))
7964 (if goto
7965 (progn
7966 (switch-to-buffer nbuf)
7967 (goto-char pos)
7968 (org-show-context 'org-goto))
7969 (if regionp
7970 (progn
7971 (kill-new (buffer-substring region-start region-end))
7972 (org-save-markers-in-region region-start region-end))
7973 (org-copy-subtree 1 nil t))
7974 (save-excursion
7975 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7976 (find-file-noselect file))))
7977 (setq reversed (org-notes-order-reversed-p))
7978 (save-excursion
7979 (save-restriction
7980 (widen)
7981 (goto-char pos)
7982 (looking-at outline-regexp)
7983 (setq level (org-get-valid-level (funcall outline-level) 1))
7984 (goto-char
7985 (if reversed
7986 (or (outline-next-heading) (point-max))
7987 (or (save-excursion (outline-get-next-sibling))
7988 (org-end-of-subtree t t)
7989 (point-max))))
7990 (if (not (bolp)) (newline))
7991 (bookmark-set "org-refile-last-stored")
7992 (org-paste-subtree level))))
7993 (if regionp
7994 (delete-region (point) (+ (point) region-length))
7995 (org-cut-subtree))
7996 (setq org-markers-to-move nil)
7997 (message "Refiled to \"%s\"" (car it)))))))
7999 (defun org-refile-goto-last-stored ()
8000 "Go to the location where the last refile was stored."
8001 (interactive)
8002 (bookmark-jump "org-refile-last-stored")
8003 (message "This is the location of the last refile"))
8005 (defun org-refile-get-location (&optional prompt default-buffer)
8006 "Prompt the user for a refile location, using PROMPT."
8007 (let ((org-refile-targets org-refile-targets)
8008 (org-refile-use-outline-path org-refile-use-outline-path))
8009 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8010 (unless org-refile-target-table
8011 (error "No refile targets"))
8012 (let* ((cbuf (current-buffer))
8013 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8014 (cfunc (if (and org-refile-use-outline-path
8015 org-outline-path-complete-in-steps)
8016 'org-olpath-completing-read
8017 'org-ido-completing-read))
8018 (extra (if org-refile-use-outline-path "/" ""))
8019 (filename (and cfn (expand-file-name cfn)))
8020 (tbl (mapcar
8021 (lambda (x)
8022 (if (not (equal filename (nth 1 x)))
8023 (cons (concat (car x) extra " ("
8024 (file-name-nondirectory (nth 1 x)) ")")
8025 (cdr x))
8026 (cons (concat (car x) extra) (cdr x))))
8027 org-refile-target-table))
8028 (completion-ignore-case t))
8029 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8030 tbl)))
8032 (defun org-olpath-completing-read (prompt collection &rest args)
8033 "Read an outline path like a file name."
8034 (let ((thetable collection)
8035 (org-completion-use-ido nil)) ; does not work with ido.
8036 (apply
8037 'org-ido-completing-read prompt
8038 (lambda (string predicate &optional flag)
8039 (let (rtn r f (l (length string)))
8040 (cond
8041 ((eq flag nil)
8042 ;; try completion
8043 (try-completion string thetable))
8044 ((eq flag t)
8045 ;; all-completions
8046 (setq rtn (all-completions string thetable predicate))
8047 (mapcar
8048 (lambda (x)
8049 (setq r (substring x l))
8050 (if (string-match " ([^)]*)$" x)
8051 (setq f (match-string 0 x))
8052 (setq f ""))
8053 (if (string-match "/" r)
8054 (concat string (substring r 0 (match-end 0)) f)
8056 rtn))
8057 ((eq flag 'lambda)
8058 ;; exact match?
8059 (assoc string thetable)))
8061 args)))
8063 ;;;; Dynamic blocks
8065 (defun org-find-dblock (name)
8066 "Find the first dynamic block with name NAME in the buffer.
8067 If not found, stay at current position and return nil."
8068 (let (pos)
8069 (save-excursion
8070 (goto-char (point-min))
8071 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8072 nil t)
8073 (match-beginning 0))))
8074 (if pos (goto-char pos))
8075 pos))
8077 (defconst org-dblock-start-re
8078 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8079 "Matches the startline of a dynamic block, with parameters.")
8081 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8082 "Matches the end of a dynamic block.")
8084 (defun org-create-dblock (plist)
8085 "Create a dynamic block section, with parameters taken from PLIST.
8086 PLIST must contain a :name entry which is used as name of the block."
8087 (unless (bolp) (newline))
8088 (let ((name (plist-get plist :name)))
8089 (insert "#+BEGIN: " name)
8090 (while plist
8091 (if (eq (car plist) :name)
8092 (setq plist (cddr plist))
8093 (insert " " (prin1-to-string (pop plist)))))
8094 (insert "\n\n#+END:\n")
8095 (beginning-of-line -2)))
8097 (defun org-prepare-dblock ()
8098 "Prepare dynamic block for refresh.
8099 This empties the block, puts the cursor at the insert position and returns
8100 the property list including an extra property :name with the block name."
8101 (unless (looking-at org-dblock-start-re)
8102 (error "Not at a dynamic block"))
8103 (let* ((begdel (1+ (match-end 0)))
8104 (name (org-no-properties (match-string 1)))
8105 (params (append (list :name name)
8106 (read (concat "(" (match-string 3) ")")))))
8107 (unless (re-search-forward org-dblock-end-re nil t)
8108 (error "Dynamic block not terminated"))
8109 (setq params
8110 (append params
8111 (list :content (buffer-substring
8112 begdel (match-beginning 0)))))
8113 (delete-region begdel (match-beginning 0))
8114 (goto-char begdel)
8115 (open-line 1)
8116 params))
8118 (defun org-map-dblocks (&optional command)
8119 "Apply COMMAND to all dynamic blocks in the current buffer.
8120 If COMMAND is not given, use `org-update-dblock'."
8121 (let ((cmd (or command 'org-update-dblock))
8122 pos)
8123 (save-excursion
8124 (goto-char (point-min))
8125 (while (re-search-forward org-dblock-start-re nil t)
8126 (goto-char (setq pos (match-beginning 0)))
8127 (condition-case nil
8128 (funcall cmd)
8129 (error (message "Error during update of dynamic block")))
8130 (goto-char pos)
8131 (unless (re-search-forward org-dblock-end-re nil t)
8132 (error "Dynamic block not terminated"))))))
8134 (defun org-dblock-update (&optional arg)
8135 "User command for updating dynamic blocks.
8136 Update the dynamic block at point. With prefix ARG, update all dynamic
8137 blocks in the buffer."
8138 (interactive "P")
8139 (if arg
8140 (org-update-all-dblocks)
8141 (or (looking-at org-dblock-start-re)
8142 (org-beginning-of-dblock))
8143 (org-update-dblock)))
8145 (defun org-update-dblock ()
8146 "Update the dynamic block at point
8147 This means to empty the block, parse for parameters and then call
8148 the correct writing function."
8149 (save-window-excursion
8150 (let* ((pos (point))
8151 (line (org-current-line))
8152 (params (org-prepare-dblock))
8153 (name (plist-get params :name))
8154 (cmd (intern (concat "org-dblock-write:" name))))
8155 (message "Updating dynamic block `%s' at line %d..." name line)
8156 (funcall cmd params)
8157 (message "Updating dynamic block `%s' at line %d...done" name line)
8158 (goto-char pos))))
8160 (defun org-beginning-of-dblock ()
8161 "Find the beginning of the dynamic block at point.
8162 Error if there is no such block at point."
8163 (let ((pos (point))
8164 beg)
8165 (end-of-line 1)
8166 (if (and (re-search-backward org-dblock-start-re nil t)
8167 (setq beg (match-beginning 0))
8168 (re-search-forward org-dblock-end-re nil t)
8169 (> (match-end 0) pos))
8170 (goto-char beg)
8171 (goto-char pos)
8172 (error "Not in a dynamic block"))))
8174 (defun org-update-all-dblocks ()
8175 "Update all dynamic blocks in the buffer.
8176 This function can be used in a hook."
8177 (when (org-mode-p)
8178 (org-map-dblocks 'org-update-dblock)))
8181 ;;;; Completion
8183 (defconst org-additional-option-like-keywords
8184 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8185 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8186 "BEGIN_EXAMPLE" "END_EXAMPLE"
8187 "BEGIN_QUOTE" "END_QUOTE"
8188 "BEGIN_VERSE" "END_VERSE"
8189 "BEGIN_SRC" "END_SRC"
8190 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8192 (defcustom org-structure-template-alist
8194 ("s" "#+begin_src ?\n\n#+end_src"
8195 "<src lang=\"?\">\n\n</src>")
8196 ("e" "#+begin_example\n?\n#+end_example"
8197 "<example>\n?\n</example>")
8198 ("q" "#+begin_quote\n?\n#+end_quote"
8199 "<quote>\n?\n</quote>")
8200 ("v" "#+begin_verse\n?\n#+end_verse"
8201 "<verse>\n?\n/verse>")
8202 ("l" "#+begin_latex\n?\n#+end_latex"
8203 "<literal style=\"latex\">\n?\n</literal>")
8204 ("L" "#+latex: "
8205 "<literal style=\"latex\">?</literal>")
8206 ("h" "#+begin_html\n?\n#+end_html"
8207 "<literal style=\"html\">\n?\n</literal>")
8208 ("H" "#+html: "
8209 "<literal style=\"html\">?</literal>")
8210 ("a" "#+begin_ascii\n?\n#+end_ascii")
8211 ("A" "#+ascii: ")
8212 ("i" "#+include %file ?"
8213 "<include file=%file markup=\"?\">")
8215 "Structure completion elements.
8216 This is a list of abbreviation keys and values. The value gets inserted
8217 it you type @samp{.} followed by the key and then the completion key,
8218 usually `M-TAB'. %file will be replaced by a file name after prompting
8219 for the file using completion.
8220 There are two templates for each key, the first uses the original Org syntax,
8221 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8222 the default when the /org-mtags.el/ module has been loaded. See also the
8223 variable `org-mtags-prefer-muse-templates'.
8224 This is an experimental feature, it is undecided if it is going to stay in."
8225 :group 'org-completion
8226 :type '(repeat
8227 (string :tag "Key")
8228 (string :tag "Template")
8229 (string :tag "Muse Template")))
8231 (defun org-try-structure-completion ()
8232 "Try to complete a structure template before point.
8233 This looks for strings like \"<e\" on an otherwise empty line and
8234 expands them."
8235 (let ((l (buffer-substring (point-at-bol) (point)))
8237 (when (and (looking-at "[ \t]*$")
8238 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8239 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8240 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8241 (match-beginning 1)) a)
8242 t)))
8244 (defun org-complete-expand-structure-template (start cell)
8245 "Expand a structure template."
8246 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8247 (rpl (nth (if musep 2 1) cell)))
8248 (delete-region start (point))
8249 (when (string-match "\\`#\\+" rpl)
8250 (cond
8251 ((bolp))
8252 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8253 (delete-region (point-at-bol) (point)))
8254 (t (newline))))
8255 (setq start (point))
8256 (if (string-match "%file" rpl)
8257 (setq rpl (replace-match
8258 (concat
8259 "\""
8260 (save-match-data
8261 (abbreviate-file-name (read-file-name "Include file: ")))
8262 "\"")
8263 t t rpl)))
8264 (insert rpl)
8265 (if (re-search-backward "\\?" start t) (delete-char 1))))
8268 (defun org-complete (&optional arg)
8269 "Perform completion on word at point.
8270 At the beginning of a headline, this completes TODO keywords as given in
8271 `org-todo-keywords'.
8272 If the current word is preceded by a backslash, completes the TeX symbols
8273 that are supported for HTML support.
8274 If the current word is preceded by \"#+\", completes special words for
8275 setting file options.
8276 In the line after \"#+STARTUP:, complete valid keywords.\"
8277 At all other locations, this simply calls the value of
8278 `org-completion-fallback-command'."
8279 (interactive "P")
8280 (org-without-partial-completion
8281 (catch 'exit
8282 (let* ((a nil)
8283 (end (point))
8284 (beg1 (save-excursion
8285 (skip-chars-backward (org-re "[:alnum:]_@"))
8286 (point)))
8287 (beg (save-excursion
8288 (skip-chars-backward "a-zA-Z0-9_:$")
8289 (point)))
8290 (confirm (lambda (x) (stringp (car x))))
8291 (searchhead (equal (char-before beg) ?*))
8292 (struct
8293 (when (and (member (char-before beg1) '(?. ?<))
8294 (setq a (assoc (buffer-substring beg1 (point))
8295 org-structure-template-alist)))
8296 (org-complete-expand-structure-template (1- beg1) a)
8297 (throw 'exit t)))
8298 (tag (and (equal (char-before beg1) ?:)
8299 (equal (char-after (point-at-bol)) ?*)))
8300 (prop (and (equal (char-before beg1) ?:)
8301 (not (equal (char-after (point-at-bol)) ?*))))
8302 (texp (equal (char-before beg) ?\\))
8303 (link (equal (char-before beg) ?\[))
8304 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8305 beg)
8306 "#+"))
8307 (startup (string-match "^#\\+STARTUP:.*"
8308 (buffer-substring (point-at-bol) (point))))
8309 (completion-ignore-case opt)
8310 (type nil)
8311 (tbl nil)
8312 (table (cond
8313 (opt
8314 (setq type :opt)
8315 (require 'org-exp)
8316 (append
8317 (mapcar
8318 (lambda (x)
8319 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8320 (cons (match-string 2 x) (match-string 1 x)))
8321 (org-split-string (org-get-current-options) "\n"))
8322 (mapcar 'list org-additional-option-like-keywords)))
8323 (startup
8324 (setq type :startup)
8325 org-startup-options)
8326 (link (append org-link-abbrev-alist-local
8327 org-link-abbrev-alist))
8328 (texp
8329 (setq type :tex)
8330 org-html-entities)
8331 ((string-match "\\`\\*+[ \t]+\\'"
8332 (buffer-substring (point-at-bol) beg))
8333 (setq type :todo)
8334 (mapcar 'list org-todo-keywords-1))
8335 (searchhead
8336 (setq type :searchhead)
8337 (save-excursion
8338 (goto-char (point-min))
8339 (while (re-search-forward org-todo-line-regexp nil t)
8340 (push (list
8341 (org-make-org-heading-search-string
8342 (match-string 3) t))
8343 tbl)))
8344 tbl)
8345 (tag (setq type :tag beg beg1)
8346 (or org-tag-alist (org-get-buffer-tags)))
8347 (prop (setq type :prop beg beg1)
8348 (mapcar 'list (org-buffer-property-keys nil t t)))
8349 (t (progn
8350 (call-interactively org-completion-fallback-command)
8351 (throw 'exit nil)))))
8352 (pattern (buffer-substring-no-properties beg end))
8353 (completion (try-completion pattern table confirm)))
8354 (cond ((eq completion t)
8355 (if (not (assoc (upcase pattern) table))
8356 (message "Already complete")
8357 (if (and (equal type :opt)
8358 (not (member (car (assoc (upcase pattern) table))
8359 org-additional-option-like-keywords)))
8360 (insert (substring (cdr (assoc (upcase pattern) table))
8361 (length pattern)))
8362 (if (memq type '(:tag :prop)) (insert ":")))))
8363 ((null completion)
8364 (message "Can't find completion for \"%s\"" pattern)
8365 (ding))
8366 ((not (string= pattern completion))
8367 (delete-region beg end)
8368 (if (string-match " +$" completion)
8369 (setq completion (replace-match "" t t completion)))
8370 (insert completion)
8371 (if (get-buffer-window "*Completions*")
8372 (delete-window (get-buffer-window "*Completions*")))
8373 (if (assoc completion table)
8374 (if (eq type :todo) (insert " ")
8375 (if (memq type '(:tag :prop)) (insert ":"))))
8376 (if (and (equal type :opt) (assoc completion table))
8377 (message "%s" (substitute-command-keys
8378 "Press \\[org-complete] again to insert example settings"))))
8380 (message "Making completion list...")
8381 (let ((list (sort (all-completions pattern table confirm)
8382 'string<)))
8383 (with-output-to-temp-buffer "*Completions*"
8384 (condition-case nil
8385 ;; Protection needed for XEmacs and emacs 21
8386 (display-completion-list list pattern)
8387 (error (display-completion-list list)))))
8388 (message "Making completion list...%s" "done")))))))
8390 ;;;; TODO, DEADLINE, Comments
8392 (defun org-toggle-comment ()
8393 "Change the COMMENT state of an entry."
8394 (interactive)
8395 (save-excursion
8396 (org-back-to-heading)
8397 (let (case-fold-search)
8398 (if (looking-at (concat outline-regexp
8399 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8400 (replace-match "" t t nil 1)
8401 (if (looking-at outline-regexp)
8402 (progn
8403 (goto-char (match-end 0))
8404 (insert org-comment-string " ")))))))
8406 (defvar org-last-todo-state-is-todo nil
8407 "This is non-nil when the last TODO state change led to a TODO state.
8408 If the last change removed the TODO tag or switched to DONE, then
8409 this is nil.")
8411 (defvar org-setting-tags nil) ; dynamically skipped
8413 (defun org-parse-local-options (string var)
8414 "Parse STRING for startup setting relevant for variable VAR."
8415 (let ((rtn (symbol-value var))
8416 e opts)
8417 (save-match-data
8418 (if (or (not string) (not (string-match "\\S-" string)))
8420 (setq opts (delq nil (mapcar (lambda (x)
8421 (setq e (assoc x org-startup-options))
8422 (if (eq (nth 1 e) var) e nil))
8423 (org-split-string string "[ \t]+"))))
8424 (if (not opts)
8426 (setq rtn nil)
8427 (while (setq e (pop opts))
8428 (if (not (nth 3 e))
8429 (setq rtn (nth 2 e))
8430 (if (not (listp rtn)) (setq rtn nil))
8431 (push (nth 2 e) rtn)))
8432 rtn)))))
8434 (defvar org-todo-setup-filter-hook nil
8435 "Hook for functions that pre-filter todo specs.
8437 Each function takes a todo spec and returns either `nil' or the spec
8438 transformed into canonical form." )
8440 (defvar org-todo-get-default-hook nil
8441 "Hook for functions that get a default item for todo.
8443 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8444 `nil' or a string to be used for the todo mark." )
8446 (defvar org-agenda-headline-snapshot-before-repeat)
8447 (defun org-todo (&optional arg)
8448 "Change the TODO state of an item.
8449 The state of an item is given by a keyword at the start of the heading,
8450 like
8451 *** TODO Write paper
8452 *** DONE Call mom
8454 The different keywords are specified in the variable `org-todo-keywords'.
8455 By default the available states are \"TODO\" and \"DONE\".
8456 So for this example: when the item starts with TODO, it is changed to DONE.
8457 When it starts with DONE, the DONE is removed. And when neither TODO nor
8458 DONE are present, add TODO at the beginning of the heading.
8460 With C-u prefix arg, use completion to determine the new state.
8461 With numeric prefix arg, switch to that state.
8462 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8463 With a tripple C-u prefix, circumvent any state blocking.
8465 For calling through lisp, arg is also interpreted in the following way:
8466 'none -> empty state
8467 \"\"(empty string) -> switch to empty state
8468 'done -> switch to DONE
8469 'nextset -> switch to the next set of keywords
8470 'previousset -> switch to the previous set of keywords
8471 \"WAITING\" -> switch to the specified keyword, but only if it
8472 really is a member of `org-todo-keywords'."
8473 (interactive "P")
8474 (if (equal arg '(16)) (setq arg 'nextset))
8475 (let ((org-blocker-hook org-blocker-hook))
8476 (when (equal arg '(64))
8477 (setq arg nil org-blocker-hook nil))
8478 (save-excursion
8479 (catch 'exit
8480 (org-back-to-heading)
8481 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8482 (or (looking-at (concat " +" org-todo-regexp " *"))
8483 (looking-at " *"))
8484 (let* ((match-data (match-data))
8485 (startpos (point-at-bol))
8486 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8487 (org-log-done org-log-done)
8488 (org-log-repeat org-log-repeat)
8489 (org-todo-log-states org-todo-log-states)
8490 (this (match-string 1))
8491 (hl-pos (match-beginning 0))
8492 (head (org-get-todo-sequence-head this))
8493 (ass (assoc head org-todo-kwd-alist))
8494 (interpret (nth 1 ass))
8495 (done-word (nth 3 ass))
8496 (final-done-word (nth 4 ass))
8497 (last-state (or this ""))
8498 (completion-ignore-case t)
8499 (member (member this org-todo-keywords-1))
8500 (tail (cdr member))
8501 (state (cond
8502 ((and org-todo-key-trigger
8503 (or (and (equal arg '(4))
8504 (eq org-use-fast-todo-selection 'prefix))
8505 (and (not arg) org-use-fast-todo-selection
8506 (not (eq org-use-fast-todo-selection
8507 'prefix)))))
8508 ;; Use fast selection
8509 (org-fast-todo-selection))
8510 ((and (equal arg '(4))
8511 (or (not org-use-fast-todo-selection)
8512 (not org-todo-key-trigger)))
8513 ;; Read a state with completion
8514 (org-ido-completing-read
8515 "State: " (mapcar (lambda(x) (list x))
8516 org-todo-keywords-1)
8517 nil t))
8518 ((eq arg 'right)
8519 (if this
8520 (if tail (car tail) nil)
8521 (car org-todo-keywords-1)))
8522 ((eq arg 'left)
8523 (if (equal member org-todo-keywords-1)
8525 (if this
8526 (nth (- (length org-todo-keywords-1)
8527 (length tail) 2)
8528 org-todo-keywords-1)
8529 (org-last org-todo-keywords-1))))
8530 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8531 (setq arg nil))) ; hack to fall back to cycling
8532 (arg
8533 ;; user or caller requests a specific state
8534 (cond
8535 ((equal arg "") nil)
8536 ((eq arg 'none) nil)
8537 ((eq arg 'done) (or done-word (car org-done-keywords)))
8538 ((eq arg 'nextset)
8539 (or (car (cdr (member head org-todo-heads)))
8540 (car org-todo-heads)))
8541 ((eq arg 'previousset)
8542 (let ((org-todo-heads (reverse org-todo-heads)))
8543 (or (car (cdr (member head org-todo-heads)))
8544 (car org-todo-heads))))
8545 ((car (member arg org-todo-keywords-1)))
8546 ((nth (1- (prefix-numeric-value arg))
8547 org-todo-keywords-1))))
8548 ((null member) (or head (car org-todo-keywords-1)))
8549 ((equal this final-done-word) nil) ;; -> make empty
8550 ((null tail) nil) ;; -> first entry
8551 ((memq interpret '(type priority))
8552 (if (eq this-command last-command)
8553 (car tail)
8554 (if (> (length tail) 0)
8555 (or done-word (car org-done-keywords))
8556 nil)))
8558 (car tail))))
8559 (state (or
8560 (run-hook-with-args-until-success
8561 'org-todo-get-default-hook state last-state)
8562 state))
8563 (next (if state (concat " " state " ") " "))
8564 (change-plist (list :type 'todo-state-change :from this :to state
8565 :position startpos))
8566 dolog now-done-p)
8567 (when org-blocker-hook
8568 (setq org-last-todo-state-is-todo
8569 (not (member this org-done-keywords)))
8570 (unless (save-excursion
8571 (save-match-data
8572 (run-hook-with-args-until-failure
8573 'org-blocker-hook change-plist)))
8574 (if (interactive-p)
8575 (error "TODO state change from %s to %s blocked" this state)
8576 ;; fail silently
8577 (message "TODO state change from %s to %s blocked" this state)
8578 (throw 'exit nil))))
8579 (store-match-data match-data)
8580 (replace-match next t t)
8581 (unless (pos-visible-in-window-p hl-pos)
8582 (message "TODO state changed to %s" (org-trim next)))
8583 (unless head
8584 (setq head (org-get-todo-sequence-head state)
8585 ass (assoc head org-todo-kwd-alist)
8586 interpret (nth 1 ass)
8587 done-word (nth 3 ass)
8588 final-done-word (nth 4 ass)))
8589 (when (memq arg '(nextset previousset))
8590 (message "Keyword-Set %d/%d: %s"
8591 (- (length org-todo-sets) -1
8592 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8593 (length org-todo-sets)
8594 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8595 (setq org-last-todo-state-is-todo
8596 (not (member state org-done-keywords)))
8597 (setq now-done-p (and (member state org-done-keywords)
8598 (not (member this org-done-keywords))))
8599 (and logging (org-local-logging logging))
8600 (when (and (or org-todo-log-states org-log-done)
8601 (not (memq arg '(nextset previousset))))
8602 ;; we need to look at recording a time and note
8603 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8604 (nth 2 (assoc this org-todo-log-states))))
8605 (when (and state
8606 (member state org-not-done-keywords)
8607 (not (member this org-not-done-keywords)))
8608 ;; This is now a todo state and was not one before
8609 ;; If there was a CLOSED time stamp, get rid of it.
8610 (org-add-planning-info nil nil 'closed))
8611 (when (and now-done-p org-log-done)
8612 ;; It is now done, and it was not done before
8613 (org-add-planning-info 'closed (org-current-time))
8614 (if (and (not dolog) (eq 'note org-log-done))
8615 (org-add-log-setup 'done state this 'findpos 'note)))
8616 (when (and state dolog)
8617 ;; This is a non-nil state, and we need to log it
8618 (org-add-log-setup 'state state this 'findpos dolog)))
8619 ;; Fixup tag positioning
8620 (org-todo-trigger-tag-changes state)
8621 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8622 (when org-provide-todo-statistics
8623 (org-update-parent-todo-statistics))
8624 (run-hooks 'org-after-todo-state-change-hook)
8625 (if (and arg (not (member state org-done-keywords)))
8626 (setq head (org-get-todo-sequence-head state)))
8627 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8628 ;; Do we need to trigger a repeat?
8629 (when now-done-p
8630 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8631 ;; This is for the agenda, take a snapshot of the headline.
8632 (save-match-data
8633 (setq org-agenda-headline-snapshot-before-repeat
8634 (org-get-heading))))
8635 (org-auto-repeat-maybe state))
8636 ;; Fixup cursor location if close to the keyword
8637 (if (and (outline-on-heading-p)
8638 (not (bolp))
8639 (save-excursion (beginning-of-line 1)
8640 (looking-at org-todo-line-regexp))
8641 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8642 (progn
8643 (goto-char (or (match-end 2) (match-end 1)))
8644 (just-one-space)))
8645 (when org-trigger-hook
8646 (save-excursion
8647 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8649 (defun org-block-todo-from-children-or-siblings (change-plist)
8650 "Block turning an entry into a TODO, using the hierarchy.
8651 This checks whether the current task should be blocked from state
8652 changes. Such blocking occurs when:
8654 1. The task has children which are not all in a completed state.
8656 2. A task has a parent with the property :ORDERED:, and there
8657 are siblings prior to the current task with incomplete
8658 status."
8659 (catch 'dont-block
8660 ;; If this is not a todo state change, or if this entry is already DONE,
8661 ;; do not block
8662 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8663 (member (plist-get change-plist :from)
8664 (cons 'done org-done-keywords))
8665 (member (plist-get change-plist :to)
8666 (cons 'todo org-not-done-keywords)))
8667 (throw 'dont-block t))
8668 ;; If this task has children, and any are undone, it's blocked
8669 (save-excursion
8670 (org-back-to-heading t)
8671 (let ((this-level (funcall outline-level)))
8672 (outline-next-heading)
8673 (let ((child-level (funcall outline-level)))
8674 (while (and (not (eobp))
8675 (> child-level this-level))
8676 ;; this todo has children, check whether they are all
8677 ;; completed
8678 (if (and (not (org-entry-is-done-p))
8679 (org-entry-is-todo-p))
8680 (throw 'dont-block nil))
8681 (outline-next-heading)
8682 (setq child-level (funcall outline-level))))))
8683 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8684 ;; any previous siblings are undone, it's blocked
8685 (save-excursion
8686 (org-back-to-heading t)
8687 (when (save-excursion
8688 (ignore-errors
8689 (outline-up-heading 1)
8690 (org-entry-get (point) "ORDERED")))
8691 (let* ((this-level (funcall outline-level))
8692 (current-level this-level))
8693 (while (and (not (bobp))
8694 (= current-level this-level))
8695 (outline-previous-heading)
8696 (setq current-level (funcall outline-level))
8697 (if (= current-level this-level)
8698 ;; this todo has children, check whether they are all
8699 ;; completed
8700 (if (and (not (org-entry-is-done-p))
8701 (org-entry-is-todo-p))
8702 (throw 'dont-block nil)))))))
8703 t)) ; don't block
8705 (defun org-toggle-ordered-property ()
8706 "Toggle the ORDERED property of the current entry."
8707 (interactive)
8708 (save-excursion
8709 (org-back-to-heading)
8710 (if (org-entry-get nil "ORDERED")
8711 (progn
8712 (org-delete-property "ORDERED")
8713 (message "Subtasks can be completed in arbitrary order or parallel"))
8714 (org-entry-put nil "ORDERED" "t")
8715 (message "Subtasks must be completed in sequence"))))
8717 (defun org-block-todo-from-checkboxes (change-plist)
8718 "Block turning an entry into a TODO, using checkboxes.
8719 This checks whether the current task should be blocked from state
8720 changes because there are uncheckd boxes in this entry."
8721 (catch 'dont-block
8722 ;; If this is not a todo state change, or if this entry is already DONE,
8723 ;; do not block
8724 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8725 (member (plist-get change-plist :from)
8726 (cons 'done org-done-keywords))
8727 (member (plist-get change-plist :to)
8728 (cons 'todo org-not-done-keywords)))
8729 (throw 'dont-block t))
8730 ;; If this task has checkboxes that are not checked, it's blocked
8731 (save-excursion
8732 (org-back-to-heading t)
8733 (let ((beg (point)) end)
8734 (outline-next-heading)
8735 (setq end (point))
8736 (goto-char beg)
8737 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8738 end t)
8739 (throw 'dont-block nil))))
8740 t)) ; do not block
8742 (defun org-update-parent-todo-statistics ()
8743 "Update any statistics cookie in the parent of the current headline."
8744 (interactive)
8745 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8746 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
8747 (catch 'exit
8748 (save-excursion
8749 (setq level (org-up-heading-safe))
8750 (unless level
8751 (throw 'exit nil))
8752 (while (re-search-forward box-re (point-at-eol) t)
8753 (setq cnt-all 0 cnt-done 0 cookie-present t)
8754 (setq is-percent (match-end 2))
8755 (save-match-data
8756 (unless (outline-next-heading) (throw 'exit nil))
8757 (while (looking-at org-todo-line-regexp)
8758 (setq kwd (match-string 2))
8759 (and kwd (setq cnt-all (1+ cnt-all)))
8760 (and (member kwd org-done-keywords)
8761 (setq cnt-done (1+ cnt-done)))
8762 (condition-case nil
8763 (org-forward-same-level 1)
8764 (error (end-of-line 1)))))
8765 (replace-match
8766 (if is-percent
8767 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8768 (format "[%d/%d]" cnt-done cnt-all))))
8769 (when cookie-present
8770 (run-hook-with-args 'org-after-todo-statistics-hook
8771 cnt-done (- cnt-all cnt-done)))))))
8773 (defvar org-after-todo-statistics-hook nil
8774 "Hook that is called after a TODO statistics cookie has been updated.
8775 Each function is called with two arguments: the number of not-done entries
8776 and the number of done entries.
8778 For example, the following function, when added to this hook, will switch
8779 an entry to DONE when all children are done, and back to TODO when new
8780 entries are set to a TODO status. Note that this hook is only called
8781 when there is a statistics cookie in the headline!
8783 (defun org-summary-todo (n-done n-not-done)
8784 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8785 (let (org-log-done org-log-states) ; turn off logging
8786 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8789 (defun org-todo-trigger-tag-changes (state)
8790 "Apply the changes defined in `org-todo-state-tags-triggers'."
8791 (let ((l org-todo-state-tags-triggers)
8792 changes)
8793 (when (or (not state) (equal state ""))
8794 (setq changes (append changes (cdr (assoc "" l)))))
8795 (when (and (stringp state) (> (length state) 0))
8796 (setq changes (append changes (cdr (assoc state l)))))
8797 (when (member state org-not-done-keywords)
8798 (setq changes (append changes (cdr (assoc 'todo l)))))
8799 (when (member state org-done-keywords)
8800 (setq changes (append changes (cdr (assoc 'done l)))))
8801 (dolist (c changes)
8802 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8804 (defun org-local-logging (value)
8805 "Get logging settings from a property VALUE."
8806 (let* (words w a)
8807 ;; directly set the variables, they are already local.
8808 (setq org-log-done nil
8809 org-log-repeat nil
8810 org-todo-log-states nil)
8811 (setq words (org-split-string value))
8812 (while (setq w (pop words))
8813 (cond
8814 ((setq a (assoc w org-startup-options))
8815 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8816 (set (nth 1 a) (nth 2 a))))
8817 ((setq a (org-extract-log-state-settings w))
8818 (and (member (car a) org-todo-keywords-1)
8819 (push a org-todo-log-states)))))))
8821 (defun org-get-todo-sequence-head (kwd)
8822 "Return the head of the TODO sequence to which KWD belongs.
8823 If KWD is not set, check if there is a text property remembering the
8824 right sequence."
8825 (let (p)
8826 (cond
8827 ((not kwd)
8828 (or (get-text-property (point-at-bol) 'org-todo-head)
8829 (progn
8830 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8831 nil (point-at-eol)))
8832 (get-text-property p 'org-todo-head))))
8833 ((not (member kwd org-todo-keywords-1))
8834 (car org-todo-keywords-1))
8835 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8837 (defun org-fast-todo-selection ()
8838 "Fast TODO keyword selection with single keys.
8839 Returns the new TODO keyword, or nil if no state change should occur."
8840 (let* ((fulltable org-todo-key-alist)
8841 (done-keywords org-done-keywords) ;; needed for the faces.
8842 (maxlen (apply 'max (mapcar
8843 (lambda (x)
8844 (if (stringp (car x)) (string-width (car x)) 0))
8845 fulltable)))
8846 (expert nil)
8847 (fwidth (+ maxlen 3 1 3))
8848 (ncol (/ (- (window-width) 4) fwidth))
8849 tg cnt e c tbl
8850 groups ingroup)
8851 (save-excursion
8852 (save-window-excursion
8853 (if expert
8854 (set-buffer (get-buffer-create " *Org todo*"))
8855 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8856 (erase-buffer)
8857 (org-set-local 'org-done-keywords done-keywords)
8858 (setq tbl fulltable cnt 0)
8859 (while (setq e (pop tbl))
8860 (cond
8861 ((equal e '(:startgroup))
8862 (push '() groups) (setq ingroup t)
8863 (when (not (= cnt 0))
8864 (setq cnt 0)
8865 (insert "\n"))
8866 (insert "{ "))
8867 ((equal e '(:endgroup))
8868 (setq ingroup nil cnt 0)
8869 (insert "}\n"))
8871 (setq tg (car e) c (cdr e))
8872 (if ingroup (push tg (car groups)))
8873 (setq tg (org-add-props tg nil 'face
8874 (org-get-todo-face tg)))
8875 (if (and (= cnt 0) (not ingroup)) (insert " "))
8876 (insert "[" c "] " tg (make-string
8877 (- fwidth 4 (length tg)) ?\ ))
8878 (when (= (setq cnt (1+ cnt)) ncol)
8879 (insert "\n")
8880 (if ingroup (insert " "))
8881 (setq cnt 0)))))
8882 (insert "\n")
8883 (goto-char (point-min))
8884 (if (not expert) (org-fit-window-to-buffer))
8885 (message "[a-z..]:Set [SPC]:clear")
8886 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8887 (cond
8888 ((or (= c ?\C-g)
8889 (and (= c ?q) (not (rassoc c fulltable))))
8890 (setq quit-flag t))
8891 ((= c ?\ ) nil)
8892 ((setq e (rassoc c fulltable) tg (car e))
8894 (t (setq quit-flag t)))))))
8896 (defun org-entry-is-todo-p ()
8897 (member (org-get-todo-state) org-not-done-keywords))
8899 (defun org-entry-is-done-p ()
8900 (member (org-get-todo-state) org-done-keywords))
8902 (defun org-get-todo-state ()
8903 (save-excursion
8904 (org-back-to-heading t)
8905 (and (looking-at org-todo-line-regexp)
8906 (match-end 2)
8907 (match-string 2))))
8909 (defun org-at-date-range-p (&optional inactive-ok)
8910 "Is the cursor inside a date range?"
8911 (interactive)
8912 (save-excursion
8913 (catch 'exit
8914 (let ((pos (point)))
8915 (skip-chars-backward "^[<\r\n")
8916 (skip-chars-backward "<[")
8917 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8918 (>= (match-end 0) pos)
8919 (throw 'exit t))
8920 (skip-chars-backward "^<[\r\n")
8921 (skip-chars-backward "<[")
8922 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8923 (>= (match-end 0) pos)
8924 (throw 'exit t)))
8925 nil)))
8927 (defun org-get-repeat ()
8928 "Check if there is a deadline/schedule with repeater in this entry."
8929 (save-match-data
8930 (save-excursion
8931 (org-back-to-heading t)
8932 (if (re-search-forward
8933 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8934 (match-string 1)))))
8936 (defvar org-last-changed-timestamp)
8937 (defvar org-last-inserted-timestamp)
8938 (defvar org-log-post-message)
8939 (defvar org-log-note-purpose)
8940 (defvar org-log-note-how)
8941 (defvar org-log-note-extra)
8942 (defun org-auto-repeat-maybe (done-word)
8943 "Check if the current headline contains a repeated deadline/schedule.
8944 If yes, set TODO state back to what it was and change the base date
8945 of repeating deadline/scheduled time stamps to new date.
8946 This function is run automatically after each state change to a DONE state."
8947 ;; last-state is dynamically scoped into this function
8948 (let* ((repeat (org-get-repeat))
8949 (aa (assoc last-state org-todo-kwd-alist))
8950 (interpret (nth 1 aa))
8951 (head (nth 2 aa))
8952 (whata '(("d" . day) ("m" . month) ("y" . year)))
8953 (msg "Entry repeats: ")
8954 (org-log-done nil)
8955 (org-todo-log-states nil)
8956 (nshiftmax 10) (nshift 0)
8957 re type n what ts time)
8958 (when repeat
8959 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8960 (org-todo (if (eq interpret 'type) last-state head))
8961 (when org-log-repeat
8962 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8963 (memq 'org-add-log-note post-command-hook))
8964 ;; OK, we are already setup for some record
8965 (if (eq org-log-repeat 'note)
8966 ;; make sure we take a note, not only a time stamp
8967 (setq org-log-note-how 'note))
8968 ;; Set up for taking a record
8969 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8970 last-state
8971 'findpos org-log-repeat)))
8972 (org-back-to-heading t)
8973 (org-add-planning-info nil nil 'closed)
8974 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8975 org-deadline-time-regexp "\\)\\|\\("
8976 org-ts-regexp "\\)"))
8977 (while (re-search-forward
8978 re (save-excursion (outline-next-heading) (point)) t)
8979 (setq type (if (match-end 1) org-scheduled-string
8980 (if (match-end 3) org-deadline-string "Plain:"))
8981 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
8982 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8983 (setq n (string-to-number (match-string 2 ts))
8984 what (match-string 3 ts))
8985 (if (equal what "w") (setq n (* n 7) what "d"))
8986 ;; Preparation, see if we need to modify the start date for the change
8987 (when (match-end 1)
8988 (setq time (save-match-data (org-time-string-to-time ts)))
8989 (cond
8990 ((equal (match-string 1 ts) ".")
8991 ;; Shift starting date to today
8992 (org-timestamp-change
8993 (- (time-to-days (current-time)) (time-to-days time))
8994 'day))
8995 ((equal (match-string 1 ts) "+")
8996 (while (or (= nshift 0)
8997 (<= (time-to-days time) (time-to-days (current-time))))
8998 (when (= (incf nshift) nshiftmax)
8999 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9000 (error "Abort")))
9001 (org-timestamp-change n (cdr (assoc what whata)))
9002 (org-at-timestamp-p t)
9003 (setq ts (match-string 1))
9004 (setq time (save-match-data (org-time-string-to-time ts))))
9005 (org-timestamp-change (- n) (cdr (assoc what whata)))
9006 ;; rematch, so that we have everything in place for the real shift
9007 (org-at-timestamp-p t)
9008 (setq ts (match-string 1))
9009 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9010 (org-timestamp-change n (cdr (assoc what whata)))
9011 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9012 (setq org-log-post-message msg)
9013 (message "%s" msg))))
9015 (defun org-show-todo-tree (arg)
9016 "Make a compact tree which shows all headlines marked with TODO.
9017 The tree will show the lines where the regexp matches, and all higher
9018 headlines above the match.
9019 With a \\[universal-argument] prefix, also show the DONE entries.
9020 With a numeric prefix N, construct a sparse tree for the Nth element
9021 of `org-todo-keywords-1'."
9022 (interactive "P")
9023 (let ((case-fold-search nil)
9024 (kwd-re
9025 (cond ((null arg) org-not-done-regexp)
9026 ((equal arg '(4))
9027 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9028 (mapcar 'list org-todo-keywords-1))))
9029 (concat "\\("
9030 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9031 "\\)\\>")))
9032 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9033 (regexp-quote (nth (1- (prefix-numeric-value arg))
9034 org-todo-keywords-1)))
9035 (t (error "Invalid prefix argument: %s" arg)))))
9036 (message "%d TODO entries found"
9037 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9039 (defun org-deadline (&optional remove time)
9040 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9041 With argument REMOVE, remove any deadline from the item.
9042 When TIME is set, it should be an internal time specification, and the
9043 scheduling will use the corresponding date."
9044 (interactive "P")
9045 (if remove
9046 (progn
9047 (org-remove-timestamp-with-keyword org-deadline-string)
9048 (message "Item no longer has a deadline."))
9049 (if (org-get-repeat)
9050 (error "Cannot change deadline on task with repeater, please do that by hand")
9051 (org-add-planning-info 'deadline time 'closed)
9052 (message "Deadline on %s" org-last-inserted-timestamp))))
9054 (defun org-schedule (&optional remove time)
9055 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9056 With argument REMOVE, remove any scheduling date from the item.
9057 When TIME is set, it should be an internal time specification, and the
9058 scheduling will use the corresponding date."
9059 (interactive "P")
9060 (if remove
9061 (progn
9062 (org-remove-timestamp-with-keyword org-scheduled-string)
9063 (message "Item is no longer scheduled."))
9064 (if (org-get-repeat)
9065 (error "Cannot reschedule task with repeater, please do that by hand")
9066 (org-add-planning-info 'scheduled time 'closed)
9067 (message "Scheduled to %s" org-last-inserted-timestamp))))
9069 (defun org-get-scheduled-time (pom &optional inherit)
9070 "Get the scheduled time as a time tuple, of a format suitable
9071 for calling org-schedule with, or if there is no scheduling,
9072 returns nil."
9073 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9074 (when time
9075 (apply 'encode-time (org-parse-time-string time)))))
9077 (defun org-get-deadline-time (pom &optional inherit)
9078 "Get the deadine as a time tuple, of a format suitable for
9079 calling org-deadlin with, or if there is no scheduling, returns
9080 nil."
9081 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9082 (when time
9083 (apply 'encode-time (org-parse-time-string time)))))
9085 (defun org-remove-timestamp-with-keyword (keyword)
9086 "Remove all time stamps with KEYWORD in the current entry."
9087 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9088 beg)
9089 (save-excursion
9090 (org-back-to-heading t)
9091 (setq beg (point))
9092 (org-end-of-subtree t t)
9093 (while (re-search-backward re beg t)
9094 (replace-match "")
9095 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9096 (equal (char-before) ?\ ))
9097 (backward-delete-char 1)
9098 (if (string-match "^[ \t]*$" (buffer-substring
9099 (point-at-bol) (point-at-eol)))
9100 (delete-region (point-at-bol)
9101 (min (point-max) (1+ (point-at-eol))))))))))
9103 (defun org-add-planning-info (what &optional time &rest remove)
9104 "Insert new timestamp with keyword in the line directly after the headline.
9105 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9106 If non is given, the user is prompted for a date.
9107 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9108 be removed."
9109 (interactive)
9110 (let (org-time-was-given org-end-time-was-given ts
9111 end default-time default-input)
9113 (when (and (not time) (memq what '(scheduled deadline)))
9114 ;; Try to get a default date/time from existing timestamp
9115 (save-excursion
9116 (org-back-to-heading t)
9117 (setq end (save-excursion (outline-next-heading) (point)))
9118 (when (re-search-forward (if (eq what 'scheduled)
9119 org-scheduled-time-regexp
9120 org-deadline-time-regexp)
9121 end t)
9122 (setq ts (match-string 1)
9123 default-time
9124 (apply 'encode-time (org-parse-time-string ts))
9125 default-input (and ts (org-get-compact-tod ts))))))
9126 (when what
9127 ;; If necessary, get the time from the user
9128 (setq time (or time (org-read-date nil 'to-time nil nil
9129 default-time default-input))))
9131 (when (and org-insert-labeled-timestamps-at-point
9132 (member what '(scheduled deadline)))
9133 (insert
9134 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9135 (org-insert-time-stamp time org-time-was-given
9136 nil nil nil (list org-end-time-was-given))
9137 (setq what nil))
9138 (save-excursion
9139 (save-restriction
9140 (let (col list elt ts buffer-invisibility-spec)
9141 (org-back-to-heading t)
9142 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9143 (goto-char (match-end 1))
9144 (setq col (current-column))
9145 (goto-char (match-end 0))
9146 (if (eobp) (insert "\n") (forward-char 1))
9147 (if (and (not (looking-at outline-regexp))
9148 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9149 "[^\r\n]*"))
9150 (not (equal (match-string 1) org-clock-string)))
9151 (narrow-to-region (match-beginning 0) (match-end 0))
9152 (insert-before-markers "\n")
9153 (backward-char 1)
9154 (narrow-to-region (point) (point))
9155 (and org-adapt-indentation (org-indent-to-column col)))
9156 ;; Check if we have to remove something.
9157 (setq list (cons what remove))
9158 (while list
9159 (setq elt (pop list))
9160 (goto-char (point-min))
9161 (when (or (and (eq elt 'scheduled)
9162 (re-search-forward org-scheduled-time-regexp nil t))
9163 (and (eq elt 'deadline)
9164 (re-search-forward org-deadline-time-regexp nil t))
9165 (and (eq elt 'closed)
9166 (re-search-forward org-closed-time-regexp nil t)))
9167 (replace-match "")
9168 (if (looking-at "--+<[^>]+>") (replace-match ""))
9169 (if (looking-at " +") (replace-match ""))))
9170 (goto-char (point-max))
9171 (when what
9172 (insert
9173 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9174 (cond ((eq what 'scheduled) org-scheduled-string)
9175 ((eq what 'deadline) org-deadline-string)
9176 ((eq what 'closed) org-closed-string))
9177 " ")
9178 (setq ts (org-insert-time-stamp
9179 time
9180 (or org-time-was-given
9181 (and (eq what 'closed) org-log-done-with-time))
9182 (eq what 'closed)
9183 nil nil (list org-end-time-was-given)))
9184 (end-of-line 1))
9185 (goto-char (point-min))
9186 (widen)
9187 (if (and (looking-at "[ \t]+\n")
9188 (equal (char-before) ?\n))
9189 (delete-region (1- (point)) (point-at-eol)))
9190 ts)))))
9192 (defvar org-log-note-marker (make-marker))
9193 (defvar org-log-note-purpose nil)
9194 (defvar org-log-note-state nil)
9195 (defvar org-log-note-previous-state nil)
9196 (defvar org-log-note-how nil)
9197 (defvar org-log-note-extra nil)
9198 (defvar org-log-note-window-configuration nil)
9199 (defvar org-log-note-return-to (make-marker))
9200 (defvar org-log-post-message nil
9201 "Message to be displayed after a log note has been stored.
9202 The auto-repeater uses this.")
9204 (defun org-add-note ()
9205 "Add a note to the current entry.
9206 This is done in the same way as adding a state change note."
9207 (interactive)
9208 (org-add-log-setup 'note nil nil 'findpos nil))
9210 (defvar org-property-end-re)
9211 (defun org-add-log-setup (&optional purpose state prev-state
9212 findpos how &optional extra)
9213 "Set up the post command hook to take a note.
9214 If this is about to TODO state change, the new state is expected in STATE.
9215 When FINDPOS is non-nil, find the correct position for the note in
9216 the current entry. If not, assume that it can be inserted at point.
9217 HOW is an indicator what kind of note should be created.
9218 EXTRA is additional text that will be inserted into the notes buffer."
9219 (let ((drawer (cond ((stringp org-log-into-drawer)
9220 org-log-into-drawer)
9221 (org-log-into-drawer "LOGBOOK")
9222 (t nil))))
9223 (save-restriction
9224 (save-excursion
9225 (when findpos
9226 (org-back-to-heading t)
9227 (narrow-to-region (point) (save-excursion
9228 (outline-next-heading) (point)))
9229 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9230 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9231 "[^\r\n]*\\)?"))
9232 (goto-char (match-end 0))
9233 (cond
9234 (drawer
9235 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9236 nil t)
9237 (progn
9238 (goto-char (match-end 0))
9239 (or org-log-states-order-reversed
9240 (and (re-search-forward org-property-end-re nil t)
9241 (goto-char (1- (match-beginning 0))))))
9242 (insert "\n:" drawer ":\n:END:")
9243 (beginning-of-line 0)
9244 (org-indent-line-function)
9245 (beginning-of-line 2)
9246 (org-indent-line-function)
9247 (end-of-line 0)))
9248 ((and org-log-state-notes-insert-after-drawers
9249 (save-excursion
9250 (forward-line) (looking-at org-drawer-regexp)))
9251 (forward-line)
9252 (while (looking-at org-drawer-regexp)
9253 (goto-char (match-end 0))
9254 (re-search-forward org-property-end-re (point-max) t)
9255 (forward-line))
9256 (forward-line -1)))
9257 (unless org-log-states-order-reversed
9258 (and (= (char-after) ?\n) (forward-char 1))
9259 (org-skip-over-state-notes)
9260 (skip-chars-backward " \t\n\r")))
9261 (move-marker org-log-note-marker (point))
9262 (setq org-log-note-purpose purpose
9263 org-log-note-state state
9264 org-log-note-previous-state prev-state
9265 org-log-note-how how
9266 org-log-note-extra extra)
9267 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9269 (defun org-skip-over-state-notes ()
9270 "Skip past the list of State notes in an entry."
9271 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9272 (while (looking-at "[ \t]*- State")
9273 (condition-case nil
9274 (org-next-item)
9275 (error (org-end-of-item)))))
9277 (defun org-add-log-note (&optional purpose)
9278 "Pop up a window for taking a note, and add this note later at point."
9279 (remove-hook 'post-command-hook 'org-add-log-note)
9280 (setq org-log-note-window-configuration (current-window-configuration))
9281 (delete-other-windows)
9282 (move-marker org-log-note-return-to (point))
9283 (switch-to-buffer (marker-buffer org-log-note-marker))
9284 (goto-char org-log-note-marker)
9285 (org-switch-to-buffer-other-window "*Org Note*")
9286 (erase-buffer)
9287 (if (memq org-log-note-how '(time state))
9288 (let (current-prefix-arg) (org-store-log-note))
9289 (let ((org-inhibit-startup t)) (org-mode))
9290 (insert (format "# Insert note for %s.
9291 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9292 (cond
9293 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9294 ((eq org-log-note-purpose 'done) "closed todo item")
9295 ((eq org-log-note-purpose 'state)
9296 (format "state change from \"%s\" to \"%s\""
9297 (or org-log-note-previous-state "")
9298 (or org-log-note-state "")))
9299 ((eq org-log-note-purpose 'note)
9300 "this entry")
9301 (t (error "This should not happen")))))
9302 (if org-log-note-extra (insert org-log-note-extra))
9303 (org-set-local 'org-finish-function 'org-store-log-note)))
9305 (defvar org-note-abort nil) ; dynamically scoped
9306 (defun org-store-log-note ()
9307 "Finish taking a log note, and insert it to where it belongs."
9308 (let ((txt (buffer-string))
9309 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9310 lines ind)
9311 (kill-buffer (current-buffer))
9312 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9313 (setq txt (replace-match "" t t txt)))
9314 (if (string-match "\\s-+\\'" txt)
9315 (setq txt (replace-match "" t t txt)))
9316 (setq lines (org-split-string txt "\n"))
9317 (when (and note (string-match "\\S-" note))
9318 (setq note
9319 (org-replace-escapes
9320 note
9321 (list (cons "%u" (user-login-name))
9322 (cons "%U" user-full-name)
9323 (cons "%t" (format-time-string
9324 (org-time-stamp-format 'long 'inactive)
9325 (current-time)))
9326 (cons "%s" (if org-log-note-state
9327 (concat "\"" org-log-note-state "\"")
9328 ""))
9329 (cons "%S" (if org-log-note-previous-state
9330 (concat "\"" org-log-note-previous-state "\"")
9331 "\"\"")))))
9332 (if lines (setq note (concat note " \\\\")))
9333 (push note lines))
9334 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9335 (when lines
9336 (save-excursion
9337 (set-buffer (marker-buffer org-log-note-marker))
9338 (save-excursion
9339 (goto-char org-log-note-marker)
9340 (move-marker org-log-note-marker nil)
9341 (end-of-line 1)
9342 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9343 (insert "- " (pop lines))
9344 (org-indent-line-function)
9345 (beginning-of-line 1)
9346 (looking-at "[ \t]*")
9347 (setq ind (concat (match-string 0) " "))
9348 (end-of-line 1)
9349 (while lines (insert "\n" ind (pop lines)))
9350 (message "Note stored")
9351 (org-back-to-heading t)
9352 (org-cycle-hide-drawers 'children)))))
9353 (set-window-configuration org-log-note-window-configuration)
9354 (with-current-buffer (marker-buffer org-log-note-return-to)
9355 (goto-char org-log-note-return-to))
9356 (move-marker org-log-note-return-to nil)
9357 (and org-log-post-message (message "%s" org-log-post-message)))
9359 (defun org-sparse-tree (&optional arg)
9360 "Create a sparse tree, prompt for the details.
9361 This command can create sparse trees. You first need to select the type
9362 of match used to create the tree:
9364 t Show entries with a specific TODO keyword.
9365 T Show entries selected by a tags match.
9366 p Enter a property name and its value (both with completion on existing
9367 names/values) and show entries with that property.
9368 r Show entries matching a regular expression
9369 d Show deadlines due within `org-deadline-warning-days'."
9370 (interactive "P")
9371 (let (ans kwd value)
9372 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9373 (setq ans (read-char-exclusive))
9374 (cond
9375 ((equal ans ?d)
9376 (call-interactively 'org-check-deadlines))
9377 ((equal ans ?b)
9378 (call-interactively 'org-check-before-date))
9379 ((equal ans ?t)
9380 (org-show-todo-tree '(4)))
9381 ((equal ans ?T)
9382 (call-interactively 'org-tags-sparse-tree))
9383 ((member ans '(?p ?P))
9384 (setq kwd (org-ido-completing-read "Property: "
9385 (mapcar 'list (org-buffer-property-keys))))
9386 (setq value (org-ido-completing-read "Value: "
9387 (mapcar 'list (org-property-values kwd))))
9388 (unless (string-match "\\`{.*}\\'" value)
9389 (setq value (concat "\"" value "\"")))
9390 (org-tags-sparse-tree arg (concat kwd "=" value)))
9391 ((member ans '(?r ?R ?/))
9392 (call-interactively 'org-occur))
9393 (t (error "No such sparse tree command \"%c\"" ans)))))
9395 (defvar org-occur-highlights nil
9396 "List of overlays used for occur matches.")
9397 (make-variable-buffer-local 'org-occur-highlights)
9398 (defvar org-occur-parameters nil
9399 "Parameters of the active org-occur calls.
9400 This is a list, each call to org-occur pushes as cons cell,
9401 containing the regular expression and the callback, onto the list.
9402 The list can contain several entries if `org-occur' has been called
9403 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9404 will only contain one set of parameters. When the highlights are
9405 removed (for example with `C-c C-c', or with the next edit (depending
9406 on `org-remove-highlights-with-change'), this variable is emptied
9407 as well.")
9408 (make-variable-buffer-local 'org-occur-parameters)
9410 (defun org-occur (regexp &optional keep-previous callback)
9411 "Make a compact tree which shows all matches of REGEXP.
9412 The tree will show the lines where the regexp matches, and all higher
9413 headlines above the match. It will also show the heading after the match,
9414 to make sure editing the matching entry is easy.
9415 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9416 call to `org-occur' will be kept, to allow stacking of calls to this
9417 command.
9418 If CALLBACK is non-nil, it is a function which is called to confirm
9419 that the match should indeed be shown."
9420 (interactive "sRegexp: \nP")
9421 (unless keep-previous
9422 (org-remove-occur-highlights nil nil t))
9423 (push (cons regexp callback) org-occur-parameters)
9424 (let ((cnt 0))
9425 (save-excursion
9426 (goto-char (point-min))
9427 (if (or (not keep-previous) ; do not want to keep
9428 (not org-occur-highlights)) ; no previous matches
9429 ;; hide everything
9430 (org-overview))
9431 (while (re-search-forward regexp nil t)
9432 (when (or (not callback)
9433 (save-match-data (funcall callback)))
9434 (setq cnt (1+ cnt))
9435 (when org-highlight-sparse-tree-matches
9436 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9437 (org-show-context 'occur-tree))))
9438 (when org-remove-highlights-with-change
9439 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9440 nil 'local))
9441 (unless org-sparse-tree-open-archived-trees
9442 (org-hide-archived-subtrees (point-min) (point-max)))
9443 (run-hooks 'org-occur-hook)
9444 (if (interactive-p)
9445 (message "%d match(es) for regexp %s" cnt regexp))
9446 cnt))
9448 (defun org-show-context (&optional key)
9449 "Make sure point and context and visible.
9450 How much context is shown depends upon the variables
9451 `org-show-hierarchy-above', `org-show-following-heading'. and
9452 `org-show-siblings'."
9453 (let ((heading-p (org-on-heading-p t))
9454 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9455 (following-p (org-get-alist-option org-show-following-heading key))
9456 (entry-p (org-get-alist-option org-show-entry-below key))
9457 (siblings-p (org-get-alist-option org-show-siblings key)))
9458 (catch 'exit
9459 ;; Show heading or entry text
9460 (if (and heading-p (not entry-p))
9461 (org-flag-heading nil) ; only show the heading
9462 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9463 (org-show-hidden-entry))) ; show entire entry
9464 (when following-p
9465 ;; Show next sibling, or heading below text
9466 (save-excursion
9467 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9468 (org-flag-heading nil))))
9469 (when siblings-p (org-show-siblings))
9470 (when hierarchy-p
9471 ;; show all higher headings, possibly with siblings
9472 (save-excursion
9473 (while (and (condition-case nil
9474 (progn (org-up-heading-all 1) t)
9475 (error nil))
9476 (not (bobp)))
9477 (org-flag-heading nil)
9478 (when siblings-p (org-show-siblings))))))))
9480 (defun org-reveal (&optional siblings)
9481 "Show current entry, hierarchy above it, and the following headline.
9482 This can be used to show a consistent set of context around locations
9483 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9484 not t for the search context.
9486 With optional argument SIBLINGS, on each level of the hierarchy all
9487 siblings are shown. This repairs the tree structure to what it would
9488 look like when opened with hierarchical calls to `org-cycle'."
9489 (interactive "P")
9490 (let ((org-show-hierarchy-above t)
9491 (org-show-following-heading t)
9492 (org-show-siblings (if siblings t org-show-siblings)))
9493 (org-show-context nil)))
9495 (defun org-highlight-new-match (beg end)
9496 "Highlight from BEG to END and mark the highlight is an occur headline."
9497 (let ((ov (org-make-overlay beg end)))
9498 (org-overlay-put ov 'face 'secondary-selection)
9499 (push ov org-occur-highlights)))
9501 (defun org-remove-occur-highlights (&optional beg end noremove)
9502 "Remove the occur highlights from the buffer.
9503 BEG and END are ignored. If NOREMOVE is nil, remove this function
9504 from the `before-change-functions' in the current buffer."
9505 (interactive)
9506 (unless org-inhibit-highlight-removal
9507 (mapc 'org-delete-overlay org-occur-highlights)
9508 (setq org-occur-highlights nil)
9509 (setq org-occur-parameters nil)
9510 (unless noremove
9511 (remove-hook 'before-change-functions
9512 'org-remove-occur-highlights 'local))))
9514 ;;;; Priorities
9516 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9517 "Regular expression matching the priority indicator.")
9519 (defvar org-remove-priority-next-time nil)
9521 (defun org-priority-up ()
9522 "Increase the priority of the current item."
9523 (interactive)
9524 (org-priority 'up))
9526 (defun org-priority-down ()
9527 "Decrease the priority of the current item."
9528 (interactive)
9529 (org-priority 'down))
9531 (defun org-priority (&optional action)
9532 "Change the priority of an item by ARG.
9533 ACTION can be `set', `up', `down', or a character."
9534 (interactive)
9535 (setq action (or action 'set))
9536 (let (current new news have remove)
9537 (save-excursion
9538 (org-back-to-heading)
9539 (if (looking-at org-priority-regexp)
9540 (setq current (string-to-char (match-string 2))
9541 have t)
9542 (setq current org-default-priority))
9543 (cond
9544 ((or (eq action 'set)
9545 (if (featurep 'xemacs) (characterp action) (integerp action)))
9546 (if (not (eq action 'set))
9547 (setq new action)
9548 (message "Priority %c-%c, SPC to remove: "
9549 org-highest-priority org-lowest-priority)
9550 (setq new (read-char-exclusive)))
9551 (if (and (= (upcase org-highest-priority) org-highest-priority)
9552 (= (upcase org-lowest-priority) org-lowest-priority))
9553 (setq new (upcase new)))
9554 (cond ((equal new ?\ ) (setq remove t))
9555 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9556 (error "Priority must be between `%c' and `%c'"
9557 org-highest-priority org-lowest-priority))))
9558 ((eq action 'up)
9559 (if (and (not have) (eq last-command this-command))
9560 (setq new org-lowest-priority)
9561 (setq new (if (and org-priority-start-cycle-with-default (not have))
9562 org-default-priority (1- current)))))
9563 ((eq action 'down)
9564 (if (and (not have) (eq last-command this-command))
9565 (setq new org-highest-priority)
9566 (setq new (if (and org-priority-start-cycle-with-default (not have))
9567 org-default-priority (1+ current)))))
9568 (t (error "Invalid action")))
9569 (if (or (< (upcase new) org-highest-priority)
9570 (> (upcase new) org-lowest-priority))
9571 (setq remove t))
9572 (setq news (format "%c" new))
9573 (if have
9574 (if remove
9575 (replace-match "" t t nil 1)
9576 (replace-match news t t nil 2))
9577 (if remove
9578 (error "No priority cookie found in line")
9579 (looking-at org-todo-line-regexp)
9580 (if (match-end 2)
9581 (progn
9582 (goto-char (match-end 2))
9583 (insert " [#" news "]"))
9584 (goto-char (match-beginning 3))
9585 (insert "[#" news "] ")))))
9586 (org-preserve-lc (org-set-tags nil 'align))
9587 (if remove
9588 (message "Priority removed")
9589 (message "Priority of current item set to %s" news))))
9592 (defun org-get-priority (s)
9593 "Find priority cookie and return priority."
9594 (save-match-data
9595 (if (not (string-match org-priority-regexp s))
9596 (* 1000 (- org-lowest-priority org-default-priority))
9597 (* 1000 (- org-lowest-priority
9598 (string-to-char (match-string 2 s)))))))
9600 ;;;; Tags
9602 (defvar org-agenda-archives-mode)
9603 (defun org-scan-tags (action matcher &optional todo-only)
9604 "Scan headline tags with inheritance and produce output ACTION.
9606 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9607 or `agenda' to produce an entry list for an agenda view. It can also be
9608 a Lisp form or a function that should be called at each matched headline, in
9609 this case the return value is a list of all return values from these calls.
9611 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9612 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9613 only lines with a TODO keyword are included in the output."
9614 (require 'org-agenda)
9615 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9616 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9617 (org-re
9618 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9619 (props (list 'face 'default
9620 'done-face 'org-done
9621 'undone-face 'default
9622 'mouse-face 'highlight
9623 'org-not-done-regexp org-not-done-regexp
9624 'org-todo-regexp org-todo-regexp
9625 'keymap org-agenda-keymap
9626 'help-echo
9627 (format "mouse-2 or RET jump to org file %s"
9628 (abbreviate-file-name
9629 (or (buffer-file-name (buffer-base-buffer))
9630 (buffer-name (buffer-base-buffer)))))))
9631 (case-fold-search nil)
9632 lspos tags tags-list
9633 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9634 (llast 0) rtn rtn1 level category i txt
9635 todo marker entry priority)
9636 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9637 (setq action (list 'lambda nil action)))
9638 (save-excursion
9639 (goto-char (point-min))
9640 (when (eq action 'sparse-tree)
9641 (org-overview)
9642 (org-remove-occur-highlights))
9643 (while (re-search-forward re nil t)
9644 (catch :skip
9645 (setq todo (if (match-end 1) (match-string 2))
9646 tags (if (match-end 4) (match-string 4)))
9647 (goto-char (setq lspos (1+ (match-beginning 0))))
9648 (setq level (org-reduced-level (funcall outline-level))
9649 category (org-get-category))
9650 (setq i llast llast level)
9651 ;; remove tag lists from same and sublevels
9652 (while (>= i level)
9653 (when (setq entry (assoc i tags-alist))
9654 (setq tags-alist (delete entry tags-alist)))
9655 (setq i (1- i)))
9656 ;; add the next tags
9657 (when tags
9658 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9659 tags-alist
9660 (cons (cons level tags) tags-alist)))
9661 ;; compile tags for current headline
9662 (setq tags-list
9663 (if org-use-tag-inheritance
9664 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9665 tags))
9666 (when org-use-tag-inheritance
9667 (setcdr (car tags-alist)
9668 (mapcar (lambda (x)
9669 (setq x (copy-sequence x))
9670 (org-add-prop-inherited x))
9671 (cdar tags-alist))))
9672 (when (and tags org-use-tag-inheritance
9673 (not (eq t org-use-tag-inheritance)))
9674 ;; selective inheritance, remove uninherited ones
9675 (setcdr (car tags-alist)
9676 (org-remove-uniherited-tags (cdar tags-alist))))
9677 (when (and (or (not todo-only)
9678 (and (member todo org-not-done-keywords)
9679 (or (not org-agenda-tags-todo-honor-ignore-options)
9680 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9681 (let ((case-fold-search t)) (eval matcher))
9683 (not (member org-archive-tag tags-list))
9684 ;; we have an archive tag, should we use this anyway?
9685 (or (not org-agenda-skip-archived-trees)
9686 (and (eq action 'agenda) org-agenda-archives-mode))))
9687 (unless (eq action 'sparse-tree) (org-agenda-skip))
9689 ;; select this headline
9691 (cond
9692 ((eq action 'sparse-tree)
9693 (and org-highlight-sparse-tree-matches
9694 (org-get-heading) (match-end 0)
9695 (org-highlight-new-match
9696 (match-beginning 0) (match-beginning 1)))
9697 (org-show-context 'tags-tree))
9698 ((eq action 'agenda)
9699 (setq txt (org-format-agenda-item
9701 (concat
9702 (if org-tags-match-list-sublevels
9703 (make-string (1- level) ?.) "")
9704 (org-get-heading))
9705 category (org-get-tags-at))
9706 priority (org-get-priority txt))
9707 (goto-char lspos)
9708 (setq marker (org-agenda-new-marker))
9709 (org-add-props txt props
9710 'org-marker marker 'org-hd-marker marker 'org-category category
9711 'todo-state todo
9712 'priority priority 'type "tagsmatch")
9713 (push txt rtn))
9714 ((functionp action)
9715 (save-excursion
9716 (setq rtn1 (funcall action))
9717 (push rtn1 rtn))
9718 (goto-char (point-at-eol)))
9719 (t (error "Invalid action")))
9721 ;; if we are to skip sublevels, jump to end of subtree
9722 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9723 (when (and (eq action 'sparse-tree)
9724 (not org-sparse-tree-open-archived-trees))
9725 (org-hide-archived-subtrees (point-min) (point-max)))
9726 (nreverse rtn)))
9728 (defun org-remove-uniherited-tags (tags)
9729 "Remove all tags that are not inherited from the list TAGS."
9730 (cond
9731 ((eq org-use-tag-inheritance t)
9732 (if org-tags-exclude-from-inheritance
9733 (org-delete-all org-tags-exclude-from-inheritance tags)
9734 tags))
9735 ((not org-use-tag-inheritance) nil)
9736 ((stringp org-use-tag-inheritance)
9737 (delq nil (mapcar
9738 (lambda (x)
9739 (if (and (string-match org-use-tag-inheritance x)
9740 (not (member x org-tags-exclude-from-inheritance)))
9741 x nil))
9742 tags)))
9743 ((listp org-use-tag-inheritance)
9744 (delq nil (mapcar
9745 (lambda (x)
9746 (if (member x org-use-tag-inheritance) x nil))
9747 tags)))))
9749 (defvar todo-only) ;; dynamically scoped
9751 (defun org-tags-sparse-tree (&optional todo-only match)
9752 "Create a sparse tree according to tags string MATCH.
9753 MATCH can contain positive and negative selection of tags, like
9754 \"+WORK+URGENT-WITHBOSS\".
9755 If optional argument TODO-ONLY is non-nil, only select lines that are
9756 also TODO lines."
9757 (interactive "P")
9758 (org-prepare-agenda-buffers (list (current-buffer)))
9759 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9761 (defvar org-cached-props nil)
9762 (defun org-cached-entry-get (pom property)
9763 (if (or (eq t org-use-property-inheritance)
9764 (and (stringp org-use-property-inheritance)
9765 (string-match org-use-property-inheritance property))
9766 (and (listp org-use-property-inheritance)
9767 (member property org-use-property-inheritance)))
9768 ;; Caching is not possible, check it directly
9769 (org-entry-get pom property 'inherit)
9770 ;; Get all properties, so that we can do complicated checks easily
9771 (cdr (assoc property (or org-cached-props
9772 (setq org-cached-props
9773 (org-entry-properties pom)))))))
9775 (defun org-global-tags-completion-table (&optional files)
9776 "Return the list of all tags in all agenda buffer/files."
9777 (save-excursion
9778 (org-uniquify
9779 (delq nil
9780 (apply 'append
9781 (mapcar
9782 (lambda (file)
9783 (set-buffer (find-file-noselect file))
9784 (append (org-get-buffer-tags)
9785 (mapcar (lambda (x) (if (stringp (car-safe x))
9786 (list (car-safe x)) nil))
9787 org-tag-alist)))
9788 (if (and files (car files))
9789 files
9790 (org-agenda-files))))))))
9792 (defun org-make-tags-matcher (match)
9793 "Create the TAGS//TODO matcher form for the selection string MATCH."
9794 ;; todo-only is scoped dynamically into this function, and the function
9795 ;; may change it if the matcher asks for it.
9796 (unless match
9797 ;; Get a new match request, with completion
9798 (let ((org-last-tags-completion-table
9799 (org-global-tags-completion-table)))
9800 (setq match (org-completing-read
9801 "Match: " 'org-tags-completion-function nil nil nil
9802 'org-tags-history))))
9804 ;; Parse the string and create a lisp form
9805 (let ((match0 match)
9806 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9807 minus tag mm
9808 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9809 orterms term orlist re-p str-p level-p level-op time-p
9810 prop-p pn pv po cat-p gv rest)
9811 (if (string-match "/+" match)
9812 ;; match contains also a todo-matching request
9813 (progn
9814 (setq tagsmatch (substring match 0 (match-beginning 0))
9815 todomatch (substring match (match-end 0)))
9816 (if (string-match "^!" todomatch)
9817 (setq todo-only t todomatch (substring todomatch 1)))
9818 (if (string-match "^\\s-*$" todomatch)
9819 (setq todomatch nil)))
9820 ;; only matching tags
9821 (setq tagsmatch match todomatch nil))
9823 ;; Make the tags matcher
9824 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9825 (setq tagsmatcher t)
9826 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9827 (while (setq term (pop orterms))
9828 (while (and (equal (substring term -1) "\\") orterms)
9829 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9830 (while (string-match re term)
9831 (setq rest (substring term (match-end 0))
9832 minus (and (match-end 1)
9833 (equal (match-string 1 term) "-"))
9834 tag (match-string 2 term)
9835 re-p (equal (string-to-char tag) ?{)
9836 level-p (match-end 4)
9837 prop-p (match-end 5)
9838 mm (cond
9839 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9840 (level-p
9841 (setq level-op (org-op-to-function (match-string 3 term)))
9842 `(,level-op level ,(string-to-number
9843 (match-string 4 term))))
9844 (prop-p
9845 (setq pn (match-string 5 term)
9846 po (match-string 6 term)
9847 pv (match-string 7 term)
9848 cat-p (equal pn "CATEGORY")
9849 re-p (equal (string-to-char pv) ?{)
9850 str-p (equal (string-to-char pv) ?\")
9851 time-p (save-match-data
9852 (string-match "^\"[[<].*[]>]\"$" pv))
9853 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9854 (if time-p (setq pv (org-matcher-time pv)))
9855 (setq po (org-op-to-function po (if time-p 'time str-p)))
9856 (cond
9857 ((equal pn "CATEGORY")
9858 (setq gv '(get-text-property (point) 'org-category)))
9859 ((equal pn "TODO")
9860 (setq gv 'todo))
9862 (setq gv `(org-cached-entry-get nil ,pn))))
9863 (if re-p
9864 (if (eq po 'org<>)
9865 `(not (string-match ,pv (or ,gv "")))
9866 `(string-match ,pv (or ,gv "")))
9867 (if str-p
9868 `(,po (or ,gv "") ,pv)
9869 `(,po (string-to-number (or ,gv ""))
9870 ,(string-to-number pv) ))))
9871 (t `(member ,(downcase tag) tags-list)))
9872 mm (if minus (list 'not mm) mm)
9873 term rest)
9874 (push mm tagsmatcher))
9875 (push (if (> (length tagsmatcher) 1)
9876 (cons 'and tagsmatcher)
9877 (car tagsmatcher))
9878 orlist)
9879 (setq tagsmatcher nil))
9880 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9881 (setq tagsmatcher
9882 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9883 ;; Make the todo matcher
9884 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9885 (setq todomatcher t)
9886 (setq orterms (org-split-string todomatch "|") orlist nil)
9887 (while (setq term (pop orterms))
9888 (while (string-match re term)
9889 (setq minus (and (match-end 1)
9890 (equal (match-string 1 term) "-"))
9891 kwd (match-string 2 term)
9892 re-p (equal (string-to-char kwd) ?{)
9893 term (substring term (match-end 0))
9894 mm (if re-p
9895 `(string-match ,(substring kwd 1 -1) todo)
9896 (list 'equal 'todo kwd))
9897 mm (if minus (list 'not mm) mm))
9898 (push mm todomatcher))
9899 (push (if (> (length todomatcher) 1)
9900 (cons 'and todomatcher)
9901 (car todomatcher))
9902 orlist)
9903 (setq todomatcher nil))
9904 (setq todomatcher (if (> (length orlist) 1)
9905 (cons 'or orlist) (car orlist))))
9907 ;; Return the string and lisp forms of the matcher
9908 (setq matcher (if todomatcher
9909 (list 'and tagsmatcher todomatcher)
9910 tagsmatcher))
9911 (cons match0 matcher)))
9913 (defun org-op-to-function (op &optional stringp)
9914 "Turn an operator into the appropriate function."
9915 (setq op
9916 (cond
9917 ((equal op "<" ) '(< string< org-time<))
9918 ((equal op ">" ) '(> org-string> org-time>))
9919 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9920 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9921 ((member op '("=" "==")) '(= string= org-time=))
9922 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9923 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9925 (defun org<> (a b) (not (= a b)))
9926 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9927 (defun org-string>= (a b) (not (string< a b)))
9928 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9929 (defun org-string<> (a b) (not (string= a b)))
9930 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9931 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9932 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9933 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9934 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9935 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9936 (defun org-2ft (s)
9937 "Convert S to a floating point time.
9938 If S is already a number, just return it. If it is a string, parse
9939 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9940 (cond
9941 ((numberp s) s)
9942 ((stringp s)
9943 (condition-case nil
9944 (float-time (apply 'encode-time (org-parse-time-string s)))
9945 (error 0.)))
9946 (t 0.)))
9948 (defun org-time-today ()
9949 "Time in seconds today at 0:00.
9950 Returns the float number of seconds since the beginning of the
9951 epoch to the beginning of today (00:00)."
9952 (float-time (apply 'encode-time
9953 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9955 (defun org-matcher-time (s)
9956 "Interpret a time comparison value."
9957 (save-match-data
9958 (cond
9959 ((string= s "<now>") (float-time))
9960 ((string= s "<today>") (org-time-today))
9961 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9962 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9963 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9964 (+ (org-time-today)
9965 (* (string-to-number (match-string 1 s))
9966 (cdr (assoc (match-string 2 s)
9967 '(("d" . 86400.0) ("w" . 604800.0)
9968 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9969 (t (org-2ft s)))))
9971 (defun org-match-any-p (re list)
9972 "Does re match any element of list?"
9973 (setq list (mapcar (lambda (x) (string-match re x)) list))
9974 (delq nil list))
9976 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9977 (defvar org-tags-overlay (org-make-overlay 1 1))
9978 (org-detach-overlay org-tags-overlay)
9980 (defun org-get-local-tags-at (&optional pos)
9981 "Get a list of tags defined in the current headline."
9982 (org-get-tags-at pos 'local))
9984 (defun org-get-local-tags ()
9985 "Get a list of tags defined in the current headline."
9986 (org-get-tags-at nil 'local))
9988 (defun org-get-tags-at (&optional pos local)
9989 "Get a list of all headline tags applicable at POS.
9990 POS defaults to point. If tags are inherited, the list contains
9991 the targets in the same sequence as the headlines appear, i.e.
9992 the tags of the current headline come last.
9993 When LOCAL is non-nil, only return tags from the current headline,
9994 ignore inherited ones."
9995 (interactive)
9996 (let (tags ltags lastpos parent)
9997 (save-excursion
9998 (save-restriction
9999 (widen)
10000 (goto-char (or pos (point)))
10001 (save-match-data
10002 (catch 'done
10003 (condition-case nil
10004 (progn
10005 (org-back-to-heading t)
10006 (while (not (equal lastpos (point)))
10007 (setq lastpos (point))
10008 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10009 (setq ltags (org-split-string
10010 (org-match-string-no-properties 1) ":"))
10011 (when parent
10012 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10013 (setq tags (append
10014 (if parent
10015 (org-remove-uniherited-tags ltags)
10016 ltags)
10017 tags)))
10018 (or org-use-tag-inheritance (throw 'done t))
10019 (if local (throw 'done t))
10020 (org-up-heading-all 1)
10021 (setq parent t)))
10022 (error nil)))))
10023 (append (org-remove-uniherited-tags org-file-tags) tags))))
10025 (defun org-add-prop-inherited (s)
10026 (add-text-properties 0 (length s) '(inherited t) s)
10029 (defun org-toggle-tag (tag &optional onoff)
10030 "Toggle the tag TAG for the current line.
10031 If ONOFF is `on' or `off', don't toggle but set to this state."
10032 (let (res current)
10033 (save-excursion
10034 (org-back-to-heading t)
10035 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10036 (point-at-eol) t)
10037 (progn
10038 (setq current (match-string 1))
10039 (replace-match ""))
10040 (setq current ""))
10041 (setq current (nreverse (org-split-string current ":")))
10042 (cond
10043 ((eq onoff 'on)
10044 (setq res t)
10045 (or (member tag current) (push tag current)))
10046 ((eq onoff 'off)
10047 (or (not (member tag current)) (setq current (delete tag current))))
10048 (t (if (member tag current)
10049 (setq current (delete tag current))
10050 (setq res t)
10051 (push tag current))))
10052 (end-of-line 1)
10053 (if current
10054 (progn
10055 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10056 (org-set-tags nil t))
10057 (delete-horizontal-space))
10058 (run-hooks 'org-after-tags-change-hook))
10059 res))
10061 (defun org-align-tags-here (to-col)
10062 ;; Assumes that this is a headline
10063 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10064 (beginning-of-line 1)
10065 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10066 (< pos (match-beginning 2)))
10067 (progn
10068 (setq tags-l (- (match-end 2) (match-beginning 2)))
10069 (goto-char (match-beginning 1))
10070 (insert " ")
10071 (delete-region (point) (1+ (match-beginning 2)))
10072 (setq ncol (max (1+ (current-column))
10073 (1+ col)
10074 (if (> to-col 0)
10075 to-col
10076 (- (abs to-col) tags-l))))
10077 (setq p (point))
10078 (insert (make-string (- ncol (current-column)) ?\ ))
10079 (setq ncol (current-column))
10080 (when indent-tabs-mode (tabify p (point-at-eol)))
10081 (org-move-to-column (min ncol col) t))
10082 (goto-char pos))))
10084 (defun org-set-tags-command (&optional arg just-align)
10085 "Call the set-tags command for the current entry."
10086 (interactive "P")
10087 (if (org-on-heading-p)
10088 (org-set-tags arg just-align)
10089 (save-excursion
10090 (org-back-to-heading t)
10091 (org-set-tags arg just-align))))
10093 (defun org-set-tags (&optional arg just-align)
10094 "Set the tags for the current headline.
10095 With prefix ARG, realign all tags in headings in the current buffer."
10096 (interactive "P")
10097 (let* ((re (concat "^" outline-regexp))
10098 (current (org-get-tags-string))
10099 (col (current-column))
10100 (org-setting-tags t)
10101 table current-tags inherited-tags ; computed below when needed
10102 tags p0 c0 c1 rpl)
10103 (if arg
10104 (save-excursion
10105 (goto-char (point-min))
10106 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10107 (while (re-search-forward re nil t)
10108 (org-set-tags nil t)
10109 (end-of-line 1)))
10110 (message "All tags realigned to column %d" org-tags-column))
10111 (if just-align
10112 (setq tags current)
10113 ;; Get a new set of tags from the user
10114 (save-excursion
10115 (setq table (or org-tag-alist (org-get-buffer-tags))
10116 org-last-tags-completion-table table
10117 current-tags (org-split-string current ":")
10118 inherited-tags (nreverse
10119 (nthcdr (length current-tags)
10120 (nreverse (org-get-tags-at))))
10121 tags
10122 (if (or (eq t org-use-fast-tag-selection)
10123 (and org-use-fast-tag-selection
10124 (delq nil (mapcar 'cdr table))))
10125 (org-fast-tag-selection
10126 current-tags inherited-tags table
10127 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10128 (let ((org-add-colon-after-tag-completion t))
10129 (org-trim
10130 (org-without-partial-completion
10131 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10132 nil nil current 'org-tags-history)))))))
10133 (while (string-match "[-+&]+" tags)
10134 ;; No boolean logic, just a list
10135 (setq tags (replace-match ":" t t tags))))
10137 (if (string-match "\\`[\t ]*\\'" tags)
10138 (setq tags "")
10139 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10140 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10142 ;; Insert new tags at the correct column
10143 (beginning-of-line 1)
10144 (cond
10145 ((and (equal current "") (equal tags "")))
10146 ((re-search-forward
10147 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10148 (point-at-eol) t)
10149 (if (equal tags "")
10150 (setq rpl "")
10151 (goto-char (match-beginning 0))
10152 (setq c0 (current-column) p0 (point)
10153 c1 (max (1+ c0) (if (> org-tags-column 0)
10154 org-tags-column
10155 (- (- org-tags-column) (length tags))))
10156 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10157 (replace-match rpl t t)
10158 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10159 tags)
10160 (t (error "Tags alignment failed")))
10161 (org-move-to-column col)
10162 (unless just-align
10163 (run-hooks 'org-after-tags-change-hook)))))
10165 (defun org-change-tag-in-region (beg end tag off)
10166 "Add or remove TAG for each entry in the region.
10167 This works in the agenda, and also in an org-mode buffer."
10168 (interactive
10169 (list (region-beginning) (region-end)
10170 (let ((org-last-tags-completion-table
10171 (if (org-mode-p)
10172 (org-get-buffer-tags)
10173 (org-global-tags-completion-table))))
10174 (org-ido-completing-read
10175 "Tag: " 'org-tags-completion-function nil nil nil
10176 'org-tags-history))
10177 (progn
10178 (message "[s]et or [r]emove? ")
10179 (equal (read-char-exclusive) ?r))))
10180 (if (fboundp 'deactivate-mark) (deactivate-mark))
10181 (let ((agendap (equal major-mode 'org-agenda-mode))
10182 l1 l2 m buf pos newhead (cnt 0))
10183 (goto-char end)
10184 (setq l2 (1- (org-current-line)))
10185 (goto-char beg)
10186 (setq l1 (org-current-line))
10187 (loop for l from l1 to l2 do
10188 (goto-line l)
10189 (setq m (get-text-property (point) 'org-hd-marker))
10190 (when (or (and (org-mode-p) (org-on-heading-p))
10191 (and agendap m))
10192 (setq buf (if agendap (marker-buffer m) (current-buffer))
10193 pos (if agendap m (point)))
10194 (with-current-buffer buf
10195 (save-excursion
10196 (save-restriction
10197 (goto-char pos)
10198 (setq cnt (1+ cnt))
10199 (org-toggle-tag tag (if off 'off 'on))
10200 (setq newhead (org-get-heading)))))
10201 (and agendap (org-agenda-change-all-lines newhead m))))
10202 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10204 (defun org-tags-completion-function (string predicate &optional flag)
10205 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10206 (confirm (lambda (x) (stringp (car x)))))
10207 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10208 (setq s1 (match-string 1 string)
10209 s2 (match-string 2 string))
10210 (setq s1 "" s2 string))
10211 (cond
10212 ((eq flag nil)
10213 ;; try completion
10214 (setq rtn (try-completion s2 ctable confirm))
10215 (if (stringp rtn)
10216 (setq rtn
10217 (concat s1 s2 (substring rtn (length s2))
10218 (if (and org-add-colon-after-tag-completion
10219 (assoc rtn ctable))
10220 ":" ""))))
10221 rtn)
10222 ((eq flag t)
10223 ;; all-completions
10224 (all-completions s2 ctable confirm)
10226 ((eq flag 'lambda)
10227 ;; exact match?
10228 (assoc s2 ctable)))
10231 (defun org-fast-tag-insert (kwd tags face &optional end)
10232 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10233 (insert (format "%-12s" (concat kwd ":"))
10234 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10235 (or end "")))
10237 (defun org-fast-tag-show-exit (flag)
10238 (save-excursion
10239 (goto-line 3)
10240 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10241 (replace-match ""))
10242 (when flag
10243 (end-of-line 1)
10244 (org-move-to-column (- (window-width) 19) t)
10245 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10247 (defun org-set-current-tags-overlay (current prefix)
10248 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10249 (if (featurep 'xemacs)
10250 (org-overlay-display org-tags-overlay (concat prefix s)
10251 'secondary-selection)
10252 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10253 (org-overlay-display org-tags-overlay (concat prefix s)))))
10255 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10256 "Fast tag selection with single keys.
10257 CURRENT is the current list of tags in the headline, INHERITED is the
10258 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10259 possibly with grouping information. TODO-TABLE is a similar table with
10260 TODO keywords, should these have keys assigned to them.
10261 If the keys are nil, a-z are automatically assigned.
10262 Returns the new tags string, or nil to not change the current settings."
10263 (let* ((fulltable (append table todo-table))
10264 (maxlen (apply 'max (mapcar
10265 (lambda (x)
10266 (if (stringp (car x)) (string-width (car x)) 0))
10267 fulltable)))
10268 (buf (current-buffer))
10269 (expert (eq org-fast-tag-selection-single-key 'expert))
10270 (buffer-tags nil)
10271 (fwidth (+ maxlen 3 1 3))
10272 (ncol (/ (- (window-width) 4) fwidth))
10273 (i-face 'org-done)
10274 (c-face 'org-todo)
10275 tg cnt e c char c1 c2 ntable tbl rtn
10276 ov-start ov-end ov-prefix
10277 (exit-after-next org-fast-tag-selection-single-key)
10278 (done-keywords org-done-keywords)
10279 groups ingroup)
10280 (save-excursion
10281 (beginning-of-line 1)
10282 (if (looking-at
10283 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10284 (setq ov-start (match-beginning 1)
10285 ov-end (match-end 1)
10286 ov-prefix "")
10287 (setq ov-start (1- (point-at-eol))
10288 ov-end (1+ ov-start))
10289 (skip-chars-forward "^\n\r")
10290 (setq ov-prefix
10291 (concat
10292 (buffer-substring (1- (point)) (point))
10293 (if (> (current-column) org-tags-column)
10295 (make-string (- org-tags-column (current-column)) ?\ ))))))
10296 (org-move-overlay org-tags-overlay ov-start ov-end)
10297 (save-window-excursion
10298 (if expert
10299 (set-buffer (get-buffer-create " *Org tags*"))
10300 (delete-other-windows)
10301 (split-window-vertically)
10302 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10303 (erase-buffer)
10304 (org-set-local 'org-done-keywords done-keywords)
10305 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10306 (org-fast-tag-insert "Current" current c-face "\n\n")
10307 (org-fast-tag-show-exit exit-after-next)
10308 (org-set-current-tags-overlay current ov-prefix)
10309 (setq tbl fulltable char ?a cnt 0)
10310 (while (setq e (pop tbl))
10311 (cond
10312 ((equal e '(:startgroup))
10313 (push '() groups) (setq ingroup t)
10314 (when (not (= cnt 0))
10315 (setq cnt 0)
10316 (insert "\n"))
10317 (insert "{ "))
10318 ((equal e '(:endgroup))
10319 (setq ingroup nil cnt 0)
10320 (insert "}\n"))
10322 (setq tg (car e) c2 nil)
10323 (if (cdr e)
10324 (setq c (cdr e))
10325 ;; automatically assign a character.
10326 (setq c1 (string-to-char
10327 (downcase (substring
10328 tg (if (= (string-to-char tg) ?@) 1 0)))))
10329 (if (or (rassoc c1 ntable) (rassoc c1 table))
10330 (while (or (rassoc char ntable) (rassoc char table))
10331 (setq char (1+ char)))
10332 (setq c2 c1))
10333 (setq c (or c2 char)))
10334 (if ingroup (push tg (car groups)))
10335 (setq tg (org-add-props tg nil 'face
10336 (cond
10337 ((not (assoc tg table))
10338 (org-get-todo-face tg))
10339 ((member tg current) c-face)
10340 ((member tg inherited) i-face)
10341 (t nil))))
10342 (if (and (= cnt 0) (not ingroup)) (insert " "))
10343 (insert "[" c "] " tg (make-string
10344 (- fwidth 4 (length tg)) ?\ ))
10345 (push (cons tg c) ntable)
10346 (when (= (setq cnt (1+ cnt)) ncol)
10347 (insert "\n")
10348 (if ingroup (insert " "))
10349 (setq cnt 0)))))
10350 (setq ntable (nreverse ntable))
10351 (insert "\n")
10352 (goto-char (point-min))
10353 (if (not expert) (org-fit-window-to-buffer))
10354 (setq rtn
10355 (catch 'exit
10356 (while t
10357 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10358 (if groups " [!] no groups" " [!]groups")
10359 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10360 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10361 (cond
10362 ((= c ?\r) (throw 'exit t))
10363 ((= c ?!)
10364 (setq groups (not groups))
10365 (goto-char (point-min))
10366 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10367 ((= c ?\C-c)
10368 (if (not expert)
10369 (org-fast-tag-show-exit
10370 (setq exit-after-next (not exit-after-next)))
10371 (setq expert nil)
10372 (delete-other-windows)
10373 (split-window-vertically)
10374 (org-switch-to-buffer-other-window " *Org tags*")
10375 (org-fit-window-to-buffer)))
10376 ((or (= c ?\C-g)
10377 (and (= c ?q) (not (rassoc c ntable))))
10378 (org-detach-overlay org-tags-overlay)
10379 (setq quit-flag t))
10380 ((= c ?\ )
10381 (setq current nil)
10382 (if exit-after-next (setq exit-after-next 'now)))
10383 ((= c ?\t)
10384 (condition-case nil
10385 (setq tg (org-ido-completing-read
10386 "Tag: "
10387 (or buffer-tags
10388 (with-current-buffer buf
10389 (org-get-buffer-tags)))))
10390 (quit (setq tg "")))
10391 (when (string-match "\\S-" tg)
10392 (add-to-list 'buffer-tags (list tg))
10393 (if (member tg current)
10394 (setq current (delete tg current))
10395 (push tg current)))
10396 (if exit-after-next (setq exit-after-next 'now)))
10397 ((setq e (rassoc c todo-table) tg (car e))
10398 (with-current-buffer buf
10399 (save-excursion (org-todo tg)))
10400 (if exit-after-next (setq exit-after-next 'now)))
10401 ((setq e (rassoc c ntable) tg (car e))
10402 (if (member tg current)
10403 (setq current (delete tg current))
10404 (loop for g in groups do
10405 (if (member tg g)
10406 (mapc (lambda (x)
10407 (setq current (delete x current)))
10408 g)))
10409 (push tg current))
10410 (if exit-after-next (setq exit-after-next 'now))))
10412 ;; Create a sorted list
10413 (setq current
10414 (sort current
10415 (lambda (a b)
10416 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10417 (if (eq exit-after-next 'now) (throw 'exit t))
10418 (goto-char (point-min))
10419 (beginning-of-line 2)
10420 (delete-region (point) (point-at-eol))
10421 (org-fast-tag-insert "Current" current c-face)
10422 (org-set-current-tags-overlay current ov-prefix)
10423 (while (re-search-forward
10424 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10425 (setq tg (match-string 1))
10426 (add-text-properties
10427 (match-beginning 1) (match-end 1)
10428 (list 'face
10429 (cond
10430 ((member tg current) c-face)
10431 ((member tg inherited) i-face)
10432 (t (get-text-property (match-beginning 1) 'face))))))
10433 (goto-char (point-min)))))
10434 (org-detach-overlay org-tags-overlay)
10435 (if rtn
10436 (mapconcat 'identity current ":")
10437 nil))))
10439 (defun org-get-tags-string ()
10440 "Get the TAGS string in the current headline."
10441 (unless (org-on-heading-p t)
10442 (error "Not on a heading"))
10443 (save-excursion
10444 (beginning-of-line 1)
10445 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10446 (org-match-string-no-properties 1)
10447 "")))
10449 (defun org-get-tags ()
10450 "Get the list of tags specified in the current headline."
10451 (org-split-string (org-get-tags-string) ":"))
10453 (defun org-get-buffer-tags ()
10454 "Get a table of all tags used in the buffer, for completion."
10455 (let (tags)
10456 (save-excursion
10457 (goto-char (point-min))
10458 (while (re-search-forward
10459 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10460 (when (equal (char-after (point-at-bol 0)) ?*)
10461 (mapc (lambda (x) (add-to-list 'tags x))
10462 (org-split-string (org-match-string-no-properties 1) ":")))))
10463 (mapcar 'list tags)))
10465 ;;;; The mapping API
10467 ;;;###autoload
10468 (defun org-map-entries (func &optional match scope &rest skip)
10469 "Call FUNC at each headline selected by MATCH in SCOPE.
10471 FUNC is a function or a lisp form. The function will be called without
10472 arguments, with the cursor positioned at the beginning of the headline.
10473 The return values of all calls to the function will be collected and
10474 returned as a list.
10476 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10477 Only headlines that are matched by this query will be considered during
10478 the iteration. When MATCH is nil or t, all headlines will be
10479 visited by the iteration.
10481 SCOPE determines the scope of this command. It can be any of:
10483 nil The current buffer, respecting the restriction if any
10484 tree The subtree started with the entry at point
10485 file The current buffer, without restriction
10486 file-with-archives
10487 The current buffer, and any archives associated with it
10488 agenda All agenda files
10489 agenda-with-archives
10490 All agenda files with any archive files associated with them
10491 \(file1 file2 ...)
10492 If this is a list, all files in the list will be scanned
10494 The remaining args are treated as settings for the skipping facilities of
10495 the scanner. The following items can be given here:
10497 archive skip trees with the archive tag.
10498 comment skip trees with the COMMENT keyword
10499 function or Emacs Lisp form:
10500 will be used as value for `org-agenda-skip-function', so whenever
10501 the the function returns t, FUNC will not be called for that
10502 entry and search will continue from the point where the
10503 function leaves it."
10504 (let* ((org-agenda-archives-mode nil) ; just to make sure
10505 (org-agenda-skip-archived-trees (memq 'archive skip))
10506 (org-agenda-skip-comment-trees (memq 'comment skip))
10507 (org-agenda-skip-function
10508 (car (org-delete-all '(comment archive) skip)))
10509 (org-tags-match-list-sublevels t)
10510 matcher file res
10511 org-todo-keywords-for-agenda
10512 org-done-keywords-for-agenda
10513 org-todo-keyword-alist-for-agenda
10514 org-tag-alist-for-agenda)
10516 (cond
10517 ((eq match t) (setq matcher t))
10518 ((eq match nil) (setq matcher t))
10519 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10521 (save-excursion
10522 (save-restriction
10523 (when (eq scope 'tree)
10524 (org-back-to-heading t)
10525 (org-narrow-to-subtree)
10526 (setq scope nil))
10528 (if (not scope)
10529 (progn
10530 (org-prepare-agenda-buffers
10531 (list (buffer-file-name (current-buffer))))
10532 (setq res (org-scan-tags func matcher)))
10533 ;; Get the right scope
10534 (cond
10535 ((and scope (listp scope) (symbolp (car scope)))
10536 (setq scope (eval scope)))
10537 ((eq scope 'agenda)
10538 (setq scope (org-agenda-files t)))
10539 ((eq scope 'agenda-with-archives)
10540 (setq scope (org-agenda-files t))
10541 (setq scope (org-add-archive-files scope)))
10542 ((eq scope 'file)
10543 (setq scope (list (buffer-file-name))))
10544 ((eq scope 'file-with-archives)
10545 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10546 (org-prepare-agenda-buffers scope)
10547 (while (setq file (pop scope))
10548 (with-current-buffer (org-find-base-buffer-visiting file)
10549 (save-excursion
10550 (save-restriction
10551 (widen)
10552 (goto-char (point-min))
10553 (setq res (append res (org-scan-tags func matcher))))))))))
10554 res))
10556 ;;;; Properties
10558 ;;; Setting and retrieving properties
10560 (defconst org-special-properties
10561 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10562 "TIMESTAMP" "TIMESTAMP_IA")
10563 "The special properties valid in Org-mode.
10565 These are properties that are not defined in the property drawer,
10566 but in some other way.")
10568 (defconst org-default-properties
10569 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10570 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10571 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10572 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10573 "Some properties that are used by Org-mode for various purposes.
10574 Being in this list makes sure that they are offered for completion.")
10576 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10577 "Regular expression matching the first line of a property drawer.")
10579 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10580 "Regular expression matching the first line of a property drawer.")
10582 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10583 "Regular expression matching the first line of a property drawer.")
10585 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10586 "Regular expression matching the first line of a property drawer.")
10588 (defconst org-property-drawer-re
10589 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10590 org-property-end-re "\\)\n?")
10591 "Matches an entire property drawer.")
10593 (defconst org-clock-drawer-re
10594 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10595 org-property-end-re "\\)\n?")
10596 "Matches an entire clock drawer.")
10598 (defun org-property-action ()
10599 "Do an action on properties."
10600 (interactive)
10601 (let (c)
10602 (org-at-property-p)
10603 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10604 (setq c (read-char-exclusive))
10605 (cond
10606 ((equal c ?s)
10607 (call-interactively 'org-set-property))
10608 ((equal c ?d)
10609 (call-interactively 'org-delete-property))
10610 ((equal c ?D)
10611 (call-interactively 'org-delete-property-globally))
10612 ((equal c ?c)
10613 (call-interactively 'org-compute-property-at-point))
10614 (t (error "No such property action %c" c)))))
10616 (defun org-at-property-p ()
10617 "Is the cursor in a property line?"
10618 ;; FIXME: Does not check if we are actually in the drawer.
10619 ;; FIXME: also returns true on any drawers.....
10620 ;; This is used by C-c C-c for property action.
10621 (save-excursion
10622 (beginning-of-line 1)
10623 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10625 (defun org-get-property-block (&optional beg end force)
10626 "Return the (beg . end) range of the body of the property drawer.
10627 BEG and END can be beginning and end of subtree, if not given
10628 they will be found.
10629 If the drawer does not exist and FORCE is non-nil, create the drawer."
10630 (catch 'exit
10631 (save-excursion
10632 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10633 (end (or end (progn (outline-next-heading) (point)))))
10634 (goto-char beg)
10635 (if (re-search-forward org-property-start-re end t)
10636 (setq beg (1+ (match-end 0)))
10637 (if force
10638 (save-excursion
10639 (org-insert-property-drawer)
10640 (setq end (progn (outline-next-heading) (point))))
10641 (throw 'exit nil))
10642 (goto-char beg)
10643 (if (re-search-forward org-property-start-re end t)
10644 (setq beg (1+ (match-end 0)))))
10645 (if (re-search-forward org-property-end-re end t)
10646 (setq end (match-beginning 0))
10647 (or force (throw 'exit nil))
10648 (goto-char beg)
10649 (setq end beg)
10650 (org-indent-line-function)
10651 (insert ":END:\n"))
10652 (cons beg end)))))
10654 (defun org-entry-properties (&optional pom which)
10655 "Get all properties of the entry at point-or-marker POM.
10656 This includes the TODO keyword, the tags, time strings for deadline,
10657 scheduled, and clocking, and any additional properties defined in the
10658 entry. The return value is an alist, keys may occur multiple times
10659 if the property key was used several times.
10660 POM may also be nil, in which case the current entry is used.
10661 If WHICH is nil or `all', get all properties. If WHICH is
10662 `special' or `standard', only get that subclass."
10663 (setq which (or which 'all))
10664 (org-with-point-at pom
10665 (let ((clockstr (substring org-clock-string 0 -1))
10666 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10667 beg end range props sum-props key value string clocksum)
10668 (save-excursion
10669 (when (condition-case nil
10670 (and (org-mode-p) (org-back-to-heading t))
10671 (error nil))
10672 (setq beg (point))
10673 (setq sum-props (get-text-property (point) 'org-summaries))
10674 (setq clocksum (get-text-property (point) :org-clock-minutes))
10675 (outline-next-heading)
10676 (setq end (point))
10677 (when (memq which '(all special))
10678 ;; Get the special properties, like TODO and tags
10679 (goto-char beg)
10680 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10681 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10682 (when (looking-at org-priority-regexp)
10683 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10684 (when (and (setq value (org-get-tags-string))
10685 (string-match "\\S-" value))
10686 (push (cons "TAGS" value) props))
10687 (when (setq value (org-get-tags-at))
10688 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10689 props))
10690 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10691 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10692 string (if (equal key clockstr)
10693 (org-no-properties
10694 (org-trim
10695 (buffer-substring
10696 (match-beginning 3) (goto-char (point-at-eol)))))
10697 (substring (org-match-string-no-properties 3) 1 -1)))
10698 (unless key
10699 (if (= (char-after (match-beginning 3)) ?\[)
10700 (setq key "TIMESTAMP_IA")
10701 (setq key "TIMESTAMP")))
10702 (when (or (equal key clockstr) (not (assoc key props)))
10703 (push (cons key string) props)))
10707 (when (memq which '(all standard))
10708 ;; Get the standard properties, like :PORP: ...
10709 (setq range (org-get-property-block beg end))
10710 (when range
10711 (goto-char (car range))
10712 (while (re-search-forward
10713 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10714 (cdr range) t)
10715 (setq key (org-match-string-no-properties 1)
10716 value (org-trim (or (org-match-string-no-properties 2) "")))
10717 (unless (member key excluded)
10718 (push (cons key (or value "")) props)))))
10719 (if clocksum
10720 (push (cons "CLOCKSUM"
10721 (org-columns-number-to-string (/ (float clocksum) 60.)
10722 'add_times))
10723 props))
10724 (unless (assoc "CATEGORY" props)
10725 (setq value (or (org-get-category)
10726 (progn (org-refresh-category-properties)
10727 (org-get-category))))
10728 (push (cons "CATEGORY" value) props))
10729 (append sum-props (nreverse props)))))))
10731 (defun org-entry-get (pom property &optional inherit)
10732 "Get value of PROPERTY for entry at point-or-marker POM.
10733 If INHERIT is non-nil and the entry does not have the property,
10734 then also check higher levels of the hierarchy.
10735 If INHERIT is the symbol `selective', use inheritance only if the setting
10736 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10737 If the property is present but empty, the return value is the empty string.
10738 If the property is not present at all, nil is returned."
10739 (org-with-point-at pom
10740 (if (and inherit (if (eq inherit 'selective)
10741 (org-property-inherit-p property)
10743 (org-entry-get-with-inheritance property)
10744 (if (member property org-special-properties)
10745 ;; We need a special property. Use brute force, get all properties.
10746 (cdr (assoc property (org-entry-properties nil 'special)))
10747 (let ((range (org-get-property-block)))
10748 (if (and range
10749 (goto-char (car range))
10750 (re-search-forward
10751 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10752 (cdr range) t))
10753 ;; Found the property, return it.
10754 (if (match-end 1)
10755 (org-match-string-no-properties 1)
10756 "")))))))
10758 (defun org-property-or-variable-value (var &optional inherit)
10759 "Check if there is a property fixing the value of VAR.
10760 If yes, return this value. If not, return the current value of the variable."
10761 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10762 (if (and prop (stringp prop) (string-match "\\S-" prop))
10763 (read prop)
10764 (symbol-value var))))
10766 (defun org-entry-delete (pom property)
10767 "Delete the property PROPERTY from entry at point-or-marker POM."
10768 (org-with-point-at pom
10769 (if (member property org-special-properties)
10770 nil ; cannot delete these properties.
10771 (let ((range (org-get-property-block)))
10772 (if (and range
10773 (goto-char (car range))
10774 (re-search-forward
10775 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10776 (cdr range) t))
10777 (progn
10778 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10780 nil)))))
10782 ;; Multi-values properties are properties that contain multiple values
10783 ;; These values are assumed to be single words, separated by whitespace.
10784 (defun org-entry-add-to-multivalued-property (pom property value)
10785 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10786 (let* ((old (org-entry-get pom property))
10787 (values (and old (org-split-string old "[ \t]"))))
10788 (setq value (org-entry-protect-space value))
10789 (unless (member value values)
10790 (setq values (cons value values))
10791 (org-entry-put pom property
10792 (mapconcat 'identity values " ")))))
10794 (defun org-entry-remove-from-multivalued-property (pom property value)
10795 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10796 (let* ((old (org-entry-get pom property))
10797 (values (and old (org-split-string old "[ \t]"))))
10798 (setq value (org-entry-protect-space value))
10799 (when (member value values)
10800 (setq values (delete value values))
10801 (org-entry-put pom property
10802 (mapconcat 'identity values " ")))))
10804 (defun org-entry-member-in-multivalued-property (pom property value)
10805 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10806 (let* ((old (org-entry-get pom property))
10807 (values (and old (org-split-string old "[ \t]"))))
10808 (setq value (org-entry-protect-space value))
10809 (member value values)))
10811 (defun org-entry-get-multivalued-property (pom property)
10812 "Return a list of values in a multivalued property."
10813 (let* ((value (org-entry-get pom property))
10814 (values (and value (org-split-string value "[ \t]"))))
10815 (mapcar 'org-entry-restore-space values)))
10817 (defun org-entry-put-multivalued-property (pom property &rest values)
10818 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10819 VALUES should be a list of strings. Spaces will be protected."
10820 (org-entry-put pom property
10821 (mapconcat 'org-entry-protect-space values " "))
10822 (let* ((value (org-entry-get pom property))
10823 (values (and value (org-split-string value "[ \t]"))))
10824 (mapcar 'org-entry-restore-space values)))
10826 (defun org-entry-protect-space (s)
10827 "Protect spaces and newline in string S."
10828 (while (string-match " " s)
10829 (setq s (replace-match "%20" t t s)))
10830 (while (string-match "\n" s)
10831 (setq s (replace-match "%0A" t t s)))
10834 (defun org-entry-restore-space (s)
10835 "Restore spaces and newline in string S."
10836 (while (string-match "%20" s)
10837 (setq s (replace-match " " t t s)))
10838 (while (string-match "%0A" s)
10839 (setq s (replace-match "\n" t t s)))
10842 (defvar org-entry-property-inherited-from (make-marker)
10843 "Marker pointing to the entry from where a property was inherited.
10844 Each call to `org-entry-get-with-inheritance' will set this marker to the
10845 location of the entry where the inheritance search matched. If there was
10846 no match, the marker will point nowhere.
10847 Note that also `org-entry-get' calls this function, if the INHERIT flag
10848 is set.")
10850 (defun org-entry-get-with-inheritance (property)
10851 "Get entry property, and search higher levels if not present."
10852 (move-marker org-entry-property-inherited-from nil)
10853 (let (tmp)
10854 (save-excursion
10855 (save-restriction
10856 (widen)
10857 (catch 'ex
10858 (while t
10859 (when (setq tmp (org-entry-get nil property))
10860 (org-back-to-heading t)
10861 (move-marker org-entry-property-inherited-from (point))
10862 (throw 'ex tmp))
10863 (or (org-up-heading-safe) (throw 'ex nil)))))
10864 (or tmp
10865 (cdr (assoc property org-file-properties))
10866 (cdr (assoc property org-global-properties))
10867 (cdr (assoc property org-global-properties-fixed))))))
10869 (defun org-entry-put (pom property value)
10870 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10871 (org-with-point-at pom
10872 (org-back-to-heading t)
10873 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10874 range)
10875 (cond
10876 ((equal property "TODO")
10877 (when (and (stringp value) (string-match "\\S-" value)
10878 (not (member value org-todo-keywords-1)))
10879 (error "\"%s\" is not a valid TODO state" value))
10880 (if (or (not value)
10881 (not (string-match "\\S-" value)))
10882 (setq value 'none))
10883 (org-todo value)
10884 (org-set-tags nil 'align))
10885 ((equal property "PRIORITY")
10886 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10887 (string-to-char value) ?\ ))
10888 (org-set-tags nil 'align))
10889 ((equal property "SCHEDULED")
10890 (if (re-search-forward org-scheduled-time-regexp end t)
10891 (cond
10892 ((eq value 'earlier) (org-timestamp-change -1 'day))
10893 ((eq value 'later) (org-timestamp-change 1 'day))
10894 (t (call-interactively 'org-schedule)))
10895 (call-interactively 'org-schedule)))
10896 ((equal property "DEADLINE")
10897 (if (re-search-forward org-deadline-time-regexp end t)
10898 (cond
10899 ((eq value 'earlier) (org-timestamp-change -1 'day))
10900 ((eq value 'later) (org-timestamp-change 1 'day))
10901 (t (call-interactively 'org-deadline)))
10902 (call-interactively 'org-deadline)))
10903 ((member property org-special-properties)
10904 (error "The %s property can not yet be set with `org-entry-put'"
10905 property))
10906 (t ; a non-special property
10907 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10908 (setq range (org-get-property-block beg end 'force))
10909 (goto-char (car range))
10910 (if (re-search-forward
10911 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10912 (progn
10913 (delete-region (match-beginning 1) (match-end 1))
10914 (goto-char (match-beginning 1)))
10915 (goto-char (cdr range))
10916 (insert "\n")
10917 (backward-char 1)
10918 (org-indent-line-function)
10919 (insert ":" property ":"))
10920 (and value (insert " " value))
10921 (org-indent-line-function)))))))
10923 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10924 "Get all property keys in the current buffer.
10925 With INCLUDE-SPECIALS, also list the special properties that reflect things
10926 like tags and TODO state.
10927 With INCLUDE-DEFAULTS, also include properties that has special meaning
10928 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10929 With INCLUDE-COLUMNS, also include property names given in COLUMN
10930 formats in the current buffer."
10931 (let (rtn range cfmt s p)
10932 (save-excursion
10933 (save-restriction
10934 (widen)
10935 (goto-char (point-min))
10936 (while (re-search-forward org-property-start-re nil t)
10937 (setq range (org-get-property-block))
10938 (goto-char (car range))
10939 (while (re-search-forward
10940 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10941 (cdr range) t)
10942 (add-to-list 'rtn (org-match-string-no-properties 1)))
10943 (outline-next-heading))))
10945 (when include-specials
10946 (setq rtn (append org-special-properties rtn)))
10948 (when include-defaults
10949 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10951 (when include-columns
10952 (save-excursion
10953 (save-restriction
10954 (widen)
10955 (goto-char (point-min))
10956 (while (re-search-forward
10957 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10958 nil t)
10959 (setq cfmt (match-string 2) s 0)
10960 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10961 cfmt s)
10962 (setq s (match-end 0)
10963 p (match-string 1 cfmt))
10964 (unless (or (equal p "ITEM")
10965 (member p org-special-properties))
10966 (add-to-list 'rtn (match-string 1 cfmt))))))))
10968 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10970 (defun org-property-values (key)
10971 "Return a list of all values of property KEY."
10972 (save-excursion
10973 (save-restriction
10974 (widen)
10975 (goto-char (point-min))
10976 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10977 values)
10978 (while (re-search-forward re nil t)
10979 (add-to-list 'values (org-trim (match-string 1))))
10980 (delete "" values)))))
10982 (defun org-insert-property-drawer ()
10983 "Insert a property drawer into the current entry."
10984 (interactive)
10985 (org-back-to-heading t)
10986 (looking-at outline-regexp)
10987 (let ((indent (- (match-end 0)(match-beginning 0)))
10988 (beg (point))
10989 (re (concat "^[ \t]*" org-keyword-time-regexp))
10990 end hiddenp)
10991 (outline-next-heading)
10992 (setq end (point))
10993 (goto-char beg)
10994 (while (re-search-forward re end t))
10995 (setq hiddenp (org-invisible-p))
10996 (end-of-line 1)
10997 (and (equal (char-after) ?\n) (forward-char 1))
10998 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
10999 (if (member (match-string 1) '("CLOCK:" ":END:"))
11000 ;; just skip this line
11001 (beginning-of-line 2)
11002 ;; Drawer start, find the end
11003 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11004 (beginning-of-line 1)))
11005 (org-skip-over-state-notes)
11006 (skip-chars-backward " \t\n\r")
11007 (if (eq (char-before) ?*) (forward-char 1))
11008 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11009 (beginning-of-line 0)
11010 (org-indent-to-column indent)
11011 (beginning-of-line 2)
11012 (org-indent-to-column indent)
11013 (beginning-of-line 0)
11014 (if hiddenp
11015 (save-excursion
11016 (org-back-to-heading t)
11017 (hide-entry))
11018 (org-flag-drawer t))))
11020 (defun org-set-property (property value)
11021 "In the current entry, set PROPERTY to VALUE.
11022 When called interactively, this will prompt for a property name, offering
11023 completion on existing and default properties. And then it will prompt
11024 for a value, offering completion either on allowed values (via an inherited
11025 xxx_ALL property) or on existing values in other instances of this property
11026 in the current file."
11027 (interactive
11028 (let* ((completion-ignore-case t)
11029 (keys (org-buffer-property-keys nil t t))
11030 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11031 (prop (if (member prop0 keys)
11032 prop0
11033 (or (cdr (assoc (downcase prop0)
11034 (mapcar (lambda (x) (cons (downcase x) x))
11035 keys)))
11036 prop0)))
11037 (cur (org-entry-get nil prop))
11038 (allowed (org-property-get-allowed-values nil prop 'table))
11039 (existing (mapcar 'list (org-property-values prop)))
11040 (val (if allowed
11041 (org-completing-read "Value: " allowed nil 'req-match)
11042 (org-completing-read
11043 (concat "Value" (if (and cur (string-match "\\S-" cur))
11044 (concat "[" cur "]") "")
11045 ": ")
11046 existing nil nil "" nil cur))))
11047 (list prop (if (equal val "") cur val))))
11048 (unless (equal (org-entry-get nil property) value)
11049 (org-entry-put nil property value)))
11051 (defun org-delete-property (property)
11052 "In the current entry, delete PROPERTY."
11053 (interactive
11054 (let* ((completion-ignore-case t)
11055 (prop (org-ido-completing-read
11056 "Property: " (org-entry-properties nil 'standard))))
11057 (list prop)))
11058 (message "Property %s %s" property
11059 (if (org-entry-delete nil property)
11060 "deleted"
11061 "was not present in the entry")))
11063 (defun org-delete-property-globally (property)
11064 "Remove PROPERTY globally, from all entries."
11065 (interactive
11066 (let* ((completion-ignore-case t)
11067 (prop (org-ido-completing-read
11068 "Globally remove property: "
11069 (mapcar 'list (org-buffer-property-keys)))))
11070 (list prop)))
11071 (save-excursion
11072 (save-restriction
11073 (widen)
11074 (goto-char (point-min))
11075 (let ((cnt 0))
11076 (while (re-search-forward
11077 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11078 nil t)
11079 (setq cnt (1+ cnt))
11080 (replace-match ""))
11081 (message "Property \"%s\" removed from %d entries" property cnt)))))
11083 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11085 (defun org-compute-property-at-point ()
11086 "Compute the property at point.
11087 This looks for an enclosing column format, extracts the operator and
11088 then applies it to the property in the column format's scope."
11089 (interactive)
11090 (unless (org-at-property-p)
11091 (error "Not at a property"))
11092 (let ((prop (org-match-string-no-properties 2)))
11093 (org-columns-get-format-and-top-level)
11094 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11095 (error "No operator defined for property %s" prop))
11096 (org-columns-compute prop)))
11098 (defun org-property-get-allowed-values (pom property &optional table)
11099 "Get allowed values for the property PROPERTY.
11100 When TABLE is non-nil, return an alist that can directly be used for
11101 completion."
11102 (let (vals)
11103 (cond
11104 ((equal property "TODO")
11105 (setq vals (org-with-point-at pom
11106 (append org-todo-keywords-1 '("")))))
11107 ((equal property "PRIORITY")
11108 (let ((n org-lowest-priority))
11109 (while (>= n org-highest-priority)
11110 (push (char-to-string n) vals)
11111 (setq n (1- n)))))
11112 ((member property org-special-properties))
11114 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11116 (when (and vals (string-match "\\S-" vals))
11117 (setq vals (car (read-from-string (concat "(" vals ")"))))
11118 (setq vals (mapcar (lambda (x)
11119 (cond ((stringp x) x)
11120 ((numberp x) (number-to-string x))
11121 ((symbolp x) (symbol-name x))
11122 (t "???")))
11123 vals)))))
11124 (if table (mapcar 'list vals) vals)))
11126 (defun org-property-previous-allowed-value (&optional previous)
11127 "Switch to the next allowed value for this property."
11128 (interactive)
11129 (org-property-next-allowed-value t))
11131 (defun org-property-next-allowed-value (&optional previous)
11132 "Switch to the next allowed value for this property."
11133 (interactive)
11134 (unless (org-at-property-p)
11135 (error "Not at a property"))
11136 (let* ((key (match-string 2))
11137 (value (match-string 3))
11138 (allowed (or (org-property-get-allowed-values (point) key)
11139 (and (member value '("[ ]" "[-]" "[X]"))
11140 '("[ ]" "[X]"))))
11141 nval)
11142 (unless allowed
11143 (error "Allowed values for this property have not been defined"))
11144 (if previous (setq allowed (reverse allowed)))
11145 (if (member value allowed)
11146 (setq nval (car (cdr (member value allowed)))))
11147 (setq nval (or nval (car allowed)))
11148 (if (equal nval value)
11149 (error "Only one allowed value for this property"))
11150 (org-at-property-p)
11151 (replace-match (concat " :" key ": " nval) t t)
11152 (org-indent-line-function)
11153 (beginning-of-line 1)
11154 (skip-chars-forward " \t")))
11156 (defun org-find-entry-with-id (ident)
11157 "Locate the entry that contains the ID property with exact value IDENT.
11158 IDENT can be a string, a symbol or a number, this function will search for
11159 the string representation of it.
11160 Return the position where this entry starts, or nil if there is no such entry."
11161 (interactive "sID: ")
11162 (let ((id (cond
11163 ((stringp ident) ident)
11164 ((symbol-name ident) (symbol-name ident))
11165 ((numberp ident) (number-to-string ident))
11166 (t (error "IDENT %s must be a string, symbol or number" ident))))
11167 (case-fold-search nil))
11168 (save-excursion
11169 (save-restriction
11170 (widen)
11171 (goto-char (point-min))
11172 (when (re-search-forward
11173 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11174 nil t)
11175 (org-back-to-heading)
11176 (point))))))
11178 ;;;; Timestamps
11180 (defvar org-last-changed-timestamp nil)
11181 (defvar org-last-inserted-timestamp nil
11182 "The last time stamp inserted with `org-insert-time-stamp'.")
11183 (defvar org-time-was-given) ; dynamically scoped parameter
11184 (defvar org-end-time-was-given) ; dynamically scoped parameter
11185 (defvar org-ts-what) ; dynamically scoped parameter
11187 (defun org-time-stamp (arg &optional inactive)
11188 "Prompt for a date/time and insert a time stamp.
11189 If the user specifies a time like HH:MM, or if this command is called
11190 with a prefix argument, the time stamp will contain date and time.
11191 Otherwise, only the date will be included. All parts of a date not
11192 specified by the user will be filled in from the current date/time.
11193 So if you press just return without typing anything, the time stamp
11194 will represent the current date/time. If there is already a timestamp
11195 at the cursor, it will be modified."
11196 (interactive "P")
11197 (let* ((ts nil)
11198 (default-time
11199 ;; Default time is either today, or, when entering a range,
11200 ;; the range start.
11201 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11202 (save-excursion
11203 (re-search-backward
11204 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11205 (- (point) 20) t)))
11206 (apply 'encode-time (org-parse-time-string (match-string 1)))
11207 (current-time)))
11208 (default-input (and ts (org-get-compact-tod ts)))
11209 org-time-was-given org-end-time-was-given time)
11210 (cond
11211 ((and (org-at-timestamp-p t)
11212 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11213 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11214 (insert "--")
11215 (setq time (let ((this-command this-command))
11216 (org-read-date arg 'totime nil nil
11217 default-time default-input)))
11218 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11219 ((org-at-timestamp-p t)
11220 (setq time (let ((this-command this-command))
11221 (org-read-date arg 'totime nil nil default-time default-input)))
11222 (when (org-at-timestamp-p t) ; just to get the match data
11223 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11224 (replace-match "")
11225 (setq org-last-changed-timestamp
11226 (org-insert-time-stamp
11227 time (or org-time-was-given arg)
11228 inactive nil nil (list org-end-time-was-given))))
11229 (message "Timestamp updated"))
11231 (setq time (let ((this-command this-command))
11232 (org-read-date arg 'totime nil nil default-time default-input)))
11233 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11234 nil nil (list org-end-time-was-given))))))
11236 ;; FIXME: can we use this for something else, like computing time differences?
11237 (defun org-get-compact-tod (s)
11238 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11239 (let* ((t1 (match-string 1 s))
11240 (h1 (string-to-number (match-string 2 s)))
11241 (m1 (string-to-number (match-string 3 s)))
11242 (t2 (and (match-end 4) (match-string 5 s)))
11243 (h2 (and t2 (string-to-number (match-string 6 s))))
11244 (m2 (and t2 (string-to-number (match-string 7 s))))
11245 dh dm)
11246 (if (not t2)
11248 (setq dh (- h2 h1) dm (- m2 m1))
11249 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11250 (concat t1 "+" (number-to-string dh)
11251 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11253 (defun org-time-stamp-inactive (&optional arg)
11254 "Insert an inactive time stamp.
11255 An inactive time stamp is enclosed in square brackets instead of angle
11256 brackets. It is inactive in the sense that it does not trigger agenda entries,
11257 does not link to the calendar and cannot be changed with the S-cursor keys.
11258 So these are more for recording a certain time/date."
11259 (interactive "P")
11260 (org-time-stamp arg 'inactive))
11262 (defvar org-date-ovl (org-make-overlay 1 1))
11263 (org-overlay-put org-date-ovl 'face 'org-warning)
11264 (org-detach-overlay org-date-ovl)
11266 (defvar org-ans1) ; dynamically scoped parameter
11267 (defvar org-ans2) ; dynamically scoped parameter
11269 (defvar org-plain-time-of-day-regexp) ; defined below
11271 (defvar org-overriding-default-time nil) ; dynamically scoped
11272 (defvar org-read-date-overlay nil)
11273 (defvar org-dcst nil) ; dynamically scoped
11275 (defun org-read-date (&optional with-time to-time from-string prompt
11276 default-time default-input)
11277 "Read a date, possibly a time, and make things smooth for the user.
11278 The prompt will suggest to enter an ISO date, but you can also enter anything
11279 which will at least partially be understood by `parse-time-string'.
11280 Unrecognized parts of the date will default to the current day, month, year,
11281 hour and minute. If this command is called to replace a timestamp at point,
11282 of to enter the second timestamp of a range, the default time is taken from the
11283 existing stamp. For example,
11284 3-2-5 --> 2003-02-05
11285 feb 15 --> currentyear-02-15
11286 sep 12 9 --> 2009-09-12
11287 12:45 --> today 12:45
11288 22 sept 0:34 --> currentyear-09-22 0:34
11289 12 --> currentyear-currentmonth-12
11290 Fri --> nearest Friday (today or later)
11291 etc.
11293 Furthermore you can specify a relative date by giving, as the *first* thing
11294 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11295 change in days weeks, months, years.
11296 With a single plus or minus, the date is relative to today. With a double
11297 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11298 +4d --> four days from today
11299 +4 --> same as above
11300 +2w --> two weeks from today
11301 ++5 --> five days from default date
11303 The function understands only English month and weekday abbreviations,
11304 but this can be configured with the variables `parse-time-months' and
11305 `parse-time-weekdays'.
11307 While prompting, a calendar is popped up - you can also select the
11308 date with the mouse (button 1). The calendar shows a period of three
11309 months. To scroll it to other months, use the keys `>' and `<'.
11310 If you don't like the calendar, turn it off with
11311 \(setq org-read-date-popup-calendar nil)
11313 With optional argument TO-TIME, the date will immediately be converted
11314 to an internal time.
11315 With an optional argument WITH-TIME, the prompt will suggest to also
11316 insert a time. Note that when WITH-TIME is not set, you can still
11317 enter a time, and this function will inform the calling routine about
11318 this change. The calling routine may then choose to change the format
11319 used to insert the time stamp into the buffer to include the time.
11320 With optional argument FROM-STRING, read from this string instead from
11321 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11322 the time/date that is used for everything that is not specified by the
11323 user."
11324 (require 'parse-time)
11325 (let* ((org-time-stamp-rounding-minutes
11326 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11327 (org-dcst org-display-custom-times)
11328 (ct (org-current-time))
11329 (def (or org-overriding-default-time default-time ct))
11330 (defdecode (decode-time def))
11331 (dummy (progn
11332 (when (< (nth 2 defdecode) org-extend-today-until)
11333 (setcar (nthcdr 2 defdecode) -1)
11334 (setcar (nthcdr 1 defdecode) 59)
11335 (setq def (apply 'encode-time defdecode)
11336 defdecode (decode-time def)))))
11337 (calendar-move-hook nil)
11338 (calendar-view-diary-initially-flag nil)
11339 (view-diary-entries-initially nil)
11340 (calendar-view-holidays-initially-flag nil)
11341 (view-calendar-holidays-initially nil)
11342 (timestr (format-time-string
11343 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11344 (prompt (concat (if prompt (concat prompt " ") "")
11345 (format "Date+time [%s]: " timestr)))
11346 ans (org-ans0 "") org-ans1 org-ans2 final)
11348 (cond
11349 (from-string (setq ans from-string))
11350 (org-read-date-popup-calendar
11351 (save-excursion
11352 (save-window-excursion
11353 (calendar)
11354 (calendar-forward-day (- (time-to-days def)
11355 (calendar-absolute-from-gregorian
11356 (calendar-current-date))))
11357 (org-eval-in-calendar nil t)
11358 (let* ((old-map (current-local-map))
11359 (map (copy-keymap calendar-mode-map))
11360 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11361 (org-defkey map (kbd "RET") 'org-calendar-select)
11362 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11363 'org-calendar-select-mouse)
11364 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11365 'org-calendar-select-mouse)
11366 (org-defkey minibuffer-local-map [(meta shift left)]
11367 (lambda () (interactive)
11368 (org-eval-in-calendar '(calendar-backward-month 1))))
11369 (org-defkey minibuffer-local-map [(meta shift right)]
11370 (lambda () (interactive)
11371 (org-eval-in-calendar '(calendar-forward-month 1))))
11372 (org-defkey minibuffer-local-map [(meta shift up)]
11373 (lambda () (interactive)
11374 (org-eval-in-calendar '(calendar-backward-year 1))))
11375 (org-defkey minibuffer-local-map [(meta shift down)]
11376 (lambda () (interactive)
11377 (org-eval-in-calendar '(calendar-forward-year 1))))
11378 (org-defkey minibuffer-local-map [(shift up)]
11379 (lambda () (interactive)
11380 (org-eval-in-calendar '(calendar-backward-week 1))))
11381 (org-defkey minibuffer-local-map [(shift down)]
11382 (lambda () (interactive)
11383 (org-eval-in-calendar '(calendar-forward-week 1))))
11384 (org-defkey minibuffer-local-map [(shift left)]
11385 (lambda () (interactive)
11386 (org-eval-in-calendar '(calendar-backward-day 1))))
11387 (org-defkey minibuffer-local-map [(shift right)]
11388 (lambda () (interactive)
11389 (org-eval-in-calendar '(calendar-forward-day 1))))
11390 (org-defkey minibuffer-local-map ">"
11391 (lambda () (interactive)
11392 (org-eval-in-calendar '(scroll-calendar-left 1))))
11393 (org-defkey minibuffer-local-map "<"
11394 (lambda () (interactive)
11395 (org-eval-in-calendar '(scroll-calendar-right 1))))
11396 (unwind-protect
11397 (progn
11398 (use-local-map map)
11399 (add-hook 'post-command-hook 'org-read-date-display)
11400 (setq org-ans0 (read-string prompt default-input nil nil))
11401 ;; org-ans0: from prompt
11402 ;; org-ans1: from mouse click
11403 ;; org-ans2: from calendar motion
11404 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11405 (remove-hook 'post-command-hook 'org-read-date-display)
11406 (use-local-map old-map)
11407 (when org-read-date-overlay
11408 (org-delete-overlay org-read-date-overlay)
11409 (setq org-read-date-overlay nil)))))))
11411 (t ; Naked prompt only
11412 (unwind-protect
11413 (setq ans (read-string prompt default-input nil timestr))
11414 (when org-read-date-overlay
11415 (org-delete-overlay org-read-date-overlay)
11416 (setq org-read-date-overlay nil)))))
11418 (setq final (org-read-date-analyze ans def defdecode))
11420 (if to-time
11421 (apply 'encode-time final)
11422 (if (and (boundp 'org-time-was-given) org-time-was-given)
11423 (format "%04d-%02d-%02d %02d:%02d"
11424 (nth 5 final) (nth 4 final) (nth 3 final)
11425 (nth 2 final) (nth 1 final))
11426 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11427 (defvar def)
11428 (defvar defdecode)
11429 (defvar with-time)
11430 (defun org-read-date-display ()
11431 "Display the current date prompt interpretation in the minibuffer."
11432 (when org-read-date-display-live
11433 (when org-read-date-overlay
11434 (org-delete-overlay org-read-date-overlay))
11435 (let ((p (point)))
11436 (end-of-line 1)
11437 (while (not (equal (buffer-substring
11438 (max (point-min) (- (point) 4)) (point))
11439 " "))
11440 (insert " "))
11441 (goto-char p))
11442 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11443 " " (or org-ans1 org-ans2)))
11444 (org-end-time-was-given nil)
11445 (f (org-read-date-analyze ans def defdecode))
11446 (fmts (if org-dcst
11447 org-time-stamp-custom-formats
11448 org-time-stamp-formats))
11449 (fmt (if (or with-time
11450 (and (boundp 'org-time-was-given) org-time-was-given))
11451 (cdr fmts)
11452 (car fmts)))
11453 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11454 (when (and org-end-time-was-given
11455 (string-match org-plain-time-of-day-regexp txt))
11456 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11457 org-end-time-was-given
11458 (substring txt (match-end 0)))))
11459 (setq org-read-date-overlay
11460 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11461 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11463 (defun org-read-date-analyze (ans def defdecode)
11464 "Analyse the combined answer of the date prompt."
11465 ;; FIXME: cleanup and comment
11466 (let (delta deltan deltaw deltadef year month day
11467 hour minute second wday pm h2 m2 tl wday1
11468 iso-year iso-weekday iso-week iso-year iso-date)
11470 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11471 (setq ans "+0"))
11473 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11474 (setq ans (replace-match "" t t ans)
11475 deltan (car delta)
11476 deltaw (nth 1 delta)
11477 deltadef (nth 2 delta)))
11479 ;; Check if there is an iso week date in there
11480 ;; If yes, sore the info and postpone interpreting it until the rest
11481 ;; of the parsing is done
11482 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11483 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11484 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11485 iso-week (string-to-number (match-string 2 ans)))
11486 (setq ans (replace-match "" t t ans)))
11488 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11489 (when (string-match
11490 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11491 (setq year (if (match-end 2)
11492 (string-to-number (match-string 2 ans))
11493 (string-to-number (format-time-string "%Y")))
11494 month (string-to-number (match-string 3 ans))
11495 day (string-to-number (match-string 4 ans)))
11496 (if (< year 100) (setq year (+ 2000 year)))
11497 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11498 t nil ans)))
11499 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11500 ;; If there is a time with am/pm, and *no* time without it, we convert
11501 ;; so that matching will be successful.
11502 (loop for i from 1 to 2 do ; twice, for end time as well
11503 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11504 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11505 (setq hour (string-to-number (match-string 1 ans))
11506 minute (if (match-end 3)
11507 (string-to-number (match-string 3 ans))
11509 pm (equal ?p
11510 (string-to-char (downcase (match-string 4 ans)))))
11511 (if (and (= hour 12) (not pm))
11512 (setq hour 0)
11513 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11514 (setq ans (replace-match (format "%02d:%02d" hour minute)
11515 t t ans))))
11517 ;; Check if a time range is given as a duration
11518 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11519 (setq hour (string-to-number (match-string 1 ans))
11520 h2 (+ hour (string-to-number (match-string 3 ans)))
11521 minute (string-to-number (match-string 2 ans))
11522 m2 (+ minute (if (match-end 5) (string-to-number
11523 (match-string 5 ans))0)))
11524 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11525 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11526 t t ans)))
11528 ;; Check if there is a time range
11529 (when (boundp 'org-end-time-was-given)
11530 (setq org-time-was-given nil)
11531 (when (and (string-match org-plain-time-of-day-regexp ans)
11532 (match-end 8))
11533 (setq org-end-time-was-given (match-string 8 ans))
11534 (setq ans (concat (substring ans 0 (match-beginning 7))
11535 (substring ans (match-end 7))))))
11537 (setq tl (parse-time-string ans)
11538 day (or (nth 3 tl) (nth 3 defdecode))
11539 month (or (nth 4 tl)
11540 (if (and org-read-date-prefer-future
11541 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11542 (1+ (nth 4 defdecode))
11543 (nth 4 defdecode)))
11544 year (or (nth 5 tl)
11545 (if (and org-read-date-prefer-future
11546 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11547 (1+ (nth 5 defdecode))
11548 (nth 5 defdecode)))
11549 hour (or (nth 2 tl) (nth 2 defdecode))
11550 minute (or (nth 1 tl) (nth 1 defdecode))
11551 second (or (nth 0 tl) 0)
11552 wday (nth 6 tl))
11554 ;; Special date definitions below
11555 (cond
11556 (iso-week
11557 ;; There was an iso week
11558 (setq year (or iso-year year)
11559 day (or iso-weekday wday 1)
11560 wday nil ; to make sure that the trigger below does not match
11561 iso-date (calendar-gregorian-from-absolute
11562 (calendar-absolute-from-iso
11563 (list iso-week day year))))
11564 ; FIXME: Should we also push ISO weeks into the future?
11565 ; (when (and org-read-date-prefer-future
11566 ; (not iso-year)
11567 ; (< (calendar-absolute-from-gregorian iso-date)
11568 ; (time-to-days (current-time))))
11569 ; (setq year (1+ year)
11570 ; iso-date (calendar-gregorian-from-absolute
11571 ; (calendar-absolute-from-iso
11572 ; (list iso-week day year)))))
11573 (setq month (car iso-date)
11574 year (nth 2 iso-date)
11575 day (nth 1 iso-date)))
11576 (deltan
11577 (unless deltadef
11578 (let ((now (decode-time (current-time))))
11579 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11580 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11581 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11582 ((equal deltaw "m") (setq month (+ month deltan)))
11583 ((equal deltaw "y") (setq year (+ year deltan)))))
11584 ((and wday (not (nth 3 tl)))
11585 ;; Weekday was given, but no day, so pick that day in the week
11586 ;; on or after the derived date.
11587 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11588 (unless (equal wday wday1)
11589 (setq day (+ day (% (- wday wday1 -7) 7))))))
11590 (if (and (boundp 'org-time-was-given)
11591 (nth 2 tl))
11592 (setq org-time-was-given t))
11593 (if (< year 100) (setq year (+ 2000 year)))
11594 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11595 (list second minute hour day month year)))
11597 (defvar parse-time-weekdays)
11599 (defun org-read-date-get-relative (s today default)
11600 "Check string S for special relative date string.
11601 TODAY and DEFAULT are internal times, for today and for a default.
11602 Return shift list (N what def-flag)
11603 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11604 N is the number of WHATs to shift.
11605 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11606 the DEFAULT date rather than TODAY."
11607 (when (and
11608 (string-match
11609 (concat
11610 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11611 "\\([0-9]+\\)?"
11612 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11613 "\\([ \t]\\|$\\)") s)
11614 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11615 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11616 (string-to-char (substring (match-string 1 s) -1))
11617 ?+))
11618 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11619 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11620 (what (if (match-end 3) (match-string 3 s) "d"))
11621 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11622 (date (if rel default today))
11623 (wday (nth 6 (decode-time date)))
11624 delta)
11625 (if wday1
11626 (progn
11627 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11628 (if (= dir ?-) (setq delta (- delta 7)))
11629 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11630 (list delta "d" rel))
11631 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11633 (defun org-eval-in-calendar (form &optional keepdate)
11634 "Eval FORM in the calendar window and return to current window.
11635 Also, store the cursor date in variable org-ans2."
11636 (let ((sw (selected-window)))
11637 (select-window (get-buffer-window "*Calendar*"))
11638 (eval form)
11639 (when (and (not keepdate) (calendar-cursor-to-date))
11640 (let* ((date (calendar-cursor-to-date))
11641 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11642 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11643 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11644 (select-window sw)))
11646 (defun org-calendar-select ()
11647 "Return to `org-read-date' with the date currently selected.
11648 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11649 (interactive)
11650 (when (calendar-cursor-to-date)
11651 (let* ((date (calendar-cursor-to-date))
11652 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11653 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11654 (if (active-minibuffer-window) (exit-minibuffer))))
11656 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11657 "Insert a date stamp for the date given by the internal TIME.
11658 WITH-HM means, use the stamp format that includes the time of the day.
11659 INACTIVE means use square brackets instead of angular ones, so that the
11660 stamp will not contribute to the agenda.
11661 PRE and POST are optional strings to be inserted before and after the
11662 stamp.
11663 The command returns the inserted time stamp."
11664 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11665 stamp)
11666 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11667 (insert-before-markers (or pre ""))
11668 (insert-before-markers (setq stamp (format-time-string fmt time)))
11669 (when (listp extra)
11670 (setq extra (car extra))
11671 (if (and (stringp extra)
11672 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11673 (setq extra (format "-%02d:%02d"
11674 (string-to-number (match-string 1 extra))
11675 (string-to-number (match-string 2 extra))))
11676 (setq extra nil)))
11677 (when extra
11678 (backward-char 1)
11679 (insert-before-markers extra)
11680 (forward-char 1))
11681 (insert-before-markers (or post ""))
11682 (setq org-last-inserted-timestamp stamp)))
11684 (defun org-toggle-time-stamp-overlays ()
11685 "Toggle the use of custom time stamp formats."
11686 (interactive)
11687 (setq org-display-custom-times (not org-display-custom-times))
11688 (unless org-display-custom-times
11689 (let ((p (point-min)) (bmp (buffer-modified-p)))
11690 (while (setq p (next-single-property-change p 'display))
11691 (if (and (get-text-property p 'display)
11692 (eq (get-text-property p 'face) 'org-date))
11693 (remove-text-properties
11694 p (setq p (next-single-property-change p 'display))
11695 '(display t))))
11696 (set-buffer-modified-p bmp)))
11697 (if (featurep 'xemacs)
11698 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11699 (org-restart-font-lock)
11700 (setq org-table-may-need-update t)
11701 (if org-display-custom-times
11702 (message "Time stamps are overlayed with custom format")
11703 (message "Time stamp overlays removed")))
11705 (defun org-display-custom-time (beg end)
11706 "Overlay modified time stamp format over timestamp between BEG and END."
11707 (let* ((ts (buffer-substring beg end))
11708 t1 w1 with-hm tf time str w2 (off 0))
11709 (save-match-data
11710 (setq t1 (org-parse-time-string ts t))
11711 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11712 (setq off (- (match-end 0) (match-beginning 0)))))
11713 (setq end (- end off))
11714 (setq w1 (- end beg)
11715 with-hm (and (nth 1 t1) (nth 2 t1))
11716 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11717 time (org-fix-decoded-time t1)
11718 str (org-add-props
11719 (format-time-string
11720 (substring tf 1 -1) (apply 'encode-time time))
11721 nil 'mouse-face 'highlight)
11722 w2 (length str))
11723 (if (not (= w2 w1))
11724 (add-text-properties (1+ beg) (+ 2 beg)
11725 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11726 (if (featurep 'xemacs)
11727 (progn
11728 (put-text-property beg end 'invisible t)
11729 (put-text-property beg end 'end-glyph (make-glyph str)))
11730 (put-text-property beg end 'display str))))
11732 (defun org-translate-time (string)
11733 "Translate all timestamps in STRING to custom format.
11734 But do this only if the variable `org-display-custom-times' is set."
11735 (when org-display-custom-times
11736 (save-match-data
11737 (let* ((start 0)
11738 (re org-ts-regexp-both)
11739 t1 with-hm inactive tf time str beg end)
11740 (while (setq start (string-match re string start))
11741 (setq beg (match-beginning 0)
11742 end (match-end 0)
11743 t1 (save-match-data
11744 (org-parse-time-string (substring string beg end) t))
11745 with-hm (and (nth 1 t1) (nth 2 t1))
11746 inactive (equal (substring string beg (1+ beg)) "[")
11747 tf (funcall (if with-hm 'cdr 'car)
11748 org-time-stamp-custom-formats)
11749 time (org-fix-decoded-time t1)
11750 str (format-time-string
11751 (concat
11752 (if inactive "[" "<") (substring tf 1 -1)
11753 (if inactive "]" ">"))
11754 (apply 'encode-time time))
11755 string (replace-match str t t string)
11756 start (+ start (length str)))))))
11757 string)
11759 (defun org-fix-decoded-time (time)
11760 "Set 0 instead of nil for the first 6 elements of time.
11761 Don't touch the rest."
11762 (let ((n 0))
11763 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11765 (defun org-days-to-time (timestamp-string)
11766 "Difference between TIMESTAMP-STRING and now in days."
11767 (- (time-to-days (org-time-string-to-time timestamp-string))
11768 (time-to-days (current-time))))
11770 (defun org-deadline-close (timestamp-string &optional ndays)
11771 "Is the time in TIMESTAMP-STRING close to the current date?"
11772 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11773 (and (< (org-days-to-time timestamp-string) ndays)
11774 (not (org-entry-is-done-p))))
11776 (defun org-get-wdays (ts)
11777 "Get the deadline lead time appropriate for timestring TS."
11778 (cond
11779 ((<= org-deadline-warning-days 0)
11780 ;; 0 or negative, enforce this value no matter what
11781 (- org-deadline-warning-days))
11782 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
11783 ;; lead time is specified.
11784 (floor (* (string-to-number (match-string 1 ts))
11785 (cdr (assoc (match-string 2 ts)
11786 '(("d" . 1) ("w" . 7)
11787 ("m" . 30.4) ("y" . 365.25)))))))
11788 ;; go for the default.
11789 (t org-deadline-warning-days)))
11791 (defun org-calendar-select-mouse (ev)
11792 "Return to `org-read-date' with the date currently selected.
11793 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11794 (interactive "e")
11795 (mouse-set-point ev)
11796 (when (calendar-cursor-to-date)
11797 (let* ((date (calendar-cursor-to-date))
11798 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11799 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11800 (if (active-minibuffer-window) (exit-minibuffer))))
11802 (defun org-check-deadlines (ndays)
11803 "Check if there are any deadlines due or past due.
11804 A deadline is considered due if it happens within `org-deadline-warning-days'
11805 days from today's date. If the deadline appears in an entry marked DONE,
11806 it is not shown. The prefix arg NDAYS can be used to test that many
11807 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11808 (interactive "P")
11809 (let* ((org-warn-days
11810 (cond
11811 ((equal ndays '(4)) 100000)
11812 (ndays (prefix-numeric-value ndays))
11813 (t (abs org-deadline-warning-days))))
11814 (case-fold-search nil)
11815 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11816 (callback
11817 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11819 (message "%d deadlines past-due or due within %d days"
11820 (org-occur regexp nil callback)
11821 org-warn-days)))
11823 (defun org-check-before-date (date)
11824 "Check if there are deadlines or scheduled entries before DATE."
11825 (interactive (list (org-read-date)))
11826 (let ((case-fold-search nil)
11827 (regexp (concat "\\<\\(" org-deadline-string
11828 "\\|" org-scheduled-string
11829 "\\) *<\\([^>]+\\)>"))
11830 (callback
11831 (lambda () (time-less-p
11832 (org-time-string-to-time (match-string 2))
11833 (org-time-string-to-time date)))))
11834 (message "%d entries before %s"
11835 (org-occur regexp nil callback) date)))
11837 (defun org-evaluate-time-range (&optional to-buffer)
11838 "Evaluate a time range by computing the difference between start and end.
11839 Normally the result is just printed in the echo area, but with prefix arg
11840 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11841 If the time range is actually in a table, the result is inserted into the
11842 next column.
11843 For time difference computation, a year is assumed to be exactly 365
11844 days in order to avoid rounding problems."
11845 (interactive "P")
11847 (org-clock-update-time-maybe)
11848 (save-excursion
11849 (unless (org-at-date-range-p t)
11850 (goto-char (point-at-bol))
11851 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11852 (if (not (org-at-date-range-p t))
11853 (error "Not at a time-stamp range, and none found in current line")))
11854 (let* ((ts1 (match-string 1))
11855 (ts2 (match-string 2))
11856 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11857 (match-end (match-end 0))
11858 (time1 (org-time-string-to-time ts1))
11859 (time2 (org-time-string-to-time ts2))
11860 (t1 (time-to-seconds time1))
11861 (t2 (time-to-seconds time2))
11862 (diff (abs (- t2 t1)))
11863 (negative (< (- t2 t1) 0))
11864 ;; (ys (floor (* 365 24 60 60)))
11865 (ds (* 24 60 60))
11866 (hs (* 60 60))
11867 (fy "%dy %dd %02d:%02d")
11868 (fy1 "%dy %dd")
11869 (fd "%dd %02d:%02d")
11870 (fd1 "%dd")
11871 (fh "%02d:%02d")
11872 y d h m align)
11873 (if havetime
11874 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11876 d (floor (/ diff ds)) diff (mod diff ds)
11877 h (floor (/ diff hs)) diff (mod diff hs)
11878 m (floor (/ diff 60)))
11879 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11881 d (floor (+ (/ diff ds) 0.5))
11882 h 0 m 0))
11883 (if (not to-buffer)
11884 (message "%s" (org-make-tdiff-string y d h m))
11885 (if (org-at-table-p)
11886 (progn
11887 (goto-char match-end)
11888 (setq align t)
11889 (and (looking-at " *|") (goto-char (match-end 0))))
11890 (goto-char match-end))
11891 (if (looking-at
11892 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11893 (replace-match ""))
11894 (if negative (insert " -"))
11895 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11896 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11897 (insert " " (format fh h m))))
11898 (if align (org-table-align))
11899 (message "Time difference inserted")))))
11901 (defun org-make-tdiff-string (y d h m)
11902 (let ((fmt "")
11903 (l nil))
11904 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11905 l (push y l)))
11906 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11907 l (push d l)))
11908 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11909 l (push h l)))
11910 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11911 l (push m l)))
11912 (apply 'format fmt (nreverse l))))
11914 (defun org-time-string-to-time (s)
11915 (apply 'encode-time (org-parse-time-string s)))
11917 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11918 "Convert a time stamp to an absolute day number.
11919 If there is a specifyer for a cyclic time stamp, get the closest date to
11920 DAYNR.
11921 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11922 (cond
11923 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11924 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11925 daynr
11926 (+ daynr 1000)))
11927 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11928 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11929 (time-to-days (current-time))) (match-string 0 s)
11930 prefer show-all))
11931 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11933 (defun org-days-to-iso-week (days)
11934 "Return the iso week number."
11935 (require 'cal-iso)
11936 (car (calendar-iso-from-absolute days)))
11938 (defun org-small-year-to-year (year)
11939 "Convert 2-digit years into 4-digit years.
11940 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11941 The year 2000 cannot be abbreviated. Any year larger than 99
11942 is returned unchanged."
11943 (if (< year 38)
11944 (setq year (+ 2000 year))
11945 (if (< year 100)
11946 (setq year (+ 1900 year))))
11947 year)
11949 (defun org-time-from-absolute (d)
11950 "Return the time corresponding to date D.
11951 D may be an absolute day number, or a calendar-type list (month day year)."
11952 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11953 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11955 (defun org-calendar-holiday ()
11956 "List of holidays, for Diary display in Org-mode."
11957 (require 'holidays)
11958 (let ((hl (funcall
11959 (if (fboundp 'calendar-check-holidays)
11960 'calendar-check-holidays 'check-calendar-holidays) date)))
11961 (if hl (mapconcat 'identity hl "; "))))
11963 (defun org-diary-sexp-entry (sexp entry date)
11964 "Process a SEXP diary ENTRY for DATE."
11965 (require 'diary-lib)
11966 (let ((result (if calendar-debug-sexp
11967 (let ((stack-trace-on-error t))
11968 (eval (car (read-from-string sexp))))
11969 (condition-case nil
11970 (eval (car (read-from-string sexp)))
11971 (error
11972 (beep)
11973 (message "Bad sexp at line %d in %s: %s"
11974 (org-current-line)
11975 (buffer-file-name) sexp)
11976 (sleep-for 2))))))
11977 (cond ((stringp result) result)
11978 ((and (consp result)
11979 (stringp (cdr result))) (cdr result))
11980 (result entry)
11981 (t nil))))
11983 (defun org-diary-to-ical-string (frombuf)
11984 "Get iCalendar entries from diary entries in buffer FROMBUF.
11985 This uses the icalendar.el library."
11986 (let* ((tmpdir (if (featurep 'xemacs)
11987 (temp-directory)
11988 temporary-file-directory))
11989 (tmpfile (make-temp-name
11990 (expand-file-name "orgics" tmpdir)))
11991 buf rtn b e)
11992 (save-excursion
11993 (set-buffer frombuf)
11994 (icalendar-export-region (point-min) (point-max) tmpfile)
11995 (setq buf (find-buffer-visiting tmpfile))
11996 (set-buffer buf)
11997 (goto-char (point-min))
11998 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11999 (setq b (match-beginning 0)))
12000 (goto-char (point-max))
12001 (if (re-search-backward "^END:VEVENT" nil t)
12002 (setq e (match-end 0)))
12003 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12004 (kill-buffer buf)
12005 (delete-file tmpfile)
12006 rtn))
12008 (defun org-closest-date (start current change prefer show-all)
12009 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12010 When PREFER is `past' return a date that is either CURRENT or past.
12011 When PREFER is `future', return a date that is either CURRENT or future.
12012 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12013 ;; Make the proper lists from the dates
12014 (catch 'exit
12015 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12016 dn dw sday cday n1 n2 n0
12017 d m y y1 y2 date1 date2 nmonths nm ny m2)
12019 (setq start (org-date-to-gregorian start)
12020 current (org-date-to-gregorian
12021 (if show-all
12022 current
12023 (time-to-days (current-time))))
12024 sday (calendar-absolute-from-gregorian start)
12025 cday (calendar-absolute-from-gregorian current))
12027 (if (<= cday sday) (throw 'exit sday))
12029 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12030 (setq dn (string-to-number (match-string 1 change))
12031 dw (cdr (assoc (match-string 2 change) a1)))
12032 (error "Invalid change specifyer: %s" change))
12033 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12034 (cond
12035 ((eq dw 'day)
12036 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12037 n2 (+ n1 dn)))
12038 ((eq dw 'year)
12039 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12040 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12041 (setq date1 (list m d y1)
12042 n1 (calendar-absolute-from-gregorian date1)
12043 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12044 n2 (calendar-absolute-from-gregorian date2)))
12045 ((eq dw 'month)
12046 ;; approx number of month between the two dates
12047 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12048 ;; How often does dn fit in there?
12049 (setq d (nth 1 start) m (car start) y (nth 2 start)
12050 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12051 m (+ m nm)
12052 ny (floor (/ m 12))
12053 y (+ y ny)
12054 m (- m (* ny 12)))
12055 (while (> m 12) (setq m (- m 12) y (1+ y)))
12056 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12057 (setq m2 (+ m dn) y2 y)
12058 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12059 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12060 (while (<= n2 cday)
12061 (setq n1 n2 m m2 y y2)
12062 (setq m2 (+ m dn) y2 y)
12063 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12064 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12065 ;; Make sure n1 is the earlier date
12066 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12067 (if show-all
12068 (cond
12069 ((eq prefer 'past) n1)
12070 ((eq prefer 'future) (if (= cday n1) n1 n2))
12071 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12072 (cond
12073 ((eq prefer 'past) n1)
12074 ((eq prefer 'future) (if (= cday n1) n1 n2))
12075 (t (if (= cday n1) n1 n2)))))))
12077 (defun org-date-to-gregorian (date)
12078 "Turn any specification of DATE into a gregorian date for the calendar."
12079 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12080 ((and (listp date) (= (length date) 3)) date)
12081 ((stringp date)
12082 (setq date (org-parse-time-string date))
12083 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12084 ((listp date)
12085 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12087 (defun org-parse-time-string (s &optional nodefault)
12088 "Parse the standard Org-mode time string.
12089 This should be a lot faster than the normal `parse-time-string'.
12090 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12091 hour and minute fields will be nil if not given."
12092 (if (string-match org-ts-regexp0 s)
12093 (list 0
12094 (if (or (match-beginning 8) (not nodefault))
12095 (string-to-number (or (match-string 8 s) "0")))
12096 (if (or (match-beginning 7) (not nodefault))
12097 (string-to-number (or (match-string 7 s) "0")))
12098 (string-to-number (match-string 4 s))
12099 (string-to-number (match-string 3 s))
12100 (string-to-number (match-string 2 s))
12101 nil nil nil)
12102 (make-list 9 0)))
12104 (defun org-timestamp-up (&optional arg)
12105 "Increase the date item at the cursor by one.
12106 If the cursor is on the year, change the year. If it is on the month or
12107 the day, change that.
12108 With prefix ARG, change by that many units."
12109 (interactive "p")
12110 (org-timestamp-change (prefix-numeric-value arg)))
12112 (defun org-timestamp-down (&optional arg)
12113 "Decrease the date item at the cursor by one.
12114 If the cursor is on the year, change the year. If it is on the month or
12115 the day, change that.
12116 With prefix ARG, change by that many units."
12117 (interactive "p")
12118 (org-timestamp-change (- (prefix-numeric-value arg))))
12120 (defun org-timestamp-up-day (&optional arg)
12121 "Increase the date in the time stamp by one day.
12122 With prefix ARG, change that many days."
12123 (interactive "p")
12124 (if (and (not (org-at-timestamp-p t))
12125 (org-on-heading-p))
12126 (org-todo 'up)
12127 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12129 (defun org-timestamp-down-day (&optional arg)
12130 "Decrease the date in the time stamp by one day.
12131 With prefix ARG, change that many days."
12132 (interactive "p")
12133 (if (and (not (org-at-timestamp-p t))
12134 (org-on-heading-p))
12135 (org-todo 'down)
12136 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12138 (defun org-at-timestamp-p (&optional inactive-ok)
12139 "Determine if the cursor is in or at a timestamp."
12140 (interactive)
12141 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12142 (pos (point))
12143 (ans (or (looking-at tsr)
12144 (save-excursion
12145 (skip-chars-backward "^[<\n\r\t")
12146 (if (> (point) (point-min)) (backward-char 1))
12147 (and (looking-at tsr)
12148 (> (- (match-end 0) pos) -1))))))
12149 (and ans
12150 (boundp 'org-ts-what)
12151 (setq org-ts-what
12152 (cond
12153 ((= pos (match-beginning 0)) 'bracket)
12154 ((= pos (1- (match-end 0))) 'bracket)
12155 ((org-pos-in-match-range pos 2) 'year)
12156 ((org-pos-in-match-range pos 3) 'month)
12157 ((org-pos-in-match-range pos 7) 'hour)
12158 ((org-pos-in-match-range pos 8) 'minute)
12159 ((or (org-pos-in-match-range pos 4)
12160 (org-pos-in-match-range pos 5)) 'day)
12161 ((and (> pos (or (match-end 8) (match-end 5)))
12162 (< pos (match-end 0)))
12163 (- pos (or (match-end 8) (match-end 5))))
12164 (t 'day))))
12165 ans))
12167 (defun org-toggle-timestamp-type ()
12168 "Toggle the type (<active> or [inactive]) of a time stamp."
12169 (interactive)
12170 (when (org-at-timestamp-p t)
12171 (let ((beg (match-beginning 0)) (end (match-end 0))
12172 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12173 (save-excursion
12174 (goto-char beg)
12175 (while (re-search-forward "[][<>]" end t)
12176 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12177 t t)))
12178 (message "Timestamp is now %sactive"
12179 (if (equal (char-after beg) ?<) "" "in")))))
12181 (defun org-timestamp-change (n &optional what)
12182 "Change the date in the time stamp at point.
12183 The date will be changed by N times WHAT. WHAT can be `day', `month',
12184 `year', `minute', `second'. If WHAT is not given, the cursor position
12185 in the timestamp determines what will be changed."
12186 (let ((pos (point))
12187 with-hm inactive
12188 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12189 org-ts-what
12190 extra rem
12191 ts time time0)
12192 (if (not (org-at-timestamp-p t))
12193 (error "Not at a timestamp"))
12194 (if (and (not what) (eq org-ts-what 'bracket))
12195 (org-toggle-timestamp-type)
12196 (if (and (not what) (not (eq org-ts-what 'day))
12197 org-display-custom-times
12198 (get-text-property (point) 'display)
12199 (not (get-text-property (1- (point)) 'display)))
12200 (setq org-ts-what 'day))
12201 (setq org-ts-what (or what org-ts-what)
12202 inactive (= (char-after (match-beginning 0)) ?\[)
12203 ts (match-string 0))
12204 (replace-match "")
12205 (if (string-match
12206 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12208 (setq extra (match-string 1 ts)))
12209 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12210 (setq with-hm t))
12211 (setq time0 (org-parse-time-string ts))
12212 (when (and (eq org-ts-what 'minute)
12213 (eq current-prefix-arg nil))
12214 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12215 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12216 (setcar (cdr time0) (+ (nth 1 time0)
12217 (if (> n 0) (- rem) (- dm rem))))))
12218 (setq time
12219 (encode-time (or (car time0) 0)
12220 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12221 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12222 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12223 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12224 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12225 (nthcdr 6 time0)))
12226 (when (integerp org-ts-what)
12227 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12228 (if (eq what 'calendar)
12229 (let ((cal-date (org-get-date-from-calendar)))
12230 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12231 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12232 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12233 (setcar time0 (or (car time0) 0))
12234 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12235 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12236 (setq time (apply 'encode-time time0))))
12237 (setq org-last-changed-timestamp
12238 (org-insert-time-stamp time with-hm inactive nil nil extra))
12239 (org-clock-update-time-maybe)
12240 (goto-char pos)
12241 ;; Try to recenter the calendar window, if any
12242 (if (and org-calendar-follow-timestamp-change
12243 (get-buffer-window "*Calendar*" t)
12244 (memq org-ts-what '(day month year)))
12245 (org-recenter-calendar (time-to-days time))))))
12247 (defun org-modify-ts-extra (s pos n dm)
12248 "Change the different parts of the lead-time and repeat fields in timestamp."
12249 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12250 ng h m new rem)
12251 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12252 (cond
12253 ((or (org-pos-in-match-range pos 2)
12254 (org-pos-in-match-range pos 3))
12255 (setq m (string-to-number (match-string 3 s))
12256 h (string-to-number (match-string 2 s)))
12257 (if (org-pos-in-match-range pos 2)
12258 (setq h (+ h n))
12259 (setq n (* dm (org-no-warnings (signum n))))
12260 (when (not (= 0 (setq rem (% m dm))))
12261 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12262 (setq m (+ m n)))
12263 (if (< m 0) (setq m (+ m 60) h (1- h)))
12264 (if (> m 59) (setq m (- m 60) h (1+ h)))
12265 (setq h (min 24 (max 0 h)))
12266 (setq ng 1 new (format "-%02d:%02d" h m)))
12267 ((org-pos-in-match-range pos 6)
12268 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12269 ((org-pos-in-match-range pos 5)
12270 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12272 ((org-pos-in-match-range pos 9)
12273 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12274 ((org-pos-in-match-range pos 8)
12275 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12277 (when ng
12278 (setq s (concat
12279 (substring s 0 (match-beginning ng))
12281 (substring s (match-end ng))))))
12284 (defun org-recenter-calendar (date)
12285 "If the calendar is visible, recenter it to DATE."
12286 (let* ((win (selected-window))
12287 (cwin (get-buffer-window "*Calendar*" t))
12288 (calendar-move-hook nil))
12289 (when cwin
12290 (select-window cwin)
12291 (calendar-goto-date (if (listp date) date
12292 (calendar-gregorian-from-absolute date)))
12293 (select-window win))))
12295 (defun org-goto-calendar (&optional arg)
12296 "Go to the Emacs calendar at the current date.
12297 If there is a time stamp in the current line, go to that date.
12298 A prefix ARG can be used to force the current date."
12299 (interactive "P")
12300 (let ((tsr org-ts-regexp) diff
12301 (calendar-move-hook nil)
12302 (calendar-view-holidays-initially-flag nil)
12303 (view-calendar-holidays-initially nil)
12304 (calendar-view-diary-initially-flag nil)
12305 (view-diary-entries-initially nil))
12306 (if (or (org-at-timestamp-p)
12307 (save-excursion
12308 (beginning-of-line 1)
12309 (looking-at (concat ".*" tsr))))
12310 (let ((d1 (time-to-days (current-time)))
12311 (d2 (time-to-days
12312 (org-time-string-to-time (match-string 1)))))
12313 (setq diff (- d2 d1))))
12314 (calendar)
12315 (calendar-goto-today)
12316 (if (and diff (not arg)) (calendar-forward-day diff))))
12318 (defun org-get-date-from-calendar ()
12319 "Return a list (month day year) of date at point in calendar."
12320 (with-current-buffer "*Calendar*"
12321 (save-match-data
12322 (calendar-cursor-to-date))))
12324 (defun org-date-from-calendar ()
12325 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12326 If there is already a time stamp at the cursor position, update it."
12327 (interactive)
12328 (if (org-at-timestamp-p t)
12329 (org-timestamp-change 0 'calendar)
12330 (let ((cal-date (org-get-date-from-calendar)))
12331 (org-insert-time-stamp
12332 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12334 (defun org-minutes-to-hh:mm-string (m)
12335 "Compute H:MM from a number of minutes."
12336 (let ((h (/ m 60)))
12337 (setq m (- m (* 60 h)))
12338 (format org-time-clocksum-format h m)))
12340 (defun org-hh:mm-string-to-minutes (s)
12341 "Convert a string H:MM to a number of minutes."
12342 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12343 (+ (* (string-to-number (match-string 1 s)) 60)
12344 (string-to-number (match-string 2 s)))
12347 ;;;; Files
12349 (defun org-save-all-org-buffers ()
12350 "Save all Org-mode buffers without user confirmation."
12351 (interactive)
12352 (message "Saving all Org-mode buffers...")
12353 (save-some-buffers t 'org-mode-p)
12354 (when (featurep 'org-id) (org-id-locations-save))
12355 (message "Saving all Org-mode buffers... done"))
12357 (defun org-revert-all-org-buffers ()
12358 "Revert all Org-mode buffers.
12359 Prompt for confirmation when there are unsaved changes.
12360 Be sure you know what you are doing before letting this function
12361 overwrite your changes.
12363 This function is useful in a setup where one tracks org files
12364 with a version control system, to revert on one machine after pulling
12365 changes from another. I believe the procedure must be like this:
12367 1. M-x org-save-all-org-buffers
12368 2. Pull changes from the other machine, resolve conflicts
12369 3. M-x org-revert-all-org-buffers"
12370 (interactive)
12371 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12372 (error "Abort"))
12373 (save-excursion
12374 (save-window-excursion
12375 (mapc
12376 (lambda (b)
12377 (when (and (with-current-buffer b (org-mode-p))
12378 (with-current-buffer b buffer-file-name))
12379 (switch-to-buffer b)
12380 (revert-buffer t 'no-confirm)))
12381 (buffer-list))
12382 (when (and (featurep 'org-id) org-id-track-globally)
12383 (org-id-locations-load)))))
12385 ;;;; Agenda files
12387 ;;;###autoload
12388 (defun org-iswitchb (&optional arg)
12389 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12390 With a prefix argument, restrict available to files.
12391 With two prefix arguments, restrict available buffers to agenda files.
12393 Due to some yet unresolved reason, the global function
12394 `iswitchb-mode' needs to be active for this function to work."
12395 (interactive "P")
12396 (require 'iswitchb)
12397 (let ((enabled iswitchb-mode) blist)
12398 (or enabled (iswitchb-mode 1))
12399 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12400 ((equal arg '(16)) (org-buffer-list 'agenda))
12401 (t (org-buffer-list))))
12402 (unwind-protect
12403 (let ((iswitchb-make-buflist-hook
12404 (lambda ()
12405 (setq iswitchb-temp-buflist
12406 (mapcar 'buffer-name blist)))))
12407 (switch-to-buffer
12408 (iswitchb-read-buffer
12409 "Switch-to: " nil t))
12410 (or enabled (iswitchb-mode -1))))))
12412 ;;;###autoload
12413 (defun org-ido-switchb (&optional arg)
12414 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12415 With a prefix argument, restrict available to files.
12416 With two prefix arguments, restrict available buffers to agenda files."
12417 (interactive "P")
12418 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12419 ((equal arg '(16)) (org-buffer-list 'agenda))
12420 (t (org-buffer-list)))))
12421 (switch-to-buffer
12422 (org-ido-completing-read "Org buffer: "
12423 (mapcar 'buffer-name blist)
12424 nil t))))
12426 (defun org-buffer-list (&optional predicate exclude-tmp)
12427 "Return a list of Org buffers.
12428 PREDICATE can be `export', `files' or `agenda'.
12430 export restrict the list to Export buffers.
12431 files restrict the list to buffers visiting Org files.
12432 agenda restrict the list to buffers visiting agenda files.
12434 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12435 (let* ((bfn nil)
12436 (agenda-files (and (eq predicate 'agenda)
12437 (mapcar 'file-truename (org-agenda-files t))))
12438 (filter
12439 (cond
12440 ((eq predicate 'files)
12441 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12442 ((eq predicate 'export)
12443 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12444 ((eq predicate 'agenda)
12445 (lambda (b)
12446 (with-current-buffer b
12447 (and (eq major-mode 'org-mode)
12448 (setq bfn (buffer-file-name b))
12449 (member (file-truename bfn) agenda-files)))))
12450 (t (lambda (b) (with-current-buffer b
12451 (or (eq major-mode 'org-mode)
12452 (string-match "\*Org .*Export"
12453 (buffer-name b)))))))))
12454 (delq nil
12455 (mapcar
12456 (lambda(b)
12457 (if (and (funcall filter b)
12458 (or (not exclude-tmp)
12459 (not (string-match "tmp" (buffer-name b)))))
12461 nil))
12462 (buffer-list)))))
12464 (defun org-agenda-files (&optional unrestricted archives)
12465 "Get the list of agenda files.
12466 Optional UNRESTRICTED means return the full list even if a restriction
12467 is currently in place.
12468 When ARCHIVES is t, include all archive files hat are really being
12469 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12470 `org-agenda-archives-mode' is t."
12471 (let ((files
12472 (cond
12473 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12474 ((stringp org-agenda-files) (org-read-agenda-file-list))
12475 ((listp org-agenda-files) org-agenda-files)
12476 (t (error "Invalid value of `org-agenda-files'")))))
12477 (setq files (apply 'append
12478 (mapcar (lambda (f)
12479 (if (file-directory-p f)
12480 (directory-files
12481 f t org-agenda-file-regexp)
12482 (list f)))
12483 files)))
12484 (when org-agenda-skip-unavailable-files
12485 (setq files (delq nil
12486 (mapcar (function
12487 (lambda (file)
12488 (and (file-readable-p file) file)))
12489 files))))
12490 (when (or (eq archives t)
12491 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12492 (setq files (org-add-archive-files files)))
12493 files))
12495 (defun org-edit-agenda-file-list ()
12496 "Edit the list of agenda files.
12497 Depending on setup, this either uses customize to edit the variable
12498 `org-agenda-files', or it visits the file that is holding the list. In the
12499 latter case, the buffer is set up in a way that saving it automatically kills
12500 the buffer and restores the previous window configuration."
12501 (interactive)
12502 (if (stringp org-agenda-files)
12503 (let ((cw (current-window-configuration)))
12504 (find-file org-agenda-files)
12505 (org-set-local 'org-window-configuration cw)
12506 (org-add-hook 'after-save-hook
12507 (lambda ()
12508 (set-window-configuration
12509 (prog1 org-window-configuration
12510 (kill-buffer (current-buffer))))
12511 (org-install-agenda-files-menu)
12512 (message "New agenda file list installed"))
12513 nil 'local)
12514 (message "%s" (substitute-command-keys
12515 "Edit list and finish with \\[save-buffer]")))
12516 (customize-variable 'org-agenda-files)))
12518 (defun org-store-new-agenda-file-list (list)
12519 "Set new value for the agenda file list and save it correctly."
12520 (if (stringp org-agenda-files)
12521 (let ((f org-agenda-files) b)
12522 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12523 (with-temp-file f
12524 (insert (mapconcat 'identity list "\n") "\n")))
12525 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12526 (setq org-agenda-files list)
12527 (customize-save-variable 'org-agenda-files org-agenda-files))))
12529 (defun org-read-agenda-file-list ()
12530 "Read the list of agenda files from a file."
12531 (when (file-directory-p org-agenda-files)
12532 (error "`org-agenda-files' cannot be a single directory"))
12533 (when (stringp org-agenda-files)
12534 (with-temp-buffer
12535 (insert-file-contents org-agenda-files)
12536 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12539 ;;;###autoload
12540 (defun org-cycle-agenda-files ()
12541 "Cycle through the files in `org-agenda-files'.
12542 If the current buffer visits an agenda file, find the next one in the list.
12543 If the current buffer does not, find the first agenda file."
12544 (interactive)
12545 (let* ((fs (org-agenda-files t))
12546 (files (append fs (list (car fs))))
12547 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12548 file)
12549 (unless files (error "No agenda files"))
12550 (catch 'exit
12551 (while (setq file (pop files))
12552 (if (equal (file-truename file) tcf)
12553 (when (car files)
12554 (find-file (car files))
12555 (throw 'exit t))))
12556 (find-file (car fs)))
12557 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12559 (defun org-agenda-file-to-front (&optional to-end)
12560 "Move/add the current file to the top of the agenda file list.
12561 If the file is not present in the list, it is added to the front. If it is
12562 present, it is moved there. With optional argument TO-END, add/move to the
12563 end of the list."
12564 (interactive "P")
12565 (let ((org-agenda-skip-unavailable-files nil)
12566 (file-alist (mapcar (lambda (x)
12567 (cons (file-truename x) x))
12568 (org-agenda-files t)))
12569 (ctf (file-truename buffer-file-name))
12570 x had)
12571 (setq x (assoc ctf file-alist) had x)
12573 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12574 (if to-end
12575 (setq file-alist (append (delq x file-alist) (list x)))
12576 (setq file-alist (cons x (delq x file-alist))))
12577 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12578 (org-install-agenda-files-menu)
12579 (message "File %s to %s of agenda file list"
12580 (if had "moved" "added") (if to-end "end" "front"))))
12582 (defun org-remove-file (&optional file)
12583 "Remove current file from the list of files in variable `org-agenda-files'.
12584 These are the files which are being checked for agenda entries.
12585 Optional argument FILE means, use this file instead of the current."
12586 (interactive)
12587 (let* ((org-agenda-skip-unavailable-files nil)
12588 (file (or file buffer-file-name))
12589 (true-file (file-truename file))
12590 (afile (abbreviate-file-name file))
12591 (files (delq nil (mapcar
12592 (lambda (x)
12593 (if (equal true-file
12594 (file-truename x))
12595 nil x))
12596 (org-agenda-files t)))))
12597 (if (not (= (length files) (length (org-agenda-files t))))
12598 (progn
12599 (org-store-new-agenda-file-list files)
12600 (org-install-agenda-files-menu)
12601 (message "Removed file: %s" afile))
12602 (message "File was not in list: %s (not removed)" afile))))
12604 (defun org-file-menu-entry (file)
12605 (vector file (list 'find-file file) t))
12607 (defun org-check-agenda-file (file)
12608 "Make sure FILE exists. If not, ask user what to do."
12609 (when (not (file-exists-p file))
12610 (message "non-existent file %s. [R]emove from list or [A]bort?"
12611 (abbreviate-file-name file))
12612 (let ((r (downcase (read-char-exclusive))))
12613 (cond
12614 ((equal r ?r)
12615 (org-remove-file file)
12616 (throw 'nextfile t))
12617 (t (error "Abort"))))))
12619 (defun org-get-agenda-file-buffer (file)
12620 "Get a buffer visiting FILE. If the buffer needs to be created, add
12621 it to the list of buffers which might be released later."
12622 (let ((buf (org-find-base-buffer-visiting file)))
12623 (if buf
12624 buf ; just return it
12625 ;; Make a new buffer and remember it
12626 (setq buf (find-file-noselect file))
12627 (if buf (push buf org-agenda-new-buffers))
12628 buf)))
12630 (defun org-release-buffers (blist)
12631 "Release all buffers in list, asking the user for confirmation when needed.
12632 When a buffer is unmodified, it is just killed. When modified, it is saved
12633 \(if the user agrees) and then killed."
12634 (let (buf file)
12635 (while (setq buf (pop blist))
12636 (setq file (buffer-file-name buf))
12637 (when (and (buffer-modified-p buf)
12638 file
12639 (y-or-n-p (format "Save file %s? " file)))
12640 (with-current-buffer buf (save-buffer)))
12641 (kill-buffer buf))))
12643 (defun org-prepare-agenda-buffers (files)
12644 "Create buffers for all agenda files, protect archived trees and comments."
12645 (interactive)
12646 (let ((pa '(:org-archived t))
12647 (pc '(:org-comment t))
12648 (pall '(:org-archived t :org-comment t))
12649 (inhibit-read-only t)
12650 (rea (concat ":" org-archive-tag ":"))
12651 bmp file re)
12652 (save-excursion
12653 (save-restriction
12654 (while (setq file (pop files))
12655 (if (bufferp file)
12656 (set-buffer file)
12657 (org-check-agenda-file file)
12658 (set-buffer (org-get-agenda-file-buffer file)))
12659 (widen)
12660 (setq bmp (buffer-modified-p))
12661 (org-refresh-category-properties)
12662 (setq org-todo-keywords-for-agenda
12663 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12664 (setq org-done-keywords-for-agenda
12665 (append org-done-keywords-for-agenda org-done-keywords))
12666 (setq org-todo-keyword-alist-for-agenda
12667 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12668 (setq org-tag-alist-for-agenda
12669 (append org-tag-alist-for-agenda org-tag-alist))
12671 (save-excursion
12672 (remove-text-properties (point-min) (point-max) pall)
12673 (when org-agenda-skip-archived-trees
12674 (goto-char (point-min))
12675 (while (re-search-forward rea nil t)
12676 (if (org-on-heading-p t)
12677 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12678 (goto-char (point-min))
12679 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12680 (while (re-search-forward re nil t)
12681 (add-text-properties
12682 (match-beginning 0) (org-end-of-subtree t) pc)))
12683 (set-buffer-modified-p bmp))))
12684 (setq org-todo-keyword-alist-for-agenda
12685 (org-uniquify org-todo-keyword-alist-for-agenda)
12686 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12688 ;;;; Embedded LaTeX
12690 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12691 "Keymap for the minor `org-cdlatex-mode'.")
12693 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12694 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12695 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12696 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12697 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12699 (defvar org-cdlatex-texmathp-advice-is-done nil
12700 "Flag remembering if we have applied the advice to texmathp already.")
12702 (define-minor-mode org-cdlatex-mode
12703 "Toggle the minor `org-cdlatex-mode'.
12704 This mode supports entering LaTeX environment and math in LaTeX fragments
12705 in Org-mode.
12706 \\{org-cdlatex-mode-map}"
12707 nil " OCDL" nil
12708 (when org-cdlatex-mode (require 'cdlatex))
12709 (unless org-cdlatex-texmathp-advice-is-done
12710 (setq org-cdlatex-texmathp-advice-is-done t)
12711 (defadvice texmathp (around org-math-always-on activate)
12712 "Always return t in org-mode buffers.
12713 This is because we want to insert math symbols without dollars even outside
12714 the LaTeX math segments. If Orgmode thinks that point is actually inside
12715 an embedded LaTeX fragment, let texmathp do its job.
12716 \\[org-cdlatex-mode-map]"
12717 (interactive)
12718 (let (p)
12719 (cond
12720 ((not (org-mode-p)) ad-do-it)
12721 ((eq this-command 'cdlatex-math-symbol)
12722 (setq ad-return-value t
12723 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12725 (let ((p (org-inside-LaTeX-fragment-p)))
12726 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12727 (setq ad-return-value t
12728 texmathp-why '("Org-mode embedded math" . 0))
12729 (if p ad-do-it)))))))))
12731 (defun turn-on-org-cdlatex ()
12732 "Unconditionally turn on `org-cdlatex-mode'."
12733 (org-cdlatex-mode 1))
12735 (defun org-inside-LaTeX-fragment-p ()
12736 "Test if point is inside a LaTeX fragment.
12737 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12738 sequence appearing also before point.
12739 Even though the matchers for math are configurable, this function assumes
12740 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12741 delimiters are skipped when they have been removed by customization.
12742 The return value is nil, or a cons cell with the delimiter and
12743 and the position of this delimiter.
12745 This function does a reasonably good job, but can locally be fooled by
12746 for example currency specifications. For example it will assume being in
12747 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12748 fragments that are properly closed, but during editing, we have to live
12749 with the uncertainty caused by missing closing delimiters. This function
12750 looks only before point, not after."
12751 (catch 'exit
12752 (let ((pos (point))
12753 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12754 (lim (progn
12755 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12756 (point)))
12757 dd-on str (start 0) m re)
12758 (goto-char pos)
12759 (when dodollar
12760 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12761 re (nth 1 (assoc "$" org-latex-regexps)))
12762 (while (string-match re str start)
12763 (cond
12764 ((= (match-end 0) (length str))
12765 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12766 ((= (match-end 0) (- (length str) 5))
12767 (throw 'exit nil))
12768 (t (setq start (match-end 0))))))
12769 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12770 (goto-char pos)
12771 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12772 (and (match-beginning 2) (throw 'exit nil))
12773 ;; count $$
12774 (while (re-search-backward "\\$\\$" lim t)
12775 (setq dd-on (not dd-on)))
12776 (goto-char pos)
12777 (if dd-on (cons "$$" m))))))
12780 (defun org-try-cdlatex-tab ()
12781 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12782 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12783 - inside a LaTeX fragment, or
12784 - after the first word in a line, where an abbreviation expansion could
12785 insert a LaTeX environment."
12786 (when org-cdlatex-mode
12787 (cond
12788 ((save-excursion
12789 (skip-chars-backward "a-zA-Z0-9*")
12790 (skip-chars-backward " \t")
12791 (bolp))
12792 (cdlatex-tab) t)
12793 ((org-inside-LaTeX-fragment-p)
12794 (cdlatex-tab) t)
12795 (t nil))))
12797 (defun org-cdlatex-underscore-caret (&optional arg)
12798 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12799 Revert to the normal definition outside of these fragments."
12800 (interactive "P")
12801 (if (org-inside-LaTeX-fragment-p)
12802 (call-interactively 'cdlatex-sub-superscript)
12803 (let (org-cdlatex-mode)
12804 (call-interactively (key-binding (vector last-input-event))))))
12806 (defun org-cdlatex-math-modify (&optional arg)
12807 "Execute `cdlatex-math-modify' in LaTeX fragments.
12808 Revert to the normal definition outside of these fragments."
12809 (interactive "P")
12810 (if (org-inside-LaTeX-fragment-p)
12811 (call-interactively 'cdlatex-math-modify)
12812 (let (org-cdlatex-mode)
12813 (call-interactively (key-binding (vector last-input-event))))))
12815 (defvar org-latex-fragment-image-overlays nil
12816 "List of overlays carrying the images of latex fragments.")
12817 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12819 (defun org-remove-latex-fragment-image-overlays ()
12820 "Remove all overlays with LaTeX fragment images in current buffer."
12821 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12822 (setq org-latex-fragment-image-overlays nil))
12824 (defun org-preview-latex-fragment (&optional subtree)
12825 "Preview the LaTeX fragment at point, or all locally or globally.
12826 If the cursor is in a LaTeX fragment, create the image and overlay
12827 it over the source code. If there is no fragment at point, display
12828 all fragments in the current text, from one headline to the next. With
12829 prefix SUBTREE, display all fragments in the current subtree. With a
12830 double prefix `C-u C-u', or when the cursor is before the first headline,
12831 display all fragments in the buffer.
12832 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12833 (interactive "P")
12834 (org-remove-latex-fragment-image-overlays)
12835 (save-excursion
12836 (save-restriction
12837 (let (beg end at msg)
12838 (cond
12839 ((or (equal subtree '(16))
12840 (not (save-excursion
12841 (re-search-backward (concat "^" outline-regexp) nil t))))
12842 (setq beg (point-min) end (point-max)
12843 msg "Creating images for buffer...%s"))
12844 ((equal subtree '(4))
12845 (org-back-to-heading)
12846 (setq beg (point) end (org-end-of-subtree t)
12847 msg "Creating images for subtree...%s"))
12849 (if (setq at (org-inside-LaTeX-fragment-p))
12850 (goto-char (max (point-min) (- (cdr at) 2)))
12851 (org-back-to-heading))
12852 (setq beg (point) end (progn (outline-next-heading) (point))
12853 msg (if at "Creating image...%s"
12854 "Creating images for entry...%s"))))
12855 (message msg "")
12856 (narrow-to-region beg end)
12857 (goto-char beg)
12858 (org-format-latex
12859 (concat "ltxpng/" (file-name-sans-extension
12860 (file-name-nondirectory
12861 buffer-file-name)))
12862 default-directory 'overlays msg at 'forbuffer)
12863 (message msg "done. Use `C-c C-c' to remove images.")))))
12865 (defvar org-latex-regexps
12866 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12867 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12868 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12869 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12870 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12871 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12872 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12873 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12874 "Regular expressions for matching embedded LaTeX.")
12876 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12877 "Replace LaTeX fragments with links to an image, and produce images."
12878 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12879 (let* ((prefixnodir (file-name-nondirectory prefix))
12880 (absprefix (expand-file-name prefix dir))
12881 (todir (file-name-directory absprefix))
12882 (opt org-format-latex-options)
12883 (matchers (plist-get opt :matchers))
12884 (re-list org-latex-regexps)
12885 (cnt 0) txt link beg end re e checkdir
12886 m n block linkfile movefile ov)
12887 ;; Check if there are old images files with this prefix, and remove them
12888 (when (file-directory-p todir)
12889 (mapc 'delete-file
12890 (directory-files
12891 todir 'full
12892 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12893 ;; Check the different regular expressions
12894 (while (setq e (pop re-list))
12895 (setq m (car e) re (nth 1 e) n (nth 2 e)
12896 block (if (nth 3 e) "\n\n" ""))
12897 (when (member m matchers)
12898 (goto-char (point-min))
12899 (while (re-search-forward re nil t)
12900 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
12901 (not (get-text-property (match-beginning n)
12902 'org-protected)))
12903 (setq txt (match-string n)
12904 beg (match-beginning n) end (match-end n)
12905 cnt (1+ cnt)
12906 linkfile (format "%s_%04d.png" prefix cnt)
12907 movefile (format "%s_%04d.png" absprefix cnt)
12908 link (concat block "[[file:" linkfile "]]" block))
12909 (if msg (message msg cnt))
12910 (goto-char beg)
12911 (unless checkdir ; make sure the directory exists
12912 (setq checkdir t)
12913 (or (file-directory-p todir) (make-directory todir)))
12914 (org-create-formula-image
12915 txt movefile opt forbuffer)
12916 (if overlays
12917 (progn
12918 (setq ov (org-make-overlay beg end))
12919 (if (featurep 'xemacs)
12920 (progn
12921 (org-overlay-put ov 'invisible t)
12922 (org-overlay-put
12923 ov 'end-glyph
12924 (make-glyph (vector 'png :file movefile))))
12925 (org-overlay-put
12926 ov 'display
12927 (list 'image :type 'png :file movefile :ascent 'center)))
12928 (push ov org-latex-fragment-image-overlays)
12929 (goto-char end))
12930 (delete-region beg end)
12931 (insert link))))))))
12933 ;; This function borrows from Ganesh Swami's latex2png.el
12934 (defun org-create-formula-image (string tofile options buffer)
12935 (let* ((tmpdir (if (featurep 'xemacs)
12936 (temp-directory)
12937 temporary-file-directory))
12938 (texfilebase (make-temp-name
12939 (expand-file-name "orgtex" tmpdir)))
12940 (texfile (concat texfilebase ".tex"))
12941 (dvifile (concat texfilebase ".dvi"))
12942 (pngfile (concat texfilebase ".png"))
12943 (fnh (if (featurep 'xemacs)
12944 (font-height (get-face-font 'default))
12945 (face-attribute 'default :height nil)))
12946 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12947 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12948 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12949 "Black"))
12950 (bg (or (plist-get options (if buffer :background :html-background))
12951 "Transparent")))
12952 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12953 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12954 (with-temp-file texfile
12955 (insert org-format-latex-header
12956 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12957 (let ((dir default-directory))
12958 (condition-case nil
12959 (progn
12960 (cd tmpdir)
12961 (call-process "latex" nil nil nil texfile))
12962 (error nil))
12963 (cd dir))
12964 (if (not (file-exists-p dvifile))
12965 (progn (message "Failed to create dvi file from %s" texfile) nil)
12966 (condition-case nil
12967 (call-process "dvipng" nil nil nil
12968 "-E" "-fg" fg "-bg" bg
12969 "-D" dpi
12970 ;;"-x" scale "-y" scale
12971 "-T" "tight"
12972 "-o" pngfile
12973 dvifile)
12974 (error nil))
12975 (if (not (file-exists-p pngfile))
12976 (progn (message "Failed to create png file from %s" texfile) nil)
12977 ;; Use the requested file name and clean up
12978 (copy-file pngfile tofile 'replace)
12979 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12980 (delete-file (concat texfilebase e)))
12981 pngfile))))
12983 (defun org-dvipng-color (attr)
12984 "Return an rgb color specification for dvipng."
12985 (apply 'format "rgb %s %s %s"
12986 (mapcar 'org-normalize-color
12987 (color-values (face-attribute 'default attr nil)))))
12989 (defun org-normalize-color (value)
12990 "Return string to be used as color value for an RGB component."
12991 (format "%g" (/ value 65535.0)))
12993 ;;;; Key bindings
12995 ;; Make `C-c C-x' a prefix key
12996 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12998 ;; TAB key with modifiers
12999 (org-defkey org-mode-map "\C-i" 'org-cycle)
13000 (org-defkey org-mode-map [(tab)] 'org-cycle)
13001 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13002 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13003 (org-defkey org-mode-map "\M-\t" 'org-complete)
13004 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13005 ;; The following line is necessary under Suse GNU/Linux
13006 (unless (featurep 'xemacs)
13007 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13008 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13009 (define-key org-mode-map [backtab] 'org-shifttab)
13011 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13012 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13013 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13015 ;; Cursor keys with modifiers
13016 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13017 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13018 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13019 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13021 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13022 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13023 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13024 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13026 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13027 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13028 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13029 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13031 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13032 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13034 ;;; Extra keys for tty access.
13035 ;; We only set them when really needed because otherwise the
13036 ;; menus don't show the simple keys
13038 (when (or org-use-extra-keys
13039 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13040 (not window-system))
13041 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13042 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13043 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13044 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13045 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13046 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13047 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13048 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13049 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13050 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13051 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13052 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13053 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13054 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13055 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13056 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13057 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13058 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13059 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13060 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13061 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13062 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13064 ;; All the other keys
13066 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13067 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13068 (if (boundp 'narrow-map)
13069 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13070 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13071 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13072 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13073 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13074 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13075 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13076 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13077 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13078 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13079 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13080 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13081 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13082 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13083 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13084 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13085 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13086 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
13087 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13088 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13089 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13090 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13091 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13092 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13093 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13094 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13095 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13096 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13097 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13098 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13099 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13100 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13101 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13102 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13103 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13104 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13105 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13106 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13107 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13108 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13109 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13110 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13111 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13112 (org-defkey org-mode-map "\C-c^" 'org-sort)
13113 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13114 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13115 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13116 (org-defkey org-mode-map "\C-m" 'org-return)
13117 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13118 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13119 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13120 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13121 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13122 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13123 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13124 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13125 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13126 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13127 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13128 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13129 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13130 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13131 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13132 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13133 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13135 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13136 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13137 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13138 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13140 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13141 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13142 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13143 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13144 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13145 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13146 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13147 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13148 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13149 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13150 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13151 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13152 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13154 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13155 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13156 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13157 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13159 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13161 (when (featurep 'xemacs)
13162 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13164 (defvar org-table-auto-blank-field) ; defined in org-table.el
13165 (defun org-self-insert-command (N)
13166 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13167 If the cursor is in a table looking at whitespace, the whitespace is
13168 overwritten, and the table is not marked as requiring realignment."
13169 (interactive "p")
13170 (if (and (org-table-p)
13171 (progn
13172 ;; check if we blank the field, and if that triggers align
13173 (and (featurep 'org-table) org-table-auto-blank-field
13174 (member last-command
13175 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13176 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13177 ;; got extra space, this field does not determine column width
13178 (let (org-table-may-need-update) (org-table-blank-field))
13179 ;; no extra space, this field may determine column width
13180 (org-table-blank-field)))
13182 (eq N 1)
13183 (looking-at "[^|\n]* |"))
13184 (let (org-table-may-need-update)
13185 (goto-char (1- (match-end 0)))
13186 (delete-backward-char 1)
13187 (goto-char (match-beginning 0))
13188 (self-insert-command N))
13189 (setq org-table-may-need-update t)
13190 (self-insert-command N)
13191 (org-fix-tags-on-the-fly)))
13193 (defun org-fix-tags-on-the-fly ()
13194 (when (and (equal (char-after (point-at-bol)) ?*)
13195 (org-on-heading-p))
13196 (org-align-tags-here org-tags-column)))
13198 (defun org-delete-backward-char (N)
13199 "Like `delete-backward-char', insert whitespace at field end in tables.
13200 When deleting backwards, in tables this function will insert whitespace in
13201 front of the next \"|\" separator, to keep the table aligned. The table will
13202 still be marked for re-alignment if the field did fill the entire column,
13203 because, in this case the deletion might narrow the column."
13204 (interactive "p")
13205 (if (and (org-table-p)
13206 (eq N 1)
13207 (string-match "|" (buffer-substring (point-at-bol) (point)))
13208 (looking-at ".*?|"))
13209 (let ((pos (point))
13210 (noalign (looking-at "[^|\n\r]* |"))
13211 (c org-table-may-need-update))
13212 (backward-delete-char N)
13213 (skip-chars-forward "^|")
13214 (insert " ")
13215 (goto-char (1- pos))
13216 ;; noalign: if there were two spaces at the end, this field
13217 ;; does not determine the width of the column.
13218 (if noalign (setq org-table-may-need-update c)))
13219 (backward-delete-char N)
13220 (org-fix-tags-on-the-fly)))
13222 (defun org-delete-char (N)
13223 "Like `delete-char', but insert whitespace at field end in tables.
13224 When deleting characters, in tables this function will insert whitespace in
13225 front of the next \"|\" separator, to keep the table aligned. The table will
13226 still be marked for re-alignment if the field did fill the entire column,
13227 because, in this case the deletion might narrow the column."
13228 (interactive "p")
13229 (if (and (org-table-p)
13230 (not (bolp))
13231 (not (= (char-after) ?|))
13232 (eq N 1))
13233 (if (looking-at ".*?|")
13234 (let ((pos (point))
13235 (noalign (looking-at "[^|\n\r]* |"))
13236 (c org-table-may-need-update))
13237 (replace-match (concat
13238 (substring (match-string 0) 1 -1)
13239 " |"))
13240 (goto-char pos)
13241 ;; noalign: if there were two spaces at the end, this field
13242 ;; does not determine the width of the column.
13243 (if noalign (setq org-table-may-need-update c)))
13244 (delete-char N))
13245 (delete-char N)
13246 (org-fix-tags-on-the-fly)))
13248 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13249 (put 'org-self-insert-command 'delete-selection t)
13250 (put 'orgtbl-self-insert-command 'delete-selection t)
13251 (put 'org-delete-char 'delete-selection 'supersede)
13252 (put 'org-delete-backward-char 'delete-selection 'supersede)
13253 (put 'org-yank 'delete-selection 'yank)
13255 ;; Make `flyspell-mode' delay after some commands
13256 (put 'org-self-insert-command 'flyspell-delayed t)
13257 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13258 (put 'org-delete-char 'flyspell-delayed t)
13259 (put 'org-delete-backward-char 'flyspell-delayed t)
13261 ;; Make pabbrev-mode expand after org-mode commands
13262 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13263 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13265 ;; How to do this: Measure non-white length of current string
13266 ;; If equal to column width, we should realign.
13268 (defun org-remap (map &rest commands)
13269 "In MAP, remap the functions given in COMMANDS.
13270 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13271 (let (new old)
13272 (while commands
13273 (setq old (pop commands) new (pop commands))
13274 (if (fboundp 'command-remapping)
13275 (org-defkey map (vector 'remap old) new)
13276 (substitute-key-definition old new map global-map)))))
13278 (when (eq org-enable-table-editor 'optimized)
13279 ;; If the user wants maximum table support, we need to hijack
13280 ;; some standard editing functions
13281 (org-remap org-mode-map
13282 'self-insert-command 'org-self-insert-command
13283 'delete-char 'org-delete-char
13284 'delete-backward-char 'org-delete-backward-char)
13285 (org-defkey org-mode-map "|" 'org-force-self-insert))
13287 (defvar org-ctrl-c-ctrl-c-hook nil
13288 "Hook for functions attaching themselves to `C-c C-c'.
13289 This can be used to add additional functionality to the C-c C-c key which
13290 executes context-dependent commands.
13291 Each function will be called with no arguments. The function must check
13292 if the context is appropriate for it to act. If yes, it should do its
13293 thing and then return a non-nil value. If the context is wrong,
13294 just do nothing.")
13296 (defvar org-metaleft-hook nil
13297 "Hook for functions attaching themselves to `M-left'.
13298 See `org-ctrl-c-ctrl-c-hook' for more information.")
13299 (defvar org-metaright-hook nil
13300 "Hook for functions attaching themselves to `M-right'.
13301 See `org-ctrl-c-ctrl-c-hook' for more information.")
13302 (defvar org-metaup-hook nil
13303 "Hook for functions attaching themselves to `M-up'.
13304 See `org-ctrl-c-ctrl-c-hook' for more information.")
13305 (defvar org-metadown-hook nil
13306 "Hook for functions attaching themselves to `M-down'.
13307 See `org-ctrl-c-ctrl-c-hook' for more information.")
13308 (defvar org-shiftmetaleft-hook nil
13309 "Hook for functions attaching themselves to `M-S-left'.
13310 See `org-ctrl-c-ctrl-c-hook' for more information.")
13311 (defvar org-shiftmetaright-hook nil
13312 "Hook for functions attaching themselves to `M-S-right'.
13313 See `org-ctrl-c-ctrl-c-hook' for more information.")
13314 (defvar org-shiftmetaup-hook nil
13315 "Hook for functions attaching themselves to `M-S-up'.
13316 See `org-ctrl-c-ctrl-c-hook' for more information.")
13317 (defvar org-shiftmetadown-hook nil
13318 "Hook for functions attaching themselves to `M-S-down'.
13319 See `org-ctrl-c-ctrl-c-hook' for more information.")
13320 (defvar org-metareturn-hook nil
13321 "Hook for functions attaching themselves to `M-RET'.
13322 See `org-ctrl-c-ctrl-c-hook' for more information.")
13324 (defun org-modifier-cursor-error ()
13325 "Throw an error, a modified cursor command was applied in wrong context."
13326 (error "This command is active in special context like tables, headlines or items"))
13328 (defun org-shiftselect-error ()
13329 "Throw an error because Shift-Cursor command was applied in wrong context."
13330 (if (and (boundp 'shift-select-mode) shift-select-mode)
13331 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13332 (error "This command works only in special context like headlines or timestamps.")))
13334 (defun org-call-for-shift-select (cmd)
13335 (let ((this-command-keys-shift-translated t))
13336 (call-interactively cmd)))
13338 (defun org-shifttab (&optional arg)
13339 "Global visibility cycling or move to previous table field.
13340 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13341 on context.
13342 See the individual commands for more information."
13343 (interactive "P")
13344 (cond
13345 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13346 ((integerp arg)
13347 (message "Content view to level: %d" arg)
13348 (org-content (prefix-numeric-value arg))
13349 (setq org-cycle-global-status 'overview))
13350 (t (call-interactively 'org-global-cycle))))
13352 (defun org-shiftmetaleft ()
13353 "Promote subtree or delete table column.
13354 Calls `org-promote-subtree', `org-outdent-item',
13355 or `org-table-delete-column', depending on context.
13356 See the individual commands for more information."
13357 (interactive)
13358 (cond
13359 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13360 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13361 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13362 ((org-at-item-p) (call-interactively 'org-outdent-item))
13363 (t (org-modifier-cursor-error))))
13365 (defun org-shiftmetaright ()
13366 "Demote subtree or insert table column.
13367 Calls `org-demote-subtree', `org-indent-item',
13368 or `org-table-insert-column', depending on context.
13369 See the individual commands for more information."
13370 (interactive)
13371 (cond
13372 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13373 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13374 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13375 ((org-at-item-p) (call-interactively 'org-indent-item))
13376 (t (org-modifier-cursor-error))))
13378 (defun org-shiftmetaup (&optional arg)
13379 "Move subtree up or kill table row.
13380 Calls `org-move-subtree-up' or `org-table-kill-row' or
13381 `org-move-item-up' depending on context. See the individual commands
13382 for more information."
13383 (interactive "P")
13384 (cond
13385 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13386 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13387 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13388 ((org-at-item-p) (call-interactively 'org-move-item-up))
13389 (t (org-modifier-cursor-error))))
13391 (defun org-shiftmetadown (&optional arg)
13392 "Move subtree down or insert table row.
13393 Calls `org-move-subtree-down' or `org-table-insert-row' or
13394 `org-move-item-down', depending on context. See the individual
13395 commands for more information."
13396 (interactive "P")
13397 (cond
13398 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13399 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13400 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13401 ((org-at-item-p) (call-interactively 'org-move-item-down))
13402 (t (org-modifier-cursor-error))))
13404 (defun org-metaleft (&optional arg)
13405 "Promote heading or move table column to left.
13406 Calls `org-do-promote' or `org-table-move-column', depending on context.
13407 With no specific context, calls the Emacs default `backward-word'.
13408 See the individual commands for more information."
13409 (interactive "P")
13410 (cond
13411 ((run-hook-with-args-until-success 'org-metaleft-hook))
13412 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13413 ((or (org-on-heading-p) (org-region-active-p))
13414 (call-interactively 'org-do-promote))
13415 ((org-at-item-p) (call-interactively 'org-outdent-item))
13416 (t (call-interactively 'backward-word))))
13418 (defun org-metaright (&optional arg)
13419 "Demote subtree or move table column to right.
13420 Calls `org-do-demote' or `org-table-move-column', depending on context.
13421 With no specific context, calls the Emacs default `forward-word'.
13422 See the individual commands for more information."
13423 (interactive "P")
13424 (cond
13425 ((run-hook-with-args-until-success 'org-metaright-hook))
13426 ((org-at-table-p) (call-interactively 'org-table-move-column))
13427 ((or (org-on-heading-p) (org-region-active-p))
13428 (call-interactively 'org-do-demote))
13429 ((org-at-item-p) (call-interactively 'org-indent-item))
13430 (t (call-interactively 'forward-word))))
13432 (defun org-metaup (&optional arg)
13433 "Move subtree up or move table row up.
13434 Calls `org-move-subtree-up' or `org-table-move-row' or
13435 `org-move-item-up', depending on context. See the individual commands
13436 for more information."
13437 (interactive "P")
13438 (cond
13439 ((run-hook-with-args-until-success 'org-metaup-hook))
13440 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13441 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13442 ((org-at-item-p) (call-interactively 'org-move-item-up))
13443 (t (transpose-lines 1) (beginning-of-line -1))))
13445 (defun org-metadown (&optional arg)
13446 "Move subtree down or move table row down.
13447 Calls `org-move-subtree-down' or `org-table-move-row' or
13448 `org-move-item-down', depending on context. See the individual
13449 commands for more information."
13450 (interactive "P")
13451 (cond
13452 ((run-hook-with-args-until-success 'org-metadown-hook))
13453 ((org-at-table-p) (call-interactively 'org-table-move-row))
13454 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13455 ((org-at-item-p) (call-interactively 'org-move-item-down))
13456 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13458 (defun org-shiftup (&optional arg)
13459 "Increase item in timestamp or increase priority of current headline.
13460 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13461 depending on context. See the individual commands for more information."
13462 (interactive "P")
13463 (cond
13464 ((and org-support-shift-select (org-region-active-p))
13465 (org-call-for-shift-select 'previous-line))
13466 ((org-at-timestamp-p t)
13467 (call-interactively (if org-edit-timestamp-down-means-later
13468 'org-timestamp-down 'org-timestamp-up)))
13469 ((and (not (eq org-support-shift-select 'always))
13470 (org-on-heading-p))
13471 (call-interactively 'org-priority-up))
13472 ((and (not org-support-shift-select) (org-at-item-p))
13473 (call-interactively 'org-previous-item))
13474 ((org-clocktable-try-shift 'up arg))
13475 (org-support-shift-select
13476 (org-call-for-shift-select 'previous-line))
13477 (t (org-shiftselect-error))))
13479 (defun org-shiftdown (&optional arg)
13480 "Decrease item in timestamp or decrease priority of current headline.
13481 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13482 depending on context. See the individual commands for more information."
13483 (interactive "P")
13484 (cond
13485 ((and org-support-shift-select (org-region-active-p))
13486 (org-call-for-shift-select 'next-line))
13487 ((org-at-timestamp-p t)
13488 (call-interactively (if org-edit-timestamp-down-means-later
13489 'org-timestamp-up 'org-timestamp-down)))
13490 ((and (not (eq org-support-shift-select 'always))
13491 (org-on-heading-p))
13492 (call-interactively 'org-priority-down))
13493 ((and (not org-support-shift-select) (org-at-item-p))
13494 (call-interactively 'org-next-item))
13495 ((org-clocktable-try-shift 'down arg))
13496 (org-support-shift-select
13497 (org-call-for-shift-select 'next-line))
13498 (t (org-shiftselect-error))))
13500 (defun org-shiftright (&optional arg)
13501 "Cycle the thing at point or in the current line, depending on context.
13502 Depending on context, this does one of the following:
13504 - switch a timestamp at point one day into the future
13505 - on a headline, switch to the next TODO keyword.
13506 - on an item, switch entire list to the next bullet type
13507 - on a property line, switch to the next allowed value
13508 - on a clocktable definition line, move time block into the future"
13509 (interactive "P")
13510 (cond
13511 ((and org-support-shift-select (org-region-active-p))
13512 (org-call-for-shift-select 'forward-char))
13513 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13514 ((and (not (eq org-support-shift-select 'always))
13515 (org-on-heading-p))
13516 (org-call-with-arg 'org-todo 'right))
13517 ((or (and org-support-shift-select
13518 (not (eq org-support-shift-select 'always))
13519 (org-at-item-bullet-p))
13520 (and (not org-support-shift-select) (org-at-item-p)))
13521 (org-call-with-arg 'org-cycle-list-bullet nil))
13522 ((and (not (eq org-support-shift-select 'always))
13523 (org-at-property-p))
13524 (call-interactively 'org-property-next-allowed-value))
13525 ((org-clocktable-try-shift 'right arg))
13526 (org-support-shift-select
13527 (org-call-for-shift-select 'forward-char))
13528 (t (org-shiftselect-error))))
13530 (defun org-shiftleft (&optional arg)
13531 "Cycle the thing at point or in the current line, depending on context.
13532 Depending on context, this does one of the following:
13534 - switch a timestamp at point one day into the past
13535 - on a headline, switch to the previous TODO keyword.
13536 - on an item, switch entire list to the previous bullet type
13537 - on a property line, switch to the previous allowed value
13538 - on a clocktable definition line, move time block into the past"
13539 (interactive "P")
13540 (cond
13541 ((and org-support-shift-select (org-region-active-p))
13542 (org-call-for-shift-select 'backward-char))
13543 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13544 ((and (not (eq org-support-shift-select 'always))
13545 (org-on-heading-p))
13546 (org-call-with-arg 'org-todo 'left))
13547 ((or (and org-support-shift-select
13548 (not (eq org-support-shift-select 'always))
13549 (org-at-item-bullet-p))
13550 (and (not org-support-shift-select) (org-at-item-p)))
13551 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13552 ((and (not (eq org-support-shift-select 'always))
13553 (org-at-property-p))
13554 (call-interactively 'org-property-previous-allowed-value))
13555 ((org-clocktable-try-shift 'left arg))
13556 (org-support-shift-select
13557 (org-call-for-shift-select 'backward-char))
13558 (t (org-shiftselect-error))))
13560 (defun org-shiftcontrolright ()
13561 "Switch to next TODO set."
13562 (interactive)
13563 (cond
13564 ((and org-support-shift-select (org-region-active-p))
13565 (org-call-for-shift-select 'forward-word))
13566 ((and (not (eq org-support-shift-select 'always))
13567 (org-on-heading-p))
13568 (org-call-with-arg 'org-todo 'nextset))
13569 (org-support-shift-select
13570 (org-call-for-shift-select 'forward-word))
13571 (t (org-shiftselect-error))))
13573 (defun org-shiftcontrolleft ()
13574 "Switch to previous TODO set."
13575 (interactive)
13576 (cond
13577 ((and org-support-shift-select (org-region-active-p))
13578 (org-call-for-shift-select 'backward-word))
13579 ((and (not (eq org-support-shift-select 'always))
13580 (org-on-heading-p))
13581 (org-call-with-arg 'org-todo 'previousset))
13582 (org-support-shift-select
13583 (org-call-for-shift-select 'backward-word))
13584 (t (org-shiftselect-error))))
13586 (defun org-ctrl-c-ret ()
13587 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13588 (interactive)
13589 (cond
13590 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13591 (t (call-interactively 'org-insert-heading))))
13593 (defun org-copy-special ()
13594 "Copy region in table or copy current subtree.
13595 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13596 See the individual commands for more information."
13597 (interactive)
13598 (call-interactively
13599 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13601 (defun org-cut-special ()
13602 "Cut region in table or cut current subtree.
13603 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13604 See the individual commands for more information."
13605 (interactive)
13606 (call-interactively
13607 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13609 (defun org-paste-special (arg)
13610 "Paste rectangular region into table, or past subtree relative to level.
13611 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13612 See the individual commands for more information."
13613 (interactive "P")
13614 (if (org-at-table-p)
13615 (org-table-paste-rectangle)
13616 (org-paste-subtree arg)))
13618 (defun org-edit-special ()
13619 "Call a special editor for the stuff at point.
13620 When at a table, call the formula editor with `org-table-edit-formulas'.
13621 When at the first line of an src example, call `org-edit-src-code'.
13622 When in an #+include line, visit the include file. Otherwise call
13623 `ffap' to visit the file at point."
13624 (interactive)
13625 (cond
13626 ((org-at-table-p)
13627 (call-interactively 'org-table-edit-formulas))
13628 ((save-excursion
13629 (beginning-of-line 1)
13630 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13631 (find-file (org-trim (match-string 1))))
13632 ((org-edit-src-code))
13633 ((org-edit-fixed-width-region))
13634 (t (call-interactively 'ffap))))
13637 (defun org-ctrl-c-ctrl-c (&optional arg)
13638 "Set tags in headline, or update according to changed information at point.
13640 This command does many different things, depending on context:
13642 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
13643 this is what we do.
13645 - If the cursor is in a headline, prompt for tags and insert them
13646 into the current line, aligned to `org-tags-column'. When called
13647 with prefix arg, realign all tags in the current buffer.
13649 - If the cursor is in one of the special #+KEYWORD lines, this
13650 triggers scanning the buffer for these lines and updating the
13651 information.
13653 - If the cursor is inside a table, realign the table. This command
13654 works even if the automatic table editor has been turned off.
13656 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13657 the entire table.
13659 - If the cursor is at a footnote reference or definition, jump to
13660 the corresponding definition or references, respectively.
13662 - If the cursor is a the beginning of a dynamic block, update it.
13664 - If the cursor is inside a table created by the table.el package,
13665 activate that table.
13667 - If the current buffer is a remember buffer, close note and file
13668 it. A prefix argument of 1 files to the default location
13669 without further interaction. A prefix argument of 2 files to
13670 the currently clocking task.
13672 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13673 links in this buffer.
13675 - If the cursor is on a numbered item in a plain list, renumber the
13676 ordered list.
13678 - If the cursor is on a checkbox, toggle it."
13679 (interactive "P")
13680 (let ((org-enable-table-editor t))
13681 (cond
13682 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13683 org-occur-highlights
13684 org-latex-fragment-image-overlays)
13685 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13686 (org-remove-occur-highlights)
13687 (org-remove-latex-fragment-image-overlays)
13688 (message "Temporary highlights/overlays removed from current buffer"))
13689 ((and (local-variable-p 'org-finish-function (current-buffer))
13690 (fboundp org-finish-function))
13691 (funcall org-finish-function))
13692 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
13693 ((org-at-property-p)
13694 (call-interactively 'org-property-action))
13695 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13696 ((org-on-heading-p) (call-interactively 'org-set-tags))
13697 ((org-at-table.el-p)
13698 (require 'table)
13699 (beginning-of-line 1)
13700 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13701 (call-interactively 'table-recognize-table))
13702 ((org-at-table-p)
13703 (org-table-maybe-eval-formula)
13704 (if arg
13705 (call-interactively 'org-table-recalculate)
13706 (org-table-maybe-recalculate-line))
13707 (call-interactively 'org-table-align))
13708 ((or (org-footnote-at-reference-p)
13709 (org-footnote-at-definition-p))
13710 (call-interactively 'org-footnote-action))
13711 ((org-at-item-checkbox-p)
13712 (call-interactively 'org-toggle-checkbox))
13713 ((org-at-item-p)
13714 (if arg
13715 (call-interactively 'org-toggle-checkbox)
13716 (call-interactively 'org-maybe-renumber-ordered-list)))
13717 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13718 ;; Dynamic block
13719 (beginning-of-line 1)
13720 (save-excursion (org-update-dblock)))
13721 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13722 (cond
13723 ((equal (match-string 1) "TBLFM")
13724 ;; Recalculate the table before this line
13725 (save-excursion
13726 (beginning-of-line 1)
13727 (skip-chars-backward " \r\n\t")
13728 (if (org-at-table-p)
13729 (org-call-with-arg 'org-table-recalculate t))))
13731 ; (org-set-regexps-and-options)
13732 ; (org-restart-font-lock)
13733 (let ((org-inhibit-startup t)) (org-mode-restart))
13734 (message "Local setup has been refreshed"))))
13735 (t (error "C-c C-c can do nothing useful at this location.")))))
13737 (defun org-mode-restart ()
13738 "Restart Org-mode, to scan again for special lines.
13739 Also updates the keyword regular expressions."
13740 (interactive)
13741 (org-mode)
13742 (message "Org-mode restarted"))
13744 (defun org-kill-note-or-show-branches ()
13745 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13746 (interactive)
13747 (if (not org-finish-function)
13748 (call-interactively 'show-branches)
13749 (let ((org-note-abort t))
13750 (funcall org-finish-function))))
13752 (defun org-return (&optional indent)
13753 "Goto next table row or insert a newline.
13754 Calls `org-table-next-row' or `newline', depending on context.
13755 See the individual commands for more information."
13756 (interactive)
13757 (cond
13758 ((bobp) (if indent (newline-and-indent) (newline)))
13759 ((org-at-table-p)
13760 (org-table-justify-field-maybe)
13761 (call-interactively 'org-table-next-row))
13762 ((and org-return-follows-link
13763 (eq (get-text-property (point) 'face) 'org-link))
13764 (call-interactively 'org-open-at-point))
13765 ((and (org-at-heading-p)
13766 (looking-at
13767 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13768 (org-show-entry)
13769 (end-of-line 1)
13770 (newline))
13771 (t (if indent (newline-and-indent) (newline)))))
13773 (defun org-return-indent ()
13774 "Goto next table row or insert a newline and indent.
13775 Calls `org-table-next-row' or `newline-and-indent', depending on
13776 context. See the individual commands for more information."
13777 (interactive)
13778 (org-return t))
13780 (defun org-ctrl-c-star ()
13781 "Compute table, or change heading status of lines.
13782 Calls `org-table-recalculate' or `org-toggle-heading',
13783 depending on context."
13784 (interactive)
13785 (cond
13786 ((org-at-table-p)
13787 (call-interactively 'org-table-recalculate))
13789 ;; Convert all lines in region to list items
13790 (call-interactively 'org-toggle-heading))))
13792 (defun org-ctrl-c-minus ()
13793 "Insert separator line in table or modify bullet status of line.
13794 Also turns a plain line or a region of lines into list items.
13795 Calls `org-table-insert-hline', `org-toggle-item', or
13796 `org-cycle-list-bullet', depending on context."
13797 (interactive)
13798 (cond
13799 ((org-at-table-p)
13800 (call-interactively 'org-table-insert-hline))
13801 ((org-region-active-p)
13802 (call-interactively 'org-toggle-item))
13803 ((org-in-item-p)
13804 (call-interactively 'org-cycle-list-bullet))
13806 (call-interactively 'org-toggle-item))))
13808 (defun org-toggle-item ()
13809 "Convert headings or normal lines to items, items to normal lines.
13810 If there is no active region, only the current line is considered.
13812 If the first line in the region is a headline, convert all headlines to items.
13814 If the first line in the region is an item, convert all items to normal lines.
13816 If the first line is normal text, add an item bullet to each line."
13817 (interactive)
13818 (let (l2 l beg end)
13819 (if (org-region-active-p)
13820 (setq beg (region-beginning) end (region-end))
13821 (setq beg (point-at-bol)
13822 end (min (1+ (point-at-eol)) (point-max))))
13823 (save-excursion
13824 (goto-char end)
13825 (setq l2 (org-current-line))
13826 (goto-char beg)
13827 (beginning-of-line 1)
13828 (setq l (1- (org-current-line)))
13829 (if (org-at-item-p)
13830 ;; We already have items, de-itemize
13831 (while (< (setq l (1+ l)) l2)
13832 (when (org-at-item-p)
13833 (goto-char (match-beginning 2))
13834 (delete-region (match-beginning 2) (match-end 2))
13835 (and (looking-at "[ \t]+") (replace-match "")))
13836 (beginning-of-line 2))
13837 (if (org-on-heading-p)
13838 ;; Headings, convert to items
13839 (while (< (setq l (1+ l)) l2)
13840 (if (looking-at org-outline-regexp)
13841 (replace-match "- " t t))
13842 (beginning-of-line 2))
13843 ;; normal lines, turn them into items
13844 (while (< (setq l (1+ l)) l2)
13845 (unless (org-at-item-p)
13846 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13847 (replace-match "\\1- \\2")))
13848 (beginning-of-line 2)))))))
13850 (defun org-toggle-heading (&optional nstars)
13851 "Convert headings to normal text, or items or text to headings.
13852 If there is no active region, only the current line is considered.
13854 If the first line is a heading, remove the stars from all headlines
13855 in the region.
13857 If the first line is a plain list item, turn all plain list items into
13858 headings.
13860 If the first line is a normal line, turn each and every line in the region
13861 into a heading.
13863 When converting a line into a heading, the number of stars is chosen
13864 such that the lines become children of the current entry. However, when
13865 a prefix argument is given, its value determines the number of stars to add."
13866 (interactive "P")
13867 (let (l2 l itemp beg end)
13868 (if (org-region-active-p)
13869 (setq beg (region-beginning) end (region-end))
13870 (setq beg (point-at-bol)
13871 end (min (1+ (point-at-eol)) (point-max))))
13872 (save-excursion
13873 (goto-char end)
13874 (setq l2 (org-current-line))
13875 (goto-char beg)
13876 (beginning-of-line 1)
13877 (setq l (1- (org-current-line)))
13878 (if (org-on-heading-p)
13879 ;; We already have headlines, de-star them
13880 (while (< (setq l (1+ l)) l2)
13881 (when (org-on-heading-p t)
13882 (and (looking-at outline-regexp) (replace-match "")))
13883 (beginning-of-line 2))
13884 (setq itemp (org-at-item-p))
13885 (let* ((stars
13886 (if nstars
13887 (make-string (prefix-numeric-value current-prefix-arg)
13889 (save-excursion
13890 (re-search-backward org-complex-heading-regexp nil t)
13891 (or (match-string 1) "*"))))
13892 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13893 (rpl (concat stars add-stars " ")))
13894 (while (< (setq l (1+ l)) l2)
13895 (if itemp
13896 (and (org-at-item-p) (replace-match rpl t t))
13897 (unless (org-on-heading-p)
13898 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13899 (replace-match (concat rpl (match-string 2))))))
13900 (beginning-of-line 2)))))))
13902 (defun org-meta-return (&optional arg)
13903 "Insert a new heading or wrap a region in a table.
13904 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13905 See the individual commands for more information."
13906 (interactive "P")
13907 (cond
13908 ((run-hook-with-args-until-success 'org-metareturn-hook))
13909 ((org-at-table-p)
13910 (call-interactively 'org-table-wrap-region))
13911 (t (call-interactively 'org-insert-heading))))
13913 ;;; Menu entries
13915 ;; Define the Org-mode menus
13916 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13917 '("Tbl"
13918 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13919 ["Next Field" org-cycle (org-at-table-p)]
13920 ["Previous Field" org-shifttab (org-at-table-p)]
13921 ["Next Row" org-return (org-at-table-p)]
13922 "--"
13923 ["Blank Field" org-table-blank-field (org-at-table-p)]
13924 ["Edit Field" org-table-edit-field (org-at-table-p)]
13925 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13926 "--"
13927 ("Column"
13928 ["Move Column Left" org-metaleft (org-at-table-p)]
13929 ["Move Column Right" org-metaright (org-at-table-p)]
13930 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13931 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13932 ("Row"
13933 ["Move Row Up" org-metaup (org-at-table-p)]
13934 ["Move Row Down" org-metadown (org-at-table-p)]
13935 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13936 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13937 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13938 "--"
13939 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13940 ("Rectangle"
13941 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13942 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13943 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13944 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13945 "--"
13946 ("Calculate"
13947 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13948 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13949 ["Edit Formulas" org-edit-special (org-at-table-p)]
13950 "--"
13951 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13952 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13953 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13954 "--"
13955 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13956 "--"
13957 ["Sum Column/Rectangle" org-table-sum
13958 (or (org-at-table-p) (org-region-active-p))]
13959 ["Which Column?" org-table-current-column (org-at-table-p)])
13960 ["Debug Formulas"
13961 org-table-toggle-formula-debugger
13962 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13963 ["Show Col/Row Numbers"
13964 org-table-toggle-coordinate-overlays
13965 :style toggle
13966 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13967 "--"
13968 ["Create" org-table-create (and (not (org-at-table-p))
13969 org-enable-table-editor)]
13970 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13971 ["Import from File" org-table-import (not (org-at-table-p))]
13972 ["Export to File" org-table-export (org-at-table-p)]
13973 "--"
13974 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13976 (easy-menu-define org-org-menu org-mode-map "Org menu"
13977 '("Org"
13978 ("Show/Hide"
13979 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13980 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13981 ["Sparse Tree..." org-sparse-tree t]
13982 ["Reveal Context" org-reveal t]
13983 ["Show All" show-all t]
13984 "--"
13985 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13986 "--"
13987 ["New Heading" org-insert-heading t]
13988 ("Navigate Headings"
13989 ["Up" outline-up-heading t]
13990 ["Next" outline-next-visible-heading t]
13991 ["Previous" outline-previous-visible-heading t]
13992 ["Next Same Level" outline-forward-same-level t]
13993 ["Previous Same Level" outline-backward-same-level t]
13994 "--"
13995 ["Jump" org-goto t])
13996 ("Edit Structure"
13997 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13998 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13999 "--"
14000 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14001 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14002 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14003 "--"
14004 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14005 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14006 ["Demote Heading" org-metaright (not (org-at-table-p))]
14007 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14008 "--"
14009 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14010 "--"
14011 ["Convert to odd levels" org-convert-to-odd-levels t]
14012 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14013 ("Editing"
14014 ["Emphasis..." org-emphasize t]
14015 ["Edit Source Example" org-edit-special t]
14016 "--"
14017 ["Footnote new/jump" org-footnote-action t]
14018 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14019 ("Archive"
14020 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14021 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14022 ; :active t :keys "C-u C-c C-x C-a"]
14023 ["Sparse trees open ARCHIVE trees"
14024 (setq org-sparse-tree-open-archived-trees
14025 (not org-sparse-tree-open-archived-trees))
14026 :style toggle :selected org-sparse-tree-open-archived-trees]
14027 ["Cycling opens ARCHIVE trees"
14028 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14029 :style toggle :selected org-cycle-open-archived-trees]
14030 "--"
14031 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14032 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14033 ; ["Check and Move Children" (org-archive-subtree '(4))
14034 ; :active t :keys "C-u C-c C-x C-s"]
14036 "--"
14037 ("TODO Lists"
14038 ["TODO/DONE/-" org-todo t]
14039 ("Select keyword"
14040 ["Next keyword" org-shiftright (org-on-heading-p)]
14041 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14042 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14043 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14044 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14045 ["Show TODO Tree" org-show-todo-tree t]
14046 ["Global TODO list" org-todo-list t]
14047 "--"
14048 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14049 :selected org-enforce-todo-dependencies :style toggle :active t]
14050 "Settings for tree at point"
14051 ["Do Children sequentially" org-toggle-ordered-property :style radio
14052 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14053 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14054 ["Do Children parallel" org-toggle-ordered-property :style radio
14055 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14056 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14057 "--"
14058 ["Set Priority" org-priority t]
14059 ["Priority Up" org-shiftup t]
14060 ["Priority Down" org-shiftdown t])
14061 ("TAGS and Properties"
14062 ["Set Tags" org-set-tags-command t]
14063 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14064 "--"
14065 ["Set property" org-set-property t]
14066 ["Column view of properties" org-columns t]
14067 ["Insert Column View DBlock" org-insert-columns-dblock t])
14068 ("Dates and Scheduling"
14069 ["Timestamp" org-time-stamp t]
14070 ["Timestamp (inactive)" org-time-stamp-inactive t]
14071 ("Change Date"
14072 ["1 Day Later" org-shiftright t]
14073 ["1 Day Earlier" org-shiftleft t]
14074 ["1 ... Later" org-shiftup t]
14075 ["1 ... Earlier" org-shiftdown t])
14076 ["Compute Time Range" org-evaluate-time-range t]
14077 ["Schedule Item" org-schedule t]
14078 ["Deadline" org-deadline t]
14079 "--"
14080 ["Custom time format" org-toggle-time-stamp-overlays
14081 :style radio :selected org-display-custom-times]
14082 "--"
14083 ["Goto Calendar" org-goto-calendar t]
14084 ["Date from Calendar" org-date-from-calendar t]
14085 "--"
14086 ["Start/Restart Timer" org-timer-start t]
14087 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14088 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14089 ["Insert Timer String" org-timer t]
14090 ["Insert Timer Item" org-timer-item t])
14091 ("Logging work"
14092 ["Clock in" org-clock-in t]
14093 ["Clock out" org-clock-out t]
14094 ["Clock cancel" org-clock-cancel t]
14095 ["Goto running clock" org-clock-goto t]
14096 ["Display times" org-clock-display t]
14097 ["Create clock table" org-clock-report t]
14098 "--"
14099 ["Record DONE time"
14100 (progn (setq org-log-done (not org-log-done))
14101 (message "Switching to %s will %s record a timestamp"
14102 (car org-done-keywords)
14103 (if org-log-done "automatically" "not")))
14104 :style toggle :selected org-log-done])
14105 "--"
14106 ["Agenda Command..." org-agenda t]
14107 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14108 ("File List for Agenda")
14109 ("Special views current file"
14110 ["TODO Tree" org-show-todo-tree t]
14111 ["Check Deadlines" org-check-deadlines t]
14112 ["Timeline" org-timeline t]
14113 ["Tags Tree" org-tags-sparse-tree t])
14114 "--"
14115 ("Hyperlinks"
14116 ["Store Link (Global)" org-store-link t]
14117 ["Insert Link" org-insert-link t]
14118 ["Follow Link" org-open-at-point t]
14119 "--"
14120 ["Next link" org-next-link t]
14121 ["Previous link" org-previous-link t]
14122 "--"
14123 ["Descriptive Links"
14124 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14125 :style radio
14126 :selected (member '(org-link) buffer-invisibility-spec)]
14127 ["Literal Links"
14128 (progn
14129 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14130 :style radio
14131 :selected (not (member '(org-link) buffer-invisibility-spec))])
14132 "--"
14133 ["Export/Publish..." org-export t]
14134 ("LaTeX"
14135 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14136 :selected org-cdlatex-mode]
14137 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14138 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14139 ["Modify math symbol" org-cdlatex-math-modify
14140 (org-inside-LaTeX-fragment-p)]
14141 ["Export LaTeX fragments as images"
14142 (if (featurep 'org-exp)
14143 (setq org-export-with-LaTeX-fragments
14144 (not org-export-with-LaTeX-fragments))
14145 (require 'org-exp))
14146 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14147 org-export-with-LaTeX-fragments)])
14148 "--"
14149 ("Documentation"
14150 ["Show Version" org-version t]
14151 ["Info Documentation" org-info t])
14152 ("Customize"
14153 ["Browse Org Group" org-customize t]
14154 "--"
14155 ["Expand This Menu" org-create-customize-menu
14156 (fboundp 'customize-menu-create)])
14157 "--"
14158 ["Refresh setup" org-mode-restart t]
14161 (defun org-info (&optional node)
14162 "Read documentation for Org-mode in the info system.
14163 With optional NODE, go directly to that node."
14164 (interactive)
14165 (info (format "(org)%s" (or node ""))))
14167 (defun org-install-agenda-files-menu ()
14168 (let ((bl (buffer-list)))
14169 (save-excursion
14170 (while bl
14171 (set-buffer (pop bl))
14172 (if (org-mode-p) (setq bl nil)))
14173 (when (org-mode-p)
14174 (easy-menu-change
14175 '("Org") "File List for Agenda"
14176 (append
14177 (list
14178 ["Edit File List" (org-edit-agenda-file-list) t]
14179 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14180 ["Remove Current File from List" org-remove-file t]
14181 ["Cycle through agenda files" org-cycle-agenda-files t]
14182 ["Occur in all agenda files" org-occur-in-agenda-files t]
14183 "--")
14184 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14186 ;;;; Documentation
14188 ;;;###autoload
14189 (defun org-require-autoloaded-modules ()
14190 (interactive)
14191 (mapc 'require
14192 '(org-agenda org-archive org-attach org-clock org-colview
14193 org-exp org-id org-export-latex org-publish
14194 org-remember org-table org-timer)))
14196 ;;;###autoload
14197 (defun org-customize ()
14198 "Call the customize function with org as argument."
14199 (interactive)
14200 (org-load-modules-maybe)
14201 (org-require-autoloaded-modules)
14202 (customize-browse 'org))
14204 (defun org-create-customize-menu ()
14205 "Create a full customization menu for Org-mode, insert it into the menu."
14206 (interactive)
14207 (org-load-modules-maybe)
14208 (org-require-autoloaded-modules)
14209 (if (fboundp 'customize-menu-create)
14210 (progn
14211 (easy-menu-change
14212 '("Org") "Customize"
14213 `(["Browse Org group" org-customize t]
14214 "--"
14215 ,(customize-menu-create 'org)
14216 ["Set" Custom-set t]
14217 ["Save" Custom-save t]
14218 ["Reset to Current" Custom-reset-current t]
14219 ["Reset to Saved" Custom-reset-saved t]
14220 ["Reset to Standard Settings" Custom-reset-standard t]))
14221 (message "\"Org\"-menu now contains full customization menu"))
14222 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14224 ;;;; Miscellaneous stuff
14226 ;;; Generally useful functions
14228 (defun org-find-text-property-in-string (prop s)
14229 "Return the first non-nil value of property PROP in string S."
14230 (or (get-text-property 0 prop s)
14231 (get-text-property (or (next-single-property-change 0 prop s) 0)
14232 prop s)))
14234 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14235 "Display the given MESSAGE as a warning."
14236 (if (fboundp 'display-warning)
14237 (display-warning 'org message
14238 (if (featurep 'xemacs)
14239 'warning
14240 :warning))
14241 (let ((buf (get-buffer-create "*Org warnings*")))
14242 (with-current-buffer buf
14243 (goto-char (point-max))
14244 (insert "Warning (Org): " message)
14245 (unless (bolp)
14246 (newline)))
14247 (display-buffer buf)
14248 (sit-for 0))))
14250 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14251 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14252 (if (and marker (marker-buffer marker)
14253 (buffer-live-p (marker-buffer marker)))
14254 (progn
14255 (switch-to-buffer (marker-buffer marker))
14256 (if (or (> marker (point-max)) (< marker (point-min)))
14257 (widen))
14258 (goto-char marker)
14259 (org-show-context 'org-goto))
14260 (if bookmark
14261 (bookmark-jump bookmark)
14262 (error "Cannot find location"))))
14264 (defun org-quote-csv-field (s)
14265 "Quote field for inclusion in CSV material."
14266 (if (string-match "[\",]" s)
14267 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14270 (defun org-plist-delete (plist property)
14271 "Delete PROPERTY from PLIST.
14272 This is in contrast to merely setting it to 0."
14273 (let (p)
14274 (while plist
14275 (if (not (eq property (car plist)))
14276 (setq p (plist-put p (car plist) (nth 1 plist))))
14277 (setq plist (cddr plist)))
14280 (defun org-force-self-insert (N)
14281 "Needed to enforce self-insert under remapping."
14282 (interactive "p")
14283 (self-insert-command N))
14285 (defun org-string-width (s)
14286 "Compute width of string, ignoring invisible characters.
14287 This ignores character with invisibility property `org-link', and also
14288 characters with property `org-cwidth', because these will become invisible
14289 upon the next fontification round."
14290 (let (b l)
14291 (when (or (eq t buffer-invisibility-spec)
14292 (assq 'org-link buffer-invisibility-spec))
14293 (while (setq b (text-property-any 0 (length s)
14294 'invisible 'org-link s))
14295 (setq s (concat (substring s 0 b)
14296 (substring s (or (next-single-property-change
14297 b 'invisible s) (length s)))))))
14298 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14299 (setq s (concat (substring s 0 b)
14300 (substring s (or (next-single-property-change
14301 b 'org-cwidth s) (length s))))))
14302 (setq l (string-width s) b -1)
14303 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14304 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14307 (defun org-get-indentation (&optional line)
14308 "Get the indentation of the current line, interpreting tabs.
14309 When LINE is given, assume it represents a line and compute its indentation."
14310 (if line
14311 (if (string-match "^ *" (org-remove-tabs line))
14312 (match-end 0))
14313 (save-excursion
14314 (beginning-of-line 1)
14315 (skip-chars-forward " \t")
14316 (current-column))))
14318 (defun org-remove-tabs (s &optional width)
14319 "Replace tabulators in S with spaces.
14320 Assumes that s is a single line, starting in column 0."
14321 (setq width (or width tab-width))
14322 (while (string-match "\t" s)
14323 (setq s (replace-match
14324 (make-string
14325 (- (* width (/ (+ (match-beginning 0) width) width))
14326 (match-beginning 0)) ?\ )
14327 t t s)))
14330 (defun org-fix-indentation (line ind)
14331 "Fix indentation in LINE.
14332 IND is a cons cell with target and minimum indentation.
14333 If the current indentation in LINE is smaller than the minimum,
14334 leave it alone. If it is larger than ind, set it to the target."
14335 (let* ((l (org-remove-tabs line))
14336 (i (org-get-indentation l))
14337 (i1 (car ind)) (i2 (cdr ind)))
14338 (if (>= i i2) (setq l (substring line i2)))
14339 (if (> i1 0)
14340 (concat (make-string i1 ?\ ) l)
14341 l)))
14343 (defun org-base-buffer (buffer)
14344 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14345 (if (not buffer)
14346 buffer
14347 (or (buffer-base-buffer buffer)
14348 buffer)))
14350 (defun org-trim (s)
14351 "Remove whitespace at beginning and end of string."
14352 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14353 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14356 (defun org-wrap (string &optional width lines)
14357 "Wrap string to either a number of lines, or a width in characters.
14358 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14359 that costs. If there is a word longer than WIDTH, the text is actually
14360 wrapped to the length of that word.
14361 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14362 many lines, whatever width that takes.
14363 The return value is a list of lines, without newlines at the end."
14364 (let* ((words (org-split-string string "[ \t\n]+"))
14365 (maxword (apply 'max (mapcar 'org-string-width words)))
14366 w ll)
14367 (cond (width
14368 (org-do-wrap words (max maxword width)))
14369 (lines
14370 (setq w maxword)
14371 (setq ll (org-do-wrap words maxword))
14372 (if (<= (length ll) lines)
14374 (setq ll words)
14375 (while (> (length ll) lines)
14376 (setq w (1+ w))
14377 (setq ll (org-do-wrap words w)))
14378 ll))
14379 (t (error "Cannot wrap this")))))
14381 (defun org-do-wrap (words width)
14382 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14383 (let (lines line)
14384 (while words
14385 (setq line (pop words))
14386 (while (and words (< (+ (length line) (length (car words))) width))
14387 (setq line (concat line " " (pop words))))
14388 (setq lines (push line lines)))
14389 (nreverse lines)))
14391 (defun org-split-string (string &optional separators)
14392 "Splits STRING into substrings at SEPARATORS.
14393 No empty strings are returned if there are matches at the beginning
14394 and end of string."
14395 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14396 (start 0)
14397 notfirst
14398 (list nil))
14399 (while (and (string-match rexp string
14400 (if (and notfirst
14401 (= start (match-beginning 0))
14402 (< start (length string)))
14403 (1+ start) start))
14404 (< (match-beginning 0) (length string)))
14405 (setq notfirst t)
14406 (or (eq (match-beginning 0) 0)
14407 (and (eq (match-beginning 0) (match-end 0))
14408 (eq (match-beginning 0) start))
14409 (setq list
14410 (cons (substring string start (match-beginning 0))
14411 list)))
14412 (setq start (match-end 0)))
14413 (or (eq start (length string))
14414 (setq list
14415 (cons (substring string start)
14416 list)))
14417 (nreverse list)))
14419 (defun org-context ()
14420 "Return a list of contexts of the current cursor position.
14421 If several contexts apply, all are returned.
14422 Each context entry is a list with a symbol naming the context, and
14423 two positions indicating start and end of the context. Possible
14424 contexts are:
14426 :headline anywhere in a headline
14427 :headline-stars on the leading stars in a headline
14428 :todo-keyword on a TODO keyword (including DONE) in a headline
14429 :tags on the TAGS in a headline
14430 :priority on the priority cookie in a headline
14431 :item on the first line of a plain list item
14432 :item-bullet on the bullet/number of a plain list item
14433 :checkbox on the checkbox in a plain list item
14434 :table in an org-mode table
14435 :table-special on a special filed in a table
14436 :table-table in a table.el table
14437 :link on a hyperlink
14438 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14439 :target on a <<target>>
14440 :radio-target on a <<<radio-target>>>
14441 :latex-fragment on a LaTeX fragment
14442 :latex-preview on a LaTeX fragment with overlayed preview image
14444 This function expects the position to be visible because it uses font-lock
14445 faces as a help to recognize the following contexts: :table-special, :link,
14446 and :keyword."
14447 (let* ((f (get-text-property (point) 'face))
14448 (faces (if (listp f) f (list f)))
14449 (p (point)) clist o)
14450 ;; First the large context
14451 (cond
14452 ((org-on-heading-p t)
14453 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14454 (when (progn
14455 (beginning-of-line 1)
14456 (looking-at org-todo-line-tags-regexp))
14457 (push (org-point-in-group p 1 :headline-stars) clist)
14458 (push (org-point-in-group p 2 :todo-keyword) clist)
14459 (push (org-point-in-group p 4 :tags) clist))
14460 (goto-char p)
14461 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14462 (if (looking-at "\\[#[A-Z0-9]\\]")
14463 (push (org-point-in-group p 0 :priority) clist)))
14465 ((org-at-item-p)
14466 (push (org-point-in-group p 2 :item-bullet) clist)
14467 (push (list :item (point-at-bol)
14468 (save-excursion (org-end-of-item) (point)))
14469 clist)
14470 (and (org-at-item-checkbox-p)
14471 (push (org-point-in-group p 0 :checkbox) clist)))
14473 ((org-at-table-p)
14474 (push (list :table (org-table-begin) (org-table-end)) clist)
14475 (if (memq 'org-formula faces)
14476 (push (list :table-special
14477 (previous-single-property-change p 'face)
14478 (next-single-property-change p 'face)) clist)))
14479 ((org-at-table-p 'any)
14480 (push (list :table-table) clist)))
14481 (goto-char p)
14483 ;; Now the small context
14484 (cond
14485 ((org-at-timestamp-p)
14486 (push (org-point-in-group p 0 :timestamp) clist))
14487 ((memq 'org-link faces)
14488 (push (list :link
14489 (previous-single-property-change p 'face)
14490 (next-single-property-change p 'face)) clist))
14491 ((memq 'org-special-keyword faces)
14492 (push (list :keyword
14493 (previous-single-property-change p 'face)
14494 (next-single-property-change p 'face)) clist))
14495 ((org-on-target-p)
14496 (push (org-point-in-group p 0 :target) clist)
14497 (goto-char (1- (match-beginning 0)))
14498 (if (looking-at org-radio-target-regexp)
14499 (push (org-point-in-group p 0 :radio-target) clist))
14500 (goto-char p))
14501 ((setq o (car (delq nil
14502 (mapcar
14503 (lambda (x)
14504 (if (memq x org-latex-fragment-image-overlays) x))
14505 (org-overlays-at (point))))))
14506 (push (list :latex-fragment
14507 (org-overlay-start o) (org-overlay-end o)) clist)
14508 (push (list :latex-preview
14509 (org-overlay-start o) (org-overlay-end o)) clist))
14510 ((org-inside-LaTeX-fragment-p)
14511 ;; FIXME: positions wrong.
14512 (push (list :latex-fragment (point) (point)) clist)))
14514 (setq clist (nreverse (delq nil clist)))
14515 clist))
14517 ;; FIXME: Compare with at-regexp-p Do we need both?
14518 (defun org-in-regexp (re &optional nlines visually)
14519 "Check if point is inside a match of regexp.
14520 Normally only the current line is checked, but you can include NLINES extra
14521 lines both before and after point into the search.
14522 If VISUALLY is set, require that the cursor is not after the match but
14523 really on, so that the block visually is on the match."
14524 (catch 'exit
14525 (let ((pos (point))
14526 (eol (point-at-eol (+ 1 (or nlines 0))))
14527 (inc (if visually 1 0)))
14528 (save-excursion
14529 (beginning-of-line (- 1 (or nlines 0)))
14530 (while (re-search-forward re eol t)
14531 (if (and (<= (match-beginning 0) pos)
14532 (>= (+ inc (match-end 0)) pos))
14533 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14535 (defun org-at-regexp-p (regexp)
14536 "Is point inside a match of REGEXP in the current line?"
14537 (catch 'exit
14538 (save-excursion
14539 (let ((pos (point)) (end (point-at-eol)))
14540 (beginning-of-line 1)
14541 (while (re-search-forward regexp end t)
14542 (if (and (<= (match-beginning 0) pos)
14543 (>= (match-end 0) pos))
14544 (throw 'exit t)))
14545 nil))))
14547 (defun org-occur-in-agenda-files (regexp &optional nlines)
14548 "Call `multi-occur' with buffers for all agenda files."
14549 (interactive "sOrg-files matching: \np")
14550 (let* ((files (org-agenda-files))
14551 (tnames (mapcar 'file-truename files))
14552 (extra org-agenda-text-search-extra-files)
14554 (when (eq (car extra) 'agenda-archives)
14555 (setq extra (cdr extra))
14556 (setq files (org-add-archive-files files)))
14557 (while (setq f (pop extra))
14558 (unless (member (file-truename f) tnames)
14559 (add-to-list 'files f 'append)
14560 (add-to-list 'tnames (file-truename f) 'append)))
14561 (multi-occur
14562 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14563 regexp)))
14565 (if (boundp 'occur-mode-find-occurrence-hook)
14566 ;; Emacs 23
14567 (add-hook 'occur-mode-find-occurrence-hook
14568 (lambda ()
14569 (when (org-mode-p)
14570 (org-reveal))))
14571 ;; Emacs 22
14572 (defadvice occur-mode-goto-occurrence
14573 (after org-occur-reveal activate)
14574 (and (org-mode-p) (org-reveal)))
14575 (defadvice occur-mode-goto-occurrence-other-window
14576 (after org-occur-reveal activate)
14577 (and (org-mode-p) (org-reveal)))
14578 (defadvice occur-mode-display-occurrence
14579 (after org-occur-reveal activate)
14580 (when (org-mode-p)
14581 (let ((pos (occur-mode-find-occurrence)))
14582 (with-current-buffer (marker-buffer pos)
14583 (save-excursion
14584 (goto-char pos)
14585 (org-reveal)))))))
14587 (defun org-uniquify (list)
14588 "Remove duplicate elements from LIST."
14589 (let (res)
14590 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14591 res))
14593 (defun org-delete-all (elts list)
14594 "Remove all elements in ELTS from LIST."
14595 (while elts
14596 (setq list (delete (pop elts) list)))
14597 list)
14599 (defun org-back-over-empty-lines ()
14600 "Move backwards over whitespace, to the beginning of the first empty line.
14601 Returns the number of empty lines passed."
14602 (let ((pos (point)))
14603 (skip-chars-backward " \t\n\r")
14604 (beginning-of-line 2)
14605 (goto-char (min (point) pos))
14606 (count-lines (point) pos)))
14608 (defun org-skip-whitespace ()
14609 (skip-chars-forward " \t\n\r"))
14611 (defun org-point-in-group (point group &optional context)
14612 "Check if POINT is in match-group GROUP.
14613 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14614 match. If the match group does ot exist or point is not inside it,
14615 return nil."
14616 (and (match-beginning group)
14617 (>= point (match-beginning group))
14618 (<= point (match-end group))
14619 (if context
14620 (list context (match-beginning group) (match-end group))
14621 t)))
14623 (defun org-switch-to-buffer-other-window (&rest args)
14624 "Switch to buffer in a second window on the current frame.
14625 In particular, do not allow pop-up frames."
14626 (let (pop-up-frames special-display-buffer-names special-display-regexps
14627 special-display-function)
14628 (apply 'switch-to-buffer-other-window args)))
14630 (defun org-combine-plists (&rest plists)
14631 "Create a single property list from all plists in PLISTS.
14632 The process starts by copying the first list, and then setting properties
14633 from the other lists. Settings in the last list are the most significant
14634 ones and overrule settings in the other lists."
14635 (let ((rtn (copy-sequence (pop plists)))
14636 p v ls)
14637 (while plists
14638 (setq ls (pop plists))
14639 (while ls
14640 (setq p (pop ls) v (pop ls))
14641 (setq rtn (plist-put rtn p v))))
14642 rtn))
14644 (defun org-move-line-down (arg)
14645 "Move the current line down. With prefix argument, move it past ARG lines."
14646 (interactive "p")
14647 (let ((col (current-column))
14648 beg end pos)
14649 (beginning-of-line 1) (setq beg (point))
14650 (beginning-of-line 2) (setq end (point))
14651 (beginning-of-line (+ 1 arg))
14652 (setq pos (move-marker (make-marker) (point)))
14653 (insert (delete-and-extract-region beg end))
14654 (goto-char pos)
14655 (org-move-to-column col)))
14657 (defun org-move-line-up (arg)
14658 "Move the current line up. With prefix argument, move it past ARG lines."
14659 (interactive "p")
14660 (let ((col (current-column))
14661 beg end pos)
14662 (beginning-of-line 1) (setq beg (point))
14663 (beginning-of-line 2) (setq end (point))
14664 (beginning-of-line (- arg))
14665 (setq pos (move-marker (make-marker) (point)))
14666 (insert (delete-and-extract-region beg end))
14667 (goto-char pos)
14668 (org-move-to-column col)))
14670 (defun org-replace-escapes (string table)
14671 "Replace %-escapes in STRING with values in TABLE.
14672 TABLE is an association list with keys like \"%a\" and string values.
14673 The sequences in STRING may contain normal field width and padding information,
14674 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14675 so values can contain further %-escapes if they are define later in TABLE."
14676 (let ((case-fold-search nil)
14677 e re rpl)
14678 (while (setq e (pop table))
14679 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14680 (while (string-match re string)
14681 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14682 (cdr e)))
14683 (setq string (replace-match rpl t t string))))
14684 string))
14687 (defun org-sublist (list start end)
14688 "Return a section of LIST, from START to END.
14689 Counting starts at 1."
14690 (let (rtn (c start))
14691 (setq list (nthcdr (1- start) list))
14692 (while (and list (<= c end))
14693 (push (pop list) rtn)
14694 (setq c (1+ c)))
14695 (nreverse rtn)))
14697 (defun org-find-base-buffer-visiting (file)
14698 "Like `find-buffer-visiting' but alway return the base buffer and
14699 not an indirect buffer."
14700 (let ((buf (find-buffer-visiting file)))
14701 (if buf
14702 (or (buffer-base-buffer buf) buf)
14703 nil)))
14705 (defun org-image-file-name-regexp (&optional extensions)
14706 "Return regexp matching the file names of images.
14707 If EXTENSIONS is given, only match these."
14708 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14709 (image-file-name-regexp)
14710 (let ((image-file-name-extensions
14711 (or extensions
14712 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14713 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14714 (concat "\\."
14715 (regexp-opt (nconc (mapcar 'upcase
14716 image-file-name-extensions)
14717 image-file-name-extensions)
14719 "\\'"))))
14721 (defun org-file-image-p (file &optional extensions)
14722 "Return non-nil if FILE is an image."
14723 (save-match-data
14724 (string-match (org-image-file-name-regexp extensions) file)))
14726 (defun org-get-cursor-date ()
14727 "Return the date at cursor in as a time.
14728 This works in the calendar and in the agenda, anywhere else it just
14729 returns the current time."
14730 (let (date day defd)
14731 (cond
14732 ((eq major-mode 'calendar-mode)
14733 (setq date (calendar-cursor-to-date)
14734 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14735 ((eq major-mode 'org-agenda-mode)
14736 (setq day (get-text-property (point) 'day))
14737 (if day
14738 (setq date (calendar-gregorian-from-absolute day)
14739 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14740 (nth 2 date))))))
14741 (or defd (current-time))))
14743 (defvar org-agenda-action-marker (make-marker)
14744 "Marker pointing to the entry for the next agenda action.")
14746 (defun org-mark-entry-for-agenda-action ()
14747 "Mark the current entry as target of an agenda action.
14748 Agenda actions are actions executed from the agenda with the key `k',
14749 which make use of the date at the cursor."
14750 (interactive)
14751 (move-marker org-agenda-action-marker
14752 (save-excursion (org-back-to-heading t) (point))
14753 (current-buffer))
14754 (message
14755 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14757 ;;; Paragraph filling stuff.
14758 ;; We want this to be just right, so use the full arsenal.
14760 (defun org-indent-line-function ()
14761 "Indent line like previous, but further if previous was headline or item."
14762 (interactive)
14763 (let* ((pos (point))
14764 (itemp (org-at-item-p))
14765 column bpos bcol tpos tcol bullet btype bullet-type)
14766 ;; Find the previous relevant line
14767 (beginning-of-line 1)
14768 (cond
14769 ((looking-at "#") (setq column 0))
14770 ((looking-at "\\*+ ") (setq column 0))
14771 ((and (looking-at "[ \t]*:END:")
14772 (save-excursion (re-search-backward org-drawer-regexp nil t)))
14773 (save-excursion
14774 (goto-char (1- (match-beginning 1)))
14775 (setq column (current-column))))
14777 (beginning-of-line 0)
14778 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
14779 (not (looking-at "[ \t]*:END:"))
14780 (not (looking-at org-drawer-regexp)))
14781 (beginning-of-line 0))
14782 (cond
14783 ((looking-at "\\*+[ \t]+")
14784 (if (not org-adapt-indentation)
14785 (setq column 0)
14786 (goto-char (match-end 0))
14787 (setq column (current-column))))
14788 ((looking-at org-drawer-regexp)
14789 (goto-char (1- (match-beginning 1)))
14790 (setq column (current-column)))
14791 ((looking-at "\\([ \t]*\\):END:")
14792 (goto-char (match-end 1))
14793 (setq column (current-column)))
14794 ((org-in-item-p)
14795 (org-beginning-of-item)
14796 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14797 (setq bpos (match-beginning 1) tpos (match-end 0)
14798 bcol (progn (goto-char bpos) (current-column))
14799 tcol (progn (goto-char tpos) (current-column))
14800 bullet (match-string 1)
14801 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14802 (if (> tcol (+ bcol org-description-max-indent))
14803 (setq tcol (+ bcol 5)))
14804 (if (not itemp)
14805 (setq column tcol)
14806 (goto-char pos)
14807 (beginning-of-line 1)
14808 (if (looking-at "\\S-")
14809 (progn
14810 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14811 (setq bullet (match-string 1)
14812 btype (if (string-match "[0-9]" bullet) "n" bullet))
14813 (setq column (if (equal btype bullet-type) bcol tcol)))
14814 (setq column (org-get-indentation)))))
14815 (t (setq column (org-get-indentation))))))
14816 (goto-char pos)
14817 (if (<= (current-column) (current-indentation))
14818 (org-indent-line-to column)
14819 (save-excursion (org-indent-line-to column)))
14820 (setq column (current-column))
14821 (beginning-of-line 1)
14822 (if (looking-at
14823 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14824 (replace-match (concat "\\1" (format org-property-format
14825 (match-string 2) (match-string 3)))
14826 t nil))
14827 (org-move-to-column column)))
14829 (defun org-set-autofill-regexps ()
14830 (interactive)
14831 ;; In the paragraph separator we include headlines, because filling
14832 ;; text in a line directly attached to a headline would otherwise
14833 ;; fill the headline as well.
14834 (org-set-local 'comment-start-skip "^#+[ \t]*")
14835 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14836 ;; The paragraph starter includes hand-formatted lists.
14837 (org-set-local 'paragraph-start
14838 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14839 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14840 ;; But only if the user has not turned off tables or fixed-width regions
14841 (org-set-local
14842 'auto-fill-inhibit-regexp
14843 (concat "\\*+ \\|#\\+"
14844 "\\|[ \t]*" org-keyword-time-regexp
14845 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14846 (concat
14847 "\\|[ \t]*["
14848 (if org-enable-table-editor "|" "")
14849 (if org-enable-fixed-width-editor ":" "")
14850 "]"))))
14851 ;; We use our own fill-paragraph function, to make sure that tables
14852 ;; and fixed-width regions are not wrapped. That function will pass
14853 ;; through to `fill-paragraph' when appropriate.
14854 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14855 ; Adaptive filling: To get full control, first make sure that
14856 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14857 (org-set-local 'adaptive-fill-regexp "\000")
14858 (org-set-local 'adaptive-fill-function
14859 'org-adaptive-fill-function)
14860 (org-set-local
14861 'align-mode-rules-list
14862 '((org-in-buffer-settings
14863 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14864 (modes . '(org-mode))))))
14866 (defun org-fill-paragraph (&optional justify)
14867 "Re-align a table, pass through to fill-paragraph if no table."
14868 (let ((table-p (org-at-table-p))
14869 (table.el-p (org-at-table.el-p)))
14870 (cond ((and (equal (char-after (point-at-bol)) ?*)
14871 (save-excursion (goto-char (point-at-bol))
14872 (looking-at outline-regexp)))
14873 t) ; skip headlines
14874 (table.el-p t) ; skip table.el tables
14875 (table-p (org-table-align) t) ; align org-mode tables
14876 (t nil)))) ; call paragraph-fill
14878 ;; For reference, this is the default value of adaptive-fill-regexp
14879 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14881 (defun org-adaptive-fill-function ()
14882 "Return a fill prefix for org-mode files.
14883 In particular, this makes sure hanging paragraphs for hand-formatted lists
14884 work correctly."
14885 (cond ((looking-at "#[ \t]+")
14886 (match-string 0))
14887 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14888 (save-excursion
14889 (if (> (match-end 1) (+ (match-beginning 1)
14890 org-description-max-indent))
14891 (goto-char (+ (match-beginning 1) 5))
14892 (goto-char (match-end 0)))
14893 (make-string (current-column) ?\ )))
14894 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14895 (save-excursion
14896 (goto-char (match-end 0))
14897 (make-string (current-column) ?\ )))
14898 (t nil)))
14900 ;;; Other stuff.
14902 (defun org-toggle-fixed-width-section (arg)
14903 "Toggle the fixed-width export.
14904 If there is no active region, the QUOTE keyword at the current headline is
14905 inserted or removed. When present, it causes the text between this headline
14906 and the next to be exported as fixed-width text, and unmodified.
14907 If there is an active region, this command adds or removes a colon as the
14908 first character of this line. If the first character of a line is a colon,
14909 this line is also exported in fixed-width font."
14910 (interactive "P")
14911 (let* ((cc 0)
14912 (regionp (org-region-active-p))
14913 (beg (if regionp (region-beginning) (point)))
14914 (end (if regionp (region-end)))
14915 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14916 (case-fold-search nil)
14917 (re "[ \t]*\\(:\\)")
14918 off)
14919 (if regionp
14920 (save-excursion
14921 (goto-char beg)
14922 (setq cc (current-column))
14923 (beginning-of-line 1)
14924 (setq off (looking-at re))
14925 (while (> nlines 0)
14926 (setq nlines (1- nlines))
14927 (beginning-of-line 1)
14928 (cond
14929 (arg
14930 (org-move-to-column cc t)
14931 (insert ":\n")
14932 (forward-line -1))
14933 ((and off (looking-at re))
14934 (replace-match "" t t nil 1))
14935 ((not off) (org-move-to-column cc t) (insert ":")))
14936 (forward-line 1)))
14937 (save-excursion
14938 (org-back-to-heading)
14939 (if (looking-at (concat outline-regexp
14940 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14941 (replace-match "" t t nil 1)
14942 (if (looking-at outline-regexp)
14943 (progn
14944 (goto-char (match-end 0))
14945 (insert org-quote-string " "))))))))
14947 ;;;; Functions extending outline functionality
14949 (defun org-beginning-of-line (&optional arg)
14950 "Go to the beginning of the current line. If that is invisible, continue
14951 to a visible line beginning. This makes the function of C-a more intuitive.
14952 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14953 first attempt, and only move to after the tags when the cursor is already
14954 beyond the end of the headline."
14955 (interactive "P")
14956 (let ((pos (point)) refpos)
14957 (beginning-of-line 1)
14958 (if (and arg (fboundp 'move-beginning-of-line))
14959 (call-interactively 'move-beginning-of-line)
14960 (if (bobp)
14962 (backward-char 1)
14963 (if (org-invisible-p)
14964 (while (and (not (bobp)) (org-invisible-p))
14965 (backward-char 1)
14966 (beginning-of-line 1))
14967 (forward-char 1))))
14968 (when org-special-ctrl-a/e
14969 (cond
14970 ((and (looking-at org-complex-heading-regexp)
14971 (= (char-after (match-end 1)) ?\ ))
14972 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14973 (point-at-eol)))
14974 (goto-char
14975 (if (eq org-special-ctrl-a/e t)
14976 (cond ((> pos refpos) refpos)
14977 ((= pos (point)) refpos)
14978 (t (point)))
14979 (cond ((> pos (point)) (point))
14980 ((not (eq last-command this-command)) (point))
14981 (t refpos)))))
14982 ((org-at-item-p)
14983 (goto-char
14984 (if (eq org-special-ctrl-a/e t)
14985 (cond ((> pos (match-end 4)) (match-end 4))
14986 ((= pos (point)) (match-end 4))
14987 (t (point)))
14988 (cond ((> pos (point)) (point))
14989 ((not (eq last-command this-command)) (point))
14990 (t (match-end 4))))))))
14991 (org-no-warnings
14992 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14994 (defun org-end-of-line (&optional arg)
14995 "Go to the end of the line.
14996 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14997 first attempt, and only move to after the tags when the cursor is already
14998 beyond the end of the headline."
14999 (interactive "P")
15000 (if (or (not org-special-ctrl-a/e)
15001 (not (org-on-heading-p))
15002 arg)
15003 (call-interactively (if (fboundp 'move-end-of-line)
15004 'move-end-of-line
15005 'end-of-line))
15006 (let ((pos (point)))
15007 (beginning-of-line 1)
15008 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15009 (if (eq org-special-ctrl-a/e t)
15010 (if (or (< pos (match-beginning 1))
15011 (= pos (match-end 0)))
15012 (goto-char (match-beginning 1))
15013 (goto-char (match-end 0)))
15014 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15015 (goto-char (match-end 0))
15016 (goto-char (match-beginning 1))))
15017 (call-interactively (if (fboundp 'move-end-of-line)
15018 'move-end-of-line
15019 'end-of-line)))))
15020 (org-no-warnings
15021 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
15024 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15025 (define-key org-mode-map "\C-e" 'org-end-of-line)
15027 (defun org-kill-line (&optional arg)
15028 "Kill line, to tags or end of line."
15029 (interactive "P")
15030 (cond
15031 ((or (not org-special-ctrl-k)
15032 (bolp)
15033 (not (org-on-heading-p)))
15034 (call-interactively 'kill-line))
15035 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15036 (kill-region (point) (match-beginning 1))
15037 (org-set-tags nil t))
15038 (t (kill-region (point) (point-at-eol)))))
15040 (define-key org-mode-map "\C-k" 'org-kill-line)
15042 (defun org-yank (&optional arg)
15043 "Yank. If the kill is a subtree, treat it specially.
15044 This command will look at the current kill and check if is a single
15045 subtree, or a series of subtrees[1]. If it passes the test, and if the
15046 cursor is at the beginning of a line or after the stars of a currently
15047 empty headline, then the yank is handled specially. How exactly depends
15048 on the value of the following variables, both set by default.
15050 org-yank-folded-subtrees
15051 When set, the subtree(s) will be folded after insertion, but only
15052 if doing so would now swallow text after the yanked text.
15054 org-yank-adjusted-subtrees
15055 When set, the subtree will be promoted or demoted in order to
15056 fit into the local outline tree structure, which means that the level
15057 will be adjusted so that it becomes the smaller one of the two
15058 *visible* surrounding headings.
15060 Any prefix to this command will cause `yank' to be called directly with
15061 no special treatment. In particular, a simple `C-u' prefix will just
15062 plainly yank the text as it is.
15064 \[1] Basically, the test checks if the first non-white line is a heading
15065 and if there are no other headings with fewer stars."
15066 (interactive "P")
15067 (setq this-command 'yank)
15068 (if arg
15069 (call-interactively 'yank)
15070 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15071 (and (org-kill-is-subtree-p)
15072 (or (bolp)
15073 (and (looking-at "[ \t]*$")
15074 (string-match
15075 "\\`\\*+\\'"
15076 (buffer-substring (point-at-bol) (point)))))))
15077 swallowp)
15078 (cond
15079 ((and subtreep org-yank-folded-subtrees)
15080 (let ((beg (point))
15081 end)
15082 (if (and subtreep org-yank-adjusted-subtrees)
15083 (org-paste-subtree nil nil 'for-yank)
15084 (call-interactively 'yank))
15085 (setq end (point))
15086 (goto-char beg)
15087 (when (and (bolp) subtreep
15088 (not (setq swallowp
15089 (org-yank-folding-would-swallow-text beg end))))
15090 (or (looking-at outline-regexp)
15091 (re-search-forward (concat "^" outline-regexp) end t))
15092 (while (and (< (point) end) (looking-at outline-regexp))
15093 (hide-subtree)
15094 (org-cycle-show-empty-lines 'folded)
15095 (condition-case nil
15096 (outline-forward-same-level 1)
15097 (error (goto-char end)))))
15098 (when swallowp
15099 (message
15100 "Yanked text not folded because that would swallow text"))
15101 (goto-char end)
15102 (skip-chars-forward " \t\n\r")
15103 (beginning-of-line 1)
15104 (push-mark beg 'nomsg)))
15105 ((and subtreep org-yank-adjusted-subtrees)
15106 (let ((beg (point-at-bol)))
15107 (org-paste-subtree nil nil 'for-yank)
15108 (push-mark beg 'nomsg)))
15110 (call-interactively 'yank))))))
15112 (defun org-yank-folding-would-swallow-text (beg end)
15113 "Would hide-subtree at BEG swallow any text after END?"
15114 (let (level)
15115 (save-excursion
15116 (goto-char beg)
15117 (when (or (looking-at outline-regexp)
15118 (re-search-forward (concat "^" outline-regexp) end t))
15119 (setq level (org-outline-level)))
15120 (goto-char end)
15121 (skip-chars-forward " \t\r\n\v\f")
15122 (if (or (eobp)
15123 (and (bolp) (looking-at org-outline-regexp)
15124 (<= (org-outline-level) level)))
15125 nil ; Nothing would be swallowed
15126 t)))) ; something would swallow
15128 (define-key org-mode-map "\C-y" 'org-yank)
15130 (defun org-invisible-p ()
15131 "Check if point is at a character currently not visible."
15132 ;; Early versions of noutline don't have `outline-invisible-p'.
15133 (if (fboundp 'outline-invisible-p)
15134 (outline-invisible-p)
15135 (get-char-property (point) 'invisible)))
15137 (defun org-invisible-p2 ()
15138 "Check if point is at a character currently not visible."
15139 (save-excursion
15140 (if (and (eolp) (not (bobp))) (backward-char 1))
15141 ;; Early versions of noutline don't have `outline-invisible-p'.
15142 (if (fboundp 'outline-invisible-p)
15143 (outline-invisible-p)
15144 (get-char-property (point) 'invisible))))
15146 (defun org-back-to-heading (&optional invisible-ok)
15147 "Call `outline-back-to-heading', but provide a better error message."
15148 (condition-case nil
15149 (outline-back-to-heading invisible-ok)
15150 (error (error "Before first headline at position %d in buffer %s"
15151 (point) (current-buffer)))))
15153 (defun org-before-first-heading-p ()
15154 "Before first heading?"
15155 (save-excursion
15156 (null (re-search-backward "^\\*+ " nil t))))
15158 (defalias 'org-on-heading-p 'outline-on-heading-p)
15159 (defalias 'org-at-heading-p 'outline-on-heading-p)
15160 (defun org-at-heading-or-item-p ()
15161 (or (org-on-heading-p) (org-at-item-p)))
15163 (defun org-on-target-p ()
15164 (or (org-in-regexp org-radio-target-regexp)
15165 (org-in-regexp org-target-regexp)))
15167 (defun org-up-heading-all (arg)
15168 "Move to the heading line of which the present line is a subheading.
15169 This function considers both visible and invisible heading lines.
15170 With argument, move up ARG levels."
15171 (if (fboundp 'outline-up-heading-all)
15172 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15173 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15175 (defun org-up-heading-safe ()
15176 "Move to the heading line of which the present line is a subheading.
15177 This version will not throw an error. It will return the level of the
15178 headline found, or nil if no higher level is found."
15179 (let (start-level re)
15180 (org-back-to-heading t)
15181 (setq start-level (funcall outline-level))
15182 (if (equal start-level 1)
15184 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15185 (if (re-search-backward re nil t)
15186 (funcall outline-level)))))
15188 (defun org-first-sibling-p ()
15189 "Is this heading the first child of its parents?"
15190 (interactive)
15191 (let ((re (concat "^" outline-regexp))
15192 level l)
15193 (unless (org-at-heading-p t)
15194 (error "Not at a heading"))
15195 (setq level (funcall outline-level))
15196 (save-excursion
15197 (if (not (re-search-backward re nil t))
15199 (setq l (funcall outline-level))
15200 (< l level)))))
15202 (defun org-goto-sibling (&optional previous)
15203 "Goto the next sibling, even if it is invisible.
15204 When PREVIOUS is set, go to the previous sibling instead. Returns t
15205 when a sibling was found. When none is found, return nil and don't
15206 move point."
15207 (let ((fun (if previous 're-search-backward 're-search-forward))
15208 (pos (point))
15209 (re (concat "^" outline-regexp))
15210 level l)
15211 (when (condition-case nil (org-back-to-heading t) (error nil))
15212 (setq level (funcall outline-level))
15213 (catch 'exit
15214 (or previous (forward-char 1))
15215 (while (funcall fun re nil t)
15216 (setq l (funcall outline-level))
15217 (when (< l level) (goto-char pos) (throw 'exit nil))
15218 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15219 (goto-char pos)
15220 nil))))
15222 (defun org-show-siblings ()
15223 "Show all siblings of the current headline."
15224 (save-excursion
15225 (while (org-goto-sibling) (org-flag-heading nil)))
15226 (save-excursion
15227 (while (org-goto-sibling 'previous)
15228 (org-flag-heading nil))))
15230 (defun org-show-hidden-entry ()
15231 "Show an entry where even the heading is hidden."
15232 (save-excursion
15233 (org-show-entry)))
15235 (defun org-flag-heading (flag &optional entry)
15236 "Flag the current heading. FLAG non-nil means make invisible.
15237 When ENTRY is non-nil, show the entire entry."
15238 (save-excursion
15239 (org-back-to-heading t)
15240 ;; Check if we should show the entire entry
15241 (if entry
15242 (progn
15243 (org-show-entry)
15244 (save-excursion
15245 (and (outline-next-heading)
15246 (org-flag-heading nil))))
15247 (outline-flag-region (max (point-min) (1- (point)))
15248 (save-excursion (outline-end-of-heading) (point))
15249 flag))))
15251 (defun org-forward-same-level (arg)
15252 "Move forward to the ARG'th subheading at same level as this one.
15253 Stop at the first and last subheadings of a superior heading.
15254 This is like outline-forward-same-level, but invisible headings are ok."
15255 (interactive "p")
15256 (org-back-to-heading t)
15257 (while (> arg 0)
15258 (let ((point-to-move-to (save-excursion
15259 (org-get-next-sibling))))
15260 (if point-to-move-to
15261 (progn
15262 (goto-char point-to-move-to)
15263 (setq arg (1- arg)))
15264 (progn
15265 (setq arg 0)
15266 (error "No following same-level heading"))))))
15268 (defun org-get-next-sibling ()
15269 "Move to next heading of the same level, and return point.
15270 If there is no such heading, return nil.
15271 This is like outline-next-sibling, but invisible headings are ok."
15272 (let ((level (funcall outline-level)))
15273 (outline-next-heading)
15274 (while (and (not (eobp)) (> (funcall outline-level) level))
15275 (outline-next-heading))
15276 (if (or (eobp) (< (funcall outline-level) level))
15278 (point))))
15280 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15281 ;; This is an exact copy of the original function, but it uses
15282 ;; `org-back-to-heading', to make it work also in invisible
15283 ;; trees. And is uses an invisible-OK argument.
15284 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15285 (org-back-to-heading invisible-OK)
15286 (let ((first t)
15287 (level (funcall outline-level)))
15288 (while (and (not (eobp))
15289 (or first (> (funcall outline-level) level)))
15290 (setq first nil)
15291 (outline-next-heading))
15292 (unless to-heading
15293 (if (memq (preceding-char) '(?\n ?\^M))
15294 (progn
15295 ;; Go to end of line before heading
15296 (forward-char -1)
15297 (if (memq (preceding-char) '(?\n ?\^M))
15298 ;; leave blank line before heading
15299 (forward-char -1))))))
15300 (point))
15302 (defun org-show-subtree ()
15303 "Show everything after this heading at deeper levels."
15304 (outline-flag-region
15305 (point)
15306 (save-excursion
15307 (outline-end-of-subtree) (outline-next-heading) (point))
15308 nil))
15310 (defun org-show-entry ()
15311 "Show the body directly following this heading.
15312 Show the heading too, if it is currently invisible."
15313 (interactive)
15314 (save-excursion
15315 (condition-case nil
15316 (progn
15317 (org-back-to-heading t)
15318 (outline-flag-region
15319 (max (point-min) (1- (point)))
15320 (save-excursion
15321 (if (re-search-forward
15322 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15323 (match-beginning 1)
15324 (point-max)))
15325 nil))
15326 (error nil))))
15328 (defun org-make-options-regexp (kwds &optional extra)
15329 "Make a regular expression for keyword lines."
15330 (concat
15332 "#?[ \t]*\\+\\("
15333 (mapconcat 'regexp-quote kwds "\\|")
15334 (if extra (concat "\\|" extra))
15335 "\\):[ \t]*"
15336 "\\(.+\\)"))
15338 ;; Make isearch reveal the necessary context
15339 (defun org-isearch-end ()
15340 "Reveal context after isearch exits."
15341 (when isearch-success ; only if search was successful
15342 (if (featurep 'xemacs)
15343 ;; Under XEmacs, the hook is run in the correct place,
15344 ;; we directly show the context.
15345 (org-show-context 'isearch)
15346 ;; In Emacs the hook runs *before* restoring the overlays.
15347 ;; So we have to use a one-time post-command-hook to do this.
15348 ;; (Emacs 22 has a special variable, see function `org-mode')
15349 (unless (and (boundp 'isearch-mode-end-hook-quit)
15350 isearch-mode-end-hook-quit)
15351 ;; Only when the isearch was not quitted.
15352 (org-add-hook 'post-command-hook 'org-isearch-post-command
15353 'append 'local)))))
15355 (defun org-isearch-post-command ()
15356 "Remove self from hook, and show context."
15357 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15358 (org-show-context 'isearch))
15361 ;;;; Integration with and fixes for other packages
15363 ;;; Imenu support
15365 (defvar org-imenu-markers nil
15366 "All markers currently used by Imenu.")
15367 (make-variable-buffer-local 'org-imenu-markers)
15369 (defun org-imenu-new-marker (&optional pos)
15370 "Return a new marker for use by Imenu, and remember the marker."
15371 (let ((m (make-marker)))
15372 (move-marker m (or pos (point)))
15373 (push m org-imenu-markers)
15376 (defun org-imenu-get-tree ()
15377 "Produce the index for Imenu."
15378 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15379 (setq org-imenu-markers nil)
15380 (let* ((n org-imenu-depth)
15381 (re (concat "^" outline-regexp))
15382 (subs (make-vector (1+ n) nil))
15383 (last-level 0)
15384 m level head)
15385 (save-excursion
15386 (save-restriction
15387 (widen)
15388 (goto-char (point-max))
15389 (while (re-search-backward re nil t)
15390 (setq level (org-reduced-level (funcall outline-level)))
15391 (when (<= level n)
15392 (looking-at org-complex-heading-regexp)
15393 (setq head (org-link-display-format
15394 (org-match-string-no-properties 4))
15395 m (org-imenu-new-marker))
15396 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15397 (if (>= level last-level)
15398 (push (cons head m) (aref subs level))
15399 (push (cons head (aref subs (1+ level))) (aref subs level))
15400 (loop for i from (1+ level) to n do (aset subs i nil)))
15401 (setq last-level level)))))
15402 (aref subs 1)))
15404 (eval-after-load "imenu"
15405 '(progn
15406 (add-hook 'imenu-after-jump-hook
15407 (lambda ()
15408 (if (eq major-mode 'org-mode)
15409 (org-show-context 'org-goto))))))
15411 (defun org-link-display-format (link)
15412 "Replace a link with either the description, or the link target
15413 if no description is present"
15414 (save-match-data
15415 (if (string-match org-bracket-link-analytic-regexp link)
15416 (replace-match (or (match-string 5 link)
15417 (concat (match-string 1 link)
15418 (match-string 3 link)))
15419 nil nil link)
15420 link)))
15422 ;; Speedbar support
15424 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15425 "Overlay marking the agenda restriction line in speedbar.")
15426 (org-overlay-put org-speedbar-restriction-lock-overlay
15427 'face 'org-agenda-restriction-lock)
15428 (org-overlay-put org-speedbar-restriction-lock-overlay
15429 'help-echo "Agendas are currently limited to this item.")
15430 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15432 (defun org-speedbar-set-agenda-restriction ()
15433 "Restrict future agenda commands to the location at point in speedbar.
15434 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15435 (interactive)
15436 (require 'org-agenda)
15437 (let (p m tp np dir txt)
15438 (cond
15439 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15440 'org-imenu t))
15441 (setq m (get-text-property p 'org-imenu-marker))
15442 (save-excursion
15443 (save-restriction
15444 (set-buffer (marker-buffer m))
15445 (goto-char m)
15446 (org-agenda-set-restriction-lock 'subtree))))
15447 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15448 'speedbar-function 'speedbar-find-file))
15449 (setq tp (previous-single-property-change
15450 (1+ p) 'speedbar-function)
15451 np (next-single-property-change
15452 tp 'speedbar-function)
15453 dir (speedbar-line-directory)
15454 txt (buffer-substring-no-properties (or tp (point-min))
15455 (or np (point-max))))
15456 (save-excursion
15457 (save-restriction
15458 (set-buffer (find-file-noselect
15459 (let ((default-directory dir))
15460 (expand-file-name txt))))
15461 (unless (org-mode-p)
15462 (error "Cannot restrict to non-Org-mode file"))
15463 (org-agenda-set-restriction-lock 'file))))
15464 (t (error "Don't know how to restrict Org-mode's agenda")))
15465 (org-move-overlay org-speedbar-restriction-lock-overlay
15466 (point-at-bol) (point-at-eol))
15467 (setq current-prefix-arg nil)
15468 (org-agenda-maybe-redo)))
15470 (eval-after-load "speedbar"
15471 '(progn
15472 (speedbar-add-supported-extension ".org")
15473 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15474 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15475 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15476 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15477 (add-hook 'speedbar-visiting-tag-hook
15478 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15481 ;;; Fixes and Hacks for problems with other packages
15483 ;; Make flyspell not check words in links, to not mess up our keymap
15484 (defun org-mode-flyspell-verify ()
15485 "Don't let flyspell put overlays at active buttons."
15486 (not (get-text-property (point) 'keymap)))
15488 ;; Make `bookmark-jump' show the jump location if it was hidden.
15489 (eval-after-load "bookmark"
15490 '(if (boundp 'bookmark-after-jump-hook)
15491 ;; We can use the hook
15492 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15493 ;; Hook not available, use advice
15494 (defadvice bookmark-jump (after org-make-visible activate)
15495 "Make the position visible."
15496 (org-bookmark-jump-unhide))))
15498 ;; Make sure saveplace show the location if it was hidden
15499 (eval-after-load "saveplace"
15500 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15501 "Make the position visible."
15502 (org-bookmark-jump-unhide)))
15504 (defun org-bookmark-jump-unhide ()
15505 "Unhide the current position, to show the bookmark location."
15506 (and (org-mode-p)
15507 (or (org-invisible-p)
15508 (save-excursion (goto-char (max (point-min) (1- (point))))
15509 (org-invisible-p)))
15510 (org-show-context 'bookmark-jump)))
15512 ;; Make session.el ignore our circular variable
15513 (eval-after-load "session"
15514 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15516 ;;;; Experimental code
15518 (defun org-closed-in-range ()
15519 "Sparse tree of items closed in a certain time range.
15520 Still experimental, may disappear in the future."
15521 (interactive)
15522 ;; Get the time interval from the user.
15523 (let* ((time1 (time-to-seconds
15524 (org-read-date nil 'to-time nil "Starting date: ")))
15525 (time2 (time-to-seconds
15526 (org-read-date nil 'to-time nil "End date:")))
15527 ;; callback function
15528 (callback (lambda ()
15529 (let ((time
15530 (time-to-seconds
15531 (apply 'encode-time
15532 (org-parse-time-string
15533 (match-string 1))))))
15534 ;; check if time in interval
15535 (and (>= time time1) (<= time time2))))))
15536 ;; make tree, check each match with the callback
15537 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15540 ;;;; Finish up
15542 (provide 'org)
15544 (run-hooks 'org-load-hook)
15546 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15548 ;;; org.el ends here