Improve documentation of `org-directory'.
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blob4a9371099e9b85a1b99faff2ec2168db988a8bab
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.21trans
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.21trans"
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 depend: TODO dependencies for Org-mode" org-depend)
185 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
186 (const :tag "C eval: Include command output as text" org-eval)
187 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
188 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
189 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
190 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
191 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
192 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
193 (const :tag "C mtags: Support for muse-like tags" org-mtags)
194 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
195 (const :tag "C registry: A registry for Org links" org-registry)
196 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
197 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
198 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
199 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
200 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
202 (defcustom org-support-shift-select nil
203 "Non-nil means, make shift-cursor commands select text when possible.
205 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
206 selecting a region, or enlarge thusly regions started in this way.
207 In Org-mode, in special contexts, these same keys are used for other
208 purposes, important enough to compete with shift selection. Org tries
209 to balance these needs by supporting `shift-select-mode' outside these
210 special contexts, under control of this variable.
212 The default of this variable is nil, to avoid confusing behavior. Shifted
213 cursor keys will then execute Org commands in the following contexts:
214 - on a headline, changing TODO state (left/right) and priority (up/down)
215 - on a time stamp, changing the time
216 - in a plain list item, changing the bullet type
217 - in a property definition line, switching between allowed values
218 - in the BEGIN line of a clock table (changing the time block).
219 Outside these contexts, the commands will throw an error.
221 When this variable is t and the cursor is not in a special context,
222 Org-mode will support shift-selection for making and enlarging regions.
223 To make this more effective, the bullet cycling will no longer happen
224 anywhere in an item line, but only if the cursor is exactly on the bullet.
226 If you set this variable to the symbol `always', then the keys
227 will not be special in headlines, property lines, and item lines, to make
228 shift selection work there as well. If this is what you want, you can
229 use the following alternative commands: `C-c C-t' and `C-c ,' to
230 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
231 TODO sets, `C-c -' to cycle item bullet types, and properties can be
232 edited by hand or in column view.
234 However, when the cursor is on a timestamp, shift-cursor commands
235 will still edit the time stamp - this is just too good to give up.
237 XEmacs user should have this variable set to nil, because shift-select-mode
238 is Emacs 23 only."
239 :group 'org
240 :type '(choice
241 (const :tag "Never" nil)
242 (const :tag "When outside special context" t)
243 (const :tag "Everywhere except timestamps" always)))
245 (defgroup org-startup nil
246 "Options concerning startup of Org-mode."
247 :tag "Org Startup"
248 :group 'org)
250 (defcustom org-startup-folded t
251 "Non-nil means, entering Org-mode will switch to OVERVIEW.
252 This can also be configured on a per-file basis by adding one of
253 the following lines anywhere in the buffer:
255 #+STARTUP: fold
256 #+STARTUP: nofold
257 #+STARTUP: content"
258 :group 'org-startup
259 :type '(choice
260 (const :tag "nofold: show all" nil)
261 (const :tag "fold: overview" t)
262 (const :tag "content: all headlines" content)))
264 (defcustom org-startup-truncated t
265 "Non-nil means, entering Org-mode will set `truncate-lines'.
266 This is useful since some lines containing links can be very long and
267 uninteresting. Also tables look terrible when wrapped."
268 :group 'org-startup
269 :type 'boolean)
271 (defcustom org-startup-align-all-tables nil
272 "Non-nil means, align all tables when visiting a file.
273 This is useful when the column width in tables is forced with <N> cookies
274 in table fields. Such tables will look correct only after the first re-align.
275 This can also be configured on a per-file basis by adding one of
276 the following lines anywhere in the buffer:
277 #+STARTUP: align
278 #+STARTUP: noalign"
279 :group 'org-startup
280 :type 'boolean)
282 (defcustom org-insert-mode-line-in-empty-file nil
283 "Non-nil means insert the first line setting Org-mode in empty files.
284 When the function `org-mode' is called interactively in an empty file, this
285 normally means that the file name does not automatically trigger Org-mode.
286 To ensure that the file will always be in Org-mode in the future, a
287 line enforcing Org-mode will be inserted into the buffer, if this option
288 has been set."
289 :group 'org-startup
290 :type 'boolean)
292 (defcustom org-replace-disputed-keys nil
293 "Non-nil means use alternative key bindings for some keys.
294 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
295 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
296 If you want to use Org-mode together with one of these other modes,
297 or more generally if you would like to move some Org-mode commands to
298 other keys, set this variable and configure the keys with the variable
299 `org-disputed-keys'.
301 This option is only relevant at load-time of Org-mode, and must be set
302 *before* org.el is loaded. Changing it requires a restart of Emacs to
303 become effective."
304 :group 'org-startup
305 :type 'boolean)
307 (defcustom org-use-extra-keys nil
308 "Non-nil means use extra key sequence definitions for certain
309 commands. This happens automatically if you run XEmacs or if
310 window-system is nil. This variable lets you do the same
311 manually. You must set it before loading org.
313 Example: on Carbon Emacs 22 running graphically, with an external
314 keyboard on a Powerbook, the default way of setting M-left might
315 not work for either Alt or ESC. Setting this variable will make
316 it work for ESC."
317 :group 'org-startup
318 :type 'boolean)
320 (if (fboundp 'defvaralias)
321 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
323 (defcustom org-disputed-keys
324 '(([(shift up)] . [(meta p)])
325 ([(shift down)] . [(meta n)])
326 ([(shift left)] . [(meta -)])
327 ([(shift right)] . [(meta +)])
328 ([(control shift right)] . [(meta shift +)])
329 ([(control shift left)] . [(meta shift -)]))
330 "Keys for which Org-mode and other modes compete.
331 This is an alist, cars are the default keys, second element specifies
332 the alternative to use when `org-replace-disputed-keys' is t.
334 Keys can be specified in any syntax supported by `define-key'.
335 The value of this option takes effect only at Org-mode's startup,
336 therefore you'll have to restart Emacs to apply it after changing."
337 :group 'org-startup
338 :type 'alist)
340 (defun org-key (key)
341 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
342 Or return the original if not disputed."
343 (if org-replace-disputed-keys
344 (let* ((nkey (key-description key))
345 (x (org-find-if (lambda (x)
346 (equal (key-description (car x)) nkey))
347 org-disputed-keys)))
348 (if x (cdr x) key))
349 key))
351 (defun org-find-if (predicate seq)
352 (catch 'exit
353 (while seq
354 (if (funcall predicate (car seq))
355 (throw 'exit (car seq))
356 (pop seq)))))
358 (defun org-defkey (keymap key def)
359 "Define a key, possibly translated, as returned by `org-key'."
360 (define-key keymap (org-key key) def))
362 (defcustom org-ellipsis nil
363 "The ellipsis to use in the Org-mode outline.
364 When nil, just use the standard three dots. When a string, use that instead,
365 When a face, use the standard 3 dots, but with the specified face.
366 The change affects only Org-mode (which will then use its own display table).
367 Changing this requires executing `M-x org-mode' in a buffer to become
368 effective."
369 :group 'org-startup
370 :type '(choice (const :tag "Default" nil)
371 (face :tag "Face" :value org-warning)
372 (string :tag "String" :value "...#")))
374 (defvar org-display-table nil
375 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
377 (defgroup org-keywords nil
378 "Keywords in Org-mode."
379 :tag "Org Keywords"
380 :group 'org)
382 (defcustom org-deadline-string "DEADLINE:"
383 "String to mark deadline entries.
384 A deadline is this string, followed by a time stamp. Should be a word,
385 terminated by a colon. You can insert a schedule keyword and
386 a timestamp with \\[org-deadline].
387 Changes become only effective after restarting Emacs."
388 :group 'org-keywords
389 :type 'string)
391 (defcustom org-scheduled-string "SCHEDULED:"
392 "String to mark scheduled TODO entries.
393 A schedule is this string, followed by a time stamp. Should be a word,
394 terminated by a colon. You can insert a schedule keyword and
395 a timestamp with \\[org-schedule].
396 Changes become only effective after restarting Emacs."
397 :group 'org-keywords
398 :type 'string)
400 (defcustom org-closed-string "CLOSED:"
401 "String used as the prefix for timestamps logging closing a TODO entry."
402 :group 'org-keywords
403 :type 'string)
405 (defcustom org-clock-string "CLOCK:"
406 "String used as prefix for timestamps clocking work hours on an item."
407 :group 'org-keywords
408 :type 'string)
410 (defcustom org-comment-string "COMMENT"
411 "Entries starting with this keyword will never be exported.
412 An entry can be toggled between COMMENT and normal with
413 \\[org-toggle-comment].
414 Changes become only effective after restarting Emacs."
415 :group 'org-keywords
416 :type 'string)
418 (defcustom org-quote-string "QUOTE"
419 "Entries starting with this keyword will be exported in fixed-width font.
420 Quoting applies only to the text in the entry following the headline, and does
421 not extend beyond the next headline, even if that is lower level.
422 An entry can be toggled between QUOTE and normal with
423 \\[org-toggle-fixed-width-section]."
424 :group 'org-keywords
425 :type 'string)
427 (defconst org-repeat-re
428 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
429 "Regular expression for specifying repeated events.
430 After a match, group 1 contains the repeat expression.")
432 (defgroup org-structure nil
433 "Options concerning the general structure of Org-mode files."
434 :tag "Org Structure"
435 :group 'org)
437 (defgroup org-reveal-location nil
438 "Options about how to make context of a location visible."
439 :tag "Org Reveal Location"
440 :group 'org-structure)
442 (defconst org-context-choice
443 '(choice
444 (const :tag "Always" t)
445 (const :tag "Never" nil)
446 (repeat :greedy t :tag "Individual contexts"
447 (cons
448 (choice :tag "Context"
449 (const agenda)
450 (const org-goto)
451 (const occur-tree)
452 (const tags-tree)
453 (const link-search)
454 (const mark-goto)
455 (const bookmark-jump)
456 (const isearch)
457 (const default))
458 (boolean))))
459 "Contexts for the reveal options.")
461 (defcustom org-show-hierarchy-above '((default . t))
462 "Non-nil means, show full hierarchy when revealing a location.
463 Org-mode often shows locations in an org-mode file which might have
464 been invisible before. When this is set, the hierarchy of headings
465 above the exposed location is shown.
466 Turning this off for example for sparse trees makes them very compact.
467 Instead of t, this can also be an alist specifying this option for different
468 contexts. Valid contexts are
469 agenda when exposing an entry from the agenda
470 org-goto when using the command `org-goto' on key C-c C-j
471 occur-tree when using the command `org-occur' on key C-c /
472 tags-tree when constructing a sparse tree based on tags matches
473 link-search when exposing search matches associated with a link
474 mark-goto when exposing the jump goal of a mark
475 bookmark-jump when exposing a bookmark location
476 isearch when exiting from an incremental search
477 default default for all contexts not set explicitly"
478 :group 'org-reveal-location
479 :type org-context-choice)
481 (defcustom org-show-following-heading '((default . nil))
482 "Non-nil means, show following heading when revealing a location.
483 Org-mode often shows locations in an org-mode file which might have
484 been invisible before. When this is set, the heading following the
485 match is shown.
486 Turning this off for example for sparse trees makes them very compact,
487 but makes it harder to edit the location of the match. In such a case,
488 use the command \\[org-reveal] to show more context.
489 Instead of t, this can also be an alist specifying this option for different
490 contexts. See `org-show-hierarchy-above' for valid contexts."
491 :group 'org-reveal-location
492 :type org-context-choice)
494 (defcustom org-show-siblings '((default . nil) (isearch t))
495 "Non-nil means, show all sibling heading when revealing a location.
496 Org-mode often shows locations in an org-mode file which might have
497 been invisible before. When this is set, the sibling of the current entry
498 heading are all made visible. If `org-show-hierarchy-above' is t,
499 the same happens on each level of the hierarchy above the current entry.
501 By default this is on for the isearch context, off for all other contexts.
502 Turning this off for example for sparse trees makes them very compact,
503 but makes it harder to edit the location of the match. In such a case,
504 use the command \\[org-reveal] to show more context.
505 Instead of t, this can also be an alist specifying this option for different
506 contexts. See `org-show-hierarchy-above' for valid contexts."
507 :group 'org-reveal-location
508 :type org-context-choice)
510 (defcustom org-show-entry-below '((default . nil))
511 "Non-nil means, show the entry below a headline when revealing a location.
512 Org-mode often shows locations in an org-mode file which might have
513 been invisible before. When this is set, the text below the headline that is
514 exposed is also shown.
516 By default this is off for all contexts.
517 Instead of t, this can also be an alist specifying this option for different
518 contexts. See `org-show-hierarchy-above' for valid contexts."
519 :group 'org-reveal-location
520 :type org-context-choice)
522 (defcustom org-indirect-buffer-display 'other-window
523 "How should indirect tree buffers be displayed?
524 This applies to indirect buffers created with the commands
525 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
526 Valid values are:
527 current-window Display in the current window
528 other-window Just display in another window.
529 dedicated-frame Create one new frame, and re-use it each time.
530 new-frame Make a new frame each time. Note that in this case
531 previously-made indirect buffers are kept, and you need to
532 kill these buffers yourself."
533 :group 'org-structure
534 :group 'org-agenda-windows
535 :type '(choice
536 (const :tag "In current window" current-window)
537 (const :tag "In current frame, other window" other-window)
538 (const :tag "Each time a new frame" new-frame)
539 (const :tag "One dedicated frame" dedicated-frame)))
541 (defgroup org-cycle nil
542 "Options concerning visibility cycling in Org-mode."
543 :tag "Org Cycle"
544 :group 'org-structure)
546 (defcustom org-drawers '("PROPERTIES" "CLOCK")
547 "Names of drawers. Drawers are not opened by cycling on the headline above.
548 Drawers only open with a TAB on the drawer line itself. A drawer looks like
549 this:
550 :DRAWERNAME:
551 .....
552 :END:
553 The drawer \"PROPERTIES\" is special for capturing properties through
554 the property API.
556 Drawers can be defined on the per-file basis with a line like:
558 #+DRAWERS: HIDDEN STATE PROPERTIES"
559 :group 'org-structure
560 :type '(repeat (string :tag "Drawer Name")))
562 (defcustom org-cycle-global-at-bob nil
563 "Cycle globally if cursor is at beginning of buffer and not at a headline.
564 This makes it possible to do global cycling without having to use S-TAB or
565 C-u TAB. For this special case to work, the first line of the buffer
566 must not be a headline - it may be empty or some other text. When used in
567 this way, `org-cycle-hook' is disables temporarily, to make sure the
568 cursor stays at the beginning of the buffer.
569 When this option is nil, don't do anything special at the beginning
570 of the buffer."
571 :group 'org-cycle
572 :type 'boolean)
574 (defcustom org-cycle-emulate-tab t
575 "Where should `org-cycle' emulate TAB.
576 nil Never
577 white Only in completely white lines
578 whitestart Only at the beginning of lines, before the first non-white char
579 t Everywhere except in headlines
580 exc-hl-bol Everywhere except at the start of a headline
581 If TAB is used in a place where it does not emulate TAB, the current subtree
582 visibility is cycled."
583 :group 'org-cycle
584 :type '(choice (const :tag "Never" nil)
585 (const :tag "Only in completely white lines" white)
586 (const :tag "Before first char in a line" whitestart)
587 (const :tag "Everywhere except in headlines" t)
588 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
591 (defcustom org-cycle-separator-lines 2
592 "Number of empty lines needed to keep an empty line between collapsed trees.
593 If you leave an empty line between the end of a subtree and the following
594 headline, this empty line is hidden when the subtree is folded.
595 Org-mode will leave (exactly) one empty line visible if the number of
596 empty lines is equal or larger to the number given in this variable.
597 So the default 2 means, at least 2 empty lines after the end of a subtree
598 are needed to produce free space between a collapsed subtree and the
599 following headline.
601 Special case: when 0, never leave empty lines in collapsed view."
602 :group 'org-cycle
603 :type 'integer)
604 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
606 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
607 org-cycle-hide-drawers
608 org-cycle-show-empty-lines
609 org-optimize-window-after-visibility-change)
610 "Hook that is run after `org-cycle' has changed the buffer visibility.
611 The function(s) in this hook must accept a single argument which indicates
612 the new state that was set by the most recent `org-cycle' command. The
613 argument is a symbol. After a global state change, it can have the values
614 `overview', `content', or `all'. After a local state change, it can have
615 the values `folded', `children', or `subtree'."
616 :group 'org-cycle
617 :type 'hook)
619 (defgroup org-edit-structure nil
620 "Options concerning structure editing in Org-mode."
621 :tag "Org Edit Structure"
622 :group 'org-structure)
624 (defcustom org-odd-levels-only nil
625 "Non-nil means, skip even levels and only use odd levels for the outline.
626 This has the effect that two stars are being added/taken away in
627 promotion/demotion commands. It also influences how levels are
628 handled by the exporters.
629 Changing it requires restart of `font-lock-mode' to become effective
630 for fontification also in regions already fontified.
631 You may also set this on a per-file basis by adding one of the following
632 lines to the buffer:
634 #+STARTUP: odd
635 #+STARTUP: oddeven"
636 :group 'org-edit-structure
637 :group 'org-font-lock
638 :type 'boolean)
640 (defcustom org-adapt-indentation t
641 "Non-nil means, adapt indentation when promoting and demoting.
642 When this is set and the *entire* text in an entry is indented, the
643 indentation is increased by one space in a demotion command, and
644 decreased by one in a promotion command. If any line in the entry
645 body starts at column 0, indentation is not changed at all."
646 :group 'org-edit-structure
647 :type 'boolean)
649 (defcustom org-special-ctrl-a/e nil
650 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
651 When t, `C-a' will bring back the cursor to the beginning of the
652 headline text, i.e. after the stars and after a possible TODO keyword.
653 In an item, this will be the position after the bullet.
654 When the cursor is already at that position, another `C-a' will bring
655 it to the beginning of the line.
656 `C-e' will jump to the end of the headline, ignoring the presence of tags
657 in the headline. A second `C-e' will then jump to the true end of the
658 line, after any tags.
659 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
660 and only a directly following, identical keypress will bring the cursor
661 to the special positions."
662 :group 'org-edit-structure
663 :type '(choice
664 (const :tag "off" nil)
665 (const :tag "after bullet first" t)
666 (const :tag "border first" reversed)))
668 (if (fboundp 'defvaralias)
669 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
671 (defcustom org-special-ctrl-k nil
672 "Non-nil means `C-k' will behave specially in headlines.
673 When nil, `C-k' will call the default `kill-line' command.
674 When t, the following will happen while the cursor is in the headline:
676 - When the cursor is at the beginning of a headline, kill the entire
677 line and possible the folded subtree below the line.
678 - When in the middle of the headline text, kill the headline up to the tags.
679 - When after the headline text, kill the tags."
680 :group 'org-edit-structure
681 :type 'boolean)
683 (defcustom org-yank-folded-subtrees t
684 "Non-nil means, when yanking subtrees, fold them.
685 If the kill is a single subtree, or a sequence of subtrees, i.e. if
686 it starts with a heading and all other headings in it are either children
687 or siblings, then fold all the subtrees. However, do this only if no
688 text after the yank would be swallowed into a folded tree by this action."
689 :group 'org-edit-structure
690 :type 'boolean)
692 (defcustom org-yank-adjusted-subtrees nil
693 "Non-nil means, when yanking subtrees, adjust the level.
694 With this setting, `org-paste-subtree' is used to insert the subtree, see
695 this function for details."
696 :group 'org-edit-structure
697 :type 'boolean)
699 (defcustom org-M-RET-may-split-line '((default . t))
700 "Non-nil means, M-RET will split the line at the cursor position.
701 When nil, it will go to the end of the line before making a
702 new line.
703 You may also set this option in a different way for different
704 contexts. Valid contexts are:
706 headline when creating a new headline
707 item when creating a new item
708 table in a table field
709 default the value to be used for all contexts not explicitly
710 customized"
711 :group 'org-structure
712 :group 'org-table
713 :type '(choice
714 (const :tag "Always" t)
715 (const :tag "Never" nil)
716 (repeat :greedy t :tag "Individual contexts"
717 (cons
718 (choice :tag "Context"
719 (const headline)
720 (const item)
721 (const table)
722 (const default))
723 (boolean)))))
726 (defcustom org-insert-heading-respect-content nil
727 "Non-nil means, insert new headings after the current subtree.
728 When nil, the new heading is created directly after the current line.
729 The commands \\[org-insert-heading-respect-content] and
730 \\[org-insert-todo-heading-respect-content] turn this variable on
731 for the duration of the command."
732 :group 'org-structure
733 :type 'boolean)
735 (defcustom org-blank-before-new-entry '((heading . auto)
736 (plain-list-item . auto))
737 "Should `org-insert-heading' leave a blank line before new heading/item?
738 The value is an alist, with `heading' and `plain-list-item' as car,
739 and a boolean flag as cdr."
740 :group 'org-edit-structure
741 :type '(list
742 (cons (const heading)
743 (choice (const :tag "Never" nil)
744 (const :tag "Always" t)
745 (const :tag "Auto" auto)))
746 (cons (const plain-list-item)
747 (choice (const :tag "Never" nil)
748 (const :tag "Always" t)
749 (const :tag "Auto" auto)))))
751 (defcustom org-insert-heading-hook nil
752 "Hook being run after inserting a new heading."
753 :group 'org-edit-structure
754 :type 'hook)
756 (defcustom org-enable-fixed-width-editor t
757 "Non-nil means, lines starting with \":\" are treated as fixed-width.
758 This currently only means, they are never auto-wrapped.
759 When nil, such lines will be treated like ordinary lines.
760 See also the QUOTE keyword."
761 :group 'org-edit-structure
762 :type 'boolean)
764 (defcustom org-edit-src-region-extra nil
765 "Additional regexps to identify regions for editing with `org-edit-src-code'.
766 For examples see the function `org-edit-src-find-region-and-lang'.
767 The regular expression identifying the begin marker should end with a newline,
768 and the regexp marking the end line should start with a newline, to make sure
769 there are kept outside the narrowed region."
770 :group 'org-edit-structure
771 :type '(repeat
772 (list
773 (regexp :tag "begin regexp")
774 (regexp :tag "end regexp")
775 (choice :tag "language"
776 (string :tag "specify")
777 (integer :tag "from match group")
778 (const :tag "from `lang' element")
779 (const :tag "from `style' element")))))
781 (defcustom org-coderef-label-format "(ref:%s)"
782 "The default coderef format.
783 This format string will be used to search for coderef labels in literal
784 examples (EXAMPLE and SRC blocks). The format can be overwritten
785 an individual literal example with the -f option, like
787 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
789 #+END_SRC
791 If you want to use this for HTML export, make sure that the format does
792 not introduce special font-locking, and avoid the HTML special
793 characters `<', `>', and `&'. The reason for this restriction is that
794 the labels are searched for only after htmlize has done its job."
795 :group 'org-edit-structure ; FIXME this is not in the right group
796 :type 'string)
798 (defcustom org-edit-fixed-width-region-mode 'artist-mode
799 "The mode that should be used to edit fixed-width regions.
800 These are the regions where each line starts with a colon."
801 :group 'org-edit-structure
802 :type '(choice
803 (const artist-mode)
804 (const picture-mode)
805 (const fundamental-mode)
806 (function :tag "Other (specify)")))
808 (defcustom org-goto-auto-isearch t
809 "Non-nil means, typing characters in org-goto starts incremental search."
810 :group 'org-edit-structure
811 :type 'boolean)
813 (defgroup org-sparse-trees nil
814 "Options concerning sparse trees in Org-mode."
815 :tag "Org Sparse Trees"
816 :group 'org-structure)
818 (defcustom org-highlight-sparse-tree-matches t
819 "Non-nil means, highlight all matches that define a sparse tree.
820 The highlights will automatically disappear the next time the buffer is
821 changed by an edit command."
822 :group 'org-sparse-trees
823 :type 'boolean)
825 (defcustom org-remove-highlights-with-change t
826 "Non-nil means, any change to the buffer will remove temporary highlights.
827 Such highlights are created by `org-occur' and `org-clock-display'.
828 When nil, `C-c C-c needs to be used to get rid of the highlights.
829 The highlights created by `org-preview-latex-fragment' always need
830 `C-c C-c' to be removed."
831 :group 'org-sparse-trees
832 :group 'org-time
833 :type 'boolean)
836 (defcustom org-occur-hook '(org-first-headline-recenter)
837 "Hook that is run after `org-occur' has constructed a sparse tree.
838 This can be used to recenter the window to show as much of the structure
839 as possible."
840 :group 'org-sparse-trees
841 :type 'hook)
843 (defgroup org-imenu-and-speedbar nil
844 "Options concerning imenu and speedbar in Org-mode."
845 :tag "Org Imenu and Speedbar"
846 :group 'org-structure)
848 (defcustom org-imenu-depth 2
849 "The maximum level for Imenu access to Org-mode headlines.
850 This also applied for speedbar access."
851 :group 'org-imenu-and-speedbar
852 :type 'number)
854 (defgroup org-table nil
855 "Options concerning tables in Org-mode."
856 :tag "Org Table"
857 :group 'org)
859 (defcustom org-enable-table-editor 'optimized
860 "Non-nil means, lines starting with \"|\" are handled by the table editor.
861 When nil, such lines will be treated like ordinary lines.
863 When equal to the symbol `optimized', the table editor will be optimized to
864 do the following:
865 - Automatic overwrite mode in front of whitespace in table fields.
866 This makes the structure of the table stay in tact as long as the edited
867 field does not exceed the column width.
868 - Minimize the number of realigns. Normally, the table is aligned each time
869 TAB or RET are pressed to move to another field. With optimization this
870 happens only if changes to a field might have changed the column width.
871 Optimization requires replacing the functions `self-insert-command',
872 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
873 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
874 very good at guessing when a re-align will be necessary, but you can always
875 force one with \\[org-ctrl-c-ctrl-c].
877 If you would like to use the optimized version in Org-mode, but the
878 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
880 This variable can be used to turn on and off the table editor during a session,
881 but in order to toggle optimization, a restart is required.
883 See also the variable `org-table-auto-blank-field'."
884 :group 'org-table
885 :type '(choice
886 (const :tag "off" nil)
887 (const :tag "on" t)
888 (const :tag "on, optimized" optimized)))
890 (defcustom org-table-tab-recognizes-table.el t
891 "Non-nil means, TAB will automatically notice a table.el table.
892 When it sees such a table, it moves point into it and - if necessary -
893 calls `table-recognize-table'."
894 :group 'org-table-editing
895 :type 'boolean)
897 (defgroup org-link nil
898 "Options concerning links in Org-mode."
899 :tag "Org Link"
900 :group 'org)
902 (defvar org-link-abbrev-alist-local nil
903 "Buffer-local version of `org-link-abbrev-alist', which see.
904 The value of this is taken from the #+LINK lines.")
905 (make-variable-buffer-local 'org-link-abbrev-alist-local)
907 (defcustom org-link-abbrev-alist nil
908 "Alist of link abbreviations.
909 The car of each element is a string, to be replaced at the start of a link.
910 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
911 links in Org-mode buffers can have an optional tag after a double colon, e.g.
913 [[linkkey:tag][description]]
915 If REPLACE is a string, the tag will simply be appended to create the link.
916 If the string contains \"%s\", the tag will be inserted there. Alternatively,
917 the placeholder \"%h\" will cause a url-encoded version of the tag to
918 be inserted at that point (see the function `url-hexify-string').
920 REPLACE may also be a function that will be called with the tag as the
921 only argument to create the link, which should be returned as a string.
923 See the manual for examples."
924 :group 'org-link
925 :type '(repeat
926 (cons
927 (string :tag "Protocol")
928 (choice
929 (string :tag "Format")
930 (function)))))
932 (defcustom org-descriptive-links t
933 "Non-nil means, hide link part and only show description of bracket links.
934 Bracket links are like [[link][description]]. This variable sets the initial
935 state in new org-mode buffers. The setting can then be toggled on a
936 per-buffer basis from the Org->Hyperlinks menu."
937 :group 'org-link
938 :type 'boolean)
940 (defcustom org-link-file-path-type 'adaptive
941 "How the path name in file links should be stored.
942 Valid values are:
944 relative Relative to the current directory, i.e. the directory of the file
945 into which the link is being inserted.
946 absolute Absolute path, if possible with ~ for home directory.
947 noabbrev Absolute path, no abbreviation of home directory.
948 adaptive Use relative path for files in the current directory and sub-
949 directories of it. For other files, use an absolute path."
950 :group 'org-link
951 :type '(choice
952 (const relative)
953 (const absolute)
954 (const noabbrev)
955 (const adaptive)))
957 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
958 "Types of links that should be activated in Org-mode files.
959 This is a list of symbols, each leading to the activation of a certain link
960 type. In principle, it does not hurt to turn on most link types - there may
961 be a small gain when turning off unused link types. The types are:
963 bracket The recommended [[link][description]] or [[link]] links with hiding.
964 angular Links in angular brackets that may contain whitespace like
965 <bbdb:Carsten Dominik>.
966 plain Plain links in normal text, no whitespace, like http://google.com.
967 radio Text that is matched by a radio target, see manual for details.
968 tag Tag settings in a headline (link to tag search).
969 date Time stamps (link to calendar).
970 footnote Footnote labels.
972 Changing this variable requires a restart of Emacs to become effective."
973 :group 'org-link
974 :type '(set :greedy t
975 (const :tag "Double bracket links (new style)" bracket)
976 (const :tag "Angular bracket links (old style)" angular)
977 (const :tag "Plain text links" plain)
978 (const :tag "Radio target matches" radio)
979 (const :tag "Tags" tag)
980 (const :tag "Timestamps" date)
981 (const :tag "Footnotes" footnote)))
983 (defcustom org-make-link-description-function nil
984 "Function to use to generate link descriptions from links. If
985 nil the link location will be used. This function must take two
986 parameters; the first is the link and the second the description
987 org-insert-link has generated, and should return the description
988 to use."
989 :group 'org-link
990 :type 'function)
992 (defgroup org-link-store nil
993 "Options concerning storing links in Org-mode."
994 :tag "Org Store Link"
995 :group 'org-link)
997 (defcustom org-email-link-description-format "Email %c: %.30s"
998 "Format of the description part of a link to an email or usenet message.
999 The following %-escapes will be replaced by corresponding information:
1001 %F full \"From\" field
1002 %f name, taken from \"From\" field, address if no name
1003 %T full \"To\" field
1004 %t first name in \"To\" field, address if no name
1005 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1006 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1007 %s subject
1008 %m message-id.
1010 You may use normal field width specification between the % and the letter.
1011 This is for example useful to limit the length of the subject.
1013 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1014 :group 'org-link-store
1015 :type 'string)
1017 (defcustom org-from-is-user-regexp
1018 (let (r1 r2)
1019 (when (and user-mail-address (not (string= user-mail-address "")))
1020 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1021 (when (and user-full-name (not (string= user-full-name "")))
1022 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1023 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1024 "Regexp matched against the \"From:\" header of an email or usenet message.
1025 It should match if the message is from the user him/herself."
1026 :group 'org-link-store
1027 :type 'regexp)
1029 (defcustom org-link-to-org-use-id 'create-if-interactive
1030 "Non-nil means, storing a link to an Org file will use entry IDs.
1032 Note that before this variable is even considered, org-id must be loaded,
1033 to please customize `org-modules' and turn it on.
1035 The variable can have the following values:
1037 t Create an ID if needed to make a link to the current entry.
1039 create-if-interactive
1040 If `org-store-link' is called directly (interactively, as a user
1041 command), do create an ID to support the link. But when doing the
1042 job for remember, only use the ID if it already exists. The
1043 purpose of this setting is to avoid proliferation of unwanted
1044 IDs, just because you happen to be in an Org file when you
1045 call `org-remember' that automatically and preemptively
1046 creates a link. If you do want to get an ID link in a remember
1047 template to an entry not having an ID, create it first by
1048 explicitly creating a link to it, using `C-c C-l' first.
1050 use-existing
1051 Use existing ID, do not create one.
1053 nil Never use an ID to make a link, instead link using a text search for
1054 the headline text."
1055 :group 'org-link-store
1056 :type '(choice
1057 (const :tag "Create ID to make link" t)
1058 (const :tag "Create if string link interactively"
1059 'create-if-interactive)
1060 (const :tag "Only use existing" 'use-existing)
1061 (const :tag "Do not use ID to create link" nil)))
1063 (defcustom org-context-in-file-links t
1064 "Non-nil means, file links from `org-store-link' contain context.
1065 A search string will be added to the file name with :: as separator and
1066 used to find the context when the link is activated by the command
1067 `org-open-at-point'.
1068 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1069 negates this setting for the duration of the command."
1070 :group 'org-link-store
1071 :type 'boolean)
1073 (defcustom org-keep-stored-link-after-insertion nil
1074 "Non-nil means, keep link in list for entire session.
1076 The command `org-store-link' adds a link pointing to the current
1077 location to an internal list. These links accumulate during a session.
1078 The command `org-insert-link' can be used to insert links into any
1079 Org-mode file (offering completion for all stored links). When this
1080 option is nil, every link which has been inserted once using \\[org-insert-link]
1081 will be removed from the list, to make completing the unused links
1082 more efficient."
1083 :group 'org-link-store
1084 :type 'boolean)
1086 (defgroup org-link-follow nil
1087 "Options concerning following links in Org-mode."
1088 :tag "Org Follow Link"
1089 :group 'org-link)
1091 (defcustom org-link-translation-function nil
1092 "Function to translate links with different syntax to Org syntax.
1093 This can be used to translate links created for example by the Planner
1094 or emacs-wiki packages to Org syntax.
1095 The function must accept two parameters, a TYPE containing the link
1096 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1097 which is everything after the link protocol. It should return a cons
1098 with possibly modified values of type and path.
1099 Org contains a function for this, so if you set this variable to
1100 `org-translate-link-from-planner', you should be able follow many
1101 links created by planner."
1102 :group 'org-link-follow
1103 :type 'function)
1105 (defcustom org-follow-link-hook nil
1106 "Hook that is run after a link has been followed."
1107 :group 'org-link-follow
1108 :type 'hook)
1110 (defcustom org-tab-follows-link nil
1111 "Non-nil means, on links TAB will follow the link.
1112 Needs to be set before org.el is loaded."
1113 :group 'org-link-follow
1114 :type 'boolean)
1116 (defcustom org-return-follows-link nil
1117 "Non-nil means, on links RET will follow the link.
1118 Needs to be set before org.el is loaded."
1119 :group 'org-link-follow
1120 :type 'boolean)
1122 (defcustom org-mouse-1-follows-link
1123 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1124 "Non-nil means, mouse-1 on a link will follow the link.
1125 A longer mouse click will still set point. Does not work on XEmacs.
1126 Needs to be set before org.el is loaded."
1127 :group 'org-link-follow
1128 :type 'boolean)
1130 (defcustom org-mark-ring-length 4
1131 "Number of different positions to be recorded in the ring
1132 Changing this requires a restart of Emacs to work correctly."
1133 :group 'org-link-follow
1134 :type 'integer)
1136 (defcustom org-link-frame-setup
1137 '((vm . vm-visit-folder-other-frame)
1138 (gnus . gnus-other-frame)
1139 (file . find-file-other-window))
1140 "Setup the frame configuration for following links.
1141 When following a link with Emacs, it may often be useful to display
1142 this link in another window or frame. This variable can be used to
1143 set this up for the different types of links.
1144 For VM, use any of
1145 `vm-visit-folder'
1146 `vm-visit-folder-other-frame'
1147 For Gnus, use any of
1148 `gnus'
1149 `gnus-other-frame'
1150 `org-gnus-no-new-news'
1151 For FILE, use any of
1152 `find-file'
1153 `find-file-other-window'
1154 `find-file-other-frame'
1155 For the calendar, use the variable `calendar-setup'.
1156 For BBDB, it is currently only possible to display the matches in
1157 another window."
1158 :group 'org-link-follow
1159 :type '(list
1160 (cons (const vm)
1161 (choice
1162 (const vm-visit-folder)
1163 (const vm-visit-folder-other-window)
1164 (const vm-visit-folder-other-frame)))
1165 (cons (const gnus)
1166 (choice
1167 (const gnus)
1168 (const gnus-other-frame)
1169 (const org-gnus-no-new-news)))
1170 (cons (const file)
1171 (choice
1172 (const find-file)
1173 (const find-file-other-window)
1174 (const find-file-other-frame)))))
1176 (defcustom org-display-internal-link-with-indirect-buffer nil
1177 "Non-nil means, use indirect buffer to display infile links.
1178 Activating internal links (from one location in a file to another location
1179 in the same file) normally just jumps to the location. When the link is
1180 activated with a C-u prefix (or with mouse-3), the link is displayed in
1181 another window. When this option is set, the other window actually displays
1182 an indirect buffer clone of the current buffer, to avoid any visibility
1183 changes to the current buffer."
1184 :group 'org-link-follow
1185 :type 'boolean)
1187 (defcustom org-open-non-existing-files nil
1188 "Non-nil means, `org-open-file' will open non-existing files.
1189 When nil, an error will be generated."
1190 :group 'org-link-follow
1191 :type 'boolean)
1193 (defcustom org-open-directory-means-index-dot-org nil
1194 "Non-nil means, a link to a directory really means to index.org.
1195 When nil, following a directory link will run dired or open a finder/explorer
1196 window on that directory."
1197 :group 'org-link-follow
1198 :type 'boolean)
1200 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1201 "Function and arguments to call for following mailto links.
1202 This is a list with the first element being a lisp function, and the
1203 remaining elements being arguments to the function. In string arguments,
1204 %a will be replaced by the address, and %s will be replaced by the subject
1205 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1206 :group 'org-link-follow
1207 :type '(choice
1208 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1209 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1210 (const :tag "message-mail" (message-mail "%a" "%s"))
1211 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1213 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1214 "Non-nil means, ask for confirmation before executing shell links.
1215 Shell links can be dangerous: just think about a link
1217 [[shell:rm -rf ~/*][Google Search]]
1219 This link would show up in your Org-mode document as \"Google Search\",
1220 but really it would remove your entire home directory.
1221 Therefore we advise against setting this variable to nil.
1222 Just change it to `y-or-n-p' of you want to confirm with a
1223 single keystroke rather than having to type \"yes\"."
1224 :group 'org-link-follow
1225 :type '(choice
1226 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1227 (const :tag "with y-or-n (faster)" y-or-n-p)
1228 (const :tag "no confirmation (dangerous)" nil)))
1230 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1231 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1232 Elisp links can be dangerous: just think about a link
1234 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1236 This link would show up in your Org-mode document as \"Google Search\",
1237 but really it would remove your entire home directory.
1238 Therefore we advise against setting this variable to nil.
1239 Just change it to `y-or-n-p' of you want to confirm with a
1240 single keystroke rather than having to type \"yes\"."
1241 :group 'org-link-follow
1242 :type '(choice
1243 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1244 (const :tag "with y-or-n (faster)" y-or-n-p)
1245 (const :tag "no confirmation (dangerous)" nil)))
1247 (defconst org-file-apps-defaults-gnu
1248 '((remote . emacs)
1249 (system . mailcap)
1250 (t . mailcap))
1251 "Default file applications on a UNIX or GNU/Linux system.
1252 See `org-file-apps'.")
1254 (defconst org-file-apps-defaults-macosx
1255 '((remote . emacs)
1256 (t . "open %s")
1257 (system . "open %s")
1258 ("ps.gz" . "gv %s")
1259 ("eps.gz" . "gv %s")
1260 ("dvi" . "xdvi %s")
1261 ("fig" . "xfig %s"))
1262 "Default file applications on a MacOS X system.
1263 The system \"open\" is known as a default, but we use X11 applications
1264 for some files for which the OS does not have a good default.
1265 See `org-file-apps'.")
1267 (defconst org-file-apps-defaults-windowsnt
1268 (list
1269 '(remote . emacs)
1270 (cons t
1271 (list (if (featurep 'xemacs)
1272 'mswindows-shell-execute
1273 'w32-shell-execute)
1274 "open" 'file))
1275 (cons 'system
1276 (list (if (featurep 'xemacs)
1277 'mswindows-shell-execute
1278 'w32-shell-execute)
1279 "open" 'file)))
1280 "Default file applications on a Windows NT system.
1281 The system \"open\" is used for most files.
1282 See `org-file-apps'.")
1284 (defcustom org-file-apps
1286 (auto-mode . emacs)
1287 ("\\.x?html?\\'" . default)
1288 ("\\.pdf\\'" . default)
1290 "External applications for opening `file:path' items in a document.
1291 Org-mode uses system defaults for different file types, but
1292 you can use this variable to set the application for a given file
1293 extension. The entries in this list are cons cells where the car identifies
1294 files and the cdr the corresponding command. Possible values for the
1295 file identifier are
1296 \"regex\" Regular expression matched against the file name. For backward
1297 compatibility, this can also be a string with only alphanumeric
1298 characters, which is then interpreted as an extension.
1299 `directory' Matches a directory
1300 `remote' Matches a remote file, accessible through tramp or efs.
1301 Remote files most likely should be visited through Emacs
1302 because external applications cannot handle such paths.
1303 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1304 so all files Emacs knows how to handle. Using this with
1305 command `emacs' will open most files in Emacs. Beware that this
1306 will also open html files inside Emacs, unless you add
1307 (\"html\" . default) to the list as well.
1308 t Default for files not matched by any of the other options.
1309 `system' The system command to open files, like `open' on Windows
1310 and Mac OS X, and mailcap under GNU/Linux. This is the command
1311 that will be selected if you call `C-c C-o' with a double
1312 `C-u C-u' prefix.
1314 Possible values for the command are:
1315 `emacs' The file will be visited by the current Emacs process.
1316 `default' Use the default application for this file type, which is the
1317 association for t in the list, most likely in the system-specific
1318 part.
1319 This can be used to overrule an unwanted setting in the
1320 system-specific variable.
1321 `system' Use the system command for opening files, like \"open\".
1322 This command is specified by the entry whose car is `system'.
1323 Most likely, the system-specific version of this variable
1324 does define this command, but you can overrule/replace it
1325 here.
1326 string A command to be executed by a shell; %s will be replaced
1327 by the path to the file.
1328 sexp A Lisp form which will be evaluated. The file path will
1329 be available in the Lisp variable `file'.
1330 For more examples, see the system specific constants
1331 `org-file-apps-defaults-macosx'
1332 `org-file-apps-defaults-windowsnt'
1333 `org-file-apps-defaults-gnu'."
1334 :group 'org-link-follow
1335 :type '(repeat
1336 (cons (choice :value ""
1337 (string :tag "Extension")
1338 (const :tag "System command to open files" system)
1339 (const :tag "Default for unrecognized files" t)
1340 (const :tag "Remote file" remote)
1341 (const :tag "Links to a directory" directory)
1342 (const :tag "Any files that have Emacs modes"
1343 auto-mode))
1344 (choice :value ""
1345 (const :tag "Visit with Emacs" emacs)
1346 (const :tag "Use default" default)
1347 (const :tag "Use the system command" system)
1348 (string :tag "Command")
1349 (sexp :tag "Lisp form")))))
1351 (defgroup org-refile nil
1352 "Options concerning refiling entries in Org-mode."
1353 :tag "Org Refile"
1354 :group 'org)
1356 (defcustom org-directory "~/org"
1357 "Directory with org files.
1358 This is just a default location to look for Org files. There is no need
1359 at all to put your files into this directory. It is only used in the
1360 following situations:
1362 1. When a remember template specifies a target file that is not an
1363 absolute path. The path will then be interpreted relative to
1364 `org-directory'
1365 2. When a remember note is filed away in an interactive way (when exiting the
1366 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1367 with `org-directory' as the default path."
1368 :group 'org-refile
1369 :group 'org-remember
1370 :type 'directory)
1372 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1373 "Default target for storing notes.
1374 Used by the hooks for remember.el. This can be a string, or nil to mean
1375 the value of `remember-data-file'.
1376 You can set this on a per-template basis with the variable
1377 `org-remember-templates'."
1378 :group 'org-refile
1379 :group 'org-remember
1380 :type '(choice
1381 (const :tag "Default from remember-data-file" nil)
1382 file))
1384 (defcustom org-goto-interface 'outline
1385 "The default interface to be used for `org-goto'.
1386 Allowed values are:
1387 outline The interface shows an outline of the relevant file
1388 and the correct heading is found by moving through
1389 the outline or by searching with incremental search.
1390 outline-path-completion Headlines in the current buffer are offered via
1391 completion. This is the interface also used by
1392 the refile command."
1393 :group 'org-refile
1394 :type '(choice
1395 (const :tag "Outline" outline)
1396 (const :tag "Outline-path-completion" outline-path-completion)))
1398 (defcustom org-goto-max-level 5
1399 "Maximum level to be considered when running org-goto with refile interface."
1400 :group 'org-refile
1401 :type 'number)
1403 (defcustom org-reverse-note-order nil
1404 "Non-nil means, store new notes at the beginning of a file or entry.
1405 When nil, new notes will be filed to the end of a file or entry.
1406 This can also be a list with cons cells of regular expressions that
1407 are matched against file names, and values."
1408 :group 'org-remember
1409 :group 'org-refile
1410 :type '(choice
1411 (const :tag "Reverse always" t)
1412 (const :tag "Reverse never" nil)
1413 (repeat :tag "By file name regexp"
1414 (cons regexp boolean))))
1416 (defcustom org-refile-targets nil
1417 "Targets for refiling entries with \\[org-refile].
1418 This is list of cons cells. Each cell contains:
1419 - a specification of the files to be considered, either a list of files,
1420 or a symbol whose function or variable value will be used to retrieve
1421 a file name or a list of file names. If you use `org-agenda-files' for
1422 that, all agenda files will be scanned for targets. Nil means, consider
1423 headings in the current buffer.
1424 - A specification of how to select find candidate refile targets. This
1425 may be any of
1426 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1427 This tag has to be present in all target headlines, inheritance will
1428 not be considered.
1429 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1430 todo keyword.
1431 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1432 headlines that are refiling targets.
1433 - a cons cell (:level . N). Any headline of level N is considered a target.
1434 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1436 When this variable is nil, all top-level headlines in the current buffer
1437 are used, equivalent to the value `((nil . (:level . 1))'."
1438 :group 'org-refile
1439 :type '(repeat
1440 (cons
1441 (choice :value org-agenda-files
1442 (const :tag "All agenda files" org-agenda-files)
1443 (const :tag "Current buffer" nil)
1444 (function) (variable) (file))
1445 (choice :tag "Identify target headline by"
1446 (cons :tag "Specific tag" (const :value :tag) (string))
1447 (cons :tag "TODO keyword" (const :value :todo) (string))
1448 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1449 (cons :tag "Level number" (const :value :level) (integer))
1450 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1452 (defcustom org-refile-use-outline-path nil
1453 "Non-nil means, provide refile targets as paths.
1454 So a level 3 headline will be available as level1/level2/level3.
1455 When the value is `file', also include the file name (without directory)
1456 into the path. When `full-file-path', include the full file path."
1457 :group 'org-refile
1458 :type '(choice
1459 (const :tag "Not" nil)
1460 (const :tag "Yes" t)
1461 (const :tag "Start with file name" file)
1462 (const :tag "Start with full file path" full-file-path)))
1464 (defcustom org-outline-path-complete-in-steps t
1465 "Non-nil means, complete the outline path in hierarchical steps.
1466 When Org-mode uses the refile interface to select an outline path
1467 \(see variable `org-refile-use-outline-path'), the completion of
1468 the path can be done is a single go, or if can be done in steps down
1469 the headline hierarchy. Going in steps is probably the best if you
1470 do not use a special completion package like `ido' or `icicles'.
1471 However, when using these packages, going in one step can be very
1472 fast, while still showing the whole path to the entry."
1473 :group 'org-refile
1474 :type 'boolean)
1476 (defgroup org-todo nil
1477 "Options concerning TODO items in Org-mode."
1478 :tag "Org TODO"
1479 :group 'org)
1481 (defgroup org-progress nil
1482 "Options concerning Progress logging in Org-mode."
1483 :tag "Org Progress"
1484 :group 'org-time)
1486 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1487 "List of TODO entry keyword sequences and their interpretation.
1488 \\<org-mode-map>This is a list of sequences.
1490 Each sequence starts with a symbol, either `sequence' or `type',
1491 indicating if the keywords should be interpreted as a sequence of
1492 action steps, or as different types of TODO items. The first
1493 keywords are states requiring action - these states will select a headline
1494 for inclusion into the global TODO list Org-mode produces. If one of
1495 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1496 signify that no further action is necessary. If \"|\" is not found,
1497 the last keyword is treated as the only DONE state of the sequence.
1499 The command \\[org-todo] cycles an entry through these states, and one
1500 additional state where no keyword is present. For details about this
1501 cycling, see the manual.
1503 TODO keywords and interpretation can also be set on a per-file basis with
1504 the special #+SEQ_TODO and #+TYP_TODO lines.
1506 Each keyword can optionally specify a character for fast state selection
1507 \(in combination with the variable `org-use-fast-todo-selection')
1508 and specifiers for state change logging, using the same syntax
1509 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1510 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1511 indicates to record a time stamp each time this state is selected.
1513 Each keyword may also specify if a timestamp or a note should be
1514 recorded when entering or leaving the state, by adding additional
1515 characters in the parenthesis after the keyword. This looks like this:
1516 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1517 record only the time of the state change. With X and Y being either
1518 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1519 Y when leaving the state if and only if the *target* state does not
1520 define X. You may omit any of the fast-selection key or X or /Y,
1521 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1523 For backward compatibility, this variable may also be just a list
1524 of keywords - in this case the interpretation (sequence or type) will be
1525 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1526 :group 'org-todo
1527 :group 'org-keywords
1528 :type '(choice
1529 (repeat :tag "Old syntax, just keywords"
1530 (string :tag "Keyword"))
1531 (repeat :tag "New syntax"
1532 (cons
1533 (choice
1534 :tag "Interpretation"
1535 (const :tag "Sequence (cycling hits every state)" sequence)
1536 (const :tag "Type (cycling directly to DONE)" type))
1537 (repeat
1538 (string :tag "Keyword"))))))
1540 (defvar org-todo-keywords-1 nil
1541 "All TODO and DONE keywords active in a buffer.")
1542 (make-variable-buffer-local 'org-todo-keywords-1)
1543 (defvar org-todo-keywords-for-agenda nil)
1544 (defvar org-done-keywords-for-agenda nil)
1545 (defvar org-todo-keyword-alist-for-agenda nil)
1546 (defvar org-tag-alist-for-agenda nil)
1547 (defvar org-agenda-contributing-files nil)
1548 (defvar org-not-done-keywords nil)
1549 (make-variable-buffer-local 'org-not-done-keywords)
1550 (defvar org-done-keywords nil)
1551 (make-variable-buffer-local 'org-done-keywords)
1552 (defvar org-todo-heads nil)
1553 (make-variable-buffer-local 'org-todo-heads)
1554 (defvar org-todo-sets nil)
1555 (make-variable-buffer-local 'org-todo-sets)
1556 (defvar org-todo-log-states nil)
1557 (make-variable-buffer-local 'org-todo-log-states)
1558 (defvar org-todo-kwd-alist nil)
1559 (make-variable-buffer-local 'org-todo-kwd-alist)
1560 (defvar org-todo-key-alist nil)
1561 (make-variable-buffer-local 'org-todo-key-alist)
1562 (defvar org-todo-key-trigger nil)
1563 (make-variable-buffer-local 'org-todo-key-trigger)
1565 (defcustom org-todo-interpretation 'sequence
1566 "Controls how TODO keywords are interpreted.
1567 This variable is in principle obsolete and is only used for
1568 backward compatibility, if the interpretation of todo keywords is
1569 not given already in `org-todo-keywords'. See that variable for
1570 more information."
1571 :group 'org-todo
1572 :group 'org-keywords
1573 :type '(choice (const sequence)
1574 (const type)))
1576 (defcustom org-use-fast-todo-selection t
1577 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1578 This variable describes if and under what circumstances the cycling
1579 mechanism for TODO keywords will be replaced by a single-key, direct
1580 selection scheme.
1582 When nil, fast selection is never used.
1584 When the symbol `prefix', it will be used when `org-todo' is called with
1585 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1586 in an agenda buffer.
1588 When t, fast selection is used by default. In this case, the prefix
1589 argument forces cycling instead.
1591 In all cases, the special interface is only used if access keys have actually
1592 been assigned by the user, i.e. if keywords in the configuration are followed
1593 by a letter in parenthesis, like TODO(t)."
1594 :group 'org-todo
1595 :type '(choice
1596 (const :tag "Never" nil)
1597 (const :tag "By default" t)
1598 (const :tag "Only with C-u C-c C-t" prefix)))
1600 (defcustom org-provide-todo-statistics t
1601 "Non-nil means, update todo statistics after insert and toggle.
1602 When this is set, todo statistics is updated in the parent of the current
1603 entry each time a todo state is changed."
1604 :group 'org-todo
1605 :type 'boolean)
1607 (defcustom org-after-todo-state-change-hook nil
1608 "Hook which is run after the state of a TODO item was changed.
1609 The new state (a string with a TODO keyword, or nil) is available in the
1610 Lisp variable `state'."
1611 :group 'org-todo
1612 :type 'hook)
1614 (defvar org-blocker-hook nil
1615 "Hook for functions that are allowed to block a state change.
1617 Each function gets as its single argument a property list, see
1618 `org-trigger-hook' for more information about this list.
1620 If any of the functions in this hook returns nil, the state change
1621 is blocked.")
1623 (defvar org-trigger-hook nil
1624 "Hook for functions that are triggered by a state change.
1626 Each function gets as its single argument a property list with at least
1627 the following elements:
1629 (:type type-of-change :position pos-at-entry-start
1630 :from old-state :to new-state)
1632 Depending on the type, more properties may be present.
1634 This mechanism is currently implemented for:
1636 TODO state changes
1637 ------------------
1638 :type todo-state-change
1639 :from previous state (keyword as a string), or nil, or a symbol
1640 'todo' or 'done', to indicate the general type of state.
1641 :to new state, like in :from")
1643 (defcustom org-enforce-todo-dependencies nil
1644 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1645 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1646 be blocked if any prior sibling is not yet done.
1647 This variable needs to be set before org.el is loaded, and you need to
1648 restart Emacs after a change to make the change effective. The only way
1649 to change is while Emacs is running is through the customize interface."
1650 :set (lambda (var val)
1651 (set var val)
1652 (if val
1653 (add-hook 'org-blocker-hook
1654 'org-block-todo-from-children-or-siblings)
1655 (remove-hook 'org-blocker-hook
1656 'org-block-todo-from-children-or-siblings)))
1657 :group 'org-todo
1658 :type 'boolean)
1660 (defcustom org-enforce-todo-checkbox-dependencies nil
1661 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1662 When this is nil, checkboxes have no influence on switching TODO states.
1663 When non-nil, you first need to check off all check boxes before the TODO
1664 entry can be switched to DONE.
1665 This variable needs to be set before org.el is loaded, and you need to
1666 restart Emacs after a change to make the change effective. The only way
1667 to change is while Emacs is running is through the customize interface."
1668 :set (lambda (var val)
1669 (set var val)
1670 (if val
1671 (add-hook 'org-blocker-hook
1672 'org-block-todo-from-checkboxes)
1673 (remove-hook 'org-blocker-hook
1674 'org-block-todo-from-checkboxes)))
1675 :group 'org-todo
1676 :type 'boolean)
1678 (defcustom org-todo-state-tags-triggers nil
1679 "Tag changes that should be triggered by TODO state changes.
1680 This is a list. Each entry is
1682 (state-change (tag . flag) .......)
1684 State-change can be a string with a state, and empty string to indicate the
1685 state that has no TODO keyword, or it can be one of the symbols `todo'
1686 or `done', meaning any not-done or done state, respectively."
1687 :group 'org-todo
1688 :group 'org-tags
1689 :type '(repeat
1690 (cons (choice :tag "When changing to"
1691 (const :tag "Not-done state" todo)
1692 (const :tag "Done state" done)
1693 (string :tag "State"))
1694 (repeat
1695 (cons :tag "Tag action"
1696 (string :tag "Tag")
1697 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1699 (defcustom org-log-done nil
1700 "Information to record when a task moves to the DONE state.
1702 Possible values are:
1704 nil Don't add anything, just change the keyword
1705 time Add a time stamp to the task
1706 note Prompt a closing note and add it with template `org-log-note-headings'
1708 This option can also be set with on a per-file-basis with
1710 #+STARTUP: nologdone
1711 #+STARTUP: logdone
1712 #+STARTUP: lognotedone
1714 You can have local logging settings for a subtree by setting the LOGGING
1715 property to one or more of these keywords."
1716 :group 'org-todo
1717 :group 'org-progress
1718 :type '(choice
1719 (const :tag "No logging" nil)
1720 (const :tag "Record CLOSED timestamp" time)
1721 (const :tag "Record CLOSED timestamp with closing note." note)))
1723 ;; Normalize old uses of org-log-done.
1724 (cond
1725 ((eq org-log-done t) (setq org-log-done 'time))
1726 ((and (listp org-log-done) (memq 'done org-log-done))
1727 (setq org-log-done 'note)))
1729 (defcustom org-log-note-clock-out nil
1730 "Non-nil means, record a note when clocking out of an item.
1731 This can also be configured on a per-file basis by adding one of
1732 the following lines anywhere in the buffer:
1734 #+STARTUP: lognoteclock-out
1735 #+STARTUP: nolognoteclock-out"
1736 :group 'org-todo
1737 :group 'org-progress
1738 :type 'boolean)
1740 (defcustom org-log-done-with-time t
1741 "Non-nil means, the CLOSED time stamp will contain date and time.
1742 When nil, only the date will be recorded."
1743 :group 'org-progress
1744 :type 'boolean)
1746 (defcustom org-log-note-headings
1747 '((done . "CLOSING NOTE %t")
1748 (state . "State %-12s %t")
1749 (note . "Note taken on %t")
1750 (clock-out . ""))
1751 "Headings for notes added to entries.
1752 The value is an alist, with the car being a symbol indicating the note
1753 context, and the cdr is the heading to be used. The heading may also be the
1754 empty string.
1755 %t in the heading will be replaced by a time stamp.
1756 %s will be replaced by the new TODO state, in double quotes.
1757 %u will be replaced by the user name.
1758 %U will be replaced by the full user name."
1759 :group 'org-todo
1760 :group 'org-progress
1761 :type '(list :greedy t
1762 (cons (const :tag "Heading when closing an item" done) string)
1763 (cons (const :tag
1764 "Heading when changing todo state (todo sequence only)"
1765 state) string)
1766 (cons (const :tag "Heading when just taking a note" note) string)
1767 (cons (const :tag "Heading when clocking out" clock-out) string)))
1769 (unless (assq 'note org-log-note-headings)
1770 (push '(note . "%t") org-log-note-headings))
1772 (defcustom org-log-state-notes-insert-after-drawers nil
1773 "Non-nil means, insert state change notes after any drawers in entry.
1774 Only the drawers that *immediately* follow the headline and the
1775 deadline/scheduled line are skipped.
1776 When nil, insert notes right after the heading and perhaps the line
1777 with deadline/scheduling if present."
1778 :group 'org-todo
1779 :group 'org-progress
1780 :type 'boolean)
1782 (defcustom org-log-states-order-reversed t
1783 "Non-nil means, the latest state change note will be directly after heading.
1784 When nil, the notes will be orderer according to time."
1785 :group 'org-todo
1786 :group 'org-progress
1787 :type 'boolean)
1789 (defcustom org-log-repeat 'time
1790 "Non-nil means, record moving through the DONE state when triggering repeat.
1791 An auto-repeating tasks is immediately switched back to TODO when marked
1792 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1793 the TODO keyword definition, or recording a closing note by setting
1794 `org-log-done', there will be no record of the task moving through DONE.
1795 This variable forces taking a note anyway. Possible values are:
1797 nil Don't force a record
1798 time Record a time stamp
1799 note Record a note
1801 This option can also be set with on a per-file-basis with
1803 #+STARTUP: logrepeat
1804 #+STARTUP: lognoterepeat
1805 #+STARTUP: nologrepeat
1807 You can have local logging settings for a subtree by setting the LOGGING
1808 property to one or more of these keywords."
1809 :group 'org-todo
1810 :group 'org-progress
1811 :type '(choice
1812 (const :tag "Don't force a record" nil)
1813 (const :tag "Force recording the DONE state" time)
1814 (const :tag "Force recording a note with the DONE state" note)))
1817 (defgroup org-priorities nil
1818 "Priorities in Org-mode."
1819 :tag "Org Priorities"
1820 :group 'org-todo)
1822 (defcustom org-highest-priority ?A
1823 "The highest priority of TODO items. A character like ?A, ?B etc.
1824 Must have a smaller ASCII number than `org-lowest-priority'."
1825 :group 'org-priorities
1826 :type 'character)
1828 (defcustom org-lowest-priority ?C
1829 "The lowest priority of TODO items. A character like ?A, ?B etc.
1830 Must have a larger ASCII number than `org-highest-priority'."
1831 :group 'org-priorities
1832 :type 'character)
1834 (defcustom org-default-priority ?B
1835 "The default priority of TODO items.
1836 This is the priority an item get if no explicit priority is given."
1837 :group 'org-priorities
1838 :type 'character)
1840 (defcustom org-priority-start-cycle-with-default t
1841 "Non-nil means, start with default priority when starting to cycle.
1842 When this is nil, the first step in the cycle will be (depending on the
1843 command used) one higher or lower that the default priority."
1844 :group 'org-priorities
1845 :type 'boolean)
1847 (defgroup org-time nil
1848 "Options concerning time stamps and deadlines in Org-mode."
1849 :tag "Org Time"
1850 :group 'org)
1852 (defcustom org-insert-labeled-timestamps-at-point nil
1853 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1854 When nil, these labeled time stamps are forces into the second line of an
1855 entry, just after the headline. When scheduling from the global TODO list,
1856 the time stamp will always be forced into the second line."
1857 :group 'org-time
1858 :type 'boolean)
1860 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1861 "Formats for `format-time-string' which are used for time stamps.
1862 It is not recommended to change this constant.")
1864 (defcustom org-time-stamp-rounding-minutes '(0 5)
1865 "Number of minutes to round time stamps to.
1866 These are two values, the first applies when first creating a time stamp.
1867 The second applies when changing it with the commands `S-up' and `S-down'.
1868 When changing the time stamp, this means that it will change in steps
1869 of N minutes, as given by the second value.
1871 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1872 numbers should be factors of 60, so for example 5, 10, 15.
1874 When this is larger than 1, you can still force an exact time-stamp by using
1875 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1876 and by using a prefix arg to `S-up/down' to specify the exact number
1877 of minutes to shift."
1878 :group 'org-time
1879 :get '(lambda (var) ; Make sure all entries have 5 elements
1880 (if (integerp (default-value var))
1881 (list (default-value var) 5)
1882 (default-value var)))
1883 :type '(list
1884 (integer :tag "when inserting times")
1885 (integer :tag "when modifying times")))
1887 ;; Normalize old customizations of this variable.
1888 (when (integerp org-time-stamp-rounding-minutes)
1889 (setq org-time-stamp-rounding-minutes
1890 (list org-time-stamp-rounding-minutes
1891 org-time-stamp-rounding-minutes)))
1893 (defcustom org-display-custom-times nil
1894 "Non-nil means, overlay custom formats over all time stamps.
1895 The formats are defined through the variable `org-time-stamp-custom-formats'.
1896 To turn this on on a per-file basis, insert anywhere in the file:
1897 #+STARTUP: customtime"
1898 :group 'org-time
1899 :set 'set-default
1900 :type 'sexp)
1901 (make-variable-buffer-local 'org-display-custom-times)
1903 (defcustom org-time-stamp-custom-formats
1904 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1905 "Custom formats for time stamps. See `format-time-string' for the syntax.
1906 These are overlayed over the default ISO format if the variable
1907 `org-display-custom-times' is set. Time like %H:%M should be at the
1908 end of the second format."
1909 :group 'org-time
1910 :type 'sexp)
1912 (defun org-time-stamp-format (&optional long inactive)
1913 "Get the right format for a time string."
1914 (let ((f (if long (cdr org-time-stamp-formats)
1915 (car org-time-stamp-formats))))
1916 (if inactive
1917 (concat "[" (substring f 1 -1) "]")
1918 f)))
1920 (defcustom org-time-clocksum-format "%d:%02d"
1921 "The format string used when creating CLOCKSUM lines, or when
1922 org-mode generates a time duration."
1923 :group 'org-time
1924 :type 'string)
1926 (defcustom org-deadline-warning-days 14
1927 "No. of days before expiration during which a deadline becomes active.
1928 This variable governs the display in sparse trees and in the agenda.
1929 When 0 or negative, it means use this number (the absolute value of it)
1930 even if a deadline has a different individual lead time specified."
1931 :group 'org-time
1932 :group 'org-agenda-daily/weekly
1933 :type 'number)
1935 (defcustom org-read-date-prefer-future t
1936 "Non-nil means, assume future for incomplete date input from user.
1937 This affects the following situations:
1938 1. The user gives a day, but no month.
1939 For example, if today is the 15th, and you enter \"3\", Org-mode will
1940 read this as the third of *next* month. However, if you enter \"17\",
1941 it will be considered as *this* month.
1942 2. The user gives a month but not a year.
1943 For example, if it is april and you enter \"feb 2\", this will be read
1944 as feb 2, *next* year. \"May 5\", however, will be this year.
1946 Currently this does not work for ISO week specifications.
1948 When this option is nil, the current month and year will always be used
1949 as defaults."
1950 :group 'org-time
1951 :type 'boolean)
1953 (defcustom org-read-date-display-live t
1954 "Non-nil means, display current interpretation of date prompt live.
1955 This display will be in an overlay, in the minibuffer."
1956 :group 'org-time
1957 :type 'boolean)
1959 (defcustom org-read-date-popup-calendar t
1960 "Non-nil means, pop up a calendar when prompting for a date.
1961 In the calendar, the date can be selected with mouse-1. However, the
1962 minibuffer will also be active, and you can simply enter the date as well.
1963 When nil, only the minibuffer will be available."
1964 :group 'org-time
1965 :type 'boolean)
1966 (if (fboundp 'defvaralias)
1967 (defvaralias 'org-popup-calendar-for-date-prompt
1968 'org-read-date-popup-calendar))
1970 (defcustom org-extend-today-until 0
1971 "The hour when your day really ends. Must be an integer.
1972 This has influence for the following applications:
1973 - When switching the agenda to \"today\". It it is still earlier than
1974 the time given here, the day recognized as TODAY is actually yesterday.
1975 - When a date is read from the user and it is still before the time given
1976 here, the current date and time will be assumed to be yesterday, 23:59.
1977 Also, timestamps inserted in remember templates follow this rule.
1979 IMPORTANT: This is a feature whose implementation is and likely will
1980 remain incomplete. Really, it is only here because past midnight seems to
1981 be the favorite working time of John Wiegley :-)"
1982 :group 'org-time
1983 :type 'number)
1985 (defcustom org-edit-timestamp-down-means-later nil
1986 "Non-nil means, S-down will increase the time in a time stamp.
1987 When nil, S-up will increase."
1988 :group 'org-time
1989 :type 'boolean)
1991 (defcustom org-calendar-follow-timestamp-change t
1992 "Non-nil means, make the calendar window follow timestamp changes.
1993 When a timestamp is modified and the calendar window is visible, it will be
1994 moved to the new date."
1995 :group 'org-time
1996 :type 'boolean)
1998 (defgroup org-tags nil
1999 "Options concerning tags in Org-mode."
2000 :tag "Org Tags"
2001 :group 'org)
2003 (defcustom org-tag-alist nil
2004 "List of tags allowed in Org-mode files.
2005 When this list is nil, Org-mode will base TAG input on what is already in the
2006 buffer.
2007 The value of this variable is an alist, the car of each entry must be a
2008 keyword as a string, the cdr may be a character that is used to select
2009 that tag through the fast-tag-selection interface.
2010 See the manual for details."
2011 :group 'org-tags
2012 :type '(repeat
2013 (choice
2014 (cons (string :tag "Tag name")
2015 (character :tag "Access char"))
2016 (const :tag "Start radio group" (:startgroup))
2017 (const :tag "End radio group" (:endgroup)))))
2019 (defvar org-file-tags nil
2020 "List of tags that can be inherited by all entries in the file.
2021 The tags will be inherited if the variable `org-use-tag-inheritance'
2022 says they should be.
2023 This variable is populated from #+TAG lines.")
2025 (defcustom org-use-fast-tag-selection 'auto
2026 "Non-nil means, use fast tag selection scheme.
2027 This is a special interface to select and deselect tags with single keys.
2028 When nil, fast selection is never used.
2029 When the symbol `auto', fast selection is used if and only if selection
2030 characters for tags have been configured, either through the variable
2031 `org-tag-alist' or through a #+TAGS line in the buffer.
2032 When t, fast selection is always used and selection keys are assigned
2033 automatically if necessary."
2034 :group 'org-tags
2035 :type '(choice
2036 (const :tag "Always" t)
2037 (const :tag "Never" nil)
2038 (const :tag "When selection characters are configured" 'auto)))
2040 (defcustom org-fast-tag-selection-single-key nil
2041 "Non-nil means, fast tag selection exits after first change.
2042 When nil, you have to press RET to exit it.
2043 During fast tag selection, you can toggle this flag with `C-c'.
2044 This variable can also have the value `expert'. In this case, the window
2045 displaying the tags menu is not even shown, until you press C-c again."
2046 :group 'org-tags
2047 :type '(choice
2048 (const :tag "No" nil)
2049 (const :tag "Yes" t)
2050 (const :tag "Expert" expert)))
2052 (defvar org-fast-tag-selection-include-todo nil
2053 "Non-nil means, fast tags selection interface will also offer TODO states.
2054 This is an undocumented feature, you should not rely on it.")
2056 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2057 "The column to which tags should be indented in a headline.
2058 If this number is positive, it specifies the column. If it is negative,
2059 it means that the tags should be flushright to that column. For example,
2060 -80 works well for a normal 80 character screen."
2061 :group 'org-tags
2062 :type 'integer)
2064 (defcustom org-auto-align-tags t
2065 "Non-nil means, realign tags after pro/demotion of TODO state change.
2066 These operations change the length of a headline and therefore shift
2067 the tags around. With this options turned on, after each such operation
2068 the tags are again aligned to `org-tags-column'."
2069 :group 'org-tags
2070 :type 'boolean)
2072 (defcustom org-use-tag-inheritance t
2073 "Non-nil means, tags in levels apply also for sublevels.
2074 When nil, only the tags directly given in a specific line apply there.
2075 This may also be a list of tags that should be inherited, or a regexp that
2076 matches tags that should be inherited. Additional control is possible
2077 with the variable `org-tags-exclude-from-inheritance' which gives an
2078 explicit list of tags to be excluded from inheritance., even if the value of
2079 `org-use-tag-inheritance' would select it for inheritance.
2081 If this option is t, a match early-on in a tree can lead to a large
2082 number of matches in the subtree when constructing the agenda or creating
2083 a sparse tree. If you only want to see the first match in a tree during
2084 a search, check out the variable `org-tags-match-list-sublevels'."
2085 :group 'org-tags
2086 :type '(choice
2087 (const :tag "Not" nil)
2088 (const :tag "Always" t)
2089 (repeat :tag "Specific tags" (string :tag "Tag"))
2090 (regexp :tag "Tags matched by regexp")))
2092 (defcustom org-tags-exclude-from-inheritance nil
2093 "List of tags that should never be inherited.
2094 This is a way to exclude a few tags from inheritance. For way to do
2095 the opposite, to actively allow inheritance for selected tags,
2096 see the variable `org-use-tag-inheritance'."
2097 :group 'org-tags
2098 :type '(repeat (string :tag "Tag")))
2100 (defun org-tag-inherit-p (tag)
2101 "Check if TAG is one that should be inherited."
2102 (cond
2103 ((member tag org-tags-exclude-from-inheritance) nil)
2104 ((eq org-use-tag-inheritance t) t)
2105 ((not org-use-tag-inheritance) nil)
2106 ((stringp org-use-tag-inheritance)
2107 (string-match org-use-tag-inheritance tag))
2108 ((listp org-use-tag-inheritance)
2109 (member tag org-use-tag-inheritance))
2110 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2112 (defcustom org-tags-match-list-sublevels t
2113 "Non-nil means list also sublevels of headlines matching tag search.
2114 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2115 the sublevels of a headline matching a tag search often also match
2116 the same search. Listing all of them can create very long lists.
2117 Setting this variable to nil causes subtrees of a match to be skipped.
2118 This option is off by default, because inheritance in on. If you turn
2119 inheritance off, you very likely want to turn this option on.
2121 As a special case, if the tag search is restricted to TODO items, the
2122 value of this variable is ignored and sublevels are always checked, to
2123 make sure all corresponding TODO items find their way into the list.
2125 This variable is semi-obsolete and probably should always be true. It
2126 is better to limit inheritance to certain tags using the variables
2127 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2128 :group 'org-tags
2129 :type 'boolean)
2131 (defvar org-tags-history nil
2132 "History of minibuffer reads for tags.")
2133 (defvar org-last-tags-completion-table nil
2134 "The last used completion table for tags.")
2135 (defvar org-after-tags-change-hook nil
2136 "Hook that is run after the tags in a line have changed.")
2138 (defgroup org-properties nil
2139 "Options concerning properties in Org-mode."
2140 :tag "Org Properties"
2141 :group 'org)
2143 (defcustom org-property-format "%-10s %s"
2144 "How property key/value pairs should be formatted by `indent-line'.
2145 When `indent-line' hits a property definition, it will format the line
2146 according to this format, mainly to make sure that the values are
2147 lined-up with respect to each other."
2148 :group 'org-properties
2149 :type 'string)
2151 (defcustom org-use-property-inheritance nil
2152 "Non-nil means, properties apply also for sublevels.
2154 This setting is chiefly used during property searches. Turning it on can
2155 cause significant overhead when doing a search, which is why it is not
2156 on by default.
2158 When nil, only the properties directly given in the current entry count.
2159 When t, every property is inherited. The value may also be a list of
2160 properties that should have inheritance, or a regular expression matching
2161 properties that should be inherited.
2163 However, note that some special properties use inheritance under special
2164 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2165 and the properties ending in \"_ALL\" when they are used as descriptor
2166 for valid values of a property.
2168 Note for programmers:
2169 When querying an entry with `org-entry-get', you can control if inheritance
2170 should be used. By default, `org-entry-get' looks only at the local
2171 properties. You can request inheritance by setting the inherit argument
2172 to t (to force inheritance) or to `selective' (to respect the setting
2173 in this variable)."
2174 :group 'org-properties
2175 :type '(choice
2176 (const :tag "Not" nil)
2177 (const :tag "Always" t)
2178 (repeat :tag "Specific properties" (string :tag "Property"))
2179 (regexp :tag "Properties matched by regexp")))
2181 (defun org-property-inherit-p (property)
2182 "Check if PROPERTY is one that should be inherited."
2183 (cond
2184 ((eq org-use-property-inheritance t) t)
2185 ((not org-use-property-inheritance) nil)
2186 ((stringp org-use-property-inheritance)
2187 (string-match org-use-property-inheritance property))
2188 ((listp org-use-property-inheritance)
2189 (member property org-use-property-inheritance))
2190 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2192 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2193 "The default column format, if no other format has been defined.
2194 This variable can be set on the per-file basis by inserting a line
2196 #+COLUMNS: %25ITEM ....."
2197 :group 'org-properties
2198 :type 'string)
2200 (defcustom org-columns-ellipses ".."
2201 "The ellipses to be used when a field in column view is truncated.
2202 When this is the empty string, as many characters as possible are shown,
2203 but then there will be no visual indication that the field has been truncated.
2204 When this is a string of length N, the last N characters of a truncated
2205 field are replaced by this string. If the column is narrower than the
2206 ellipses string, only part of the ellipses string will be shown."
2207 :group 'org-properties
2208 :type 'string)
2210 (defcustom org-columns-modify-value-for-display-function nil
2211 "Function that modifies values for display in column view.
2212 For example, it can be used to cut out a certain part from a time stamp.
2213 The function must take 2 arguments:
2215 column-title The title of the column (*not* the property name)
2216 value The value that should be modified.
2218 The function should return the value that should be displayed,
2219 or nil if the normal value should be used."
2220 :group 'org-properties
2221 :type 'function)
2223 (defcustom org-effort-property "Effort"
2224 "The property that is being used to keep track of effort estimates.
2225 Effort estimates given in this property need to have the format H:MM."
2226 :group 'org-properties
2227 :group 'org-progress
2228 :type '(string :tag "Property"))
2230 (defconst org-global-properties-fixed
2231 '(("VISIBILITY_ALL" . "folded children content all"))
2232 "List of property/value pairs that can be inherited by any entry.
2233 These are fixed values, for the preset properties.")
2236 (defcustom org-global-properties nil
2237 "List of property/value pairs that can be inherited by any entry.
2238 You can set buffer-local values for the same purpose in the variable
2239 `org-file-properties' this by adding lines like
2241 #+PROPERTY: NAME VALUE"
2242 :group 'org-properties
2243 :type '(repeat
2244 (cons (string :tag "Property")
2245 (string :tag "Value"))))
2247 (defvar org-file-properties nil
2248 "List of property/value pairs that can be inherited by any entry.
2249 Valid for the current buffer.
2250 This variable is populated from #+PROPERTY lines.")
2251 (make-variable-buffer-local 'org-file-properties)
2253 (defgroup org-agenda nil
2254 "Options concerning agenda views in Org-mode."
2255 :tag "Org Agenda"
2256 :group 'org)
2258 (defvar org-category nil
2259 "Variable used by org files to set a category for agenda display.
2260 Such files should use a file variable to set it, for example
2262 # -*- mode: org; org-category: \"ELisp\"
2264 or contain a special line
2266 #+CATEGORY: ELisp
2268 If the file does not specify a category, then file's base name
2269 is used instead.")
2270 (make-variable-buffer-local 'org-category)
2271 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2273 (defcustom org-agenda-files nil
2274 "The files to be used for agenda display.
2275 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2276 \\[org-remove-file]. You can also use customize to edit the list.
2278 If an entry is a directory, all files in that directory that are matched by
2279 `org-agenda-file-regexp' will be part of the file list.
2281 If the value of the variable is not a list but a single file name, then
2282 the list of agenda files is actually stored and maintained in that file, one
2283 agenda file per line."
2284 :group 'org-agenda
2285 :type '(choice
2286 (repeat :tag "List of files and directories" file)
2287 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2289 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2290 "Regular expression to match files for `org-agenda-files'.
2291 If any element in the list in that variable contains a directory instead
2292 of a normal file, all files in that directory that are matched by this
2293 regular expression will be included."
2294 :group 'org-agenda
2295 :type 'regexp)
2297 (defcustom org-agenda-text-search-extra-files nil
2298 "List of extra files to be searched by text search commands.
2299 These files will be search in addition to the agenda files by the
2300 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2301 Note that these files will only be searched for text search commands,
2302 not for the other agenda views like todo lists, tag searches or the weekly
2303 agenda. This variable is intended to list notes and possibly archive files
2304 that should also be searched by these two commands.
2305 In fact, if the first element in the list is the symbol `agenda-archives',
2306 than all archive files of all agenda files will be added to the search
2307 scope."
2308 :group 'org-agenda
2309 :type '(set :greedy t
2310 (const :tag "Agenda Archives" agenda-archives)
2311 (repeat :inline t (file))))
2313 (if (fboundp 'defvaralias)
2314 (defvaralias 'org-agenda-multi-occur-extra-files
2315 'org-agenda-text-search-extra-files))
2317 (defcustom org-agenda-skip-unavailable-files nil
2318 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2319 A nil value means to remove them, after a query, from the list."
2320 :group 'org-agenda
2321 :type 'boolean)
2323 (defcustom org-calendar-to-agenda-key [?c]
2324 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2325 The command `org-calendar-goto-agenda' will be bound to this key. The
2326 default is the character `c' because then `c' can be used to switch back and
2327 forth between agenda and calendar."
2328 :group 'org-agenda
2329 :type 'sexp)
2331 (defcustom org-calendar-agenda-action-key [?k]
2332 "The key to be installed in `calendar-mode-map' for agenda-action.
2333 The command `org-agenda-action' will be bound to this key. The
2334 default is the character `k' because we use the same key in the agenda."
2335 :group 'org-agenda
2336 :type 'sexp)
2338 (eval-after-load "calendar"
2339 '(progn
2340 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2341 'org-calendar-goto-agenda)
2342 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2343 'org-agenda-action)))
2345 (defgroup org-latex nil
2346 "Options for embedding LaTeX code into Org-mode."
2347 :tag "Org LaTeX"
2348 :group 'org)
2350 (defcustom org-format-latex-options
2351 '(:foreground default :background default :scale 1.0
2352 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2353 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2354 "Options for creating images from LaTeX fragments.
2355 This is a property list with the following properties:
2356 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2357 `default' means use the foreground of the default face.
2358 :background the background color, or \"Transparent\".
2359 `default' means use the background of the default face.
2360 :scale a scaling factor for the size of the images.
2361 :html-foreground, :html-background, :html-scale
2362 the same numbers for HTML export.
2363 :matchers a list indicating which matchers should be used to
2364 find LaTeX fragments. Valid members of this list are:
2365 \"begin\" find environments
2366 \"$1\" find single characters surrounded by $.$
2367 \"$\" find math expressions surrounded by $...$
2368 \"$$\" find math expressions surrounded by $$....$$
2369 \"\\(\" find math expressions surrounded by \\(...\\)
2370 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2371 :group 'org-latex
2372 :type 'plist)
2374 (defcustom org-format-latex-header "\\documentclass{article}
2375 \\usepackage{fullpage} % do not remove
2376 \\usepackage{amssymb}
2377 \\usepackage[usenames]{color}
2378 \\usepackage{amsmath}
2379 \\usepackage{latexsym}
2380 \\usepackage[mathscr]{eucal}
2381 \\pagestyle{empty} % do not remove"
2382 "The document header used for processing LaTeX fragments."
2383 :group 'org-latex
2384 :type 'string)
2387 (defgroup org-font-lock nil
2388 "Font-lock settings for highlighting in Org-mode."
2389 :tag "Org Font Lock"
2390 :group 'org)
2392 (defcustom org-level-color-stars-only nil
2393 "Non-nil means fontify only the stars in each headline.
2394 When nil, the entire headline is fontified.
2395 Changing it requires restart of `font-lock-mode' to become effective
2396 also in regions already fontified."
2397 :group 'org-font-lock
2398 :type 'boolean)
2400 (defcustom org-hide-leading-stars nil
2401 "Non-nil means, hide the first N-1 stars in a headline.
2402 This works by using the face `org-hide' for these stars. This
2403 face is white for a light background, and black for a dark
2404 background. You may have to customize the face `org-hide' to
2405 make this work.
2406 Changing it requires restart of `font-lock-mode' to become effective
2407 also in regions already fontified.
2408 You may also set this on a per-file basis by adding one of the following
2409 lines to the buffer:
2411 #+STARTUP: hidestars
2412 #+STARTUP: showstars"
2413 :group 'org-font-lock
2414 :type 'boolean)
2416 (defcustom org-fontify-done-headline nil
2417 "Non-nil means, change the face of a headline if it is marked DONE.
2418 Normally, only the TODO/DONE keyword indicates the state of a headline.
2419 When this is non-nil, the headline after the keyword is set to the
2420 `org-headline-done' as an additional indication."
2421 :group 'org-font-lock
2422 :type 'boolean)
2424 (defcustom org-fontify-emphasized-text t
2425 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2426 Changing this variable requires a restart of Emacs to take effect."
2427 :group 'org-font-lock
2428 :type 'boolean)
2430 (defcustom org-highlight-latex-fragments-and-specials nil
2431 "Non-nil means, fontify what is treated specially by the exporters."
2432 :group 'org-font-lock
2433 :type 'boolean)
2435 (defcustom org-hide-emphasis-markers nil
2436 "Non-nil mean font-lock should hide the emphasis marker characters."
2437 :group 'org-font-lock
2438 :type 'boolean)
2440 (defvar org-emph-re nil
2441 "Regular expression for matching emphasis.")
2442 (defvar org-verbatim-re nil
2443 "Regular expression for matching verbatim text.")
2444 (defvar org-emphasis-regexp-components) ; defined just below
2445 (defvar org-emphasis-alist) ; defined just below
2446 (defun org-set-emph-re (var val)
2447 "Set variable and compute the emphasis regular expression."
2448 (set var val)
2449 (when (and (boundp 'org-emphasis-alist)
2450 (boundp 'org-emphasis-regexp-components)
2451 org-emphasis-alist org-emphasis-regexp-components)
2452 (let* ((e org-emphasis-regexp-components)
2453 (pre (car e))
2454 (post (nth 1 e))
2455 (border (nth 2 e))
2456 (body (nth 3 e))
2457 (nl (nth 4 e))
2458 (body1 (concat body "*?"))
2459 (markers (mapconcat 'car org-emphasis-alist ""))
2460 (vmarkers (mapconcat
2461 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2462 org-emphasis-alist "")))
2463 ;; make sure special characters appear at the right position in the class
2464 (if (string-match "\\^" markers)
2465 (setq markers (concat (replace-match "" t t markers) "^")))
2466 (if (string-match "-" markers)
2467 (setq markers (concat (replace-match "" t t markers) "-")))
2468 (if (string-match "\\^" vmarkers)
2469 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2470 (if (string-match "-" vmarkers)
2471 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2472 (if (> nl 0)
2473 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2474 (int-to-string nl) "\\}")))
2475 ;; Make the regexp
2476 (setq org-emph-re
2477 (concat "\\([" pre "]\\|^\\)"
2478 "\\("
2479 "\\([" markers "]\\)"
2480 "\\("
2481 "[^" border "]\\|"
2482 "[^" border "]"
2483 body1
2484 "[^" border "]"
2485 "\\)"
2486 "\\3\\)"
2487 "\\([" post "]\\|$\\)"))
2488 (setq org-verbatim-re
2489 (concat "\\([" pre "]\\|^\\)"
2490 "\\("
2491 "\\([" vmarkers "]\\)"
2492 "\\("
2493 "[^" border "]\\|"
2494 "[^" border "]"
2495 body1
2496 "[^" border "]"
2497 "\\)"
2498 "\\3\\)"
2499 "\\([" post "]\\|$\\)")))))
2501 (defcustom org-emphasis-regexp-components
2502 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2503 "Components used to build the regular expression for emphasis.
2504 This is a list with 6 entries. Terminology: In an emphasis string
2505 like \" *strong word* \", we call the initial space PREMATCH, the final
2506 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2507 and \"trong wor\" is the body. The different components in this variable
2508 specify what is allowed/forbidden in each part:
2510 pre Chars allowed as prematch. Beginning of line will be allowed too.
2511 post Chars allowed as postmatch. End of line will be allowed too.
2512 border The chars *forbidden* as border characters.
2513 body-regexp A regexp like \".\" to match a body character. Don't use
2514 non-shy groups here, and don't allow newline here.
2515 newline The maximum number of newlines allowed in an emphasis exp.
2517 Use customize to modify this, or restart Emacs after changing it."
2518 :group 'org-font-lock
2519 :set 'org-set-emph-re
2520 :type '(list
2521 (sexp :tag "Allowed chars in pre ")
2522 (sexp :tag "Allowed chars in post ")
2523 (sexp :tag "Forbidden chars in border ")
2524 (sexp :tag "Regexp for body ")
2525 (integer :tag "number of newlines allowed")
2526 (option (boolean :tag "Please ignore this button"))))
2528 (defcustom org-emphasis-alist
2529 `(("*" bold "<b>" "</b>")
2530 ("/" italic "<i>" "</i>")
2531 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2532 ("=" org-code "<code>" "</code>" verbatim)
2533 ("~" org-verbatim "<code>" "</code>" verbatim)
2534 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2535 "<del>" "</del>")
2537 "Special syntax for emphasized text.
2538 Text starting and ending with a special character will be emphasized, for
2539 example *bold*, _underlined_ and /italic/. This variable sets the marker
2540 characters, the face to be used by font-lock for highlighting in Org-mode
2541 Emacs buffers, and the HTML tags to be used for this.
2542 Use customize to modify this, or restart Emacs after changing it."
2543 :group 'org-font-lock
2544 :set 'org-set-emph-re
2545 :type '(repeat
2546 (list
2547 (string :tag "Marker character")
2548 (choice
2549 (face :tag "Font-lock-face")
2550 (plist :tag "Face property list"))
2551 (string :tag "HTML start tag")
2552 (string :tag "HTML end tag")
2553 (option (const verbatim)))))
2555 ;;; Miscellaneous options
2557 (defgroup org-completion nil
2558 "Completion in Org-mode."
2559 :tag "Org Completion"
2560 :group 'org)
2562 (defcustom org-completion-use-ido nil
2563 "Non-nil means, use ido completion wherever possible.
2564 Note that `ido-mode' must be active for this variable to be relevant.
2565 If you decide to turn this variable on, you might well want to turn off
2566 `org-outline-path-complete-in-steps'."
2567 :group 'org-completion
2568 :type 'boolean)
2570 (defcustom org-completion-fallback-command 'hippie-expand
2571 "The expansion command called by \\[org-complete] in normal context.
2572 Normal means, no org-mode-specific context."
2573 :group 'org-completion
2574 :type 'function)
2576 ;;; Functions and variables from ther packages
2577 ;; Declared here to avoid compiler warnings
2579 ;; XEmacs only
2580 (defvar outline-mode-menu-heading)
2581 (defvar outline-mode-menu-show)
2582 (defvar outline-mode-menu-hide)
2583 (defvar zmacs-regions) ; XEmacs regions
2585 ;; Emacs only
2586 (defvar mark-active)
2588 ;; Various packages
2589 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2590 (declare-function calendar-forward-day "cal-move" (arg))
2591 (declare-function calendar-goto-date "cal-move" (date))
2592 (declare-function calendar-goto-today "cal-move" ())
2593 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2594 (defvar calc-embedded-close-formula)
2595 (defvar calc-embedded-open-formula)
2596 (declare-function cdlatex-tab "ext:cdlatex" ())
2597 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2598 (defvar font-lock-unfontify-region-function)
2599 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2600 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2601 (defvar iswitchb-temp-buflist)
2602 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2603 (defvar org-agenda-tags-todo-honor-ignore-options)
2604 (declare-function org-agenda-skip "org-agenda" ())
2605 (declare-function org-format-agenda-item "org-agenda"
2606 (extra txt &optional category tags dotime noprefix remove-re))
2607 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2608 (declare-function org-agenda-change-all-lines "org-agenda"
2609 (newhead hdmarker &optional fixface just-this))
2610 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2611 (declare-function org-agenda-maybe-redo "org-agenda" ())
2612 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2613 (beg end))
2614 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2615 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2616 "org-agenda" (&optional end))
2618 (declare-function parse-time-string "parse-time" (string))
2619 (declare-function remember "remember" (&optional initial))
2620 (declare-function remember-buffer-desc "remember" ())
2621 (declare-function remember-finalize "remember" ())
2622 (defvar remember-save-after-remembering)
2623 (defvar remember-data-file)
2624 (defvar remember-register)
2625 (defvar remember-buffer)
2626 (defvar remember-handler-functions)
2627 (defvar remember-annotation-functions)
2628 (defvar texmathp-why)
2629 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2630 (declare-function table--at-cell-p "table" (position &optional object at-column))
2632 (defvar w3m-current-url)
2633 (defvar w3m-current-title)
2635 (defvar org-latex-regexps)
2637 ;;; Autoload and prepare some org modules
2639 ;; Some table stuff that needs to be defined here, because it is used
2640 ;; by the functions setting up org-mode or checking for table context.
2642 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2643 "Detects an org-type or table-type table.")
2644 (defconst org-table-line-regexp "^[ \t]*|"
2645 "Detects an org-type table line.")
2646 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2647 "Detects an org-type table line.")
2648 (defconst org-table-hline-regexp "^[ \t]*|-"
2649 "Detects an org-type table hline.")
2650 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2651 "Detects a table-type table hline.")
2652 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2653 "Searching from within a table (any type) this finds the first line
2654 outside the table.")
2656 ;; Autoload the functions in org-table.el that are needed by functions here.
2658 (eval-and-compile
2659 (org-autoload "org-table"
2660 '(org-table-align org-table-begin org-table-blank-field
2661 org-table-convert org-table-convert-region org-table-copy-down
2662 org-table-copy-region org-table-create
2663 org-table-create-or-convert-from-region
2664 org-table-create-with-table.el org-table-current-dline
2665 org-table-cut-region org-table-delete-column org-table-edit-field
2666 org-table-edit-formulas org-table-end org-table-eval-formula
2667 org-table-export org-table-field-info
2668 org-table-get-stored-formulas org-table-goto-column
2669 org-table-hline-and-move org-table-import org-table-insert-column
2670 org-table-insert-hline org-table-insert-row org-table-iterate
2671 org-table-justify-field-maybe org-table-kill-row
2672 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2673 org-table-move-column org-table-move-column-left
2674 org-table-move-column-right org-table-move-row
2675 org-table-move-row-down org-table-move-row-up
2676 org-table-next-field org-table-next-row org-table-paste-rectangle
2677 org-table-previous-field org-table-recalculate
2678 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2679 org-table-toggle-coordinate-overlays
2680 org-table-toggle-formula-debugger org-table-wrap-region
2681 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2683 (defun org-at-table-p (&optional table-type)
2684 "Return t if the cursor is inside an org-type table.
2685 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2686 (if org-enable-table-editor
2687 (save-excursion
2688 (beginning-of-line 1)
2689 (looking-at (if table-type org-table-any-line-regexp
2690 org-table-line-regexp)))
2691 nil))
2692 (defsubst org-table-p () (org-at-table-p))
2694 (defun org-at-table.el-p ()
2695 "Return t if and only if we are at a table.el table."
2696 (and (org-at-table-p 'any)
2697 (save-excursion
2698 (goto-char (org-table-begin 'any))
2699 (looking-at org-table1-hline-regexp))))
2700 (defun org-table-recognize-table.el ()
2701 "If there is a table.el table nearby, recognize it and move into it."
2702 (if org-table-tab-recognizes-table.el
2703 (if (org-at-table.el-p)
2704 (progn
2705 (beginning-of-line 1)
2706 (if (looking-at org-table-dataline-regexp)
2708 (if (looking-at org-table1-hline-regexp)
2709 (progn
2710 (beginning-of-line 2)
2711 (if (looking-at org-table-any-border-regexp)
2712 (beginning-of-line -1)))))
2713 (if (re-search-forward "|" (org-table-end t) t)
2714 (progn
2715 (require 'table)
2716 (if (table--at-cell-p (point))
2718 (message "recognizing table.el table...")
2719 (table-recognize-table)
2720 (message "recognizing table.el table...done")))
2721 (error "This should not happen..."))
2723 nil)
2724 nil))
2726 (defun org-at-table-hline-p ()
2727 "Return t if the cursor is inside a hline in a table."
2728 (if org-enable-table-editor
2729 (save-excursion
2730 (beginning-of-line 1)
2731 (looking-at org-table-hline-regexp))
2732 nil))
2734 (defvar org-table-clean-did-remove-column nil)
2736 (defun org-table-map-tables (function)
2737 "Apply FUNCTION to the start of all tables in the buffer."
2738 (save-excursion
2739 (save-restriction
2740 (widen)
2741 (goto-char (point-min))
2742 (while (re-search-forward org-table-any-line-regexp nil t)
2743 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2744 (beginning-of-line 1)
2745 (if (looking-at org-table-line-regexp)
2746 (save-excursion (funcall function)))
2747 (re-search-forward org-table-any-border-regexp nil 1))))
2748 (message "Mapping tables: done"))
2750 ;; Declare and autoload functions from org-exp.el
2752 (declare-function org-default-export-plist "org-exp")
2753 (declare-function org-infile-export-plist "org-exp")
2754 (declare-function org-get-current-options "org-exp")
2755 (eval-and-compile
2756 (org-autoload "org-exp"
2757 '(org-export org-export-as-ascii org-export-visible
2758 org-insert-export-options-template org-export-as-html-and-open
2759 org-export-as-html-batch org-export-as-html-to-buffer
2760 org-replace-region-by-html org-export-region-as-html
2761 org-export-as-html org-export-icalendar-this-file
2762 org-export-icalendar-all-agenda-files
2763 org-table-clean-before-export
2764 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2766 ;; Declare and autoload functions from org-agenda.el
2768 (eval-and-compile
2769 (org-autoload "org-agenda"
2770 '(org-agenda org-agenda-list org-search-view
2771 org-todo-list org-tags-view org-agenda-list-stuck-projects
2772 org-diary org-agenda-to-appt
2773 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2775 ;; Autoload org-remember
2777 (eval-and-compile
2778 (org-autoload "org-remember"
2779 '(org-remember-insinuate org-remember-annotation
2780 org-remember-apply-template org-remember org-remember-handler)))
2782 ;; Autoload org-clock.el
2785 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2786 (beg end))
2787 (declare-function org-clock-update-mode-line "org-clock" ())
2788 (defvar org-clock-start-time)
2789 (defvar org-clock-marker (make-marker)
2790 "Marker recording the last clock-in.")
2792 (eval-and-compile
2793 (org-autoload
2794 "org-clock"
2795 '(org-clock-in org-clock-out org-clock-cancel
2796 org-clock-goto org-clock-sum org-clock-display
2797 org-clock-remove-overlays org-clock-report
2798 org-clocktable-shift org-dblock-write:clocktable
2799 org-get-clocktable)))
2801 (defun org-clock-update-time-maybe ()
2802 "If this is a CLOCK line, update it and return t.
2803 Otherwise, return nil."
2804 (interactive)
2805 (save-excursion
2806 (beginning-of-line 1)
2807 (skip-chars-forward " \t")
2808 (when (looking-at org-clock-string)
2809 (let ((re (concat "[ \t]*" org-clock-string
2810 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2811 "\\([ \t]*=>.*\\)?\\)?"))
2812 ts te h m s neg)
2813 (cond
2814 ((not (looking-at re))
2815 nil)
2816 ((not (match-end 2))
2817 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2818 (> org-clock-marker (point))
2819 (<= org-clock-marker (point-at-eol)))
2820 ;; The clock is running here
2821 (setq org-clock-start-time
2822 (apply 'encode-time
2823 (org-parse-time-string (match-string 1))))
2824 (org-clock-update-mode-line)))
2826 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2827 (end-of-line 1)
2828 (setq ts (match-string 1)
2829 te (match-string 3))
2830 (setq s (- (time-to-seconds
2831 (apply 'encode-time (org-parse-time-string te)))
2832 (time-to-seconds
2833 (apply 'encode-time (org-parse-time-string ts))))
2834 neg (< s 0)
2835 s (abs s)
2836 h (floor (/ s 3600))
2837 s (- s (* 3600 h))
2838 m (floor (/ s 60))
2839 s (- s (* 60 s)))
2840 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2841 t))))))
2843 (defun org-check-running-clock ()
2844 "Check if the current buffer contains the running clock.
2845 If yes, offer to stop it and to save the buffer with the changes."
2846 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2847 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2848 (buffer-name))))
2849 (org-clock-out)
2850 (when (y-or-n-p "Save changed buffer?")
2851 (save-buffer))))
2853 (defun org-clocktable-try-shift (dir n)
2854 "Check if this line starts a clock table, if yes, shift the time block."
2855 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2856 (org-clocktable-shift dir n)))
2858 ;; Autoload org-timer.el
2860 ;(declare-function org-timer "org-timer")
2862 (eval-and-compile
2863 (org-autoload
2864 "org-timer"
2865 '(org-timer-start org-timer org-timer-item
2866 org-timer-change-times-in-region)))
2869 ;; Autoload archiving code
2870 ;; The stuff that is needed for cycling and tags has to be defined here.
2872 (defgroup org-archive nil
2873 "Options concerning archiving in Org-mode."
2874 :tag "Org Archive"
2875 :group 'org-structure)
2877 (defcustom org-archive-location "%s_archive::"
2878 "The location where subtrees should be archived.
2880 The value of this variable is a string, consisting of two parts,
2881 separated by a double-colon. The first part is a filename and
2882 the second part is a headline.
2884 When the filename is omitted, archiving happens in the same file.
2885 %s in the filename will be replaced by the current file
2886 name (without the directory part). Archiving to a different file
2887 is useful to keep archived entries from contributing to the
2888 Org-mode Agenda.
2890 The archived entries will be filed as subtrees of the specified
2891 headline. When the headline is omitted, the subtrees are simply
2892 filed away at the end of the file, as top-level entries. Also in
2893 the heading you can use %s to represent the file name, this can be
2894 useful when using the same archive for a number of different files.
2896 Here are a few examples:
2897 \"%s_archive::\"
2898 If the current file is Projects.org, archive in file
2899 Projects.org_archive, as top-level trees. This is the default.
2901 \"::* Archived Tasks\"
2902 Archive in the current file, under the top-level headline
2903 \"* Archived Tasks\".
2905 \"~/org/archive.org::\"
2906 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2908 \"~/org/archive.org::From %s\"
2909 Archive in file ~/org/archive.org (absolute path), und headlines
2910 \"From FILENAME\" where file name is the current file name.
2912 \"basement::** Finished Tasks\"
2913 Archive in file ./basement (relative path), as level 3 trees
2914 below the level 2 heading \"** Finished Tasks\".
2916 You may set this option on a per-file basis by adding to the buffer a
2917 line like
2919 #+ARCHIVE: basement::** Finished Tasks
2921 You may also define it locally for a subtree by setting an ARCHIVE property
2922 in the entry. If such a property is found in an entry, or anywhere up
2923 the hierarchy, it will be used."
2924 :group 'org-archive
2925 :type 'string)
2927 (defcustom org-archive-tag "ARCHIVE"
2928 "The tag that marks a subtree as archived.
2929 An archived subtree does not open during visibility cycling, and does
2930 not contribute to the agenda listings.
2931 After changing this, font-lock must be restarted in the relevant buffers to
2932 get the proper fontification."
2933 :group 'org-archive
2934 :group 'org-keywords
2935 :type 'string)
2937 (defcustom org-agenda-skip-archived-trees t
2938 "Non-nil means, the agenda will skip any items located in archived trees.
2939 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2940 variable is no longer recommended, you should leave it at the value t.
2941 Instead, use the key `v' to cycle the archives-mode in the agenda."
2942 :group 'org-archive
2943 :group 'org-agenda-skip
2944 :type 'boolean)
2946 (defcustom org-cycle-open-archived-trees nil
2947 "Non-nil means, `org-cycle' will open archived trees.
2948 An archived tree is a tree marked with the tag ARCHIVE.
2949 When nil, archived trees will stay folded. You can still open them with
2950 normal outline commands like `show-all', but not with the cycling commands."
2951 :group 'org-archive
2952 :group 'org-cycle
2953 :type 'boolean)
2955 (defcustom org-sparse-tree-open-archived-trees nil
2956 "Non-nil means sparse tree construction shows matches in archived trees.
2957 When nil, matches in these trees are highlighted, but the trees are kept in
2958 collapsed state."
2959 :group 'org-archive
2960 :group 'org-sparse-trees
2961 :type 'boolean)
2963 (defun org-cycle-hide-archived-subtrees (state)
2964 "Re-hide all archived subtrees after a visibility state change."
2965 (when (and (not org-cycle-open-archived-trees)
2966 (not (memq state '(overview folded))))
2967 (save-excursion
2968 (let* ((globalp (memq state '(contents all)))
2969 (beg (if globalp (point-min) (point)))
2970 (end (if globalp (point-max) (org-end-of-subtree t))))
2971 (org-hide-archived-subtrees beg end)
2972 (goto-char beg)
2973 (if (looking-at (concat ".*:" org-archive-tag ":"))
2974 (message "%s" (substitute-command-keys
2975 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2977 (defun org-force-cycle-archived ()
2978 "Cycle subtree even if it is archived."
2979 (interactive)
2980 (setq this-command 'org-cycle)
2981 (let ((org-cycle-open-archived-trees t))
2982 (call-interactively 'org-cycle)))
2984 (defun org-hide-archived-subtrees (beg end)
2985 "Re-hide all archived subtrees after a visibility state change."
2986 (save-excursion
2987 (let* ((re (concat ":" org-archive-tag ":")))
2988 (goto-char beg)
2989 (while (re-search-forward re end t)
2990 (and (org-on-heading-p) (hide-subtree))
2991 (org-end-of-subtree t)))))
2993 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2995 (eval-and-compile
2996 (org-autoload "org-archive"
2997 '(org-add-archive-files org-archive-subtree
2998 org-archive-to-archive-sibling org-toggle-archive-tag)))
3000 ;; Autoload Column View Code
3002 (declare-function org-columns-number-to-string "org-colview")
3003 (declare-function org-columns-get-format-and-top-level "org-colview")
3004 (declare-function org-columns-compute "org-colview")
3006 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3007 '(org-columns-number-to-string org-columns-get-format-and-top-level
3008 org-columns-compute org-agenda-columns org-columns-remove-overlays
3009 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3011 ;; Autoload ID code
3013 (declare-function org-id-store-link "org-id")
3014 (org-autoload "org-id"
3015 '(org-id-get-create org-id-new org-id-copy org-id-get
3016 org-id-get-with-outline-path-completion
3017 org-id-get-with-outline-drilling
3018 org-id-goto org-id-find org-id-store-link))
3020 ;;; Variables for pre-computed regular expressions, all buffer local
3022 (defvar org-drawer-regexp nil
3023 "Matches first line of a hidden block.")
3024 (make-variable-buffer-local 'org-drawer-regexp)
3025 (defvar org-todo-regexp nil
3026 "Matches any of the TODO state keywords.")
3027 (make-variable-buffer-local 'org-todo-regexp)
3028 (defvar org-not-done-regexp nil
3029 "Matches any of the TODO state keywords except the last one.")
3030 (make-variable-buffer-local 'org-not-done-regexp)
3031 (defvar org-todo-line-regexp nil
3032 "Matches a headline and puts TODO state into group 2 if present.")
3033 (make-variable-buffer-local 'org-todo-line-regexp)
3034 (defvar org-complex-heading-regexp nil
3035 "Matches a headline and puts everything into groups:
3036 group 1: the stars
3037 group 2: The todo keyword, maybe
3038 group 3: Priority cookie
3039 group 4: True headline
3040 group 5: Tags")
3041 (make-variable-buffer-local 'org-complex-heading-regexp)
3042 (defvar org-todo-line-tags-regexp nil
3043 "Matches a headline and puts TODO state into group 2 if present.
3044 Also put tags into group 4 if tags are present.")
3045 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3046 (defvar org-nl-done-regexp nil
3047 "Matches newline followed by a headline with the DONE keyword.")
3048 (make-variable-buffer-local 'org-nl-done-regexp)
3049 (defvar org-looking-at-done-regexp nil
3050 "Matches the DONE keyword a point.")
3051 (make-variable-buffer-local 'org-looking-at-done-regexp)
3052 (defvar org-ds-keyword-length 12
3053 "Maximum length of the Deadline and SCHEDULED keywords.")
3054 (make-variable-buffer-local 'org-ds-keyword-length)
3055 (defvar org-deadline-regexp nil
3056 "Matches the DEADLINE keyword.")
3057 (make-variable-buffer-local 'org-deadline-regexp)
3058 (defvar org-deadline-time-regexp nil
3059 "Matches the DEADLINE keyword together with a time stamp.")
3060 (make-variable-buffer-local 'org-deadline-time-regexp)
3061 (defvar org-deadline-line-regexp nil
3062 "Matches the DEADLINE keyword and the rest of the line.")
3063 (make-variable-buffer-local 'org-deadline-line-regexp)
3064 (defvar org-scheduled-regexp nil
3065 "Matches the SCHEDULED keyword.")
3066 (make-variable-buffer-local 'org-scheduled-regexp)
3067 (defvar org-scheduled-time-regexp nil
3068 "Matches the SCHEDULED keyword together with a time stamp.")
3069 (make-variable-buffer-local 'org-scheduled-time-regexp)
3070 (defvar org-closed-time-regexp nil
3071 "Matches the CLOSED keyword together with a time stamp.")
3072 (make-variable-buffer-local 'org-closed-time-regexp)
3074 (defvar org-keyword-time-regexp nil
3075 "Matches any of the 4 keywords, together with the time stamp.")
3076 (make-variable-buffer-local 'org-keyword-time-regexp)
3077 (defvar org-keyword-time-not-clock-regexp nil
3078 "Matches any of the 3 keywords, together with the time stamp.")
3079 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3080 (defvar org-maybe-keyword-time-regexp nil
3081 "Matches a timestamp, possibly preceeded by a keyword.")
3082 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3083 (defvar org-planning-or-clock-line-re nil
3084 "Matches a line with planning or clock info.")
3085 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3087 (defconst org-plain-time-of-day-regexp
3088 (concat
3089 "\\(\\<[012]?[0-9]"
3090 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3091 "\\(--?"
3092 "\\(\\<[012]?[0-9]"
3093 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3094 "\\)?")
3095 "Regular expression to match a plain time or time range.
3096 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3097 groups carry important information:
3098 0 the full match
3099 1 the first time, range or not
3100 8 the second time, if it is a range.")
3102 (defconst org-plain-time-extension-regexp
3103 (concat
3104 "\\(\\<[012]?[0-9]"
3105 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3106 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3107 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3108 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3109 groups carry important information:
3110 0 the full match
3111 7 hours of duration
3112 9 minutes of duration")
3114 (defconst org-stamp-time-of-day-regexp
3115 (concat
3116 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3117 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3118 "\\(--?"
3119 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3120 "Regular expression to match a timestamp time or time range.
3121 After a match, the following groups carry important information:
3122 0 the full match
3123 1 date plus weekday, for backreferencing to make sure both times on same day
3124 2 the first time, range or not
3125 4 the second time, if it is a range.")
3127 (defconst org-startup-options
3128 '(("fold" org-startup-folded t)
3129 ("overview" org-startup-folded t)
3130 ("nofold" org-startup-folded nil)
3131 ("showall" org-startup-folded nil)
3132 ("content" org-startup-folded content)
3133 ("hidestars" org-hide-leading-stars t)
3134 ("showstars" org-hide-leading-stars nil)
3135 ("odd" org-odd-levels-only t)
3136 ("oddeven" org-odd-levels-only nil)
3137 ("align" org-startup-align-all-tables t)
3138 ("noalign" org-startup-align-all-tables nil)
3139 ("customtime" org-display-custom-times t)
3140 ("logdone" org-log-done time)
3141 ("lognotedone" org-log-done note)
3142 ("nologdone" org-log-done nil)
3143 ("lognoteclock-out" org-log-note-clock-out t)
3144 ("nolognoteclock-out" org-log-note-clock-out nil)
3145 ("logrepeat" org-log-repeat state)
3146 ("lognoterepeat" org-log-repeat note)
3147 ("nologrepeat" org-log-repeat nil)
3148 ("fninline" org-footnote-define-inline t)
3149 ("nofninline" org-footnote-define-inline nil)
3150 ("fnlocal" org-footnote-section nil)
3151 ("fnauto" org-footnote-auto-label t)
3152 ("fnprompt" org-footnote-auto-label nil)
3153 ("fnconfirm" org-footnote-auto-label confirm)
3154 ("fnplain" org-footnote-auto-label plain)
3155 ("constcgs" constants-unit-system cgs)
3156 ("constSI" constants-unit-system SI))
3157 "Variable associated with STARTUP options for org-mode.
3158 Each element is a list of three items: The startup options as written
3159 in the #+STARTUP line, the corresponding variable, and the value to
3160 set this variable to if the option is found. An optional forth element PUSH
3161 means to push this value onto the list in the variable.")
3163 (defun org-set-regexps-and-options ()
3164 "Precompute regular expressions for current buffer."
3165 (when (org-mode-p)
3166 (org-set-local 'org-todo-kwd-alist nil)
3167 (org-set-local 'org-todo-key-alist nil)
3168 (org-set-local 'org-todo-key-trigger nil)
3169 (org-set-local 'org-todo-keywords-1 nil)
3170 (org-set-local 'org-done-keywords nil)
3171 (org-set-local 'org-todo-heads nil)
3172 (org-set-local 'org-todo-sets nil)
3173 (org-set-local 'org-todo-log-states nil)
3174 (org-set-local 'org-file-properties nil)
3175 (org-set-local 'org-file-tags nil)
3176 (let ((re (org-make-options-regexp
3177 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3178 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3179 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3180 (splitre "[ \t]+")
3181 kwds kws0 kwsa key log value cat arch tags const links hw dws
3182 tail sep kws1 prio props ftags drawers
3183 ext-setup-or-nil setup-contents (start 0))
3184 (save-excursion
3185 (save-restriction
3186 (widen)
3187 (goto-char (point-min))
3188 (while (or (and ext-setup-or-nil
3189 (string-match re ext-setup-or-nil start)
3190 (setq start (match-end 0)))
3191 (and (setq ext-setup-or-nil nil start 0)
3192 (re-search-forward re nil t)))
3193 (setq key (upcase (match-string 1 ext-setup-or-nil))
3194 value (org-match-string-no-properties 2 ext-setup-or-nil))
3195 (cond
3196 ((equal key "CATEGORY")
3197 (if (string-match "[ \t]+$" value)
3198 (setq value (replace-match "" t t value)))
3199 (setq cat value))
3200 ((member key '("SEQ_TODO" "TODO"))
3201 (push (cons 'sequence (org-split-string value splitre)) kwds))
3202 ((equal key "TYP_TODO")
3203 (push (cons 'type (org-split-string value splitre)) kwds))
3204 ((equal key "TAGS")
3205 (setq tags (append tags (org-split-string value splitre))))
3206 ((equal key "COLUMNS")
3207 (org-set-local 'org-columns-default-format value))
3208 ((equal key "LINK")
3209 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3210 (push (cons (match-string 1 value)
3211 (org-trim (match-string 2 value)))
3212 links)))
3213 ((equal key "PRIORITIES")
3214 (setq prio (org-split-string value " +")))
3215 ((equal key "PROPERTY")
3216 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3217 (push (cons (match-string 1 value) (match-string 2 value))
3218 props)))
3219 ((equal key "FILETAGS")
3220 (when (string-match "\\S-" value)
3221 (setq ftags
3222 (append
3223 ftags
3224 (apply 'append
3225 (mapcar (lambda (x) (org-split-string x ":"))
3226 (org-split-string value)))))))
3227 ((equal key "DRAWERS")
3228 (setq drawers (org-split-string value splitre)))
3229 ((equal key "CONSTANTS")
3230 (setq const (append const (org-split-string value splitre))))
3231 ((equal key "STARTUP")
3232 (let ((opts (org-split-string value splitre))
3233 l var val)
3234 (while (setq l (pop opts))
3235 (when (setq l (assoc l org-startup-options))
3236 (setq var (nth 1 l) val (nth 2 l))
3237 (if (not (nth 3 l))
3238 (set (make-local-variable var) val)
3239 (if (not (listp (symbol-value var)))
3240 (set (make-local-variable var) nil))
3241 (set (make-local-variable var) (symbol-value var))
3242 (add-to-list var val))))))
3243 ((equal key "ARCHIVE")
3244 (string-match " *$" value)
3245 (setq arch (replace-match "" t t value))
3246 (remove-text-properties 0 (length arch)
3247 '(face t fontified t) arch))
3248 ((equal key "SETUPFILE")
3249 (setq setup-contents (org-file-contents
3250 (expand-file-name
3251 (org-remove-double-quotes value))
3252 'noerror))
3253 (if (not ext-setup-or-nil)
3254 (setq ext-setup-or-nil setup-contents start 0)
3255 (setq ext-setup-or-nil
3256 (concat (substring ext-setup-or-nil 0 start)
3257 "\n" setup-contents "\n"
3258 (substring ext-setup-or-nil start)))))
3259 ))))
3260 (when cat
3261 (org-set-local 'org-category (intern cat))
3262 (push (cons "CATEGORY" cat) props))
3263 (when prio
3264 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3265 (setq prio (mapcar 'string-to-char prio))
3266 (org-set-local 'org-highest-priority (nth 0 prio))
3267 (org-set-local 'org-lowest-priority (nth 1 prio))
3268 (org-set-local 'org-default-priority (nth 2 prio)))
3269 (and props (org-set-local 'org-file-properties (nreverse props)))
3270 (and ftags (org-set-local 'org-file-tags ftags))
3271 (and drawers (org-set-local 'org-drawers drawers))
3272 (and arch (org-set-local 'org-archive-location arch))
3273 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3274 ;; Process the TODO keywords
3275 (unless kwds
3276 ;; Use the global values as if they had been given locally.
3277 (setq kwds (default-value 'org-todo-keywords))
3278 (if (stringp (car kwds))
3279 (setq kwds (list (cons org-todo-interpretation
3280 (default-value 'org-todo-keywords)))))
3281 (setq kwds (reverse kwds)))
3282 (setq kwds (nreverse kwds))
3283 (let (inter kws kw)
3284 (while (setq kws (pop kwds))
3285 (setq inter (pop kws) sep (member "|" kws)
3286 kws0 (delete "|" (copy-sequence kws))
3287 kwsa nil
3288 kws1 (mapcar
3289 (lambda (x)
3290 ;; 1 2
3291 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3292 (progn
3293 (setq kw (match-string 1 x)
3294 key (and (match-end 2) (match-string 2 x))
3295 log (org-extract-log-state-settings x))
3296 (push (cons kw (and key (string-to-char key))) kwsa)
3297 (and log (push log org-todo-log-states))
3299 (error "Invalid TODO keyword %s" x)))
3300 kws0)
3301 kwsa (if kwsa (append '((:startgroup))
3302 (nreverse kwsa)
3303 '((:endgroup))))
3304 hw (car kws1)
3305 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3306 tail (list inter hw (car dws) (org-last dws)))
3307 (add-to-list 'org-todo-heads hw 'append)
3308 (push kws1 org-todo-sets)
3309 (setq org-done-keywords (append org-done-keywords dws nil))
3310 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3311 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3312 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3313 (setq org-todo-sets (nreverse org-todo-sets)
3314 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3315 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3316 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3317 ;; Process the constants
3318 (when const
3319 (let (e cst)
3320 (while (setq e (pop const))
3321 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3322 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3323 (setq org-table-formula-constants-local cst)))
3325 ;; Process the tags.
3326 (when tags
3327 (let (e tgs)
3328 (while (setq e (pop tags))
3329 (cond
3330 ((equal e "{") (push '(:startgroup) tgs))
3331 ((equal e "}") (push '(:endgroup) tgs))
3332 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3333 (push (cons (match-string 1 e)
3334 (string-to-char (match-string 2 e)))
3335 tgs))
3336 (t (push (list e) tgs))))
3337 (org-set-local 'org-tag-alist nil)
3338 (while (setq e (pop tgs))
3339 (or (and (stringp (car e))
3340 (assoc (car e) org-tag-alist))
3341 (push e org-tag-alist)))))
3343 ;; Compute the regular expressions and other local variables
3344 (if (not org-done-keywords)
3345 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3346 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3347 (length org-scheduled-string)
3348 (length org-clock-string)
3349 (length org-closed-string)))
3350 org-drawer-regexp
3351 (concat "^[ \t]*:\\("
3352 (mapconcat 'regexp-quote org-drawers "\\|")
3353 "\\):[ \t]*$")
3354 org-not-done-keywords
3355 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3356 org-todo-regexp
3357 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3358 "\\|") "\\)\\>")
3359 org-not-done-regexp
3360 (concat "\\<\\("
3361 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3362 "\\)\\>")
3363 org-todo-line-regexp
3364 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3365 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3366 "\\)\\>\\)?[ \t]*\\(.*\\)")
3367 org-complex-heading-regexp
3368 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3369 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3370 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3371 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3372 org-nl-done-regexp
3373 (concat "\n\\*+[ \t]+"
3374 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3375 "\\)" "\\>")
3376 org-todo-line-tags-regexp
3377 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3378 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3379 (org-re
3380 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3381 org-looking-at-done-regexp
3382 (concat "^" "\\(?:"
3383 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3384 "\\>")
3385 org-deadline-regexp (concat "\\<" org-deadline-string)
3386 org-deadline-time-regexp
3387 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3388 org-deadline-line-regexp
3389 (concat "\\<\\(" org-deadline-string "\\).*")
3390 org-scheduled-regexp
3391 (concat "\\<" org-scheduled-string)
3392 org-scheduled-time-regexp
3393 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3394 org-closed-time-regexp
3395 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3396 org-keyword-time-regexp
3397 (concat "\\<\\(" org-scheduled-string
3398 "\\|" org-deadline-string
3399 "\\|" org-closed-string
3400 "\\|" org-clock-string "\\)"
3401 " *[[<]\\([^]>]+\\)[]>]")
3402 org-keyword-time-not-clock-regexp
3403 (concat "\\<\\(" org-scheduled-string
3404 "\\|" org-deadline-string
3405 "\\|" org-closed-string
3406 "\\)"
3407 " *[[<]\\([^]>]+\\)[]>]")
3408 org-maybe-keyword-time-regexp
3409 (concat "\\(\\<\\(" org-scheduled-string
3410 "\\|" org-deadline-string
3411 "\\|" org-closed-string
3412 "\\|" org-clock-string "\\)\\)?"
3413 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3414 org-planning-or-clock-line-re
3415 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3416 "\\|" org-deadline-string
3417 "\\|" org-closed-string "\\|" org-clock-string
3418 "\\)\\>\\)")
3420 (org-compute-latex-and-specials-regexp)
3421 (org-set-font-lock-defaults))))
3423 (defun org-file-contents (file &optional noerror)
3424 "Return the contents of FILE, as a string."
3425 (if (or (not file)
3426 (not (file-readable-p file)))
3427 (if noerror
3428 (progn
3429 (message "Cannot read file %s" file)
3430 (ding) (sit-for 2)
3432 (error "Cannot read file %s" file))
3433 (with-temp-buffer
3434 (insert-file-contents file)
3435 (buffer-string))))
3437 (defun org-extract-log-state-settings (x)
3438 "Extract the log state setting from a TODO keyword string.
3439 This will extract info from a string like \"WAIT(w@/!)\"."
3440 (let (kw key log1 log2)
3441 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3442 (setq kw (match-string 1 x)
3443 key (and (match-end 2) (match-string 2 x))
3444 log1 (and (match-end 3) (match-string 3 x))
3445 log2 (and (match-end 4) (match-string 4 x)))
3446 (and (or log1 log2)
3447 (list kw
3448 (and log1 (if (equal log1 "!") 'time 'note))
3449 (and log2 (if (equal log2 "!") 'time 'note)))))))
3451 (defun org-remove-keyword-keys (list)
3452 "Remove a pair of parenthesis at the end of each string in LIST."
3453 (mapcar (lambda (x)
3454 (if (string-match "(.*)$" x)
3455 (substring x 0 (match-beginning 0))
3457 list))
3459 ;; FIXME: this could be done much better, using second characters etc.
3460 (defun org-assign-fast-keys (alist)
3461 "Assign fast keys to a keyword-key alist.
3462 Respect keys that are already there."
3463 (let (new e k c c1 c2 (char ?a))
3464 (while (setq e (pop alist))
3465 (cond
3466 ((equal e '(:startgroup)) (push e new))
3467 ((equal e '(:endgroup)) (push e new))
3469 (setq k (car e) c2 nil)
3470 (if (cdr e)
3471 (setq c (cdr e))
3472 ;; automatically assign a character.
3473 (setq c1 (string-to-char
3474 (downcase (substring
3475 k (if (= (string-to-char k) ?@) 1 0)))))
3476 (if (or (rassoc c1 new) (rassoc c1 alist))
3477 (while (or (rassoc char new) (rassoc char alist))
3478 (setq char (1+ char)))
3479 (setq c2 c1))
3480 (setq c (or c2 char)))
3481 (push (cons k c) new))))
3482 (nreverse new)))
3484 ;;; Some variables used in various places
3486 (defvar org-window-configuration nil
3487 "Used in various places to store a window configuration.")
3488 (defvar org-finish-function nil
3489 "Function to be called when `C-c C-c' is used.
3490 This is for getting out of special buffers like remember.")
3493 ;; FIXME: Occasionally check by commenting these, to make sure
3494 ;; no other functions uses these, forgetting to let-bind them.
3495 (defvar entry)
3496 (defvar state)
3497 (defvar last-state)
3498 (defvar date)
3499 (defvar description)
3501 ;; Defined somewhere in this file, but used before definition.
3502 (defvar org-html-entities)
3503 (defvar org-struct-menu)
3504 (defvar org-org-menu)
3505 (defvar org-tbl-menu)
3506 (defvar org-agenda-keymap)
3508 ;;;; Define the Org-mode
3510 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3511 (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."))
3514 ;; We use a before-change function to check if a table might need
3515 ;; an update.
3516 (defvar org-table-may-need-update t
3517 "Indicates that a table might need an update.
3518 This variable is set by `org-before-change-function'.
3519 `org-table-align' sets it back to nil.")
3520 (defun org-before-change-function (beg end)
3521 "Every change indicates that a table might need an update."
3522 (setq org-table-may-need-update t))
3523 (defvar org-mode-map)
3524 (defvar org-mode-hook nil
3525 "Mode hook for Org-mode, run after the mode was turned on.")
3526 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3527 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3528 (defvar org-table-buffer-is-an nil)
3529 (defconst org-outline-regexp "\\*+ ")
3531 ;;;###autoload
3532 (define-derived-mode org-mode outline-mode "Org"
3533 "Outline-based notes management and organizer, alias
3534 \"Carsten's outline-mode for keeping track of everything.\"
3536 Org-mode develops organizational tasks around a NOTES file which
3537 contains information about projects as plain text. Org-mode is
3538 implemented on top of outline-mode, which is ideal to keep the content
3539 of large files well structured. It supports ToDo items, deadlines and
3540 time stamps, which magically appear in the diary listing of the Emacs
3541 calendar. Tables are easily created with a built-in table editor.
3542 Plain text URL-like links connect to websites, emails (VM), Usenet
3543 messages (Gnus), BBDB entries, and any files related to the project.
3544 For printing and sharing of notes, an Org-mode file (or a part of it)
3545 can be exported as a structured ASCII or HTML file.
3547 The following commands are available:
3549 \\{org-mode-map}"
3551 ;; Get rid of Outline menus, they are not needed
3552 ;; Need to do this here because define-derived-mode sets up
3553 ;; the keymap so late. Still, it is a waste to call this each time
3554 ;; we switch another buffer into org-mode.
3555 (if (featurep 'xemacs)
3556 (when (boundp 'outline-mode-menu-heading)
3557 ;; Assume this is Greg's port, it used easymenu
3558 (easy-menu-remove outline-mode-menu-heading)
3559 (easy-menu-remove outline-mode-menu-show)
3560 (easy-menu-remove outline-mode-menu-hide))
3561 (define-key org-mode-map [menu-bar headings] 'undefined)
3562 (define-key org-mode-map [menu-bar hide] 'undefined)
3563 (define-key org-mode-map [menu-bar show] 'undefined))
3565 (org-load-modules-maybe)
3566 (easy-menu-add org-org-menu)
3567 (easy-menu-add org-tbl-menu)
3568 (org-install-agenda-files-menu)
3569 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3570 (org-add-to-invisibility-spec '(org-cwidth))
3571 (when (featurep 'xemacs)
3572 (org-set-local 'line-move-ignore-invisible t))
3573 (org-set-local 'outline-regexp org-outline-regexp)
3574 (org-set-local 'outline-level 'org-outline-level)
3575 (when (and org-ellipsis
3576 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3577 (fboundp 'make-glyph-code))
3578 (unless org-display-table
3579 (setq org-display-table (make-display-table)))
3580 (set-display-table-slot
3581 org-display-table 4
3582 (vconcat (mapcar
3583 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3584 org-ellipsis)))
3585 (if (stringp org-ellipsis) org-ellipsis "..."))))
3586 (setq buffer-display-table org-display-table))
3587 (org-set-regexps-and-options)
3588 (when (and org-tag-faces (not org-tags-special-faces-re))
3589 ;; tag faces set outside customize.... force initialization.
3590 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3591 ;; Calc embedded
3592 (org-set-local 'calc-embedded-open-mode "# ")
3593 (modify-syntax-entry ?# "<")
3594 (modify-syntax-entry ?@ "w")
3595 (if org-startup-truncated (setq truncate-lines t))
3596 (org-set-local 'font-lock-unfontify-region-function
3597 'org-unfontify-region)
3598 ;; Activate before-change-function
3599 (org-set-local 'org-table-may-need-update t)
3600 (org-add-hook 'before-change-functions 'org-before-change-function nil
3601 'local)
3602 ;; Check for running clock before killing a buffer
3603 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3604 ;; Paragraphs and auto-filling
3605 (org-set-autofill-regexps)
3606 (setq indent-line-function 'org-indent-line-function)
3607 (org-update-radio-target-regexp)
3608 ;; Make sure dependence stuff works reliably, even for users who set it
3609 ;; too late :-(
3610 (if org-enforce-todo-dependencies
3611 (add-hook 'org-blocker-hook
3612 'org-block-todo-from-children-or-siblings)
3613 (remove-hook 'org-blocker-hook
3614 'org-block-todo-from-children-or-siblings))
3615 (if org-enforce-todo-checkbox-dependencies
3616 (add-hook 'org-blocker-hook
3617 'org-block-todo-from-checkboxes)
3618 (remove-hook 'org-blocker-hook
3619 'org-block-todo-from-checkboxes))
3621 ;; Comment characters
3622 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3623 (org-set-local 'comment-padding " ")
3625 ;; Align options lines
3626 (org-set-local
3627 'align-mode-rules-list
3628 '((org-in-buffer-settings
3629 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3630 (modes . '(org-mode)))))
3632 ;; Imenu
3633 (org-set-local 'imenu-create-index-function
3634 'org-imenu-get-tree)
3636 ;; Make isearch reveal context
3637 (if (or (featurep 'xemacs)
3638 (not (boundp 'outline-isearch-open-invisible-function)))
3639 ;; Emacs 21 and XEmacs make use of the hook
3640 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3641 ;; Emacs 22 deals with this through a special variable
3642 (org-set-local 'outline-isearch-open-invisible-function
3643 (lambda (&rest ignore) (org-show-context 'isearch))))
3645 ;; If empty file that did not turn on org-mode automatically, make it to.
3646 (if (and org-insert-mode-line-in-empty-file
3647 (interactive-p)
3648 (= (point-min) (point-max)))
3649 (insert "# -*- mode: org -*-\n\n"))
3651 (unless org-inhibit-startup
3652 (when org-startup-align-all-tables
3653 (let ((bmp (buffer-modified-p)))
3654 (org-table-map-tables 'org-table-align)
3655 (set-buffer-modified-p bmp)))
3656 (org-set-startup-visibility)))
3658 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3660 (defun org-current-time ()
3661 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3662 (if (> (car org-time-stamp-rounding-minutes) 1)
3663 (let ((r (car org-time-stamp-rounding-minutes))
3664 (time (decode-time)))
3665 (apply 'encode-time
3666 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3667 (nthcdr 2 time))))
3668 (current-time)))
3670 ;;;; Font-Lock stuff, including the activators
3672 (defvar org-mouse-map (make-sparse-keymap))
3673 (org-defkey org-mouse-map
3674 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3675 (org-defkey org-mouse-map
3676 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3677 (when org-mouse-1-follows-link
3678 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3679 (when org-tab-follows-link
3680 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3681 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3682 (when org-return-follows-link
3683 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3684 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3686 (require 'font-lock)
3688 (defconst org-non-link-chars "]\t\n\r<>")
3689 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3690 "shell" "elisp"))
3691 (defvar org-link-types-re nil
3692 "Matches a link that has a url-like prefix like \"http:\"")
3693 (defvar org-link-re-with-space nil
3694 "Matches a link with spaces, optional angular brackets around it.")
3695 (defvar org-link-re-with-space2 nil
3696 "Matches a link with spaces, optional angular brackets around it.")
3697 (defvar org-link-re-with-space3 nil
3698 "Matches a link with spaces, only for internal part in bracket links.")
3699 (defvar org-angle-link-re nil
3700 "Matches link with angular brackets, spaces are allowed.")
3701 (defvar org-plain-link-re nil
3702 "Matches plain link, without spaces.")
3703 (defvar org-bracket-link-regexp nil
3704 "Matches a link in double brackets.")
3705 (defvar org-bracket-link-analytic-regexp nil
3706 "Regular expression used to analyze links.
3707 Here is what the match groups contain after a match:
3708 1: http:
3709 2: http
3710 3: path
3711 4: [desc]
3712 5: desc")
3713 (defvar org-bracket-link-analytic-regexp++ nil
3714 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3715 (defvar org-any-link-re nil
3716 "Regular expression matching any link.")
3718 (defun org-make-link-regexps ()
3719 "Update the link regular expressions.
3720 This should be called after the variable `org-link-types' has changed."
3721 (setq org-link-types-re
3722 (concat
3723 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3724 org-link-re-with-space
3725 (concat
3726 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3727 "\\([^" org-non-link-chars " ]"
3728 "[^" org-non-link-chars "]*"
3729 "[^" org-non-link-chars " ]\\)>?")
3730 org-link-re-with-space2
3731 (concat
3732 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3733 "\\([^" org-non-link-chars " ]"
3734 "[^\t\n\r]*"
3735 "[^" org-non-link-chars " ]\\)>?")
3736 org-link-re-with-space3
3737 (concat
3738 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3739 "\\([^" org-non-link-chars " ]"
3740 "[^\t\n\r]*\\)")
3741 org-angle-link-re
3742 (concat
3743 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3744 "\\([^" org-non-link-chars " ]"
3745 "[^" org-non-link-chars "]*"
3746 "\\)>")
3747 org-plain-link-re
3748 (concat
3749 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3750 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3751 org-bracket-link-regexp
3752 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3753 org-bracket-link-analytic-regexp
3754 (concat
3755 "\\[\\["
3756 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3757 "\\([^]]+\\)"
3758 "\\]"
3759 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3760 "\\]")
3761 org-bracket-link-analytic-regexp++
3762 (concat
3763 "\\[\\["
3764 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3765 "\\([^]]+\\)"
3766 "\\]"
3767 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3768 "\\]")
3769 org-any-link-re
3770 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3771 org-angle-link-re "\\)\\|\\("
3772 org-plain-link-re "\\)")))
3774 (org-make-link-regexps)
3776 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3777 "Regular expression for fast time stamp matching.")
3778 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3779 "Regular expression for fast time stamp matching.")
3780 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3781 "Regular expression matching time strings for analysis.
3782 This one does not require the space after the date, so it can be used
3783 on a string that terminates immediately after the date.")
3784 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3785 "Regular expression matching time strings for analysis.")
3786 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3787 "Regular expression matching time stamps, with groups.")
3788 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3789 "Regular expression matching time stamps (also [..]), with groups.")
3790 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3791 "Regular expression matching a time stamp range.")
3792 (defconst org-tr-regexp-both
3793 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3794 "Regular expression matching a time stamp range.")
3795 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3796 org-ts-regexp "\\)?")
3797 "Regular expression matching a time stamp or time stamp range.")
3798 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3799 org-ts-regexp-both "\\)?")
3800 "Regular expression matching a time stamp or time stamp range.
3801 The time stamps may be either active or inactive.")
3803 (defvar org-emph-face nil)
3805 (defun org-do-emphasis-faces (limit)
3806 "Run through the buffer and add overlays to links."
3807 (let (rtn)
3808 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3809 (if (not (= (char-after (match-beginning 3))
3810 (char-after (match-beginning 4))))
3811 (progn
3812 (setq rtn t)
3813 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3814 'face
3815 (nth 1 (assoc (match-string 3)
3816 org-emphasis-alist)))
3817 (add-text-properties (match-beginning 2) (match-end 2)
3818 '(font-lock-multiline t))
3819 (when org-hide-emphasis-markers
3820 (add-text-properties (match-end 4) (match-beginning 5)
3821 '(invisible org-link))
3822 (add-text-properties (match-beginning 3) (match-end 3)
3823 '(invisible org-link)))))
3824 (backward-char 1))
3825 rtn))
3827 (defun org-emphasize (&optional char)
3828 "Insert or change an emphasis, i.e. a font like bold or italic.
3829 If there is an active region, change that region to a new emphasis.
3830 If there is no region, just insert the marker characters and position
3831 the cursor between them.
3832 CHAR should be either the marker character, or the first character of the
3833 HTML tag associated with that emphasis. If CHAR is a space, the means
3834 to remove the emphasis of the selected region.
3835 If char is not given (for example in an interactive call) it
3836 will be prompted for."
3837 (interactive)
3838 (let ((eal org-emphasis-alist) e det
3839 (erc org-emphasis-regexp-components)
3840 (prompt "")
3841 (string "") beg end move tag c s)
3842 (if (org-region-active-p)
3843 (setq beg (region-beginning) end (region-end)
3844 string (buffer-substring beg end))
3845 (setq move t))
3847 (while (setq e (pop eal))
3848 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3849 c (aref tag 0))
3850 (push (cons c (string-to-char (car e))) det)
3851 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3852 (substring tag 1)))))
3853 (setq det (nreverse det))
3854 (unless char
3855 (message "%s" (concat "Emphasis marker or tag:" prompt))
3856 (setq char (read-char-exclusive)))
3857 (setq char (or (cdr (assoc char det)) char))
3858 (if (equal char ?\ )
3859 (setq s "" move nil)
3860 (unless (assoc (char-to-string char) org-emphasis-alist)
3861 (error "No such emphasis marker: \"%c\"" char))
3862 (setq s (char-to-string char)))
3863 (while (and (> (length string) 1)
3864 (equal (substring string 0 1) (substring string -1))
3865 (assoc (substring string 0 1) org-emphasis-alist))
3866 (setq string (substring string 1 -1)))
3867 (setq string (concat s string s))
3868 (if beg (delete-region beg end))
3869 (unless (or (bolp)
3870 (string-match (concat "[" (nth 0 erc) "\n]")
3871 (char-to-string (char-before (point)))))
3872 (insert " "))
3873 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3874 (char-to-string (char-after (point))))
3875 (insert " ") (backward-char 1))
3876 (insert string)
3877 (and move (backward-char 1))))
3879 (defconst org-nonsticky-props
3880 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3883 (defun org-activate-plain-links (limit)
3884 "Run through the buffer and add overlays to links."
3885 (catch 'exit
3886 (let (f)
3887 (while (re-search-forward org-plain-link-re limit t)
3888 (setq f (get-text-property (match-beginning 0) 'face))
3889 (if (or (eq f 'org-tag)
3890 (and (listp f) (memq 'org-tag f)))
3892 (add-text-properties (match-beginning 0) (match-end 0)
3893 (list 'mouse-face 'highlight
3894 'rear-nonsticky org-nonsticky-props
3895 'keymap org-mouse-map
3897 (throw 'exit t))))))
3899 (defun org-activate-code (limit)
3900 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3901 (progn
3902 (remove-text-properties (match-beginning 0) (match-end 0)
3903 '(display t invisible t intangible t))
3904 t)))
3906 (defun org-activate-angle-links (limit)
3907 "Run through the buffer and add overlays to links."
3908 (if (re-search-forward org-angle-link-re limit t)
3909 (progn
3910 (add-text-properties (match-beginning 0) (match-end 0)
3911 (list 'mouse-face 'highlight
3912 'rear-nonsticky org-nonsticky-props
3913 'keymap org-mouse-map
3915 t)))
3917 (defun org-activate-footnote-links (limit)
3918 "Run through the buffer and add overlays to links."
3919 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3920 limit t)
3921 (progn
3922 (add-text-properties (match-beginning 2) (match-end 2)
3923 (list 'mouse-face 'highlight
3924 'rear-nonsticky org-nonsticky-props
3925 'keymap org-mouse-map
3926 'help-echo
3927 (if (= (point-at-bol) (match-beginning 2))
3928 "Footnote definition"
3929 "Footnote reference")
3931 t)))
3933 (defun org-activate-bracket-links (limit)
3934 "Run through the buffer and add overlays to bracketed links."
3935 (if (re-search-forward org-bracket-link-regexp limit t)
3936 (let* ((help (concat "LINK: "
3937 (org-match-string-no-properties 1)))
3938 ;; FIXME: above we should remove the escapes.
3939 ;; but that requires another match, protecting match data,
3940 ;; a lot of overhead for font-lock.
3941 (ip (org-maybe-intangible
3942 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3943 'keymap org-mouse-map 'mouse-face 'highlight
3944 'font-lock-multiline t 'help-echo help)))
3945 (vp (list 'rear-nonsticky org-nonsticky-props
3946 'keymap org-mouse-map 'mouse-face 'highlight
3947 ' font-lock-multiline t 'help-echo help)))
3948 ;; We need to remove the invisible property here. Table narrowing
3949 ;; may have made some of this invisible.
3950 (remove-text-properties (match-beginning 0) (match-end 0)
3951 '(invisible nil))
3952 (if (match-end 3)
3953 (progn
3954 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3955 (add-text-properties (match-beginning 3) (match-end 3) vp)
3956 (add-text-properties (match-end 3) (match-end 0) ip))
3957 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3958 (add-text-properties (match-beginning 1) (match-end 1) vp)
3959 (add-text-properties (match-end 1) (match-end 0) ip))
3960 t)))
3962 (defun org-activate-dates (limit)
3963 "Run through the buffer and add overlays to dates."
3964 (if (re-search-forward org-tsr-regexp-both limit t)
3965 (progn
3966 (add-text-properties (match-beginning 0) (match-end 0)
3967 (list 'mouse-face 'highlight
3968 'rear-nonsticky org-nonsticky-props
3969 'keymap org-mouse-map))
3970 (when org-display-custom-times
3971 (if (match-end 3)
3972 (org-display-custom-time (match-beginning 3) (match-end 3)))
3973 (org-display-custom-time (match-beginning 1) (match-end 1)))
3974 t)))
3976 (defvar org-target-link-regexp nil
3977 "Regular expression matching radio targets in plain text.")
3978 (make-variable-buffer-local 'org-target-link-regexp)
3979 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3980 "Regular expression matching a link target.")
3981 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3982 "Regular expression matching a radio target.")
3983 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3984 "Regular expression matching any target.")
3986 (defun org-activate-target-links (limit)
3987 "Run through the buffer and add overlays to target matches."
3988 (when org-target-link-regexp
3989 (let ((case-fold-search t))
3990 (if (re-search-forward org-target-link-regexp limit t)
3991 (progn
3992 (add-text-properties (match-beginning 0) (match-end 0)
3993 (list 'mouse-face 'highlight
3994 'rear-nonsticky org-nonsticky-props
3995 'keymap org-mouse-map
3996 'help-echo "Radio target link"
3997 'org-linked-text t))
3998 t)))))
4000 (defun org-update-radio-target-regexp ()
4001 "Find all radio targets in this file and update the regular expression."
4002 (interactive)
4003 (when (memq 'radio org-activate-links)
4004 (setq org-target-link-regexp
4005 (org-make-target-link-regexp (org-all-targets 'radio)))
4006 (org-restart-font-lock)))
4008 (defun org-hide-wide-columns (limit)
4009 (let (s e)
4010 (setq s (text-property-any (point) (or limit (point-max))
4011 'org-cwidth t))
4012 (when s
4013 (setq e (next-single-property-change s 'org-cwidth))
4014 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4015 (goto-char e)
4016 t)))
4018 (defvar org-latex-and-specials-regexp nil
4019 "Regular expression for highlighting export special stuff.")
4020 (defvar org-match-substring-regexp)
4021 (defvar org-match-substring-with-braces-regexp)
4022 (defvar org-export-html-special-string-regexps)
4024 (defun org-compute-latex-and-specials-regexp ()
4025 "Compute regular expression for stuff treated specially by exporters."
4026 (if (not org-highlight-latex-fragments-and-specials)
4027 (org-set-local 'org-latex-and-specials-regexp nil)
4028 (require 'org-exp)
4029 (let*
4030 ((matchers (plist-get org-format-latex-options :matchers))
4031 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4032 org-latex-regexps)))
4033 (options (org-combine-plists (org-default-export-plist)
4034 (org-infile-export-plist)))
4035 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4036 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4037 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4038 (org-export-html-expand (plist-get options :expand-quoted-html))
4039 (org-export-with-special-strings (plist-get options :special-strings))
4040 (re-sub
4041 (cond
4042 ((equal org-export-with-sub-superscripts '{})
4043 (list org-match-substring-with-braces-regexp))
4044 (org-export-with-sub-superscripts
4045 (list org-match-substring-regexp))
4046 (t nil)))
4047 (re-latex
4048 (if org-export-with-LaTeX-fragments
4049 (mapcar (lambda (x) (nth 1 x)) latexs)))
4050 (re-macros
4051 (if org-export-with-TeX-macros
4052 (list (concat "\\\\"
4053 (regexp-opt
4054 (append (mapcar 'car org-html-entities)
4055 (if (boundp 'org-latex-entities)
4056 org-latex-entities nil))
4057 'words))) ; FIXME
4059 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4060 (re-special (if org-export-with-special-strings
4061 (mapcar (lambda (x) (car x))
4062 org-export-html-special-string-regexps)))
4063 (re-rest
4064 (delq nil
4065 (list
4066 (if org-export-html-expand "@<[^>\n]+>")
4067 ))))
4068 (org-set-local
4069 'org-latex-and-specials-regexp
4070 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4071 re-rest) "\\|")))))
4073 (defun org-do-latex-and-special-faces (limit)
4074 "Run through the buffer and add overlays to links."
4075 (when org-latex-and-specials-regexp
4076 (let (rtn d)
4077 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4078 limit t))
4079 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4080 'face))
4081 '(org-code org-verbatim underline)))
4082 (progn
4083 (setq rtn t
4084 d (cond ((member (char-after (1+ (match-beginning 0)))
4085 '(?_ ?^)) 1)
4086 (t 0)))
4087 (font-lock-prepend-text-property
4088 (+ d (match-beginning 0)) (match-end 0)
4089 'face 'org-latex-and-export-specials)
4090 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4091 '(font-lock-multiline t)))))
4092 rtn)))
4094 (defun org-restart-font-lock ()
4095 "Restart font-lock-mode, to force refontification."
4096 (when (and (boundp 'font-lock-mode) font-lock-mode)
4097 (font-lock-mode -1)
4098 (font-lock-mode 1)))
4100 (defun org-all-targets (&optional radio)
4101 "Return a list of all targets in this file.
4102 With optional argument RADIO, only find radio targets."
4103 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4104 rtn)
4105 (save-excursion
4106 (goto-char (point-min))
4107 (while (re-search-forward re nil t)
4108 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4109 rtn)))
4111 (defun org-make-target-link-regexp (targets)
4112 "Make regular expression matching all strings in TARGETS.
4113 The regular expression finds the targets also if there is a line break
4114 between words."
4115 (and targets
4116 (concat
4117 "\\<\\("
4118 (mapconcat
4119 (lambda (x)
4120 (while (string-match " +" x)
4121 (setq x (replace-match "\\s-+" t t x)))
4123 targets
4124 "\\|")
4125 "\\)\\>")))
4127 (defun org-activate-tags (limit)
4128 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4129 (progn
4130 (add-text-properties (match-beginning 1) (match-end 1)
4131 (list 'mouse-face 'highlight
4132 'rear-nonsticky org-nonsticky-props
4133 'keymap org-mouse-map))
4134 t)))
4136 (defun org-outline-level ()
4137 (save-excursion
4138 (looking-at outline-regexp)
4139 (if (match-beginning 1)
4140 (+ (org-get-string-indentation (match-string 1)) 1000)
4141 (1- (- (match-end 0) (match-beginning 0))))))
4143 (defvar org-font-lock-keywords nil)
4145 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4146 "Regular expression matching a property line.")
4148 (defvar org-font-lock-hook nil
4149 "Functions to be called for special font lock stuff.")
4151 (defun org-font-lock-hook (limit)
4152 (run-hook-with-args 'org-font-lock-hook limit))
4154 (defun org-set-font-lock-defaults ()
4155 (let* ((em org-fontify-emphasized-text)
4156 (lk org-activate-links)
4157 (org-font-lock-extra-keywords
4158 (list
4159 ;; Call the hook
4160 '(org-font-lock-hook)
4161 ;; Headlines
4162 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4163 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4164 ;; Table lines
4165 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4166 (1 'org-table t))
4167 ;; Table internals
4168 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4169 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4170 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4171 ;; Drawers
4172 (list org-drawer-regexp '(0 'org-special-keyword t))
4173 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4174 ;; Properties
4175 (list org-property-re
4176 '(1 'org-special-keyword t)
4177 '(3 'org-property-value t))
4178 (if org-format-transports-properties-p
4179 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4180 ;; Links
4181 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4182 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4183 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4184 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4185 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4186 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4187 (if (memq 'footnote lk) '(org-activate-footnote-links
4188 (2 'org-footnote t)))
4189 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4190 '(org-hide-wide-columns (0 nil append))
4191 ;; TODO lines
4192 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4193 '(1 (org-get-todo-face 1) t))
4194 ;; DONE
4195 (if org-fontify-done-headline
4196 (list (concat "^[*]+ +\\<\\("
4197 (mapconcat 'regexp-quote org-done-keywords "\\|")
4198 "\\)\\(.*\\)")
4199 '(2 'org-headline-done t))
4200 nil)
4201 ;; Priorities
4202 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4203 ;; Tags
4204 '(org-font-lock-add-tag-faces)
4205 ;; Special keywords
4206 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4207 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4208 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4209 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4210 ;; Emphasis
4211 (if em
4212 (if (featurep 'xemacs)
4213 '(org-do-emphasis-faces (0 nil append))
4214 '(org-do-emphasis-faces)))
4215 ;; Checkboxes
4216 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4217 2 'bold prepend)
4218 (if org-provide-checkbox-statistics
4219 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4220 (0 (org-get-checkbox-statistics-face) t)))
4221 ;; Description list items
4222 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4223 2 'bold prepend)
4224 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4225 '(1 'org-archived prepend))
4226 ;; Specials
4227 '(org-do-latex-and-special-faces)
4228 ;; Code
4229 '(org-activate-code (1 'org-code t))
4230 ;; COMMENT
4231 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4232 "\\|" org-quote-string "\\)\\>")
4233 '(1 'org-special-keyword t))
4234 '("^#.*" (0 'font-lock-comment-face t))
4236 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4237 ;; Now set the full font-lock-keywords
4238 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4239 (org-set-local 'font-lock-defaults
4240 '(org-font-lock-keywords t nil nil backward-paragraph))
4241 (kill-local-variable 'font-lock-keywords) nil))
4243 (defvar org-m nil)
4244 (defvar org-l nil)
4245 (defvar org-f nil)
4246 (defun org-get-level-face (n)
4247 "Get the right face for match N in font-lock matching of headlines."
4248 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4249 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4250 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4251 (cond
4252 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4253 ((eq n 2) org-f)
4254 (t (if org-level-color-stars-only nil org-f))))
4256 (defun org-get-todo-face (kwd)
4257 "Get the right face for a TODO keyword KWD.
4258 If KWD is a number, get the corresponding match group."
4259 (if (numberp kwd) (setq kwd (match-string kwd)))
4260 (or (cdr (assoc kwd org-todo-keyword-faces))
4261 (and (member kwd org-done-keywords) 'org-done)
4262 'org-todo))
4264 (defun org-font-lock-add-tag-faces (limit)
4265 "Add the special tag faces."
4266 (when (and org-tag-faces org-tags-special-faces-re)
4267 (while (re-search-forward org-tags-special-faces-re limit t)
4268 (add-text-properties (match-beginning 1) (match-end 1)
4269 (list 'face (org-get-tag-face 1)
4270 'font-lock-fontified t))
4271 (backward-char 1))))
4273 (defun org-get-tag-face (kwd)
4274 "Get the right face for a TODO keyword KWD.
4275 If KWD is a number, get the corresponding match group."
4276 (if (numberp kwd) (setq kwd (match-string kwd)))
4277 (or (cdr (assoc kwd org-tag-faces))
4278 'org-tag))
4280 (defun org-unfontify-region (beg end &optional maybe_loudly)
4281 "Remove fontification and activation overlays from links."
4282 (font-lock-default-unfontify-region beg end)
4283 (let* ((buffer-undo-list t)
4284 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4285 (inhibit-modification-hooks t)
4286 deactivate-mark buffer-file-name buffer-file-truename)
4287 (remove-text-properties beg end
4288 '(mouse-face t keymap t org-linked-text t
4289 invisible t intangible t))))
4291 ;;;; Visibility cycling, including org-goto and indirect buffer
4293 ;;; Cycling
4295 (defvar org-cycle-global-status nil)
4296 (make-variable-buffer-local 'org-cycle-global-status)
4297 (defvar org-cycle-subtree-status nil)
4298 (make-variable-buffer-local 'org-cycle-subtree-status)
4300 ;;;###autoload
4301 (defun org-cycle (&optional arg)
4302 "Visibility cycling for Org-mode.
4304 - When this function is called with a prefix argument, rotate the entire
4305 buffer through 3 states (global cycling)
4306 1. OVERVIEW: Show only top-level headlines.
4307 2. CONTENTS: Show all headlines of all levels, but no body text.
4308 3. SHOW ALL: Show everything.
4309 When called with two C-u C-u prefixes, switch to the startup visibility,
4310 determined by the variable `org-startup-folded', and by any VISIBILITY
4311 properties in the buffer.
4312 When called with three C-u C-u C-u prefixed, show the entire buffer,
4313 including drawers.
4315 - When point is at the beginning of a headline, rotate the subtree started
4316 by this line through 3 different states (local cycling)
4317 1. FOLDED: Only the main headline is shown.
4318 2. CHILDREN: The main headline and the direct children are shown.
4319 From this state, you can move to one of the children
4320 and zoom in further.
4321 3. SUBTREE: Show the entire subtree, including body text.
4323 - When there is a numeric prefix, go up to a heading with level ARG, do
4324 a `show-subtree' and return to the previous cursor position. If ARG
4325 is negative, go up that many levels.
4327 - When point is not at the beginning of a headline, execute the global
4328 binding for TAB, which is re-indenting the line. See the option
4329 `org-cycle-emulate-tab' for details.
4331 - Special case: if point is at the beginning of the buffer and there is
4332 no headline in line 1, this function will act as if called with prefix arg.
4333 But only if also the variable `org-cycle-global-at-bob' is t."
4334 (interactive "P")
4335 (org-load-modules-maybe)
4336 (let* ((outline-regexp
4337 (if (and (org-mode-p) org-cycle-include-plain-lists)
4338 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4339 outline-regexp))
4340 (bob-special (and org-cycle-global-at-bob (bobp)
4341 (not (looking-at outline-regexp))))
4342 (org-cycle-hook
4343 (if bob-special
4344 (delq 'org-optimize-window-after-visibility-change
4345 (copy-sequence org-cycle-hook))
4346 org-cycle-hook))
4347 (pos (point)))
4349 (if (or bob-special (equal arg '(4)))
4350 ;; special case: use global cycling
4351 (setq arg t))
4353 (cond
4355 ((equal arg '(16))
4356 (org-set-startup-visibility)
4357 (message "Startup visibility, plus VISIBILITY properties"))
4359 ((equal arg '(64))
4360 (show-all)
4361 (message "Entire buffer visible, including drawers"))
4363 ((org-at-table-p 'any)
4364 ;; Enter the table or move to the next field in the table
4365 (or (org-table-recognize-table.el)
4366 (progn
4367 (if arg (org-table-edit-field t)
4368 (org-table-justify-field-maybe)
4369 (call-interactively 'org-table-next-field)))))
4371 ((eq arg t) ;; Global cycling
4373 (cond
4374 ((and (eq last-command this-command)
4375 (eq org-cycle-global-status 'overview))
4376 ;; We just created the overview - now do table of contents
4377 ;; This can be slow in very large buffers, so indicate action
4378 (message "CONTENTS...")
4379 (org-content)
4380 (message "CONTENTS...done")
4381 (setq org-cycle-global-status 'contents)
4382 (run-hook-with-args 'org-cycle-hook 'contents))
4384 ((and (eq last-command this-command)
4385 (eq org-cycle-global-status 'contents))
4386 ;; We just showed the table of contents - now show everything
4387 (show-all)
4388 (message "SHOW ALL")
4389 (setq org-cycle-global-status 'all)
4390 (run-hook-with-args 'org-cycle-hook 'all))
4393 ;; Default action: go to overview
4394 (org-overview)
4395 (message "OVERVIEW")
4396 (setq org-cycle-global-status 'overview)
4397 (run-hook-with-args 'org-cycle-hook 'overview))))
4399 ((and org-drawers org-drawer-regexp
4400 (save-excursion
4401 (beginning-of-line 1)
4402 (looking-at org-drawer-regexp)))
4403 ;; Toggle block visibility
4404 (org-flag-drawer
4405 (not (get-char-property (match-end 0) 'invisible))))
4407 ((integerp arg)
4408 ;; Show-subtree, ARG levels up from here.
4409 (save-excursion
4410 (org-back-to-heading)
4411 (outline-up-heading (if (< arg 0) (- arg)
4412 (- (funcall outline-level) arg)))
4413 (org-show-subtree)))
4415 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4416 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4417 ;; At a heading: rotate between three different views
4418 (org-back-to-heading)
4419 (let ((goal-column 0) eoh eol eos)
4420 ;; First, some boundaries
4421 (save-excursion
4422 (org-back-to-heading)
4423 (save-excursion
4424 (beginning-of-line 2)
4425 (while (and (not (eobp)) ;; this is like `next-line'
4426 (get-char-property (1- (point)) 'invisible))
4427 (beginning-of-line 2)) (setq eol (point)))
4428 (outline-end-of-heading) (setq eoh (point))
4429 (org-end-of-subtree t)
4430 (unless (eobp)
4431 (skip-chars-forward " \t\n")
4432 (beginning-of-line 1) ; in case this is an item
4434 (setq eos (1- (point))))
4435 ;; Find out what to do next and set `this-command'
4436 (cond
4437 ((= eos eoh)
4438 ;; Nothing is hidden behind this heading
4439 (message "EMPTY ENTRY")
4440 (setq org-cycle-subtree-status nil)
4441 (save-excursion
4442 (goto-char eos)
4443 (outline-next-heading)
4444 (if (org-invisible-p) (org-flag-heading nil))))
4445 ((or (>= eol eos)
4446 (not (string-match "\\S-" (buffer-substring eol eos))))
4447 ;; Entire subtree is hidden in one line: open it
4448 (org-show-entry)
4449 (show-children)
4450 (message "CHILDREN")
4451 (save-excursion
4452 (goto-char eos)
4453 (outline-next-heading)
4454 (if (org-invisible-p) (org-flag-heading nil)))
4455 (setq org-cycle-subtree-status 'children)
4456 (run-hook-with-args 'org-cycle-hook 'children))
4457 ((and (eq last-command this-command)
4458 (eq org-cycle-subtree-status 'children))
4459 ;; We just showed the children, now show everything.
4460 (org-show-subtree)
4461 (message "SUBTREE")
4462 (setq org-cycle-subtree-status 'subtree)
4463 (run-hook-with-args 'org-cycle-hook 'subtree))
4465 ;; Default action: hide the subtree.
4466 (hide-subtree)
4467 (message "FOLDED")
4468 (setq org-cycle-subtree-status 'folded)
4469 (run-hook-with-args 'org-cycle-hook 'folded)))))
4471 ;; TAB emulation and template completion
4472 (buffer-read-only (org-back-to-heading))
4474 ((org-try-structure-completion))
4476 ((org-try-cdlatex-tab))
4478 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4479 (or (not (bolp))
4480 (not (looking-at outline-regexp))))
4481 (call-interactively (global-key-binding "\t")))
4483 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4484 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4485 (or (and (eq org-cycle-emulate-tab 'white)
4486 (= (match-end 0) (point-at-eol)))
4487 (and (eq org-cycle-emulate-tab 'whitestart)
4488 (>= (match-end 0) pos))))
4490 (eq org-cycle-emulate-tab t))
4491 (call-interactively (global-key-binding "\t")))
4493 (t (save-excursion
4494 (org-back-to-heading)
4495 (org-cycle))))))
4497 ;;;###autoload
4498 (defun org-global-cycle (&optional arg)
4499 "Cycle the global visibility. For details see `org-cycle'.
4500 With C-u prefix arg, switch to startup visibility.
4501 With a numeric prefix, show all headlines up to that level."
4502 (interactive "P")
4503 (let ((org-cycle-include-plain-lists
4504 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4505 (cond
4506 ((integerp arg)
4507 (show-all)
4508 (hide-sublevels arg)
4509 (setq org-cycle-global-status 'contents))
4510 ((equal arg '(4))
4511 (org-set-startup-visibility)
4512 (message "Startup visibility, plus VISIBILITY properties."))
4514 (org-cycle '(4))))))
4516 (defun org-set-startup-visibility ()
4517 "Set the visibility required by startup options and properties."
4518 (cond
4519 ((eq org-startup-folded t)
4520 (org-cycle '(4)))
4521 ((eq org-startup-folded 'content)
4522 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4523 (org-cycle '(4)) (org-cycle '(4)))))
4524 (org-set-visibility-according-to-property 'no-cleanup)
4525 (org-cycle-hide-archived-subtrees 'all)
4526 (org-cycle-hide-drawers 'all)
4527 (org-cycle-show-empty-lines 'all))
4529 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4530 "Switch subtree visibilities according to :VISIBILITY: property."
4531 (interactive)
4532 (let (org-show-entry-below state)
4533 (save-excursion
4534 (goto-char (point-min))
4535 (while (re-search-forward
4536 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4537 nil t)
4538 (setq state (match-string 1))
4539 (save-excursion
4540 (org-back-to-heading t)
4541 (hide-subtree)
4542 (org-reveal)
4543 (cond
4544 ((equal state '("fold" "folded"))
4545 (hide-subtree))
4546 ((equal state "children")
4547 (org-show-hidden-entry)
4548 (show-children))
4549 ((equal state "content")
4550 (save-excursion
4551 (save-restriction
4552 (org-narrow-to-subtree)
4553 (org-content))))
4554 ((member state '("all" "showall"))
4555 (show-subtree)))))
4556 (unless no-cleanup
4557 (org-cycle-hide-archived-subtrees 'all)
4558 (org-cycle-hide-drawers 'all)
4559 (org-cycle-show-empty-lines 'all)))))
4561 (defun org-overview ()
4562 "Switch to overview mode, showing only top-level headlines.
4563 Really, this shows all headlines with level equal or greater than the level
4564 of the first headline in the buffer. This is important, because if the
4565 first headline is not level one, then (hide-sublevels 1) gives confusing
4566 results."
4567 (interactive)
4568 (let ((level (save-excursion
4569 (goto-char (point-min))
4570 (if (re-search-forward (concat "^" outline-regexp) nil t)
4571 (progn
4572 (goto-char (match-beginning 0))
4573 (funcall outline-level))))))
4574 (and level (hide-sublevels level))))
4576 (defun org-content (&optional arg)
4577 "Show all headlines in the buffer, like a table of contents.
4578 With numerical argument N, show content up to level N."
4579 (interactive "P")
4580 (save-excursion
4581 ;; Visit all headings and show their offspring
4582 (and (integerp arg) (org-overview))
4583 (goto-char (point-max))
4584 (catch 'exit
4585 (while (and (progn (condition-case nil
4586 (outline-previous-visible-heading 1)
4587 (error (goto-char (point-min))))
4589 (looking-at outline-regexp))
4590 (if (integerp arg)
4591 (show-children (1- arg))
4592 (show-branches))
4593 (if (bobp) (throw 'exit nil))))))
4596 (defun org-optimize-window-after-visibility-change (state)
4597 "Adjust the window after a change in outline visibility.
4598 This function is the default value of the hook `org-cycle-hook'."
4599 (when (get-buffer-window (current-buffer))
4600 (cond
4601 ; ((eq state 'overview) (org-first-headline-recenter 1))
4602 ; ((eq state 'overview) (org-beginning-of-line))
4603 ((eq state 'content) nil)
4604 ((eq state 'all) nil)
4605 ((eq state 'folded) nil)
4606 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4607 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4609 (defun org-compact-display-after-subtree-move ()
4610 "Show a compacter version of the tree of the entry's parent."
4611 (save-excursion
4612 (if (org-up-heading-safe)
4613 (progn
4614 (hide-subtree)
4615 (show-entry)
4616 (show-children)
4617 (org-cycle-show-empty-lines 'children)
4618 (org-cycle-hide-drawers 'children))
4619 (org-overview))))
4621 (defun org-cycle-show-empty-lines (state)
4622 "Show empty lines above all visible headlines.
4623 The region to be covered depends on STATE when called through
4624 `org-cycle-hook'. Lisp program can use t for STATE to get the
4625 entire buffer covered. Note that an empty line is only shown if there
4626 are at least `org-cycle-separator-lines' empty lines before the headline."
4627 (when (> org-cycle-separator-lines 0)
4628 (save-excursion
4629 (let* ((n org-cycle-separator-lines)
4630 (re (cond
4631 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4632 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4633 (t (let ((ns (number-to-string (- n 2))))
4634 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4635 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4636 beg end)
4637 (cond
4638 ((memq state '(overview contents t))
4639 (setq beg (point-min) end (point-max)))
4640 ((memq state '(children folded))
4641 (setq beg (point) end (progn (org-end-of-subtree t t)
4642 (beginning-of-line 2)
4643 (point)))))
4644 (when beg
4645 (goto-char beg)
4646 (while (re-search-forward re end t)
4647 (if (not (get-char-property (match-end 1) 'invisible))
4648 (outline-flag-region
4649 (match-beginning 1) (match-end 1) nil)))))))
4650 ;; Never hide empty lines at the end of the file.
4651 (save-excursion
4652 (goto-char (point-max))
4653 (outline-previous-heading)
4654 (outline-end-of-heading)
4655 (if (and (looking-at "[ \t\n]+")
4656 (= (match-end 0) (point-max)))
4657 (outline-flag-region (point) (match-end 0) nil))))
4659 (defun org-show-empty-lines-in-parent ()
4660 "Move to the parent and re-show empty lines before visible headlines."
4661 (save-excursion
4662 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4663 (org-cycle-show-empty-lines context))))
4665 (defun org-cycle-hide-drawers (state)
4666 "Re-hide all drawers after a visibility state change."
4667 (when (and (org-mode-p)
4668 (not (memq state '(overview folded))))
4669 (save-excursion
4670 (let* ((globalp (memq state '(contents all)))
4671 (beg (if globalp (point-min) (point)))
4672 (end (if globalp (point-max) (org-end-of-subtree t))))
4673 (goto-char beg)
4674 (while (re-search-forward org-drawer-regexp end t)
4675 (org-flag-drawer t))))))
4677 (defun org-flag-drawer (flag)
4678 (save-excursion
4679 (beginning-of-line 1)
4680 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4681 (let ((b (match-end 0))
4682 (outline-regexp org-outline-regexp))
4683 (if (re-search-forward
4684 "^[ \t]*:END:"
4685 (save-excursion (outline-next-heading) (point)) t)
4686 (outline-flag-region b (point-at-eol) flag)
4687 (error ":END: line missing"))))))
4689 (defun org-subtree-end-visible-p ()
4690 "Is the end of the current subtree visible?"
4691 (pos-visible-in-window-p
4692 (save-excursion (org-end-of-subtree t) (point))))
4694 (defun org-first-headline-recenter (&optional N)
4695 "Move cursor to the first headline and recenter the headline.
4696 Optional argument N means, put the headline into the Nth line of the window."
4697 (goto-char (point-min))
4698 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4699 (beginning-of-line)
4700 (recenter (prefix-numeric-value N))))
4702 ;;; Org-goto
4704 (defvar org-goto-window-configuration nil)
4705 (defvar org-goto-marker nil)
4706 (defvar org-goto-map
4707 (let ((map (make-sparse-keymap)))
4708 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4709 (while (setq cmd (pop cmds))
4710 (substitute-key-definition cmd cmd map global-map)))
4711 (suppress-keymap map)
4712 (org-defkey map "\C-m" 'org-goto-ret)
4713 (org-defkey map [(return)] 'org-goto-ret)
4714 (org-defkey map [(left)] 'org-goto-left)
4715 (org-defkey map [(right)] 'org-goto-right)
4716 (org-defkey map [(control ?g)] 'org-goto-quit)
4717 (org-defkey map "\C-i" 'org-cycle)
4718 (org-defkey map [(tab)] 'org-cycle)
4719 (org-defkey map [(down)] 'outline-next-visible-heading)
4720 (org-defkey map [(up)] 'outline-previous-visible-heading)
4721 (if org-goto-auto-isearch
4722 (if (fboundp 'define-key-after)
4723 (define-key-after map [t] 'org-goto-local-auto-isearch)
4724 nil)
4725 (org-defkey map "q" 'org-goto-quit)
4726 (org-defkey map "n" 'outline-next-visible-heading)
4727 (org-defkey map "p" 'outline-previous-visible-heading)
4728 (org-defkey map "f" 'outline-forward-same-level)
4729 (org-defkey map "b" 'outline-backward-same-level)
4730 (org-defkey map "u" 'outline-up-heading))
4731 (org-defkey map "/" 'org-occur)
4732 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4733 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4734 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4735 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4736 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4737 map))
4739 (defconst org-goto-help
4740 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4741 RET=jump to location [Q]uit and return to previous location
4742 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4744 (defvar org-goto-start-pos) ; dynamically scoped parameter
4746 ;; FIXME: Docstring doe not mention both interfaces
4747 (defun org-goto (&optional alternative-interface)
4748 "Look up a different location in the current file, keeping current visibility.
4750 When you want look-up or go to a different location in a document, the
4751 fastest way is often to fold the entire buffer and then dive into the tree.
4752 This method has the disadvantage, that the previous location will be folded,
4753 which may not be what you want.
4755 This command works around this by showing a copy of the current buffer
4756 in an indirect buffer, in overview mode. You can dive into the tree in
4757 that copy, use org-occur and incremental search to find a location.
4758 When pressing RET or `Q', the command returns to the original buffer in
4759 which the visibility is still unchanged. After RET is will also jump to
4760 the location selected in the indirect buffer and expose the
4761 the headline hierarchy above."
4762 (interactive "P")
4763 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4764 (org-refile-use-outline-path t)
4765 (interface
4766 (if (not alternative-interface)
4767 org-goto-interface
4768 (if (eq org-goto-interface 'outline)
4769 'outline-path-completion
4770 'outline)))
4771 (org-goto-start-pos (point))
4772 (selected-point
4773 (if (eq interface 'outline)
4774 (car (org-get-location (current-buffer) org-goto-help))
4775 (nth 3 (org-refile-get-location "Goto: ")))))
4776 (if selected-point
4777 (progn
4778 (org-mark-ring-push org-goto-start-pos)
4779 (goto-char selected-point)
4780 (if (or (org-invisible-p) (org-invisible-p2))
4781 (org-show-context 'org-goto)))
4782 (message "Quit"))))
4784 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4785 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4786 (defvar org-goto-local-auto-isearch-map) ; defined below
4788 (defun org-get-location (buf help)
4789 "Let the user select a location in the Org-mode buffer BUF.
4790 This function uses a recursive edit. It returns the selected position
4791 or nil."
4792 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4793 (isearch-hide-immediately nil)
4794 (isearch-search-fun-function
4795 (lambda () 'org-goto-local-search-headings))
4796 (org-goto-selected-point org-goto-exit-command))
4797 (save-excursion
4798 (save-window-excursion
4799 (delete-other-windows)
4800 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4801 (switch-to-buffer
4802 (condition-case nil
4803 (make-indirect-buffer (current-buffer) "*org-goto*")
4804 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4805 (with-output-to-temp-buffer "*Help*"
4806 (princ help))
4807 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4808 (setq buffer-read-only nil)
4809 (let ((org-startup-truncated t)
4810 (org-startup-folded nil)
4811 (org-startup-align-all-tables nil))
4812 (org-mode)
4813 (org-overview))
4814 (setq buffer-read-only t)
4815 (if (and (boundp 'org-goto-start-pos)
4816 (integer-or-marker-p org-goto-start-pos))
4817 (let ((org-show-hierarchy-above t)
4818 (org-show-siblings t)
4819 (org-show-following-heading t))
4820 (goto-char org-goto-start-pos)
4821 (and (org-invisible-p) (org-show-context)))
4822 (goto-char (point-min)))
4823 (org-beginning-of-line)
4824 (message "Select location and press RET")
4825 (use-local-map org-goto-map)
4826 (recursive-edit)
4828 (kill-buffer "*org-goto*")
4829 (cons org-goto-selected-point org-goto-exit-command)))
4831 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4832 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4833 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4834 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4836 (defun org-goto-local-search-headings (string bound noerror)
4837 "Search and make sure that any matches are in headlines."
4838 (catch 'return
4839 (while (if isearch-forward
4840 (search-forward string bound noerror)
4841 (search-backward string bound noerror))
4842 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4843 (and (member :headline context)
4844 (not (member :tags context))))
4845 (throw 'return (point))))))
4847 (defun org-goto-local-auto-isearch ()
4848 "Start isearch."
4849 (interactive)
4850 (goto-char (point-min))
4851 (let ((keys (this-command-keys)))
4852 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4853 (isearch-mode t)
4854 (isearch-process-search-char (string-to-char keys)))))
4856 (defun org-goto-ret (&optional arg)
4857 "Finish `org-goto' by going to the new location."
4858 (interactive "P")
4859 (setq org-goto-selected-point (point)
4860 org-goto-exit-command 'return)
4861 (throw 'exit nil))
4863 (defun org-goto-left ()
4864 "Finish `org-goto' by going to the new location."
4865 (interactive)
4866 (if (org-on-heading-p)
4867 (progn
4868 (beginning-of-line 1)
4869 (setq org-goto-selected-point (point)
4870 org-goto-exit-command 'left)
4871 (throw 'exit nil))
4872 (error "Not on a heading")))
4874 (defun org-goto-right ()
4875 "Finish `org-goto' by going to the new location."
4876 (interactive)
4877 (if (org-on-heading-p)
4878 (progn
4879 (setq org-goto-selected-point (point)
4880 org-goto-exit-command 'right)
4881 (throw 'exit nil))
4882 (error "Not on a heading")))
4884 (defun org-goto-quit ()
4885 "Finish `org-goto' without cursor motion."
4886 (interactive)
4887 (setq org-goto-selected-point nil)
4888 (setq org-goto-exit-command 'quit)
4889 (throw 'exit nil))
4891 ;;; Indirect buffer display of subtrees
4893 (defvar org-indirect-dedicated-frame nil
4894 "This is the frame being used for indirect tree display.")
4895 (defvar org-last-indirect-buffer nil)
4897 (defun org-tree-to-indirect-buffer (&optional arg)
4898 "Create indirect buffer and narrow it to current subtree.
4899 With numerical prefix ARG, go up to this level and then take that tree.
4900 If ARG is negative, go up that many levels.
4901 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4902 indirect buffer previously made with this command, to avoid proliferation of
4903 indirect buffers. However, when you call the command with a `C-u' prefix, or
4904 when `org-indirect-buffer-display' is `new-frame', the last buffer
4905 is kept so that you can work with several indirect buffers at the same time.
4906 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4907 requests that a new frame be made for the new buffer, so that the dedicated
4908 frame is not changed."
4909 (interactive "P")
4910 (let ((cbuf (current-buffer))
4911 (cwin (selected-window))
4912 (pos (point))
4913 beg end level heading ibuf)
4914 (save-excursion
4915 (org-back-to-heading t)
4916 (when (numberp arg)
4917 (setq level (org-outline-level))
4918 (if (< arg 0) (setq arg (+ level arg)))
4919 (while (> (setq level (org-outline-level)) arg)
4920 (outline-up-heading 1 t)))
4921 (setq beg (point)
4922 heading (org-get-heading))
4923 (org-end-of-subtree t) (setq end (point)))
4924 (if (and (buffer-live-p org-last-indirect-buffer)
4925 (not (eq org-indirect-buffer-display 'new-frame))
4926 (not arg))
4927 (kill-buffer org-last-indirect-buffer))
4928 (setq ibuf (org-get-indirect-buffer cbuf)
4929 org-last-indirect-buffer ibuf)
4930 (cond
4931 ((or (eq org-indirect-buffer-display 'new-frame)
4932 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4933 (select-frame (make-frame))
4934 (delete-other-windows)
4935 (switch-to-buffer ibuf)
4936 (org-set-frame-title heading))
4937 ((eq org-indirect-buffer-display 'dedicated-frame)
4938 (raise-frame
4939 (select-frame (or (and org-indirect-dedicated-frame
4940 (frame-live-p org-indirect-dedicated-frame)
4941 org-indirect-dedicated-frame)
4942 (setq org-indirect-dedicated-frame (make-frame)))))
4943 (delete-other-windows)
4944 (switch-to-buffer ibuf)
4945 (org-set-frame-title (concat "Indirect: " heading)))
4946 ((eq org-indirect-buffer-display 'current-window)
4947 (switch-to-buffer ibuf))
4948 ((eq org-indirect-buffer-display 'other-window)
4949 (pop-to-buffer ibuf))
4950 (t (error "Invalid value.")))
4951 (if (featurep 'xemacs)
4952 (save-excursion (org-mode) (turn-on-font-lock)))
4953 (narrow-to-region beg end)
4954 (show-all)
4955 (goto-char pos)
4956 (and (window-live-p cwin) (select-window cwin))))
4958 (defun org-get-indirect-buffer (&optional buffer)
4959 (setq buffer (or buffer (current-buffer)))
4960 (let ((n 1) (base (buffer-name buffer)) bname)
4961 (while (buffer-live-p
4962 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4963 (setq n (1+ n)))
4964 (condition-case nil
4965 (make-indirect-buffer buffer bname 'clone)
4966 (error (make-indirect-buffer buffer bname)))))
4968 (defun org-set-frame-title (title)
4969 "Set the title of the current frame to the string TITLE."
4970 ;; FIXME: how to name a single frame in XEmacs???
4971 (unless (featurep 'xemacs)
4972 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4974 ;;;; Structure editing
4976 ;;; Inserting headlines
4978 (defun org-previous-line-empty-p ()
4979 (save-excursion
4980 (and (not (bobp))
4981 (or (beginning-of-line 0) t)
4982 (save-match-data
4983 (looking-at "[ \t]*$")))))
4985 (defun org-insert-heading (&optional force-heading)
4986 "Insert a new heading or item with same depth at point.
4987 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4988 If point is at the beginning of a headline, insert a sibling before the
4989 current headline. If point is not at the beginning, do not split the line,
4990 but create the new headline after the current line."
4991 (interactive "P")
4992 (if (= (buffer-size) 0)
4993 (insert "\n* ")
4994 (when (or force-heading (not (org-insert-item)))
4995 (let* ((empty-line-p nil)
4996 (head (save-excursion
4997 (condition-case nil
4998 (progn
4999 (org-back-to-heading)
5000 (setq empty-line-p (org-previous-line-empty-p))
5001 (match-string 0))
5002 (error "*"))))
5003 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5004 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5005 pos hide-previous previous-pos)
5006 (cond
5007 ((and (org-on-heading-p) (bolp)
5008 (or (bobp)
5009 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5010 ;; insert before the current line
5011 (open-line (if blank 2 1)))
5012 ((and (bolp)
5013 (or (bobp)
5014 (save-excursion
5015 (backward-char 1) (not (org-invisible-p)))))
5016 ;; insert right here
5017 nil)
5019 ;; somewhere in the line
5020 (save-excursion
5021 (setq previous-pos (point-at-bol))
5022 (end-of-line)
5023 (setq hide-previous (org-invisible-p)))
5024 (and org-insert-heading-respect-content (org-show-subtree))
5025 (let ((split
5026 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5027 (save-excursion
5028 (let ((p (point)))
5029 (goto-char (point-at-bol))
5030 (and (looking-at org-complex-heading-regexp)
5031 (> p (match-beginning 4)))))))
5032 tags pos)
5033 (cond
5034 (org-insert-heading-respect-content
5035 (org-end-of-subtree nil t)
5036 (or (bolp) (newline))
5037 (or (org-previous-line-empty-p)
5038 (and blank (newline)))
5039 (open-line 1))
5040 ((org-on-heading-p)
5041 (when hide-previous
5042 (show-children)
5043 (org-show-entry))
5044 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5045 (setq tags (and (match-end 2) (match-string 2)))
5046 (and (match-end 1)
5047 (delete-region (match-beginning 1) (match-end 1)))
5048 (setq pos (point-at-bol))
5049 (or split (end-of-line 1))
5050 (delete-horizontal-space)
5051 (newline (if blank 2 1))
5052 (when tags
5053 (save-excursion
5054 (goto-char pos)
5055 (end-of-line 1)
5056 (insert " " tags)
5057 (org-set-tags nil 'align))))
5059 (or split (end-of-line 1))
5060 (newline (if blank 2 1)))))))
5061 (insert head) (just-one-space)
5062 (setq pos (point))
5063 (end-of-line 1)
5064 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5065 (when (and org-insert-heading-respect-content hide-previous)
5066 (save-excursion
5067 (goto-char previous-pos)
5068 (hide-subtree)))
5069 (run-hooks 'org-insert-heading-hook)))))
5071 (defun org-get-heading (&optional no-tags)
5072 "Return the heading of the current entry, without the stars."
5073 (save-excursion
5074 (org-back-to-heading t)
5075 (if (looking-at
5076 (if no-tags
5077 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5078 "\\*+[ \t]+\\([^\r\n]*\\)"))
5079 (match-string 1) "")))
5081 (defun org-heading-components ()
5082 "Return the components of the current heading.
5083 This is a list with the following elements:
5084 - the level as an integer
5085 - the reduced level, different if `org-odd-levels-only' is set.
5086 - the TODO keyword, or nil
5087 - the priority character, like ?A, or nil if no priority is given
5088 - the headline text itself, or the tags string if no headline text
5089 - the tags string, or nil."
5090 (save-excursion
5091 (org-back-to-heading t)
5092 (if (looking-at org-complex-heading-regexp)
5093 (list (length (match-string 1))
5094 (org-reduced-level (length (match-string 1)))
5095 (org-match-string-no-properties 2)
5096 (and (match-end 3) (aref (match-string 3) 2))
5097 (org-match-string-no-properties 4)
5098 (org-match-string-no-properties 5)))))
5100 (defun org-insert-heading-after-current ()
5101 "Insert a new heading with same level as current, after current subtree."
5102 (interactive)
5103 (org-back-to-heading)
5104 (org-insert-heading)
5105 (org-move-subtree-down)
5106 (end-of-line 1))
5108 (defun org-insert-heading-respect-content ()
5109 (interactive)
5110 (let ((org-insert-heading-respect-content t))
5111 (org-insert-heading t)))
5113 (defun org-insert-todo-heading-respect-content (&optional force-state)
5114 (interactive "P")
5115 (let ((org-insert-heading-respect-content t))
5116 (org-insert-todo-heading force-state t)))
5118 (defun org-insert-todo-heading (arg &optional force-heading)
5119 "Insert a new heading with the same level and TODO state as current heading.
5120 If the heading has no TODO state, or if the state is DONE, use the first
5121 state (TODO by default). Also with prefix arg, force first state."
5122 (interactive "P")
5123 (when (or force-heading (not (org-insert-item 'checkbox)))
5124 (org-insert-heading force-heading)
5125 (save-excursion
5126 (org-back-to-heading)
5127 (outline-previous-heading)
5128 (looking-at org-todo-line-regexp))
5129 (if (or arg
5130 (not (match-beginning 2))
5131 (member (match-string 2) org-done-keywords))
5132 (insert (car org-todo-keywords-1) " ")
5133 (insert (match-string 2) " "))
5134 (when org-provide-todo-statistics
5135 (org-update-parent-todo-statistics))))
5137 (defun org-insert-subheading (arg)
5138 "Insert a new subheading and demote it.
5139 Works for outline headings and for plain lists alike."
5140 (interactive "P")
5141 (org-insert-heading arg)
5142 (cond
5143 ((org-on-heading-p) (org-do-demote))
5144 ((org-at-item-p) (org-indent-item 1))))
5146 (defun org-insert-todo-subheading (arg)
5147 "Insert a new subheading with TODO keyword or checkbox and demote it.
5148 Works for outline headings and for plain lists alike."
5149 (interactive "P")
5150 (org-insert-todo-heading arg)
5151 (cond
5152 ((org-on-heading-p) (org-do-demote))
5153 ((org-at-item-p) (org-indent-item 1))))
5155 ;;; Promotion and Demotion
5157 (defun org-promote-subtree ()
5158 "Promote the entire subtree.
5159 See also `org-promote'."
5160 (interactive)
5161 (save-excursion
5162 (org-map-tree 'org-promote))
5163 (org-fix-position-after-promote))
5165 (defun org-demote-subtree ()
5166 "Demote the entire subtree. See `org-demote'.
5167 See also `org-promote'."
5168 (interactive)
5169 (save-excursion
5170 (org-map-tree 'org-demote))
5171 (org-fix-position-after-promote))
5174 (defun org-do-promote ()
5175 "Promote the current heading higher up the tree.
5176 If the region is active in `transient-mark-mode', promote all headings
5177 in the region."
5178 (interactive)
5179 (save-excursion
5180 (if (org-region-active-p)
5181 (org-map-region 'org-promote (region-beginning) (region-end))
5182 (org-promote)))
5183 (org-fix-position-after-promote))
5185 (defun org-do-demote ()
5186 "Demote the current heading lower down the tree.
5187 If the region is active in `transient-mark-mode', demote all headings
5188 in the region."
5189 (interactive)
5190 (save-excursion
5191 (if (org-region-active-p)
5192 (org-map-region 'org-demote (region-beginning) (region-end))
5193 (org-demote)))
5194 (org-fix-position-after-promote))
5196 (defun org-fix-position-after-promote ()
5197 "Make sure that after pro/demotion cursor position is right."
5198 (let ((pos (point)))
5199 (when (save-excursion
5200 (beginning-of-line 1)
5201 (looking-at org-todo-line-regexp)
5202 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5203 (cond ((eobp) (insert " "))
5204 ((eolp) (insert " "))
5205 ((equal (char-after) ?\ ) (forward-char 1))))))
5207 (defun org-reduced-level (l)
5208 "Compute the effective level of a heading.
5209 This takes into account the setting of `org-odd-levels-only'."
5210 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5212 (defun org-get-valid-level (level &optional change)
5213 "Rectify a level change under the influence of `org-odd-levels-only'
5214 LEVEL is a current level, CHANGE is by how much the level should be
5215 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5216 even level numbers will become the next higher odd number."
5217 (if org-odd-levels-only
5218 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5219 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5220 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5221 (max 1 (+ level change))))
5223 (if (boundp 'define-obsolete-function-alias)
5224 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5225 (define-obsolete-function-alias 'org-get-legal-level
5226 'org-get-valid-level)
5227 (define-obsolete-function-alias 'org-get-legal-level
5228 'org-get-valid-level "23.1")))
5230 (defun org-promote ()
5231 "Promote the current heading higher up the tree.
5232 If the region is active in `transient-mark-mode', promote all headings
5233 in the region."
5234 (org-back-to-heading t)
5235 (let* ((level (save-match-data (funcall outline-level)))
5236 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5237 (diff (abs (- level (length up-head) -1))))
5238 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5239 (replace-match up-head nil t)
5240 ;; Fixup tag positioning
5241 (and org-auto-align-tags (org-set-tags nil t))
5242 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5244 (defun org-demote ()
5245 "Demote the current heading lower down the tree.
5246 If the region is active in `transient-mark-mode', demote all headings
5247 in the region."
5248 (org-back-to-heading t)
5249 (let* ((level (save-match-data (funcall outline-level)))
5250 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5251 (diff (abs (- level (length down-head) -1))))
5252 (replace-match down-head nil t)
5253 ;; Fixup tag positioning
5254 (and org-auto-align-tags (org-set-tags nil t))
5255 (if org-adapt-indentation (org-fixup-indentation diff))))
5257 (defun org-map-tree (fun)
5258 "Call FUN for every heading underneath the current one."
5259 (org-back-to-heading)
5260 (let ((level (funcall outline-level)))
5261 (save-excursion
5262 (funcall fun)
5263 (while (and (progn
5264 (outline-next-heading)
5265 (> (funcall outline-level) level))
5266 (not (eobp)))
5267 (funcall fun)))))
5269 (defun org-map-region (fun beg end)
5270 "Call FUN for every heading between BEG and END."
5271 (let ((org-ignore-region t))
5272 (save-excursion
5273 (setq end (copy-marker end))
5274 (goto-char beg)
5275 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5276 (< (point) end))
5277 (funcall fun))
5278 (while (and (progn
5279 (outline-next-heading)
5280 (< (point) end))
5281 (not (eobp)))
5282 (funcall fun)))))
5284 (defun org-fixup-indentation (diff)
5285 "Change the indentation in the current entry by DIFF
5286 However, if any line in the current entry has no indentation, or if it
5287 would end up with no indentation after the change, nothing at all is done."
5288 (save-excursion
5289 (let ((end (save-excursion (outline-next-heading)
5290 (point-marker)))
5291 (prohibit (if (> diff 0)
5292 "^\\S-"
5293 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5294 col)
5295 (unless (save-excursion (end-of-line 1)
5296 (re-search-forward prohibit end t))
5297 (while (and (< (point) end)
5298 (re-search-forward "^[ \t]+" end t))
5299 (goto-char (match-end 0))
5300 (setq col (current-column))
5301 (if (< diff 0) (replace-match ""))
5302 (org-indent-to-column (+ diff col))))
5303 (move-marker end nil))))
5305 (defun org-convert-to-odd-levels ()
5306 "Convert an org-mode file with all levels allowed to one with odd levels.
5307 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5308 level 5 etc."
5309 (interactive)
5310 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5311 (let ((org-odd-levels-only nil) n)
5312 (save-excursion
5313 (goto-char (point-min))
5314 (while (re-search-forward "^\\*\\*+ " nil t)
5315 (setq n (- (length (match-string 0)) 2))
5316 (while (>= (setq n (1- n)) 0)
5317 (org-demote))
5318 (end-of-line 1))))))
5321 (defun org-convert-to-oddeven-levels ()
5322 "Convert an org-mode file with only odd levels to one with odd and even levels.
5323 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5324 section with an even level, conversion would destroy the structure of the file. An error
5325 is signaled in this case."
5326 (interactive)
5327 (goto-char (point-min))
5328 ;; First check if there are no even levels
5329 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5330 (org-show-context t)
5331 (error "Not all levels are odd in this file. Conversion not possible."))
5332 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5333 (let ((org-odd-levels-only nil) n)
5334 (save-excursion
5335 (goto-char (point-min))
5336 (while (re-search-forward "^\\*\\*+ " nil t)
5337 (setq n (/ (1- (length (match-string 0))) 2))
5338 (while (>= (setq n (1- n)) 0)
5339 (org-promote))
5340 (end-of-line 1))))))
5342 (defun org-tr-level (n)
5343 "Make N odd if required."
5344 (if org-odd-levels-only (1+ (/ n 2)) n))
5346 ;;; Vertical tree motion, cutting and pasting of subtrees
5348 (defun org-move-subtree-up (&optional arg)
5349 "Move the current subtree up past ARG headlines of the same level."
5350 (interactive "p")
5351 (org-move-subtree-down (- (prefix-numeric-value arg))))
5353 (defun org-move-subtree-down (&optional arg)
5354 "Move the current subtree down past ARG headlines of the same level."
5355 (interactive "p")
5356 (setq arg (prefix-numeric-value arg))
5357 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5358 'outline-get-last-sibling))
5359 (ins-point (make-marker))
5360 (cnt (abs arg))
5361 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5362 ;; Select the tree
5363 (org-back-to-heading)
5364 (setq beg0 (point))
5365 (save-excursion
5366 (setq ne-beg (org-back-over-empty-lines))
5367 (setq beg (point)))
5368 (save-match-data
5369 (save-excursion (outline-end-of-heading)
5370 (setq folded (org-invisible-p)))
5371 (outline-end-of-subtree))
5372 (outline-next-heading)
5373 (setq ne-end (org-back-over-empty-lines))
5374 (setq end (point))
5375 (goto-char beg0)
5376 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5377 ;; include less whitespace
5378 (save-excursion
5379 (goto-char beg)
5380 (forward-line (- ne-beg ne-end))
5381 (setq beg (point))))
5382 ;; Find insertion point, with error handling
5383 (while (> cnt 0)
5384 (or (and (funcall movfunc) (looking-at outline-regexp))
5385 (progn (goto-char beg0)
5386 (error "Cannot move past superior level or buffer limit")))
5387 (setq cnt (1- cnt)))
5388 (if (> arg 0)
5389 ;; Moving forward - still need to move over subtree
5390 (progn (org-end-of-subtree t t)
5391 (save-excursion
5392 (org-back-over-empty-lines)
5393 (or (bolp) (newline)))))
5394 (setq ne-ins (org-back-over-empty-lines))
5395 (move-marker ins-point (point))
5396 (setq txt (buffer-substring beg end))
5397 (org-save-markers-in-region beg end)
5398 (delete-region beg end)
5399 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5400 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5401 (let ((bbb (point)))
5402 (insert-before-markers txt)
5403 (org-reinstall-markers-in-region bbb)
5404 (move-marker ins-point bbb))
5405 (or (bolp) (insert "\n"))
5406 (setq ins-end (point))
5407 (goto-char ins-point)
5408 (org-skip-whitespace)
5409 (when (and (< arg 0)
5410 (org-first-sibling-p)
5411 (> ne-ins ne-beg))
5412 ;; Move whitespace back to beginning
5413 (save-excursion
5414 (goto-char ins-end)
5415 (let ((kill-whole-line t))
5416 (kill-line (- ne-ins ne-beg)) (point)))
5417 (insert (make-string (- ne-ins ne-beg) ?\n)))
5418 (move-marker ins-point nil)
5419 (org-compact-display-after-subtree-move)
5420 (org-show-empty-lines-in-parent)
5421 (unless folded
5422 (org-show-entry)
5423 (show-children)
5424 (org-cycle-hide-drawers 'children))))
5426 (defvar org-subtree-clip ""
5427 "Clipboard for cut and paste of subtrees.
5428 This is actually only a copy of the kill, because we use the normal kill
5429 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5431 (defvar org-subtree-clip-folded nil
5432 "Was the last copied subtree folded?
5433 This is used to fold the tree back after pasting.")
5435 (defun org-cut-subtree (&optional n)
5436 "Cut the current subtree into the clipboard.
5437 With prefix arg N, cut this many sequential subtrees.
5438 This is a short-hand for marking the subtree and then cutting it."
5439 (interactive "p")
5440 (org-copy-subtree n 'cut))
5442 (defun org-copy-subtree (&optional n cut force-store-markers)
5443 "Cut the current subtree into the clipboard.
5444 With prefix arg N, cut this many sequential subtrees.
5445 This is a short-hand for marking the subtree and then copying it.
5446 If CUT is non-nil, actually cut the subtree.
5447 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5448 of some markers in the region, even if CUT is non-nil. This is
5449 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5450 (interactive "p")
5451 (let (beg end folded (beg0 (point)))
5452 (if (interactive-p)
5453 (org-back-to-heading nil) ; take what looks like a subtree
5454 (org-back-to-heading t)) ; take what is really there
5455 (org-back-over-empty-lines)
5456 (setq beg (point))
5457 (skip-chars-forward " \t\r\n")
5458 (save-match-data
5459 (save-excursion (outline-end-of-heading)
5460 (setq folded (org-invisible-p)))
5461 (condition-case nil
5462 (outline-forward-same-level (1- n))
5463 (error nil))
5464 (org-end-of-subtree t t))
5465 (org-back-over-empty-lines)
5466 (setq end (point))
5467 (goto-char beg0)
5468 (when (> end beg)
5469 (setq org-subtree-clip-folded folded)
5470 (when (or cut force-store-markers)
5471 (org-save-markers-in-region beg end))
5472 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5473 (setq org-subtree-clip (current-kill 0))
5474 (message "%s: Subtree(s) with %d characters"
5475 (if cut "Cut" "Copied")
5476 (length org-subtree-clip)))))
5478 (defun org-paste-subtree (&optional level tree for-yank)
5479 "Paste the clipboard as a subtree, with modification of headline level.
5480 The entire subtree is promoted or demoted in order to match a new headline
5481 level.
5483 If the cursor is at the beginning of a headline, the same level as
5484 that headline is used to paste the tree
5486 If not, the new level is derived from the *visible* headings
5487 before and after the insertion point, and taken to be the inferior headline
5488 level of the two. So if the previous visible heading is level 3 and the
5489 next is level 4 (or vice versa), level 4 will be used for insertion.
5490 This makes sure that the subtree remains an independent subtree and does
5491 not swallow low level entries.
5493 You can also force a different level, either by using a numeric prefix
5494 argument, or by inserting the heading marker by hand. For example, if the
5495 cursor is after \"*****\", then the tree will be shifted to level 5.
5497 If optional TREE is given, use this text instead of the kill ring.
5499 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5500 move back over whitespace before inserting, and move point to the end of
5501 the inserted text when done."
5502 (interactive "P")
5503 (unless (org-kill-is-subtree-p tree)
5504 (error "%s"
5505 (substitute-command-keys
5506 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5507 (let* ((visp (not (org-invisible-p)))
5508 (txt (or tree (and kill-ring (current-kill 0))))
5509 (^re (concat "^\\(" outline-regexp "\\)"))
5510 (re (concat "\\(" outline-regexp "\\)"))
5511 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5513 (old-level (if (string-match ^re txt)
5514 (- (match-end 0) (match-beginning 0) 1)
5515 -1))
5516 (force-level (cond (level (prefix-numeric-value level))
5517 ((and (looking-at "[ \t]*$")
5518 (string-match
5519 ^re_ (buffer-substring
5520 (point-at-bol) (point))))
5521 (- (match-end 1) (match-beginning 1)))
5522 ((and (bolp)
5523 (looking-at org-outline-regexp))
5524 (- (match-end 0) (point) 1))
5525 (t nil)))
5526 (previous-level (save-excursion
5527 (condition-case nil
5528 (progn
5529 (outline-previous-visible-heading 1)
5530 (if (looking-at re)
5531 (- (match-end 0) (match-beginning 0) 1)
5533 (error 1))))
5534 (next-level (save-excursion
5535 (condition-case nil
5536 (progn
5537 (or (looking-at outline-regexp)
5538 (outline-next-visible-heading 1))
5539 (if (looking-at re)
5540 (- (match-end 0) (match-beginning 0) 1)
5542 (error 1))))
5543 (new-level (or force-level (max previous-level next-level)))
5544 (shift (if (or (= old-level -1)
5545 (= new-level -1)
5546 (= old-level new-level))
5548 (- new-level old-level)))
5549 (delta (if (> shift 0) -1 1))
5550 (func (if (> shift 0) 'org-demote 'org-promote))
5551 (org-odd-levels-only nil)
5552 beg end newend)
5553 ;; Remove the forced level indicator
5554 (if force-level
5555 (delete-region (point-at-bol) (point)))
5556 ;; Paste
5557 (beginning-of-line 1)
5558 (unless for-yank (org-back-over-empty-lines))
5559 (setq beg (point))
5560 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5561 (insert-before-markers txt)
5562 (unless (string-match "\n\\'" txt) (insert "\n"))
5563 (setq newend (point))
5564 (org-reinstall-markers-in-region beg)
5565 (setq end (point))
5566 (goto-char beg)
5567 (skip-chars-forward " \t\n\r")
5568 (setq beg (point))
5569 (if (and (org-invisible-p) visp)
5570 (save-excursion (outline-show-heading)))
5571 ;; Shift if necessary
5572 (unless (= shift 0)
5573 (save-restriction
5574 (narrow-to-region beg end)
5575 (while (not (= shift 0))
5576 (org-map-region func (point-min) (point-max))
5577 (setq shift (+ delta shift)))
5578 (goto-char (point-min))
5579 (setq newend (point-max))))
5580 (when (or (interactive-p) for-yank)
5581 (message "Clipboard pasted as level %d subtree" new-level))
5582 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5583 kill-ring
5584 (eq org-subtree-clip (current-kill 0))
5585 org-subtree-clip-folded)
5586 ;; The tree was folded before it was killed/copied
5587 (hide-subtree))
5588 (and for-yank (goto-char newend))))
5590 (defun org-kill-is-subtree-p (&optional txt)
5591 "Check if the current kill is an outline subtree, or a set of trees.
5592 Returns nil if kill does not start with a headline, or if the first
5593 headline level is not the largest headline level in the tree.
5594 So this will actually accept several entries of equal levels as well,
5595 which is OK for `org-paste-subtree'.
5596 If optional TXT is given, check this string instead of the current kill."
5597 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5598 (start-level (and kill
5599 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5600 org-outline-regexp "\\)")
5601 kill)
5602 (- (match-end 2) (match-beginning 2) 1)))
5603 (re (concat "^" org-outline-regexp))
5604 (start (1+ (or (match-beginning 2) -1))))
5605 (if (not start-level)
5606 (progn
5607 nil) ;; does not even start with a heading
5608 (catch 'exit
5609 (while (setq start (string-match re kill (1+ start)))
5610 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5611 (throw 'exit nil)))
5612 t))))
5614 (defvar org-markers-to-move nil
5615 "Markers that should be moved with a cut-and-paste operation.
5616 Those markers are stored together with their positions relative to
5617 the start of the region.")
5619 (defun org-save-markers-in-region (beg end)
5620 "Check markers in region.
5621 If these markers are between BEG and END, record their position relative
5622 to BEG, so that after moving the block of text, we can put the markers back
5623 into place.
5624 This function gets called just before an entry or tree gets cut from the
5625 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5626 called immediately, to move the markers with the entries."
5627 (setq org-markers-to-move nil)
5628 (when (featurep 'org-clock)
5629 (org-clock-save-markers-for-cut-and-paste beg end))
5630 (when (featurep 'org-agenda)
5631 (org-agenda-save-markers-for-cut-and-paste beg end)))
5633 (defun org-check-and-save-marker (marker beg end)
5634 "Check if MARKER is between BEG and END.
5635 If yes, remember the marker and the distance to BEG."
5636 (when (and (marker-buffer marker)
5637 (equal (marker-buffer marker) (current-buffer)))
5638 (if (and (>= marker beg) (< marker end))
5639 (push (cons marker (- marker beg)) org-markers-to-move))))
5641 (defun org-reinstall-markers-in-region (beg)
5642 "Move all remembered markers to their position relative to BEG."
5643 (mapc (lambda (x)
5644 (move-marker (car x) (+ beg (cdr x))))
5645 org-markers-to-move)
5646 (setq org-markers-to-move nil))
5648 (defun org-narrow-to-subtree ()
5649 "Narrow buffer to the current subtree."
5650 (interactive)
5651 (save-excursion
5652 (save-match-data
5653 (narrow-to-region
5654 (progn (org-back-to-heading) (point))
5655 (progn (org-end-of-subtree t) (point))))))
5658 ;;; Outline Sorting
5660 (defun org-sort (with-case)
5661 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5662 Optional argument WITH-CASE means sort case-sensitively."
5663 (interactive "P")
5664 (if (org-at-table-p)
5665 (org-call-with-arg 'org-table-sort-lines with-case)
5666 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5668 (defun org-sort-remove-invisible (s)
5669 (remove-text-properties 0 (length s) org-rm-props s)
5670 (while (string-match org-bracket-link-regexp s)
5671 (setq s (replace-match (if (match-end 2)
5672 (match-string 3 s)
5673 (match-string 1 s)) t t s)))
5676 (defvar org-priority-regexp) ; defined later in the file
5678 (defun org-sort-entries-or-items
5679 (&optional with-case sorting-type getkey-func compare-func property)
5680 "Sort entries on a certain level of an outline tree.
5681 If there is an active region, the entries in the region are sorted.
5682 Else, if the cursor is before the first entry, sort the top-level items.
5683 Else, the children of the entry at point are sorted.
5685 Sorting can be alphabetically, numerically, and by date/time as given by
5686 the first time stamp in the entry. The command prompts for the sorting
5687 type unless it has been given to the function through the SORTING-TYPE
5688 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5689 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5690 called with point at the beginning of the record. It must return either
5691 a string or a number that should serve as the sorting key for that record.
5693 Comparing entries ignores case by default. However, with an optional argument
5694 WITH-CASE, the sorting considers case as well."
5695 (interactive "P")
5696 (let ((case-func (if with-case 'identity 'downcase))
5697 start beg end stars re re2
5698 txt what tmp plain-list-p)
5699 ;; Find beginning and end of region to sort
5700 (cond
5701 ((org-region-active-p)
5702 ;; we will sort the region
5703 (setq end (region-end)
5704 what "region")
5705 (goto-char (region-beginning))
5706 (if (not (org-on-heading-p)) (outline-next-heading))
5707 (setq start (point)))
5708 ((org-at-item-p)
5709 ;; we will sort this plain list
5710 (org-beginning-of-item-list) (setq start (point))
5711 (org-end-of-item-list) (setq end (point))
5712 (goto-char start)
5713 (setq plain-list-p t
5714 what "plain list"))
5715 ((or (org-on-heading-p)
5716 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5717 ;; we will sort the children of the current headline
5718 (org-back-to-heading)
5719 (setq start (point)
5720 end (progn (org-end-of-subtree t t)
5721 (org-back-over-empty-lines)
5722 (point))
5723 what "children")
5724 (goto-char start)
5725 (show-subtree)
5726 (outline-next-heading))
5728 ;; we will sort the top-level entries in this file
5729 (goto-char (point-min))
5730 (or (org-on-heading-p) (outline-next-heading))
5731 (setq start (point) end (point-max) what "top-level")
5732 (goto-char start)
5733 (show-all)))
5735 (setq beg (point))
5736 (if (>= beg end) (error "Nothing to sort"))
5738 (unless plain-list-p
5739 (looking-at "\\(\\*+\\)")
5740 (setq stars (match-string 1)
5741 re (concat "^" (regexp-quote stars) " +")
5742 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5743 txt (buffer-substring beg end))
5744 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5745 (if (and (not (equal stars "*")) (string-match re2 txt))
5746 (error "Region to sort contains a level above the first entry")))
5748 (unless sorting-type
5749 (message
5750 (if plain-list-p
5751 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5752 "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:")
5753 what)
5754 (setq sorting-type (read-char-exclusive))
5756 (and (= (downcase sorting-type) ?f)
5757 (setq getkey-func
5758 (org-ido-completing-read "Sort using function: "
5759 obarray 'fboundp t nil nil))
5760 (setq getkey-func (intern getkey-func)))
5762 (and (= (downcase sorting-type) ?r)
5763 (setq property
5764 (org-ido-completing-read "Property: "
5765 (mapcar 'list (org-buffer-property-keys t))
5766 nil t))))
5768 (message "Sorting entries...")
5770 (save-restriction
5771 (narrow-to-region start end)
5773 (let ((dcst (downcase sorting-type))
5774 (now (current-time)))
5775 (sort-subr
5776 (/= dcst sorting-type)
5777 ;; This function moves to the beginning character of the "record" to
5778 ;; be sorted.
5779 (if plain-list-p
5780 (lambda nil
5781 (if (org-at-item-p) t (goto-char (point-max))))
5782 (lambda nil
5783 (if (re-search-forward re nil t)
5784 (goto-char (match-beginning 0))
5785 (goto-char (point-max)))))
5786 ;; This function moves to the last character of the "record" being
5787 ;; sorted.
5788 (if plain-list-p
5789 'org-end-of-item
5790 (lambda nil
5791 (save-match-data
5792 (condition-case nil
5793 (outline-forward-same-level 1)
5794 (error
5795 (goto-char (point-max)))))))
5797 ;; This function returns the value that gets sorted against.
5798 (if plain-list-p
5799 (lambda nil
5800 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5801 (cond
5802 ((= dcst ?n)
5803 (string-to-number (buffer-substring (match-end 0)
5804 (point-at-eol))))
5805 ((= dcst ?a)
5806 (buffer-substring (match-end 0) (point-at-eol)))
5807 ((= dcst ?t)
5808 (if (re-search-forward org-ts-regexp
5809 (point-at-eol) t)
5810 (org-time-string-to-time (match-string 0))
5811 now))
5812 ((= dcst ?f)
5813 (if getkey-func
5814 (progn
5815 (setq tmp (funcall getkey-func))
5816 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5817 tmp)
5818 (error "Invalid key function `%s'" getkey-func)))
5819 (t (error "Invalid sorting type `%c'" sorting-type)))))
5820 (lambda nil
5821 (cond
5822 ((= dcst ?n)
5823 (if (looking-at org-complex-heading-regexp)
5824 (string-to-number (match-string 4))
5825 nil))
5826 ((= dcst ?a)
5827 (if (looking-at org-complex-heading-regexp)
5828 (funcall case-func (match-string 4))
5829 nil))
5830 ((= dcst ?t)
5831 (if (re-search-forward org-ts-regexp
5832 (save-excursion
5833 (forward-line 2)
5834 (point)) t)
5835 (org-time-string-to-time (match-string 0))
5836 now))
5837 ((= dcst ?p)
5838 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5839 (string-to-char (match-string 2))
5840 org-default-priority))
5841 ((= dcst ?r)
5842 (or (org-entry-get nil property) ""))
5843 ((= dcst ?o)
5844 (if (looking-at org-complex-heading-regexp)
5845 (- 9999 (length (member (match-string 2)
5846 org-todo-keywords-1)))))
5847 ((= dcst ?f)
5848 (if getkey-func
5849 (progn
5850 (setq tmp (funcall getkey-func))
5851 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5852 tmp)
5853 (error "Invalid key function `%s'" getkey-func)))
5854 (t (error "Invalid sorting type `%c'" sorting-type)))))
5856 (cond
5857 ((= dcst ?a) 'string<)
5858 ((= dcst ?t) 'time-less-p)
5859 ((= dcst ?f) compare-func)
5860 (t nil)))))
5861 (message "Sorting entries...done")))
5863 (defun org-do-sort (table what &optional with-case sorting-type)
5864 "Sort TABLE of WHAT according to SORTING-TYPE.
5865 The user will be prompted for the SORTING-TYPE if the call to this
5866 function does not specify it. WHAT is only for the prompt, to indicate
5867 what is being sorted. The sorting key will be extracted from
5868 the car of the elements of the table.
5869 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5870 (unless sorting-type
5871 (message
5872 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5873 what)
5874 (setq sorting-type (read-char-exclusive)))
5875 (let ((dcst (downcase sorting-type))
5876 extractfun comparefun)
5877 ;; Define the appropriate functions
5878 (cond
5879 ((= dcst ?n)
5880 (setq extractfun 'string-to-number
5881 comparefun (if (= dcst sorting-type) '< '>)))
5882 ((= dcst ?a)
5883 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5884 (lambda(x) (downcase (org-sort-remove-invisible x))))
5885 comparefun (if (= dcst sorting-type)
5886 'string<
5887 (lambda (a b) (and (not (string< a b))
5888 (not (string= a b)))))))
5889 ((= dcst ?t)
5890 (setq extractfun
5891 (lambda (x)
5892 (if (string-match org-ts-regexp x)
5893 (time-to-seconds
5894 (org-time-string-to-time (match-string 0 x)))
5896 comparefun (if (= dcst sorting-type) '< '>)))
5897 (t (error "Invalid sorting type `%c'" sorting-type)))
5899 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5900 table)
5901 (lambda (a b) (funcall comparefun (car a) (car b))))))
5903 ;;; Editing source examples
5905 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5906 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5907 (defvar org-edit-src-force-single-line nil)
5908 (defvar org-edit-src-from-org-mode nil)
5909 (defvar org-edit-src-picture nil)
5911 (define-minor-mode org-exit-edit-mode
5912 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5914 (defun org-edit-src-code ()
5915 "Edit the source code example at point.
5916 An indirect buffer is created, and that buffer is then narrowed to the
5917 example at point and switched to the correct language mode. When done,
5918 exit by killing the buffer with \\[org-edit-src-exit]."
5919 (interactive)
5920 (let ((line (org-current-line))
5921 (case-fold-search t)
5922 (msg (substitute-command-keys
5923 "Edit, then exit with C-c ' (C-c and single quote)"))
5924 (info (org-edit-src-find-region-and-lang))
5925 (org-mode-p (eq major-mode 'org-mode))
5926 beg end lang lang-f single lfmt)
5927 (if (not info)
5929 (setq beg (nth 0 info)
5930 end (nth 1 info)
5931 lang (nth 2 info)
5932 single (nth 3 info)
5933 lfmt (nth 4 info)
5934 lang-f (intern (concat lang "-mode")))
5935 (unless (functionp lang-f)
5936 (error "No such language mode: %s" lang-f))
5937 (goto-line line)
5938 (if (get-buffer "*Org Edit Src Example*")
5939 (kill-buffer "*Org Edit Src Example*"))
5940 (switch-to-buffer (make-indirect-buffer (current-buffer)
5941 "*Org Edit Src Example*"))
5942 (narrow-to-region beg end)
5943 (remove-text-properties beg end '(display nil invisible nil
5944 intangible nil))
5945 (let ((org-inhibit-startup t))
5946 (funcall lang-f))
5947 (set (make-local-variable 'org-edit-src-force-single-line) single)
5948 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5949 (when lfmt
5950 (set (make-local-variable 'org-coderef-label-format) lfmt))
5951 (when org-mode-p
5952 (goto-char (point-min))
5953 (while (re-search-forward "^," nil t)
5954 (replace-match "")))
5955 (goto-line line)
5956 (org-exit-edit-mode)
5957 (org-set-local 'header-line-format msg)
5958 (message "%s" msg)
5959 t)))
5961 (defun org-edit-fixed-width-region ()
5962 "Edit the fixed-width ascii drawing at point.
5963 This must be a region where each line starts with a colon followed by
5964 a space character.
5965 An indirect buffer is created, and that buffer is then narrowed to the
5966 example at point and switched to artist-mode. When done,
5967 exit by killing the buffer with \\[org-edit-src-exit]."
5968 (interactive)
5969 (let ((line (org-current-line))
5970 (case-fold-search t)
5971 (msg (substitute-command-keys
5972 "Edit, then exit with C-c ' (C-c and single quote)"))
5973 (org-mode-p (eq major-mode 'org-mode))
5974 beg end)
5975 (beginning-of-line 1)
5976 (if (looking-at "[ \t]*[^:\n \t]")
5978 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5979 (setq beg (point) end beg)
5980 (save-excursion
5981 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5982 (setq beg (point-at-bol 2))
5983 (setq beg (point))))
5984 (save-excursion
5985 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5986 (setq end (1- (match-beginning 0)))
5987 (setq end (point))))
5988 (goto-line line))
5989 (if (get-buffer "*Org Edit Picture*")
5990 (kill-buffer "*Org Edit Picture*"))
5991 (switch-to-buffer (make-indirect-buffer (current-buffer)
5992 "*Org Edit Picture*"))
5993 (narrow-to-region beg end)
5994 (remove-text-properties beg end '(display nil invisible nil
5995 intangible nil))
5996 (when (fboundp 'font-lock-unfontify-region)
5997 (font-lock-unfontify-region (point-min) (point-max)))
5998 (cond
5999 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6000 (fundamental-mode)
6001 (artist-mode 1))
6002 (t (funcall org-edit-fixed-width-region-mode)))
6003 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6004 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6005 (set (make-local-variable 'org-edit-src-picture) t)
6006 (goto-char (point-min))
6007 (while (re-search-forward "^[ \t]*: ?" nil t)
6008 (replace-match ""))
6009 (goto-line line)
6010 (org-exit-edit-mode)
6011 (org-set-local 'header-line-format msg)
6012 (message "%s" msg)
6013 t)))
6016 (defun org-edit-src-find-region-and-lang ()
6017 "Find the region and language for a local edit.
6018 Return a list with beginning and end of the region, a string representing
6019 the language, a switch telling of the content should be in a single line."
6020 (let ((re-list
6021 (append
6022 org-edit-src-region-extra
6024 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6025 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6026 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6027 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6028 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6029 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6030 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6031 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6032 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6033 ("^#\\+html:" "\n" "html" single-line)
6034 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6035 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6036 ("^#\\+latex:" "\n" "latex" single-line)
6037 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6038 ("^#\\+ascii:" "\n" "ascii" single-line)
6040 (pos (point))
6041 re1 re2 single beg end lang lfmt match-re1)
6042 (catch 'exit
6043 (while (setq entry (pop re-list))
6044 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6045 single (nth 3 entry))
6046 (save-excursion
6047 (if (or (looking-at re1)
6048 (re-search-backward re1 nil t))
6049 (progn
6050 (setq match-re1 (match-string 0))
6051 (setq beg (match-end 0)
6052 lang (org-edit-src-get-lang lang)
6053 lfmt (org-edit-src-get-label-format match-re1))
6054 (if (and (re-search-forward re2 nil t)
6055 (>= (match-end 0) pos))
6056 (throw 'exit (list beg (match-beginning 0)
6057 lang single lfmt))))
6058 (if (or (looking-at re2)
6059 (re-search-forward re2 nil t))
6060 (progn
6061 (setq end (match-beginning 0))
6062 (if (and (re-search-backward re1 nil t)
6063 (<= (match-beginning 0) pos))
6064 (progn
6065 (setq lfmt (org-edit-src-get-label-format
6066 (match-string 0)))
6067 (throw 'exit
6068 (list (match-end 0) end
6069 (org-edit-src-get-lang lang)
6070 single lfmt))))))))))))
6072 (defun org-edit-src-get-lang (lang)
6073 "Extract the src language."
6074 (let ((m (match-string 0)))
6075 (cond
6076 ((stringp lang) lang)
6077 ((integerp lang) (match-string lang))
6078 ((and (eq lang 'lang)
6079 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6080 (match-string 1 m))
6081 ((and (eq lang 'style)
6082 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6083 (match-string 1 m))
6084 (t "fundamental"))))
6086 (defun org-edit-src-get-label-format (s)
6087 "Extract the label format."
6088 (save-match-data
6089 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6090 (match-string 1 s))))
6092 (defun org-edit-src-exit ()
6093 "Exit special edit and protect problematic lines."
6094 (interactive)
6095 (unless (buffer-base-buffer (current-buffer))
6096 (error "This is not an indirect buffer, something is wrong..."))
6097 (unless (> (point-min) 1)
6098 (error "This buffer is not narrowed, something is wrong..."))
6099 (goto-char (point-min))
6100 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6101 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6102 (when (org-bound-and-true-p org-edit-src-force-single-line)
6103 (goto-char (point-min))
6104 (while (re-search-forward "\n" nil t)
6105 (replace-match " "))
6106 (goto-char (point-min))
6107 (if (looking-at "\\s-*") (replace-match " "))
6108 (if (re-search-forward "\\s-+\\'" nil t)
6109 (replace-match "")))
6110 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6111 (goto-char (point-min))
6112 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6113 (replace-match ",\\1"))
6114 (when font-lock-mode
6115 (font-lock-unfontify-region (point-min) (point-max)))
6116 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6117 (when (org-bound-and-true-p org-edit-src-picture)
6118 (untabify (point-min) (point-max))
6119 (goto-char (point-min))
6120 (while (re-search-forward "^" nil t)
6121 (replace-match ": "))
6122 (when font-lock-mode
6123 (font-lock-unfontify-region (point-min) (point-max)))
6124 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6125 (kill-buffer (current-buffer))
6126 (and (org-mode-p) (org-restart-font-lock)))
6129 ;;; The orgstruct minor mode
6131 ;; Define a minor mode which can be used in other modes in order to
6132 ;; integrate the org-mode structure editing commands.
6134 ;; This is really a hack, because the org-mode structure commands use
6135 ;; keys which normally belong to the major mode. Here is how it
6136 ;; works: The minor mode defines all the keys necessary to operate the
6137 ;; structure commands, but wraps the commands into a function which
6138 ;; tests if the cursor is currently at a headline or a plain list
6139 ;; item. If that is the case, the structure command is used,
6140 ;; temporarily setting many Org-mode variables like regular
6141 ;; expressions for filling etc. However, when any of those keys is
6142 ;; used at a different location, function uses `key-binding' to look
6143 ;; up if the key has an associated command in another currently active
6144 ;; keymap (minor modes, major mode, global), and executes that
6145 ;; command. There might be problems if any of the keys is otherwise
6146 ;; used as a prefix key.
6148 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6149 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6150 ;; addresses this by checking explicitly for both bindings.
6152 (defvar orgstruct-mode-map (make-sparse-keymap)
6153 "Keymap for the minor `orgstruct-mode'.")
6155 (defvar org-local-vars nil
6156 "List of local variables, for use by `orgstruct-mode'")
6158 ;;;###autoload
6159 (define-minor-mode orgstruct-mode
6160 "Toggle the minor more `orgstruct-mode'.
6161 This mode is for using Org-mode structure commands in other modes.
6162 The following key behave as if Org-mode was active, if the cursor
6163 is on a headline, or on a plain list item (both in the definition
6164 of Org-mode).
6166 M-up Move entry/item up
6167 M-down Move entry/item down
6168 M-left Promote
6169 M-right Demote
6170 M-S-up Move entry/item up
6171 M-S-down Move entry/item down
6172 M-S-left Promote subtree
6173 M-S-right Demote subtree
6174 M-q Fill paragraph and items like in Org-mode
6175 C-c ^ Sort entries
6176 C-c - Cycle list bullet
6177 TAB Cycle item visibility
6178 M-RET Insert new heading/item
6179 S-M-RET Insert new TODO heading / Checkbox item
6180 C-c C-c Set tags / toggle checkbox"
6181 nil " OrgStruct" nil
6182 (org-load-modules-maybe)
6183 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6185 ;;;###autoload
6186 (defun turn-on-orgstruct ()
6187 "Unconditionally turn on `orgstruct-mode'."
6188 (orgstruct-mode 1))
6190 ;;;###autoload
6191 (defun turn-on-orgstruct++ ()
6192 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6193 In addition to setting orgstruct-mode, this also exports all indentation and
6194 autofilling variables from org-mode into the buffer. Note that turning
6195 off orgstruct-mode will *not* remove these additional settings."
6196 (orgstruct-mode 1)
6197 (let (var val)
6198 (mapc
6199 (lambda (x)
6200 (when (string-match
6201 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6202 (symbol-name (car x)))
6203 (setq var (car x) val (nth 1 x))
6204 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6205 org-local-vars)))
6207 (defun orgstruct-error ()
6208 "Error when there is no default binding for a structure key."
6209 (interactive)
6210 (error "This key has no function outside structure elements"))
6212 (defun orgstruct-setup ()
6213 "Setup orgstruct keymaps."
6214 (let ((nfunc 0)
6215 (bindings
6216 (list
6217 '([(meta up)] org-metaup)
6218 '([(meta down)] org-metadown)
6219 '([(meta left)] org-metaleft)
6220 '([(meta right)] org-metaright)
6221 '([(meta shift up)] org-shiftmetaup)
6222 '([(meta shift down)] org-shiftmetadown)
6223 '([(meta shift left)] org-shiftmetaleft)
6224 '([(meta shift right)] org-shiftmetaright)
6225 '([(shift up)] org-shiftup)
6226 '([(shift down)] org-shiftdown)
6227 '([(shift left)] org-shiftleft)
6228 '([(shift right)] org-shiftright)
6229 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6230 '("\M-q" fill-paragraph)
6231 '("\C-c^" org-sort)
6232 '("\C-c-" org-cycle-list-bullet)))
6233 elt key fun cmd)
6234 (while (setq elt (pop bindings))
6235 (setq nfunc (1+ nfunc))
6236 (setq key (org-key (car elt))
6237 fun (nth 1 elt)
6238 cmd (orgstruct-make-binding fun nfunc key))
6239 (org-defkey orgstruct-mode-map key cmd))
6241 ;; Special treatment needed for TAB and RET
6242 (org-defkey orgstruct-mode-map [(tab)]
6243 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6244 (org-defkey orgstruct-mode-map "\C-i"
6245 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6247 (org-defkey orgstruct-mode-map "\M-\C-m"
6248 (orgstruct-make-binding 'org-insert-heading 105
6249 "\M-\C-m" [(meta return)]))
6250 (org-defkey orgstruct-mode-map [(meta return)]
6251 (orgstruct-make-binding 'org-insert-heading 106
6252 [(meta return)] "\M-\C-m"))
6254 (org-defkey orgstruct-mode-map [(shift meta return)]
6255 (orgstruct-make-binding 'org-insert-todo-heading 107
6256 [(meta return)] "\M-\C-m"))
6258 (unless org-local-vars
6259 (setq org-local-vars (org-get-local-variables)))
6263 (defun orgstruct-make-binding (fun n &rest keys)
6264 "Create a function for binding in the structure minor mode.
6265 FUN is the command to call inside a table. N is used to create a unique
6266 command name. KEYS are keys that should be checked in for a command
6267 to execute outside of tables."
6268 (eval
6269 (list 'defun
6270 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6271 '(arg)
6272 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6273 "Outside of structure, run the binding of `"
6274 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6275 "'.")
6276 '(interactive "p")
6277 (list 'if
6278 '(org-context-p 'headline 'item)
6279 (list 'org-run-like-in-org-mode (list 'quote fun))
6280 (list 'let '(orgstruct-mode)
6281 (list 'call-interactively
6282 (append '(or)
6283 (mapcar (lambda (k)
6284 (list 'key-binding k))
6285 keys)
6286 '('orgstruct-error))))))))
6288 (defun org-context-p (&rest contexts)
6289 "Check if local context is any of CONTEXTS.
6290 Possible values in the list of contexts are `table', `headline', and `item'."
6291 (let ((pos (point)))
6292 (goto-char (point-at-bol))
6293 (prog1 (or (and (memq 'table contexts)
6294 (looking-at "[ \t]*|"))
6295 (and (memq 'headline contexts)
6296 ;;????????? (looking-at "\\*+"))
6297 (looking-at outline-regexp))
6298 (and (memq 'item contexts)
6299 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6300 (goto-char pos))))
6302 (defun org-get-local-variables ()
6303 "Return a list of all local variables in an org-mode buffer."
6304 (let (varlist)
6305 (with-current-buffer (get-buffer-create "*Org tmp*")
6306 (erase-buffer)
6307 (org-mode)
6308 (setq varlist (buffer-local-variables)))
6309 (kill-buffer "*Org tmp*")
6310 (delq nil
6311 (mapcar
6312 (lambda (x)
6313 (setq x
6314 (if (symbolp x)
6315 (list x)
6316 (list (car x) (list 'quote (cdr x)))))
6317 (if (string-match
6318 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6319 (symbol-name (car x)))
6320 x nil))
6321 varlist))))
6323 ;;;###autoload
6324 (defun org-run-like-in-org-mode (cmd)
6325 (org-load-modules-maybe)
6326 (unless org-local-vars
6327 (setq org-local-vars (org-get-local-variables)))
6328 (eval (list 'let org-local-vars
6329 (list 'call-interactively (list 'quote cmd)))))
6331 ;;;; Archiving
6333 (defun org-get-category (&optional pos)
6334 "Get the category applying to position POS."
6335 (get-text-property (or pos (point)) 'org-category))
6337 (defun org-refresh-category-properties ()
6338 "Refresh category text properties in the buffer."
6339 (let ((def-cat (cond
6340 ((null org-category)
6341 (if buffer-file-name
6342 (file-name-sans-extension
6343 (file-name-nondirectory buffer-file-name))
6344 "???"))
6345 ((symbolp org-category) (symbol-name org-category))
6346 (t org-category)))
6347 beg end cat pos optionp)
6348 (org-unmodified
6349 (save-excursion
6350 (save-restriction
6351 (widen)
6352 (goto-char (point-min))
6353 (put-text-property (point) (point-max) 'org-category def-cat)
6354 (while (re-search-forward
6355 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6356 (setq pos (match-end 0)
6357 optionp (equal (char-after (match-beginning 0)) ?#)
6358 cat (org-trim (match-string 2)))
6359 (if optionp
6360 (setq beg (point-at-bol) end (point-max))
6361 (org-back-to-heading t)
6362 (setq beg (point) end (org-end-of-subtree t t)))
6363 (put-text-property beg end 'org-category cat)
6364 (goto-char pos)))))))
6367 ;;;; Link Stuff
6369 ;;; Link abbreviations
6371 (defun org-link-expand-abbrev (link)
6372 "Apply replacements as defined in `org-link-abbrev-alist."
6373 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6374 (let* ((key (match-string 1 link))
6375 (as (or (assoc key org-link-abbrev-alist-local)
6376 (assoc key org-link-abbrev-alist)))
6377 (tag (and (match-end 2) (match-string 3 link)))
6378 rpl)
6379 (if (not as)
6380 link
6381 (setq rpl (cdr as))
6382 (cond
6383 ((symbolp rpl) (funcall rpl tag))
6384 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6385 ((string-match "%h" rpl)
6386 (replace-match (url-hexify-string (or tag "")) t t rpl))
6387 (t (concat rpl tag)))))
6388 link))
6390 ;;; Storing and inserting links
6392 (defvar org-insert-link-history nil
6393 "Minibuffer history for links inserted with `org-insert-link'.")
6395 (defvar org-stored-links nil
6396 "Contains the links stored with `org-store-link'.")
6398 (defvar org-store-link-plist nil
6399 "Plist with info about the most recently link created with `org-store-link'.")
6401 (defvar org-link-protocols nil
6402 "Link protocols added to Org-mode using `org-add-link-type'.")
6404 (defvar org-store-link-functions nil
6405 "List of functions that are called to create and store a link.
6406 Each function will be called in turn until one returns a non-nil
6407 value. Each function should check if it is responsible for creating
6408 this link (for example by looking at the major mode).
6409 If not, it must exit and return nil.
6410 If yes, it should return a non-nil value after a calling
6411 `org-store-link-props' with a list of properties and values.
6412 Special properties are:
6414 :type The link prefix. like \"http\". This must be given.
6415 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6416 This is obligatory as well.
6417 :description Optional default description for the second pair
6418 of brackets in an Org-mode link. The user can still change
6419 this when inserting this link into an Org-mode buffer.
6421 In addition to these, any additional properties can be specified
6422 and then used in remember templates.")
6424 (defun org-add-link-type (type &optional follow export)
6425 "Add TYPE to the list of `org-link-types'.
6426 Re-compute all regular expressions depending on `org-link-types'
6428 FOLLOW and EXPORT are two functions.
6430 FOLLOW should take the link path as the single argument and do whatever
6431 is necessary to follow the link, for example find a file or display
6432 a mail message.
6434 EXPORT should format the link path for export to one of the export formats.
6435 It should be a function accepting three arguments:
6437 path the path of the link, the text after the prefix (like \"http:\")
6438 desc the description of the link, if any, nil if there was no description
6439 format the export format, a symbol like `html' or `latex'.
6441 The function may use the FORMAT information to return different values
6442 depending on the format. The return value will be put literally into
6443 the exported file.
6444 Org-mode has a built-in default for exporting links. If you are happy with
6445 this default, there is no need to define an export function for the link
6446 type. For a simple example of an export function, see `org-bbdb.el'."
6447 (add-to-list 'org-link-types type t)
6448 (org-make-link-regexps)
6449 (if (assoc type org-link-protocols)
6450 (setcdr (assoc type org-link-protocols) (list follow export))
6451 (push (list type follow export) org-link-protocols)))
6453 ;;;###autoload
6454 (defun org-store-link (arg)
6455 "\\<org-mode-map>Store an org-link to the current location.
6456 This link is added to `org-stored-links' and can later be inserted
6457 into an org-buffer with \\[org-insert-link].
6459 For some link types, a prefix arg is interpreted:
6460 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6461 For file links, arg negates `org-context-in-file-links'."
6462 (interactive "P")
6463 (org-load-modules-maybe)
6464 (setq org-store-link-plist nil) ; reset
6465 (let (link cpltxt desc description search txt)
6466 (cond
6468 ((run-hook-with-args-until-success 'org-store-link-functions)
6469 (setq link (plist-get org-store-link-plist :link)
6470 desc (or (plist-get org-store-link-plist :description) link)))
6472 ((equal (buffer-name) "*Org Edit Src Example*")
6473 (let (label gc)
6474 (while (or (not label)
6475 (save-excursion
6476 (save-restriction
6477 (widen)
6478 (goto-char (point-min))
6479 (re-search-forward
6480 (regexp-quote (format org-coderef-label-format label))
6481 nil t))))
6482 (when label (message "Label exists already") (sit-for 2))
6483 (setq label (read-string "Code line label: " label)))
6484 (end-of-line 1)
6485 (setq link (format org-coderef-label-format label))
6486 (setq gc (- 79 (length link)))
6487 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6488 (insert link)
6489 (setq link (concat "(" label ")") desc nil)))
6491 ((eq major-mode 'calendar-mode)
6492 (let ((cd (calendar-cursor-to-date)))
6493 (setq link
6494 (format-time-string
6495 (car org-time-stamp-formats)
6496 (apply 'encode-time
6497 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6498 nil nil nil))))
6499 (org-store-link-props :type "calendar" :date cd)))
6501 ((eq major-mode 'w3-mode)
6502 (setq cpltxt (url-view-url t)
6503 link (org-make-link cpltxt))
6504 (org-store-link-props :type "w3" :url (url-view-url t)))
6506 ((eq major-mode 'w3m-mode)
6507 (setq cpltxt (or w3m-current-title w3m-current-url)
6508 link (org-make-link w3m-current-url))
6509 (org-store-link-props :type "w3m" :url (url-view-url t)))
6511 ((setq search (run-hook-with-args-until-success
6512 'org-create-file-search-functions))
6513 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6514 "::" search))
6515 (setq cpltxt (or description link)))
6517 ((eq major-mode 'image-mode)
6518 (setq cpltxt (concat "file:"
6519 (abbreviate-file-name buffer-file-name))
6520 link (org-make-link cpltxt))
6521 (org-store-link-props :type "image" :file buffer-file-name))
6523 ((eq major-mode 'dired-mode)
6524 ;; link to the file in the current line
6525 (setq cpltxt (concat "file:"
6526 (abbreviate-file-name
6527 (expand-file-name
6528 (dired-get-filename nil t))))
6529 link (org-make-link cpltxt)))
6531 ((and buffer-file-name (org-mode-p))
6532 (cond
6533 ((org-in-regexp "<<\\(.*?\\)>>")
6534 (setq cpltxt
6535 (concat "file:"
6536 (abbreviate-file-name buffer-file-name)
6537 "::" (match-string 1))
6538 link (org-make-link cpltxt)))
6539 ((and (featurep 'org-id)
6540 (or (eq org-link-to-org-use-id t)
6541 (and (eq org-link-to-org-use-id 'create-if-interactive)
6542 (interactive-p))
6543 (and org-link-to-org-use-id
6544 (condition-case nil
6545 (org-entry-get nil "ID")
6546 (error nil)))))
6547 ;; We can make a link using the ID.
6548 (setq link (condition-case nil
6549 (prog1 (org-id-store-link)
6550 (setq desc (plist-get org-store-link-plist
6551 :description)))
6552 (error
6553 ;; probably before first headline, link to file only
6554 (concat "file:"
6555 (abbreviate-file-name buffer-file-name))))))
6557 ;; Just link to current headline
6558 (setq cpltxt (concat "file:"
6559 (abbreviate-file-name buffer-file-name)))
6560 ;; Add a context search string
6561 (when (org-xor org-context-in-file-links arg)
6562 (setq txt (cond
6563 ((org-on-heading-p) nil)
6564 ((org-region-active-p)
6565 (buffer-substring (region-beginning) (region-end)))
6566 (t nil)))
6567 (when (or (null txt) (string-match "\\S-" txt))
6568 (setq cpltxt
6569 (concat cpltxt "::"
6570 (condition-case nil
6571 (org-make-org-heading-search-string txt)
6572 (error "")))
6573 desc "NONE")))
6574 (if (string-match "::\\'" cpltxt)
6575 (setq cpltxt (substring cpltxt 0 -2)))
6576 (setq link (org-make-link cpltxt)))))
6578 ((buffer-file-name (buffer-base-buffer))
6579 ;; Just link to this file here.
6580 (setq cpltxt (concat "file:"
6581 (abbreviate-file-name
6582 (buffer-file-name (buffer-base-buffer)))))
6583 ;; Add a context string
6584 (when (org-xor org-context-in-file-links arg)
6585 (setq txt (if (org-region-active-p)
6586 (buffer-substring (region-beginning) (region-end))
6587 (buffer-substring (point-at-bol) (point-at-eol))))
6588 ;; Only use search option if there is some text.
6589 (when (string-match "\\S-" txt)
6590 (setq cpltxt
6591 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6592 desc "NONE")))
6593 (setq link (org-make-link cpltxt)))
6595 ((interactive-p)
6596 (error "Cannot link to a buffer which is not visiting a file"))
6598 (t (setq link nil)))
6600 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6601 (setq link (or link cpltxt)
6602 desc (or desc cpltxt))
6603 (if (equal desc "NONE") (setq desc nil))
6605 (if (and (interactive-p) link)
6606 (progn
6607 (setq org-stored-links
6608 (cons (list link desc) org-stored-links))
6609 (message "Stored: %s" (or desc link)))
6610 (and link (org-make-link-string link desc)))))
6612 (defun org-store-link-props (&rest plist)
6613 "Store link properties, extract names and addresses."
6614 (let (x adr)
6615 (when (setq x (plist-get plist :from))
6616 (setq adr (mail-extract-address-components x))
6617 (setq plist (plist-put plist :fromname (car adr)))
6618 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6619 (when (setq x (plist-get plist :to))
6620 (setq adr (mail-extract-address-components x))
6621 (setq plist (plist-put plist :toname (car adr)))
6622 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6623 (let ((from (plist-get plist :from))
6624 (to (plist-get plist :to)))
6625 (when (and from to org-from-is-user-regexp)
6626 (setq plist
6627 (plist-put plist :fromto
6628 (if (string-match org-from-is-user-regexp from)
6629 (concat "to %t")
6630 (concat "from %f"))))))
6631 (setq org-store-link-plist plist))
6633 (defun org-add-link-props (&rest plist)
6634 "Add these properties to the link property list."
6635 (let (key value)
6636 (while plist
6637 (setq key (pop plist) value (pop plist))
6638 (setq org-store-link-plist
6639 (plist-put org-store-link-plist key value)))))
6641 (defun org-email-link-description (&optional fmt)
6642 "Return the description part of an email link.
6643 This takes information from `org-store-link-plist' and formats it
6644 according to FMT (default from `org-email-link-description-format')."
6645 (setq fmt (or fmt org-email-link-description-format))
6646 (let* ((p org-store-link-plist)
6647 (to (plist-get p :toaddress))
6648 (from (plist-get p :fromaddress))
6649 (table
6650 (list
6651 (cons "%c" (plist-get p :fromto))
6652 (cons "%F" (plist-get p :from))
6653 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6654 (cons "%T" (plist-get p :to))
6655 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6656 (cons "%s" (plist-get p :subject))
6657 (cons "%m" (plist-get p :message-id)))))
6658 (when (string-match "%c" fmt)
6659 ;; Check if the user wrote this message
6660 (if (and org-from-is-user-regexp from to
6661 (save-match-data (string-match org-from-is-user-regexp from)))
6662 (setq fmt (replace-match "to %t" t t fmt))
6663 (setq fmt (replace-match "from %f" t t fmt))))
6664 (org-replace-escapes fmt table)))
6666 (defun org-make-org-heading-search-string (&optional string heading)
6667 "Make search string for STRING or current headline."
6668 (interactive)
6669 (let ((s (or string (org-get-heading))))
6670 (unless (and string (not heading))
6671 ;; We are using a headline, clean up garbage in there.
6672 (if (string-match org-todo-regexp s)
6673 (setq s (replace-match "" t t s)))
6674 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6675 (setq s (replace-match "" t t s)))
6676 (setq s (org-trim s))
6677 (if (string-match (concat "^\\(" org-quote-string "\\|"
6678 org-comment-string "\\)") s)
6679 (setq s (replace-match "" t t s)))
6680 (while (string-match org-ts-regexp s)
6681 (setq s (replace-match "" t t s))))
6682 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6683 (setq s (replace-match " " t t s)))
6684 (or string (setq s (concat "*" s))) ; Add * for headlines
6685 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6687 (defun org-make-link (&rest strings)
6688 "Concatenate STRINGS."
6689 (apply 'concat strings))
6691 (defun org-make-link-string (link &optional description)
6692 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6693 (unless (string-match "\\S-" link)
6694 (error "Empty link"))
6695 (when (stringp description)
6696 ;; Remove brackets from the description, they are fatal.
6697 (while (string-match "\\[" description)
6698 (setq description (replace-match "{" t t description)))
6699 (while (string-match "\\]" description)
6700 (setq description (replace-match "}" t t description))))
6701 (when (equal (org-link-escape link) description)
6702 ;; No description needed, it is identical
6703 (setq description nil))
6704 (when (and (not description)
6705 (not (equal link (org-link-escape link))))
6706 (setq description (org-extract-attributes link)))
6707 (concat "[[" (org-link-escape link) "]"
6708 (if description (concat "[" description "]") "")
6709 "]"))
6711 (defconst org-link-escape-chars
6712 '((?\ . "%20")
6713 (?\[ . "%5B")
6714 (?\] . "%5D")
6715 (?\340 . "%E0") ; `a
6716 (?\342 . "%E2") ; ^a
6717 (?\347 . "%E7") ; ,c
6718 (?\350 . "%E8") ; `e
6719 (?\351 . "%E9") ; 'e
6720 (?\352 . "%EA") ; ^e
6721 (?\356 . "%EE") ; ^i
6722 (?\364 . "%F4") ; ^o
6723 (?\371 . "%F9") ; `u
6724 (?\373 . "%FB") ; ^u
6725 (?\; . "%3B")
6726 (?? . "%3F")
6727 (?= . "%3D")
6728 (?+ . "%2B")
6730 "Association list of escapes for some characters problematic in links.
6731 This is the list that is used for internal purposes.")
6733 (defconst org-link-escape-chars-browser
6734 '((?\ . "%20")) ; 32 for the SPC char
6735 "Association list of escapes for some characters problematic in links.
6736 This is the list that is used before handing over to the browser.")
6738 (defun org-link-escape (text &optional table)
6739 "Escape characters in TEXT that are problematic for links."
6740 (setq table (or table org-link-escape-chars))
6741 (when text
6742 (let ((re (mapconcat (lambda (x) (regexp-quote
6743 (char-to-string (car x))))
6744 table "\\|")))
6745 (while (string-match re text)
6746 (setq text
6747 (replace-match
6748 (cdr (assoc (string-to-char (match-string 0 text))
6749 table))
6750 t t text)))
6751 text)))
6753 (defun org-link-unescape (text &optional table)
6754 "Reverse the action of `org-link-escape'."
6755 (setq table (or table org-link-escape-chars))
6756 (when text
6757 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6758 table "\\|")))
6759 (while (string-match re text)
6760 (setq text
6761 (replace-match
6762 (char-to-string (car (rassoc (match-string 0 text) table)))
6763 t t text)))
6764 text)))
6766 (defun org-xor (a b)
6767 "Exclusive or."
6768 (if a (not b) b))
6770 (defun org-fixup-message-id-for-http (s)
6771 "Replace special characters in a message id, so it can be used in an http query."
6772 (while (string-match "<" s)
6773 (setq s (replace-match "%3C" t t s)))
6774 (while (string-match ">" s)
6775 (setq s (replace-match "%3E" t t s)))
6776 (while (string-match "@" s)
6777 (setq s (replace-match "%40" t t s)))
6780 ;;;###autoload
6781 (defun org-insert-link-global ()
6782 "Insert a link like Org-mode does.
6783 This command can be called in any mode to insert a link in Org-mode syntax."
6784 (interactive)
6785 (org-load-modules-maybe)
6786 (org-run-like-in-org-mode 'org-insert-link))
6788 (defun org-insert-link (&optional complete-file link-location)
6789 "Insert a link. At the prompt, enter the link.
6791 Completion can be used to insert any of the link protocol prefixes like
6792 http or ftp in use.
6794 The history can be used to select a link previously stored with
6795 `org-store-link'. When the empty string is entered (i.e. if you just
6796 press RET at the prompt), the link defaults to the most recently
6797 stored link. As SPC triggers completion in the minibuffer, you need to
6798 use M-SPC or C-q SPC to force the insertion of a space character.
6800 You will also be prompted for a description, and if one is given, it will
6801 be displayed in the buffer instead of the link.
6803 If there is already a link at point, this command will allow you to edit link
6804 and description parts.
6806 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6807 be selected using completion. The path to the file will be relative to the
6808 current directory if the file is in the current directory or a subdirectory.
6809 Otherwise, the link will be the absolute path as completed in the minibuffer
6810 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6811 option `org-link-file-path-type'.
6813 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6814 the current directory or below.
6816 With three \\[universal-argument] prefixes, negate the meaning of
6817 `org-keep-stored-link-after-insertion'.
6819 If `org-make-link-description-function' is non-nil, this function will be
6820 called with the link target, and the result will be the default
6821 link description.
6823 If the LINK-LOCATION parameter is non-nil, this value will be
6824 used as the link location instead of reading one interactively."
6825 (interactive "P")
6826 (let* ((wcf (current-window-configuration))
6827 (region (if (org-region-active-p)
6828 (buffer-substring (region-beginning) (region-end))))
6829 (remove (and region (list (region-beginning) (region-end))))
6830 (desc region)
6831 tmphist ; byte-compile incorrectly complains about this
6832 (link link-location)
6833 entry file)
6834 (cond
6835 (link-location) ; specified by arg, just use it.
6836 ((org-in-regexp org-bracket-link-regexp 1)
6837 ;; We do have a link at point, and we are going to edit it.
6838 (setq remove (list (match-beginning 0) (match-end 0)))
6839 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6840 (setq link (read-string "Link: "
6841 (org-link-unescape
6842 (org-match-string-no-properties 1)))))
6843 ((or (org-in-regexp org-angle-link-re)
6844 (org-in-regexp org-plain-link-re))
6845 ;; Convert to bracket link
6846 (setq remove (list (match-beginning 0) (match-end 0))
6847 link (read-string "Link: "
6848 (org-remove-angle-brackets (match-string 0)))))
6849 ((member complete-file '((4) (16)))
6850 ;; Completing read for file names.
6851 (setq file (read-file-name "File: "))
6852 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6853 (pwd1 (file-name-as-directory (abbreviate-file-name
6854 (expand-file-name ".")))))
6855 (cond
6856 ((equal complete-file '(16))
6857 (setq link (org-make-link
6858 "file:"
6859 (abbreviate-file-name (expand-file-name file)))))
6860 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6861 (setq link (org-make-link "file:" (match-string 1 file))))
6862 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6863 (expand-file-name file))
6864 (setq link (org-make-link
6865 "file:" (match-string 1 (expand-file-name file)))))
6866 (t (setq link (org-make-link "file:" file))))))
6868 ;; Read link, with completion for stored links.
6869 (with-output-to-temp-buffer "*Org Links*"
6870 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6871 (when org-stored-links
6872 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6873 (princ (mapconcat
6874 (lambda (x)
6875 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6876 (reverse org-stored-links) "\n"))))
6877 (let ((cw (selected-window)))
6878 (select-window (get-buffer-window "*Org Links*"))
6879 (setq truncate-lines t)
6880 (org-fit-window-to-buffer)
6881 (select-window cw))
6882 ;; Fake a link history, containing the stored links.
6883 (setq tmphist (append (mapcar 'car org-stored-links)
6884 org-insert-link-history))
6885 (unwind-protect
6886 (setq link
6887 (let ((org-completion-use-ido nil))
6888 (org-completing-read
6889 "Link: "
6890 (append
6891 (mapcar (lambda (x) (list (concat (car x) ":")))
6892 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6893 (mapcar (lambda (x) (list (concat x ":")))
6894 org-link-types))
6895 nil nil nil
6896 'tmphist
6897 (or (car (car org-stored-links))))))
6898 (set-window-configuration wcf)
6899 (kill-buffer "*Org Links*"))
6900 (setq entry (assoc link org-stored-links))
6901 (or entry (push link org-insert-link-history))
6902 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6903 (not org-keep-stored-link-after-insertion))
6904 (setq org-stored-links (delq (assoc link org-stored-links)
6905 org-stored-links)))
6906 (setq desc (or desc (nth 1 entry)))))
6908 (if (string-match org-plain-link-re link)
6909 ;; URL-like link, normalize the use of angular brackets.
6910 (setq link (org-make-link (org-remove-angle-brackets link))))
6912 ;; Check if we are linking to the current file with a search option
6913 ;; If yes, simplify the link by using only the search option.
6914 (when (and buffer-file-name
6915 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6916 (let* ((path (match-string 1 link))
6917 (case-fold-search nil)
6918 (search (match-string 2 link)))
6919 (save-match-data
6920 (if (equal (file-truename buffer-file-name) (file-truename path))
6921 ;; We are linking to this same file, with a search option
6922 (setq link search)))))
6924 ;; Check if we can/should use a relative path. If yes, simplify the link
6925 (when (string-match "^file:\\(.*\\)" link)
6926 (let* ((path (match-string 1 link))
6927 (origpath path)
6928 (case-fold-search nil))
6929 (cond
6930 ((or (eq org-link-file-path-type 'absolute)
6931 (equal complete-file '(16)))
6932 (setq path (abbreviate-file-name (expand-file-name path))))
6933 ((eq org-link-file-path-type 'noabbrev)
6934 (setq path (expand-file-name path)))
6935 ((eq org-link-file-path-type 'relative)
6936 (setq path (file-relative-name path)))
6938 (save-match-data
6939 (if (string-match (concat "^" (regexp-quote
6940 (file-name-as-directory
6941 (expand-file-name "."))))
6942 (expand-file-name path))
6943 ;; We are linking a file with relative path name.
6944 (setq path (substring (expand-file-name path)
6945 (match-end 0)))
6946 (setq path (abbreviate-file-name (expand-file-name path)))))))
6947 (setq link (concat "file:" path))
6948 (if (equal desc origpath)
6949 (setq desc path))))
6951 (if org-make-link-description-function
6952 (setq desc (funcall org-make-link-description-function link desc)))
6954 (setq desc (read-string "Description: " desc))
6955 (unless (string-match "\\S-" desc) (setq desc nil))
6956 (if remove (apply 'delete-region remove))
6957 (insert (org-make-link-string link desc))))
6959 (defun org-completing-read (&rest args)
6960 "Completing-read with SPACE being a normal character."
6961 (let ((minibuffer-local-completion-map
6962 (copy-keymap minibuffer-local-completion-map)))
6963 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6964 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
6965 (apply 'org-ido-completing-read args)))
6967 (defun org-ido-completing-read (&rest args)
6968 "Completing-read using `ido-mode' speedups if available"
6969 (if (and org-completion-use-ido
6970 (fboundp 'ido-completing-read)
6971 (boundp 'ido-mode) ido-mode
6972 (listp (second args)))
6973 (apply 'ido-completing-read (concat (car args)) (cdr args))
6974 (apply 'completing-read args)))
6976 (defun org-extract-attributes (s)
6977 "Extract the attributes cookie from a string and set as text property."
6978 (let (a attr (start 0) key value)
6979 (save-match-data
6980 (when (string-match "{{\\([^}]+\\)}}$" s)
6981 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6982 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6983 (setq key (match-string 1 a) value (match-string 2 a)
6984 start (match-end 0)
6985 attr (plist-put attr (intern key) value))))
6986 (org-add-props s nil 'org-attr attr))
6989 (defun org-attributes-to-string (plist)
6990 "Format a property list into an HTML attribute list."
6991 (let ((s "") key value)
6992 (while plist
6993 (setq key (pop plist) value (pop plist))
6994 (and value
6995 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6998 ;;; Opening/following a link
7000 (defvar org-link-search-failed nil)
7002 (defun org-next-link ()
7003 "Move forward to the next link.
7004 If the link is in hidden text, expose it."
7005 (interactive)
7006 (when (and org-link-search-failed (eq this-command last-command))
7007 (goto-char (point-min))
7008 (message "Link search wrapped back to beginning of buffer"))
7009 (setq org-link-search-failed nil)
7010 (let* ((pos (point))
7011 (ct (org-context))
7012 (a (assoc :link ct)))
7013 (if a (goto-char (nth 2 a)))
7014 (if (re-search-forward org-any-link-re nil t)
7015 (progn
7016 (goto-char (match-beginning 0))
7017 (if (org-invisible-p) (org-show-context)))
7018 (goto-char pos)
7019 (setq org-link-search-failed t)
7020 (error "No further link found"))))
7022 (defun org-previous-link ()
7023 "Move backward to the previous link.
7024 If the link is in hidden text, expose it."
7025 (interactive)
7026 (when (and org-link-search-failed (eq this-command last-command))
7027 (goto-char (point-max))
7028 (message "Link search wrapped back to end of buffer"))
7029 (setq org-link-search-failed nil)
7030 (let* ((pos (point))
7031 (ct (org-context))
7032 (a (assoc :link ct)))
7033 (if a (goto-char (nth 1 a)))
7034 (if (re-search-backward org-any-link-re nil t)
7035 (progn
7036 (goto-char (match-beginning 0))
7037 (if (org-invisible-p) (org-show-context)))
7038 (goto-char pos)
7039 (setq org-link-search-failed t)
7040 (error "No further link found"))))
7042 (defun org-translate-link (s)
7043 "Translate a link string if a translation function has been defined."
7044 (if (and org-link-translation-function
7045 (fboundp org-link-translation-function)
7046 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7047 (progn
7048 (setq s (funcall org-link-translation-function
7049 (match-string 1) (match-string 2)))
7050 (concat (car s) ":" (cdr s)))
7053 (defun org-translate-link-from-planner (type path)
7054 "Translate a link from Emacs Planner syntax so that Org can follow it.
7055 This is still an experimental function, your mileage may vary."
7056 (cond
7057 ((member type '("http" "https" "news" "ftp"))
7058 ;; standard Internet links are the same.
7059 nil)
7060 ((and (equal type "irc") (string-match "^//" path))
7061 ;; Planner has two / at the beginning of an irc link, we have 1.
7062 ;; We should have zero, actually....
7063 (setq path (substring path 1)))
7064 ((and (equal type "lisp") (string-match "^/" path))
7065 ;; Planner has a slash, we do not.
7066 (setq type "elisp" path (substring path 1)))
7067 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7068 ;; A typical message link. Planner has the id after the fina slash,
7069 ;; we separate it with a hash mark
7070 (setq path (concat (match-string 1 path) "#"
7071 (org-remove-angle-brackets (match-string 2 path)))))
7073 (cons type path))
7075 (defun org-find-file-at-mouse (ev)
7076 "Open file link or URL at mouse."
7077 (interactive "e")
7078 (mouse-set-point ev)
7079 (org-open-at-point 'in-emacs))
7081 (defun org-open-at-mouse (ev)
7082 "Open file link or URL at mouse."
7083 (interactive "e")
7084 (mouse-set-point ev)
7085 (if (eq major-mode 'org-agenda-mode)
7086 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7087 (org-open-at-point))
7089 (defvar org-window-config-before-follow-link nil
7090 "The window configuration before following a link.
7091 This is saved in case the need arises to restore it.")
7093 (defvar org-open-link-marker (make-marker)
7094 "Marker pointing to the location where `org-open-at-point; was called.")
7096 ;;;###autoload
7097 (defun org-open-at-point-global ()
7098 "Follow a link like Org-mode does.
7099 This command can be called in any mode to follow a link that has
7100 Org-mode syntax."
7101 (interactive)
7102 (org-run-like-in-org-mode 'org-open-at-point))
7104 ;;;###autoload
7105 (defun org-open-link-from-string (s &optional arg)
7106 "Open a link in the string S, as if it was in Org-mode."
7107 (interactive "sLink: \nP")
7108 (with-temp-buffer
7109 (let ((org-inhibit-startup t))
7110 (org-mode)
7111 (insert s)
7112 (goto-char (point-min))
7113 (org-open-at-point arg))))
7115 (defun org-open-at-point (&optional in-emacs)
7116 "Open link at or after point.
7117 If there is no link at point, this function will search forward up to
7118 the end of the current subtree.
7119 Normally, files will be opened by an appropriate application. If the
7120 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7121 With a double prefix argument, try to open outside of Emacs, in the
7122 application the system uses for this file type."
7123 (interactive "P")
7124 (org-load-modules-maybe)
7125 (move-marker org-open-link-marker (point))
7126 (setq org-window-config-before-follow-link (current-window-configuration))
7127 (org-remove-occur-highlights nil nil t)
7128 (cond
7129 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7130 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7131 (org-footnote-action))
7133 (let (type path link line search (pos (point)))
7134 (catch 'match
7135 (save-excursion
7136 (skip-chars-forward "^]\n\r")
7137 (when (org-in-regexp org-bracket-link-regexp)
7138 (setq link (org-extract-attributes
7139 (org-link-unescape (org-match-string-no-properties 1))))
7140 (while (string-match " *\n *" link)
7141 (setq link (replace-match " " t t link)))
7142 (setq link (org-link-expand-abbrev link))
7143 (cond
7144 ((or (file-name-absolute-p link)
7145 (string-match "^\\.\\.?/" link))
7146 (setq type "file" path link))
7147 ((string-match org-link-re-with-space3 link)
7148 (setq type (match-string 1 link) path (match-string 2 link)))
7149 (t (setq type "thisfile" path link)))
7150 (throw 'match t)))
7152 (when (get-text-property (point) 'org-linked-text)
7153 (setq type "thisfile"
7154 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7155 (1+ (point)) (point))
7156 path (buffer-substring
7157 (previous-single-property-change pos 'org-linked-text)
7158 (next-single-property-change pos 'org-linked-text)))
7159 (throw 'match t))
7161 (save-excursion
7162 (when (or (org-in-regexp org-angle-link-re)
7163 (org-in-regexp org-plain-link-re))
7164 (setq type (match-string 1) path (match-string 2))
7165 (throw 'match t)))
7166 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7167 (setq type "tree-match"
7168 path (match-string 1))
7169 (throw 'match t))
7170 (save-excursion
7171 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7172 (setq type "tags"
7173 path (match-string 1))
7174 (while (string-match ":" path)
7175 (setq path (replace-match "+" t t path)))
7176 (throw 'match t))))
7177 (unless path
7178 (error "No link found"))
7179 ;; Remove any trailing spaces in path
7180 (if (string-match " +\\'" path)
7181 (setq path (replace-match "" t t path)))
7182 (if (and org-link-translation-function
7183 (fboundp org-link-translation-function))
7184 ;; Check if we need to translate the link
7185 (let ((tmp (funcall org-link-translation-function type path)))
7186 (setq type (car tmp) path (cdr tmp))))
7188 (cond
7190 ((assoc type org-link-protocols)
7191 (funcall (nth 1 (assoc type org-link-protocols)) path))
7193 ((equal type "mailto")
7194 (let ((cmd (car org-link-mailto-program))
7195 (args (cdr org-link-mailto-program)) args1
7196 (address path) (subject "") a)
7197 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7198 (setq address (match-string 1 path)
7199 subject (org-link-escape (match-string 2 path))))
7200 (while args
7201 (cond
7202 ((not (stringp (car args))) (push (pop args) args1))
7203 (t (setq a (pop args))
7204 (if (string-match "%a" a)
7205 (setq a (replace-match address t t a)))
7206 (if (string-match "%s" a)
7207 (setq a (replace-match subject t t a)))
7208 (push a args1))))
7209 (apply cmd (nreverse args1))))
7211 ((member type '("http" "https" "ftp" "news"))
7212 (browse-url (concat type ":" (org-link-escape
7213 path org-link-escape-chars-browser))))
7215 ((member type '("message"))
7216 (browse-url (concat type ":" path)))
7218 ((string= type "tags")
7219 (org-tags-view in-emacs path))
7220 ((string= type "thisfile")
7221 (if in-emacs
7222 (switch-to-buffer-other-window
7223 (org-get-buffer-for-internal-link (current-buffer)))
7224 (org-mark-ring-push))
7225 (let ((cmd `(org-link-search
7226 ,path
7227 ,(cond ((equal in-emacs '(4)) 'occur)
7228 ((equal in-emacs '(16)) 'org-occur)
7229 (t nil))
7230 ,pos)))
7231 (condition-case nil (eval cmd)
7232 (error (progn (widen) (eval cmd))))))
7234 ((string= type "tree-match")
7235 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7237 ((string= type "file")
7238 (if (string-match "::\\([0-9]+\\)\\'" path)
7239 (setq line (string-to-number (match-string 1 path))
7240 path (substring path 0 (match-beginning 0)))
7241 (if (string-match "::\\(.+\\)\\'" path)
7242 (setq search (match-string 1 path)
7243 path (substring path 0 (match-beginning 0)))))
7244 (if (string-match "[*?{]" (file-name-nondirectory path))
7245 (dired path)
7246 (org-open-file path in-emacs line search)))
7248 ((string= type "news")
7249 (require 'org-gnus)
7250 (org-gnus-follow-link path))
7252 ((string= type "shell")
7253 (let ((cmd path))
7254 (if (or (not org-confirm-shell-link-function)
7255 (funcall org-confirm-shell-link-function
7256 (format "Execute \"%s\" in shell? "
7257 (org-add-props cmd nil
7258 'face 'org-warning))))
7259 (progn
7260 (message "Executing %s" cmd)
7261 (shell-command cmd))
7262 (error "Abort"))))
7264 ((string= type "elisp")
7265 (let ((cmd path))
7266 (if (or (not org-confirm-elisp-link-function)
7267 (funcall org-confirm-elisp-link-function
7268 (format "Execute \"%s\" as elisp? "
7269 (org-add-props cmd nil
7270 'face 'org-warning))))
7271 (message "%s => %s" cmd
7272 (if (equal (string-to-char cmd) ?\()
7273 (eval (read cmd))
7274 (call-interactively (read cmd))))
7275 (error "Abort"))))
7278 (browse-url-at-point))))))
7279 (move-marker org-open-link-marker nil)
7280 (run-hook-with-args 'org-follow-link-hook))
7282 ;;;; Time estimates
7284 (defun org-get-effort (&optional pom)
7285 "Get the effort estimate for the current entry."
7286 (org-entry-get pom org-effort-property))
7288 ;;; File search
7290 (defvar org-create-file-search-functions nil
7291 "List of functions to construct the right search string for a file link.
7292 These functions are called in turn with point at the location to
7293 which the link should point.
7295 A function in the hook should first test if it would like to
7296 handle this file type, for example by checking the major-mode or
7297 the file extension. If it decides not to handle this file, it
7298 should just return nil to give other functions a chance. If it
7299 does handle the file, it must return the search string to be used
7300 when following the link. The search string will be part of the
7301 file link, given after a double colon, and `org-open-at-point'
7302 will automatically search for it. If special measures must be
7303 taken to make the search successful, another function should be
7304 added to the companion hook `org-execute-file-search-functions',
7305 which see.
7307 A function in this hook may also use `setq' to set the variable
7308 `description' to provide a suggestion for the descriptive text to
7309 be used for this link when it gets inserted into an Org-mode
7310 buffer with \\[org-insert-link].")
7312 (defvar org-execute-file-search-functions nil
7313 "List of functions to execute a file search triggered by a link.
7315 Functions added to this hook must accept a single argument, the
7316 search string that was part of the file link, the part after the
7317 double colon. The function must first check if it would like to
7318 handle this search, for example by checking the major-mode or the
7319 file extension. If it decides not to handle this search, it
7320 should just return nil to give other functions a chance. If it
7321 does handle the search, it must return a non-nil value to keep
7322 other functions from trying.
7324 Each function can access the current prefix argument through the
7325 variable `current-prefix-argument'. Note that a single prefix is
7326 used to force opening a link in Emacs, so it may be good to only
7327 use a numeric or double prefix to guide the search function.
7329 In case this is needed, a function in this hook can also restore
7330 the window configuration before `org-open-at-point' was called using:
7332 (set-window-configuration org-window-config-before-follow-link)")
7334 (defun org-link-search (s &optional type avoid-pos)
7335 "Search for a link search option.
7336 If S is surrounded by forward slashes, it is interpreted as a
7337 regular expression. In org-mode files, this will create an `org-occur'
7338 sparse tree. In ordinary files, `occur' will be used to list matches.
7339 If the current buffer is in `dired-mode', grep will be used to search
7340 in all files. If AVOID-POS is given, ignore matches near that position."
7341 (let ((case-fold-search t)
7342 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7343 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7344 (append '(("") (" ") ("\t") ("\n"))
7345 org-emphasis-alist)
7346 "\\|") "\\)"))
7347 (pos (point))
7348 (pre nil) (post nil)
7349 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7350 (cond
7351 ;; First check if there are any special
7352 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7353 ;; Now try the builtin stuff
7354 ((save-excursion
7355 (goto-char (point-min))
7356 (and
7357 (re-search-forward
7358 (concat "<<" (regexp-quote s0) ">>") nil t)
7359 (setq type 'dedicated
7360 pos (match-beginning 0))))
7361 ;; There is an exact target for this
7362 (goto-char pos))
7363 ((and (string-match "^(\\(.*\\))$" s0)
7364 (save-excursion
7365 (goto-char (point-min))
7366 (and
7367 (re-search-forward
7368 (concat "[^[]" (regexp-quote
7369 (format org-coderef-label-format
7370 (match-string 1 s0))))
7371 nil t)
7372 (setq type 'dedicated
7373 pos (1+ (match-beginning 0))))))
7374 ;; There is a coderef target for this
7375 (goto-char pos))
7376 ((string-match "^/\\(.*\\)/$" s)
7377 ;; A regular expression
7378 (cond
7379 ((org-mode-p)
7380 (org-occur (match-string 1 s)))
7381 ;;((eq major-mode 'dired-mode)
7382 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7383 (t (org-do-occur (match-string 1 s)))))
7385 ;; A normal search strings
7386 (when (equal (string-to-char s) ?*)
7387 ;; Anchor on headlines, post may include tags.
7388 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7389 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7390 s (substring s 1)))
7391 (remove-text-properties
7392 0 (length s)
7393 '(face nil mouse-face nil keymap nil fontified nil) s)
7394 ;; Make a series of regular expressions to find a match
7395 (setq words (org-split-string s "[ \n\r\t]+")
7397 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7398 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7399 "\\)" markers)
7400 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7401 re2a (concat "[ \t\r\n]" re2a_)
7402 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7403 re4 (concat "[^a-zA-Z_]" re4_)
7405 re1 (concat pre re2 post)
7406 re3 (concat pre (if pre re4_ re4) post)
7407 re5 (concat pre ".*" re4)
7408 re2 (concat pre re2)
7409 re2a (concat pre (if pre re2a_ re2a))
7410 re4 (concat pre (if pre re4_ re4))
7411 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7412 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7413 re5 "\\)"
7415 (cond
7416 ((eq type 'org-occur) (org-occur reall))
7417 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7418 (t (goto-char (point-min))
7419 (setq type 'fuzzy)
7420 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7421 (org-search-not-self 1 re1 nil t)
7422 (org-search-not-self 1 re2 nil t)
7423 (org-search-not-self 1 re2a nil t)
7424 (org-search-not-self 1 re3 nil t)
7425 (org-search-not-self 1 re4 nil t)
7426 (org-search-not-self 1 re5 nil t)
7428 (goto-char (match-beginning 1))
7429 (goto-char pos)
7430 (error "No match")))))
7432 ;; Normal string-search
7433 (goto-char (point-min))
7434 (if (search-forward s nil t)
7435 (goto-char (match-beginning 0))
7436 (error "No match"))))
7437 (and (org-mode-p) (org-show-context 'link-search))
7438 type))
7440 (defun org-search-not-self (group &rest args)
7441 "Execute `re-search-forward', but only accept matches that do not
7442 enclose the position of `org-open-link-marker'."
7443 (let ((m org-open-link-marker))
7444 (catch 'exit
7445 (while (apply 're-search-forward args)
7446 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7447 (goto-char (match-end group))
7448 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7449 (> (match-beginning 0) (marker-position m))
7450 (< (match-end 0) (marker-position m)))
7451 (save-match-data
7452 (or (not (org-in-regexp
7453 org-bracket-link-analytic-regexp 1))
7454 (not (match-end 4)) ; no description
7455 (and (<= (match-beginning 4) (point))
7456 (>= (match-end 4) (point))))))
7457 (throw 'exit (point))))))))
7459 (defun org-get-buffer-for-internal-link (buffer)
7460 "Return a buffer to be used for displaying the link target of internal links."
7461 (cond
7462 ((not org-display-internal-link-with-indirect-buffer)
7463 buffer)
7464 ((string-match "(Clone)$" (buffer-name buffer))
7465 (message "Buffer is already a clone, not making another one")
7466 ;; we also do not modify visibility in this case
7467 buffer)
7468 (t ; make a new indirect buffer for displaying the link
7469 (let* ((bn (buffer-name buffer))
7470 (ibn (concat bn "(Clone)"))
7471 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7472 (with-current-buffer ib (org-overview))
7473 ib))))
7475 (defun org-do-occur (regexp &optional cleanup)
7476 "Call the Emacs command `occur'.
7477 If CLEANUP is non-nil, remove the printout of the regular expression
7478 in the *Occur* buffer. This is useful if the regex is long and not useful
7479 to read."
7480 (occur regexp)
7481 (when cleanup
7482 (let ((cwin (selected-window)) win beg end)
7483 (when (setq win (get-buffer-window "*Occur*"))
7484 (select-window win))
7485 (goto-char (point-min))
7486 (when (re-search-forward "match[a-z]+" nil t)
7487 (setq beg (match-end 0))
7488 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7489 (setq end (1- (match-beginning 0)))))
7490 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7491 (goto-char (point-min))
7492 (select-window cwin))))
7494 ;;; The mark ring for links jumps
7496 (defvar org-mark-ring nil
7497 "Mark ring for positions before jumps in Org-mode.")
7498 (defvar org-mark-ring-last-goto nil
7499 "Last position in the mark ring used to go back.")
7500 ;; Fill and close the ring
7501 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7502 (loop for i from 1 to org-mark-ring-length do
7503 (push (make-marker) org-mark-ring))
7504 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7505 org-mark-ring)
7507 (defun org-mark-ring-push (&optional pos buffer)
7508 "Put the current position or POS into the mark ring and rotate it."
7509 (interactive)
7510 (setq pos (or pos (point)))
7511 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7512 (move-marker (car org-mark-ring)
7513 (or pos (point))
7514 (or buffer (current-buffer)))
7515 (message "%s"
7516 (substitute-command-keys
7517 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7519 (defun org-mark-ring-goto (&optional n)
7520 "Jump to the previous position in the mark ring.
7521 With prefix arg N, jump back that many stored positions. When
7522 called several times in succession, walk through the entire ring.
7523 Org-mode commands jumping to a different position in the current file,
7524 or to another Org-mode file, automatically push the old position
7525 onto the ring."
7526 (interactive "p")
7527 (let (p m)
7528 (if (eq last-command this-command)
7529 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7530 (setq p org-mark-ring))
7531 (setq org-mark-ring-last-goto p)
7532 (setq m (car p))
7533 (switch-to-buffer (marker-buffer m))
7534 (goto-char m)
7535 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7537 (defun org-remove-angle-brackets (s)
7538 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7539 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7541 (defun org-add-angle-brackets (s)
7542 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7543 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7545 (defun org-remove-double-quotes (s)
7546 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7547 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7550 ;;; Following specific links
7552 (defun org-follow-timestamp-link ()
7553 (cond
7554 ((org-at-date-range-p t)
7555 (let ((org-agenda-start-on-weekday)
7556 (t1 (match-string 1))
7557 (t2 (match-string 2)))
7558 (setq t1 (time-to-days (org-time-string-to-time t1))
7559 t2 (time-to-days (org-time-string-to-time t2)))
7560 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7561 ((org-at-timestamp-p t)
7562 (org-agenda-list nil (time-to-days (org-time-string-to-time
7563 (substring (match-string 1) 0 10)))
7565 (t (error "This should not happen"))))
7568 ;;; Following file links
7569 (defvar org-wait nil)
7570 (defun org-open-file (path &optional in-emacs line search)
7571 "Open the file at PATH.
7572 First, this expands any special file name abbreviations. Then the
7573 configuration variable `org-file-apps' is checked if it contains an
7574 entry for this file type, and if yes, the corresponding command is launched.
7576 If no application is found, Emacs simply visits the file.
7578 With optional prefix argument IN-EMACS, Emacs will visit the file.
7579 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7580 and o use an external application to visit the file.
7582 Optional LINE specifies a line to go to, optional SEARCH a string to
7583 search for. If LINE or SEARCH is given, the file will always be
7584 opened in Emacs.
7585 If the file does not exist, an error is thrown."
7586 (setq in-emacs (or in-emacs line search))
7587 (let* ((file (if (equal path "")
7588 buffer-file-name
7589 (substitute-in-file-name (expand-file-name path))))
7590 (apps (append org-file-apps (org-default-apps)))
7591 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7592 (dirp (if remp nil (file-directory-p file)))
7593 (file (if (and dirp org-open-directory-means-index-dot-org)
7594 (concat (file-name-as-directory file) "index.org")
7595 file))
7596 (a-m-a-p (assq 'auto-mode apps))
7597 (dfile (downcase file))
7598 (old-buffer (current-buffer))
7599 (old-pos (point))
7600 (old-mode major-mode)
7601 ext cmd)
7602 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7603 (setq ext (match-string 1 dfile))
7604 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7605 (setq ext (match-string 1 dfile))))
7606 (cond
7607 ((equal in-emacs '(16))
7608 (setq cmd (cdr (assoc 'system apps))))
7609 (in-emacs (setq cmd 'emacs))
7611 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7612 (and dirp (cdr (assoc 'directory apps)))
7613 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7614 'string-match)
7615 (cdr (assoc ext apps))
7616 (cdr (assoc t apps))))))
7617 (when (eq cmd 'system)
7618 (setq cmd (cdr (assoc 'system apps))))
7619 (when (eq cmd 'default)
7620 (setq cmd (cdr (assoc t apps))))
7621 (when (eq cmd 'mailcap)
7622 (require 'mailcap)
7623 (mailcap-parse-mailcaps)
7624 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7625 (command (mailcap-mime-info mime-type)))
7626 (if (stringp command)
7627 (setq cmd command)
7628 (setq cmd 'emacs))))
7629 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7630 (not (file-exists-p file))
7631 (not org-open-non-existing-files))
7632 (error "No such file: %s" file))
7633 (cond
7634 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7635 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7636 (while (string-match "['\"]%s['\"]" cmd)
7637 (setq cmd (replace-match "%s" t t cmd)))
7638 (while (string-match "%s" cmd)
7639 (setq cmd (replace-match
7640 (save-match-data
7641 (shell-quote-argument
7642 (convert-standard-filename file)))
7643 t t cmd)))
7644 (save-window-excursion
7645 (start-process-shell-command cmd nil cmd)
7646 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7648 ((or (stringp cmd)
7649 (eq cmd 'emacs))
7650 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7651 (widen)
7652 (if line (goto-line line)
7653 (if search (org-link-search search))))
7654 ((consp cmd)
7655 (let ((file (convert-standard-filename file)))
7656 (eval cmd)))
7657 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7658 (and (org-mode-p) (eq old-mode 'org-mode)
7659 (or (not (equal old-buffer (current-buffer)))
7660 (not (equal old-pos (point))))
7661 (org-mark-ring-push old-pos old-buffer))))
7663 (defun org-default-apps ()
7664 "Return the default applications for this operating system."
7665 (cond
7666 ((eq system-type 'darwin)
7667 org-file-apps-defaults-macosx)
7668 ((eq system-type 'windows-nt)
7669 org-file-apps-defaults-windowsnt)
7670 (t org-file-apps-defaults-gnu)))
7672 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7673 "Convert extensions to regular expressions in the cars of LIST.
7674 Also, weed out any non-string entries, because the return value is used
7675 only for regexp matching.
7676 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7677 point to the symbol `emacs', indicating that the file should
7678 be opened in Emacs."
7679 (append
7680 (delq nil
7681 (mapcar (lambda (x)
7682 (if (not (stringp (car x)))
7684 (if (string-match "\\W" (car x))
7686 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7687 list))
7688 (if add-auto-mode
7689 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7691 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7692 (defun org-file-remote-p (file)
7693 "Test whether FILE specifies a location on a remote system.
7694 Return non-nil if the location is indeed remote.
7696 For example, the filename \"/user@host:/foo\" specifies a location
7697 on the system \"/user@host:\"."
7698 (cond ((fboundp 'file-remote-p)
7699 (file-remote-p file))
7700 ((fboundp 'tramp-handle-file-remote-p)
7701 (tramp-handle-file-remote-p file))
7702 ((and (boundp 'ange-ftp-name-format)
7703 (string-match (car ange-ftp-name-format) file))
7705 (t nil)))
7708 ;;;; Refiling
7710 (defun org-get-org-file ()
7711 "Read a filename, with default directory `org-directory'."
7712 (let ((default (or org-default-notes-file remember-data-file)))
7713 (read-file-name (format "File name [%s]: " default)
7714 (file-name-as-directory org-directory)
7715 default)))
7717 (defun org-notes-order-reversed-p ()
7718 "Check if the current file should receive notes in reversed order."
7719 (cond
7720 ((not org-reverse-note-order) nil)
7721 ((eq t org-reverse-note-order) t)
7722 ((not (listp org-reverse-note-order)) nil)
7723 (t (catch 'exit
7724 (let ((all org-reverse-note-order)
7725 entry)
7726 (while (setq entry (pop all))
7727 (if (string-match (car entry) buffer-file-name)
7728 (throw 'exit (cdr entry))))
7729 nil)))))
7731 (defvar org-refile-target-table nil
7732 "The list of refile targets, created by `org-refile'.")
7734 (defvar org-agenda-new-buffers nil
7735 "Buffers created to visit agenda files.")
7737 (defun org-get-refile-targets (&optional default-buffer)
7738 "Produce a table with refile targets."
7739 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7740 targets txt re files f desc descre fast-path-p level)
7741 (message "Getting targets...")
7742 (with-current-buffer (or default-buffer (current-buffer))
7743 (while (setq entry (pop entries))
7744 (setq files (car entry) desc (cdr entry))
7745 (setq fast-path-p nil)
7746 (cond
7747 ((null files) (setq files (list (current-buffer))))
7748 ((eq files 'org-agenda-files)
7749 (setq files (org-agenda-files 'unrestricted)))
7750 ((and (symbolp files) (fboundp files))
7751 (setq files (funcall files)))
7752 ((and (symbolp files) (boundp files))
7753 (setq files (symbol-value files))))
7754 (if (stringp files) (setq files (list files)))
7755 (cond
7756 ((eq (car desc) :tag)
7757 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7758 ((eq (car desc) :todo)
7759 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7760 ((eq (car desc) :regexp)
7761 (setq descre (cdr desc)))
7762 ((eq (car desc) :level)
7763 (setq descre (concat "^\\*\\{" (number-to-string
7764 (if org-odd-levels-only
7765 (1- (* 2 (cdr desc)))
7766 (cdr desc)))
7767 "\\}[ \t]")))
7768 ((eq (car desc) :maxlevel)
7769 (setq fast-path-p t)
7770 (setq descre (concat "^\\*\\{1," (number-to-string
7771 (if org-odd-levels-only
7772 (1- (* 2 (cdr desc)))
7773 (cdr desc)))
7774 "\\}[ \t]")))
7775 (t (error "Bad refiling target description %s" desc)))
7776 (while (setq f (pop files))
7777 (save-excursion
7778 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7779 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7780 (setq f (expand-file-name f))
7781 (save-excursion
7782 (save-restriction
7783 (widen)
7784 (goto-char (point-min))
7785 (while (re-search-forward descre nil t)
7786 (goto-char (point-at-bol))
7787 (when (looking-at org-complex-heading-regexp)
7788 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7789 txt (org-link-display-format (match-string 4))
7790 re (concat "^" (regexp-quote
7791 (buffer-substring (match-beginning 1)
7792 (match-end 4)))))
7793 (if (match-end 5) (setq re (concat re "[ \t]+"
7794 (regexp-quote
7795 (match-string 5)))))
7796 (setq re (concat re "[ \t]*$"))
7797 (when org-refile-use-outline-path
7798 (setq txt (mapconcat 'org-protect-slash
7799 (append
7800 (if (eq org-refile-use-outline-path 'file)
7801 (list (file-name-nondirectory
7802 (buffer-file-name (buffer-base-buffer))))
7803 (if (eq org-refile-use-outline-path 'full-file-path)
7804 (list (buffer-file-name (buffer-base-buffer)))))
7805 (org-get-outline-path fast-path-p level txt)
7806 (list txt))
7807 "/")))
7808 (push (list txt f re (point)) targets))
7809 (goto-char (point-at-eol))))))))
7810 (message "Getting targets...done")
7811 (nreverse targets))))
7813 (defun org-protect-slash (s)
7814 (while (string-match "/" s)
7815 (setq s (replace-match "\\" t t s)))
7818 (defvar org-olpa (make-vector 20 nil))
7820 (defun org-get-outline-path (&optional fastp level heading)
7821 "Return the outline path to the current entry, as a list."
7822 (if fastp
7823 (progn
7824 (if (> level 19)
7825 (error "Outline path failure, more than 19 levels."))
7826 (loop for i from level upto 19 do
7827 (aset org-olpa i nil))
7828 (prog1
7829 (delq nil (append org-olpa nil))
7830 (aset org-olpa level heading)))
7831 (let (rtn)
7832 (save-excursion
7833 (while (org-up-heading-safe)
7834 (when (looking-at org-complex-heading-regexp)
7835 (push (org-match-string-no-properties 4) rtn)))
7836 rtn))))
7838 (defvar org-refile-history nil
7839 "History for refiling operations.")
7841 (defun org-refile (&optional goto default-buffer)
7842 "Move the entry at point to another heading.
7843 The list of target headings is compiled using the information in
7844 `org-refile-targets', which see. This list is created before each use
7845 and will therefore always be up-to-date.
7847 At the target location, the entry is filed as a subitem of the target heading.
7848 Depending on `org-reverse-note-order', the new subitem will either be the
7849 first or the last subitem.
7851 If there is an active region, all entries in that region will be moved.
7852 However, the region must fulfil the requirement that the first heading
7853 is the first one sets the top-level of the moved text - at most siblings
7854 below it are allowed.
7856 With prefix arg GOTO, the command will only visit the target location,
7857 not actually move anything.
7858 With a double prefix `C-u C-u', go to the location where the last refiling
7859 operation has put the subtree."
7860 (interactive "P")
7861 (let* ((cbuf (current-buffer))
7862 (regionp (org-region-active-p))
7863 (region-start (and regionp (region-beginning)))
7864 (region-end (and regionp (region-end)))
7865 (region-length (and regionp (- region-end region-start)))
7866 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7867 pos it nbuf file re level reversed)
7868 (when regionp (goto-char region-start)
7869 (unless (org-kill-is-subtree-p
7870 (buffer-substring region-start region-end))
7871 (error "The region is not a (sequence of) subtree(s)")))
7872 (if (equal goto '(16))
7873 (org-refile-goto-last-stored)
7874 (when (setq it (org-refile-get-location
7875 (if goto "Goto: " "Refile to: ") default-buffer))
7876 (setq file (nth 1 it)
7877 re (nth 2 it)
7878 pos (nth 3 it))
7879 (if (and (equal (buffer-file-name) file)
7880 (if regionp
7881 (and (>= pos region-start)
7882 (<= pos region-end))
7883 (and (>= pos (point))
7884 (< pos (save-excursion
7885 (org-end-of-subtree t t))))))
7886 (error "Cannot refile to position inside the tree or region"))
7888 (setq nbuf (or (find-buffer-visiting file)
7889 (find-file-noselect file)))
7890 (if goto
7891 (progn
7892 (switch-to-buffer nbuf)
7893 (goto-char pos)
7894 (org-show-context 'org-goto))
7895 (if regionp
7896 (progn
7897 (kill-new (buffer-substring region-start region-end))
7898 (org-save-markers-in-region region-start region-end))
7899 (org-copy-subtree 1 nil t))
7900 (save-excursion
7901 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7902 (find-file-noselect file))))
7903 (setq reversed (org-notes-order-reversed-p))
7904 (save-excursion
7905 (save-restriction
7906 (widen)
7907 (goto-char pos)
7908 (looking-at outline-regexp)
7909 (setq level (org-get-valid-level (funcall outline-level) 1))
7910 (goto-char
7911 (if reversed
7912 (or (outline-next-heading) (point-max))
7913 (or (save-excursion (outline-get-next-sibling))
7914 (org-end-of-subtree t t)
7915 (point-max))))
7916 (if (not (bolp)) (newline))
7917 (bookmark-set "org-refile-last-stored")
7918 (org-paste-subtree level))))
7919 (if regionp
7920 (delete-region (point) (+ (point) region-length))
7921 (org-cut-subtree))
7922 (setq org-markers-to-move nil)
7923 (message "Refiled to \"%s\"" (car it)))))))
7925 (defun org-refile-goto-last-stored ()
7926 "Go to the location where the last refile was stored."
7927 (interactive)
7928 (bookmark-jump "org-refile-last-stored")
7929 (message "This is the location of the last refile"))
7931 (defun org-refile-get-location (&optional prompt default-buffer)
7932 "Prompt the user for a refile location, using PROMPT."
7933 (let ((org-refile-targets org-refile-targets)
7934 (org-refile-use-outline-path org-refile-use-outline-path))
7935 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7936 (unless org-refile-target-table
7937 (error "No refile targets"))
7938 (let* ((cbuf (current-buffer))
7939 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7940 (cfunc (if (and org-refile-use-outline-path
7941 org-outline-path-complete-in-steps)
7942 'org-olpath-completing-read
7943 'org-ido-completing-read))
7944 (extra (if org-refile-use-outline-path "/" ""))
7945 (filename (and cfn (expand-file-name cfn)))
7946 (tbl (mapcar
7947 (lambda (x)
7948 (if (not (equal filename (nth 1 x)))
7949 (cons (concat (car x) extra " ("
7950 (file-name-nondirectory (nth 1 x)) ")")
7951 (cdr x))
7952 (cons (concat (car x) extra) (cdr x))))
7953 org-refile-target-table))
7954 (completion-ignore-case t))
7955 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7956 tbl)))
7958 (defun org-olpath-completing-read (prompt collection &rest args)
7959 "Read an outline path like a file name."
7960 (let ((thetable collection))
7961 (apply
7962 'org-ido-completing-read prompt
7963 (lambda (string predicate &optional flag)
7964 (let (rtn r f (l (length string)))
7965 (cond
7966 ((eq flag nil)
7967 ;; try completion
7968 (try-completion string thetable))
7969 ((eq flag t)
7970 ;; all-completions
7971 (setq rtn (all-completions string thetable predicate))
7972 (mapcar
7973 (lambda (x)
7974 (setq r (substring x l))
7975 (if (string-match " ([^)]*)$" x)
7976 (setq f (match-string 0 x))
7977 (setq f ""))
7978 (if (string-match "/" r)
7979 (concat string (substring r 0 (match-end 0)) f)
7981 rtn))
7982 ((eq flag 'lambda)
7983 ;; exact match?
7984 (assoc string thetable)))
7986 args)))
7988 ;;;; Dynamic blocks
7990 (defun org-find-dblock (name)
7991 "Find the first dynamic block with name NAME in the buffer.
7992 If not found, stay at current position and return nil."
7993 (let (pos)
7994 (save-excursion
7995 (goto-char (point-min))
7996 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7997 nil t)
7998 (match-beginning 0))))
7999 (if pos (goto-char pos))
8000 pos))
8002 (defconst org-dblock-start-re
8003 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8004 "Matches the startline of a dynamic block, with parameters.")
8006 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8007 "Matches the end of a dynamic block.")
8009 (defun org-create-dblock (plist)
8010 "Create a dynamic block section, with parameters taken from PLIST.
8011 PLIST must contain a :name entry which is used as name of the block."
8012 (unless (bolp) (newline))
8013 (let ((name (plist-get plist :name)))
8014 (insert "#+BEGIN: " name)
8015 (while plist
8016 (if (eq (car plist) :name)
8017 (setq plist (cddr plist))
8018 (insert " " (prin1-to-string (pop plist)))))
8019 (insert "\n\n#+END:\n")
8020 (beginning-of-line -2)))
8022 (defun org-prepare-dblock ()
8023 "Prepare dynamic block for refresh.
8024 This empties the block, puts the cursor at the insert position and returns
8025 the property list including an extra property :name with the block name."
8026 (unless (looking-at org-dblock-start-re)
8027 (error "Not at a dynamic block"))
8028 (let* ((begdel (1+ (match-end 0)))
8029 (name (org-no-properties (match-string 1)))
8030 (params (append (list :name name)
8031 (read (concat "(" (match-string 3) ")")))))
8032 (unless (re-search-forward org-dblock-end-re nil t)
8033 (error "Dynamic block not terminated"))
8034 (setq params
8035 (append params
8036 (list :content (buffer-substring
8037 begdel (match-beginning 0)))))
8038 (delete-region begdel (match-beginning 0))
8039 (goto-char begdel)
8040 (open-line 1)
8041 params))
8043 (defun org-map-dblocks (&optional command)
8044 "Apply COMMAND to all dynamic blocks in the current buffer.
8045 If COMMAND is not given, use `org-update-dblock'."
8046 (let ((cmd (or command 'org-update-dblock))
8047 pos)
8048 (save-excursion
8049 (goto-char (point-min))
8050 (while (re-search-forward org-dblock-start-re nil t)
8051 (goto-char (setq pos (match-beginning 0)))
8052 (condition-case nil
8053 (funcall cmd)
8054 (error (message "Error during update of dynamic block")))
8055 (goto-char pos)
8056 (unless (re-search-forward org-dblock-end-re nil t)
8057 (error "Dynamic block not terminated"))))))
8059 (defun org-dblock-update (&optional arg)
8060 "User command for updating dynamic blocks.
8061 Update the dynamic block at point. With prefix ARG, update all dynamic
8062 blocks in the buffer."
8063 (interactive "P")
8064 (if arg
8065 (org-update-all-dblocks)
8066 (or (looking-at org-dblock-start-re)
8067 (org-beginning-of-dblock))
8068 (org-update-dblock)))
8070 (defun org-update-dblock ()
8071 "Update the dynamic block at point
8072 This means to empty the block, parse for parameters and then call
8073 the correct writing function."
8074 (save-window-excursion
8075 (let* ((pos (point))
8076 (line (org-current-line))
8077 (params (org-prepare-dblock))
8078 (name (plist-get params :name))
8079 (cmd (intern (concat "org-dblock-write:" name))))
8080 (message "Updating dynamic block `%s' at line %d..." name line)
8081 (funcall cmd params)
8082 (message "Updating dynamic block `%s' at line %d...done" name line)
8083 (goto-char pos))))
8085 (defun org-beginning-of-dblock ()
8086 "Find the beginning of the dynamic block at point.
8087 Error if there is no such block at point."
8088 (let ((pos (point))
8089 beg)
8090 (end-of-line 1)
8091 (if (and (re-search-backward org-dblock-start-re nil t)
8092 (setq beg (match-beginning 0))
8093 (re-search-forward org-dblock-end-re nil t)
8094 (> (match-end 0) pos))
8095 (goto-char beg)
8096 (goto-char pos)
8097 (error "Not in a dynamic block"))))
8099 (defun org-update-all-dblocks ()
8100 "Update all dynamic blocks in the buffer.
8101 This function can be used in a hook."
8102 (when (org-mode-p)
8103 (org-map-dblocks 'org-update-dblock)))
8106 ;;;; Completion
8108 (defconst org-additional-option-like-keywords
8109 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8110 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8111 "BEGIN_EXAMPLE" "END_EXAMPLE"
8112 "BEGIN_QUOTE" "END_QUOTE"
8113 "BEGIN_VERSE" "END_VERSE"
8114 "BEGIN_SRC" "END_SRC"
8115 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8117 (defcustom org-structure-template-alist
8119 ("s" "#+begin_src ?\n\n#+end_src"
8120 "<src lang=\"?\">\n\n</src>")
8121 ("e" "#+begin_example\n?\n#+end_example"
8122 "<example>\n?\n</example>")
8123 ("q" "#+begin_quote\n?\n#+end_quote"
8124 "<quote>\n?\n</quote>")
8125 ("v" "#+begin_verse\n?\n#+end_verse"
8126 "<verse>\n?\n/verse>")
8127 ("l" "#+begin_latex\n?\n#+end_latex"
8128 "<literal style=\"latex\">\n?\n</literal>")
8129 ("L" "#+latex: "
8130 "<literal style=\"latex\">?</literal>")
8131 ("h" "#+begin_html\n?\n#+end_html"
8132 "<literal style=\"html\">\n?\n</literal>")
8133 ("H" "#+html: "
8134 "<literal style=\"html\">?</literal>")
8135 ("a" "#+begin_ascii\n?\n#+end_ascii")
8136 ("A" "#+ascii: ")
8137 ("i" "#+include %file ?"
8138 "<include file=%file markup=\"?\">")
8140 "Structure completion elements.
8141 This is a list of abbreviation keys and values. The value gets inserted
8142 it you type @samp{.} followed by the key and then the completion key,
8143 usually `M-TAB'. %file will be replaced by a file name after prompting
8144 for the file using completion.
8145 There are two templates for each key, the first uses the original Org syntax,
8146 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8147 the default when the /org-mtags.el/ module has been loaded. See also the
8148 variable `org-mtags-prefer-muse-templates'.
8149 This is an experimental feature, it is undecided if it is going to stay in."
8150 :group 'org-completion
8151 :type '(repeat
8152 (string :tag "Key")
8153 (string :tag "Template")
8154 (string :tag "Muse Template")))
8156 (defun org-try-structure-completion ()
8157 "Try to complete a structure template before point.
8158 This looks for strings like \"<e\" on an otherwise empty line and
8159 expands them."
8160 (let ((l (buffer-substring (point-at-bol) (point)))
8162 (when (and (looking-at "[ \t]*$")
8163 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8164 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8165 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8166 (match-beginning 1)) a)
8167 t)))
8169 (defun org-complete-expand-structure-template (start cell)
8170 "Expand a structure template."
8171 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8172 (rpl (nth (if musep 2 1) cell)))
8173 (delete-region start (point))
8174 (when (string-match "\\`#\\+" rpl)
8175 (cond
8176 ((bolp))
8177 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8178 (delete-region (point-at-bol) (point)))
8179 (t (newline))))
8180 (setq start (point))
8181 (if (string-match "%file" rpl)
8182 (setq rpl (replace-match
8183 (concat
8184 "\""
8185 (save-match-data
8186 (abbreviate-file-name (read-file-name "Include file: ")))
8187 "\"")
8188 t t rpl)))
8189 (insert rpl)
8190 (if (re-search-backward "\\?" start t) (delete-char 1))))
8193 (defun org-complete (&optional arg)
8194 "Perform completion on word at point.
8195 At the beginning of a headline, this completes TODO keywords as given in
8196 `org-todo-keywords'.
8197 If the current word is preceded by a backslash, completes the TeX symbols
8198 that are supported for HTML support.
8199 If the current word is preceded by \"#+\", completes special words for
8200 setting file options.
8201 In the line after \"#+STARTUP:, complete valid keywords.\"
8202 At all other locations, this simply calls the value of
8203 `org-completion-fallback-command'."
8204 (interactive "P")
8205 (org-without-partial-completion
8206 (catch 'exit
8207 (let* ((a nil)
8208 (end (point))
8209 (beg1 (save-excursion
8210 (skip-chars-backward (org-re "[:alnum:]_@"))
8211 (point)))
8212 (beg (save-excursion
8213 (skip-chars-backward "a-zA-Z0-9_:$")
8214 (point)))
8215 (confirm (lambda (x) (stringp (car x))))
8216 (searchhead (equal (char-before beg) ?*))
8217 (struct
8218 (when (and (member (char-before beg1) '(?. ?<))
8219 (setq a (assoc (buffer-substring beg1 (point))
8220 org-structure-template-alist)))
8221 (org-complete-expand-structure-template (1- beg1) a)
8222 (throw 'exit t)))
8223 (tag (and (equal (char-before beg1) ?:)
8224 (equal (char-after (point-at-bol)) ?*)))
8225 (prop (and (equal (char-before beg1) ?:)
8226 (not (equal (char-after (point-at-bol)) ?*))))
8227 (texp (equal (char-before beg) ?\\))
8228 (link (equal (char-before beg) ?\[))
8229 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8230 beg)
8231 "#+"))
8232 (startup (string-match "^#\\+STARTUP:.*"
8233 (buffer-substring (point-at-bol) (point))))
8234 (completion-ignore-case opt)
8235 (type nil)
8236 (tbl nil)
8237 (table (cond
8238 (opt
8239 (setq type :opt)
8240 (require 'org-exp)
8241 (append
8242 (mapcar
8243 (lambda (x)
8244 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8245 (cons (match-string 2 x) (match-string 1 x)))
8246 (org-split-string (org-get-current-options) "\n"))
8247 (mapcar 'list org-additional-option-like-keywords)))
8248 (startup
8249 (setq type :startup)
8250 org-startup-options)
8251 (link (append org-link-abbrev-alist-local
8252 org-link-abbrev-alist))
8253 (texp
8254 (setq type :tex)
8255 org-html-entities)
8256 ((string-match "\\`\\*+[ \t]+\\'"
8257 (buffer-substring (point-at-bol) beg))
8258 (setq type :todo)
8259 (mapcar 'list org-todo-keywords-1))
8260 (searchhead
8261 (setq type :searchhead)
8262 (save-excursion
8263 (goto-char (point-min))
8264 (while (re-search-forward org-todo-line-regexp nil t)
8265 (push (list
8266 (org-make-org-heading-search-string
8267 (match-string 3) t))
8268 tbl)))
8269 tbl)
8270 (tag (setq type :tag beg beg1)
8271 (or org-tag-alist (org-get-buffer-tags)))
8272 (prop (setq type :prop beg beg1)
8273 (mapcar 'list (org-buffer-property-keys nil t t)))
8274 (t (progn
8275 (call-interactively org-completion-fallback-command)
8276 (throw 'exit nil)))))
8277 (pattern (buffer-substring-no-properties beg end))
8278 (completion (try-completion pattern table confirm)))
8279 (cond ((eq completion t)
8280 (if (not (assoc (upcase pattern) table))
8281 (message "Already complete")
8282 (if (and (equal type :opt)
8283 (not (member (car (assoc (upcase pattern) table))
8284 org-additional-option-like-keywords)))
8285 (insert (substring (cdr (assoc (upcase pattern) table))
8286 (length pattern)))
8287 (if (memq type '(:tag :prop)) (insert ":")))))
8288 ((null completion)
8289 (message "Can't find completion for \"%s\"" pattern)
8290 (ding))
8291 ((not (string= pattern completion))
8292 (delete-region beg end)
8293 (if (string-match " +$" completion)
8294 (setq completion (replace-match "" t t completion)))
8295 (insert completion)
8296 (if (get-buffer-window "*Completions*")
8297 (delete-window (get-buffer-window "*Completions*")))
8298 (if (assoc completion table)
8299 (if (eq type :todo) (insert " ")
8300 (if (memq type '(:tag :prop)) (insert ":"))))
8301 (if (and (equal type :opt) (assoc completion table))
8302 (message "%s" (substitute-command-keys
8303 "Press \\[org-complete] again to insert example settings"))))
8305 (message "Making completion list...")
8306 (let ((list (sort (all-completions pattern table confirm)
8307 'string<)))
8308 (with-output-to-temp-buffer "*Completions*"
8309 (condition-case nil
8310 ;; Protection needed for XEmacs and emacs 21
8311 (display-completion-list list pattern)
8312 (error (display-completion-list list)))))
8313 (message "Making completion list...%s" "done")))))))
8315 ;;;; TODO, DEADLINE, Comments
8317 (defun org-toggle-comment ()
8318 "Change the COMMENT state of an entry."
8319 (interactive)
8320 (save-excursion
8321 (org-back-to-heading)
8322 (let (case-fold-search)
8323 (if (looking-at (concat outline-regexp
8324 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8325 (replace-match "" t t nil 1)
8326 (if (looking-at outline-regexp)
8327 (progn
8328 (goto-char (match-end 0))
8329 (insert org-comment-string " ")))))))
8331 (defvar org-last-todo-state-is-todo nil
8332 "This is non-nil when the last TODO state change led to a TODO state.
8333 If the last change removed the TODO tag or switched to DONE, then
8334 this is nil.")
8336 (defvar org-setting-tags nil) ; dynamically skipped
8338 (defun org-parse-local-options (string var)
8339 "Parse STRING for startup setting relevant for variable VAR."
8340 (let ((rtn (symbol-value var))
8341 e opts)
8342 (save-match-data
8343 (if (or (not string) (not (string-match "\\S-" string)))
8345 (setq opts (delq nil (mapcar (lambda (x)
8346 (setq e (assoc x org-startup-options))
8347 (if (eq (nth 1 e) var) e nil))
8348 (org-split-string string "[ \t]+"))))
8349 (if (not opts)
8351 (setq rtn nil)
8352 (while (setq e (pop opts))
8353 (if (not (nth 3 e))
8354 (setq rtn (nth 2 e))
8355 (if (not (listp rtn)) (setq rtn nil))
8356 (push (nth 2 e) rtn)))
8357 rtn)))))
8359 (defvar org-agenda-headline-snapshot-before-repeat)
8360 (defun org-todo (&optional arg)
8361 "Change the TODO state of an item.
8362 The state of an item is given by a keyword at the start of the heading,
8363 like
8364 *** TODO Write paper
8365 *** DONE Call mom
8367 The different keywords are specified in the variable `org-todo-keywords'.
8368 By default the available states are \"TODO\" and \"DONE\".
8369 So for this example: when the item starts with TODO, it is changed to DONE.
8370 When it starts with DONE, the DONE is removed. And when neither TODO nor
8371 DONE are present, add TODO at the beginning of the heading.
8373 With C-u prefix arg, use completion to determine the new state.
8374 With numeric prefix arg, switch to that state.
8375 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8376 With a tripple C-u prefix, circumvent any state blocking.
8378 For calling through lisp, arg is also interpreted in the following way:
8379 'none -> empty state
8380 \"\"(empty string) -> switch to empty state
8381 'done -> switch to DONE
8382 'nextset -> switch to the next set of keywords
8383 'previousset -> switch to the previous set of keywords
8384 \"WAITING\" -> switch to the specified keyword, but only if it
8385 really is a member of `org-todo-keywords'."
8386 (interactive "P")
8387 (if (equal arg '(16)) (setq arg 'nextset))
8388 (let ((org-blocker-hook org-blocker-hook))
8389 (when (equal arg '(64))
8390 (setq arg nil org-blocker-hook nil))
8391 (save-excursion
8392 (catch 'exit
8393 (org-back-to-heading)
8394 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8395 (or (looking-at (concat " +" org-todo-regexp " *"))
8396 (looking-at " *"))
8397 (let* ((match-data (match-data))
8398 (startpos (point-at-bol))
8399 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8400 (org-log-done org-log-done)
8401 (org-log-repeat org-log-repeat)
8402 (org-todo-log-states org-todo-log-states)
8403 (this (match-string 1))
8404 (hl-pos (match-beginning 0))
8405 (head (org-get-todo-sequence-head this))
8406 (ass (assoc head org-todo-kwd-alist))
8407 (interpret (nth 1 ass))
8408 (done-word (nth 3 ass))
8409 (final-done-word (nth 4 ass))
8410 (last-state (or this ""))
8411 (completion-ignore-case t)
8412 (member (member this org-todo-keywords-1))
8413 (tail (cdr member))
8414 (state (cond
8415 ((and org-todo-key-trigger
8416 (or (and (equal arg '(4))
8417 (eq org-use-fast-todo-selection 'prefix))
8418 (and (not arg) org-use-fast-todo-selection
8419 (not (eq org-use-fast-todo-selection
8420 'prefix)))))
8421 ;; Use fast selection
8422 (org-fast-todo-selection))
8423 ((and (equal arg '(4))
8424 (or (not org-use-fast-todo-selection)
8425 (not org-todo-key-trigger)))
8426 ;; Read a state with completion
8427 (org-ido-completing-read
8428 "State: " (mapcar (lambda(x) (list x))
8429 org-todo-keywords-1)
8430 nil t))
8431 ((eq arg 'right)
8432 (if this
8433 (if tail (car tail) nil)
8434 (car org-todo-keywords-1)))
8435 ((eq arg 'left)
8436 (if (equal member org-todo-keywords-1)
8438 (if this
8439 (nth (- (length org-todo-keywords-1)
8440 (length tail) 2)
8441 org-todo-keywords-1)
8442 (org-last org-todo-keywords-1))))
8443 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8444 (setq arg nil))) ; hack to fall back to cycling
8445 (arg
8446 ;; user or caller requests a specific state
8447 (cond
8448 ((equal arg "") nil)
8449 ((eq arg 'none) nil)
8450 ((eq arg 'done) (or done-word (car org-done-keywords)))
8451 ((eq arg 'nextset)
8452 (or (car (cdr (member head org-todo-heads)))
8453 (car org-todo-heads)))
8454 ((eq arg 'previousset)
8455 (let ((org-todo-heads (reverse org-todo-heads)))
8456 (or (car (cdr (member head org-todo-heads)))
8457 (car org-todo-heads))))
8458 ((car (member arg org-todo-keywords-1)))
8459 ((nth (1- (prefix-numeric-value arg))
8460 org-todo-keywords-1))))
8461 ((null member) (or head (car org-todo-keywords-1)))
8462 ((equal this final-done-word) nil) ;; -> make empty
8463 ((null tail) nil) ;; -> first entry
8464 ((eq interpret 'sequence)
8465 (car tail))
8466 ((memq interpret '(type priority))
8467 (if (eq this-command last-command)
8468 (car tail)
8469 (if (> (length tail) 0)
8470 (or done-word (car org-done-keywords))
8471 nil)))
8472 (t nil)))
8473 (next (if state (concat " " state " ") " "))
8474 (change-plist (list :type 'todo-state-change :from this :to state
8475 :position startpos))
8476 dolog now-done-p)
8477 (when org-blocker-hook
8478 (setq org-last-todo-state-is-todo
8479 (not (member this org-done-keywords)))
8480 (unless (save-excursion
8481 (save-match-data
8482 (run-hook-with-args-until-failure
8483 'org-blocker-hook change-plist)))
8484 (if (interactive-p)
8485 (error "TODO state change from %s to %s blocked" this state)
8486 ;; fail silently
8487 (message "TODO state change from %s to %s blocked" this state)
8488 (throw 'exit nil))))
8489 (store-match-data match-data)
8490 (replace-match next t t)
8491 (unless (pos-visible-in-window-p hl-pos)
8492 (message "TODO state changed to %s" (org-trim next)))
8493 (unless head
8494 (setq head (org-get-todo-sequence-head state)
8495 ass (assoc head org-todo-kwd-alist)
8496 interpret (nth 1 ass)
8497 done-word (nth 3 ass)
8498 final-done-word (nth 4 ass)))
8499 (when (memq arg '(nextset previousset))
8500 (message "Keyword-Set %d/%d: %s"
8501 (- (length org-todo-sets) -1
8502 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8503 (length org-todo-sets)
8504 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8505 (setq org-last-todo-state-is-todo
8506 (not (member state org-done-keywords)))
8507 (setq now-done-p (and (member state org-done-keywords)
8508 (not (member this org-done-keywords))))
8509 (and logging (org-local-logging logging))
8510 (when (and (or org-todo-log-states org-log-done)
8511 (not (memq arg '(nextset previousset))))
8512 ;; we need to look at recording a time and note
8513 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8514 (nth 2 (assoc this org-todo-log-states))))
8515 (when (and state
8516 (member state org-not-done-keywords)
8517 (not (member this org-not-done-keywords)))
8518 ;; This is now a todo state and was not one before
8519 ;; If there was a CLOSED time stamp, get rid of it.
8520 (org-add-planning-info nil nil 'closed))
8521 (when (and now-done-p org-log-done)
8522 ;; It is now done, and it was not done before
8523 (org-add-planning-info 'closed (org-current-time))
8524 (if (and (not dolog) (eq 'note org-log-done))
8525 (org-add-log-setup 'done state 'findpos 'note)))
8526 (when (and state dolog)
8527 ;; This is a non-nil state, and we need to log it
8528 (org-add-log-setup 'state state 'findpos dolog)))
8529 ;; Fixup tag positioning
8530 (org-todo-trigger-tag-changes state)
8531 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8532 (when org-provide-todo-statistics
8533 (org-update-parent-todo-statistics))
8534 (run-hooks 'org-after-todo-state-change-hook)
8535 (if (and arg (not (member state org-done-keywords)))
8536 (setq head (org-get-todo-sequence-head state)))
8537 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8538 ;; Do we need to trigger a repeat?
8539 (when now-done-p
8540 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8541 ;; This is for the agenda, take a snapshot of the headline.
8542 (save-match-data
8543 (setq org-agenda-headline-snapshot-before-repeat
8544 (org-get-heading))))
8545 (org-auto-repeat-maybe state))
8546 ;; Fixup cursor location if close to the keyword
8547 (if (and (outline-on-heading-p)
8548 (not (bolp))
8549 (save-excursion (beginning-of-line 1)
8550 (looking-at org-todo-line-regexp))
8551 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8552 (progn
8553 (goto-char (or (match-end 2) (match-end 1)))
8554 (just-one-space)))
8555 (when org-trigger-hook
8556 (save-excursion
8557 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8559 (defun org-block-todo-from-children-or-siblings (change-plist)
8560 "Block turning an entry into a TODO, using the hierarchy.
8561 This checks whether the current task should be blocked from state
8562 changes. Such blocking occurs when:
8564 1. The task has children which are not all in a completed state.
8566 2. A task has a parent with the property :ORDERED:, and there
8567 are siblings prior to the current task with incomplete
8568 status."
8569 (catch 'dont-block
8570 ;; If this is not a todo state change, or if this entry is already DONE,
8571 ;; do not block
8572 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8573 (member (plist-get change-plist :from)
8574 (cons 'done org-done-keywords))
8575 (member (plist-get change-plist :to)
8576 (cons 'todo org-not-done-keywords)))
8577 (throw 'dont-block t))
8578 ;; If this task has children, and any are undone, it's blocked
8579 (save-excursion
8580 (org-back-to-heading t)
8581 (let ((this-level (funcall outline-level)))
8582 (outline-next-heading)
8583 (let ((child-level (funcall outline-level)))
8584 (while (and (not (eobp))
8585 (> child-level this-level))
8586 ;; this todo has children, check whether they are all
8587 ;; completed
8588 (if (and (not (org-entry-is-done-p))
8589 (org-entry-is-todo-p))
8590 (throw 'dont-block nil))
8591 (outline-next-heading)
8592 (setq child-level (funcall outline-level))))))
8593 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8594 ;; any previous siblings are undone, it's blocked
8595 (save-excursion
8596 (org-back-to-heading t)
8597 (when (save-excursion
8598 (ignore-errors
8599 (outline-up-heading 1)
8600 (org-entry-get (point) "ORDERED")))
8601 (let* ((this-level (funcall outline-level))
8602 (current-level this-level))
8603 (while (and (not (bobp))
8604 (= current-level this-level))
8605 (outline-previous-heading)
8606 (setq current-level (funcall outline-level))
8607 (if (= current-level this-level)
8608 ;; this todo has children, check whether they are all
8609 ;; completed
8610 (if (and (not (org-entry-is-done-p))
8611 (org-entry-is-todo-p))
8612 (throw 'dont-block nil)))))))
8613 t)) ; don't block
8615 (defun org-toggle-ordered-property ()
8616 "Toggle the ORDERED property of the current entry."
8617 (interactive)
8618 (save-excursion
8619 (org-back-to-heading)
8620 (if (org-entry-get nil "ORDERED")
8621 (progn
8622 (org-delete-property "ORDERED")
8623 (message "Subtasks can be completed in arbitrary order or parallel"))
8624 (org-entry-put nil "ORDERED" "t")
8625 (message "Subtasks must be completed in sequence"))))
8627 (defun org-block-todo-from-checkboxes (change-plist)
8628 "Block turning an entry into a TODO, using checkboxes.
8629 This checks whether the current task should be blocked from state
8630 changes because there are uncheckd boxes in this entry."
8631 (catch 'dont-block
8632 ;; If this is not a todo state change, or if this entry is already DONE,
8633 ;; do not block
8634 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8635 (member (plist-get change-plist :from)
8636 (cons 'done org-done-keywords))
8637 (member (plist-get change-plist :to)
8638 (cons 'todo org-not-done-keywords)))
8639 (throw 'dont-block t))
8640 ;; If this task has checkboxes that are not checked, it's blocked
8641 (save-excursion
8642 (org-back-to-heading t)
8643 (let ((beg (point)) end)
8644 (outline-next-heading)
8645 (setq end (point))
8646 (goto-char beg)
8647 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8648 end t)
8649 (throw 'dont-block nil))))
8650 t)) ; do not block
8652 (defun org-update-parent-todo-statistics ()
8653 "Update any statistics cookie in the parent of the current headline."
8654 (interactive)
8655 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8656 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
8657 (catch 'exit
8658 (save-excursion
8659 (setq level (org-up-heading-safe))
8660 (unless level
8661 (throw 'exit nil))
8662 (while (re-search-forward box-re (point-at-eol) t)
8663 (setq cnt-all 0 cnt-done 0 cookie-present t)
8664 (setq is-percent (match-end 2))
8665 (save-match-data
8666 (unless (outline-next-heading) (throw 'exit nil))
8667 (while (looking-at org-todo-line-regexp)
8668 (setq kwd (match-string 2))
8669 (and kwd (setq cnt-all (1+ cnt-all)))
8670 (and (member kwd org-done-keywords)
8671 (setq cnt-done (1+ cnt-done)))
8672 (condition-case nil
8673 (org-forward-same-level 1)
8674 (error (end-of-line 1)))))
8675 (replace-match
8676 (if is-percent
8677 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8678 (format "[%d/%d]" cnt-done cnt-all))))
8679 (when cookie-present
8680 (run-hook-with-args 'org-after-todo-statistics-hook
8681 cnt-done (- cnt-all cnt-done)))))))
8683 (defvar org-after-todo-statistics-hook nil
8684 "Hook that is called after a TODO statistics cookie has been updated.
8685 Each function is called with two arguments: the number of not-done entries
8686 and the number of done entries.
8688 For example, the following function, when added to this hook, will switch
8689 an entry to DONE when all children are done, and back to TODO when new
8690 entries are set to a TODO status. Note that this hook is only called
8691 when there is a statistics cookie in the headline!
8693 (defun org-summary-todo (n-done n-not-done)
8694 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8695 (let (org-log-done org-log-states) ; turn off logging
8696 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8699 (defun org-todo-trigger-tag-changes (state)
8700 "Apply the changes defined in `org-todo-state-tags-triggers'."
8701 (let ((l org-todo-state-tags-triggers)
8702 changes)
8703 (when (or (not state) (equal state ""))
8704 (setq changes (append changes (cdr (assoc "" l)))))
8705 (when (and (stringp state) (> (length state) 0))
8706 (setq changes (append changes (cdr (assoc state l)))))
8707 (when (member state org-not-done-keywords)
8708 (setq changes (append changes (cdr (assoc 'todo l)))))
8709 (when (member state org-done-keywords)
8710 (setq changes (append changes (cdr (assoc 'done l)))))
8711 (dolist (c changes)
8712 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8714 (defun org-local-logging (value)
8715 "Get logging settings from a property VALUE."
8716 (let* (words w a)
8717 ;; directly set the variables, they are already local.
8718 (setq org-log-done nil
8719 org-log-repeat nil
8720 org-todo-log-states nil)
8721 (setq words (org-split-string value))
8722 (while (setq w (pop words))
8723 (cond
8724 ((setq a (assoc w org-startup-options))
8725 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8726 (set (nth 1 a) (nth 2 a))))
8727 ((setq a (org-extract-log-state-settings w))
8728 (and (member (car a) org-todo-keywords-1)
8729 (push a org-todo-log-states)))))))
8731 (defun org-get-todo-sequence-head (kwd)
8732 "Return the head of the TODO sequence to which KWD belongs.
8733 If KWD is not set, check if there is a text property remembering the
8734 right sequence."
8735 (let (p)
8736 (cond
8737 ((not kwd)
8738 (or (get-text-property (point-at-bol) 'org-todo-head)
8739 (progn
8740 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8741 nil (point-at-eol)))
8742 (get-text-property p 'org-todo-head))))
8743 ((not (member kwd org-todo-keywords-1))
8744 (car org-todo-keywords-1))
8745 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8747 (defun org-fast-todo-selection ()
8748 "Fast TODO keyword selection with single keys.
8749 Returns the new TODO keyword, or nil if no state change should occur."
8750 (let* ((fulltable org-todo-key-alist)
8751 (done-keywords org-done-keywords) ;; needed for the faces.
8752 (maxlen (apply 'max (mapcar
8753 (lambda (x)
8754 (if (stringp (car x)) (string-width (car x)) 0))
8755 fulltable)))
8756 (expert nil)
8757 (fwidth (+ maxlen 3 1 3))
8758 (ncol (/ (- (window-width) 4) fwidth))
8759 tg cnt e c tbl
8760 groups ingroup)
8761 (save-excursion
8762 (save-window-excursion
8763 (if expert
8764 (set-buffer (get-buffer-create " *Org todo*"))
8765 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8766 (erase-buffer)
8767 (org-set-local 'org-done-keywords done-keywords)
8768 (setq tbl fulltable cnt 0)
8769 (while (setq e (pop tbl))
8770 (cond
8771 ((equal e '(:startgroup))
8772 (push '() groups) (setq ingroup t)
8773 (when (not (= cnt 0))
8774 (setq cnt 0)
8775 (insert "\n"))
8776 (insert "{ "))
8777 ((equal e '(:endgroup))
8778 (setq ingroup nil cnt 0)
8779 (insert "}\n"))
8781 (setq tg (car e) c (cdr e))
8782 (if ingroup (push tg (car groups)))
8783 (setq tg (org-add-props tg nil 'face
8784 (org-get-todo-face tg)))
8785 (if (and (= cnt 0) (not ingroup)) (insert " "))
8786 (insert "[" c "] " tg (make-string
8787 (- fwidth 4 (length tg)) ?\ ))
8788 (when (= (setq cnt (1+ cnt)) ncol)
8789 (insert "\n")
8790 (if ingroup (insert " "))
8791 (setq cnt 0)))))
8792 (insert "\n")
8793 (goto-char (point-min))
8794 (if (not expert) (org-fit-window-to-buffer))
8795 (message "[a-z..]:Set [SPC]:clear")
8796 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8797 (cond
8798 ((or (= c ?\C-g)
8799 (and (= c ?q) (not (rassoc c fulltable))))
8800 (setq quit-flag t))
8801 ((= c ?\ ) nil)
8802 ((setq e (rassoc c fulltable) tg (car e))
8804 (t (setq quit-flag t)))))))
8806 (defun org-entry-is-todo-p ()
8807 (member (org-get-todo-state) org-not-done-keywords))
8809 (defun org-entry-is-done-p ()
8810 (member (org-get-todo-state) org-done-keywords))
8812 (defun org-get-todo-state ()
8813 (save-excursion
8814 (org-back-to-heading t)
8815 (and (looking-at org-todo-line-regexp)
8816 (match-end 2)
8817 (match-string 2))))
8819 (defun org-at-date-range-p (&optional inactive-ok)
8820 "Is the cursor inside a date range?"
8821 (interactive)
8822 (save-excursion
8823 (catch 'exit
8824 (let ((pos (point)))
8825 (skip-chars-backward "^[<\r\n")
8826 (skip-chars-backward "<[")
8827 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8828 (>= (match-end 0) pos)
8829 (throw 'exit t))
8830 (skip-chars-backward "^<[\r\n")
8831 (skip-chars-backward "<[")
8832 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8833 (>= (match-end 0) pos)
8834 (throw 'exit t)))
8835 nil)))
8837 (defun org-get-repeat ()
8838 "Check if there is a deadline/schedule with repeater in this entry."
8839 (save-match-data
8840 (save-excursion
8841 (org-back-to-heading t)
8842 (if (re-search-forward
8843 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8844 (match-string 1)))))
8846 (defvar org-last-changed-timestamp)
8847 (defvar org-last-inserted-timestamp)
8848 (defvar org-log-post-message)
8849 (defvar org-log-note-purpose)
8850 (defvar org-log-note-how)
8851 (defvar org-log-note-extra)
8852 (defun org-auto-repeat-maybe (done-word)
8853 "Check if the current headline contains a repeated deadline/schedule.
8854 If yes, set TODO state back to what it was and change the base date
8855 of repeating deadline/scheduled time stamps to new date.
8856 This function is run automatically after each state change to a DONE state."
8857 ;; last-state is dynamically scoped into this function
8858 (let* ((repeat (org-get-repeat))
8859 (aa (assoc last-state org-todo-kwd-alist))
8860 (interpret (nth 1 aa))
8861 (head (nth 2 aa))
8862 (whata '(("d" . day) ("m" . month) ("y" . year)))
8863 (msg "Entry repeats: ")
8864 (org-log-done nil)
8865 (org-todo-log-states nil)
8866 (nshiftmax 10) (nshift 0)
8867 re type n what ts time)
8868 (when repeat
8869 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8870 (org-todo (if (eq interpret 'type) last-state head))
8871 (when org-log-repeat
8872 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8873 (memq 'org-add-log-note post-command-hook))
8874 ;; OK, we are already setup for some record
8875 (if (eq org-log-repeat 'note)
8876 ;; make sure we take a note, not only a time stamp
8877 (setq org-log-note-how 'note))
8878 ;; Set up for taking a record
8879 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8880 'findpos org-log-repeat)))
8881 (org-back-to-heading t)
8882 (org-add-planning-info nil nil 'closed)
8883 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8884 org-deadline-time-regexp "\\)\\|\\("
8885 org-ts-regexp "\\)"))
8886 (while (re-search-forward
8887 re (save-excursion (outline-next-heading) (point)) t)
8888 (setq type (if (match-end 1) org-scheduled-string
8889 (if (match-end 3) org-deadline-string "Plain:"))
8890 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
8891 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8892 (setq n (string-to-number (match-string 2 ts))
8893 what (match-string 3 ts))
8894 (if (equal what "w") (setq n (* n 7) what "d"))
8895 ;; Preparation, see if we need to modify the start date for the change
8896 (when (match-end 1)
8897 (setq time (save-match-data (org-time-string-to-time ts)))
8898 (cond
8899 ((equal (match-string 1 ts) ".")
8900 ;; Shift starting date to today
8901 (org-timestamp-change
8902 (- (time-to-days (current-time)) (time-to-days time))
8903 'day))
8904 ((equal (match-string 1 ts) "+")
8905 (while (or (= nshift 0)
8906 (<= (time-to-days time) (time-to-days (current-time))))
8907 (when (= (incf nshift) nshiftmax)
8908 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8909 (error "Abort")))
8910 (org-timestamp-change n (cdr (assoc what whata)))
8911 (org-at-timestamp-p t)
8912 (setq ts (match-string 1))
8913 (setq time (save-match-data (org-time-string-to-time ts))))
8914 (org-timestamp-change (- n) (cdr (assoc what whata)))
8915 ;; rematch, so that we have everything in place for the real shift
8916 (org-at-timestamp-p t)
8917 (setq ts (match-string 1))
8918 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8919 (org-timestamp-change n (cdr (assoc what whata)))
8920 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8921 (setq org-log-post-message msg)
8922 (message "%s" msg))))
8924 (defun org-show-todo-tree (arg)
8925 "Make a compact tree which shows all headlines marked with TODO.
8926 The tree will show the lines where the regexp matches, and all higher
8927 headlines above the match.
8928 With a \\[universal-argument] prefix, also show the DONE entries.
8929 With a numeric prefix N, construct a sparse tree for the Nth element
8930 of `org-todo-keywords-1'."
8931 (interactive "P")
8932 (let ((case-fold-search nil)
8933 (kwd-re
8934 (cond ((null arg) org-not-done-regexp)
8935 ((equal arg '(4))
8936 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8937 (mapcar 'list org-todo-keywords-1))))
8938 (concat "\\("
8939 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8940 "\\)\\>")))
8941 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8942 (regexp-quote (nth (1- (prefix-numeric-value arg))
8943 org-todo-keywords-1)))
8944 (t (error "Invalid prefix argument: %s" arg)))))
8945 (message "%d TODO entries found"
8946 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8948 (defun org-deadline (&optional remove time)
8949 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8950 With argument REMOVE, remove any deadline from the item.
8951 When TIME is set, it should be an internal time specification, and the
8952 scheduling will use the corresponding date."
8953 (interactive "P")
8954 (if remove
8955 (progn
8956 (org-remove-timestamp-with-keyword org-deadline-string)
8957 (message "Item no longer has a deadline."))
8958 (if (org-get-repeat)
8959 (error "Cannot change deadline on task with repeater, please do that by hand")
8960 (org-add-planning-info 'deadline time 'closed)
8961 (message "Deadline on %s" org-last-inserted-timestamp))))
8963 (defun org-schedule (&optional remove time)
8964 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8965 With argument REMOVE, remove any scheduling date from the item.
8966 When TIME is set, it should be an internal time specification, and the
8967 scheduling will use the corresponding date."
8968 (interactive "P")
8969 (if remove
8970 (progn
8971 (org-remove-timestamp-with-keyword org-scheduled-string)
8972 (message "Item is no longer scheduled."))
8973 (if (org-get-repeat)
8974 (error "Cannot reschedule task with repeater, please do that by hand")
8975 (org-add-planning-info 'scheduled time 'closed)
8976 (message "Scheduled to %s" org-last-inserted-timestamp))))
8978 (defun org-get-scheduled-time (pom &optional inherit)
8979 "Get the scheduled time as a time tuple, of a format suitable
8980 for calling org-schedule with, or if there is no scheduling,
8981 returns nil."
8982 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
8983 (when time
8984 (apply 'encode-time (org-parse-time-string time)))))
8986 (defun org-get-deadline-time (pom &optional inherit)
8987 "Get the deadine as a time tuple, of a format suitable for
8988 calling org-deadlin with, or if there is no scheduling, returns
8989 nil."
8990 (let ((time (org-entry-get pom "DEADLINE" inherit)))
8991 (when time
8992 (apply 'encode-time (org-parse-time-string time)))))
8994 (defun org-remove-timestamp-with-keyword (keyword)
8995 "Remove all time stamps with KEYWORD in the current entry."
8996 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8997 beg)
8998 (save-excursion
8999 (org-back-to-heading t)
9000 (setq beg (point))
9001 (org-end-of-subtree t t)
9002 (while (re-search-backward re beg t)
9003 (replace-match "")
9004 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9005 (equal (char-before) ?\ ))
9006 (backward-delete-char 1)
9007 (if (string-match "^[ \t]*$" (buffer-substring
9008 (point-at-bol) (point-at-eol)))
9009 (delete-region (point-at-bol)
9010 (min (point-max) (1+ (point-at-eol))))))))))
9012 (defun org-add-planning-info (what &optional time &rest remove)
9013 "Insert new timestamp with keyword in the line directly after the headline.
9014 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9015 If non is given, the user is prompted for a date.
9016 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9017 be removed."
9018 (interactive)
9019 (let (org-time-was-given org-end-time-was-given ts
9020 end default-time default-input)
9022 (when (and (not time) (memq what '(scheduled deadline)))
9023 ;; Try to get a default date/time from existing timestamp
9024 (save-excursion
9025 (org-back-to-heading t)
9026 (setq end (save-excursion (outline-next-heading) (point)))
9027 (when (re-search-forward (if (eq what 'scheduled)
9028 org-scheduled-time-regexp
9029 org-deadline-time-regexp)
9030 end t)
9031 (setq ts (match-string 1)
9032 default-time
9033 (apply 'encode-time (org-parse-time-string ts))
9034 default-input (and ts (org-get-compact-tod ts))))))
9035 (when what
9036 ;; If necessary, get the time from the user
9037 (setq time (or time (org-read-date nil 'to-time nil nil
9038 default-time default-input))))
9040 (when (and org-insert-labeled-timestamps-at-point
9041 (member what '(scheduled deadline)))
9042 (insert
9043 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9044 (org-insert-time-stamp time org-time-was-given
9045 nil nil nil (list org-end-time-was-given))
9046 (setq what nil))
9047 (save-excursion
9048 (save-restriction
9049 (let (col list elt ts buffer-invisibility-spec)
9050 (org-back-to-heading t)
9051 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9052 (goto-char (match-end 1))
9053 (setq col (current-column))
9054 (goto-char (match-end 0))
9055 (if (eobp) (insert "\n") (forward-char 1))
9056 (if (and (not (looking-at outline-regexp))
9057 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9058 "[^\r\n]*"))
9059 (not (equal (match-string 1) org-clock-string)))
9060 (narrow-to-region (match-beginning 0) (match-end 0))
9061 (insert-before-markers "\n")
9062 (backward-char 1)
9063 (narrow-to-region (point) (point))
9064 (and org-adapt-indentation (org-indent-to-column col)))
9065 ;; Check if we have to remove something.
9066 (setq list (cons what remove))
9067 (while list
9068 (setq elt (pop list))
9069 (goto-char (point-min))
9070 (when (or (and (eq elt 'scheduled)
9071 (re-search-forward org-scheduled-time-regexp nil t))
9072 (and (eq elt 'deadline)
9073 (re-search-forward org-deadline-time-regexp nil t))
9074 (and (eq elt 'closed)
9075 (re-search-forward org-closed-time-regexp nil t)))
9076 (replace-match "")
9077 (if (looking-at "--+<[^>]+>") (replace-match ""))
9078 (if (looking-at " +") (replace-match ""))))
9079 (goto-char (point-max))
9080 (when what
9081 (insert
9082 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9083 (cond ((eq what 'scheduled) org-scheduled-string)
9084 ((eq what 'deadline) org-deadline-string)
9085 ((eq what 'closed) org-closed-string))
9086 " ")
9087 (setq ts (org-insert-time-stamp
9088 time
9089 (or org-time-was-given
9090 (and (eq what 'closed) org-log-done-with-time))
9091 (eq what 'closed)
9092 nil nil (list org-end-time-was-given)))
9093 (end-of-line 1))
9094 (goto-char (point-min))
9095 (widen)
9096 (if (and (looking-at "[ \t]+\n")
9097 (equal (char-before) ?\n))
9098 (delete-region (1- (point)) (point-at-eol)))
9099 ts)))))
9101 (defvar org-log-note-marker (make-marker))
9102 (defvar org-log-note-purpose nil)
9103 (defvar org-log-note-state nil)
9104 (defvar org-log-note-how nil)
9105 (defvar org-log-note-extra nil)
9106 (defvar org-log-note-window-configuration nil)
9107 (defvar org-log-note-return-to (make-marker))
9108 (defvar org-log-post-message nil
9109 "Message to be displayed after a log note has been stored.
9110 The auto-repeater uses this.")
9112 (defun org-add-note ()
9113 "Add a note to the current entry.
9114 This is done in the same way as adding a state change note."
9115 (interactive)
9116 (org-add-log-setup 'note nil 'findpos nil))
9118 (defvar org-property-end-re)
9119 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
9120 "Set up the post command hook to take a note.
9121 If this is about to TODO state change, the new state is expected in STATE.
9122 When FINDPOS is non-nil, find the correct position for the note in
9123 the current entry. If not, assume that it can be inserted at point.
9124 HOW is an indicator what kind of note should be created.
9125 EXTRA is additional text that will be inserted into the notes buffer."
9126 (save-restriction
9127 (save-excursion
9128 (when findpos
9129 (org-back-to-heading t)
9130 (narrow-to-region (point) (save-excursion
9131 (outline-next-heading) (point)))
9132 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9133 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9134 "[^\r\n]*\\)?"))
9135 (goto-char (match-end 0))
9136 (when (and org-log-state-notes-insert-after-drawers
9137 (save-excursion
9138 (forward-line) (looking-at org-drawer-regexp)))
9139 (progn (forward-line)
9140 (while (looking-at org-drawer-regexp)
9141 (goto-char (match-end 0))
9142 (re-search-forward org-property-end-re (point-max) t)
9143 (forward-line))
9144 (forward-line -1)))
9145 (unless org-log-states-order-reversed
9146 (and (= (char-after) ?\n) (forward-char 1))
9147 (org-skip-over-state-notes)
9148 (skip-chars-backward " \t\n\r")))
9149 (move-marker org-log-note-marker (point))
9150 (setq org-log-note-purpose purpose
9151 org-log-note-state state
9152 org-log-note-how how
9153 org-log-note-extra extra)
9154 (add-hook 'post-command-hook 'org-add-log-note 'append))))
9156 (defun org-skip-over-state-notes ()
9157 "Skip past the list of State notes in an entry."
9158 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9159 (while (looking-at "[ \t]*- State")
9160 (condition-case nil
9161 (org-next-item)
9162 (error (org-end-of-item)))))
9164 (defun org-add-log-note (&optional purpose)
9165 "Pop up a window for taking a note, and add this note later at point."
9166 (remove-hook 'post-command-hook 'org-add-log-note)
9167 (setq org-log-note-window-configuration (current-window-configuration))
9168 (delete-other-windows)
9169 (move-marker org-log-note-return-to (point))
9170 (switch-to-buffer (marker-buffer org-log-note-marker))
9171 (goto-char org-log-note-marker)
9172 (org-switch-to-buffer-other-window "*Org Note*")
9173 (erase-buffer)
9174 (if (memq org-log-note-how '(time state))
9175 (let (current-prefix-arg) (org-store-log-note))
9176 (let ((org-inhibit-startup t)) (org-mode))
9177 (insert (format "# Insert note for %s.
9178 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9179 (cond
9180 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9181 ((eq org-log-note-purpose 'done) "closed todo item")
9182 ((eq org-log-note-purpose 'state)
9183 (format "state change to \"%s\"" org-log-note-state))
9184 ((eq org-log-note-purpose 'note)
9185 "this entry")
9186 (t (error "This should not happen")))))
9187 (if org-log-note-extra (insert org-log-note-extra))
9188 (org-set-local 'org-finish-function 'org-store-log-note)))
9190 (defvar org-note-abort nil) ; dynamically scoped
9191 (defun org-store-log-note ()
9192 "Finish taking a log note, and insert it to where it belongs."
9193 (let ((txt (buffer-string))
9194 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9195 lines ind)
9196 (kill-buffer (current-buffer))
9197 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9198 (setq txt (replace-match "" t t txt)))
9199 (if (string-match "\\s-+\\'" txt)
9200 (setq txt (replace-match "" t t txt)))
9201 (setq lines (org-split-string txt "\n"))
9202 (when (and note (string-match "\\S-" note))
9203 (setq note
9204 (org-replace-escapes
9205 note
9206 (list (cons "%u" (user-login-name))
9207 (cons "%U" user-full-name)
9208 (cons "%t" (format-time-string
9209 (org-time-stamp-format 'long 'inactive)
9210 (current-time)))
9211 (cons "%s" (if org-log-note-state
9212 (concat "\"" org-log-note-state "\"")
9213 "")))))
9214 (if lines (setq note (concat note " \\\\")))
9215 (push note lines))
9216 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9217 (when lines
9218 (save-excursion
9219 (set-buffer (marker-buffer org-log-note-marker))
9220 (save-excursion
9221 (goto-char org-log-note-marker)
9222 (move-marker org-log-note-marker nil)
9223 (end-of-line 1)
9224 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9225 (indent-relative nil)
9226 (insert "- " (pop lines))
9227 (org-indent-line-function)
9228 (beginning-of-line 1)
9229 (looking-at "[ \t]*")
9230 (setq ind (concat (match-string 0) " "))
9231 (end-of-line 1)
9232 (while lines (insert "\n" ind (pop lines)))))))
9233 (set-window-configuration org-log-note-window-configuration)
9234 (with-current-buffer (marker-buffer org-log-note-return-to)
9235 (goto-char org-log-note-return-to))
9236 (move-marker org-log-note-return-to nil)
9237 (and org-log-post-message (message "%s" org-log-post-message)))
9239 (defun org-sparse-tree (&optional arg)
9240 "Create a sparse tree, prompt for the details.
9241 This command can create sparse trees. You first need to select the type
9242 of match used to create the tree:
9244 t Show entries with a specific TODO keyword.
9245 T Show entries selected by a tags match.
9246 p Enter a property name and its value (both with completion on existing
9247 names/values) and show entries with that property.
9248 r Show entries matching a regular expression
9249 d Show deadlines due within `org-deadline-warning-days'."
9250 (interactive "P")
9251 (let (ans kwd value)
9252 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9253 (setq ans (read-char-exclusive))
9254 (cond
9255 ((equal ans ?d)
9256 (call-interactively 'org-check-deadlines))
9257 ((equal ans ?b)
9258 (call-interactively 'org-check-before-date))
9259 ((equal ans ?t)
9260 (org-show-todo-tree '(4)))
9261 ((equal ans ?T)
9262 (call-interactively 'org-tags-sparse-tree))
9263 ((member ans '(?p ?P))
9264 (setq kwd (org-ido-completing-read "Property: "
9265 (mapcar 'list (org-buffer-property-keys))))
9266 (setq value (org-ido-completing-read "Value: "
9267 (mapcar 'list (org-property-values kwd))))
9268 (unless (string-match "\\`{.*}\\'" value)
9269 (setq value (concat "\"" value "\"")))
9270 (org-tags-sparse-tree arg (concat kwd "=" value)))
9271 ((member ans '(?r ?R ?/))
9272 (call-interactively 'org-occur))
9273 (t (error "No such sparse tree command \"%c\"" ans)))))
9275 (defvar org-occur-highlights nil
9276 "List of overlays used for occur matches.")
9277 (make-variable-buffer-local 'org-occur-highlights)
9278 (defvar org-occur-parameters nil
9279 "Parameters of the active org-occur calls.
9280 This is a list, each call to org-occur pushes as cons cell,
9281 containing the regular expression and the callback, onto the list.
9282 The list can contain several entries if `org-occur' has been called
9283 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9284 will only contain one set of parameters. When the highlights are
9285 removed (for example with `C-c C-c', or with the next edit (depending
9286 on `org-remove-highlights-with-change'), this variable is emptied
9287 as well.")
9288 (make-variable-buffer-local 'org-occur-parameters)
9290 (defun org-occur (regexp &optional keep-previous callback)
9291 "Make a compact tree which shows all matches of REGEXP.
9292 The tree will show the lines where the regexp matches, and all higher
9293 headlines above the match. It will also show the heading after the match,
9294 to make sure editing the matching entry is easy.
9295 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9296 call to `org-occur' will be kept, to allow stacking of calls to this
9297 command.
9298 If CALLBACK is non-nil, it is a function which is called to confirm
9299 that the match should indeed be shown."
9300 (interactive "sRegexp: \nP")
9301 (unless keep-previous
9302 (org-remove-occur-highlights nil nil t))
9303 (push (cons regexp callback) org-occur-parameters)
9304 (let ((cnt 0))
9305 (save-excursion
9306 (goto-char (point-min))
9307 (if (or (not keep-previous) ; do not want to keep
9308 (not org-occur-highlights)) ; no previous matches
9309 ;; hide everything
9310 (org-overview))
9311 (while (re-search-forward regexp nil t)
9312 (when (or (not callback)
9313 (save-match-data (funcall callback)))
9314 (setq cnt (1+ cnt))
9315 (when org-highlight-sparse-tree-matches
9316 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9317 (org-show-context 'occur-tree))))
9318 (when org-remove-highlights-with-change
9319 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9320 nil 'local))
9321 (unless org-sparse-tree-open-archived-trees
9322 (org-hide-archived-subtrees (point-min) (point-max)))
9323 (run-hooks 'org-occur-hook)
9324 (if (interactive-p)
9325 (message "%d match(es) for regexp %s" cnt regexp))
9326 cnt))
9328 (defun org-show-context (&optional key)
9329 "Make sure point and context and visible.
9330 How much context is shown depends upon the variables
9331 `org-show-hierarchy-above', `org-show-following-heading'. and
9332 `org-show-siblings'."
9333 (let ((heading-p (org-on-heading-p t))
9334 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9335 (following-p (org-get-alist-option org-show-following-heading key))
9336 (entry-p (org-get-alist-option org-show-entry-below key))
9337 (siblings-p (org-get-alist-option org-show-siblings key)))
9338 (catch 'exit
9339 ;; Show heading or entry text
9340 (if (and heading-p (not entry-p))
9341 (org-flag-heading nil) ; only show the heading
9342 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9343 (org-show-hidden-entry))) ; show entire entry
9344 (when following-p
9345 ;; Show next sibling, or heading below text
9346 (save-excursion
9347 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9348 (org-flag-heading nil))))
9349 (when siblings-p (org-show-siblings))
9350 (when hierarchy-p
9351 ;; show all higher headings, possibly with siblings
9352 (save-excursion
9353 (while (and (condition-case nil
9354 (progn (org-up-heading-all 1) t)
9355 (error nil))
9356 (not (bobp)))
9357 (org-flag-heading nil)
9358 (when siblings-p (org-show-siblings))))))))
9360 (defun org-reveal (&optional siblings)
9361 "Show current entry, hierarchy above it, and the following headline.
9362 This can be used to show a consistent set of context around locations
9363 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9364 not t for the search context.
9366 With optional argument SIBLINGS, on each level of the hierarchy all
9367 siblings are shown. This repairs the tree structure to what it would
9368 look like when opened with hierarchical calls to `org-cycle'."
9369 (interactive "P")
9370 (let ((org-show-hierarchy-above t)
9371 (org-show-following-heading t)
9372 (org-show-siblings (if siblings t org-show-siblings)))
9373 (org-show-context nil)))
9375 (defun org-highlight-new-match (beg end)
9376 "Highlight from BEG to END and mark the highlight is an occur headline."
9377 (let ((ov (org-make-overlay beg end)))
9378 (org-overlay-put ov 'face 'secondary-selection)
9379 (push ov org-occur-highlights)))
9381 (defun org-remove-occur-highlights (&optional beg end noremove)
9382 "Remove the occur highlights from the buffer.
9383 BEG and END are ignored. If NOREMOVE is nil, remove this function
9384 from the `before-change-functions' in the current buffer."
9385 (interactive)
9386 (unless org-inhibit-highlight-removal
9387 (mapc 'org-delete-overlay org-occur-highlights)
9388 (setq org-occur-highlights nil)
9389 (setq org-occur-parameters nil)
9390 (unless noremove
9391 (remove-hook 'before-change-functions
9392 'org-remove-occur-highlights 'local))))
9394 ;;;; Priorities
9396 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9397 "Regular expression matching the priority indicator.")
9399 (defvar org-remove-priority-next-time nil)
9401 (defun org-priority-up ()
9402 "Increase the priority of the current item."
9403 (interactive)
9404 (org-priority 'up))
9406 (defun org-priority-down ()
9407 "Decrease the priority of the current item."
9408 (interactive)
9409 (org-priority 'down))
9411 (defun org-priority (&optional action)
9412 "Change the priority of an item by ARG.
9413 ACTION can be `set', `up', `down', or a character."
9414 (interactive)
9415 (setq action (or action 'set))
9416 (let (current new news have remove)
9417 (save-excursion
9418 (org-back-to-heading)
9419 (if (looking-at org-priority-regexp)
9420 (setq current (string-to-char (match-string 2))
9421 have t)
9422 (setq current org-default-priority))
9423 (cond
9424 ((or (eq action 'set)
9425 (if (featurep 'xemacs) (characterp action) (integerp action)))
9426 (if (not (eq action 'set))
9427 (setq new action)
9428 (message "Priority %c-%c, SPC to remove: "
9429 org-highest-priority org-lowest-priority)
9430 (setq new (read-char-exclusive)))
9431 (if (and (= (upcase org-highest-priority) org-highest-priority)
9432 (= (upcase org-lowest-priority) org-lowest-priority))
9433 (setq new (upcase new)))
9434 (cond ((equal new ?\ ) (setq remove t))
9435 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9436 (error "Priority must be between `%c' and `%c'"
9437 org-highest-priority org-lowest-priority))))
9438 ((eq action 'up)
9439 (if (and (not have) (eq last-command this-command))
9440 (setq new org-lowest-priority)
9441 (setq new (if (and org-priority-start-cycle-with-default (not have))
9442 org-default-priority (1- current)))))
9443 ((eq action 'down)
9444 (if (and (not have) (eq last-command this-command))
9445 (setq new org-highest-priority)
9446 (setq new (if (and org-priority-start-cycle-with-default (not have))
9447 org-default-priority (1+ current)))))
9448 (t (error "Invalid action")))
9449 (if (or (< (upcase new) org-highest-priority)
9450 (> (upcase new) org-lowest-priority))
9451 (setq remove t))
9452 (setq news (format "%c" new))
9453 (if have
9454 (if remove
9455 (replace-match "" t t nil 1)
9456 (replace-match news t t nil 2))
9457 (if remove
9458 (error "No priority cookie found in line")
9459 (looking-at org-todo-line-regexp)
9460 (if (match-end 2)
9461 (progn
9462 (goto-char (match-end 2))
9463 (insert " [#" news "]"))
9464 (goto-char (match-beginning 3))
9465 (insert "[#" news "] ")))))
9466 (org-preserve-lc (org-set-tags nil 'align))
9467 (if remove
9468 (message "Priority removed")
9469 (message "Priority of current item set to %s" news))))
9472 (defun org-get-priority (s)
9473 "Find priority cookie and return priority."
9474 (save-match-data
9475 (if (not (string-match org-priority-regexp s))
9476 (* 1000 (- org-lowest-priority org-default-priority))
9477 (* 1000 (- org-lowest-priority
9478 (string-to-char (match-string 2 s)))))))
9480 ;;;; Tags
9482 (defvar org-agenda-archives-mode)
9483 (defun org-scan-tags (action matcher &optional todo-only)
9484 "Scan headline tags with inheritance and produce output ACTION.
9486 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9487 or `agenda' to produce an entry list for an agenda view. It can also be
9488 a Lisp form or a function that should be called at each matched headline, in
9489 this case the return value is a list of all return values from these calls.
9491 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9492 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9493 only lines with a TODO keyword are included in the output."
9494 (require 'org-agenda)
9495 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9496 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9497 (org-re
9498 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9499 (props (list 'face 'default
9500 'done-face 'org-done
9501 'undone-face 'default
9502 'mouse-face 'highlight
9503 'org-not-done-regexp org-not-done-regexp
9504 'org-todo-regexp org-todo-regexp
9505 'keymap org-agenda-keymap
9506 'help-echo
9507 (format "mouse-2 or RET jump to org file %s"
9508 (abbreviate-file-name
9509 (or (buffer-file-name (buffer-base-buffer))
9510 (buffer-name (buffer-base-buffer)))))))
9511 (case-fold-search nil)
9512 lspos tags tags-list
9513 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9514 (llast 0) rtn rtn1 level category i txt
9515 todo marker entry priority)
9516 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9517 (setq action (list 'lambda nil action)))
9518 (save-excursion
9519 (goto-char (point-min))
9520 (when (eq action 'sparse-tree)
9521 (org-overview)
9522 (org-remove-occur-highlights))
9523 (while (re-search-forward re nil t)
9524 (catch :skip
9525 (setq todo (if (match-end 1) (match-string 2))
9526 tags (if (match-end 4) (match-string 4)))
9527 (goto-char (setq lspos (1+ (match-beginning 0))))
9528 (setq level (org-reduced-level (funcall outline-level))
9529 category (org-get-category))
9530 (setq i llast llast level)
9531 ;; remove tag lists from same and sublevels
9532 (while (>= i level)
9533 (when (setq entry (assoc i tags-alist))
9534 (setq tags-alist (delete entry tags-alist)))
9535 (setq i (1- i)))
9536 ;; add the next tags
9537 (when tags
9538 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9539 tags-alist
9540 (cons (cons level tags) tags-alist)))
9541 ;; compile tags for current headline
9542 (setq tags-list
9543 (if org-use-tag-inheritance
9544 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9545 tags))
9546 (when org-use-tag-inheritance
9547 (setcdr (car tags-alist)
9548 (mapcar (lambda (x)
9549 (setq x (copy-sequence x))
9550 (org-add-prop-inherited x))
9551 (cdar tags-alist))))
9552 (when (and tags org-use-tag-inheritance
9553 (not (eq t org-use-tag-inheritance)))
9554 ;; selective inheritance, remove uninherited ones
9555 (setcdr (car tags-alist)
9556 (org-remove-uniherited-tags (cdar tags-alist))))
9557 (when (and (or (not todo-only)
9558 (and (member todo org-not-done-keywords)
9559 (or (not org-agenda-tags-todo-honor-ignore-options)
9560 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9561 (let ((case-fold-search t)) (eval matcher))
9563 (not (member org-archive-tag tags-list))
9564 ;; we have an archive tag, should we use this anyway?
9565 (or (not org-agenda-skip-archived-trees)
9566 (and (eq action 'agenda) org-agenda-archives-mode))))
9567 (unless (eq action 'sparse-tree) (org-agenda-skip))
9569 ;; select this headline
9571 (cond
9572 ((eq action 'sparse-tree)
9573 (and org-highlight-sparse-tree-matches
9574 (org-get-heading) (match-end 0)
9575 (org-highlight-new-match
9576 (match-beginning 0) (match-beginning 1)))
9577 (org-show-context 'tags-tree))
9578 ((eq action 'agenda)
9579 (setq txt (org-format-agenda-item
9581 (concat
9582 (if org-tags-match-list-sublevels
9583 (make-string (1- level) ?.) "")
9584 (org-get-heading))
9585 category (org-get-tags-at))
9586 priority (org-get-priority txt))
9587 (goto-char lspos)
9588 (setq marker (org-agenda-new-marker))
9589 (org-add-props txt props
9590 'org-marker marker 'org-hd-marker marker 'org-category category
9591 'priority priority 'type "tagsmatch")
9592 (push txt rtn))
9593 ((functionp action)
9594 (save-excursion
9595 (setq rtn1 (funcall action))
9596 (push rtn1 rtn))
9597 (goto-char (point-at-eol)))
9598 (t (error "Invalid action")))
9600 ;; if we are to skip sublevels, jump to end of subtree
9601 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9602 (when (and (eq action 'sparse-tree)
9603 (not org-sparse-tree-open-archived-trees))
9604 (org-hide-archived-subtrees (point-min) (point-max)))
9605 (nreverse rtn)))
9607 (defun org-remove-uniherited-tags (tags)
9608 "Remove all tags that are not inherited from the list TAGS."
9609 (cond
9610 ((eq org-use-tag-inheritance t)
9611 (if org-tags-exclude-from-inheritance
9612 (org-delete-all org-tags-exclude-from-inheritance tags)
9613 tags))
9614 ((not org-use-tag-inheritance) nil)
9615 ((stringp org-use-tag-inheritance)
9616 (delq nil (mapcar
9617 (lambda (x)
9618 (if (and (string-match org-use-tag-inheritance x)
9619 (not (member x org-tags-exclude-from-inheritance)))
9620 x nil))
9621 tags)))
9622 ((listp org-use-tag-inheritance)
9623 (delq nil (mapcar
9624 (lambda (x)
9625 (if (member x org-use-tag-inheritance) x nil))
9626 tags)))))
9628 (defvar todo-only) ;; dynamically scoped
9630 (defun org-tags-sparse-tree (&optional todo-only match)
9631 "Create a sparse tree according to tags string MATCH.
9632 MATCH can contain positive and negative selection of tags, like
9633 \"+WORK+URGENT-WITHBOSS\".
9634 If optional argument TODO-ONLY is non-nil, only select lines that are
9635 also TODO lines."
9636 (interactive "P")
9637 (org-prepare-agenda-buffers (list (current-buffer)))
9638 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9640 (defvar org-cached-props nil)
9641 (defun org-cached-entry-get (pom property)
9642 (if (or (eq t org-use-property-inheritance)
9643 (and (stringp org-use-property-inheritance)
9644 (string-match org-use-property-inheritance property))
9645 (and (listp org-use-property-inheritance)
9646 (member property org-use-property-inheritance)))
9647 ;; Caching is not possible, check it directly
9648 (org-entry-get pom property 'inherit)
9649 ;; Get all properties, so that we can do complicated checks easily
9650 (cdr (assoc property (or org-cached-props
9651 (setq org-cached-props
9652 (org-entry-properties pom)))))))
9654 (defun org-global-tags-completion-table (&optional files)
9655 "Return the list of all tags in all agenda buffer/files."
9656 (save-excursion
9657 (org-uniquify
9658 (delq nil
9659 (apply 'append
9660 (mapcar
9661 (lambda (file)
9662 (set-buffer (find-file-noselect file))
9663 (append (org-get-buffer-tags)
9664 (mapcar (lambda (x) (if (stringp (car-safe x))
9665 (list (car-safe x)) nil))
9666 org-tag-alist)))
9667 (if (and files (car files))
9668 files
9669 (org-agenda-files))))))))
9671 (defun org-make-tags-matcher (match)
9672 "Create the TAGS//TODO matcher form for the selection string MATCH."
9673 ;; todo-only is scoped dynamically into this function, and the function
9674 ;; may change it if the matcher asks for it.
9675 (unless match
9676 ;; Get a new match request, with completion
9677 (let ((org-last-tags-completion-table
9678 (org-global-tags-completion-table)))
9679 (setq match (org-completing-read
9680 "Match: " 'org-tags-completion-function nil nil nil
9681 'org-tags-history))))
9683 ;; Parse the string and create a lisp form
9684 (let ((match0 match)
9685 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9686 minus tag mm
9687 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9688 orterms term orlist re-p str-p level-p level-op time-p
9689 prop-p pn pv po cat-p gv rest)
9690 (if (string-match "/+" match)
9691 ;; match contains also a todo-matching request
9692 (progn
9693 (setq tagsmatch (substring match 0 (match-beginning 0))
9694 todomatch (substring match (match-end 0)))
9695 (if (string-match "^!" todomatch)
9696 (setq todo-only t todomatch (substring todomatch 1)))
9697 (if (string-match "^\\s-*$" todomatch)
9698 (setq todomatch nil)))
9699 ;; only matching tags
9700 (setq tagsmatch match todomatch nil))
9702 ;; Make the tags matcher
9703 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9704 (setq tagsmatcher t)
9705 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9706 (while (setq term (pop orterms))
9707 (while (and (equal (substring term -1) "\\") orterms)
9708 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9709 (while (string-match re term)
9710 (setq rest (substring term (match-end 0))
9711 minus (and (match-end 1)
9712 (equal (match-string 1 term) "-"))
9713 tag (match-string 2 term)
9714 re-p (equal (string-to-char tag) ?{)
9715 level-p (match-end 4)
9716 prop-p (match-end 5)
9717 mm (cond
9718 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9719 (level-p
9720 (setq level-op (org-op-to-function (match-string 3 term)))
9721 `(,level-op level ,(string-to-number
9722 (match-string 4 term))))
9723 (prop-p
9724 (setq pn (match-string 5 term)
9725 po (match-string 6 term)
9726 pv (match-string 7 term)
9727 cat-p (equal pn "CATEGORY")
9728 re-p (equal (string-to-char pv) ?{)
9729 str-p (equal (string-to-char pv) ?\")
9730 time-p (save-match-data
9731 (string-match "^\"[[<].*[]>]\"$" pv))
9732 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9733 (if time-p (setq pv (org-matcher-time pv)))
9734 (setq po (org-op-to-function po (if time-p 'time str-p)))
9735 (cond
9736 ((equal pn "CATEGORY")
9737 (setq gv '(get-text-property (point) 'org-category)))
9738 ((equal pn "TODO")
9739 (setq gv 'todo))
9741 (setq gv `(org-cached-entry-get nil ,pn))))
9742 (if re-p
9743 (if (eq po 'org<>)
9744 `(not (string-match ,pv (or ,gv "")))
9745 `(string-match ,pv (or ,gv "")))
9746 (if str-p
9747 `(,po (or ,gv "") ,pv)
9748 `(,po (string-to-number (or ,gv ""))
9749 ,(string-to-number pv) ))))
9750 (t `(member ,(downcase tag) tags-list)))
9751 mm (if minus (list 'not mm) mm)
9752 term rest)
9753 (push mm tagsmatcher))
9754 (push (if (> (length tagsmatcher) 1)
9755 (cons 'and tagsmatcher)
9756 (car tagsmatcher))
9757 orlist)
9758 (setq tagsmatcher nil))
9759 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9760 (setq tagsmatcher
9761 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9762 ;; Make the todo matcher
9763 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9764 (setq todomatcher t)
9765 (setq orterms (org-split-string todomatch "|") orlist nil)
9766 (while (setq term (pop orterms))
9767 (while (string-match re term)
9768 (setq minus (and (match-end 1)
9769 (equal (match-string 1 term) "-"))
9770 kwd (match-string 2 term)
9771 re-p (equal (string-to-char kwd) ?{)
9772 term (substring term (match-end 0))
9773 mm (if re-p
9774 `(string-match ,(substring kwd 1 -1) todo)
9775 (list 'equal 'todo kwd))
9776 mm (if minus (list 'not mm) mm))
9777 (push mm todomatcher))
9778 (push (if (> (length todomatcher) 1)
9779 (cons 'and todomatcher)
9780 (car todomatcher))
9781 orlist)
9782 (setq todomatcher nil))
9783 (setq todomatcher (if (> (length orlist) 1)
9784 (cons 'or orlist) (car orlist))))
9786 ;; Return the string and lisp forms of the matcher
9787 (setq matcher (if todomatcher
9788 (list 'and tagsmatcher todomatcher)
9789 tagsmatcher))
9790 (cons match0 matcher)))
9792 (defun org-op-to-function (op &optional stringp)
9793 "Turn an operator into the appropriate function."
9794 (setq op
9795 (cond
9796 ((equal op "<" ) '(< string< org-time<))
9797 ((equal op ">" ) '(> org-string> org-time>))
9798 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9799 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9800 ((member op '("=" "==")) '(= string= org-time=))
9801 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9802 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9804 (defun org<> (a b) (not (= a b)))
9805 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9806 (defun org-string>= (a b) (not (string< a b)))
9807 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9808 (defun org-string<> (a b) (not (string= a b)))
9809 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9810 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9811 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9812 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9813 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9814 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9815 (defun org-2ft (s)
9816 "Convert S to a floating point time.
9817 If S is already a number, just return it. If it is a string, parse
9818 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9819 (cond
9820 ((numberp s) s)
9821 ((stringp s)
9822 (condition-case nil
9823 (float-time (apply 'encode-time (org-parse-time-string s)))
9824 (error 0.)))
9825 (t 0.)))
9827 (defun org-time-today ()
9828 "Time in seconds today at 0:00.
9829 Returns the float number of seconds since the beginning of the
9830 epoch to the beginning of today (00:00)."
9831 (float-time (apply 'encode-time
9832 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9834 (defun org-matcher-time (s)
9835 "Interpret a time comparison value."
9836 (save-match-data
9837 (cond
9838 ((string= s "<now>") (float-time))
9839 ((string= s "<today>") (org-time-today))
9840 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9841 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9842 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9843 (+ (org-time-today)
9844 (* (string-to-number (match-string 1 s))
9845 (cdr (assoc (match-string 2 s)
9846 '(("d" . 86400.0) ("w" . 604800.0)
9847 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9848 (t (org-2ft s)))))
9850 (defun org-match-any-p (re list)
9851 "Does re match any element of list?"
9852 (setq list (mapcar (lambda (x) (string-match re x)) list))
9853 (delq nil list))
9855 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9856 (defvar org-tags-overlay (org-make-overlay 1 1))
9857 (org-detach-overlay org-tags-overlay)
9859 (defun org-get-local-tags-at (&optional pos)
9860 "Get a list of tags defined in the current headline."
9861 (org-get-tags-at pos 'local))
9863 (defun org-get-local-tags ()
9864 "Get a list of tags defined in the current headline."
9865 (org-get-tags-at nil 'local))
9867 (defun org-get-tags-at (&optional pos local)
9868 "Get a list of all headline tags applicable at POS.
9869 POS defaults to point. If tags are inherited, the list contains
9870 the targets in the same sequence as the headlines appear, i.e.
9871 the tags of the current headline come last.
9872 When LOCAL is non-nil, only return tags from the current headline,
9873 ignore inherited ones."
9874 (interactive)
9875 (let (tags ltags lastpos parent)
9876 (save-excursion
9877 (save-restriction
9878 (widen)
9879 (goto-char (or pos (point)))
9880 (save-match-data
9881 (catch 'done
9882 (condition-case nil
9883 (progn
9884 (org-back-to-heading t)
9885 (while (not (equal lastpos (point)))
9886 (setq lastpos (point))
9887 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9888 (setq ltags (org-split-string
9889 (org-match-string-no-properties 1) ":"))
9890 (when parent
9891 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9892 (setq tags (append
9893 (if parent
9894 (org-remove-uniherited-tags ltags)
9895 ltags)
9896 tags)))
9897 (or org-use-tag-inheritance (throw 'done t))
9898 (if local (throw 'done t))
9899 (org-up-heading-all 1)
9900 (setq parent t)))
9901 (error nil)))))
9902 (append (org-remove-uniherited-tags org-file-tags) tags))))
9904 (defun org-add-prop-inherited (s)
9905 (add-text-properties 0 (length s) '(inherited t) s)
9908 (defun org-toggle-tag (tag &optional onoff)
9909 "Toggle the tag TAG for the current line.
9910 If ONOFF is `on' or `off', don't toggle but set to this state."
9911 (let (res current)
9912 (save-excursion
9913 (org-back-to-heading t)
9914 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9915 (point-at-eol) t)
9916 (progn
9917 (setq current (match-string 1))
9918 (replace-match ""))
9919 (setq current ""))
9920 (setq current (nreverse (org-split-string current ":")))
9921 (cond
9922 ((eq onoff 'on)
9923 (setq res t)
9924 (or (member tag current) (push tag current)))
9925 ((eq onoff 'off)
9926 (or (not (member tag current)) (setq current (delete tag current))))
9927 (t (if (member tag current)
9928 (setq current (delete tag current))
9929 (setq res t)
9930 (push tag current))))
9931 (end-of-line 1)
9932 (if current
9933 (progn
9934 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9935 (org-set-tags nil t))
9936 (delete-horizontal-space))
9937 (run-hooks 'org-after-tags-change-hook))
9938 res))
9940 (defun org-align-tags-here (to-col)
9941 ;; Assumes that this is a headline
9942 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9943 (beginning-of-line 1)
9944 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9945 (< pos (match-beginning 2)))
9946 (progn
9947 (setq tags-l (- (match-end 2) (match-beginning 2)))
9948 (goto-char (match-beginning 1))
9949 (insert " ")
9950 (delete-region (point) (1+ (match-beginning 2)))
9951 (setq ncol (max (1+ (current-column))
9952 (1+ col)
9953 (if (> to-col 0)
9954 to-col
9955 (- (abs to-col) tags-l))))
9956 (setq p (point))
9957 (insert (make-string (- ncol (current-column)) ?\ ))
9958 (setq ncol (current-column))
9959 (when indent-tabs-mode (tabify p (point-at-eol)))
9960 (org-move-to-column (min ncol col) t))
9961 (goto-char pos))))
9963 (defun org-set-tags-command (&optional arg just-align)
9964 "Call the set-tags command for the current entry."
9965 (interactive "P")
9966 (if (org-on-heading-p)
9967 (org-set-tags arg just-align)
9968 (save-excursion
9969 (org-back-to-heading t)
9970 (org-set-tags arg just-align))))
9972 (defun org-set-tags (&optional arg just-align)
9973 "Set the tags for the current headline.
9974 With prefix ARG, realign all tags in headings in the current buffer."
9975 (interactive "P")
9976 (let* ((re (concat "^" outline-regexp))
9977 (current (org-get-tags-string))
9978 (col (current-column))
9979 (org-setting-tags t)
9980 table current-tags inherited-tags ; computed below when needed
9981 tags p0 c0 c1 rpl)
9982 (if arg
9983 (save-excursion
9984 (goto-char (point-min))
9985 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9986 (while (re-search-forward re nil t)
9987 (org-set-tags nil t)
9988 (end-of-line 1)))
9989 (message "All tags realigned to column %d" org-tags-column))
9990 (if just-align
9991 (setq tags current)
9992 ;; Get a new set of tags from the user
9993 (save-excursion
9994 (setq table (or org-tag-alist (org-get-buffer-tags))
9995 org-last-tags-completion-table table
9996 current-tags (org-split-string current ":")
9997 inherited-tags (nreverse
9998 (nthcdr (length current-tags)
9999 (nreverse (org-get-tags-at))))
10000 tags
10001 (if (or (eq t org-use-fast-tag-selection)
10002 (and org-use-fast-tag-selection
10003 (delq nil (mapcar 'cdr table))))
10004 (org-fast-tag-selection
10005 current-tags inherited-tags table
10006 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10007 (let ((org-add-colon-after-tag-completion t))
10008 (org-trim
10009 (org-without-partial-completion
10010 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10011 nil nil current 'org-tags-history)))))))
10012 (while (string-match "[-+&]+" tags)
10013 ;; No boolean logic, just a list
10014 (setq tags (replace-match ":" t t tags))))
10016 (if (string-match "\\`[\t ]*\\'" tags)
10017 (setq tags "")
10018 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10019 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10021 ;; Insert new tags at the correct column
10022 (beginning-of-line 1)
10023 (cond
10024 ((and (equal current "") (equal tags "")))
10025 ((re-search-forward
10026 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10027 (point-at-eol) t)
10028 (if (equal tags "")
10029 (setq rpl "")
10030 (goto-char (match-beginning 0))
10031 (setq c0 (current-column) p0 (point)
10032 c1 (max (1+ c0) (if (> org-tags-column 0)
10033 org-tags-column
10034 (- (- org-tags-column) (length tags))))
10035 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10036 (replace-match rpl t t)
10037 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10038 tags)
10039 (t (error "Tags alignment failed")))
10040 (org-move-to-column col)
10041 (unless just-align
10042 (run-hooks 'org-after-tags-change-hook)))))
10044 (defun org-change-tag-in-region (beg end tag off)
10045 "Add or remove TAG for each entry in the region.
10046 This works in the agenda, and also in an org-mode buffer."
10047 (interactive
10048 (list (region-beginning) (region-end)
10049 (let ((org-last-tags-completion-table
10050 (if (org-mode-p)
10051 (org-get-buffer-tags)
10052 (org-global-tags-completion-table))))
10053 (org-ido-completing-read
10054 "Tag: " 'org-tags-completion-function nil nil nil
10055 'org-tags-history))
10056 (progn
10057 (message "[s]et or [r]emove? ")
10058 (equal (read-char-exclusive) ?r))))
10059 (if (fboundp 'deactivate-mark) (deactivate-mark))
10060 (let ((agendap (equal major-mode 'org-agenda-mode))
10061 l1 l2 m buf pos newhead (cnt 0))
10062 (goto-char end)
10063 (setq l2 (1- (org-current-line)))
10064 (goto-char beg)
10065 (setq l1 (org-current-line))
10066 (loop for l from l1 to l2 do
10067 (goto-line l)
10068 (setq m (get-text-property (point) 'org-hd-marker))
10069 (when (or (and (org-mode-p) (org-on-heading-p))
10070 (and agendap m))
10071 (setq buf (if agendap (marker-buffer m) (current-buffer))
10072 pos (if agendap m (point)))
10073 (with-current-buffer buf
10074 (save-excursion
10075 (save-restriction
10076 (goto-char pos)
10077 (setq cnt (1+ cnt))
10078 (org-toggle-tag tag (if off 'off 'on))
10079 (setq newhead (org-get-heading)))))
10080 (and agendap (org-agenda-change-all-lines newhead m))))
10081 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10083 (defun org-tags-completion-function (string predicate &optional flag)
10084 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10085 (confirm (lambda (x) (stringp (car x)))))
10086 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10087 (setq s1 (match-string 1 string)
10088 s2 (match-string 2 string))
10089 (setq s1 "" s2 string))
10090 (cond
10091 ((eq flag nil)
10092 ;; try completion
10093 (setq rtn (try-completion s2 ctable confirm))
10094 (if (stringp rtn)
10095 (setq rtn
10096 (concat s1 s2 (substring rtn (length s2))
10097 (if (and org-add-colon-after-tag-completion
10098 (assoc rtn ctable))
10099 ":" ""))))
10100 rtn)
10101 ((eq flag t)
10102 ;; all-completions
10103 (all-completions s2 ctable confirm)
10105 ((eq flag 'lambda)
10106 ;; exact match?
10107 (assoc s2 ctable)))
10110 (defun org-fast-tag-insert (kwd tags face &optional end)
10111 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10112 (insert (format "%-12s" (concat kwd ":"))
10113 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10114 (or end "")))
10116 (defun org-fast-tag-show-exit (flag)
10117 (save-excursion
10118 (goto-line 3)
10119 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10120 (replace-match ""))
10121 (when flag
10122 (end-of-line 1)
10123 (org-move-to-column (- (window-width) 19) t)
10124 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10126 (defun org-set-current-tags-overlay (current prefix)
10127 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10128 (if (featurep 'xemacs)
10129 (org-overlay-display org-tags-overlay (concat prefix s)
10130 'secondary-selection)
10131 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10132 (org-overlay-display org-tags-overlay (concat prefix s)))))
10134 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10135 "Fast tag selection with single keys.
10136 CURRENT is the current list of tags in the headline, INHERITED is the
10137 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10138 possibly with grouping information. TODO-TABLE is a similar table with
10139 TODO keywords, should these have keys assigned to them.
10140 If the keys are nil, a-z are automatically assigned.
10141 Returns the new tags string, or nil to not change the current settings."
10142 (let* ((fulltable (append table todo-table))
10143 (maxlen (apply 'max (mapcar
10144 (lambda (x)
10145 (if (stringp (car x)) (string-width (car x)) 0))
10146 fulltable)))
10147 (buf (current-buffer))
10148 (expert (eq org-fast-tag-selection-single-key 'expert))
10149 (buffer-tags nil)
10150 (fwidth (+ maxlen 3 1 3))
10151 (ncol (/ (- (window-width) 4) fwidth))
10152 (i-face 'org-done)
10153 (c-face 'org-todo)
10154 tg cnt e c char c1 c2 ntable tbl rtn
10155 ov-start ov-end ov-prefix
10156 (exit-after-next org-fast-tag-selection-single-key)
10157 (done-keywords org-done-keywords)
10158 groups ingroup)
10159 (save-excursion
10160 (beginning-of-line 1)
10161 (if (looking-at
10162 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10163 (setq ov-start (match-beginning 1)
10164 ov-end (match-end 1)
10165 ov-prefix "")
10166 (setq ov-start (1- (point-at-eol))
10167 ov-end (1+ ov-start))
10168 (skip-chars-forward "^\n\r")
10169 (setq ov-prefix
10170 (concat
10171 (buffer-substring (1- (point)) (point))
10172 (if (> (current-column) org-tags-column)
10174 (make-string (- org-tags-column (current-column)) ?\ ))))))
10175 (org-move-overlay org-tags-overlay ov-start ov-end)
10176 (save-window-excursion
10177 (if expert
10178 (set-buffer (get-buffer-create " *Org tags*"))
10179 (delete-other-windows)
10180 (split-window-vertically)
10181 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10182 (erase-buffer)
10183 (org-set-local 'org-done-keywords done-keywords)
10184 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10185 (org-fast-tag-insert "Current" current c-face "\n\n")
10186 (org-fast-tag-show-exit exit-after-next)
10187 (org-set-current-tags-overlay current ov-prefix)
10188 (setq tbl fulltable char ?a cnt 0)
10189 (while (setq e (pop tbl))
10190 (cond
10191 ((equal e '(:startgroup))
10192 (push '() groups) (setq ingroup t)
10193 (when (not (= cnt 0))
10194 (setq cnt 0)
10195 (insert "\n"))
10196 (insert "{ "))
10197 ((equal e '(:endgroup))
10198 (setq ingroup nil cnt 0)
10199 (insert "}\n"))
10201 (setq tg (car e) c2 nil)
10202 (if (cdr e)
10203 (setq c (cdr e))
10204 ;; automatically assign a character.
10205 (setq c1 (string-to-char
10206 (downcase (substring
10207 tg (if (= (string-to-char tg) ?@) 1 0)))))
10208 (if (or (rassoc c1 ntable) (rassoc c1 table))
10209 (while (or (rassoc char ntable) (rassoc char table))
10210 (setq char (1+ char)))
10211 (setq c2 c1))
10212 (setq c (or c2 char)))
10213 (if ingroup (push tg (car groups)))
10214 (setq tg (org-add-props tg nil 'face
10215 (cond
10216 ((not (assoc tg table))
10217 (org-get-todo-face tg))
10218 ((member tg current) c-face)
10219 ((member tg inherited) i-face)
10220 (t nil))))
10221 (if (and (= cnt 0) (not ingroup)) (insert " "))
10222 (insert "[" c "] " tg (make-string
10223 (- fwidth 4 (length tg)) ?\ ))
10224 (push (cons tg c) ntable)
10225 (when (= (setq cnt (1+ cnt)) ncol)
10226 (insert "\n")
10227 (if ingroup (insert " "))
10228 (setq cnt 0)))))
10229 (setq ntable (nreverse ntable))
10230 (insert "\n")
10231 (goto-char (point-min))
10232 (if (not expert) (org-fit-window-to-buffer))
10233 (setq rtn
10234 (catch 'exit
10235 (while t
10236 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10237 (if groups " [!] no groups" " [!]groups")
10238 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10239 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10240 (cond
10241 ((= c ?\r) (throw 'exit t))
10242 ((= c ?!)
10243 (setq groups (not groups))
10244 (goto-char (point-min))
10245 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10246 ((= c ?\C-c)
10247 (if (not expert)
10248 (org-fast-tag-show-exit
10249 (setq exit-after-next (not exit-after-next)))
10250 (setq expert nil)
10251 (delete-other-windows)
10252 (split-window-vertically)
10253 (org-switch-to-buffer-other-window " *Org tags*")
10254 (org-fit-window-to-buffer)))
10255 ((or (= c ?\C-g)
10256 (and (= c ?q) (not (rassoc c ntable))))
10257 (org-detach-overlay org-tags-overlay)
10258 (setq quit-flag t))
10259 ((= c ?\ )
10260 (setq current nil)
10261 (if exit-after-next (setq exit-after-next 'now)))
10262 ((= c ?\t)
10263 (condition-case nil
10264 (setq tg (org-ido-completing-read
10265 "Tag: "
10266 (or buffer-tags
10267 (with-current-buffer buf
10268 (org-get-buffer-tags)))))
10269 (quit (setq tg "")))
10270 (when (string-match "\\S-" tg)
10271 (add-to-list 'buffer-tags (list tg))
10272 (if (member tg current)
10273 (setq current (delete tg current))
10274 (push tg current)))
10275 (if exit-after-next (setq exit-after-next 'now)))
10276 ((setq e (rassoc c todo-table) tg (car e))
10277 (with-current-buffer buf
10278 (save-excursion (org-todo tg)))
10279 (if exit-after-next (setq exit-after-next 'now)))
10280 ((setq e (rassoc c ntable) tg (car e))
10281 (if (member tg current)
10282 (setq current (delete tg current))
10283 (loop for g in groups do
10284 (if (member tg g)
10285 (mapc (lambda (x)
10286 (setq current (delete x current)))
10287 g)))
10288 (push tg current))
10289 (if exit-after-next (setq exit-after-next 'now))))
10291 ;; Create a sorted list
10292 (setq current
10293 (sort current
10294 (lambda (a b)
10295 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10296 (if (eq exit-after-next 'now) (throw 'exit t))
10297 (goto-char (point-min))
10298 (beginning-of-line 2)
10299 (delete-region (point) (point-at-eol))
10300 (org-fast-tag-insert "Current" current c-face)
10301 (org-set-current-tags-overlay current ov-prefix)
10302 (while (re-search-forward
10303 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10304 (setq tg (match-string 1))
10305 (add-text-properties
10306 (match-beginning 1) (match-end 1)
10307 (list 'face
10308 (cond
10309 ((member tg current) c-face)
10310 ((member tg inherited) i-face)
10311 (t (get-text-property (match-beginning 1) 'face))))))
10312 (goto-char (point-min)))))
10313 (org-detach-overlay org-tags-overlay)
10314 (if rtn
10315 (mapconcat 'identity current ":")
10316 nil))))
10318 (defun org-get-tags-string ()
10319 "Get the TAGS string in the current headline."
10320 (unless (org-on-heading-p t)
10321 (error "Not on a heading"))
10322 (save-excursion
10323 (beginning-of-line 1)
10324 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10325 (org-match-string-no-properties 1)
10326 "")))
10328 (defun org-get-tags ()
10329 "Get the list of tags specified in the current headline."
10330 (org-split-string (org-get-tags-string) ":"))
10332 (defun org-get-buffer-tags ()
10333 "Get a table of all tags used in the buffer, for completion."
10334 (let (tags)
10335 (save-excursion
10336 (goto-char (point-min))
10337 (while (re-search-forward
10338 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10339 (when (equal (char-after (point-at-bol 0)) ?*)
10340 (mapc (lambda (x) (add-to-list 'tags x))
10341 (org-split-string (org-match-string-no-properties 1) ":")))))
10342 (mapcar 'list tags)))
10344 ;;;; The mapping API
10346 ;;;###autoload
10347 (defun org-map-entries (func &optional match scope &rest skip)
10348 "Call FUNC at each headline selected by MATCH in SCOPE.
10350 FUNC is a function or a lisp form. The function will be called without
10351 arguments, with the cursor positioned at the beginning of the headline.
10352 The return values of all calls to the function will be collected and
10353 returned as a list.
10355 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10356 Only headlines that are matched by this query will be considered during
10357 the iteration. When MATCH is nil or t, all headlines will be
10358 visited by the iteration.
10360 SCOPE determines the scope of this command. It can be any of:
10362 nil The current buffer, respecting the restriction if any
10363 tree The subtree started with the entry at point
10364 file The current buffer, without restriction
10365 file-with-archives
10366 The current buffer, and any archives associated with it
10367 agenda All agenda files
10368 agenda-with-archives
10369 All agenda files with any archive files associated with them
10370 \(file1 file2 ...)
10371 If this is a list, all files in the list will be scanned
10373 The remaining args are treated as settings for the skipping facilities of
10374 the scanner. The following items can be given here:
10376 archive skip trees with the archive tag.
10377 comment skip trees with the COMMENT keyword
10378 function or Emacs Lisp form:
10379 will be used as value for `org-agenda-skip-function', so whenever
10380 the the function returns t, FUNC will not be called for that
10381 entry and search will continue from the point where the
10382 function leaves it."
10383 (let* ((org-agenda-archives-mode nil) ; just to make sure
10384 (org-agenda-skip-archived-trees (memq 'archive skip))
10385 (org-agenda-skip-comment-trees (memq 'comment skip))
10386 (org-agenda-skip-function
10387 (car (org-delete-all '(comment archive) skip)))
10388 (org-tags-match-list-sublevels t)
10389 matcher file res
10390 org-todo-keywords-for-agenda
10391 org-done-keywords-for-agenda
10392 org-todo-keyword-alist-for-agenda
10393 org-tag-alist-for-agenda)
10395 (cond
10396 ((eq match t) (setq matcher t))
10397 ((eq match nil) (setq matcher t))
10398 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10400 (save-excursion
10401 (save-restriction
10402 (when (eq scope 'tree)
10403 (org-back-to-heading t)
10404 (org-narrow-to-subtree)
10405 (setq scope nil))
10407 (if (not scope)
10408 (progn
10409 (org-prepare-agenda-buffers
10410 (list (buffer-file-name (current-buffer))))
10411 (setq res (org-scan-tags func matcher)))
10412 ;; Get the right scope
10413 (cond
10414 ((and scope (listp scope) (symbolp (car scope)))
10415 (setq scope (eval scope)))
10416 ((eq scope 'agenda)
10417 (setq scope (org-agenda-files t)))
10418 ((eq scope 'agenda-with-archives)
10419 (setq scope (org-agenda-files t))
10420 (setq scope (org-add-archive-files scope)))
10421 ((eq scope 'file)
10422 (setq scope (list (buffer-file-name))))
10423 ((eq scope 'file-with-archives)
10424 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10425 (org-prepare-agenda-buffers scope)
10426 (while (setq file (pop scope))
10427 (with-current-buffer (org-find-base-buffer-visiting file)
10428 (save-excursion
10429 (save-restriction
10430 (widen)
10431 (goto-char (point-min))
10432 (setq res (append res (org-scan-tags func matcher))))))))))
10433 res))
10435 ;;;; Properties
10437 ;;; Setting and retrieving properties
10439 (defconst org-special-properties
10440 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10441 "TIMESTAMP" "TIMESTAMP_IA")
10442 "The special properties valid in Org-mode.
10444 These are properties that are not defined in the property drawer,
10445 but in some other way.")
10447 (defconst org-default-properties
10448 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10449 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10450 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10451 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10452 "Some properties that are used by Org-mode for various purposes.
10453 Being in this list makes sure that they are offered for completion.")
10455 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10456 "Regular expression matching the first line of a property drawer.")
10458 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10459 "Regular expression matching the first line of a property drawer.")
10461 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10462 "Regular expression matching the first line of a property drawer.")
10464 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10465 "Regular expression matching the first line of a property drawer.")
10467 (defconst org-property-drawer-re
10468 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10469 org-property-end-re "\\)\n?")
10470 "Matches an entire property drawer.")
10472 (defconst org-clock-drawer-re
10473 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10474 org-property-end-re "\\)\n?")
10475 "Matches an entire clock drawer.")
10477 (defun org-property-action ()
10478 "Do an action on properties."
10479 (interactive)
10480 (let (c)
10481 (org-at-property-p)
10482 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10483 (setq c (read-char-exclusive))
10484 (cond
10485 ((equal c ?s)
10486 (call-interactively 'org-set-property))
10487 ((equal c ?d)
10488 (call-interactively 'org-delete-property))
10489 ((equal c ?D)
10490 (call-interactively 'org-delete-property-globally))
10491 ((equal c ?c)
10492 (call-interactively 'org-compute-property-at-point))
10493 (t (error "No such property action %c" c)))))
10495 (defun org-at-property-p ()
10496 "Is the cursor in a property line?"
10497 ;; FIXME: Does not check if we are actually in the drawer.
10498 ;; FIXME: also returns true on any drawers.....
10499 ;; This is used by C-c C-c for property action.
10500 (save-excursion
10501 (beginning-of-line 1)
10502 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10504 (defun org-get-property-block (&optional beg end force)
10505 "Return the (beg . end) range of the body of the property drawer.
10506 BEG and END can be beginning and end of subtree, if not given
10507 they will be found.
10508 If the drawer does not exist and FORCE is non-nil, create the drawer."
10509 (catch 'exit
10510 (save-excursion
10511 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10512 (end (or end (progn (outline-next-heading) (point)))))
10513 (goto-char beg)
10514 (if (re-search-forward org-property-start-re end t)
10515 (setq beg (1+ (match-end 0)))
10516 (if force
10517 (save-excursion
10518 (org-insert-property-drawer)
10519 (setq end (progn (outline-next-heading) (point))))
10520 (throw 'exit nil))
10521 (goto-char beg)
10522 (if (re-search-forward org-property-start-re end t)
10523 (setq beg (1+ (match-end 0)))))
10524 (if (re-search-forward org-property-end-re end t)
10525 (setq end (match-beginning 0))
10526 (or force (throw 'exit nil))
10527 (goto-char beg)
10528 (setq end beg)
10529 (org-indent-line-function)
10530 (insert ":END:\n"))
10531 (cons beg end)))))
10533 (defun org-entry-properties (&optional pom which)
10534 "Get all properties of the entry at point-or-marker POM.
10535 This includes the TODO keyword, the tags, time strings for deadline,
10536 scheduled, and clocking, and any additional properties defined in the
10537 entry. The return value is an alist, keys may occur multiple times
10538 if the property key was used several times.
10539 POM may also be nil, in which case the current entry is used.
10540 If WHICH is nil or `all', get all properties. If WHICH is
10541 `special' or `standard', only get that subclass."
10542 (setq which (or which 'all))
10543 (org-with-point-at pom
10544 (let ((clockstr (substring org-clock-string 0 -1))
10545 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10546 beg end range props sum-props key value string clocksum)
10547 (save-excursion
10548 (when (condition-case nil
10549 (and (org-mode-p) (org-back-to-heading t))
10550 (error nil))
10551 (setq beg (point))
10552 (setq sum-props (get-text-property (point) 'org-summaries))
10553 (setq clocksum (get-text-property (point) :org-clock-minutes))
10554 (outline-next-heading)
10555 (setq end (point))
10556 (when (memq which '(all special))
10557 ;; Get the special properties, like TODO and tags
10558 (goto-char beg)
10559 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10560 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10561 (when (looking-at org-priority-regexp)
10562 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10563 (when (and (setq value (org-get-tags-string))
10564 (string-match "\\S-" value))
10565 (push (cons "TAGS" value) props))
10566 (when (setq value (org-get-tags-at))
10567 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10568 props))
10569 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10570 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10571 string (if (equal key clockstr)
10572 (org-no-properties
10573 (org-trim
10574 (buffer-substring
10575 (match-beginning 3) (goto-char (point-at-eol)))))
10576 (substring (org-match-string-no-properties 3) 1 -1)))
10577 (unless key
10578 (if (= (char-after (match-beginning 3)) ?\[)
10579 (setq key "TIMESTAMP_IA")
10580 (setq key "TIMESTAMP")))
10581 (when (or (equal key clockstr) (not (assoc key props)))
10582 (push (cons key string) props)))
10586 (when (memq which '(all standard))
10587 ;; Get the standard properties, like :PORP: ...
10588 (setq range (org-get-property-block beg end))
10589 (when range
10590 (goto-char (car range))
10591 (while (re-search-forward
10592 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10593 (cdr range) t)
10594 (setq key (org-match-string-no-properties 1)
10595 value (org-trim (or (org-match-string-no-properties 2) "")))
10596 (unless (member key excluded)
10597 (push (cons key (or value "")) props)))))
10598 (if clocksum
10599 (push (cons "CLOCKSUM"
10600 (org-columns-number-to-string (/ (float clocksum) 60.)
10601 'add_times))
10602 props))
10603 (unless (assoc "CATEGORY" props)
10604 (setq value (or (org-get-category)
10605 (progn (org-refresh-category-properties)
10606 (org-get-category))))
10607 (push (cons "CATEGORY" value) props))
10608 (append sum-props (nreverse props)))))))
10610 (defun org-entry-get (pom property &optional inherit)
10611 "Get value of PROPERTY for entry at point-or-marker POM.
10612 If INHERIT is non-nil and the entry does not have the property,
10613 then also check higher levels of the hierarchy.
10614 If INHERIT is the symbol `selective', use inheritance only if the setting
10615 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10616 If the property is present but empty, the return value is the empty string.
10617 If the property is not present at all, nil is returned."
10618 (org-with-point-at pom
10619 (if (and inherit (if (eq inherit 'selective)
10620 (org-property-inherit-p property)
10622 (org-entry-get-with-inheritance property)
10623 (if (member property org-special-properties)
10624 ;; We need a special property. Use brute force, get all properties.
10625 (cdr (assoc property (org-entry-properties nil 'special)))
10626 (let ((range (org-get-property-block)))
10627 (if (and range
10628 (goto-char (car range))
10629 (re-search-forward
10630 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10631 (cdr range) t))
10632 ;; Found the property, return it.
10633 (if (match-end 1)
10634 (org-match-string-no-properties 1)
10635 "")))))))
10637 (defun org-property-or-variable-value (var &optional inherit)
10638 "Check if there is a property fixing the value of VAR.
10639 If yes, return this value. If not, return the current value of the variable."
10640 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10641 (if (and prop (stringp prop) (string-match "\\S-" prop))
10642 (read prop)
10643 (symbol-value var))))
10645 (defun org-entry-delete (pom property)
10646 "Delete the property PROPERTY from entry at point-or-marker POM."
10647 (org-with-point-at pom
10648 (if (member property org-special-properties)
10649 nil ; cannot delete these properties.
10650 (let ((range (org-get-property-block)))
10651 (if (and range
10652 (goto-char (car range))
10653 (re-search-forward
10654 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10655 (cdr range) t))
10656 (progn
10657 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10659 nil)))))
10661 ;; Multi-values properties are properties that contain multiple values
10662 ;; These values are assumed to be single words, separated by whitespace.
10663 (defun org-entry-add-to-multivalued-property (pom property value)
10664 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10665 (let* ((old (org-entry-get pom property))
10666 (values (and old (org-split-string old "[ \t]"))))
10667 (setq value (org-entry-protect-space value))
10668 (unless (member value values)
10669 (setq values (cons value values))
10670 (org-entry-put pom property
10671 (mapconcat 'identity values " ")))))
10673 (defun org-entry-remove-from-multivalued-property (pom property value)
10674 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10675 (let* ((old (org-entry-get pom property))
10676 (values (and old (org-split-string old "[ \t]"))))
10677 (setq value (org-entry-protect-space value))
10678 (when (member value values)
10679 (setq values (delete value values))
10680 (org-entry-put pom property
10681 (mapconcat 'identity values " ")))))
10683 (defun org-entry-member-in-multivalued-property (pom property value)
10684 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10685 (let* ((old (org-entry-get pom property))
10686 (values (and old (org-split-string old "[ \t]"))))
10687 (setq value (org-entry-protect-space value))
10688 (member value values)))
10690 (defun org-entry-get-multivalued-property (pom property)
10691 "Return a list of values in a multivalued property."
10692 (let* ((value (org-entry-get pom property))
10693 (values (and value (org-split-string value "[ \t]"))))
10694 (mapcar 'org-entry-restore-space values)))
10696 (defun org-entry-put-multivalued-property (pom property &rest values)
10697 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10698 VALUES should be a list of strings. Spaces will be protected."
10699 (org-entry-put pom property
10700 (mapconcat 'org-entry-protect-space values " "))
10701 (let* ((value (org-entry-get pom property))
10702 (values (and value (org-split-string value "[ \t]"))))
10703 (mapcar 'org-entry-restore-space values)))
10705 (defun org-entry-protect-space (s)
10706 "Protect spaces and newline in string S."
10707 (while (string-match " " s)
10708 (setq s (replace-match "%20" t t s)))
10709 (while (string-match "\n" s)
10710 (setq s (replace-match "%0A" t t s)))
10713 (defun org-entry-restore-space (s)
10714 "Restore spaces and newline in string S."
10715 (while (string-match "%20" s)
10716 (setq s (replace-match " " t t s)))
10717 (while (string-match "%0A" s)
10718 (setq s (replace-match "\n" t t s)))
10721 (defvar org-entry-property-inherited-from (make-marker)
10722 "Marker pointing to the entry from where a property was inherited.
10723 Each call to `org-entry-get-with-inheritance' will set this marker to the
10724 location of the entry where the inheritance search matched. If there was
10725 no match, the marker will point nowhere.
10726 Note that also `org-entry-get' calls this function, if the INHERIT flag
10727 is set.")
10729 (defun org-entry-get-with-inheritance (property)
10730 "Get entry property, and search higher levels if not present."
10731 (move-marker org-entry-property-inherited-from nil)
10732 (let (tmp)
10733 (save-excursion
10734 (save-restriction
10735 (widen)
10736 (catch 'ex
10737 (while t
10738 (when (setq tmp (org-entry-get nil property))
10739 (org-back-to-heading t)
10740 (move-marker org-entry-property-inherited-from (point))
10741 (throw 'ex tmp))
10742 (or (org-up-heading-safe) (throw 'ex nil)))))
10743 (or tmp
10744 (cdr (assoc property org-file-properties))
10745 (cdr (assoc property org-global-properties))
10746 (cdr (assoc property org-global-properties-fixed))))))
10748 (defun org-entry-put (pom property value)
10749 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10750 (org-with-point-at pom
10751 (org-back-to-heading t)
10752 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10753 range)
10754 (cond
10755 ((equal property "TODO")
10756 (when (and (stringp value) (string-match "\\S-" value)
10757 (not (member value org-todo-keywords-1)))
10758 (error "\"%s\" is not a valid TODO state" value))
10759 (if (or (not value)
10760 (not (string-match "\\S-" value)))
10761 (setq value 'none))
10762 (org-todo value)
10763 (org-set-tags nil 'align))
10764 ((equal property "PRIORITY")
10765 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10766 (string-to-char value) ?\ ))
10767 (org-set-tags nil 'align))
10768 ((equal property "SCHEDULED")
10769 (if (re-search-forward org-scheduled-time-regexp end t)
10770 (cond
10771 ((eq value 'earlier) (org-timestamp-change -1 'day))
10772 ((eq value 'later) (org-timestamp-change 1 'day))
10773 (t (call-interactively 'org-schedule)))
10774 (call-interactively 'org-schedule)))
10775 ((equal property "DEADLINE")
10776 (if (re-search-forward org-deadline-time-regexp end t)
10777 (cond
10778 ((eq value 'earlier) (org-timestamp-change -1 'day))
10779 ((eq value 'later) (org-timestamp-change 1 'day))
10780 (t (call-interactively 'org-deadline)))
10781 (call-interactively 'org-deadline)))
10782 ((member property org-special-properties)
10783 (error "The %s property can not yet be set with `org-entry-put'"
10784 property))
10785 (t ; a non-special property
10786 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10787 (setq range (org-get-property-block beg end 'force))
10788 (goto-char (car range))
10789 (if (re-search-forward
10790 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10791 (progn
10792 (delete-region (match-beginning 1) (match-end 1))
10793 (goto-char (match-beginning 1)))
10794 (goto-char (cdr range))
10795 (insert "\n")
10796 (backward-char 1)
10797 (org-indent-line-function)
10798 (insert ":" property ":"))
10799 (and value (insert " " value))
10800 (org-indent-line-function)))))))
10802 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10803 "Get all property keys in the current buffer.
10804 With INCLUDE-SPECIALS, also list the special properties that reflect things
10805 like tags and TODO state.
10806 With INCLUDE-DEFAULTS, also include properties that has special meaning
10807 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10808 With INCLUDE-COLUMNS, also include property names given in COLUMN
10809 formats in the current buffer."
10810 (let (rtn range cfmt s p)
10811 (save-excursion
10812 (save-restriction
10813 (widen)
10814 (goto-char (point-min))
10815 (while (re-search-forward org-property-start-re nil t)
10816 (setq range (org-get-property-block))
10817 (goto-char (car range))
10818 (while (re-search-forward
10819 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10820 (cdr range) t)
10821 (add-to-list 'rtn (org-match-string-no-properties 1)))
10822 (outline-next-heading))))
10824 (when include-specials
10825 (setq rtn (append org-special-properties rtn)))
10827 (when include-defaults
10828 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10830 (when include-columns
10831 (save-excursion
10832 (save-restriction
10833 (widen)
10834 (goto-char (point-min))
10835 (while (re-search-forward
10836 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10837 nil t)
10838 (setq cfmt (match-string 2) s 0)
10839 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10840 cfmt s)
10841 (setq s (match-end 0)
10842 p (match-string 1 cfmt))
10843 (unless (or (equal p "ITEM")
10844 (member p org-special-properties))
10845 (add-to-list 'rtn (match-string 1 cfmt))))))))
10847 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10849 (defun org-property-values (key)
10850 "Return a list of all values of property KEY."
10851 (save-excursion
10852 (save-restriction
10853 (widen)
10854 (goto-char (point-min))
10855 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10856 values)
10857 (while (re-search-forward re nil t)
10858 (add-to-list 'values (org-trim (match-string 1))))
10859 (delete "" values)))))
10861 (defun org-insert-property-drawer ()
10862 "Insert a property drawer into the current entry."
10863 (interactive)
10864 (org-back-to-heading t)
10865 (looking-at outline-regexp)
10866 (let ((indent (- (match-end 0)(match-beginning 0)))
10867 (beg (point))
10868 (re (concat "^[ \t]*" org-keyword-time-regexp))
10869 end hiddenp)
10870 (outline-next-heading)
10871 (setq end (point))
10872 (goto-char beg)
10873 (while (re-search-forward re end t))
10874 (setq hiddenp (org-invisible-p))
10875 (end-of-line 1)
10876 (and (equal (char-after) ?\n) (forward-char 1))
10877 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10878 (beginning-of-line 2))
10879 (org-skip-over-state-notes)
10880 (skip-chars-backward " \t\n\r")
10881 (if (eq (char-before) ?*) (forward-char 1))
10882 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10883 (beginning-of-line 0)
10884 (org-indent-to-column indent)
10885 (beginning-of-line 2)
10886 (org-indent-to-column indent)
10887 (beginning-of-line 0)
10888 (if hiddenp
10889 (save-excursion
10890 (org-back-to-heading t)
10891 (hide-entry))
10892 (org-flag-drawer t))))
10894 (defun org-set-property (property value)
10895 "In the current entry, set PROPERTY to VALUE.
10896 When called interactively, this will prompt for a property name, offering
10897 completion on existing and default properties. And then it will prompt
10898 for a value, offering completion either on allowed values (via an inherited
10899 xxx_ALL property) or on existing values in other instances of this property
10900 in the current file."
10901 (interactive
10902 (let* ((completion-ignore-case t)
10903 (keys (org-buffer-property-keys nil t t))
10904 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10905 (prop (if (member prop0 keys)
10906 prop0
10907 (or (cdr (assoc (downcase prop0)
10908 (mapcar (lambda (x) (cons (downcase x) x))
10909 keys)))
10910 prop0)))
10911 (cur (org-entry-get nil prop))
10912 (allowed (org-property-get-allowed-values nil prop 'table))
10913 (existing (mapcar 'list (org-property-values prop)))
10914 (val (if allowed
10915 (org-completing-read "Value: " allowed nil 'req-match)
10916 (org-completing-read
10917 (concat "Value" (if (and cur (string-match "\\S-" cur))
10918 (concat "[" cur "]") "")
10919 ": ")
10920 existing nil nil "" nil cur))))
10921 (list prop (if (equal val "") cur val))))
10922 (unless (equal (org-entry-get nil property) value)
10923 (org-entry-put nil property value)))
10925 (defun org-delete-property (property)
10926 "In the current entry, delete PROPERTY."
10927 (interactive
10928 (let* ((completion-ignore-case t)
10929 (prop (org-ido-completing-read
10930 "Property: " (org-entry-properties nil 'standard))))
10931 (list prop)))
10932 (message "Property %s %s" property
10933 (if (org-entry-delete nil property)
10934 "deleted"
10935 "was not present in the entry")))
10937 (defun org-delete-property-globally (property)
10938 "Remove PROPERTY globally, from all entries."
10939 (interactive
10940 (let* ((completion-ignore-case t)
10941 (prop (org-ido-completing-read
10942 "Globally remove property: "
10943 (mapcar 'list (org-buffer-property-keys)))))
10944 (list prop)))
10945 (save-excursion
10946 (save-restriction
10947 (widen)
10948 (goto-char (point-min))
10949 (let ((cnt 0))
10950 (while (re-search-forward
10951 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10952 nil t)
10953 (setq cnt (1+ cnt))
10954 (replace-match ""))
10955 (message "Property \"%s\" removed from %d entries" property cnt)))))
10957 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10959 (defun org-compute-property-at-point ()
10960 "Compute the property at point.
10961 This looks for an enclosing column format, extracts the operator and
10962 then applies it to the property in the column format's scope."
10963 (interactive)
10964 (unless (org-at-property-p)
10965 (error "Not at a property"))
10966 (let ((prop (org-match-string-no-properties 2)))
10967 (org-columns-get-format-and-top-level)
10968 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10969 (error "No operator defined for property %s" prop))
10970 (org-columns-compute prop)))
10972 (defun org-property-get-allowed-values (pom property &optional table)
10973 "Get allowed values for the property PROPERTY.
10974 When TABLE is non-nil, return an alist that can directly be used for
10975 completion."
10976 (let (vals)
10977 (cond
10978 ((equal property "TODO")
10979 (setq vals (org-with-point-at pom
10980 (append org-todo-keywords-1 '("")))))
10981 ((equal property "PRIORITY")
10982 (let ((n org-lowest-priority))
10983 (while (>= n org-highest-priority)
10984 (push (char-to-string n) vals)
10985 (setq n (1- n)))))
10986 ((member property org-special-properties))
10988 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10990 (when (and vals (string-match "\\S-" vals))
10991 (setq vals (car (read-from-string (concat "(" vals ")"))))
10992 (setq vals (mapcar (lambda (x)
10993 (cond ((stringp x) x)
10994 ((numberp x) (number-to-string x))
10995 ((symbolp x) (symbol-name x))
10996 (t "???")))
10997 vals)))))
10998 (if table (mapcar 'list vals) vals)))
11000 (defun org-property-previous-allowed-value (&optional previous)
11001 "Switch to the next allowed value for this property."
11002 (interactive)
11003 (org-property-next-allowed-value t))
11005 (defun org-property-next-allowed-value (&optional previous)
11006 "Switch to the next allowed value for this property."
11007 (interactive)
11008 (unless (org-at-property-p)
11009 (error "Not at a property"))
11010 (let* ((key (match-string 2))
11011 (value (match-string 3))
11012 (allowed (or (org-property-get-allowed-values (point) key)
11013 (and (member value '("[ ]" "[-]" "[X]"))
11014 '("[ ]" "[X]"))))
11015 nval)
11016 (unless allowed
11017 (error "Allowed values for this property have not been defined"))
11018 (if previous (setq allowed (reverse allowed)))
11019 (if (member value allowed)
11020 (setq nval (car (cdr (member value allowed)))))
11021 (setq nval (or nval (car allowed)))
11022 (if (equal nval value)
11023 (error "Only one allowed value for this property"))
11024 (org-at-property-p)
11025 (replace-match (concat " :" key ": " nval) t t)
11026 (org-indent-line-function)
11027 (beginning-of-line 1)
11028 (skip-chars-forward " \t")))
11030 (defun org-find-entry-with-id (ident)
11031 "Locate the entry that contains the ID property with exact value IDENT.
11032 IDENT can be a string, a symbol or a number, this function will search for
11033 the string representation of it.
11034 Return the position where this entry starts, or nil if there is no such entry."
11035 (interactive "sID: ")
11036 (let ((id (cond
11037 ((stringp ident) ident)
11038 ((symbol-name ident) (symbol-name ident))
11039 ((numberp ident) (number-to-string ident))
11040 (t (error "IDENT %s must be a string, symbol or number" ident))))
11041 (case-fold-search nil))
11042 (save-excursion
11043 (save-restriction
11044 (widen)
11045 (goto-char (point-min))
11046 (when (re-search-forward
11047 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11048 nil t)
11049 (org-back-to-heading)
11050 (point))))))
11052 ;;;; Timestamps
11054 (defvar org-last-changed-timestamp nil)
11055 (defvar org-last-inserted-timestamp nil
11056 "The last time stamp inserted with `org-insert-time-stamp'.")
11057 (defvar org-time-was-given) ; dynamically scoped parameter
11058 (defvar org-end-time-was-given) ; dynamically scoped parameter
11059 (defvar org-ts-what) ; dynamically scoped parameter
11061 (defun org-time-stamp (arg &optional inactive)
11062 "Prompt for a date/time and insert a time stamp.
11063 If the user specifies a time like HH:MM, or if this command is called
11064 with a prefix argument, the time stamp will contain date and time.
11065 Otherwise, only the date will be included. All parts of a date not
11066 specified by the user will be filled in from the current date/time.
11067 So if you press just return without typing anything, the time stamp
11068 will represent the current date/time. If there is already a timestamp
11069 at the cursor, it will be modified."
11070 (interactive "P")
11071 (let* ((ts nil)
11072 (default-time
11073 ;; Default time is either today, or, when entering a range,
11074 ;; the range start.
11075 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11076 (save-excursion
11077 (re-search-backward
11078 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11079 (- (point) 20) t)))
11080 (apply 'encode-time (org-parse-time-string (match-string 1)))
11081 (current-time)))
11082 (default-input (and ts (org-get-compact-tod ts)))
11083 org-time-was-given org-end-time-was-given time)
11084 (cond
11085 ((and (org-at-timestamp-p t)
11086 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11087 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11088 (insert "--")
11089 (setq time (let ((this-command this-command))
11090 (org-read-date arg 'totime nil nil
11091 default-time default-input)))
11092 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11093 ((org-at-timestamp-p t)
11094 (setq time (let ((this-command this-command))
11095 (org-read-date arg 'totime nil nil default-time default-input)))
11096 (when (org-at-timestamp-p t) ; just to get the match data
11097 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11098 (replace-match "")
11099 (setq org-last-changed-timestamp
11100 (org-insert-time-stamp
11101 time (or org-time-was-given arg)
11102 inactive nil nil (list org-end-time-was-given))))
11103 (message "Timestamp updated"))
11105 (setq time (let ((this-command this-command))
11106 (org-read-date arg 'totime nil nil default-time default-input)))
11107 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11108 nil nil (list org-end-time-was-given))))))
11110 ;; FIXME: can we use this for something else, like computing time differences?
11111 (defun org-get-compact-tod (s)
11112 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11113 (let* ((t1 (match-string 1 s))
11114 (h1 (string-to-number (match-string 2 s)))
11115 (m1 (string-to-number (match-string 3 s)))
11116 (t2 (and (match-end 4) (match-string 5 s)))
11117 (h2 (and t2 (string-to-number (match-string 6 s))))
11118 (m2 (and t2 (string-to-number (match-string 7 s))))
11119 dh dm)
11120 (if (not t2)
11122 (setq dh (- h2 h1) dm (- m2 m1))
11123 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11124 (concat t1 "+" (number-to-string dh)
11125 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11127 (defun org-time-stamp-inactive (&optional arg)
11128 "Insert an inactive time stamp.
11129 An inactive time stamp is enclosed in square brackets instead of angle
11130 brackets. It is inactive in the sense that it does not trigger agenda entries,
11131 does not link to the calendar and cannot be changed with the S-cursor keys.
11132 So these are more for recording a certain time/date."
11133 (interactive "P")
11134 (org-time-stamp arg 'inactive))
11136 (defvar org-date-ovl (org-make-overlay 1 1))
11137 (org-overlay-put org-date-ovl 'face 'org-warning)
11138 (org-detach-overlay org-date-ovl)
11140 (defvar org-ans1) ; dynamically scoped parameter
11141 (defvar org-ans2) ; dynamically scoped parameter
11143 (defvar org-plain-time-of-day-regexp) ; defined below
11145 (defvar org-overriding-default-time nil) ; dynamically scoped
11146 (defvar org-read-date-overlay nil)
11147 (defvar org-dcst nil) ; dynamically scoped
11149 (defun org-read-date (&optional with-time to-time from-string prompt
11150 default-time default-input)
11151 "Read a date, possibly a time, and make things smooth for the user.
11152 The prompt will suggest to enter an ISO date, but you can also enter anything
11153 which will at least partially be understood by `parse-time-string'.
11154 Unrecognized parts of the date will default to the current day, month, year,
11155 hour and minute. If this command is called to replace a timestamp at point,
11156 of to enter the second timestamp of a range, the default time is taken from the
11157 existing stamp. For example,
11158 3-2-5 --> 2003-02-05
11159 feb 15 --> currentyear-02-15
11160 sep 12 9 --> 2009-09-12
11161 12:45 --> today 12:45
11162 22 sept 0:34 --> currentyear-09-22 0:34
11163 12 --> currentyear-currentmonth-12
11164 Fri --> nearest Friday (today or later)
11165 etc.
11167 Furthermore you can specify a relative date by giving, as the *first* thing
11168 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11169 change in days weeks, months, years.
11170 With a single plus or minus, the date is relative to today. With a double
11171 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11172 +4d --> four days from today
11173 +4 --> same as above
11174 +2w --> two weeks from today
11175 ++5 --> five days from default date
11177 The function understands only English month and weekday abbreviations,
11178 but this can be configured with the variables `parse-time-months' and
11179 `parse-time-weekdays'.
11181 While prompting, a calendar is popped up - you can also select the
11182 date with the mouse (button 1). The calendar shows a period of three
11183 months. To scroll it to other months, use the keys `>' and `<'.
11184 If you don't like the calendar, turn it off with
11185 \(setq org-read-date-popup-calendar nil)
11187 With optional argument TO-TIME, the date will immediately be converted
11188 to an internal time.
11189 With an optional argument WITH-TIME, the prompt will suggest to also
11190 insert a time. Note that when WITH-TIME is not set, you can still
11191 enter a time, and this function will inform the calling routine about
11192 this change. The calling routine may then choose to change the format
11193 used to insert the time stamp into the buffer to include the time.
11194 With optional argument FROM-STRING, read from this string instead from
11195 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11196 the time/date that is used for everything that is not specified by the
11197 user."
11198 (require 'parse-time)
11199 (let* ((org-time-stamp-rounding-minutes
11200 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11201 (org-dcst org-display-custom-times)
11202 (ct (org-current-time))
11203 (def (or org-overriding-default-time default-time ct))
11204 (defdecode (decode-time def))
11205 (dummy (progn
11206 (when (< (nth 2 defdecode) org-extend-today-until)
11207 (setcar (nthcdr 2 defdecode) -1)
11208 (setcar (nthcdr 1 defdecode) 59)
11209 (setq def (apply 'encode-time defdecode)
11210 defdecode (decode-time def)))))
11211 (calendar-move-hook nil)
11212 (calendar-view-diary-initially-flag nil)
11213 (view-diary-entries-initially nil)
11214 (calendar-view-holidays-initially-flag nil)
11215 (view-calendar-holidays-initially nil)
11216 (timestr (format-time-string
11217 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11218 (prompt (concat (if prompt (concat prompt " ") "")
11219 (format "Date+time [%s]: " timestr)))
11220 ans (org-ans0 "") org-ans1 org-ans2 final)
11222 (cond
11223 (from-string (setq ans from-string))
11224 (org-read-date-popup-calendar
11225 (save-excursion
11226 (save-window-excursion
11227 (calendar)
11228 (calendar-forward-day (- (time-to-days def)
11229 (calendar-absolute-from-gregorian
11230 (calendar-current-date))))
11231 (org-eval-in-calendar nil t)
11232 (let* ((old-map (current-local-map))
11233 (map (copy-keymap calendar-mode-map))
11234 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11235 (org-defkey map (kbd "RET") 'org-calendar-select)
11236 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11237 'org-calendar-select-mouse)
11238 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11239 'org-calendar-select-mouse)
11240 (org-defkey minibuffer-local-map [(meta shift left)]
11241 (lambda () (interactive)
11242 (org-eval-in-calendar '(calendar-backward-month 1))))
11243 (org-defkey minibuffer-local-map [(meta shift right)]
11244 (lambda () (interactive)
11245 (org-eval-in-calendar '(calendar-forward-month 1))))
11246 (org-defkey minibuffer-local-map [(meta shift up)]
11247 (lambda () (interactive)
11248 (org-eval-in-calendar '(calendar-backward-year 1))))
11249 (org-defkey minibuffer-local-map [(meta shift down)]
11250 (lambda () (interactive)
11251 (org-eval-in-calendar '(calendar-forward-year 1))))
11252 (org-defkey minibuffer-local-map [(shift up)]
11253 (lambda () (interactive)
11254 (org-eval-in-calendar '(calendar-backward-week 1))))
11255 (org-defkey minibuffer-local-map [(shift down)]
11256 (lambda () (interactive)
11257 (org-eval-in-calendar '(calendar-forward-week 1))))
11258 (org-defkey minibuffer-local-map [(shift left)]
11259 (lambda () (interactive)
11260 (org-eval-in-calendar '(calendar-backward-day 1))))
11261 (org-defkey minibuffer-local-map [(shift right)]
11262 (lambda () (interactive)
11263 (org-eval-in-calendar '(calendar-forward-day 1))))
11264 (org-defkey minibuffer-local-map ">"
11265 (lambda () (interactive)
11266 (org-eval-in-calendar '(scroll-calendar-left 1))))
11267 (org-defkey minibuffer-local-map "<"
11268 (lambda () (interactive)
11269 (org-eval-in-calendar '(scroll-calendar-right 1))))
11270 (unwind-protect
11271 (progn
11272 (use-local-map map)
11273 (add-hook 'post-command-hook 'org-read-date-display)
11274 (setq org-ans0 (read-string prompt default-input nil nil))
11275 ;; org-ans0: from prompt
11276 ;; org-ans1: from mouse click
11277 ;; org-ans2: from calendar motion
11278 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11279 (remove-hook 'post-command-hook 'org-read-date-display)
11280 (use-local-map old-map)
11281 (when org-read-date-overlay
11282 (org-delete-overlay org-read-date-overlay)
11283 (setq org-read-date-overlay nil)))))))
11285 (t ; Naked prompt only
11286 (unwind-protect
11287 (setq ans (read-string prompt default-input nil timestr))
11288 (when org-read-date-overlay
11289 (org-delete-overlay org-read-date-overlay)
11290 (setq org-read-date-overlay nil)))))
11292 (setq final (org-read-date-analyze ans def defdecode))
11294 (if to-time
11295 (apply 'encode-time final)
11296 (if (and (boundp 'org-time-was-given) org-time-was-given)
11297 (format "%04d-%02d-%02d %02d:%02d"
11298 (nth 5 final) (nth 4 final) (nth 3 final)
11299 (nth 2 final) (nth 1 final))
11300 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11301 (defvar def)
11302 (defvar defdecode)
11303 (defvar with-time)
11304 (defun org-read-date-display ()
11305 "Display the current date prompt interpretation in the minibuffer."
11306 (when org-read-date-display-live
11307 (when org-read-date-overlay
11308 (org-delete-overlay org-read-date-overlay))
11309 (let ((p (point)))
11310 (end-of-line 1)
11311 (while (not (equal (buffer-substring
11312 (max (point-min) (- (point) 4)) (point))
11313 " "))
11314 (insert " "))
11315 (goto-char p))
11316 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11317 " " (or org-ans1 org-ans2)))
11318 (org-end-time-was-given nil)
11319 (f (org-read-date-analyze ans def defdecode))
11320 (fmts (if org-dcst
11321 org-time-stamp-custom-formats
11322 org-time-stamp-formats))
11323 (fmt (if (or with-time
11324 (and (boundp 'org-time-was-given) org-time-was-given))
11325 (cdr fmts)
11326 (car fmts)))
11327 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11328 (when (and org-end-time-was-given
11329 (string-match org-plain-time-of-day-regexp txt))
11330 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11331 org-end-time-was-given
11332 (substring txt (match-end 0)))))
11333 (setq org-read-date-overlay
11334 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11335 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11337 (defun org-read-date-analyze (ans def defdecode)
11338 "Analyse the combined answer of the date prompt."
11339 ;; FIXME: cleanup and comment
11340 (let (delta deltan deltaw deltadef year month day
11341 hour minute second wday pm h2 m2 tl wday1
11342 iso-year iso-weekday iso-week iso-year iso-date)
11344 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11345 (setq ans "+0"))
11347 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11348 (setq ans (replace-match "" t t ans)
11349 deltan (car delta)
11350 deltaw (nth 1 delta)
11351 deltadef (nth 2 delta)))
11353 ;; Check if there is an iso week date in there
11354 ;; If yes, sore the info and postpone interpreting it until the rest
11355 ;; of the parsing is done
11356 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11357 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11358 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11359 iso-week (string-to-number (match-string 2 ans)))
11360 (setq ans (replace-match "" t t ans)))
11362 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11363 (when (string-match
11364 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11365 (setq year (if (match-end 2)
11366 (string-to-number (match-string 2 ans))
11367 (string-to-number (format-time-string "%Y")))
11368 month (string-to-number (match-string 3 ans))
11369 day (string-to-number (match-string 4 ans)))
11370 (if (< year 100) (setq year (+ 2000 year)))
11371 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11372 t nil ans)))
11373 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11374 ;; If there is a time with am/pm, and *no* time without it, we convert
11375 ;; so that matching will be successful.
11376 (loop for i from 1 to 2 do ; twice, for end time as well
11377 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11378 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11379 (setq hour (string-to-number (match-string 1 ans))
11380 minute (if (match-end 3)
11381 (string-to-number (match-string 3 ans))
11383 pm (equal ?p
11384 (string-to-char (downcase (match-string 4 ans)))))
11385 (if (and (= hour 12) (not pm))
11386 (setq hour 0)
11387 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11388 (setq ans (replace-match (format "%02d:%02d" hour minute)
11389 t t ans))))
11391 ;; Check if a time range is given as a duration
11392 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11393 (setq hour (string-to-number (match-string 1 ans))
11394 h2 (+ hour (string-to-number (match-string 3 ans)))
11395 minute (string-to-number (match-string 2 ans))
11396 m2 (+ minute (if (match-end 5) (string-to-number
11397 (match-string 5 ans))0)))
11398 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11399 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11400 t t ans)))
11402 ;; Check if there is a time range
11403 (when (boundp 'org-end-time-was-given)
11404 (setq org-time-was-given nil)
11405 (when (and (string-match org-plain-time-of-day-regexp ans)
11406 (match-end 8))
11407 (setq org-end-time-was-given (match-string 8 ans))
11408 (setq ans (concat (substring ans 0 (match-beginning 7))
11409 (substring ans (match-end 7))))))
11411 (setq tl (parse-time-string ans)
11412 day (or (nth 3 tl) (nth 3 defdecode))
11413 month (or (nth 4 tl)
11414 (if (and org-read-date-prefer-future
11415 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11416 (1+ (nth 4 defdecode))
11417 (nth 4 defdecode)))
11418 year (or (nth 5 tl)
11419 (if (and org-read-date-prefer-future
11420 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11421 (1+ (nth 5 defdecode))
11422 (nth 5 defdecode)))
11423 hour (or (nth 2 tl) (nth 2 defdecode))
11424 minute (or (nth 1 tl) (nth 1 defdecode))
11425 second (or (nth 0 tl) 0)
11426 wday (nth 6 tl))
11428 ;; Special date definitions below
11429 (cond
11430 (iso-week
11431 ;; There was an iso week
11432 (setq year (or iso-year year)
11433 day (or iso-weekday wday 1)
11434 wday nil ; to make sure that the trigger below does not match
11435 iso-date (calendar-gregorian-from-absolute
11436 (calendar-absolute-from-iso
11437 (list iso-week day year))))
11438 ; FIXME: Should we also push ISO weeks into the future?
11439 ; (when (and org-read-date-prefer-future
11440 ; (not iso-year)
11441 ; (< (calendar-absolute-from-gregorian iso-date)
11442 ; (time-to-days (current-time))))
11443 ; (setq year (1+ year)
11444 ; iso-date (calendar-gregorian-from-absolute
11445 ; (calendar-absolute-from-iso
11446 ; (list iso-week day year)))))
11447 (setq month (car iso-date)
11448 year (nth 2 iso-date)
11449 day (nth 1 iso-date)))
11450 (deltan
11451 (unless deltadef
11452 (let ((now (decode-time (current-time))))
11453 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11454 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11455 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11456 ((equal deltaw "m") (setq month (+ month deltan)))
11457 ((equal deltaw "y") (setq year (+ year deltan)))))
11458 ((and wday (not (nth 3 tl)))
11459 ;; Weekday was given, but no day, so pick that day in the week
11460 ;; on or after the derived date.
11461 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11462 (unless (equal wday wday1)
11463 (setq day (+ day (% (- wday wday1 -7) 7))))))
11464 (if (and (boundp 'org-time-was-given)
11465 (nth 2 tl))
11466 (setq org-time-was-given t))
11467 (if (< year 100) (setq year (+ 2000 year)))
11468 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11469 (list second minute hour day month year)))
11471 (defvar parse-time-weekdays)
11473 (defun org-read-date-get-relative (s today default)
11474 "Check string S for special relative date string.
11475 TODAY and DEFAULT are internal times, for today and for a default.
11476 Return shift list (N what def-flag)
11477 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11478 N is the number of WHATs to shift.
11479 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11480 the DEFAULT date rather than TODAY."
11481 (when (and
11482 (string-match
11483 (concat
11484 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11485 "\\([0-9]+\\)?"
11486 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11487 "\\([ \t]\\|$\\)") s)
11488 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11489 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11490 (string-to-char (substring (match-string 1 s) -1))
11491 ?+))
11492 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11493 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11494 (what (if (match-end 3) (match-string 3 s) "d"))
11495 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11496 (date (if rel default today))
11497 (wday (nth 6 (decode-time date)))
11498 delta)
11499 (if wday1
11500 (progn
11501 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11502 (if (= dir ?-) (setq delta (- delta 7)))
11503 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11504 (list delta "d" rel))
11505 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11507 (defun org-eval-in-calendar (form &optional keepdate)
11508 "Eval FORM in the calendar window and return to current window.
11509 Also, store the cursor date in variable org-ans2."
11510 (let ((sw (selected-window)))
11511 (select-window (get-buffer-window "*Calendar*"))
11512 (eval form)
11513 (when (and (not keepdate) (calendar-cursor-to-date))
11514 (let* ((date (calendar-cursor-to-date))
11515 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11516 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11517 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11518 (select-window sw)))
11520 (defun org-calendar-select ()
11521 "Return to `org-read-date' with the date currently selected.
11522 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11523 (interactive)
11524 (when (calendar-cursor-to-date)
11525 (let* ((date (calendar-cursor-to-date))
11526 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11527 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11528 (if (active-minibuffer-window) (exit-minibuffer))))
11530 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11531 "Insert a date stamp for the date given by the internal TIME.
11532 WITH-HM means, use the stamp format that includes the time of the day.
11533 INACTIVE means use square brackets instead of angular ones, so that the
11534 stamp will not contribute to the agenda.
11535 PRE and POST are optional strings to be inserted before and after the
11536 stamp.
11537 The command returns the inserted time stamp."
11538 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11539 stamp)
11540 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11541 (insert-before-markers (or pre ""))
11542 (insert-before-markers (setq stamp (format-time-string fmt time)))
11543 (when (listp extra)
11544 (setq extra (car extra))
11545 (if (and (stringp extra)
11546 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11547 (setq extra (format "-%02d:%02d"
11548 (string-to-number (match-string 1 extra))
11549 (string-to-number (match-string 2 extra))))
11550 (setq extra nil)))
11551 (when extra
11552 (backward-char 1)
11553 (insert-before-markers extra)
11554 (forward-char 1))
11555 (insert-before-markers (or post ""))
11556 (setq org-last-inserted-timestamp stamp)))
11558 (defun org-toggle-time-stamp-overlays ()
11559 "Toggle the use of custom time stamp formats."
11560 (interactive)
11561 (setq org-display-custom-times (not org-display-custom-times))
11562 (unless org-display-custom-times
11563 (let ((p (point-min)) (bmp (buffer-modified-p)))
11564 (while (setq p (next-single-property-change p 'display))
11565 (if (and (get-text-property p 'display)
11566 (eq (get-text-property p 'face) 'org-date))
11567 (remove-text-properties
11568 p (setq p (next-single-property-change p 'display))
11569 '(display t))))
11570 (set-buffer-modified-p bmp)))
11571 (if (featurep 'xemacs)
11572 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11573 (org-restart-font-lock)
11574 (setq org-table-may-need-update t)
11575 (if org-display-custom-times
11576 (message "Time stamps are overlayed with custom format")
11577 (message "Time stamp overlays removed")))
11579 (defun org-display-custom-time (beg end)
11580 "Overlay modified time stamp format over timestamp between BEG and END."
11581 (let* ((ts (buffer-substring beg end))
11582 t1 w1 with-hm tf time str w2 (off 0))
11583 (save-match-data
11584 (setq t1 (org-parse-time-string ts t))
11585 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11586 (setq off (- (match-end 0) (match-beginning 0)))))
11587 (setq end (- end off))
11588 (setq w1 (- end beg)
11589 with-hm (and (nth 1 t1) (nth 2 t1))
11590 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11591 time (org-fix-decoded-time t1)
11592 str (org-add-props
11593 (format-time-string
11594 (substring tf 1 -1) (apply 'encode-time time))
11595 nil 'mouse-face 'highlight)
11596 w2 (length str))
11597 (if (not (= w2 w1))
11598 (add-text-properties (1+ beg) (+ 2 beg)
11599 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11600 (if (featurep 'xemacs)
11601 (progn
11602 (put-text-property beg end 'invisible t)
11603 (put-text-property beg end 'end-glyph (make-glyph str)))
11604 (put-text-property beg end 'display str))))
11606 (defun org-translate-time (string)
11607 "Translate all timestamps in STRING to custom format.
11608 But do this only if the variable `org-display-custom-times' is set."
11609 (when org-display-custom-times
11610 (save-match-data
11611 (let* ((start 0)
11612 (re org-ts-regexp-both)
11613 t1 with-hm inactive tf time str beg end)
11614 (while (setq start (string-match re string start))
11615 (setq beg (match-beginning 0)
11616 end (match-end 0)
11617 t1 (save-match-data
11618 (org-parse-time-string (substring string beg end) t))
11619 with-hm (and (nth 1 t1) (nth 2 t1))
11620 inactive (equal (substring string beg (1+ beg)) "[")
11621 tf (funcall (if with-hm 'cdr 'car)
11622 org-time-stamp-custom-formats)
11623 time (org-fix-decoded-time t1)
11624 str (format-time-string
11625 (concat
11626 (if inactive "[" "<") (substring tf 1 -1)
11627 (if inactive "]" ">"))
11628 (apply 'encode-time time))
11629 string (replace-match str t t string)
11630 start (+ start (length str)))))))
11631 string)
11633 (defun org-fix-decoded-time (time)
11634 "Set 0 instead of nil for the first 6 elements of time.
11635 Don't touch the rest."
11636 (let ((n 0))
11637 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11639 (defun org-days-to-time (timestamp-string)
11640 "Difference between TIMESTAMP-STRING and now in days."
11641 (- (time-to-days (org-time-string-to-time timestamp-string))
11642 (time-to-days (current-time))))
11644 (defun org-deadline-close (timestamp-string &optional ndays)
11645 "Is the time in TIMESTAMP-STRING close to the current date?"
11646 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11647 (and (< (org-days-to-time timestamp-string) ndays)
11648 (not (org-entry-is-done-p))))
11650 (defun org-get-wdays (ts)
11651 "Get the deadline lead time appropriate for timestring TS."
11652 (cond
11653 ((<= org-deadline-warning-days 0)
11654 ;; 0 or negative, enforce this value no matter what
11655 (- org-deadline-warning-days))
11656 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11657 ;; lead time is specified.
11658 (floor (* (string-to-number (match-string 1 ts))
11659 (cdr (assoc (match-string 2 ts)
11660 '(("d" . 1) ("w" . 7)
11661 ("m" . 30.4) ("y" . 365.25)))))))
11662 ;; go for the default.
11663 (t org-deadline-warning-days)))
11665 (defun org-calendar-select-mouse (ev)
11666 "Return to `org-read-date' with the date currently selected.
11667 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11668 (interactive "e")
11669 (mouse-set-point ev)
11670 (when (calendar-cursor-to-date)
11671 (let* ((date (calendar-cursor-to-date))
11672 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11673 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11674 (if (active-minibuffer-window) (exit-minibuffer))))
11676 (defun org-check-deadlines (ndays)
11677 "Check if there are any deadlines due or past due.
11678 A deadline is considered due if it happens within `org-deadline-warning-days'
11679 days from today's date. If the deadline appears in an entry marked DONE,
11680 it is not shown. The prefix arg NDAYS can be used to test that many
11681 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11682 (interactive "P")
11683 (let* ((org-warn-days
11684 (cond
11685 ((equal ndays '(4)) 100000)
11686 (ndays (prefix-numeric-value ndays))
11687 (t (abs org-deadline-warning-days))))
11688 (case-fold-search nil)
11689 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11690 (callback
11691 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11693 (message "%d deadlines past-due or due within %d days"
11694 (org-occur regexp nil callback)
11695 org-warn-days)))
11697 (defun org-check-before-date (date)
11698 "Check if there are deadlines or scheduled entries before DATE."
11699 (interactive (list (org-read-date)))
11700 (let ((case-fold-search nil)
11701 (regexp (concat "\\<\\(" org-deadline-string
11702 "\\|" org-scheduled-string
11703 "\\) *<\\([^>]+\\)>"))
11704 (callback
11705 (lambda () (time-less-p
11706 (org-time-string-to-time (match-string 2))
11707 (org-time-string-to-time date)))))
11708 (message "%d entries before %s"
11709 (org-occur regexp nil callback) date)))
11711 (defun org-evaluate-time-range (&optional to-buffer)
11712 "Evaluate a time range by computing the difference between start and end.
11713 Normally the result is just printed in the echo area, but with prefix arg
11714 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11715 If the time range is actually in a table, the result is inserted into the
11716 next column.
11717 For time difference computation, a year is assumed to be exactly 365
11718 days in order to avoid rounding problems."
11719 (interactive "P")
11721 (org-clock-update-time-maybe)
11722 (save-excursion
11723 (unless (org-at-date-range-p t)
11724 (goto-char (point-at-bol))
11725 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11726 (if (not (org-at-date-range-p t))
11727 (error "Not at a time-stamp range, and none found in current line")))
11728 (let* ((ts1 (match-string 1))
11729 (ts2 (match-string 2))
11730 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11731 (match-end (match-end 0))
11732 (time1 (org-time-string-to-time ts1))
11733 (time2 (org-time-string-to-time ts2))
11734 (t1 (time-to-seconds time1))
11735 (t2 (time-to-seconds time2))
11736 (diff (abs (- t2 t1)))
11737 (negative (< (- t2 t1) 0))
11738 ;; (ys (floor (* 365 24 60 60)))
11739 (ds (* 24 60 60))
11740 (hs (* 60 60))
11741 (fy "%dy %dd %02d:%02d")
11742 (fy1 "%dy %dd")
11743 (fd "%dd %02d:%02d")
11744 (fd1 "%dd")
11745 (fh "%02d:%02d")
11746 y d h m align)
11747 (if havetime
11748 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11750 d (floor (/ diff ds)) diff (mod diff ds)
11751 h (floor (/ diff hs)) diff (mod diff hs)
11752 m (floor (/ diff 60)))
11753 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11755 d (floor (+ (/ diff ds) 0.5))
11756 h 0 m 0))
11757 (if (not to-buffer)
11758 (message "%s" (org-make-tdiff-string y d h m))
11759 (if (org-at-table-p)
11760 (progn
11761 (goto-char match-end)
11762 (setq align t)
11763 (and (looking-at " *|") (goto-char (match-end 0))))
11764 (goto-char match-end))
11765 (if (looking-at
11766 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11767 (replace-match ""))
11768 (if negative (insert " -"))
11769 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11770 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11771 (insert " " (format fh h m))))
11772 (if align (org-table-align))
11773 (message "Time difference inserted")))))
11775 (defun org-make-tdiff-string (y d h m)
11776 (let ((fmt "")
11777 (l nil))
11778 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11779 l (push y l)))
11780 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11781 l (push d l)))
11782 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11783 l (push h l)))
11784 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11785 l (push m l)))
11786 (apply 'format fmt (nreverse l))))
11788 (defun org-time-string-to-time (s)
11789 (apply 'encode-time (org-parse-time-string s)))
11791 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11792 "Convert a time stamp to an absolute day number.
11793 If there is a specifyer for a cyclic time stamp, get the closest date to
11794 DAYNR.
11795 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11796 (cond
11797 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11798 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11799 daynr
11800 (+ daynr 1000)))
11801 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11802 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11803 (time-to-days (current-time))) (match-string 0 s)
11804 prefer show-all))
11805 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11807 (defun org-days-to-iso-week (days)
11808 "Return the iso week number."
11809 (require 'cal-iso)
11810 (car (calendar-iso-from-absolute days)))
11812 (defun org-small-year-to-year (year)
11813 "Convert 2-digit years into 4-digit years.
11814 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11815 The year 2000 cannot be abbreviated. Any year larger than 99
11816 is returned unchanged."
11817 (if (< year 38)
11818 (setq year (+ 2000 year))
11819 (if (< year 100)
11820 (setq year (+ 1900 year))))
11821 year)
11823 (defun org-time-from-absolute (d)
11824 "Return the time corresponding to date D.
11825 D may be an absolute day number, or a calendar-type list (month day year)."
11826 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11827 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11829 (defun org-calendar-holiday ()
11830 "List of holidays, for Diary display in Org-mode."
11831 (require 'holidays)
11832 (let ((hl (funcall
11833 (if (fboundp 'calendar-check-holidays)
11834 'calendar-check-holidays 'check-calendar-holidays) date)))
11835 (if hl (mapconcat 'identity hl "; "))))
11837 (defun org-diary-sexp-entry (sexp entry date)
11838 "Process a SEXP diary ENTRY for DATE."
11839 (require 'diary-lib)
11840 (let ((result (if calendar-debug-sexp
11841 (let ((stack-trace-on-error t))
11842 (eval (car (read-from-string sexp))))
11843 (condition-case nil
11844 (eval (car (read-from-string sexp)))
11845 (error
11846 (beep)
11847 (message "Bad sexp at line %d in %s: %s"
11848 (org-current-line)
11849 (buffer-file-name) sexp)
11850 (sleep-for 2))))))
11851 (cond ((stringp result) result)
11852 ((and (consp result)
11853 (stringp (cdr result))) (cdr result))
11854 (result entry)
11855 (t nil))))
11857 (defun org-diary-to-ical-string (frombuf)
11858 "Get iCalendar entries from diary entries in buffer FROMBUF.
11859 This uses the icalendar.el library."
11860 (let* ((tmpdir (if (featurep 'xemacs)
11861 (temp-directory)
11862 temporary-file-directory))
11863 (tmpfile (make-temp-name
11864 (expand-file-name "orgics" tmpdir)))
11865 buf rtn b e)
11866 (save-excursion
11867 (set-buffer frombuf)
11868 (icalendar-export-region (point-min) (point-max) tmpfile)
11869 (setq buf (find-buffer-visiting tmpfile))
11870 (set-buffer buf)
11871 (goto-char (point-min))
11872 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11873 (setq b (match-beginning 0)))
11874 (goto-char (point-max))
11875 (if (re-search-backward "^END:VEVENT" nil t)
11876 (setq e (match-end 0)))
11877 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11878 (kill-buffer buf)
11879 (delete-file tmpfile)
11880 rtn))
11882 (defun org-closest-date (start current change prefer show-all)
11883 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11884 When PREFER is `past' return a date that is either CURRENT or past.
11885 When PREFER is `future', return a date that is either CURRENT or future.
11886 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11887 ;; Make the proper lists from the dates
11888 (catch 'exit
11889 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11890 dn dw sday cday n1 n2 n0
11891 d m y y1 y2 date1 date2 nmonths nm ny m2)
11893 (setq start (org-date-to-gregorian start)
11894 current (org-date-to-gregorian
11895 (if show-all
11896 current
11897 (time-to-days (current-time))))
11898 sday (calendar-absolute-from-gregorian start)
11899 cday (calendar-absolute-from-gregorian current))
11901 (if (<= cday sday) (throw 'exit sday))
11903 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11904 (setq dn (string-to-number (match-string 1 change))
11905 dw (cdr (assoc (match-string 2 change) a1)))
11906 (error "Invalid change specifyer: %s" change))
11907 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11908 (cond
11909 ((eq dw 'day)
11910 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11911 n2 (+ n1 dn)))
11912 ((eq dw 'year)
11913 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11914 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11915 (setq date1 (list m d y1)
11916 n1 (calendar-absolute-from-gregorian date1)
11917 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11918 n2 (calendar-absolute-from-gregorian date2)))
11919 ((eq dw 'month)
11920 ;; approx number of month between the two dates
11921 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11922 ;; How often does dn fit in there?
11923 (setq d (nth 1 start) m (car start) y (nth 2 start)
11924 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11925 m (+ m nm)
11926 ny (floor (/ m 12))
11927 y (+ y ny)
11928 m (- m (* ny 12)))
11929 (while (> m 12) (setq m (- m 12) y (1+ y)))
11930 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11931 (setq m2 (+ m dn) y2 y)
11932 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11933 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11934 (while (<= n2 cday)
11935 (setq n1 n2 m m2 y y2)
11936 (setq m2 (+ m dn) y2 y)
11937 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11938 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11939 ;; Make sure n1 is the earlier date
11940 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11941 (if show-all
11942 (cond
11943 ((eq prefer 'past) n1)
11944 ((eq prefer 'future) (if (= cday n1) n1 n2))
11945 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11946 (cond
11947 ((eq prefer 'past) n1)
11948 ((eq prefer 'future) (if (= cday n1) n1 n2))
11949 (t (if (= cday n1) n1 n2)))))))
11951 (defun org-date-to-gregorian (date)
11952 "Turn any specification of DATE into a gregorian date for the calendar."
11953 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11954 ((and (listp date) (= (length date) 3)) date)
11955 ((stringp date)
11956 (setq date (org-parse-time-string date))
11957 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11958 ((listp date)
11959 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11961 (defun org-parse-time-string (s &optional nodefault)
11962 "Parse the standard Org-mode time string.
11963 This should be a lot faster than the normal `parse-time-string'.
11964 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11965 hour and minute fields will be nil if not given."
11966 (if (string-match org-ts-regexp0 s)
11967 (list 0
11968 (if (or (match-beginning 8) (not nodefault))
11969 (string-to-number (or (match-string 8 s) "0")))
11970 (if (or (match-beginning 7) (not nodefault))
11971 (string-to-number (or (match-string 7 s) "0")))
11972 (string-to-number (match-string 4 s))
11973 (string-to-number (match-string 3 s))
11974 (string-to-number (match-string 2 s))
11975 nil nil nil)
11976 (make-list 9 0)))
11978 (defun org-timestamp-up (&optional arg)
11979 "Increase the date item at the cursor by one.
11980 If the cursor is on the year, change the year. If it is on the month or
11981 the day, change that.
11982 With prefix ARG, change by that many units."
11983 (interactive "p")
11984 (org-timestamp-change (prefix-numeric-value arg)))
11986 (defun org-timestamp-down (&optional arg)
11987 "Decrease the date item at the cursor by one.
11988 If the cursor is on the year, change the year. If it is on the month or
11989 the day, change that.
11990 With prefix ARG, change by that many units."
11991 (interactive "p")
11992 (org-timestamp-change (- (prefix-numeric-value arg))))
11994 (defun org-timestamp-up-day (&optional arg)
11995 "Increase the date in the time stamp by one day.
11996 With prefix ARG, change that many days."
11997 (interactive "p")
11998 (if (and (not (org-at-timestamp-p t))
11999 (org-on-heading-p))
12000 (org-todo 'up)
12001 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12003 (defun org-timestamp-down-day (&optional arg)
12004 "Decrease the date in the time stamp by one day.
12005 With prefix ARG, change that many days."
12006 (interactive "p")
12007 (if (and (not (org-at-timestamp-p t))
12008 (org-on-heading-p))
12009 (org-todo 'down)
12010 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12012 (defun org-at-timestamp-p (&optional inactive-ok)
12013 "Determine if the cursor is in or at a timestamp."
12014 (interactive)
12015 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12016 (pos (point))
12017 (ans (or (looking-at tsr)
12018 (save-excursion
12019 (skip-chars-backward "^[<\n\r\t")
12020 (if (> (point) (point-min)) (backward-char 1))
12021 (and (looking-at tsr)
12022 (> (- (match-end 0) pos) -1))))))
12023 (and ans
12024 (boundp 'org-ts-what)
12025 (setq org-ts-what
12026 (cond
12027 ((= pos (match-beginning 0)) 'bracket)
12028 ((= pos (1- (match-end 0))) 'bracket)
12029 ((org-pos-in-match-range pos 2) 'year)
12030 ((org-pos-in-match-range pos 3) 'month)
12031 ((org-pos-in-match-range pos 7) 'hour)
12032 ((org-pos-in-match-range pos 8) 'minute)
12033 ((or (org-pos-in-match-range pos 4)
12034 (org-pos-in-match-range pos 5)) 'day)
12035 ((and (> pos (or (match-end 8) (match-end 5)))
12036 (< pos (match-end 0)))
12037 (- pos (or (match-end 8) (match-end 5))))
12038 (t 'day))))
12039 ans))
12041 (defun org-toggle-timestamp-type ()
12042 "Toggle the type (<active> or [inactive]) of a time stamp."
12043 (interactive)
12044 (when (org-at-timestamp-p t)
12045 (let ((beg (match-beginning 0)) (end (match-end 0))
12046 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12047 (save-excursion
12048 (goto-char beg)
12049 (while (re-search-forward "[][<>]" end t)
12050 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12051 t t)))
12052 (message "Timestamp is now %sactive"
12053 (if (equal (char-after beg) ?<) "" "in")))))
12055 (defun org-timestamp-change (n &optional what)
12056 "Change the date in the time stamp at point.
12057 The date will be changed by N times WHAT. WHAT can be `day', `month',
12058 `year', `minute', `second'. If WHAT is not given, the cursor position
12059 in the timestamp determines what will be changed."
12060 (let ((pos (point))
12061 with-hm inactive
12062 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12063 org-ts-what
12064 extra rem
12065 ts time time0)
12066 (if (not (org-at-timestamp-p t))
12067 (error "Not at a timestamp"))
12068 (if (and (not what) (eq org-ts-what 'bracket))
12069 (org-toggle-timestamp-type)
12070 (if (and (not what) (not (eq org-ts-what 'day))
12071 org-display-custom-times
12072 (get-text-property (point) 'display)
12073 (not (get-text-property (1- (point)) 'display)))
12074 (setq org-ts-what 'day))
12075 (setq org-ts-what (or what org-ts-what)
12076 inactive (= (char-after (match-beginning 0)) ?\[)
12077 ts (match-string 0))
12078 (replace-match "")
12079 (if (string-match
12080 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12082 (setq extra (match-string 1 ts)))
12083 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12084 (setq with-hm t))
12085 (setq time0 (org-parse-time-string ts))
12086 (when (and (eq org-ts-what 'minute)
12087 (eq current-prefix-arg nil))
12088 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12089 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12090 (setcar (cdr time0) (+ (nth 1 time0)
12091 (if (> n 0) (- rem) (- dm rem))))))
12092 (setq time
12093 (encode-time (or (car time0) 0)
12094 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12095 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12096 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12097 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12098 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12099 (nthcdr 6 time0)))
12100 (when (integerp org-ts-what)
12101 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12102 (if (eq what 'calendar)
12103 (let ((cal-date (org-get-date-from-calendar)))
12104 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12105 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12106 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12107 (setcar time0 (or (car time0) 0))
12108 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12109 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12110 (setq time (apply 'encode-time time0))))
12111 (setq org-last-changed-timestamp
12112 (org-insert-time-stamp time with-hm inactive nil nil extra))
12113 (org-clock-update-time-maybe)
12114 (goto-char pos)
12115 ;; Try to recenter the calendar window, if any
12116 (if (and org-calendar-follow-timestamp-change
12117 (get-buffer-window "*Calendar*" t)
12118 (memq org-ts-what '(day month year)))
12119 (org-recenter-calendar (time-to-days time))))))
12121 (defun org-modify-ts-extra (s pos n dm)
12122 "Change the different parts of the lead-time and repeat fields in timestamp."
12123 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12124 ng h m new rem)
12125 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12126 (cond
12127 ((or (org-pos-in-match-range pos 2)
12128 (org-pos-in-match-range pos 3))
12129 (setq m (string-to-number (match-string 3 s))
12130 h (string-to-number (match-string 2 s)))
12131 (if (org-pos-in-match-range pos 2)
12132 (setq h (+ h n))
12133 (setq n (* dm (org-no-warnings (signum n))))
12134 (when (not (= 0 (setq rem (% m dm))))
12135 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12136 (setq m (+ m n)))
12137 (if (< m 0) (setq m (+ m 60) h (1- h)))
12138 (if (> m 59) (setq m (- m 60) h (1+ h)))
12139 (setq h (min 24 (max 0 h)))
12140 (setq ng 1 new (format "-%02d:%02d" h m)))
12141 ((org-pos-in-match-range pos 6)
12142 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12143 ((org-pos-in-match-range pos 5)
12144 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12146 ((org-pos-in-match-range pos 9)
12147 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12148 ((org-pos-in-match-range pos 8)
12149 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12151 (when ng
12152 (setq s (concat
12153 (substring s 0 (match-beginning ng))
12155 (substring s (match-end ng))))))
12158 (defun org-recenter-calendar (date)
12159 "If the calendar is visible, recenter it to DATE."
12160 (let* ((win (selected-window))
12161 (cwin (get-buffer-window "*Calendar*" t))
12162 (calendar-move-hook nil))
12163 (when cwin
12164 (select-window cwin)
12165 (calendar-goto-date (if (listp date) date
12166 (calendar-gregorian-from-absolute date)))
12167 (select-window win))))
12169 (defun org-goto-calendar (&optional arg)
12170 "Go to the Emacs calendar at the current date.
12171 If there is a time stamp in the current line, go to that date.
12172 A prefix ARG can be used to force the current date."
12173 (interactive "P")
12174 (let ((tsr org-ts-regexp) diff
12175 (calendar-move-hook nil)
12176 (calendar-view-holidays-initially-flag nil)
12177 (view-calendar-holidays-initially nil)
12178 (calendar-view-diary-initially-flag nil)
12179 (view-diary-entries-initially nil))
12180 (if (or (org-at-timestamp-p)
12181 (save-excursion
12182 (beginning-of-line 1)
12183 (looking-at (concat ".*" tsr))))
12184 (let ((d1 (time-to-days (current-time)))
12185 (d2 (time-to-days
12186 (org-time-string-to-time (match-string 1)))))
12187 (setq diff (- d2 d1))))
12188 (calendar)
12189 (calendar-goto-today)
12190 (if (and diff (not arg)) (calendar-forward-day diff))))
12192 (defun org-get-date-from-calendar ()
12193 "Return a list (month day year) of date at point in calendar."
12194 (with-current-buffer "*Calendar*"
12195 (save-match-data
12196 (calendar-cursor-to-date))))
12198 (defun org-date-from-calendar ()
12199 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12200 If there is already a time stamp at the cursor position, update it."
12201 (interactive)
12202 (if (org-at-timestamp-p t)
12203 (org-timestamp-change 0 'calendar)
12204 (let ((cal-date (org-get-date-from-calendar)))
12205 (org-insert-time-stamp
12206 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12208 (defun org-minutes-to-hh:mm-string (m)
12209 "Compute H:MM from a number of minutes."
12210 (let ((h (/ m 60)))
12211 (setq m (- m (* 60 h)))
12212 (format org-time-clocksum-format h m)))
12214 (defun org-hh:mm-string-to-minutes (s)
12215 "Convert a string H:MM to a number of minutes."
12216 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12217 (+ (* (string-to-number (match-string 1 s)) 60)
12218 (string-to-number (match-string 2 s)))
12221 ;;;; Agenda files
12223 ;;;###autoload
12224 (defun org-iswitchb (&optional arg)
12225 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12226 With a prefix argument, restrict available to files.
12227 With two prefix arguments, restrict available buffers to agenda files.
12229 Due to some yet unresolved reason, the global function
12230 `iswitchb-mode' needs to be active for this function to work."
12231 (interactive "P")
12232 (require 'iswitchb)
12233 (let ((enabled iswitchb-mode) blist)
12234 (or enabled (iswitchb-mode 1))
12235 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12236 ((equal arg '(16)) (org-buffer-list 'agenda))
12237 (t (org-buffer-list))))
12238 (unwind-protect
12239 (let ((iswitchb-make-buflist-hook
12240 (lambda ()
12241 (setq iswitchb-temp-buflist
12242 (mapcar 'buffer-name blist)))))
12243 (switch-to-buffer
12244 (iswitchb-read-buffer
12245 "Switch-to: " nil t))
12246 (or enabled (iswitchb-mode -1))))))
12248 ;;;###autoload
12249 (defun org-ido-switchb (&optional arg)
12250 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12251 With a prefix argument, restrict available to files.
12252 With two prefix arguments, restrict available buffers to agenda files."
12253 (interactive "P")
12254 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12255 ((equal arg '(16)) (org-buffer-list 'agenda))
12256 (t (org-buffer-list)))))
12257 (switch-to-buffer
12258 (org-ido-completing-read "Org buffer: "
12259 (mapcar 'buffer-name blist)
12260 nil t))))
12262 (defun org-buffer-list (&optional predicate exclude-tmp)
12263 "Return a list of Org buffers.
12264 PREDICATE can be `export', `files' or `agenda'.
12266 export restrict the list to Export buffers.
12267 files restrict the list to buffers visiting Org files.
12268 agenda restrict the list to buffers visiting agenda files.
12270 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12271 (let* ((bfn nil)
12272 (agenda-files (and (eq predicate 'agenda)
12273 (mapcar 'file-truename (org-agenda-files t))))
12274 (filter
12275 (cond
12276 ((eq predicate 'files)
12277 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12278 ((eq predicate 'export)
12279 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12280 ((eq predicate 'agenda)
12281 (lambda (b)
12282 (with-current-buffer b
12283 (and (eq major-mode 'org-mode)
12284 (setq bfn (buffer-file-name b))
12285 (member (file-truename bfn) agenda-files)))))
12286 (t (lambda (b) (with-current-buffer b
12287 (or (eq major-mode 'org-mode)
12288 (string-match "\*Org .*Export"
12289 (buffer-name b)))))))))
12290 (delq nil
12291 (mapcar
12292 (lambda(b)
12293 (if (and (funcall filter b)
12294 (or (not exclude-tmp)
12295 (not (string-match "tmp" (buffer-name b)))))
12297 nil))
12298 (buffer-list)))))
12300 (defun org-agenda-files (&optional unrestricted archives)
12301 "Get the list of agenda files.
12302 Optional UNRESTRICTED means return the full list even if a restriction
12303 is currently in place.
12304 When ARCHIVES is t, include all archive files hat are really being
12305 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12306 `org-agenda-archives-mode' is t."
12307 (let ((files
12308 (cond
12309 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12310 ((stringp org-agenda-files) (org-read-agenda-file-list))
12311 ((listp org-agenda-files) org-agenda-files)
12312 (t (error "Invalid value of `org-agenda-files'")))))
12313 (setq files (apply 'append
12314 (mapcar (lambda (f)
12315 (if (file-directory-p f)
12316 (directory-files
12317 f t org-agenda-file-regexp)
12318 (list f)))
12319 files)))
12320 (when org-agenda-skip-unavailable-files
12321 (setq files (delq nil
12322 (mapcar (function
12323 (lambda (file)
12324 (and (file-readable-p file) file)))
12325 files))))
12326 (when (or (eq archives t)
12327 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12328 (setq files (org-add-archive-files files)))
12329 files))
12331 (defun org-edit-agenda-file-list ()
12332 "Edit the list of agenda files.
12333 Depending on setup, this either uses customize to edit the variable
12334 `org-agenda-files', or it visits the file that is holding the list. In the
12335 latter case, the buffer is set up in a way that saving it automatically kills
12336 the buffer and restores the previous window configuration."
12337 (interactive)
12338 (if (stringp org-agenda-files)
12339 (let ((cw (current-window-configuration)))
12340 (find-file org-agenda-files)
12341 (org-set-local 'org-window-configuration cw)
12342 (org-add-hook 'after-save-hook
12343 (lambda ()
12344 (set-window-configuration
12345 (prog1 org-window-configuration
12346 (kill-buffer (current-buffer))))
12347 (org-install-agenda-files-menu)
12348 (message "New agenda file list installed"))
12349 nil 'local)
12350 (message "%s" (substitute-command-keys
12351 "Edit list and finish with \\[save-buffer]")))
12352 (customize-variable 'org-agenda-files)))
12354 (defun org-store-new-agenda-file-list (list)
12355 "Set new value for the agenda file list and save it correctly."
12356 (if (stringp org-agenda-files)
12357 (let ((f org-agenda-files) b)
12358 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12359 (with-temp-file f
12360 (insert (mapconcat 'identity list "\n") "\n")))
12361 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12362 (setq org-agenda-files list)
12363 (customize-save-variable 'org-agenda-files org-agenda-files))))
12365 (defun org-read-agenda-file-list ()
12366 "Read the list of agenda files from a file."
12367 (when (file-directory-p org-agenda-files)
12368 (error "`org-agenda-files' cannot be a single directory"))
12369 (when (stringp org-agenda-files)
12370 (with-temp-buffer
12371 (insert-file-contents org-agenda-files)
12372 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12375 ;;;###autoload
12376 (defun org-cycle-agenda-files ()
12377 "Cycle through the files in `org-agenda-files'.
12378 If the current buffer visits an agenda file, find the next one in the list.
12379 If the current buffer does not, find the first agenda file."
12380 (interactive)
12381 (let* ((fs (org-agenda-files t))
12382 (files (append fs (list (car fs))))
12383 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12384 file)
12385 (unless files (error "No agenda files"))
12386 (catch 'exit
12387 (while (setq file (pop files))
12388 (if (equal (file-truename file) tcf)
12389 (when (car files)
12390 (find-file (car files))
12391 (throw 'exit t))))
12392 (find-file (car fs)))
12393 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12395 (defun org-agenda-file-to-front (&optional to-end)
12396 "Move/add the current file to the top of the agenda file list.
12397 If the file is not present in the list, it is added to the front. If it is
12398 present, it is moved there. With optional argument TO-END, add/move to the
12399 end of the list."
12400 (interactive "P")
12401 (let ((org-agenda-skip-unavailable-files nil)
12402 (file-alist (mapcar (lambda (x)
12403 (cons (file-truename x) x))
12404 (org-agenda-files t)))
12405 (ctf (file-truename buffer-file-name))
12406 x had)
12407 (setq x (assoc ctf file-alist) had x)
12409 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12410 (if to-end
12411 (setq file-alist (append (delq x file-alist) (list x)))
12412 (setq file-alist (cons x (delq x file-alist))))
12413 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12414 (org-install-agenda-files-menu)
12415 (message "File %s to %s of agenda file list"
12416 (if had "moved" "added") (if to-end "end" "front"))))
12418 (defun org-remove-file (&optional file)
12419 "Remove current file from the list of files in variable `org-agenda-files'.
12420 These are the files which are being checked for agenda entries.
12421 Optional argument FILE means, use this file instead of the current."
12422 (interactive)
12423 (let* ((org-agenda-skip-unavailable-files nil)
12424 (file (or file buffer-file-name))
12425 (true-file (file-truename file))
12426 (afile (abbreviate-file-name file))
12427 (files (delq nil (mapcar
12428 (lambda (x)
12429 (if (equal true-file
12430 (file-truename x))
12431 nil x))
12432 (org-agenda-files t)))))
12433 (if (not (= (length files) (length (org-agenda-files t))))
12434 (progn
12435 (org-store-new-agenda-file-list files)
12436 (org-install-agenda-files-menu)
12437 (message "Removed file: %s" afile))
12438 (message "File was not in list: %s (not removed)" afile))))
12440 (defun org-file-menu-entry (file)
12441 (vector file (list 'find-file file) t))
12443 (defun org-check-agenda-file (file)
12444 "Make sure FILE exists. If not, ask user what to do."
12445 (when (not (file-exists-p file))
12446 (message "non-existent file %s. [R]emove from list or [A]bort?"
12447 (abbreviate-file-name file))
12448 (let ((r (downcase (read-char-exclusive))))
12449 (cond
12450 ((equal r ?r)
12451 (org-remove-file file)
12452 (throw 'nextfile t))
12453 (t (error "Abort"))))))
12455 (defun org-get-agenda-file-buffer (file)
12456 "Get a buffer visiting FILE. If the buffer needs to be created, add
12457 it to the list of buffers which might be released later."
12458 (let ((buf (org-find-base-buffer-visiting file)))
12459 (if buf
12460 buf ; just return it
12461 ;; Make a new buffer and remember it
12462 (setq buf (find-file-noselect file))
12463 (if buf (push buf org-agenda-new-buffers))
12464 buf)))
12466 (defun org-release-buffers (blist)
12467 "Release all buffers in list, asking the user for confirmation when needed.
12468 When a buffer is unmodified, it is just killed. When modified, it is saved
12469 \(if the user agrees) and then killed."
12470 (let (buf file)
12471 (while (setq buf (pop blist))
12472 (setq file (buffer-file-name buf))
12473 (when (and (buffer-modified-p buf)
12474 file
12475 (y-or-n-p (format "Save file %s? " file)))
12476 (with-current-buffer buf (save-buffer)))
12477 (kill-buffer buf))))
12479 (defun org-prepare-agenda-buffers (files)
12480 "Create buffers for all agenda files, protect archived trees and comments."
12481 (interactive)
12482 (let ((pa '(:org-archived t))
12483 (pc '(:org-comment t))
12484 (pall '(:org-archived t :org-comment t))
12485 (inhibit-read-only t)
12486 (rea (concat ":" org-archive-tag ":"))
12487 bmp file re)
12488 (save-excursion
12489 (save-restriction
12490 (while (setq file (pop files))
12491 (if (bufferp file)
12492 (set-buffer file)
12493 (org-check-agenda-file file)
12494 (set-buffer (org-get-agenda-file-buffer file)))
12495 (widen)
12496 (setq bmp (buffer-modified-p))
12497 (org-refresh-category-properties)
12498 (setq org-todo-keywords-for-agenda
12499 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12500 (setq org-done-keywords-for-agenda
12501 (append org-done-keywords-for-agenda org-done-keywords))
12502 (setq org-todo-keyword-alist-for-agenda
12503 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12504 (setq org-tag-alist-for-agenda
12505 (append org-tag-alist-for-agenda org-tag-alist))
12507 (save-excursion
12508 (remove-text-properties (point-min) (point-max) pall)
12509 (when org-agenda-skip-archived-trees
12510 (goto-char (point-min))
12511 (while (re-search-forward rea nil t)
12512 (if (org-on-heading-p t)
12513 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12514 (goto-char (point-min))
12515 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12516 (while (re-search-forward re nil t)
12517 (add-text-properties
12518 (match-beginning 0) (org-end-of-subtree t) pc)))
12519 (set-buffer-modified-p bmp))))
12520 (setq org-todo-keyword-alist-for-agenda
12521 (org-uniquify org-todo-keyword-alist-for-agenda)
12522 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12524 ;;;; Embedded LaTeX
12526 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12527 "Keymap for the minor `org-cdlatex-mode'.")
12529 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12530 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12531 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12532 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12533 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12535 (defvar org-cdlatex-texmathp-advice-is-done nil
12536 "Flag remembering if we have applied the advice to texmathp already.")
12538 (define-minor-mode org-cdlatex-mode
12539 "Toggle the minor `org-cdlatex-mode'.
12540 This mode supports entering LaTeX environment and math in LaTeX fragments
12541 in Org-mode.
12542 \\{org-cdlatex-mode-map}"
12543 nil " OCDL" nil
12544 (when org-cdlatex-mode (require 'cdlatex))
12545 (unless org-cdlatex-texmathp-advice-is-done
12546 (setq org-cdlatex-texmathp-advice-is-done t)
12547 (defadvice texmathp (around org-math-always-on activate)
12548 "Always return t in org-mode buffers.
12549 This is because we want to insert math symbols without dollars even outside
12550 the LaTeX math segments. If Orgmode thinks that point is actually inside
12551 an embedded LaTeX fragment, let texmathp do its job.
12552 \\[org-cdlatex-mode-map]"
12553 (interactive)
12554 (let (p)
12555 (cond
12556 ((not (org-mode-p)) ad-do-it)
12557 ((eq this-command 'cdlatex-math-symbol)
12558 (setq ad-return-value t
12559 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12561 (let ((p (org-inside-LaTeX-fragment-p)))
12562 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12563 (setq ad-return-value t
12564 texmathp-why '("Org-mode embedded math" . 0))
12565 (if p ad-do-it)))))))))
12567 (defun turn-on-org-cdlatex ()
12568 "Unconditionally turn on `org-cdlatex-mode'."
12569 (org-cdlatex-mode 1))
12571 (defun org-inside-LaTeX-fragment-p ()
12572 "Test if point is inside a LaTeX fragment.
12573 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12574 sequence appearing also before point.
12575 Even though the matchers for math are configurable, this function assumes
12576 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12577 delimiters are skipped when they have been removed by customization.
12578 The return value is nil, or a cons cell with the delimiter and
12579 and the position of this delimiter.
12581 This function does a reasonably good job, but can locally be fooled by
12582 for example currency specifications. For example it will assume being in
12583 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12584 fragments that are properly closed, but during editing, we have to live
12585 with the uncertainty caused by missing closing delimiters. This function
12586 looks only before point, not after."
12587 (catch 'exit
12588 (let ((pos (point))
12589 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12590 (lim (progn
12591 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12592 (point)))
12593 dd-on str (start 0) m re)
12594 (goto-char pos)
12595 (when dodollar
12596 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12597 re (nth 1 (assoc "$" org-latex-regexps)))
12598 (while (string-match re str start)
12599 (cond
12600 ((= (match-end 0) (length str))
12601 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12602 ((= (match-end 0) (- (length str) 5))
12603 (throw 'exit nil))
12604 (t (setq start (match-end 0))))))
12605 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12606 (goto-char pos)
12607 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12608 (and (match-beginning 2) (throw 'exit nil))
12609 ;; count $$
12610 (while (re-search-backward "\\$\\$" lim t)
12611 (setq dd-on (not dd-on)))
12612 (goto-char pos)
12613 (if dd-on (cons "$$" m))))))
12616 (defun org-try-cdlatex-tab ()
12617 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12618 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12619 - inside a LaTeX fragment, or
12620 - after the first word in a line, where an abbreviation expansion could
12621 insert a LaTeX environment."
12622 (when org-cdlatex-mode
12623 (cond
12624 ((save-excursion
12625 (skip-chars-backward "a-zA-Z0-9*")
12626 (skip-chars-backward " \t")
12627 (bolp))
12628 (cdlatex-tab) t)
12629 ((org-inside-LaTeX-fragment-p)
12630 (cdlatex-tab) t)
12631 (t nil))))
12633 (defun org-cdlatex-underscore-caret (&optional arg)
12634 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12635 Revert to the normal definition outside of these fragments."
12636 (interactive "P")
12637 (if (org-inside-LaTeX-fragment-p)
12638 (call-interactively 'cdlatex-sub-superscript)
12639 (let (org-cdlatex-mode)
12640 (call-interactively (key-binding (vector last-input-event))))))
12642 (defun org-cdlatex-math-modify (&optional arg)
12643 "Execute `cdlatex-math-modify' in LaTeX fragments.
12644 Revert to the normal definition outside of these fragments."
12645 (interactive "P")
12646 (if (org-inside-LaTeX-fragment-p)
12647 (call-interactively 'cdlatex-math-modify)
12648 (let (org-cdlatex-mode)
12649 (call-interactively (key-binding (vector last-input-event))))))
12651 (defvar org-latex-fragment-image-overlays nil
12652 "List of overlays carrying the images of latex fragments.")
12653 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12655 (defun org-remove-latex-fragment-image-overlays ()
12656 "Remove all overlays with LaTeX fragment images in current buffer."
12657 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12658 (setq org-latex-fragment-image-overlays nil))
12660 (defun org-preview-latex-fragment (&optional subtree)
12661 "Preview the LaTeX fragment at point, or all locally or globally.
12662 If the cursor is in a LaTeX fragment, create the image and overlay
12663 it over the source code. If there is no fragment at point, display
12664 all fragments in the current text, from one headline to the next. With
12665 prefix SUBTREE, display all fragments in the current subtree. With a
12666 double prefix `C-u C-u', or when the cursor is before the first headline,
12667 display all fragments in the buffer.
12668 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12669 (interactive "P")
12670 (org-remove-latex-fragment-image-overlays)
12671 (save-excursion
12672 (save-restriction
12673 (let (beg end at msg)
12674 (cond
12675 ((or (equal subtree '(16))
12676 (not (save-excursion
12677 (re-search-backward (concat "^" outline-regexp) nil t))))
12678 (setq beg (point-min) end (point-max)
12679 msg "Creating images for buffer...%s"))
12680 ((equal subtree '(4))
12681 (org-back-to-heading)
12682 (setq beg (point) end (org-end-of-subtree t)
12683 msg "Creating images for subtree...%s"))
12685 (if (setq at (org-inside-LaTeX-fragment-p))
12686 (goto-char (max (point-min) (- (cdr at) 2)))
12687 (org-back-to-heading))
12688 (setq beg (point) end (progn (outline-next-heading) (point))
12689 msg (if at "Creating image...%s"
12690 "Creating images for entry...%s"))))
12691 (message msg "")
12692 (narrow-to-region beg end)
12693 (goto-char beg)
12694 (org-format-latex
12695 (concat "ltxpng/" (file-name-sans-extension
12696 (file-name-nondirectory
12697 buffer-file-name)))
12698 default-directory 'overlays msg at 'forbuffer)
12699 (message msg "done. Use `C-c C-c' to remove images.")))))
12701 (defvar org-latex-regexps
12702 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12703 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12704 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12705 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12706 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12707 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12708 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12709 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12710 "Regular expressions for matching embedded LaTeX.")
12712 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12713 "Replace LaTeX fragments with links to an image, and produce images."
12714 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12715 (let* ((prefixnodir (file-name-nondirectory prefix))
12716 (absprefix (expand-file-name prefix dir))
12717 (todir (file-name-directory absprefix))
12718 (opt org-format-latex-options)
12719 (matchers (plist-get opt :matchers))
12720 (re-list org-latex-regexps)
12721 (cnt 0) txt link beg end re e checkdir
12722 m n block linkfile movefile ov)
12723 ;; Check if there are old images files with this prefix, and remove them
12724 (when (file-directory-p todir)
12725 (mapc 'delete-file
12726 (directory-files
12727 todir 'full
12728 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12729 ;; Check the different regular expressions
12730 (while (setq e (pop re-list))
12731 (setq m (car e) re (nth 1 e) n (nth 2 e)
12732 block (if (nth 3 e) "\n\n" ""))
12733 (when (member m matchers)
12734 (goto-char (point-min))
12735 (while (re-search-forward re nil t)
12736 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
12737 (not (get-text-property (match-beginning n)
12738 'org-protected)))
12739 (setq txt (match-string n)
12740 beg (match-beginning n) end (match-end n)
12741 cnt (1+ cnt)
12742 linkfile (format "%s_%04d.png" prefix cnt)
12743 movefile (format "%s_%04d.png" absprefix cnt)
12744 link (concat block "[[file:" linkfile "]]" block))
12745 (if msg (message msg cnt))
12746 (goto-char beg)
12747 (unless checkdir ; make sure the directory exists
12748 (setq checkdir t)
12749 (or (file-directory-p todir) (make-directory todir)))
12750 (org-create-formula-image
12751 txt movefile opt forbuffer)
12752 (if overlays
12753 (progn
12754 (setq ov (org-make-overlay beg end))
12755 (if (featurep 'xemacs)
12756 (progn
12757 (org-overlay-put ov 'invisible t)
12758 (org-overlay-put
12759 ov 'end-glyph
12760 (make-glyph (vector 'png :file movefile))))
12761 (org-overlay-put
12762 ov 'display
12763 (list 'image :type 'png :file movefile :ascent 'center)))
12764 (push ov org-latex-fragment-image-overlays)
12765 (goto-char end))
12766 (delete-region beg end)
12767 (insert link))))))))
12769 ;; This function borrows from Ganesh Swami's latex2png.el
12770 (defun org-create-formula-image (string tofile options buffer)
12771 (let* ((tmpdir (if (featurep 'xemacs)
12772 (temp-directory)
12773 temporary-file-directory))
12774 (texfilebase (make-temp-name
12775 (expand-file-name "orgtex" tmpdir)))
12776 (texfile (concat texfilebase ".tex"))
12777 (dvifile (concat texfilebase ".dvi"))
12778 (pngfile (concat texfilebase ".png"))
12779 (fnh (if (featurep 'xemacs)
12780 (font-height (get-face-font 'default))
12781 (face-attribute 'default :height nil)))
12782 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12783 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12784 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12785 "Black"))
12786 (bg (or (plist-get options (if buffer :background :html-background))
12787 "Transparent")))
12788 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12789 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12790 (with-temp-file texfile
12791 (insert org-format-latex-header
12792 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12793 (let ((dir default-directory))
12794 (condition-case nil
12795 (progn
12796 (cd tmpdir)
12797 (call-process "latex" nil nil nil texfile))
12798 (error nil))
12799 (cd dir))
12800 (if (not (file-exists-p dvifile))
12801 (progn (message "Failed to create dvi file from %s" texfile) nil)
12802 (condition-case nil
12803 (call-process "dvipng" nil nil nil
12804 "-E" "-fg" fg "-bg" bg
12805 "-D" dpi
12806 ;;"-x" scale "-y" scale
12807 "-T" "tight"
12808 "-o" pngfile
12809 dvifile)
12810 (error nil))
12811 (if (not (file-exists-p pngfile))
12812 (progn (message "Failed to create png file from %s" texfile) nil)
12813 ;; Use the requested file name and clean up
12814 (copy-file pngfile tofile 'replace)
12815 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12816 (delete-file (concat texfilebase e)))
12817 pngfile))))
12819 (defun org-dvipng-color (attr)
12820 "Return an rgb color specification for dvipng."
12821 (apply 'format "rgb %s %s %s"
12822 (mapcar 'org-normalize-color
12823 (color-values (face-attribute 'default attr nil)))))
12825 (defun org-normalize-color (value)
12826 "Return string to be used as color value for an RGB component."
12827 (format "%g" (/ value 65535.0)))
12829 ;;;; Key bindings
12831 ;; Make `C-c C-x' a prefix key
12832 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12834 ;; TAB key with modifiers
12835 (org-defkey org-mode-map "\C-i" 'org-cycle)
12836 (org-defkey org-mode-map [(tab)] 'org-cycle)
12837 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12838 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12839 (org-defkey org-mode-map "\M-\t" 'org-complete)
12840 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12841 ;; The following line is necessary under Suse GNU/Linux
12842 (unless (featurep 'xemacs)
12843 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12844 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12845 (define-key org-mode-map [backtab] 'org-shifttab)
12847 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12848 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12849 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12851 ;; Cursor keys with modifiers
12852 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12853 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12854 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12855 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12857 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12858 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12859 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12860 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12862 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12863 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12864 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12865 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12867 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12868 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12870 ;;; Extra keys for tty access.
12871 ;; We only set them when really needed because otherwise the
12872 ;; menus don't show the simple keys
12874 (when (or org-use-extra-keys
12875 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12876 (not window-system))
12877 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12878 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12879 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12880 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12881 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12882 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12883 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12884 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12885 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12886 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12887 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12888 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12889 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12890 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12891 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12892 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12893 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12894 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12895 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12896 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12897 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12898 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12900 ;; All the other keys
12902 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12903 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12904 (if (boundp 'narrow-map)
12905 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12906 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12907 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12908 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12909 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12910 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12911 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12912 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12913 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12914 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12915 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12916 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12917 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12918 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12919 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12920 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12921 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12922 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12923 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12924 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12925 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12926 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12927 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12928 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12929 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12930 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12931 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12932 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12933 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12934 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12935 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12936 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12937 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12938 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12939 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12940 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12941 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12942 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12943 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12944 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12945 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12946 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12947 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12948 (org-defkey org-mode-map "\C-c^" 'org-sort)
12949 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12950 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12951 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12952 (org-defkey org-mode-map "\C-m" 'org-return)
12953 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12954 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12955 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12956 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12957 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12958 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12959 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12960 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12961 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12962 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12963 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12964 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12965 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12966 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12967 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12968 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12969 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12971 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12972 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12973 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12974 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12976 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12977 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12978 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12979 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12980 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12981 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12982 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12983 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12984 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12985 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12986 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12987 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
12988 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12990 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12991 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12992 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12993 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
12995 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12997 (when (featurep 'xemacs)
12998 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13000 (defvar org-table-auto-blank-field) ; defined in org-table.el
13001 (defun org-self-insert-command (N)
13002 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13003 If the cursor is in a table looking at whitespace, the whitespace is
13004 overwritten, and the table is not marked as requiring realignment."
13005 (interactive "p")
13006 (if (and (org-table-p)
13007 (progn
13008 ;; check if we blank the field, and if that triggers align
13009 (and (featurep 'org-table) org-table-auto-blank-field
13010 (member last-command
13011 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13012 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13013 ;; got extra space, this field does not determine column width
13014 (let (org-table-may-need-update) (org-table-blank-field))
13015 ;; no extra space, this field may determine column width
13016 (org-table-blank-field)))
13018 (eq N 1)
13019 (looking-at "[^|\n]* |"))
13020 (let (org-table-may-need-update)
13021 (goto-char (1- (match-end 0)))
13022 (delete-backward-char 1)
13023 (goto-char (match-beginning 0))
13024 (self-insert-command N))
13025 (setq org-table-may-need-update t)
13026 (self-insert-command N)
13027 (org-fix-tags-on-the-fly)))
13029 (defun org-fix-tags-on-the-fly ()
13030 (when (and (equal (char-after (point-at-bol)) ?*)
13031 (org-on-heading-p))
13032 (org-align-tags-here org-tags-column)))
13034 (defun org-delete-backward-char (N)
13035 "Like `delete-backward-char', insert whitespace at field end in tables.
13036 When deleting backwards, in tables this function will insert whitespace in
13037 front of the next \"|\" separator, to keep the table aligned. The table will
13038 still be marked for re-alignment if the field did fill the entire column,
13039 because, in this case the deletion might narrow the column."
13040 (interactive "p")
13041 (if (and (org-table-p)
13042 (eq N 1)
13043 (string-match "|" (buffer-substring (point-at-bol) (point)))
13044 (looking-at ".*?|"))
13045 (let ((pos (point))
13046 (noalign (looking-at "[^|\n\r]* |"))
13047 (c org-table-may-need-update))
13048 (backward-delete-char N)
13049 (skip-chars-forward "^|")
13050 (insert " ")
13051 (goto-char (1- pos))
13052 ;; noalign: if there were two spaces at the end, this field
13053 ;; does not determine the width of the column.
13054 (if noalign (setq org-table-may-need-update c)))
13055 (backward-delete-char N)
13056 (org-fix-tags-on-the-fly)))
13058 (defun org-delete-char (N)
13059 "Like `delete-char', but insert whitespace at field end in tables.
13060 When deleting characters, in tables this function will insert whitespace in
13061 front of the next \"|\" separator, to keep the table aligned. The table will
13062 still be marked for re-alignment if the field did fill the entire column,
13063 because, in this case the deletion might narrow the column."
13064 (interactive "p")
13065 (if (and (org-table-p)
13066 (not (bolp))
13067 (not (= (char-after) ?|))
13068 (eq N 1))
13069 (if (looking-at ".*?|")
13070 (let ((pos (point))
13071 (noalign (looking-at "[^|\n\r]* |"))
13072 (c org-table-may-need-update))
13073 (replace-match (concat
13074 (substring (match-string 0) 1 -1)
13075 " |"))
13076 (goto-char pos)
13077 ;; noalign: if there were two spaces at the end, this field
13078 ;; does not determine the width of the column.
13079 (if noalign (setq org-table-may-need-update c)))
13080 (delete-char N))
13081 (delete-char N)
13082 (org-fix-tags-on-the-fly)))
13084 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13085 (put 'org-self-insert-command 'delete-selection t)
13086 (put 'orgtbl-self-insert-command 'delete-selection t)
13087 (put 'org-delete-char 'delete-selection 'supersede)
13088 (put 'org-delete-backward-char 'delete-selection 'supersede)
13089 (put 'org-yank 'delete-selection 'yank)
13091 ;; Make `flyspell-mode' delay after some commands
13092 (put 'org-self-insert-command 'flyspell-delayed t)
13093 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13094 (put 'org-delete-char 'flyspell-delayed t)
13095 (put 'org-delete-backward-char 'flyspell-delayed t)
13097 ;; Make pabbrev-mode expand after org-mode commands
13098 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13099 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13101 ;; How to do this: Measure non-white length of current string
13102 ;; If equal to column width, we should realign.
13104 (defun org-remap (map &rest commands)
13105 "In MAP, remap the functions given in COMMANDS.
13106 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13107 (let (new old)
13108 (while commands
13109 (setq old (pop commands) new (pop commands))
13110 (if (fboundp 'command-remapping)
13111 (org-defkey map (vector 'remap old) new)
13112 (substitute-key-definition old new map global-map)))))
13114 (when (eq org-enable-table-editor 'optimized)
13115 ;; If the user wants maximum table support, we need to hijack
13116 ;; some standard editing functions
13117 (org-remap org-mode-map
13118 'self-insert-command 'org-self-insert-command
13119 'delete-char 'org-delete-char
13120 'delete-backward-char 'org-delete-backward-char)
13121 (org-defkey org-mode-map "|" 'org-force-self-insert))
13123 (defun org-modifier-cursor-error ()
13124 "Throw an error, a modified cursor command was applied in wrong context."
13125 (error "This command is active in special context like tables, headlines or items"))
13127 (defun org-shiftselect-error ()
13128 "Throw an error because Shift-Cursor command was applied in wrong context."
13129 (if (and (boundp 'shift-select-mode) shift-select-mode)
13130 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13131 (error "This command works only in special context like headlines or timestamps.")))
13133 (defun org-call-for-shift-select (cmd)
13134 (let ((this-command-keys-shift-translated t))
13135 (call-interactively cmd)))
13137 (defun org-shifttab (&optional arg)
13138 "Global visibility cycling or move to previous table field.
13139 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13140 on context.
13141 See the individual commands for more information."
13142 (interactive "P")
13143 (cond
13144 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13145 ((integerp arg)
13146 (message "Content view to level: %d" arg)
13147 (org-content (prefix-numeric-value arg))
13148 (setq org-cycle-global-status 'overview))
13149 (t (call-interactively 'org-global-cycle))))
13151 (defun org-shiftmetaleft ()
13152 "Promote subtree or delete table column.
13153 Calls `org-promote-subtree', `org-outdent-item',
13154 or `org-table-delete-column', depending on context.
13155 See the individual commands for more information."
13156 (interactive)
13157 (cond
13158 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13159 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13160 ((org-at-item-p) (call-interactively 'org-outdent-item))
13161 (t (org-modifier-cursor-error))))
13163 (defun org-shiftmetaright ()
13164 "Demote subtree or insert table column.
13165 Calls `org-demote-subtree', `org-indent-item',
13166 or `org-table-insert-column', depending on context.
13167 See the individual commands for more information."
13168 (interactive)
13169 (cond
13170 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13171 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13172 ((org-at-item-p) (call-interactively 'org-indent-item))
13173 (t (org-modifier-cursor-error))))
13175 (defun org-shiftmetaup (&optional arg)
13176 "Move subtree up or kill table row.
13177 Calls `org-move-subtree-up' or `org-table-kill-row' or
13178 `org-move-item-up' depending on context. See the individual commands
13179 for more information."
13180 (interactive "P")
13181 (cond
13182 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13183 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13184 ((org-at-item-p) (call-interactively 'org-move-item-up))
13185 (t (org-modifier-cursor-error))))
13186 (defun org-shiftmetadown (&optional arg)
13187 "Move subtree down or insert table row.
13188 Calls `org-move-subtree-down' or `org-table-insert-row' or
13189 `org-move-item-down', depending on context. See the individual
13190 commands for more information."
13191 (interactive "P")
13192 (cond
13193 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13194 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13195 ((org-at-item-p) (call-interactively 'org-move-item-down))
13196 (t (org-modifier-cursor-error))))
13198 (defun org-metaleft (&optional arg)
13199 "Promote heading or move table column to left.
13200 Calls `org-do-promote' or `org-table-move-column', depending on context.
13201 With no specific context, calls the Emacs default `backward-word'.
13202 See the individual commands for more information."
13203 (interactive "P")
13204 (cond
13205 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13206 ((or (org-on-heading-p) (org-region-active-p))
13207 (call-interactively 'org-do-promote))
13208 ((org-at-item-p) (call-interactively 'org-outdent-item))
13209 (t (call-interactively 'backward-word))))
13211 (defun org-metaright (&optional arg)
13212 "Demote subtree or move table column to right.
13213 Calls `org-do-demote' or `org-table-move-column', depending on context.
13214 With no specific context, calls the Emacs default `forward-word'.
13215 See the individual commands for more information."
13216 (interactive "P")
13217 (cond
13218 ((org-at-table-p) (call-interactively 'org-table-move-column))
13219 ((or (org-on-heading-p) (org-region-active-p))
13220 (call-interactively 'org-do-demote))
13221 ((org-at-item-p) (call-interactively 'org-indent-item))
13222 (t (call-interactively 'forward-word))))
13224 (defun org-metaup (&optional arg)
13225 "Move subtree up or move table row up.
13226 Calls `org-move-subtree-up' or `org-table-move-row' or
13227 `org-move-item-up', depending on context. See the individual commands
13228 for more information."
13229 (interactive "P")
13230 (cond
13231 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13232 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13233 ((org-at-item-p) (call-interactively 'org-move-item-up))
13234 (t (transpose-lines 1) (beginning-of-line -1))))
13236 (defun org-metadown (&optional arg)
13237 "Move subtree down or move table row down.
13238 Calls `org-move-subtree-down' or `org-table-move-row' or
13239 `org-move-item-down', depending on context. See the individual
13240 commands for more information."
13241 (interactive "P")
13242 (cond
13243 ((org-at-table-p) (call-interactively 'org-table-move-row))
13244 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13245 ((org-at-item-p) (call-interactively 'org-move-item-down))
13246 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13248 (defun org-shiftup (&optional arg)
13249 "Increase item in timestamp or increase priority of current headline.
13250 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13251 depending on context. See the individual commands for more information."
13252 (interactive "P")
13253 (cond
13254 ((and org-support-shift-select (org-region-active-p))
13255 (org-call-for-shift-select 'previous-line))
13256 ((org-at-timestamp-p t)
13257 (call-interactively (if org-edit-timestamp-down-means-later
13258 'org-timestamp-down 'org-timestamp-up)))
13259 ((and (not (eq org-support-shift-select 'always))
13260 (org-on-heading-p))
13261 (call-interactively 'org-priority-up))
13262 ((and (not org-support-shift-select) (org-at-item-p))
13263 (call-interactively 'org-previous-item))
13264 ((org-clocktable-try-shift 'up arg))
13265 (org-support-shift-select
13266 (org-call-for-shift-select 'previous-line))
13267 (t (org-shiftselect-error))))
13269 (defun org-shiftdown (&optional arg)
13270 "Decrease item in timestamp or decrease priority of current headline.
13271 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13272 depending on context. See the individual commands for more information."
13273 (interactive "P")
13274 (cond
13275 ((and org-support-shift-select (org-region-active-p))
13276 (org-call-for-shift-select 'next-line))
13277 ((org-at-timestamp-p t)
13278 (call-interactively (if org-edit-timestamp-down-means-later
13279 'org-timestamp-up 'org-timestamp-down)))
13280 ((and (not (eq org-support-shift-select 'always))
13281 (org-on-heading-p))
13282 (call-interactively 'org-priority-down))
13283 ((and (not org-support-shift-select) (org-at-item-p))
13284 (call-interactively 'org-next-item))
13285 ((org-clocktable-try-shift 'down arg))
13286 (org-support-shift-select
13287 (org-call-for-shift-select 'next-line))
13288 (t (org-shiftselect-error))))
13290 (defun org-shiftright (&optional arg)
13291 "Cycle the thing at point or in the current line, depending on context.
13292 Depending on context, this does one of the following:
13294 - switch a timestamp at point one day into the future
13295 - on a headline, switch to the next TODO keyword.
13296 - on an item, switch entire list to the next bullet type
13297 - on a property line, switch to the next allowed value
13298 - on a clocktable definition line, move time block into the future"
13299 (interactive "P")
13300 (cond
13301 ((and org-support-shift-select (org-region-active-p))
13302 (org-call-for-shift-select 'forward-char))
13303 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13304 ((and (not (eq org-support-shift-select 'always))
13305 (org-on-heading-p))
13306 (org-call-with-arg 'org-todo 'right))
13307 ((or (and org-support-shift-select
13308 (not (eq org-support-shift-select 'always))
13309 (org-at-item-bullet-p))
13310 (and (not org-support-shift-select) (org-at-item-p)))
13311 (org-call-with-arg 'org-cycle-list-bullet nil))
13312 ((and (not (eq org-support-shift-select 'always))
13313 (org-at-property-p))
13314 (call-interactively 'org-property-next-allowed-value))
13315 ((org-clocktable-try-shift 'right arg))
13316 (org-support-shift-select
13317 (org-call-for-shift-select 'forward-char))
13318 (t (org-shiftselect-error))))
13320 (defun org-shiftleft (&optional arg)
13321 "Cycle the thing at point or in the current line, depending on context.
13322 Depending on context, this does one of the following:
13324 - switch a timestamp at point one day into the past
13325 - on a headline, switch to the previous TODO keyword.
13326 - on an item, switch entire list to the previous bullet type
13327 - on a property line, switch to the previous allowed value
13328 - on a clocktable definition line, move time block into the past"
13329 (interactive "P")
13330 (cond
13331 ((and org-support-shift-select (org-region-active-p))
13332 (org-call-for-shift-select 'backward-char))
13333 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13334 ((and (not (eq org-support-shift-select 'always))
13335 (org-on-heading-p))
13336 (org-call-with-arg 'org-todo 'left))
13337 ((or (and org-support-shift-select
13338 (not (eq org-support-shift-select 'always))
13339 (org-at-item-bullet-p))
13340 (and (not org-support-shift-select) (org-at-item-p)))
13341 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13342 ((and (not (eq org-support-shift-select 'always))
13343 (org-at-property-p))
13344 (call-interactively 'org-property-previous-allowed-value))
13345 ((org-clocktable-try-shift 'left arg))
13346 (org-support-shift-select
13347 (org-call-for-shift-select 'backward-char))
13348 (t (org-shiftselect-error))))
13350 (defun org-shiftcontrolright ()
13351 "Switch to next TODO set."
13352 (interactive)
13353 (cond
13354 ((and org-support-shift-select (org-region-active-p))
13355 (org-call-for-shift-select 'forward-word))
13356 ((and (not (eq org-support-shift-select 'always))
13357 (org-on-heading-p))
13358 (org-call-with-arg 'org-todo 'nextset))
13359 (org-support-shift-select
13360 (org-call-for-shift-select 'forward-word))
13361 (t (org-shiftselect-error))))
13363 (defun org-shiftcontrolleft ()
13364 "Switch to previous TODO set."
13365 (interactive)
13366 (cond
13367 ((and org-support-shift-select (org-region-active-p))
13368 (org-call-for-shift-select 'backward-word))
13369 ((and (not (eq org-support-shift-select 'always))
13370 (org-on-heading-p))
13371 (org-call-with-arg 'org-todo 'previousset))
13372 (org-support-shift-select
13373 (org-call-for-shift-select 'backward-word))
13374 (t (org-shiftselect-error))))
13376 (defun org-ctrl-c-ret ()
13377 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13378 (interactive)
13379 (cond
13380 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13381 (t (call-interactively 'org-insert-heading))))
13383 (defun org-copy-special ()
13384 "Copy region in table or copy current subtree.
13385 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13386 See the individual commands for more information."
13387 (interactive)
13388 (call-interactively
13389 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13391 (defun org-cut-special ()
13392 "Cut region in table or cut current subtree.
13393 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13394 See the individual commands for more information."
13395 (interactive)
13396 (call-interactively
13397 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13399 (defun org-paste-special (arg)
13400 "Paste rectangular region into table, or past subtree relative to level.
13401 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13402 See the individual commands for more information."
13403 (interactive "P")
13404 (if (org-at-table-p)
13405 (org-table-paste-rectangle)
13406 (org-paste-subtree arg)))
13408 (defun org-edit-special ()
13409 "Call a special editor for the stuff at point.
13410 When at a table, call the formula editor with `org-table-edit-formulas'.
13411 When at the first line of an src example, call `org-edit-src-code'.
13412 When in an #+include line, visit the include file. Otherwise call
13413 `ffap' to visit the file at point."
13414 (interactive)
13415 (cond
13416 ((org-at-table-p)
13417 (call-interactively 'org-table-edit-formulas))
13418 ((save-excursion
13419 (beginning-of-line 1)
13420 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13421 (find-file (org-trim (match-string 1))))
13422 ((org-edit-src-code))
13423 ((org-edit-fixed-width-region))
13424 (t (call-interactively 'ffap))))
13426 (defun org-ctrl-c-ctrl-c (&optional arg)
13427 "Set tags in headline, or update according to changed information at point.
13429 This command does many different things, depending on context:
13431 - If the cursor is in a headline, prompt for tags and insert them
13432 into the current line, aligned to `org-tags-column'. When called
13433 with prefix arg, realign all tags in the current buffer.
13435 - If the cursor is in one of the special #+KEYWORD lines, this
13436 triggers scanning the buffer for these lines and updating the
13437 information.
13439 - If the cursor is inside a table, realign the table. This command
13440 works even if the automatic table editor has been turned off.
13442 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13443 the entire table.
13445 - If the cursor is at a footnote reference or definition, jump to
13446 the corresponding definition or references, respectively.
13448 - If the cursor is a the beginning of a dynamic block, update it.
13450 - If the cursor is inside a table created by the table.el package,
13451 activate that table.
13453 - If the current buffer is a remember buffer, close note and file
13454 it. A prefix argument of 1 files to the default location
13455 without further interaction. A prefix argument of 2 files to
13456 the currently clocking task.
13458 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13459 links in this buffer.
13461 - If the cursor is on a numbered item in a plain list, renumber the
13462 ordered list.
13464 - If the cursor is on a checkbox, toggle it."
13465 (interactive "P")
13466 (let ((org-enable-table-editor t))
13467 (cond
13468 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13469 org-occur-highlights
13470 org-latex-fragment-image-overlays)
13471 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13472 (org-remove-occur-highlights)
13473 (org-remove-latex-fragment-image-overlays)
13474 (message "Temporary highlights/overlays removed from current buffer"))
13475 ((and (local-variable-p 'org-finish-function (current-buffer))
13476 (fboundp org-finish-function))
13477 (funcall org-finish-function))
13478 ((org-at-property-p)
13479 (call-interactively 'org-property-action))
13480 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13481 ((org-on-heading-p) (call-interactively 'org-set-tags))
13482 ((org-at-table.el-p)
13483 (require 'table)
13484 (beginning-of-line 1)
13485 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13486 (call-interactively 'table-recognize-table))
13487 ((org-at-table-p)
13488 (org-table-maybe-eval-formula)
13489 (if arg
13490 (call-interactively 'org-table-recalculate)
13491 (org-table-maybe-recalculate-line))
13492 (call-interactively 'org-table-align))
13493 ((or (org-footnote-at-reference-p)
13494 (org-footnote-at-definition-p))
13495 (call-interactively 'org-footnote-action))
13496 ((org-at-item-checkbox-p)
13497 (call-interactively 'org-toggle-checkbox))
13498 ((org-at-item-p)
13499 (call-interactively 'org-maybe-renumber-ordered-list))
13500 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13501 ;; Dynamic block
13502 (beginning-of-line 1)
13503 (save-excursion (org-update-dblock)))
13504 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13505 (cond
13506 ((equal (match-string 1) "TBLFM")
13507 ;; Recalculate the table before this line
13508 (save-excursion
13509 (beginning-of-line 1)
13510 (skip-chars-backward " \r\n\t")
13511 (if (org-at-table-p)
13512 (org-call-with-arg 'org-table-recalculate t))))
13514 ; (org-set-regexps-and-options)
13515 ; (org-restart-font-lock)
13516 (let ((org-inhibit-startup t)) (org-mode-restart))
13517 (message "Local setup has been refreshed"))))
13518 (t (error "C-c C-c can do nothing useful at this location.")))))
13520 (defun org-mode-restart ()
13521 "Restart Org-mode, to scan again for special lines.
13522 Also updates the keyword regular expressions."
13523 (interactive)
13524 (org-mode)
13525 (message "Org-mode restarted"))
13527 (defun org-kill-note-or-show-branches ()
13528 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13529 (interactive)
13530 (if (not org-finish-function)
13531 (call-interactively 'show-branches)
13532 (let ((org-note-abort t))
13533 (funcall org-finish-function))))
13535 (defun org-return (&optional indent)
13536 "Goto next table row or insert a newline.
13537 Calls `org-table-next-row' or `newline', depending on context.
13538 See the individual commands for more information."
13539 (interactive)
13540 (cond
13541 ((bobp) (if indent (newline-and-indent) (newline)))
13542 ((and (org-at-heading-p)
13543 (looking-at
13544 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13545 (org-show-entry)
13546 (end-of-line 1)
13547 (newline))
13548 ((org-at-table-p)
13549 (org-table-justify-field-maybe)
13550 (call-interactively 'org-table-next-row))
13551 (t (if indent (newline-and-indent) (newline)))))
13553 (defun org-return-indent ()
13554 "Goto next table row or insert a newline and indent.
13555 Calls `org-table-next-row' or `newline-and-indent', depending on
13556 context. See the individual commands for more information."
13557 (interactive)
13558 (org-return t))
13560 (defun org-ctrl-c-star ()
13561 "Compute table, or change heading status of lines.
13562 Calls `org-table-recalculate' or `org-toggle-heading',
13563 depending on context."
13564 (interactive)
13565 (cond
13566 ((org-at-table-p)
13567 (call-interactively 'org-table-recalculate))
13569 ;; Convert all lines in region to list items
13570 (call-interactively 'org-toggle-heading))))
13572 (defun org-ctrl-c-minus ()
13573 "Insert separator line in table or modify bullet status of line.
13574 Also turns a plain line or a region of lines into list items.
13575 Calls `org-table-insert-hline', `org-toggle-item', or
13576 `org-cycle-list-bullet', depending on context."
13577 (interactive)
13578 (cond
13579 ((org-at-table-p)
13580 (call-interactively 'org-table-insert-hline))
13581 ((org-region-active-p)
13582 (call-interactively 'org-toggle-item))
13583 ((org-in-item-p)
13584 (call-interactively 'org-cycle-list-bullet))
13586 (call-interactively 'org-toggle-item))))
13588 (defun org-toggle-item ()
13589 "Convert headings or normal lines to items, items to normal lines.
13590 If there is no active region, only the current line is considered.
13592 If the first line in the region is a headline, convert all headlines to items.
13594 If the first line in the region is an item, convert all items to normal lines.
13596 If the first line is normal text, add an item bullet to each line."
13597 (interactive)
13598 (let (l2 l beg end)
13599 (if (org-region-active-p)
13600 (setq beg (region-beginning) end (region-end))
13601 (setq beg (point-at-bol)
13602 end (min (1+ (point-at-eol)) (point-max))))
13603 (save-excursion
13604 (goto-char end)
13605 (setq l2 (org-current-line))
13606 (goto-char beg)
13607 (beginning-of-line 1)
13608 (setq l (1- (org-current-line)))
13609 (if (org-at-item-p)
13610 ;; We already have items, de-itemize
13611 (while (< (setq l (1+ l)) l2)
13612 (when (org-at-item-p)
13613 (goto-char (match-beginning 2))
13614 (delete-region (match-beginning 2) (match-end 2))
13615 (and (looking-at "[ \t]+") (replace-match "")))
13616 (beginning-of-line 2))
13617 (if (org-on-heading-p)
13618 ;; Headings, convert to items
13619 (while (< (setq l (1+ l)) l2)
13620 (if (looking-at org-outline-regexp)
13621 (replace-match "- " t t))
13622 (beginning-of-line 2))
13623 ;; normal lines, turn them into items
13624 (while (< (setq l (1+ l)) l2)
13625 (unless (org-at-item-p)
13626 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13627 (replace-match "\\1- \\2")))
13628 (beginning-of-line 2)))))))
13630 (defun org-toggle-heading (&optional nstars)
13631 "Convert headings to normal text, or items or text to headings.
13632 If there is no active region, only the current line is considered.
13634 If the first line is a heading, remove the stars from all headlines
13635 in the region.
13637 If the first line is a plain list item, turn all plain list items into
13638 headings.
13640 If the first line is a normal line, turn each and every line in the region
13641 into a heading.
13643 When converting a line into a heading, the number of stars is chosen
13644 such that the lines become children of the current entry. However, when
13645 a prefix argument is given, its value determines the number of stars to add."
13646 (interactive "P")
13647 (let (l2 l itemp beg end)
13648 (if (org-region-active-p)
13649 (setq beg (region-beginning) end (region-end))
13650 (setq beg (point-at-bol)
13651 end (min (1+ (point-at-eol)) (point-max))))
13652 (save-excursion
13653 (goto-char end)
13654 (setq l2 (org-current-line))
13655 (goto-char beg)
13656 (beginning-of-line 1)
13657 (setq l (1- (org-current-line)))
13658 (if (org-on-heading-p)
13659 ;; We already have headlines, de-star them
13660 (while (< (setq l (1+ l)) l2)
13661 (when (org-on-heading-p t)
13662 (and (looking-at outline-regexp) (replace-match "")))
13663 (beginning-of-line 2))
13664 (setq itemp (org-at-item-p))
13665 (let* ((stars
13666 (if nstars
13667 (make-string (prefix-numeric-value current-prefix-arg)
13669 (save-excursion
13670 (re-search-backward org-complex-heading-regexp nil t)
13671 (or (match-string 1) "*"))))
13672 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13673 (rpl (concat stars add-stars " ")))
13674 (while (< (setq l (1+ l)) l2)
13675 (if itemp
13676 (and (org-at-item-p) (replace-match rpl t t))
13677 (unless (org-on-heading-p)
13678 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13679 (replace-match (concat rpl (match-string 2))))))
13680 (beginning-of-line 2)))))))
13682 (defun org-meta-return (&optional arg)
13683 "Insert a new heading or wrap a region in a table.
13684 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13685 See the individual commands for more information."
13686 (interactive "P")
13687 (cond
13688 ((org-at-table-p)
13689 (call-interactively 'org-table-wrap-region))
13690 (t (call-interactively 'org-insert-heading))))
13692 ;;; Menu entries
13694 ;; Define the Org-mode menus
13695 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13696 '("Tbl"
13697 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13698 ["Next Field" org-cycle (org-at-table-p)]
13699 ["Previous Field" org-shifttab (org-at-table-p)]
13700 ["Next Row" org-return (org-at-table-p)]
13701 "--"
13702 ["Blank Field" org-table-blank-field (org-at-table-p)]
13703 ["Edit Field" org-table-edit-field (org-at-table-p)]
13704 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13705 "--"
13706 ("Column"
13707 ["Move Column Left" org-metaleft (org-at-table-p)]
13708 ["Move Column Right" org-metaright (org-at-table-p)]
13709 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13710 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13711 ("Row"
13712 ["Move Row Up" org-metaup (org-at-table-p)]
13713 ["Move Row Down" org-metadown (org-at-table-p)]
13714 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13715 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13716 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13717 "--"
13718 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13719 ("Rectangle"
13720 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13721 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13722 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13723 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13724 "--"
13725 ("Calculate"
13726 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13727 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13728 ["Edit Formulas" org-edit-special (org-at-table-p)]
13729 "--"
13730 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13731 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13732 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13733 "--"
13734 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13735 "--"
13736 ["Sum Column/Rectangle" org-table-sum
13737 (or (org-at-table-p) (org-region-active-p))]
13738 ["Which Column?" org-table-current-column (org-at-table-p)])
13739 ["Debug Formulas"
13740 org-table-toggle-formula-debugger
13741 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13742 ["Show Col/Row Numbers"
13743 org-table-toggle-coordinate-overlays
13744 :style toggle
13745 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13746 "--"
13747 ["Create" org-table-create (and (not (org-at-table-p))
13748 org-enable-table-editor)]
13749 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13750 ["Import from File" org-table-import (not (org-at-table-p))]
13751 ["Export to File" org-table-export (org-at-table-p)]
13752 "--"
13753 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13755 (easy-menu-define org-org-menu org-mode-map "Org menu"
13756 '("Org"
13757 ("Show/Hide"
13758 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13759 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13760 ["Sparse Tree..." org-sparse-tree t]
13761 ["Reveal Context" org-reveal t]
13762 ["Show All" show-all t]
13763 "--"
13764 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13765 "--"
13766 ["New Heading" org-insert-heading t]
13767 ("Navigate Headings"
13768 ["Up" outline-up-heading t]
13769 ["Next" outline-next-visible-heading t]
13770 ["Previous" outline-previous-visible-heading t]
13771 ["Next Same Level" outline-forward-same-level t]
13772 ["Previous Same Level" outline-backward-same-level t]
13773 "--"
13774 ["Jump" org-goto t])
13775 ("Edit Structure"
13776 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13777 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13778 "--"
13779 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13780 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13781 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13782 "--"
13783 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13784 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13785 ["Demote Heading" org-metaright (not (org-at-table-p))]
13786 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13787 "--"
13788 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13789 "--"
13790 ["Convert to odd levels" org-convert-to-odd-levels t]
13791 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13792 ("Editing"
13793 ["Emphasis..." org-emphasize t]
13794 ["Edit Source Example" org-edit-special t]
13795 "--"
13796 ["Footnote new/jump" org-footnote-action t]
13797 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13798 ("Archive"
13799 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13800 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13801 ; :active t :keys "C-u C-c C-x C-a"]
13802 ["Sparse trees open ARCHIVE trees"
13803 (setq org-sparse-tree-open-archived-trees
13804 (not org-sparse-tree-open-archived-trees))
13805 :style toggle :selected org-sparse-tree-open-archived-trees]
13806 ["Cycling opens ARCHIVE trees"
13807 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13808 :style toggle :selected org-cycle-open-archived-trees]
13809 "--"
13810 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13811 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13812 ; ["Check and Move Children" (org-archive-subtree '(4))
13813 ; :active t :keys "C-u C-c C-x C-s"]
13815 "--"
13816 ("TODO Lists"
13817 ["TODO/DONE/-" org-todo t]
13818 ("Select keyword"
13819 ["Next keyword" org-shiftright (org-on-heading-p)]
13820 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13821 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13822 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13823 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13824 ["Show TODO Tree" org-show-todo-tree t]
13825 ["Global TODO list" org-todo-list t]
13826 "--"
13827 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
13828 :selected org-enforce-todo-dependencies :style toggle :active t]
13829 "Settings for tree at point"
13830 ["Do Children sequentially" org-toggle-ordered-property :style radio
13831 :selected (ignore-errors (org-entry-get nil "ORDERED"))
13832 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13833 ["Do Children parallel" org-toggle-ordered-property :style radio
13834 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
13835 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13836 "--"
13837 ["Set Priority" org-priority t]
13838 ["Priority Up" org-shiftup t]
13839 ["Priority Down" org-shiftdown t])
13840 ("TAGS and Properties"
13841 ["Set Tags" org-set-tags-command t]
13842 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13843 "--"
13844 ["Set property" org-set-property t]
13845 ["Column view of properties" org-columns t]
13846 ["Insert Column View DBlock" org-insert-columns-dblock t])
13847 ("Dates and Scheduling"
13848 ["Timestamp" org-time-stamp t]
13849 ["Timestamp (inactive)" org-time-stamp-inactive t]
13850 ("Change Date"
13851 ["1 Day Later" org-shiftright t]
13852 ["1 Day Earlier" org-shiftleft t]
13853 ["1 ... Later" org-shiftup t]
13854 ["1 ... Earlier" org-shiftdown t])
13855 ["Compute Time Range" org-evaluate-time-range t]
13856 ["Schedule Item" org-schedule t]
13857 ["Deadline" org-deadline t]
13858 "--"
13859 ["Custom time format" org-toggle-time-stamp-overlays
13860 :style radio :selected org-display-custom-times]
13861 "--"
13862 ["Goto Calendar" org-goto-calendar t]
13863 ["Date from Calendar" org-date-from-calendar t]
13864 "--"
13865 ["Start/Restart Timer" org-timer-start t]
13866 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13867 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13868 ["Insert Timer String" org-timer t]
13869 ["Insert Timer Item" org-timer-item t])
13870 ("Logging work"
13871 ["Clock in" org-clock-in t]
13872 ["Clock out" org-clock-out t]
13873 ["Clock cancel" org-clock-cancel t]
13874 ["Goto running clock" org-clock-goto t]
13875 ["Display times" org-clock-display t]
13876 ["Create clock table" org-clock-report t]
13877 "--"
13878 ["Record DONE time"
13879 (progn (setq org-log-done (not org-log-done))
13880 (message "Switching to %s will %s record a timestamp"
13881 (car org-done-keywords)
13882 (if org-log-done "automatically" "not")))
13883 :style toggle :selected org-log-done])
13884 "--"
13885 ["Agenda Command..." org-agenda t]
13886 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13887 ("File List for Agenda")
13888 ("Special views current file"
13889 ["TODO Tree" org-show-todo-tree t]
13890 ["Check Deadlines" org-check-deadlines t]
13891 ["Timeline" org-timeline t]
13892 ["Tags Tree" org-tags-sparse-tree t])
13893 "--"
13894 ("Hyperlinks"
13895 ["Store Link (Global)" org-store-link t]
13896 ["Insert Link" org-insert-link t]
13897 ["Follow Link" org-open-at-point t]
13898 "--"
13899 ["Next link" org-next-link t]
13900 ["Previous link" org-previous-link t]
13901 "--"
13902 ["Descriptive Links"
13903 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13904 :style radio
13905 :selected (member '(org-link) buffer-invisibility-spec)]
13906 ["Literal Links"
13907 (progn
13908 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13909 :style radio
13910 :selected (not (member '(org-link) buffer-invisibility-spec))])
13911 "--"
13912 ["Export/Publish..." org-export t]
13913 ("LaTeX"
13914 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13915 :selected org-cdlatex-mode]
13916 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13917 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13918 ["Modify math symbol" org-cdlatex-math-modify
13919 (org-inside-LaTeX-fragment-p)]
13920 ["Export LaTeX fragments as images"
13921 (if (featurep 'org-exp)
13922 (setq org-export-with-LaTeX-fragments
13923 (not org-export-with-LaTeX-fragments))
13924 (require 'org-exp))
13925 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13926 org-export-with-LaTeX-fragments)])
13927 "--"
13928 ("Documentation"
13929 ["Show Version" org-version t]
13930 ["Info Documentation" org-info t])
13931 ("Customize"
13932 ["Browse Org Group" org-customize t]
13933 "--"
13934 ["Expand This Menu" org-create-customize-menu
13935 (fboundp 'customize-menu-create)])
13936 "--"
13937 ["Refresh setup" org-mode-restart t]
13940 (defun org-info (&optional node)
13941 "Read documentation for Org-mode in the info system.
13942 With optional NODE, go directly to that node."
13943 (interactive)
13944 (info (format "(org)%s" (or node ""))))
13946 (defun org-install-agenda-files-menu ()
13947 (let ((bl (buffer-list)))
13948 (save-excursion
13949 (while bl
13950 (set-buffer (pop bl))
13951 (if (org-mode-p) (setq bl nil)))
13952 (when (org-mode-p)
13953 (easy-menu-change
13954 '("Org") "File List for Agenda"
13955 (append
13956 (list
13957 ["Edit File List" (org-edit-agenda-file-list) t]
13958 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13959 ["Remove Current File from List" org-remove-file t]
13960 ["Cycle through agenda files" org-cycle-agenda-files t]
13961 ["Occur in all agenda files" org-occur-in-agenda-files t]
13962 "--")
13963 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13965 ;;;; Documentation
13967 ;;;###autoload
13968 (defun org-require-autoloaded-modules ()
13969 (interactive)
13970 (mapc 'require
13971 '(org-agenda org-archive org-attach org-clock org-colview
13972 org-exp org-id org-export-latex org-publish
13973 org-remember org-table org-timer)))
13975 ;;;###autoload
13976 (defun org-customize ()
13977 "Call the customize function with org as argument."
13978 (interactive)
13979 (org-load-modules-maybe)
13980 (org-require-autoloaded-modules)
13981 (customize-browse 'org))
13983 (defun org-create-customize-menu ()
13984 "Create a full customization menu for Org-mode, insert it into the menu."
13985 (interactive)
13986 (org-load-modules-maybe)
13987 (org-require-autoloaded-modules)
13988 (if (fboundp 'customize-menu-create)
13989 (progn
13990 (easy-menu-change
13991 '("Org") "Customize"
13992 `(["Browse Org group" org-customize t]
13993 "--"
13994 ,(customize-menu-create 'org)
13995 ["Set" Custom-set t]
13996 ["Save" Custom-save t]
13997 ["Reset to Current" Custom-reset-current t]
13998 ["Reset to Saved" Custom-reset-saved t]
13999 ["Reset to Standard Settings" Custom-reset-standard t]))
14000 (message "\"Org\"-menu now contains full customization menu"))
14001 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14003 ;;;; Miscellaneous stuff
14005 ;;; Generally useful functions
14007 (defun org-find-text-property-in-string (prop s)
14008 "Return the first non-nil value of property PROP in string S."
14009 (or (get-text-property 0 prop s)
14010 (get-text-property (or (next-single-property-change 0 prop s) 0)
14011 prop s)))
14013 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14014 "Display the given MESSAGE as a warning."
14015 (if (fboundp 'display-warning)
14016 (display-warning 'org message
14017 (if (featurep 'xemacs)
14018 'warning
14019 :warning))
14020 (let ((buf (get-buffer-create "*Org warnings*")))
14021 (with-current-buffer buf
14022 (goto-char (point-max))
14023 (insert "Warning (Org): " message)
14024 (unless (bolp)
14025 (newline)))
14026 (display-buffer buf)
14027 (sit-for 0))))
14029 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14030 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14031 (if (and marker (marker-buffer marker)
14032 (buffer-live-p (marker-buffer marker)))
14033 (progn
14034 (switch-to-buffer (marker-buffer marker))
14035 (if (or (> marker (point-max)) (< marker (point-min)))
14036 (widen))
14037 (goto-char marker)
14038 (org-show-context 'org-goto))
14039 (if bookmark
14040 (bookmark-jump bookmark)
14041 (error "Cannot find location"))))
14043 (defun org-quote-csv-field (s)
14044 "Quote field for inclusion in CSV material."
14045 (if (string-match "[\",]" s)
14046 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14049 (defun org-plist-delete (plist property)
14050 "Delete PROPERTY from PLIST.
14051 This is in contrast to merely setting it to 0."
14052 (let (p)
14053 (while plist
14054 (if (not (eq property (car plist)))
14055 (setq p (plist-put p (car plist) (nth 1 plist))))
14056 (setq plist (cddr plist)))
14059 (defun org-force-self-insert (N)
14060 "Needed to enforce self-insert under remapping."
14061 (interactive "p")
14062 (self-insert-command N))
14064 (defun org-string-width (s)
14065 "Compute width of string, ignoring invisible characters.
14066 This ignores character with invisibility property `org-link', and also
14067 characters with property `org-cwidth', because these will become invisible
14068 upon the next fontification round."
14069 (let (b l)
14070 (when (or (eq t buffer-invisibility-spec)
14071 (assq 'org-link buffer-invisibility-spec))
14072 (while (setq b (text-property-any 0 (length s)
14073 'invisible 'org-link s))
14074 (setq s (concat (substring s 0 b)
14075 (substring s (or (next-single-property-change
14076 b 'invisible s) (length s)))))))
14077 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14078 (setq s (concat (substring s 0 b)
14079 (substring s (or (next-single-property-change
14080 b 'org-cwidth s) (length s))))))
14081 (setq l (string-width s) b -1)
14082 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14083 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14086 (defun org-get-indentation (&optional line)
14087 "Get the indentation of the current line, interpreting tabs.
14088 When LINE is given, assume it represents a line and compute its indentation."
14089 (if line
14090 (if (string-match "^ *" (org-remove-tabs line))
14091 (match-end 0))
14092 (save-excursion
14093 (beginning-of-line 1)
14094 (skip-chars-forward " \t")
14095 (current-column))))
14097 (defun org-remove-tabs (s &optional width)
14098 "Replace tabulators in S with spaces.
14099 Assumes that s is a single line, starting in column 0."
14100 (setq width (or width tab-width))
14101 (while (string-match "\t" s)
14102 (setq s (replace-match
14103 (make-string
14104 (- (* width (/ (+ (match-beginning 0) width) width))
14105 (match-beginning 0)) ?\ )
14106 t t s)))
14109 (defun org-fix-indentation (line ind)
14110 "Fix indentation in LINE.
14111 IND is a cons cell with target and minimum indentation.
14112 If the current indentation in LINE is smaller than the minimum,
14113 leave it alone. If it is larger than ind, set it to the target."
14114 (let* ((l (org-remove-tabs line))
14115 (i (org-get-indentation l))
14116 (i1 (car ind)) (i2 (cdr ind)))
14117 (if (>= i i2) (setq l (substring line i2)))
14118 (if (> i1 0)
14119 (concat (make-string i1 ?\ ) l)
14120 l)))
14122 (defun org-base-buffer (buffer)
14123 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14124 (if (not buffer)
14125 buffer
14126 (or (buffer-base-buffer buffer)
14127 buffer)))
14129 (defun org-trim (s)
14130 "Remove whitespace at beginning and end of string."
14131 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14132 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14135 (defun org-wrap (string &optional width lines)
14136 "Wrap string to either a number of lines, or a width in characters.
14137 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14138 that costs. If there is a word longer than WIDTH, the text is actually
14139 wrapped to the length of that word.
14140 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14141 many lines, whatever width that takes.
14142 The return value is a list of lines, without newlines at the end."
14143 (let* ((words (org-split-string string "[ \t\n]+"))
14144 (maxword (apply 'max (mapcar 'org-string-width words)))
14145 w ll)
14146 (cond (width
14147 (org-do-wrap words (max maxword width)))
14148 (lines
14149 (setq w maxword)
14150 (setq ll (org-do-wrap words maxword))
14151 (if (<= (length ll) lines)
14153 (setq ll words)
14154 (while (> (length ll) lines)
14155 (setq w (1+ w))
14156 (setq ll (org-do-wrap words w)))
14157 ll))
14158 (t (error "Cannot wrap this")))))
14160 (defun org-do-wrap (words width)
14161 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14162 (let (lines line)
14163 (while words
14164 (setq line (pop words))
14165 (while (and words (< (+ (length line) (length (car words))) width))
14166 (setq line (concat line " " (pop words))))
14167 (setq lines (push line lines)))
14168 (nreverse lines)))
14170 (defun org-split-string (string &optional separators)
14171 "Splits STRING into substrings at SEPARATORS.
14172 No empty strings are returned if there are matches at the beginning
14173 and end of string."
14174 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14175 (start 0)
14176 notfirst
14177 (list nil))
14178 (while (and (string-match rexp string
14179 (if (and notfirst
14180 (= start (match-beginning 0))
14181 (< start (length string)))
14182 (1+ start) start))
14183 (< (match-beginning 0) (length string)))
14184 (setq notfirst t)
14185 (or (eq (match-beginning 0) 0)
14186 (and (eq (match-beginning 0) (match-end 0))
14187 (eq (match-beginning 0) start))
14188 (setq list
14189 (cons (substring string start (match-beginning 0))
14190 list)))
14191 (setq start (match-end 0)))
14192 (or (eq start (length string))
14193 (setq list
14194 (cons (substring string start)
14195 list)))
14196 (nreverse list)))
14198 (defun org-context ()
14199 "Return a list of contexts of the current cursor position.
14200 If several contexts apply, all are returned.
14201 Each context entry is a list with a symbol naming the context, and
14202 two positions indicating start and end of the context. Possible
14203 contexts are:
14205 :headline anywhere in a headline
14206 :headline-stars on the leading stars in a headline
14207 :todo-keyword on a TODO keyword (including DONE) in a headline
14208 :tags on the TAGS in a headline
14209 :priority on the priority cookie in a headline
14210 :item on the first line of a plain list item
14211 :item-bullet on the bullet/number of a plain list item
14212 :checkbox on the checkbox in a plain list item
14213 :table in an org-mode table
14214 :table-special on a special filed in a table
14215 :table-table in a table.el table
14216 :link on a hyperlink
14217 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14218 :target on a <<target>>
14219 :radio-target on a <<<radio-target>>>
14220 :latex-fragment on a LaTeX fragment
14221 :latex-preview on a LaTeX fragment with overlayed preview image
14223 This function expects the position to be visible because it uses font-lock
14224 faces as a help to recognize the following contexts: :table-special, :link,
14225 and :keyword."
14226 (let* ((f (get-text-property (point) 'face))
14227 (faces (if (listp f) f (list f)))
14228 (p (point)) clist o)
14229 ;; First the large context
14230 (cond
14231 ((org-on-heading-p t)
14232 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14233 (when (progn
14234 (beginning-of-line 1)
14235 (looking-at org-todo-line-tags-regexp))
14236 (push (org-point-in-group p 1 :headline-stars) clist)
14237 (push (org-point-in-group p 2 :todo-keyword) clist)
14238 (push (org-point-in-group p 4 :tags) clist))
14239 (goto-char p)
14240 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14241 (if (looking-at "\\[#[A-Z0-9]\\]")
14242 (push (org-point-in-group p 0 :priority) clist)))
14244 ((org-at-item-p)
14245 (push (org-point-in-group p 2 :item-bullet) clist)
14246 (push (list :item (point-at-bol)
14247 (save-excursion (org-end-of-item) (point)))
14248 clist)
14249 (and (org-at-item-checkbox-p)
14250 (push (org-point-in-group p 0 :checkbox) clist)))
14252 ((org-at-table-p)
14253 (push (list :table (org-table-begin) (org-table-end)) clist)
14254 (if (memq 'org-formula faces)
14255 (push (list :table-special
14256 (previous-single-property-change p 'face)
14257 (next-single-property-change p 'face)) clist)))
14258 ((org-at-table-p 'any)
14259 (push (list :table-table) clist)))
14260 (goto-char p)
14262 ;; Now the small context
14263 (cond
14264 ((org-at-timestamp-p)
14265 (push (org-point-in-group p 0 :timestamp) clist))
14266 ((memq 'org-link faces)
14267 (push (list :link
14268 (previous-single-property-change p 'face)
14269 (next-single-property-change p 'face)) clist))
14270 ((memq 'org-special-keyword faces)
14271 (push (list :keyword
14272 (previous-single-property-change p 'face)
14273 (next-single-property-change p 'face)) clist))
14274 ((org-on-target-p)
14275 (push (org-point-in-group p 0 :target) clist)
14276 (goto-char (1- (match-beginning 0)))
14277 (if (looking-at org-radio-target-regexp)
14278 (push (org-point-in-group p 0 :radio-target) clist))
14279 (goto-char p))
14280 ((setq o (car (delq nil
14281 (mapcar
14282 (lambda (x)
14283 (if (memq x org-latex-fragment-image-overlays) x))
14284 (org-overlays-at (point))))))
14285 (push (list :latex-fragment
14286 (org-overlay-start o) (org-overlay-end o)) clist)
14287 (push (list :latex-preview
14288 (org-overlay-start o) (org-overlay-end o)) clist))
14289 ((org-inside-LaTeX-fragment-p)
14290 ;; FIXME: positions wrong.
14291 (push (list :latex-fragment (point) (point)) clist)))
14293 (setq clist (nreverse (delq nil clist)))
14294 clist))
14296 ;; FIXME: Compare with at-regexp-p Do we need both?
14297 (defun org-in-regexp (re &optional nlines visually)
14298 "Check if point is inside a match of regexp.
14299 Normally only the current line is checked, but you can include NLINES extra
14300 lines both before and after point into the search.
14301 If VISUALLY is set, require that the cursor is not after the match but
14302 really on, so that the block visually is on the match."
14303 (catch 'exit
14304 (let ((pos (point))
14305 (eol (point-at-eol (+ 1 (or nlines 0))))
14306 (inc (if visually 1 0)))
14307 (save-excursion
14308 (beginning-of-line (- 1 (or nlines 0)))
14309 (while (re-search-forward re eol t)
14310 (if (and (<= (match-beginning 0) pos)
14311 (>= (+ inc (match-end 0)) pos))
14312 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14314 (defun org-at-regexp-p (regexp)
14315 "Is point inside a match of REGEXP in the current line?"
14316 (catch 'exit
14317 (save-excursion
14318 (let ((pos (point)) (end (point-at-eol)))
14319 (beginning-of-line 1)
14320 (while (re-search-forward regexp end t)
14321 (if (and (<= (match-beginning 0) pos)
14322 (>= (match-end 0) pos))
14323 (throw 'exit t)))
14324 nil))))
14326 (defun org-occur-in-agenda-files (regexp &optional nlines)
14327 "Call `multi-occur' with buffers for all agenda files."
14328 (interactive "sOrg-files matching: \np")
14329 (let* ((files (org-agenda-files))
14330 (tnames (mapcar 'file-truename files))
14331 (extra org-agenda-text-search-extra-files)
14333 (when (eq (car extra) 'agenda-archives)
14334 (setq extra (cdr extra))
14335 (setq files (org-add-archive-files files)))
14336 (while (setq f (pop extra))
14337 (unless (member (file-truename f) tnames)
14338 (add-to-list 'files f 'append)
14339 (add-to-list 'tnames (file-truename f) 'append)))
14340 (multi-occur
14341 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14342 regexp)))
14344 (if (boundp 'occur-mode-find-occurrence-hook)
14345 ;; Emacs 23
14346 (add-hook 'occur-mode-find-occurrence-hook
14347 (lambda ()
14348 (when (org-mode-p)
14349 (org-reveal))))
14350 ;; Emacs 22
14351 (defadvice occur-mode-goto-occurrence
14352 (after org-occur-reveal activate)
14353 (and (org-mode-p) (org-reveal)))
14354 (defadvice occur-mode-goto-occurrence-other-window
14355 (after org-occur-reveal activate)
14356 (and (org-mode-p) (org-reveal)))
14357 (defadvice occur-mode-display-occurrence
14358 (after org-occur-reveal activate)
14359 (when (org-mode-p)
14360 (let ((pos (occur-mode-find-occurrence)))
14361 (with-current-buffer (marker-buffer pos)
14362 (save-excursion
14363 (goto-char pos)
14364 (org-reveal)))))))
14366 (defun org-uniquify (list)
14367 "Remove duplicate elements from LIST."
14368 (let (res)
14369 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14370 res))
14372 (defun org-delete-all (elts list)
14373 "Remove all elements in ELTS from LIST."
14374 (while elts
14375 (setq list (delete (pop elts) list)))
14376 list)
14378 (defun org-back-over-empty-lines ()
14379 "Move backwards over whitespace, to the beginning of the first empty line.
14380 Returns the number of empty lines passed."
14381 (let ((pos (point)))
14382 (skip-chars-backward " \t\n\r")
14383 (beginning-of-line 2)
14384 (goto-char (min (point) pos))
14385 (count-lines (point) pos)))
14387 (defun org-skip-whitespace ()
14388 (skip-chars-forward " \t\n\r"))
14390 (defun org-point-in-group (point group &optional context)
14391 "Check if POINT is in match-group GROUP.
14392 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14393 match. If the match group does ot exist or point is not inside it,
14394 return nil."
14395 (and (match-beginning group)
14396 (>= point (match-beginning group))
14397 (<= point (match-end group))
14398 (if context
14399 (list context (match-beginning group) (match-end group))
14400 t)))
14402 (defun org-switch-to-buffer-other-window (&rest args)
14403 "Switch to buffer in a second window on the current frame.
14404 In particular, do not allow pop-up frames."
14405 (let (pop-up-frames special-display-buffer-names special-display-regexps
14406 special-display-function)
14407 (apply 'switch-to-buffer-other-window args)))
14409 (defun org-combine-plists (&rest plists)
14410 "Create a single property list from all plists in PLISTS.
14411 The process starts by copying the first list, and then setting properties
14412 from the other lists. Settings in the last list are the most significant
14413 ones and overrule settings in the other lists."
14414 (let ((rtn (copy-sequence (pop plists)))
14415 p v ls)
14416 (while plists
14417 (setq ls (pop plists))
14418 (while ls
14419 (setq p (pop ls) v (pop ls))
14420 (setq rtn (plist-put rtn p v))))
14421 rtn))
14423 (defun org-move-line-down (arg)
14424 "Move the current line down. With prefix argument, move it past ARG lines."
14425 (interactive "p")
14426 (let ((col (current-column))
14427 beg end pos)
14428 (beginning-of-line 1) (setq beg (point))
14429 (beginning-of-line 2) (setq end (point))
14430 (beginning-of-line (+ 1 arg))
14431 (setq pos (move-marker (make-marker) (point)))
14432 (insert (delete-and-extract-region beg end))
14433 (goto-char pos)
14434 (org-move-to-column col)))
14436 (defun org-move-line-up (arg)
14437 "Move the current line up. With prefix argument, move it past ARG lines."
14438 (interactive "p")
14439 (let ((col (current-column))
14440 beg end pos)
14441 (beginning-of-line 1) (setq beg (point))
14442 (beginning-of-line 2) (setq end (point))
14443 (beginning-of-line (- arg))
14444 (setq pos (move-marker (make-marker) (point)))
14445 (insert (delete-and-extract-region beg end))
14446 (goto-char pos)
14447 (org-move-to-column col)))
14449 (defun org-replace-escapes (string table)
14450 "Replace %-escapes in STRING with values in TABLE.
14451 TABLE is an association list with keys like \"%a\" and string values.
14452 The sequences in STRING may contain normal field width and padding information,
14453 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14454 so values can contain further %-escapes if they are define later in TABLE."
14455 (let ((case-fold-search nil)
14456 e re rpl)
14457 (while (setq e (pop table))
14458 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14459 (while (string-match re string)
14460 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14461 (cdr e)))
14462 (setq string (replace-match rpl t t string))))
14463 string))
14466 (defun org-sublist (list start end)
14467 "Return a section of LIST, from START to END.
14468 Counting starts at 1."
14469 (let (rtn (c start))
14470 (setq list (nthcdr (1- start) list))
14471 (while (and list (<= c end))
14472 (push (pop list) rtn)
14473 (setq c (1+ c)))
14474 (nreverse rtn)))
14476 (defun org-find-base-buffer-visiting (file)
14477 "Like `find-buffer-visiting' but alway return the base buffer and
14478 not an indirect buffer."
14479 (let ((buf (find-buffer-visiting file)))
14480 (if buf
14481 (or (buffer-base-buffer buf) buf)
14482 nil)))
14484 (defun org-image-file-name-regexp (&optional extensions)
14485 "Return regexp matching the file names of images.
14486 If EXTENSIONS is given, only match these."
14487 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14488 (image-file-name-regexp)
14489 (let ((image-file-name-extensions
14490 (or extensions
14491 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14492 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14493 (concat "\\."
14494 (regexp-opt (nconc (mapcar 'upcase
14495 image-file-name-extensions)
14496 image-file-name-extensions)
14498 "\\'"))))
14500 (defun org-file-image-p (file &optional extensions)
14501 "Return non-nil if FILE is an image."
14502 (save-match-data
14503 (string-match (org-image-file-name-regexp extensions) file)))
14505 (defun org-get-cursor-date ()
14506 "Return the date at cursor in as a time.
14507 This works in the calendar and in the agenda, anywhere else it just
14508 returns the current time."
14509 (let (date day defd)
14510 (cond
14511 ((eq major-mode 'calendar-mode)
14512 (setq date (calendar-cursor-to-date)
14513 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14514 ((eq major-mode 'org-agenda-mode)
14515 (setq day (get-text-property (point) 'day))
14516 (if day
14517 (setq date (calendar-gregorian-from-absolute day)
14518 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14519 (nth 2 date))))))
14520 (or defd (current-time))))
14522 (defvar org-agenda-action-marker (make-marker)
14523 "Marker pointing to the entry for the next agenda action.")
14525 (defun org-mark-entry-for-agenda-action ()
14526 "Mark the current entry as target of an agenda action.
14527 Agenda actions are actions executed from the agenda with the key `k',
14528 which make use of the date at the cursor."
14529 (interactive)
14530 (move-marker org-agenda-action-marker
14531 (save-excursion (org-back-to-heading t) (point))
14532 (current-buffer))
14533 (message
14534 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14536 ;;; Paragraph filling stuff.
14537 ;; We want this to be just right, so use the full arsenal.
14539 (defun org-indent-line-function ()
14540 "Indent line like previous, but further if previous was headline or item."
14541 (interactive)
14542 (let* ((pos (point))
14543 (itemp (org-at-item-p))
14544 column bpos bcol tpos tcol bullet btype bullet-type)
14545 ;; Find the previous relevant line
14546 (beginning-of-line 1)
14547 (cond
14548 ((looking-at "#") (setq column 0))
14549 ((looking-at "\\*+ ") (setq column 0))
14551 (beginning-of-line 0)
14552 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14553 (beginning-of-line 0))
14554 (cond
14555 ((looking-at "\\*+[ \t]+")
14556 (if (not org-adapt-indentation)
14557 (setq column 0)
14558 (goto-char (match-end 0))
14559 (setq column (current-column))))
14560 ((org-in-item-p)
14561 (org-beginning-of-item)
14562 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14563 (setq bpos (match-beginning 1) tpos (match-end 0)
14564 bcol (progn (goto-char bpos) (current-column))
14565 tcol (progn (goto-char tpos) (current-column))
14566 bullet (match-string 1)
14567 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14568 (if (> tcol (+ bcol org-description-max-indent))
14569 (setq tcol (+ bcol 5)))
14570 (if (not itemp)
14571 (setq column tcol)
14572 (goto-char pos)
14573 (beginning-of-line 1)
14574 (if (looking-at "\\S-")
14575 (progn
14576 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14577 (setq bullet (match-string 1)
14578 btype (if (string-match "[0-9]" bullet) "n" bullet))
14579 (setq column (if (equal btype bullet-type) bcol tcol)))
14580 (setq column (org-get-indentation)))))
14581 (t (setq column (org-get-indentation))))))
14582 (goto-char pos)
14583 (if (<= (current-column) (current-indentation))
14584 (org-indent-line-to column)
14585 (save-excursion (org-indent-line-to column)))
14586 (setq column (current-column))
14587 (beginning-of-line 1)
14588 (if (looking-at
14589 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14590 (replace-match (concat "\\1" (format org-property-format
14591 (match-string 2) (match-string 3)))
14592 t nil))
14593 (org-move-to-column column)))
14595 (defun org-set-autofill-regexps ()
14596 (interactive)
14597 ;; In the paragraph separator we include headlines, because filling
14598 ;; text in a line directly attached to a headline would otherwise
14599 ;; fill the headline as well.
14600 (org-set-local 'comment-start-skip "^#+[ \t]*")
14601 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14602 ;; The paragraph starter includes hand-formatted lists.
14603 (org-set-local 'paragraph-start
14604 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14605 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14606 ;; But only if the user has not turned off tables or fixed-width regions
14607 (org-set-local
14608 'auto-fill-inhibit-regexp
14609 (concat "\\*+ \\|#\\+"
14610 "\\|[ \t]*" org-keyword-time-regexp
14611 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14612 (concat
14613 "\\|[ \t]*["
14614 (if org-enable-table-editor "|" "")
14615 (if org-enable-fixed-width-editor ":" "")
14616 "]"))))
14617 ;; We use our own fill-paragraph function, to make sure that tables
14618 ;; and fixed-width regions are not wrapped. That function will pass
14619 ;; through to `fill-paragraph' when appropriate.
14620 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14621 ; Adaptive filling: To get full control, first make sure that
14622 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14623 (org-set-local 'adaptive-fill-regexp "\000")
14624 (org-set-local 'adaptive-fill-function
14625 'org-adaptive-fill-function)
14626 (org-set-local
14627 'align-mode-rules-list
14628 '((org-in-buffer-settings
14629 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14630 (modes . '(org-mode))))))
14632 (defun org-fill-paragraph (&optional justify)
14633 "Re-align a table, pass through to fill-paragraph if no table."
14634 (let ((table-p (org-at-table-p))
14635 (table.el-p (org-at-table.el-p)))
14636 (cond ((and (equal (char-after (point-at-bol)) ?*)
14637 (save-excursion (goto-char (point-at-bol))
14638 (looking-at outline-regexp)))
14639 t) ; skip headlines
14640 (table.el-p t) ; skip table.el tables
14641 (table-p (org-table-align) t) ; align org-mode tables
14642 (t nil)))) ; call paragraph-fill
14644 ;; For reference, this is the default value of adaptive-fill-regexp
14645 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14647 (defun org-adaptive-fill-function ()
14648 "Return a fill prefix for org-mode files.
14649 In particular, this makes sure hanging paragraphs for hand-formatted lists
14650 work correctly."
14651 (cond ((looking-at "#[ \t]+")
14652 (match-string 0))
14653 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14654 (save-excursion
14655 (if (> (match-end 1) (+ (match-beginning 1)
14656 org-description-max-indent))
14657 (goto-char (+ (match-beginning 1) 5))
14658 (goto-char (match-end 0)))
14659 (make-string (current-column) ?\ )))
14660 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14661 (save-excursion
14662 (goto-char (match-end 0))
14663 (make-string (current-column) ?\ )))
14664 (t nil)))
14666 ;;; Other stuff.
14668 (defun org-toggle-fixed-width-section (arg)
14669 "Toggle the fixed-width export.
14670 If there is no active region, the QUOTE keyword at the current headline is
14671 inserted or removed. When present, it causes the text between this headline
14672 and the next to be exported as fixed-width text, and unmodified.
14673 If there is an active region, this command adds or removes a colon as the
14674 first character of this line. If the first character of a line is a colon,
14675 this line is also exported in fixed-width font."
14676 (interactive "P")
14677 (let* ((cc 0)
14678 (regionp (org-region-active-p))
14679 (beg (if regionp (region-beginning) (point)))
14680 (end (if regionp (region-end)))
14681 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14682 (case-fold-search nil)
14683 (re "[ \t]*\\(:\\)")
14684 off)
14685 (if regionp
14686 (save-excursion
14687 (goto-char beg)
14688 (setq cc (current-column))
14689 (beginning-of-line 1)
14690 (setq off (looking-at re))
14691 (while (> nlines 0)
14692 (setq nlines (1- nlines))
14693 (beginning-of-line 1)
14694 (cond
14695 (arg
14696 (org-move-to-column cc t)
14697 (insert ":\n")
14698 (forward-line -1))
14699 ((and off (looking-at re))
14700 (replace-match "" t t nil 1))
14701 ((not off) (org-move-to-column cc t) (insert ":")))
14702 (forward-line 1)))
14703 (save-excursion
14704 (org-back-to-heading)
14705 (if (looking-at (concat outline-regexp
14706 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14707 (replace-match "" t t nil 1)
14708 (if (looking-at outline-regexp)
14709 (progn
14710 (goto-char (match-end 0))
14711 (insert org-quote-string " "))))))))
14713 ;;;; Functions extending outline functionality
14715 (defun org-beginning-of-line (&optional arg)
14716 "Go to the beginning of the current line. If that is invisible, continue
14717 to a visible line beginning. This makes the function of C-a more intuitive.
14718 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14719 first attempt, and only move to after the tags when the cursor is already
14720 beyond the end of the headline."
14721 (interactive "P")
14722 (let ((pos (point)) refpos)
14723 (beginning-of-line 1)
14724 (if (bobp)
14726 (backward-char 1)
14727 (if (org-invisible-p)
14728 (while (and (not (bobp)) (org-invisible-p))
14729 (backward-char 1)
14730 (beginning-of-line 1))
14731 (forward-char 1)))
14732 (when org-special-ctrl-a/e
14733 (cond
14734 ((and (looking-at org-complex-heading-regexp)
14735 (= (char-after (match-end 1)) ?\ ))
14736 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14737 (point-at-eol)))
14738 (goto-char
14739 (if (eq org-special-ctrl-a/e t)
14740 (cond ((> pos refpos) refpos)
14741 ((= pos (point)) refpos)
14742 (t (point)))
14743 (cond ((> pos (point)) (point))
14744 ((not (eq last-command this-command)) (point))
14745 (t refpos)))))
14746 ((org-at-item-p)
14747 (goto-char
14748 (if (eq org-special-ctrl-a/e t)
14749 (cond ((> pos (match-end 4)) (match-end 4))
14750 ((= pos (point)) (match-end 4))
14751 (t (point)))
14752 (cond ((> pos (point)) (point))
14753 ((not (eq last-command this-command)) (point))
14754 (t (match-end 4))))))))
14755 (org-no-warnings
14756 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14758 (defun org-end-of-line (&optional arg)
14759 "Go to the end of the line.
14760 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14761 first attempt, and only move to after the tags when the cursor is already
14762 beyond the end of the headline."
14763 (interactive "P")
14764 (if (or (not org-special-ctrl-a/e)
14765 (not (org-on-heading-p)))
14766 (end-of-line arg)
14767 (let ((pos (point)))
14768 (beginning-of-line 1)
14769 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14770 (if (eq org-special-ctrl-a/e t)
14771 (if (or (< pos (match-beginning 1))
14772 (= pos (match-end 0)))
14773 (goto-char (match-beginning 1))
14774 (goto-char (match-end 0)))
14775 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14776 (goto-char (match-end 0))
14777 (goto-char (match-beginning 1))))
14778 (end-of-line arg))))
14779 (org-no-warnings
14780 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14783 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14784 (define-key org-mode-map "\C-e" 'org-end-of-line)
14786 (defun org-kill-line (&optional arg)
14787 "Kill line, to tags or end of line."
14788 (interactive "P")
14789 (cond
14790 ((or (not org-special-ctrl-k)
14791 (bolp)
14792 (not (org-on-heading-p)))
14793 (call-interactively 'kill-line))
14794 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14795 (kill-region (point) (match-beginning 1))
14796 (org-set-tags nil t))
14797 (t (kill-region (point) (point-at-eol)))))
14799 (define-key org-mode-map "\C-k" 'org-kill-line)
14801 (defun org-yank (&optional arg)
14802 "Yank. If the kill is a subtree, treat it specially.
14803 This command will look at the current kill and check if is a single
14804 subtree, or a series of subtrees[1]. If it passes the test, and if the
14805 cursor is at the beginning of a line or after the stars of a currently
14806 empty headline, then the yank is handled specially. How exactly depends
14807 on the value of the following variables, both set by default.
14809 org-yank-folded-subtrees
14810 When set, the subtree(s) will be folded after insertion, but only
14811 if doing so would now swallow text after the yanked text.
14813 org-yank-adjusted-subtrees
14814 When set, the subtree will be promoted or demoted in order to
14815 fit into the local outline tree structure, which means that the level
14816 will be adjusted so that it becomes the smaller one of the two
14817 *visible* surrounding headings.
14819 Any prefix to this command will cause `yank' to be called directly with
14820 no special treatment. In particular, a simple `C-u' prefix will just
14821 plainly yank the text as it is.
14823 \[1] Basically, the test checks if the first non-white line is a heading
14824 and if there are no other headings with fewer stars."
14825 (interactive "P")
14826 (setq this-command 'yank)
14827 (if arg
14828 (call-interactively 'yank)
14829 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14830 (and (org-kill-is-subtree-p)
14831 (or (bolp)
14832 (and (looking-at "[ \t]*$")
14833 (string-match
14834 "\\`\\*+\\'"
14835 (buffer-substring (point-at-bol) (point)))))))
14836 swallowp)
14837 (cond
14838 ((and subtreep org-yank-folded-subtrees)
14839 (let ((beg (point))
14840 end)
14841 (if (and subtreep org-yank-adjusted-subtrees)
14842 (org-paste-subtree nil nil 'for-yank)
14843 (call-interactively 'yank))
14844 (setq end (point))
14845 (goto-char beg)
14846 (when (and (bolp) subtreep
14847 (not (setq swallowp
14848 (org-yank-folding-would-swallow-text beg end))))
14849 (or (looking-at outline-regexp)
14850 (re-search-forward (concat "^" outline-regexp) end t))
14851 (while (and (< (point) end) (looking-at outline-regexp))
14852 (hide-subtree)
14853 (org-cycle-show-empty-lines 'folded)
14854 (condition-case nil
14855 (outline-forward-same-level 1)
14856 (error (goto-char end)))))
14857 (when swallowp
14858 (message
14859 "Yanked text not folded because that would swallow text"))
14860 (goto-char end)
14861 (skip-chars-forward " \t\n\r")
14862 (beginning-of-line 1)
14863 (push-mark beg 'nomsg)))
14864 ((and subtreep org-yank-adjusted-subtrees)
14865 (let ((beg (point-at-bol)))
14866 (org-paste-subtree nil nil 'for-yank)
14867 (push-mark beg 'nomsg)))
14869 (call-interactively 'yank))))))
14871 (defun org-yank-folding-would-swallow-text (beg end)
14872 "Would hide-subtree at BEG swallow any text after END?"
14873 (let (level)
14874 (save-excursion
14875 (goto-char beg)
14876 (when (or (looking-at outline-regexp)
14877 (re-search-forward (concat "^" outline-regexp) end t))
14878 (setq level (org-outline-level)))
14879 (goto-char end)
14880 (skip-chars-forward " \t\r\n\v\f")
14881 (if (or (eobp)
14882 (and (bolp) (looking-at org-outline-regexp)
14883 (<= (org-outline-level) level)))
14884 nil ; Nothing would be swallowed
14885 t)))) ; something would swallow
14887 (define-key org-mode-map "\C-y" 'org-yank)
14889 (defun org-invisible-p ()
14890 "Check if point is at a character currently not visible."
14891 ;; Early versions of noutline don't have `outline-invisible-p'.
14892 (if (fboundp 'outline-invisible-p)
14893 (outline-invisible-p)
14894 (get-char-property (point) 'invisible)))
14896 (defun org-invisible-p2 ()
14897 "Check if point is at a character currently not visible."
14898 (save-excursion
14899 (if (and (eolp) (not (bobp))) (backward-char 1))
14900 ;; Early versions of noutline don't have `outline-invisible-p'.
14901 (if (fboundp 'outline-invisible-p)
14902 (outline-invisible-p)
14903 (get-char-property (point) 'invisible))))
14905 (defun org-back-to-heading (&optional invisible-ok)
14906 "Call `outline-back-to-heading', but provide a better error message."
14907 (condition-case nil
14908 (outline-back-to-heading invisible-ok)
14909 (error (error "Before first headline at position %d in buffer %s"
14910 (point) (current-buffer)))))
14912 (defun org-before-first-heading-p ()
14913 "Before first heading?"
14914 (save-excursion
14915 (null (re-search-backward "^\\*+ " nil t))))
14917 (defalias 'org-on-heading-p 'outline-on-heading-p)
14918 (defalias 'org-at-heading-p 'outline-on-heading-p)
14919 (defun org-at-heading-or-item-p ()
14920 (or (org-on-heading-p) (org-at-item-p)))
14922 (defun org-on-target-p ()
14923 (or (org-in-regexp org-radio-target-regexp)
14924 (org-in-regexp org-target-regexp)))
14926 (defun org-up-heading-all (arg)
14927 "Move to the heading line of which the present line is a subheading.
14928 This function considers both visible and invisible heading lines.
14929 With argument, move up ARG levels."
14930 (if (fboundp 'outline-up-heading-all)
14931 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14932 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14934 (defun org-up-heading-safe ()
14935 "Move to the heading line of which the present line is a subheading.
14936 This version will not throw an error. It will return the level of the
14937 headline found, or nil if no higher level is found."
14938 (let (start-level re)
14939 (org-back-to-heading t)
14940 (setq start-level (funcall outline-level))
14941 (if (equal start-level 1)
14943 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14944 (if (re-search-backward re nil t)
14945 (funcall outline-level)))))
14947 (defun org-first-sibling-p ()
14948 "Is this heading the first child of its parents?"
14949 (interactive)
14950 (let ((re (concat "^" outline-regexp))
14951 level l)
14952 (unless (org-at-heading-p t)
14953 (error "Not at a heading"))
14954 (setq level (funcall outline-level))
14955 (save-excursion
14956 (if (not (re-search-backward re nil t))
14958 (setq l (funcall outline-level))
14959 (< l level)))))
14961 (defun org-goto-sibling (&optional previous)
14962 "Goto the next sibling, even if it is invisible.
14963 When PREVIOUS is set, go to the previous sibling instead. Returns t
14964 when a sibling was found. When none is found, return nil and don't
14965 move point."
14966 (let ((fun (if previous 're-search-backward 're-search-forward))
14967 (pos (point))
14968 (re (concat "^" outline-regexp))
14969 level l)
14970 (when (condition-case nil (org-back-to-heading t) (error nil))
14971 (setq level (funcall outline-level))
14972 (catch 'exit
14973 (or previous (forward-char 1))
14974 (while (funcall fun re nil t)
14975 (setq l (funcall outline-level))
14976 (when (< l level) (goto-char pos) (throw 'exit nil))
14977 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14978 (goto-char pos)
14979 nil))))
14981 (defun org-show-siblings ()
14982 "Show all siblings of the current headline."
14983 (save-excursion
14984 (while (org-goto-sibling) (org-flag-heading nil)))
14985 (save-excursion
14986 (while (org-goto-sibling 'previous)
14987 (org-flag-heading nil))))
14989 (defun org-show-hidden-entry ()
14990 "Show an entry where even the heading is hidden."
14991 (save-excursion
14992 (org-show-entry)))
14994 (defun org-flag-heading (flag &optional entry)
14995 "Flag the current heading. FLAG non-nil means make invisible.
14996 When ENTRY is non-nil, show the entire entry."
14997 (save-excursion
14998 (org-back-to-heading t)
14999 ;; Check if we should show the entire entry
15000 (if entry
15001 (progn
15002 (org-show-entry)
15003 (save-excursion
15004 (and (outline-next-heading)
15005 (org-flag-heading nil))))
15006 (outline-flag-region (max (point-min) (1- (point)))
15007 (save-excursion (outline-end-of-heading) (point))
15008 flag))))
15010 (defun org-forward-same-level (arg)
15011 "Move forward to the ARG'th subheading at same level as this one.
15012 Stop at the first and last subheadings of a superior heading.
15013 This is like outline-forward-same-level, but invisible headings are ok."
15014 (interactive "p")
15015 (org-back-to-heading t)
15016 (while (> arg 0)
15017 (let ((point-to-move-to (save-excursion
15018 (org-get-next-sibling))))
15019 (if point-to-move-to
15020 (progn
15021 (goto-char point-to-move-to)
15022 (setq arg (1- arg)))
15023 (progn
15024 (setq arg 0)
15025 (error "No following same-level heading"))))))
15027 (defun org-get-next-sibling ()
15028 "Move to next heading of the same level, and return point.
15029 If there is no such heading, return nil.
15030 This is like outline-next-sibling, but invisible headings are ok."
15031 (let ((level (funcall outline-level)))
15032 (outline-next-heading)
15033 (while (and (not (eobp)) (> (funcall outline-level) level))
15034 (outline-next-heading))
15035 (if (or (eobp) (< (funcall outline-level) level))
15037 (point))))
15039 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15040 ;; This is an exact copy of the original function, but it uses
15041 ;; `org-back-to-heading', to make it work also in invisible
15042 ;; trees. And is uses an invisible-OK argument.
15043 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15044 (org-back-to-heading invisible-OK)
15045 (let ((first t)
15046 (level (funcall outline-level)))
15047 (while (and (not (eobp))
15048 (or first (> (funcall outline-level) level)))
15049 (setq first nil)
15050 (outline-next-heading))
15051 (unless to-heading
15052 (if (memq (preceding-char) '(?\n ?\^M))
15053 (progn
15054 ;; Go to end of line before heading
15055 (forward-char -1)
15056 (if (memq (preceding-char) '(?\n ?\^M))
15057 ;; leave blank line before heading
15058 (forward-char -1))))))
15059 (point))
15061 (defun org-show-subtree ()
15062 "Show everything after this heading at deeper levels."
15063 (outline-flag-region
15064 (point)
15065 (save-excursion
15066 (outline-end-of-subtree) (outline-next-heading) (point))
15067 nil))
15069 (defun org-show-entry ()
15070 "Show the body directly following this heading.
15071 Show the heading too, if it is currently invisible."
15072 (interactive)
15073 (save-excursion
15074 (condition-case nil
15075 (progn
15076 (org-back-to-heading t)
15077 (outline-flag-region
15078 (max (point-min) (1- (point)))
15079 (save-excursion
15080 (re-search-forward
15081 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
15082 (or (match-beginning 1) (point-max)))
15083 nil))
15084 (error nil))))
15086 (defun org-make-options-regexp (kwds)
15087 "Make a regular expression for keyword lines."
15088 (concat
15090 "#?[ \t]*\\+\\("
15091 (mapconcat 'regexp-quote kwds "\\|")
15092 "\\):[ \t]*"
15093 "\\(.+\\)"))
15095 ;; Make isearch reveal the necessary context
15096 (defun org-isearch-end ()
15097 "Reveal context after isearch exits."
15098 (when isearch-success ; only if search was successful
15099 (if (featurep 'xemacs)
15100 ;; Under XEmacs, the hook is run in the correct place,
15101 ;; we directly show the context.
15102 (org-show-context 'isearch)
15103 ;; In Emacs the hook runs *before* restoring the overlays.
15104 ;; So we have to use a one-time post-command-hook to do this.
15105 ;; (Emacs 22 has a special variable, see function `org-mode')
15106 (unless (and (boundp 'isearch-mode-end-hook-quit)
15107 isearch-mode-end-hook-quit)
15108 ;; Only when the isearch was not quitted.
15109 (org-add-hook 'post-command-hook 'org-isearch-post-command
15110 'append 'local)))))
15112 (defun org-isearch-post-command ()
15113 "Remove self from hook, and show context."
15114 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15115 (org-show-context 'isearch))
15118 ;;;; Integration with and fixes for other packages
15120 ;;; Imenu support
15122 (defvar org-imenu-markers nil
15123 "All markers currently used by Imenu.")
15124 (make-variable-buffer-local 'org-imenu-markers)
15126 (defun org-imenu-new-marker (&optional pos)
15127 "Return a new marker for use by Imenu, and remember the marker."
15128 (let ((m (make-marker)))
15129 (move-marker m (or pos (point)))
15130 (push m org-imenu-markers)
15133 (defun org-imenu-get-tree ()
15134 "Produce the index for Imenu."
15135 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15136 (setq org-imenu-markers nil)
15137 (let* ((n org-imenu-depth)
15138 (re (concat "^" outline-regexp))
15139 (subs (make-vector (1+ n) nil))
15140 (last-level 0)
15141 m level head)
15142 (save-excursion
15143 (save-restriction
15144 (widen)
15145 (goto-char (point-max))
15146 (while (re-search-backward re nil t)
15147 (setq level (org-reduced-level (funcall outline-level)))
15148 (when (<= level n)
15149 (looking-at org-complex-heading-regexp)
15150 (setq head (org-link-display-format
15151 (org-match-string-no-properties 4))
15152 m (org-imenu-new-marker))
15153 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15154 (if (>= level last-level)
15155 (push (cons head m) (aref subs level))
15156 (push (cons head (aref subs (1+ level))) (aref subs level))
15157 (loop for i from (1+ level) to n do (aset subs i nil)))
15158 (setq last-level level)))))
15159 (aref subs 1)))
15161 (eval-after-load "imenu"
15162 '(progn
15163 (add-hook 'imenu-after-jump-hook
15164 (lambda ()
15165 (if (eq major-mode 'org-mode)
15166 (org-show-context 'org-goto))))))
15168 (defun org-link-display-format (link)
15169 "Replace a link with either the description, or the link target
15170 if no description is present"
15171 (save-match-data
15172 (if (string-match org-bracket-link-analytic-regexp link)
15173 (replace-match (or (match-string 5 link)
15174 (concat (match-string 1 link)
15175 (match-string 3 link)))
15176 nil nil link)
15177 link)))
15179 ;; Speedbar support
15181 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15182 "Overlay marking the agenda restriction line in speedbar.")
15183 (org-overlay-put org-speedbar-restriction-lock-overlay
15184 'face 'org-agenda-restriction-lock)
15185 (org-overlay-put org-speedbar-restriction-lock-overlay
15186 'help-echo "Agendas are currently limited to this item.")
15187 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15189 (defun org-speedbar-set-agenda-restriction ()
15190 "Restrict future agenda commands to the location at point in speedbar.
15191 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15192 (interactive)
15193 (require 'org-agenda)
15194 (let (p m tp np dir txt)
15195 (cond
15196 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15197 'org-imenu t))
15198 (setq m (get-text-property p 'org-imenu-marker))
15199 (save-excursion
15200 (save-restriction
15201 (set-buffer (marker-buffer m))
15202 (goto-char m)
15203 (org-agenda-set-restriction-lock 'subtree))))
15204 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15205 'speedbar-function 'speedbar-find-file))
15206 (setq tp (previous-single-property-change
15207 (1+ p) 'speedbar-function)
15208 np (next-single-property-change
15209 tp 'speedbar-function)
15210 dir (speedbar-line-directory)
15211 txt (buffer-substring-no-properties (or tp (point-min))
15212 (or np (point-max))))
15213 (save-excursion
15214 (save-restriction
15215 (set-buffer (find-file-noselect
15216 (let ((default-directory dir))
15217 (expand-file-name txt))))
15218 (unless (org-mode-p)
15219 (error "Cannot restrict to non-Org-mode file"))
15220 (org-agenda-set-restriction-lock 'file))))
15221 (t (error "Don't know how to restrict Org-mode's agenda")))
15222 (org-move-overlay org-speedbar-restriction-lock-overlay
15223 (point-at-bol) (point-at-eol))
15224 (setq current-prefix-arg nil)
15225 (org-agenda-maybe-redo)))
15227 (eval-after-load "speedbar"
15228 '(progn
15229 (speedbar-add-supported-extension ".org")
15230 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15231 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15232 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15233 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15234 (add-hook 'speedbar-visiting-tag-hook
15235 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15238 ;;; Fixes and Hacks for problems with other packages
15240 ;; Make flyspell not check words in links, to not mess up our keymap
15241 (defun org-mode-flyspell-verify ()
15242 "Don't let flyspell put overlays at active buttons."
15243 (not (get-text-property (point) 'keymap)))
15245 ;; Make `bookmark-jump' show the jump location if it was hidden.
15246 (eval-after-load "bookmark"
15247 '(if (boundp 'bookmark-after-jump-hook)
15248 ;; We can use the hook
15249 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15250 ;; Hook not available, use advice
15251 (defadvice bookmark-jump (after org-make-visible activate)
15252 "Make the position visible."
15253 (org-bookmark-jump-unhide))))
15255 ;; Make sure saveplace show the location if it was hidden
15256 (eval-after-load "saveplace"
15257 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15258 "Make the position visible."
15259 (org-bookmark-jump-unhide)))
15261 (defun org-bookmark-jump-unhide ()
15262 "Unhide the current position, to show the bookmark location."
15263 (and (org-mode-p)
15264 (or (org-invisible-p)
15265 (save-excursion (goto-char (max (point-min) (1- (point))))
15266 (org-invisible-p)))
15267 (org-show-context 'bookmark-jump)))
15269 ;; Make session.el ignore our circular variable
15270 (eval-after-load "session"
15271 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15273 ;;;; Experimental code
15275 (defun org-closed-in-range ()
15276 "Sparse tree of items closed in a certain time range.
15277 Still experimental, may disappear in the future."
15278 (interactive)
15279 ;; Get the time interval from the user.
15280 (let* ((time1 (time-to-seconds
15281 (org-read-date nil 'to-time nil "Starting date: ")))
15282 (time2 (time-to-seconds
15283 (org-read-date nil 'to-time nil "End date:")))
15284 ;; callback function
15285 (callback (lambda ()
15286 (let ((time
15287 (time-to-seconds
15288 (apply 'encode-time
15289 (org-parse-time-string
15290 (match-string 1))))))
15291 ;; check if time in interval
15292 (and (>= time time1) (<= time time2))))))
15293 ;; make tree, check each match with the callback
15294 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15297 ;;;; Finish up
15299 (provide 'org)
15301 (run-hooks 'org-load-hook)
15303 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15305 ;;; org.el ends here