Release 6.20h
[org-mode.git] / lisp / org.el
blobff0451f377611357627271713d69100124b89008
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.20h
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.20h"
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 ot 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 t
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 directory will be used as default to prompt for org files.
1359 Used by the hooks for remember.el."
1360 :group 'org-refile
1361 :group 'org-remember
1362 :type 'directory)
1364 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1365 "Default target for storing notes.
1366 Used by the hooks for remember.el. This can be a string, or nil to mean
1367 the value of `remember-data-file'.
1368 You can set this on a per-template basis with the variable
1369 `org-remember-templates'."
1370 :group 'org-refile
1371 :group 'org-remember
1372 :type '(choice
1373 (const :tag "Default from remember-data-file" nil)
1374 file))
1376 (defcustom org-goto-interface 'outline
1377 "The default interface to be used for `org-goto'.
1378 Allowed values are:
1379 outline The interface shows an outline of the relevant file
1380 and the correct heading is found by moving through
1381 the outline or by searching with incremental search.
1382 outline-path-completion Headlines in the current buffer are offered via
1383 completion. This is the interface also used by
1384 the refile command."
1385 :group 'org-refile
1386 :type '(choice
1387 (const :tag "Outline" outline)
1388 (const :tag "Outline-path-completion" outline-path-completion)))
1390 (defcustom org-goto-max-level 5
1391 "Maximum level to be considered when running org-goto with refile interface."
1392 :group 'org-refile
1393 :type 'number)
1395 (defcustom org-reverse-note-order nil
1396 "Non-nil means, store new notes at the beginning of a file or entry.
1397 When nil, new notes will be filed to the end of a file or entry.
1398 This can also be a list with cons cells of regular expressions that
1399 are matched against file names, and values."
1400 :group 'org-remember
1401 :group 'org-refile
1402 :type '(choice
1403 (const :tag "Reverse always" t)
1404 (const :tag "Reverse never" nil)
1405 (repeat :tag "By file name regexp"
1406 (cons regexp boolean))))
1408 (defcustom org-refile-targets nil
1409 "Targets for refiling entries with \\[org-refile].
1410 This is list of cons cells. Each cell contains:
1411 - a specification of the files to be considered, either a list of files,
1412 or a symbol whose function or variable value will be used to retrieve
1413 a file name or a list of file names. If you use `org-agenda-files' for
1414 that, all agenda files will be scanned for targets. Nil means, consider
1415 headings in the current buffer.
1416 - A specification of how to select find candidate refile targets. This
1417 may be any of
1418 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1419 This tag has to be present in all target headlines, inheritance will
1420 not be considered.
1421 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1422 todo keyword.
1423 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1424 headlines that are refiling targets.
1425 - a cons cell (:level . N). Any headline of level N is considered a target.
1426 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1428 When this variable is nil, all top-level headlines in the current buffer
1429 are used, equivalent to the value `((nil . (:level . 1))'."
1430 :group 'org-refile
1431 :type '(repeat
1432 (cons
1433 (choice :value org-agenda-files
1434 (const :tag "All agenda files" org-agenda-files)
1435 (const :tag "Current buffer" nil)
1436 (function) (variable) (file))
1437 (choice :tag "Identify target headline by"
1438 (cons :tag "Specific tag" (const :value :tag) (string))
1439 (cons :tag "TODO keyword" (const :value :todo) (string))
1440 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1441 (cons :tag "Level number" (const :value :level) (integer))
1442 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1444 (defcustom org-refile-use-outline-path nil
1445 "Non-nil means, provide refile targets as paths.
1446 So a level 3 headline will be available as level1/level2/level3.
1447 When the value is `file', also include the file name (without directory)
1448 into the path. When `full-file-path', include the full file path."
1449 :group 'org-refile
1450 :type '(choice
1451 (const :tag "Not" nil)
1452 (const :tag "Yes" t)
1453 (const :tag "Start with file name" file)
1454 (const :tag "Start with full file path" full-file-path)))
1456 (defcustom org-outline-path-complete-in-steps t
1457 "Non-nil means, complete the outline path in hierarchical steps.
1458 When Org-mode uses the refile interface to select an outline path
1459 \(see variable `org-refile-use-outline-path'), the completion of
1460 the path can be done is a single go, or if can be done in steps down
1461 the headline hierarchy. Going in steps is probably the best if you
1462 do not use a special completion package like `ido' or `icicles'.
1463 However, when using these packages, going in one step can be very
1464 fast, while still showing the whole path to the entry."
1465 :group 'org-refile
1466 :type 'boolean)
1468 (defgroup org-todo nil
1469 "Options concerning TODO items in Org-mode."
1470 :tag "Org TODO"
1471 :group 'org)
1473 (defgroup org-progress nil
1474 "Options concerning Progress logging in Org-mode."
1475 :tag "Org Progress"
1476 :group 'org-time)
1478 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1479 "List of TODO entry keyword sequences and their interpretation.
1480 \\<org-mode-map>This is a list of sequences.
1482 Each sequence starts with a symbol, either `sequence' or `type',
1483 indicating if the keywords should be interpreted as a sequence of
1484 action steps, or as different types of TODO items. The first
1485 keywords are states requiring action - these states will select a headline
1486 for inclusion into the global TODO list Org-mode produces. If one of
1487 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1488 signify that no further action is necessary. If \"|\" is not found,
1489 the last keyword is treated as the only DONE state of the sequence.
1491 The command \\[org-todo] cycles an entry through these states, and one
1492 additional state where no keyword is present. For details about this
1493 cycling, see the manual.
1495 TODO keywords and interpretation can also be set on a per-file basis with
1496 the special #+SEQ_TODO and #+TYP_TODO lines.
1498 Each keyword can optionally specify a character for fast state selection
1499 \(in combination with the variable `org-use-fast-todo-selection')
1500 and specifiers for state change logging, using the same syntax
1501 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1502 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1503 indicates to record a time stamp each time this state is selected.
1505 Each keyword may also specify if a timestamp or a note should be
1506 recorded when entering or leaving the state, by adding additional
1507 characters in the parenthesis after the keyword. This looks like this:
1508 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1509 record only the time of the state change. With X and Y being either
1510 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1511 Y when leaving the state if and only if the *target* state does not
1512 define X. You may omit any of the fast-selection key or X or /Y,
1513 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1515 For backward compatibility, this variable may also be just a list
1516 of keywords - in this case the interpretation (sequence or type) will be
1517 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1518 :group 'org-todo
1519 :group 'org-keywords
1520 :type '(choice
1521 (repeat :tag "Old syntax, just keywords"
1522 (string :tag "Keyword"))
1523 (repeat :tag "New syntax"
1524 (cons
1525 (choice
1526 :tag "Interpretation"
1527 (const :tag "Sequence (cycling hits every state)" sequence)
1528 (const :tag "Type (cycling directly to DONE)" type))
1529 (repeat
1530 (string :tag "Keyword"))))))
1532 (defvar org-todo-keywords-1 nil
1533 "All TODO and DONE keywords active in a buffer.")
1534 (make-variable-buffer-local 'org-todo-keywords-1)
1535 (defvar org-todo-keywords-for-agenda nil)
1536 (defvar org-done-keywords-for-agenda nil)
1537 (defvar org-todo-keyword-alist-for-agenda nil)
1538 (defvar org-tag-alist-for-agenda nil)
1539 (defvar org-agenda-contributing-files nil)
1540 (defvar org-not-done-keywords nil)
1541 (make-variable-buffer-local 'org-not-done-keywords)
1542 (defvar org-done-keywords nil)
1543 (make-variable-buffer-local 'org-done-keywords)
1544 (defvar org-todo-heads nil)
1545 (make-variable-buffer-local 'org-todo-heads)
1546 (defvar org-todo-sets nil)
1547 (make-variable-buffer-local 'org-todo-sets)
1548 (defvar org-todo-log-states nil)
1549 (make-variable-buffer-local 'org-todo-log-states)
1550 (defvar org-todo-kwd-alist nil)
1551 (make-variable-buffer-local 'org-todo-kwd-alist)
1552 (defvar org-todo-key-alist nil)
1553 (make-variable-buffer-local 'org-todo-key-alist)
1554 (defvar org-todo-key-trigger nil)
1555 (make-variable-buffer-local 'org-todo-key-trigger)
1557 (defcustom org-todo-interpretation 'sequence
1558 "Controls how TODO keywords are interpreted.
1559 This variable is in principle obsolete and is only used for
1560 backward compatibility, if the interpretation of todo keywords is
1561 not given already in `org-todo-keywords'. See that variable for
1562 more information."
1563 :group 'org-todo
1564 :group 'org-keywords
1565 :type '(choice (const sequence)
1566 (const type)))
1568 (defcustom org-use-fast-todo-selection 'prefix
1569 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1570 This variable describes if and under what circumstances the cycling
1571 mechanism for TODO keywords will be replaced by a single-key, direct
1572 selection scheme.
1574 When nil, fast selection is never used.
1576 When the symbol `prefix', it will be used when `org-todo' is called with
1577 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1578 in an agenda buffer.
1580 When t, fast selection is used by default. In this case, the prefix
1581 argument forces cycling instead.
1583 In all cases, the special interface is only used if access keys have actually
1584 been assigned by the user, i.e. if keywords in the configuration are followed
1585 by a letter in parenthesis, like TODO(t)."
1586 :group 'org-todo
1587 :type '(choice
1588 (const :tag "Never" nil)
1589 (const :tag "By default" t)
1590 (const :tag "Only with C-u C-c C-t" prefix)))
1592 (defcustom org-provide-todo-statistics t
1593 "Non-nil means, update todo statistics after insert and toggle.
1594 When this is set, todo statistics is updated in the parent of the current
1595 entry each time a todo state is changed."
1596 :group 'org-todo
1597 :type 'boolean)
1599 (defcustom org-after-todo-state-change-hook nil
1600 "Hook which is run after the state of a TODO item was changed.
1601 The new state (a string with a TODO keyword, or nil) is available in the
1602 Lisp variable `state'."
1603 :group 'org-todo
1604 :type 'hook)
1606 (defvar org-blocker-hook nil
1607 "Hook for functions that are allowed to block a state change.
1609 Each function gets as its single argument a property list, see
1610 `org-trigger-hook' for more information about this list.
1612 If any of the functions in this hook returns nil, the state change
1613 is blocked.")
1615 (defvar org-trigger-hook nil
1616 "Hook for functions that are triggered by a state change.
1618 Each function gets as its single argument a property list with at least
1619 the following elements:
1621 (:type type-of-change :position pos-at-entry-start
1622 :from old-state :to new-state)
1624 Depending on the type, more properties may be present.
1626 This mechanism is currently implemented for:
1628 TODO state changes
1629 ------------------
1630 :type todo-state-change
1631 :from previous state (keyword as a string), or nil, or a symbol
1632 'todo' or 'done', to indicate the general type of state.
1633 :to new state, like in :from")
1635 (defcustom org-enforce-todo-dependencies nil
1636 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1637 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1638 be blocked if any prior sibling is not yet done.
1639 You need to set this variable through the customize interface, or to
1640 restart emacs after changing the value."
1641 :set (lambda (var val)
1642 (set var val)
1643 (if val
1644 (add-hook 'org-blocker-hook
1645 'org-block-todo-from-children-or-siblings)
1646 (remove-hook 'org-blocker-hook
1647 'org-block-todo-from-children-or-siblings)))
1648 :group 'org-todo
1649 :type 'boolean)
1651 (defcustom org-enforce-todo-checkbox-dependencies nil
1652 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1653 When this is nil, checkboxes have no influence on switching TODO states.
1654 When non-nil, you first need to check off all check boxes before the TODO
1655 entry can be switched to DONE.
1656 You need to set this variable through the customize interface, or to
1657 restart emacs after changing the value."
1658 :set (lambda (var val)
1659 (set var val)
1660 (if val
1661 (add-hook 'org-blocker-hook
1662 'org-block-todo-from-checkboxes)
1663 (remove-hook 'org-blocker-hook
1664 'org-block-todo-from-checkboxes)))
1665 :group 'org-todo
1666 :type 'boolean)
1668 (defcustom org-todo-state-tags-triggers nil
1669 "Tag changes that should be triggered by TODO state changes.
1670 This is a list. Each entry is
1672 (state-change (tag . flag) .......)
1674 State-change can be a string with a state, and empty string to indicate the
1675 state that has no TODO keyword, or it can be one of the symbols `todo'
1676 or `done', meaning any not-done or done state, respectively."
1677 :group 'org-todo
1678 :group 'org-tags
1679 :type '(repeat
1680 (cons (choice :tag "When changing to"
1681 (const :tag "Not-done state" todo)
1682 (const :tag "Done state" done)
1683 (string :tag "State"))
1684 (repeat
1685 (cons :tag "Tag action"
1686 (string :tag "Tag")
1687 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1689 (defcustom org-log-done nil
1690 "Information to record when a task moves to the DONE state.
1692 Possible values are:
1694 nil Don't add anything, just change the keyword
1695 time Add a time stamp to the task
1696 note Prompt a closing note and add it with template `org-log-note-headings'
1698 This option can also be set with on a per-file-basis with
1700 #+STARTUP: nologdone
1701 #+STARTUP: logdone
1702 #+STARTUP: lognotedone
1704 You can have local logging settings for a subtree by setting the LOGGING
1705 property to one or more of these keywords."
1706 :group 'org-todo
1707 :group 'org-progress
1708 :type '(choice
1709 (const :tag "No logging" nil)
1710 (const :tag "Record CLOSED timestamp" time)
1711 (const :tag "Record CLOSED timestamp with closing note." note)))
1713 ;; Normalize old uses of org-log-done.
1714 (cond
1715 ((eq org-log-done t) (setq org-log-done 'time))
1716 ((and (listp org-log-done) (memq 'done org-log-done))
1717 (setq org-log-done 'note)))
1719 (defcustom org-log-note-clock-out nil
1720 "Non-nil means, record a note when clocking out of an item.
1721 This can also be configured on a per-file basis by adding one of
1722 the following lines anywhere in the buffer:
1724 #+STARTUP: lognoteclock-out
1725 #+STARTUP: nolognoteclock-out"
1726 :group 'org-todo
1727 :group 'org-progress
1728 :type 'boolean)
1730 (defcustom org-log-done-with-time t
1731 "Non-nil means, the CLOSED time stamp will contain date and time.
1732 When nil, only the date will be recorded."
1733 :group 'org-progress
1734 :type 'boolean)
1736 (defcustom org-log-note-headings
1737 '((done . "CLOSING NOTE %t")
1738 (state . "State %-12s %t")
1739 (note . "Note taken on %t")
1740 (clock-out . ""))
1741 "Headings for notes added to entries.
1742 The value is an alist, with the car being a symbol indicating the note
1743 context, and the cdr is the heading to be used. The heading may also be the
1744 empty string.
1745 %t in the heading will be replaced by a time stamp.
1746 %s will be replaced by the new TODO state, in double quotes.
1747 %u will be replaced by the user name.
1748 %U will be replaced by the full user name."
1749 :group 'org-todo
1750 :group 'org-progress
1751 :type '(list :greedy t
1752 (cons (const :tag "Heading when closing an item" done) string)
1753 (cons (const :tag
1754 "Heading when changing todo state (todo sequence only)"
1755 state) string)
1756 (cons (const :tag "Heading when just taking a note" note) string)
1757 (cons (const :tag "Heading when clocking out" clock-out) string)))
1759 (unless (assq 'note org-log-note-headings)
1760 (push '(note . "%t") org-log-note-headings))
1762 (defcustom org-log-state-notes-insert-after-drawers nil
1763 "Non-nil means, insert state change notes after any drawers in entry.
1764 Only the drawers that *immediately* follow the headline and the
1765 deadline/scheduled line are skipped.
1766 When nil, insert notes right after the heading and perhaps the line
1767 with deadline/scheduling if present."
1768 :group 'org-todo
1769 :group 'org-progress
1770 :type 'boolean)
1772 (defcustom org-log-states-order-reversed t
1773 "Non-nil means, the latest state change note will be directly after heading.
1774 When nil, the notes will be orderer according to time."
1775 :group 'org-todo
1776 :group 'org-progress
1777 :type 'boolean)
1779 (defcustom org-log-repeat 'time
1780 "Non-nil means, record moving through the DONE state when triggering repeat.
1781 An auto-repeating tasks is immediately switched back to TODO when marked
1782 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1783 the TODO keyword definition, or recording a closing note by setting
1784 `org-log-done', there will be no record of the task moving through DONE.
1785 This variable forces taking a note anyway. Possible values are:
1787 nil Don't force a record
1788 time Record a time stamp
1789 note Record a note
1791 This option can also be set with on a per-file-basis with
1793 #+STARTUP: logrepeat
1794 #+STARTUP: lognoterepeat
1795 #+STARTUP: nologrepeat
1797 You can have local logging settings for a subtree by setting the LOGGING
1798 property to one or more of these keywords."
1799 :group 'org-todo
1800 :group 'org-progress
1801 :type '(choice
1802 (const :tag "Don't force a record" nil)
1803 (const :tag "Force recording the DONE state" time)
1804 (const :tag "Force recording a note with the DONE state" note)))
1807 (defgroup org-priorities nil
1808 "Priorities in Org-mode."
1809 :tag "Org Priorities"
1810 :group 'org-todo)
1812 (defcustom org-highest-priority ?A
1813 "The highest priority of TODO items. A character like ?A, ?B etc.
1814 Must have a smaller ASCII number than `org-lowest-priority'."
1815 :group 'org-priorities
1816 :type 'character)
1818 (defcustom org-lowest-priority ?C
1819 "The lowest priority of TODO items. A character like ?A, ?B etc.
1820 Must have a larger ASCII number than `org-highest-priority'."
1821 :group 'org-priorities
1822 :type 'character)
1824 (defcustom org-default-priority ?B
1825 "The default priority of TODO items.
1826 This is the priority an item get if no explicit priority is given."
1827 :group 'org-priorities
1828 :type 'character)
1830 (defcustom org-priority-start-cycle-with-default t
1831 "Non-nil means, start with default priority when starting to cycle.
1832 When this is nil, the first step in the cycle will be (depending on the
1833 command used) one higher or lower that the default priority."
1834 :group 'org-priorities
1835 :type 'boolean)
1837 (defgroup org-time nil
1838 "Options concerning time stamps and deadlines in Org-mode."
1839 :tag "Org Time"
1840 :group 'org)
1842 (defcustom org-insert-labeled-timestamps-at-point nil
1843 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1844 When nil, these labeled time stamps are forces into the second line of an
1845 entry, just after the headline. When scheduling from the global TODO list,
1846 the time stamp will always be forced into the second line."
1847 :group 'org-time
1848 :type 'boolean)
1850 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1851 "Formats for `format-time-string' which are used for time stamps.
1852 It is not recommended to change this constant.")
1854 (defcustom org-time-stamp-rounding-minutes '(0 5)
1855 "Number of minutes to round time stamps to.
1856 These are two values, the first applies when first creating a time stamp.
1857 The second applies when changing it with the commands `S-up' and `S-down'.
1858 When changing the time stamp, this means that it will change in steps
1859 of N minutes, as given by the second value.
1861 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1862 numbers should be factors of 60, so for example 5, 10, 15.
1864 When this is larger than 1, you can still force an exact time-stamp by using
1865 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1866 and by using a prefix arg to `S-up/down' to specify the exact number
1867 of minutes to shift."
1868 :group 'org-time
1869 :get '(lambda (var) ; Make sure all entries have 5 elements
1870 (if (integerp (default-value var))
1871 (list (default-value var) 5)
1872 (default-value var)))
1873 :type '(list
1874 (integer :tag "when inserting times")
1875 (integer :tag "when modifying times")))
1877 ;; Normalize old customizations of this variable.
1878 (when (integerp org-time-stamp-rounding-minutes)
1879 (setq org-time-stamp-rounding-minutes
1880 (list org-time-stamp-rounding-minutes
1881 org-time-stamp-rounding-minutes)))
1883 (defcustom org-display-custom-times nil
1884 "Non-nil means, overlay custom formats over all time stamps.
1885 The formats are defined through the variable `org-time-stamp-custom-formats'.
1886 To turn this on on a per-file basis, insert anywhere in the file:
1887 #+STARTUP: customtime"
1888 :group 'org-time
1889 :set 'set-default
1890 :type 'sexp)
1891 (make-variable-buffer-local 'org-display-custom-times)
1893 (defcustom org-time-stamp-custom-formats
1894 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1895 "Custom formats for time stamps. See `format-time-string' for the syntax.
1896 These are overlayed over the default ISO format if the variable
1897 `org-display-custom-times' is set. Time like %H:%M should be at the
1898 end of the second format."
1899 :group 'org-time
1900 :type 'sexp)
1902 (defun org-time-stamp-format (&optional long inactive)
1903 "Get the right format for a time string."
1904 (let ((f (if long (cdr org-time-stamp-formats)
1905 (car org-time-stamp-formats))))
1906 (if inactive
1907 (concat "[" (substring f 1 -1) "]")
1908 f)))
1910 (defcustom org-time-clocksum-format "%d:%02d"
1911 "The format string used when creating CLOCKSUM lines, or when
1912 org-mode generates a time duration."
1913 :group 'org-time
1914 :type 'string)
1916 (defcustom org-deadline-warning-days 14
1917 "No. of days before expiration during which a deadline becomes active.
1918 This variable governs the display in sparse trees and in the agenda.
1919 When 0 or negative, it means use this number (the absolute value of it)
1920 even if a deadline has a different individual lead time specified."
1921 :group 'org-time
1922 :group 'org-agenda-daily/weekly
1923 :type 'number)
1925 (defcustom org-read-date-prefer-future t
1926 "Non-nil means, assume future for incomplete date input from user.
1927 This affects the following situations:
1928 1. The user gives a day, but no month.
1929 For example, if today is the 15th, and you enter \"3\", Org-mode will
1930 read this as the third of *next* month. However, if you enter \"17\",
1931 it will be considered as *this* month.
1932 2. The user gives a month but not a year.
1933 For example, if it is april and you enter \"feb 2\", this will be read
1934 as feb 2, *next* year. \"May 5\", however, will be this year.
1936 Currently this does not work for ISO week specifications.
1938 When this option is nil, the current month and year will always be used
1939 as defaults."
1940 :group 'org-time
1941 :type 'boolean)
1943 (defcustom org-read-date-display-live t
1944 "Non-nil means, display current interpretation of date prompt live.
1945 This display will be in an overlay, in the minibuffer."
1946 :group 'org-time
1947 :type 'boolean)
1949 (defcustom org-read-date-popup-calendar t
1950 "Non-nil means, pop up a calendar when prompting for a date.
1951 In the calendar, the date can be selected with mouse-1. However, the
1952 minibuffer will also be active, and you can simply enter the date as well.
1953 When nil, only the minibuffer will be available."
1954 :group 'org-time
1955 :type 'boolean)
1956 (if (fboundp 'defvaralias)
1957 (defvaralias 'org-popup-calendar-for-date-prompt
1958 'org-read-date-popup-calendar))
1960 (defcustom org-extend-today-until 0
1961 "The hour when your day really ends. Must be an integer.
1962 This has influence for the following applications:
1963 - When switching the agenda to \"today\". It it is still earlier than
1964 the time given here, the day recognized as TODAY is actually yesterday.
1965 - When a date is read from the user and it is still before the time given
1966 here, the current date and time will be assumed to be yesterday, 23:59.
1967 Also, timestamps inserted in remember templates follow this rule.
1969 IMPORTANT: This is a feature whose implementation is and likely will
1970 remain incomplete. Really, it is only here because past midnight seems to
1971 be the favorite working time of John Wiegley :-)"
1972 :group 'org-time
1973 :type 'number)
1975 (defcustom org-edit-timestamp-down-means-later nil
1976 "Non-nil means, S-down will increase the time in a time stamp.
1977 When nil, S-up will increase."
1978 :group 'org-time
1979 :type 'boolean)
1981 (defcustom org-calendar-follow-timestamp-change t
1982 "Non-nil means, make the calendar window follow timestamp changes.
1983 When a timestamp is modified and the calendar window is visible, it will be
1984 moved to the new date."
1985 :group 'org-time
1986 :type 'boolean)
1988 (defgroup org-tags nil
1989 "Options concerning tags in Org-mode."
1990 :tag "Org Tags"
1991 :group 'org)
1993 (defcustom org-tag-alist nil
1994 "List of tags allowed in Org-mode files.
1995 When this list is nil, Org-mode will base TAG input on what is already in the
1996 buffer.
1997 The value of this variable is an alist, the car of each entry must be a
1998 keyword as a string, the cdr may be a character that is used to select
1999 that tag through the fast-tag-selection interface.
2000 See the manual for details."
2001 :group 'org-tags
2002 :type '(repeat
2003 (choice
2004 (cons (string :tag "Tag name")
2005 (character :tag "Access char"))
2006 (const :tag "Start radio group" (:startgroup))
2007 (const :tag "End radio group" (:endgroup)))))
2009 (defvar org-file-tags nil
2010 "List of tags that can be inherited by all entries in the file.
2011 The tags will be inherited if the variable `org-use-tag-inheritance'
2012 says they should be.
2013 This variable is populated from #+TAG lines.")
2015 (defcustom org-use-fast-tag-selection 'auto
2016 "Non-nil means, use fast tag selection scheme.
2017 This is a special interface to select and deselect tags with single keys.
2018 When nil, fast selection is never used.
2019 When the symbol `auto', fast selection is used if and only if selection
2020 characters for tags have been configured, either through the variable
2021 `org-tag-alist' or through a #+TAGS line in the buffer.
2022 When t, fast selection is always used and selection keys are assigned
2023 automatically if necessary."
2024 :group 'org-tags
2025 :type '(choice
2026 (const :tag "Always" t)
2027 (const :tag "Never" nil)
2028 (const :tag "When selection characters are configured" 'auto)))
2030 (defcustom org-fast-tag-selection-single-key nil
2031 "Non-nil means, fast tag selection exits after first change.
2032 When nil, you have to press RET to exit it.
2033 During fast tag selection, you can toggle this flag with `C-c'.
2034 This variable can also have the value `expert'. In this case, the window
2035 displaying the tags menu is not even shown, until you press C-c again."
2036 :group 'org-tags
2037 :type '(choice
2038 (const :tag "No" nil)
2039 (const :tag "Yes" t)
2040 (const :tag "Expert" expert)))
2042 (defvar org-fast-tag-selection-include-todo nil
2043 "Non-nil means, fast tags selection interface will also offer TODO states.
2044 This is an undocumented feature, you should not rely on it.")
2046 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
2047 "The column to which tags should be indented in a headline.
2048 If this number is positive, it specifies the column. If it is negative,
2049 it means that the tags should be flushright to that column. For example,
2050 -80 works well for a normal 80 character screen."
2051 :group 'org-tags
2052 :type 'integer)
2054 (defcustom org-auto-align-tags t
2055 "Non-nil means, realign tags after pro/demotion of TODO state change.
2056 These operations change the length of a headline and therefore shift
2057 the tags around. With this options turned on, after each such operation
2058 the tags are again aligned to `org-tags-column'."
2059 :group 'org-tags
2060 :type 'boolean)
2062 (defcustom org-use-tag-inheritance t
2063 "Non-nil means, tags in levels apply also for sublevels.
2064 When nil, only the tags directly given in a specific line apply there.
2065 This may also be a list of tags that should be inherited, or a regexp that
2066 matches tags that should be inherited. Additional control is possible
2067 with the variable `org-tags-exclude-from-inheritance' which gives an
2068 explicit list of tags to be excluded from inheritance., even if the value of
2069 `org-use-tag-inheritance' would select it for inheritance.
2071 If this option is t, a match early-on in a tree can lead to a large
2072 number of matches in the subtree when constructing the agenda or creating
2073 a sparse tree. If you only want to see the first match in a tree during
2074 a search, check out the variable `org-tags-match-list-sublevels'."
2075 :group 'org-tags
2076 :type '(choice
2077 (const :tag "Not" nil)
2078 (const :tag "Always" t)
2079 (repeat :tag "Specific tags" (string :tag "Tag"))
2080 (regexp :tag "Tags matched by regexp")))
2082 (defcustom org-tags-exclude-from-inheritance nil
2083 "List of tags that should never be inherited.
2084 This is a way to exclude a few tags from inheritance. For way to do
2085 the opposite, to actively allow inheritance for selected tags,
2086 see the variable `org-use-tag-inheritance'."
2087 :group 'org-tags
2088 :type '(repeat (string :tag "Tag")))
2090 (defun org-tag-inherit-p (tag)
2091 "Check if TAG is one that should be inherited."
2092 (cond
2093 ((member tag org-tags-exclude-from-inheritance) nil)
2094 ((eq org-use-tag-inheritance t) t)
2095 ((not org-use-tag-inheritance) nil)
2096 ((stringp org-use-tag-inheritance)
2097 (string-match org-use-tag-inheritance tag))
2098 ((listp org-use-tag-inheritance)
2099 (member tag org-use-tag-inheritance))
2100 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2102 (defcustom org-tags-match-list-sublevels t
2103 "Non-nil means list also sublevels of headlines matching tag search.
2104 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2105 the sublevels of a headline matching a tag search often also match
2106 the same search. Listing all of them can create very long lists.
2107 Setting this variable to nil causes subtrees of a match to be skipped.
2108 This option is off by default, because inheritance in on. If you turn
2109 inheritance off, you very likely want to turn this option on.
2111 As a special case, if the tag search is restricted to TODO items, the
2112 value of this variable is ignored and sublevels are always checked, to
2113 make sure all corresponding TODO items find their way into the list.
2115 This variable is semi-obsolete and probably should always be true. It
2116 is better to limit inheritance to certain tags using the variables
2117 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2118 :group 'org-tags
2119 :type 'boolean)
2121 (defvar org-tags-history nil
2122 "History of minibuffer reads for tags.")
2123 (defvar org-last-tags-completion-table nil
2124 "The last used completion table for tags.")
2125 (defvar org-after-tags-change-hook nil
2126 "Hook that is run after the tags in a line have changed.")
2128 (defgroup org-properties nil
2129 "Options concerning properties in Org-mode."
2130 :tag "Org Properties"
2131 :group 'org)
2133 (defcustom org-property-format "%-10s %s"
2134 "How property key/value pairs should be formatted by `indent-line'.
2135 When `indent-line' hits a property definition, it will format the line
2136 according to this format, mainly to make sure that the values are
2137 lined-up with respect to each other."
2138 :group 'org-properties
2139 :type 'string)
2141 (defcustom org-use-property-inheritance nil
2142 "Non-nil means, properties apply also for sublevels.
2144 This setting is chiefly used during property searches. Turning it on can
2145 cause significant overhead when doing a search, which is why it is not
2146 on by default.
2148 When nil, only the properties directly given in the current entry count.
2149 When t, every property is inherited. The value may also be a list of
2150 properties that should have inheritance, or a regular expression matching
2151 properties that should be inherited.
2153 However, note that some special properties use inheritance under special
2154 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2155 and the properties ending in \"_ALL\" when they are used as descriptor
2156 for valid values of a property.
2158 Note for programmers:
2159 When querying an entry with `org-entry-get', you can control if inheritance
2160 should be used. By default, `org-entry-get' looks only at the local
2161 properties. You can request inheritance by setting the inherit argument
2162 to t (to force inheritance) or to `selective' (to respect the setting
2163 in this variable)."
2164 :group 'org-properties
2165 :type '(choice
2166 (const :tag "Not" nil)
2167 (const :tag "Always" t)
2168 (repeat :tag "Specific properties" (string :tag "Property"))
2169 (regexp :tag "Properties matched by regexp")))
2171 (defun org-property-inherit-p (property)
2172 "Check if PROPERTY is one that should be inherited."
2173 (cond
2174 ((eq org-use-property-inheritance t) t)
2175 ((not org-use-property-inheritance) nil)
2176 ((stringp org-use-property-inheritance)
2177 (string-match org-use-property-inheritance property))
2178 ((listp org-use-property-inheritance)
2179 (member property org-use-property-inheritance))
2180 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2182 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2183 "The default column format, if no other format has been defined.
2184 This variable can be set on the per-file basis by inserting a line
2186 #+COLUMNS: %25ITEM ....."
2187 :group 'org-properties
2188 :type 'string)
2190 (defcustom org-columns-ellipses ".."
2191 "The ellipses to be used when a field in column view is truncated.
2192 When this is the empty string, as many characters as possible are shown,
2193 but then there will be no visual indication that the field has been truncated.
2194 When this is a string of length N, the last N characters of a truncated
2195 field are replaced by this string. If the column is narrower than the
2196 ellipses string, only part of the ellipses string will be shown."
2197 :group 'org-properties
2198 :type 'string)
2200 (defcustom org-columns-modify-value-for-display-function nil
2201 "Function that modifies values for display in column view.
2202 For example, it can be used to cut out a certain part from a time stamp.
2203 The function must take 2 arguments:
2205 column-title The title of the column (*not* the property name)
2206 value The value that should be modified.
2208 The function should return the value that should be displayed,
2209 or nil if the normal value should be used."
2210 :group 'org-properties
2211 :type 'function)
2213 (defcustom org-effort-property "Effort"
2214 "The property that is being used to keep track of effort estimates.
2215 Effort estimates given in this property need to have the format H:MM."
2216 :group 'org-properties
2217 :group 'org-progress
2218 :type '(string :tag "Property"))
2220 (defconst org-global-properties-fixed
2221 '(("VISIBILITY_ALL" . "folded children content all"))
2222 "List of property/value pairs that can be inherited by any entry.
2223 These are fixed values, for the preset properties.")
2226 (defcustom org-global-properties nil
2227 "List of property/value pairs that can be inherited by any entry.
2228 You can set buffer-local values for the same purpose in the variable
2229 `org-file-properties' this by adding lines like
2231 #+PROPERTY: NAME VALUE"
2232 :group 'org-properties
2233 :type '(repeat
2234 (cons (string :tag "Property")
2235 (string :tag "Value"))))
2237 (defvar org-file-properties nil
2238 "List of property/value pairs that can be inherited by any entry.
2239 Valid for the current buffer.
2240 This variable is populated from #+PROPERTY lines.")
2241 (make-variable-buffer-local 'org-file-properties)
2243 (defgroup org-agenda nil
2244 "Options concerning agenda views in Org-mode."
2245 :tag "Org Agenda"
2246 :group 'org)
2248 (defvar org-category nil
2249 "Variable used by org files to set a category for agenda display.
2250 Such files should use a file variable to set it, for example
2252 # -*- mode: org; org-category: \"ELisp\"
2254 or contain a special line
2256 #+CATEGORY: ELisp
2258 If the file does not specify a category, then file's base name
2259 is used instead.")
2260 (make-variable-buffer-local 'org-category)
2261 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2263 (defcustom org-agenda-files nil
2264 "The files to be used for agenda display.
2265 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2266 \\[org-remove-file]. You can also use customize to edit the list.
2268 If an entry is a directory, all files in that directory that are matched by
2269 `org-agenda-file-regexp' will be part of the file list.
2271 If the value of the variable is not a list but a single file name, then
2272 the list of agenda files is actually stored and maintained in that file, one
2273 agenda file per line."
2274 :group 'org-agenda
2275 :type '(choice
2276 (repeat :tag "List of files and directories" file)
2277 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2279 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2280 "Regular expression to match files for `org-agenda-files'.
2281 If any element in the list in that variable contains a directory instead
2282 of a normal file, all files in that directory that are matched by this
2283 regular expression will be included."
2284 :group 'org-agenda
2285 :type 'regexp)
2287 (defcustom org-agenda-text-search-extra-files nil
2288 "List of extra files to be searched by text search commands.
2289 These files will be search in addition to the agenda files by the
2290 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2291 Note that these files will only be searched for text search commands,
2292 not for the other agenda views like todo lists, tag searches or the weekly
2293 agenda. This variable is intended to list notes and possibly archive files
2294 that should also be searched by these two commands.
2295 In fact, if the first element in the list is the symbol `agenda-archives',
2296 than all archive files of all agenda files will be added to the search
2297 scope."
2298 :group 'org-agenda
2299 :type '(set :greedy t
2300 (const :tag "Agenda Archives" agenda-archives)
2301 (repeat :inline t (file))))
2303 (if (fboundp 'defvaralias)
2304 (defvaralias 'org-agenda-multi-occur-extra-files
2305 'org-agenda-text-search-extra-files))
2307 (defcustom org-agenda-skip-unavailable-files nil
2308 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2309 A nil value means to remove them, after a query, from the list."
2310 :group 'org-agenda
2311 :type 'boolean)
2313 (defcustom org-calendar-to-agenda-key [?c]
2314 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2315 The command `org-calendar-goto-agenda' will be bound to this key. The
2316 default is the character `c' because then `c' can be used to switch back and
2317 forth between agenda and calendar."
2318 :group 'org-agenda
2319 :type 'sexp)
2321 (defcustom org-calendar-agenda-action-key [?k]
2322 "The key to be installed in `calendar-mode-map' for agenda-action.
2323 The command `org-agenda-action' will be bound to this key. The
2324 default is the character `k' because we use the same key in the agenda."
2325 :group 'org-agenda
2326 :type 'sexp)
2328 (eval-after-load "calendar"
2329 '(progn
2330 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2331 'org-calendar-goto-agenda)
2332 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2333 'org-agenda-action)))
2335 (defgroup org-latex nil
2336 "Options for embedding LaTeX code into Org-mode."
2337 :tag "Org LaTeX"
2338 :group 'org)
2340 (defcustom org-format-latex-options
2341 '(:foreground default :background default :scale 1.0
2342 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2343 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2344 "Options for creating images from LaTeX fragments.
2345 This is a property list with the following properties:
2346 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2347 `default' means use the foreground of the default face.
2348 :background the background color, or \"Transparent\".
2349 `default' means use the background of the default face.
2350 :scale a scaling factor for the size of the images.
2351 :html-foreground, :html-background, :html-scale
2352 the same numbers for HTML export.
2353 :matchers a list indicating which matchers should be used to
2354 find LaTeX fragments. Valid members of this list are:
2355 \"begin\" find environments
2356 \"$1\" find single characters surrounded by $.$
2357 \"$\" find math expressions surrounded by $...$
2358 \"$$\" find math expressions surrounded by $$....$$
2359 \"\\(\" find math expressions surrounded by \\(...\\)
2360 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2361 :group 'org-latex
2362 :type 'plist)
2364 (defcustom org-format-latex-header "\\documentclass{article}
2365 \\usepackage{fullpage} % do not remove
2366 \\usepackage{amssymb}
2367 \\usepackage[usenames]{color}
2368 \\usepackage{amsmath}
2369 \\usepackage{latexsym}
2370 \\usepackage[mathscr]{eucal}
2371 \\pagestyle{empty} % do not remove"
2372 "The document header used for processing LaTeX fragments."
2373 :group 'org-latex
2374 :type 'string)
2377 (defgroup org-font-lock nil
2378 "Font-lock settings for highlighting in Org-mode."
2379 :tag "Org Font Lock"
2380 :group 'org)
2382 (defcustom org-level-color-stars-only nil
2383 "Non-nil means fontify only the stars in each headline.
2384 When nil, the entire headline is fontified.
2385 Changing it requires restart of `font-lock-mode' to become effective
2386 also in regions already fontified."
2387 :group 'org-font-lock
2388 :type 'boolean)
2390 (defcustom org-hide-leading-stars nil
2391 "Non-nil means, hide the first N-1 stars in a headline.
2392 This works by using the face `org-hide' for these stars. This
2393 face is white for a light background, and black for a dark
2394 background. You may have to customize the face `org-hide' to
2395 make this work.
2396 Changing it requires restart of `font-lock-mode' to become effective
2397 also in regions already fontified.
2398 You may also set this on a per-file basis by adding one of the following
2399 lines to the buffer:
2401 #+STARTUP: hidestars
2402 #+STARTUP: showstars"
2403 :group 'org-font-lock
2404 :type 'boolean)
2406 (defcustom org-fontify-done-headline nil
2407 "Non-nil means, change the face of a headline if it is marked DONE.
2408 Normally, only the TODO/DONE keyword indicates the state of a headline.
2409 When this is non-nil, the headline after the keyword is set to the
2410 `org-headline-done' as an additional indication."
2411 :group 'org-font-lock
2412 :type 'boolean)
2414 (defcustom org-fontify-emphasized-text t
2415 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2416 Changing this variable requires a restart of Emacs to take effect."
2417 :group 'org-font-lock
2418 :type 'boolean)
2420 (defcustom org-highlight-latex-fragments-and-specials nil
2421 "Non-nil means, fontify what is treated specially by the exporters."
2422 :group 'org-font-lock
2423 :type 'boolean)
2425 (defcustom org-hide-emphasis-markers nil
2426 "Non-nil mean font-lock should hide the emphasis marker characters."
2427 :group 'org-font-lock
2428 :type 'boolean)
2430 (defvar org-emph-re nil
2431 "Regular expression for matching emphasis.")
2432 (defvar org-verbatim-re nil
2433 "Regular expression for matching verbatim text.")
2434 (defvar org-emphasis-regexp-components) ; defined just below
2435 (defvar org-emphasis-alist) ; defined just below
2436 (defun org-set-emph-re (var val)
2437 "Set variable and compute the emphasis regular expression."
2438 (set var val)
2439 (when (and (boundp 'org-emphasis-alist)
2440 (boundp 'org-emphasis-regexp-components)
2441 org-emphasis-alist org-emphasis-regexp-components)
2442 (let* ((e org-emphasis-regexp-components)
2443 (pre (car e))
2444 (post (nth 1 e))
2445 (border (nth 2 e))
2446 (body (nth 3 e))
2447 (nl (nth 4 e))
2448 (body1 (concat body "*?"))
2449 (markers (mapconcat 'car org-emphasis-alist ""))
2450 (vmarkers (mapconcat
2451 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2452 org-emphasis-alist "")))
2453 ;; make sure special characters appear at the right position in the class
2454 (if (string-match "\\^" markers)
2455 (setq markers (concat (replace-match "" t t markers) "^")))
2456 (if (string-match "-" markers)
2457 (setq markers (concat (replace-match "" t t markers) "-")))
2458 (if (string-match "\\^" vmarkers)
2459 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2460 (if (string-match "-" vmarkers)
2461 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2462 (if (> nl 0)
2463 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2464 (int-to-string nl) "\\}")))
2465 ;; Make the regexp
2466 (setq org-emph-re
2467 (concat "\\([" pre "]\\|^\\)"
2468 "\\("
2469 "\\([" markers "]\\)"
2470 "\\("
2471 "[^" border "]\\|"
2472 "[^" border "]"
2473 body1
2474 "[^" border "]"
2475 "\\)"
2476 "\\3\\)"
2477 "\\([" post "]\\|$\\)"))
2478 (setq org-verbatim-re
2479 (concat "\\([" pre "]\\|^\\)"
2480 "\\("
2481 "\\([" vmarkers "]\\)"
2482 "\\("
2483 "[^" border "]\\|"
2484 "[^" border "]"
2485 body1
2486 "[^" border "]"
2487 "\\)"
2488 "\\3\\)"
2489 "\\([" post "]\\|$\\)")))))
2491 (defcustom org-emphasis-regexp-components
2492 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2493 "Components used to build the regular expression for emphasis.
2494 This is a list with 6 entries. Terminology: In an emphasis string
2495 like \" *strong word* \", we call the initial space PREMATCH, the final
2496 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2497 and \"trong wor\" is the body. The different components in this variable
2498 specify what is allowed/forbidden in each part:
2500 pre Chars allowed as prematch. Beginning of line will be allowed too.
2501 post Chars allowed as postmatch. End of line will be allowed too.
2502 border The chars *forbidden* as border characters.
2503 body-regexp A regexp like \".\" to match a body character. Don't use
2504 non-shy groups here, and don't allow newline here.
2505 newline The maximum number of newlines allowed in an emphasis exp.
2507 Use customize to modify this, or restart Emacs after changing it."
2508 :group 'org-font-lock
2509 :set 'org-set-emph-re
2510 :type '(list
2511 (sexp :tag "Allowed chars in pre ")
2512 (sexp :tag "Allowed chars in post ")
2513 (sexp :tag "Forbidden chars in border ")
2514 (sexp :tag "Regexp for body ")
2515 (integer :tag "number of newlines allowed")
2516 (option (boolean :tag "Please ignore this button"))))
2518 (defcustom org-emphasis-alist
2519 `(("*" bold "<b>" "</b>")
2520 ("/" italic "<i>" "</i>")
2521 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2522 ("=" org-code "<code>" "</code>" verbatim)
2523 ("~" org-verbatim "<code>" "</code>" verbatim)
2524 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2525 "<del>" "</del>")
2527 "Special syntax for emphasized text.
2528 Text starting and ending with a special character will be emphasized, for
2529 example *bold*, _underlined_ and /italic/. This variable sets the marker
2530 characters, the face to be used by font-lock for highlighting in Org-mode
2531 Emacs buffers, and the HTML tags to be used for this.
2532 Use customize to modify this, or restart Emacs after changing it."
2533 :group 'org-font-lock
2534 :set 'org-set-emph-re
2535 :type '(repeat
2536 (list
2537 (string :tag "Marker character")
2538 (choice
2539 (face :tag "Font-lock-face")
2540 (plist :tag "Face property list"))
2541 (string :tag "HTML start tag")
2542 (string :tag "HTML end tag")
2543 (option (const verbatim)))))
2545 ;;; Miscellaneous options
2547 (defgroup org-completion nil
2548 "Completion in Org-mode."
2549 :tag "Org Completion"
2550 :group 'org)
2552 (defcustom org-completion-use-ido nil
2553 "Non-nil means, use ido completion wherever possible.
2554 Note that `ido-mode' must be active for this variable to be relevant.
2555 If you decide to turn this variable on, you might well want to turn off
2556 `org-outline-path-complete-in-steps'."
2557 :group 'org-completion
2558 :type 'boolean)
2560 (defcustom org-completion-fallback-command 'hippie-expand
2561 "The expansion command called by \\[org-complete] in normal context.
2562 Normal means, no org-mode-specific context."
2563 :group 'org-completion
2564 :type 'function)
2566 ;;; Functions and variables from ther packages
2567 ;; Declared here to avoid compiler warnings
2569 ;; XEmacs only
2570 (defvar outline-mode-menu-heading)
2571 (defvar outline-mode-menu-show)
2572 (defvar outline-mode-menu-hide)
2573 (defvar zmacs-regions) ; XEmacs regions
2575 ;; Emacs only
2576 (defvar mark-active)
2578 ;; Various packages
2579 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2580 (declare-function calendar-forward-day "cal-move" (arg))
2581 (declare-function calendar-goto-date "cal-move" (date))
2582 (declare-function calendar-goto-today "cal-move" ())
2583 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2584 (defvar calc-embedded-close-formula)
2585 (defvar calc-embedded-open-formula)
2586 (declare-function cdlatex-tab "ext:cdlatex" ())
2587 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2588 (defvar font-lock-unfontify-region-function)
2589 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2590 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2591 (defvar iswitchb-temp-buflist)
2592 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2593 (defvar org-agenda-tags-todo-honor-ignore-options)
2594 (declare-function org-agenda-skip "org-agenda" ())
2595 (declare-function org-format-agenda-item "org-agenda"
2596 (extra txt &optional category tags dotime noprefix remove-re))
2597 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2598 (declare-function org-agenda-change-all-lines "org-agenda"
2599 (newhead hdmarker &optional fixface just-this))
2600 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2601 (declare-function org-agenda-maybe-redo "org-agenda" ())
2602 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2603 (beg end))
2604 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2605 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2606 "org-agenda" (&optional end))
2608 (declare-function parse-time-string "parse-time" (string))
2609 (declare-function remember "remember" (&optional initial))
2610 (declare-function remember-buffer-desc "remember" ())
2611 (declare-function remember-finalize "remember" ())
2612 (defvar remember-save-after-remembering)
2613 (defvar remember-data-file)
2614 (defvar remember-register)
2615 (defvar remember-buffer)
2616 (defvar remember-handler-functions)
2617 (defvar remember-annotation-functions)
2618 (defvar texmathp-why)
2619 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2620 (declare-function table--at-cell-p "table" (position &optional object at-column))
2622 (defvar w3m-current-url)
2623 (defvar w3m-current-title)
2625 (defvar org-latex-regexps)
2627 ;;; Autoload and prepare some org modules
2629 ;; Some table stuff that needs to be defined here, because it is used
2630 ;; by the functions setting up org-mode or checking for table context.
2632 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2633 "Detects an org-type or table-type table.")
2634 (defconst org-table-line-regexp "^[ \t]*|"
2635 "Detects an org-type table line.")
2636 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2637 "Detects an org-type table line.")
2638 (defconst org-table-hline-regexp "^[ \t]*|-"
2639 "Detects an org-type table hline.")
2640 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2641 "Detects a table-type table hline.")
2642 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2643 "Searching from within a table (any type) this finds the first line
2644 outside the table.")
2646 ;; Autoload the functions in org-table.el that are needed by functions here.
2648 (eval-and-compile
2649 (org-autoload "org-table"
2650 '(org-table-align org-table-begin org-table-blank-field
2651 org-table-convert org-table-convert-region org-table-copy-down
2652 org-table-copy-region org-table-create
2653 org-table-create-or-convert-from-region
2654 org-table-create-with-table.el org-table-current-dline
2655 org-table-cut-region org-table-delete-column org-table-edit-field
2656 org-table-edit-formulas org-table-end org-table-eval-formula
2657 org-table-export org-table-field-info
2658 org-table-get-stored-formulas org-table-goto-column
2659 org-table-hline-and-move org-table-import org-table-insert-column
2660 org-table-insert-hline org-table-insert-row org-table-iterate
2661 org-table-justify-field-maybe org-table-kill-row
2662 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2663 org-table-move-column org-table-move-column-left
2664 org-table-move-column-right org-table-move-row
2665 org-table-move-row-down org-table-move-row-up
2666 org-table-next-field org-table-next-row org-table-paste-rectangle
2667 org-table-previous-field org-table-recalculate
2668 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2669 org-table-toggle-coordinate-overlays
2670 org-table-toggle-formula-debugger org-table-wrap-region
2671 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2673 (defun org-at-table-p (&optional table-type)
2674 "Return t if the cursor is inside an org-type table.
2675 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2676 (if org-enable-table-editor
2677 (save-excursion
2678 (beginning-of-line 1)
2679 (looking-at (if table-type org-table-any-line-regexp
2680 org-table-line-regexp)))
2681 nil))
2682 (defsubst org-table-p () (org-at-table-p))
2684 (defun org-at-table.el-p ()
2685 "Return t if and only if we are at a table.el table."
2686 (and (org-at-table-p 'any)
2687 (save-excursion
2688 (goto-char (org-table-begin 'any))
2689 (looking-at org-table1-hline-regexp))))
2690 (defun org-table-recognize-table.el ()
2691 "If there is a table.el table nearby, recognize it and move into it."
2692 (if org-table-tab-recognizes-table.el
2693 (if (org-at-table.el-p)
2694 (progn
2695 (beginning-of-line 1)
2696 (if (looking-at org-table-dataline-regexp)
2698 (if (looking-at org-table1-hline-regexp)
2699 (progn
2700 (beginning-of-line 2)
2701 (if (looking-at org-table-any-border-regexp)
2702 (beginning-of-line -1)))))
2703 (if (re-search-forward "|" (org-table-end t) t)
2704 (progn
2705 (require 'table)
2706 (if (table--at-cell-p (point))
2708 (message "recognizing table.el table...")
2709 (table-recognize-table)
2710 (message "recognizing table.el table...done")))
2711 (error "This should not happen..."))
2713 nil)
2714 nil))
2716 (defun org-at-table-hline-p ()
2717 "Return t if the cursor is inside a hline in a table."
2718 (if org-enable-table-editor
2719 (save-excursion
2720 (beginning-of-line 1)
2721 (looking-at org-table-hline-regexp))
2722 nil))
2724 (defvar org-table-clean-did-remove-column nil)
2726 (defun org-table-map-tables (function)
2727 "Apply FUNCTION to the start of all tables in the buffer."
2728 (save-excursion
2729 (save-restriction
2730 (widen)
2731 (goto-char (point-min))
2732 (while (re-search-forward org-table-any-line-regexp nil t)
2733 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2734 (beginning-of-line 1)
2735 (if (looking-at org-table-line-regexp)
2736 (save-excursion (funcall function)))
2737 (re-search-forward org-table-any-border-regexp nil 1))))
2738 (message "Mapping tables: done"))
2740 ;; Declare and autoload functions from org-exp.el
2742 (declare-function org-default-export-plist "org-exp")
2743 (declare-function org-infile-export-plist "org-exp")
2744 (declare-function org-get-current-options "org-exp")
2745 (eval-and-compile
2746 (org-autoload "org-exp"
2747 '(org-export org-export-as-ascii org-export-visible
2748 org-insert-export-options-template org-export-as-html-and-open
2749 org-export-as-html-batch org-export-as-html-to-buffer
2750 org-replace-region-by-html org-export-region-as-html
2751 org-export-as-html org-export-icalendar-this-file
2752 org-export-icalendar-all-agenda-files
2753 org-table-clean-before-export
2754 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2756 ;; Declare and autoload functions from org-agenda.el
2758 (eval-and-compile
2759 (org-autoload "org-agenda"
2760 '(org-agenda org-agenda-list org-search-view
2761 org-todo-list org-tags-view org-agenda-list-stuck-projects
2762 org-diary org-agenda-to-appt
2763 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2765 ;; Autoload org-remember
2767 (eval-and-compile
2768 (org-autoload "org-remember"
2769 '(org-remember-insinuate org-remember-annotation
2770 org-remember-apply-template org-remember org-remember-handler)))
2772 ;; Autoload org-clock.el
2775 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2776 (beg end))
2777 (declare-function org-clock-update-mode-line "org-clock" ())
2778 (defvar org-clock-start-time)
2779 (defvar org-clock-marker (make-marker)
2780 "Marker recording the last clock-in.")
2782 (eval-and-compile
2783 (org-autoload
2784 "org-clock"
2785 '(org-clock-in org-clock-out org-clock-cancel
2786 org-clock-goto org-clock-sum org-clock-display
2787 org-clock-remove-overlays org-clock-report
2788 org-clocktable-shift org-dblock-write:clocktable
2789 org-get-clocktable)))
2791 (defun org-clock-update-time-maybe ()
2792 "If this is a CLOCK line, update it and return t.
2793 Otherwise, return nil."
2794 (interactive)
2795 (save-excursion
2796 (beginning-of-line 1)
2797 (skip-chars-forward " \t")
2798 (when (looking-at org-clock-string)
2799 (let ((re (concat "[ \t]*" org-clock-string
2800 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2801 "\\([ \t]*=>.*\\)?\\)?"))
2802 ts te h m s neg)
2803 (cond
2804 ((not (looking-at re))
2805 nil)
2806 ((not (match-end 2))
2807 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2808 (> org-clock-marker (point))
2809 (<= org-clock-marker (point-at-eol)))
2810 ;; The clock is running here
2811 (setq org-clock-start-time
2812 (apply 'encode-time
2813 (org-parse-time-string (match-string 1))))
2814 (org-clock-update-mode-line)))
2816 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2817 (end-of-line 1)
2818 (setq ts (match-string 1)
2819 te (match-string 3))
2820 (setq s (- (time-to-seconds
2821 (apply 'encode-time (org-parse-time-string te)))
2822 (time-to-seconds
2823 (apply 'encode-time (org-parse-time-string ts))))
2824 neg (< s 0)
2825 s (abs s)
2826 h (floor (/ s 3600))
2827 s (- s (* 3600 h))
2828 m (floor (/ s 60))
2829 s (- s (* 60 s)))
2830 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2831 t))))))
2833 (defun org-check-running-clock ()
2834 "Check if the current buffer contains the running clock.
2835 If yes, offer to stop it and to save the buffer with the changes."
2836 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2837 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2838 (buffer-name))))
2839 (org-clock-out)
2840 (when (y-or-n-p "Save changed buffer?")
2841 (save-buffer))))
2843 (defun org-clocktable-try-shift (dir n)
2844 "Check if this line starts a clock table, if yes, shift the time block."
2845 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2846 (org-clocktable-shift dir n)))
2848 ;; Autoload org-timer.el
2850 ;(declare-function org-timer "org-timer")
2852 (eval-and-compile
2853 (org-autoload
2854 "org-timer"
2855 '(org-timer-start org-timer org-timer-item
2856 org-timer-change-times-in-region)))
2859 ;; Autoload archiving code
2860 ;; The stuff that is needed for cycling and tags has to be defined here.
2862 (defgroup org-archive nil
2863 "Options concerning archiving in Org-mode."
2864 :tag "Org Archive"
2865 :group 'org-structure)
2867 (defcustom org-archive-location "%s_archive::"
2868 "The location where subtrees should be archived.
2870 The value of this variable is a string, consisting of two parts,
2871 separated by a double-colon. The first part is a filename and
2872 the second part is a headline.
2874 When the filename is omitted, archiving happens in the same file.
2875 %s in the filename will be replaced by the current file
2876 name (without the directory part). Archiving to a different file
2877 is useful to keep archived entries from contributing to the
2878 Org-mode Agenda.
2880 The archived entries will be filed as subtrees of the specified
2881 headline. When the headline is omitted, the subtrees are simply
2882 filed away at the end of the file, as top-level entries. Also in
2883 the heading you can use %s to represent the file name, this can be
2884 useful when using the same archive for a number of different files.
2886 Here are a few examples:
2887 \"%s_archive::\"
2888 If the current file is Projects.org, archive in file
2889 Projects.org_archive, as top-level trees. This is the default.
2891 \"::* Archived Tasks\"
2892 Archive in the current file, under the top-level headline
2893 \"* Archived Tasks\".
2895 \"~/org/archive.org::\"
2896 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2898 \"~/org/archive.org::From %s\"
2899 Archive in file ~/org/archive.org (absolute path), und headlines
2900 \"From FILENAME\" where file name is the current file name.
2902 \"basement::** Finished Tasks\"
2903 Archive in file ./basement (relative path), as level 3 trees
2904 below the level 2 heading \"** Finished Tasks\".
2906 You may set this option on a per-file basis by adding to the buffer a
2907 line like
2909 #+ARCHIVE: basement::** Finished Tasks
2911 You may also define it locally for a subtree by setting an ARCHIVE property
2912 in the entry. If such a property is found in an entry, or anywhere up
2913 the hierarchy, it will be used."
2914 :group 'org-archive
2915 :type 'string)
2917 (defcustom org-archive-tag "ARCHIVE"
2918 "The tag that marks a subtree as archived.
2919 An archived subtree does not open during visibility cycling, and does
2920 not contribute to the agenda listings.
2921 After changing this, font-lock must be restarted in the relevant buffers to
2922 get the proper fontification."
2923 :group 'org-archive
2924 :group 'org-keywords
2925 :type 'string)
2927 (defcustom org-agenda-skip-archived-trees t
2928 "Non-nil means, the agenda will skip any items located in archived trees.
2929 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2930 variable is no longer recommended, you should leave it at the value t.
2931 Instead, use the key `v' to cycle the archives-mode in the agenda."
2932 :group 'org-archive
2933 :group 'org-agenda-skip
2934 :type 'boolean)
2936 (defcustom org-cycle-open-archived-trees nil
2937 "Non-nil means, `org-cycle' will open archived trees.
2938 An archived tree is a tree marked with the tag ARCHIVE.
2939 When nil, archived trees will stay folded. You can still open them with
2940 normal outline commands like `show-all', but not with the cycling commands."
2941 :group 'org-archive
2942 :group 'org-cycle
2943 :type 'boolean)
2945 (defcustom org-sparse-tree-open-archived-trees nil
2946 "Non-nil means sparse tree construction shows matches in archived trees.
2947 When nil, matches in these trees are highlighted, but the trees are kept in
2948 collapsed state."
2949 :group 'org-archive
2950 :group 'org-sparse-trees
2951 :type 'boolean)
2953 (defun org-cycle-hide-archived-subtrees (state)
2954 "Re-hide all archived subtrees after a visibility state change."
2955 (when (and (not org-cycle-open-archived-trees)
2956 (not (memq state '(overview folded))))
2957 (save-excursion
2958 (let* ((globalp (memq state '(contents all)))
2959 (beg (if globalp (point-min) (point)))
2960 (end (if globalp (point-max) (org-end-of-subtree t))))
2961 (org-hide-archived-subtrees beg end)
2962 (goto-char beg)
2963 (if (looking-at (concat ".*:" org-archive-tag ":"))
2964 (message "%s" (substitute-command-keys
2965 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2967 (defun org-force-cycle-archived ()
2968 "Cycle subtree even if it is archived."
2969 (interactive)
2970 (setq this-command 'org-cycle)
2971 (let ((org-cycle-open-archived-trees t))
2972 (call-interactively 'org-cycle)))
2974 (defun org-hide-archived-subtrees (beg end)
2975 "Re-hide all archived subtrees after a visibility state change."
2976 (save-excursion
2977 (let* ((re (concat ":" org-archive-tag ":")))
2978 (goto-char beg)
2979 (while (re-search-forward re end t)
2980 (and (org-on-heading-p) (hide-subtree))
2981 (org-end-of-subtree t)))))
2983 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2985 (eval-and-compile
2986 (org-autoload "org-archive"
2987 '(org-add-archive-files org-archive-subtree
2988 org-archive-to-archive-sibling org-toggle-archive-tag)))
2990 ;; Autoload Column View Code
2992 (declare-function org-columns-number-to-string "org-colview")
2993 (declare-function org-columns-get-format-and-top-level "org-colview")
2994 (declare-function org-columns-compute "org-colview")
2996 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2997 '(org-columns-number-to-string org-columns-get-format-and-top-level
2998 org-columns-compute org-agenda-columns org-columns-remove-overlays
2999 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3001 ;; Autoload ID code
3003 (declare-function org-id-store-link "org-id")
3004 (org-autoload "org-id"
3005 '(org-id-get-create org-id-new org-id-copy org-id-get
3006 org-id-get-with-outline-path-completion
3007 org-id-get-with-outline-drilling
3008 org-id-goto org-id-find org-id-store-link))
3010 ;;; Variables for pre-computed regular expressions, all buffer local
3012 (defvar org-drawer-regexp nil
3013 "Matches first line of a hidden block.")
3014 (make-variable-buffer-local 'org-drawer-regexp)
3015 (defvar org-todo-regexp nil
3016 "Matches any of the TODO state keywords.")
3017 (make-variable-buffer-local 'org-todo-regexp)
3018 (defvar org-not-done-regexp nil
3019 "Matches any of the TODO state keywords except the last one.")
3020 (make-variable-buffer-local 'org-not-done-regexp)
3021 (defvar org-todo-line-regexp nil
3022 "Matches a headline and puts TODO state into group 2 if present.")
3023 (make-variable-buffer-local 'org-todo-line-regexp)
3024 (defvar org-complex-heading-regexp nil
3025 "Matches a headline and puts everything into groups:
3026 group 1: the stars
3027 group 2: The todo keyword, maybe
3028 group 3: Priority cookie
3029 group 4: True headline
3030 group 5: Tags")
3031 (make-variable-buffer-local 'org-complex-heading-regexp)
3032 (defvar org-todo-line-tags-regexp nil
3033 "Matches a headline and puts TODO state into group 2 if present.
3034 Also put tags into group 4 if tags are present.")
3035 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3036 (defvar org-nl-done-regexp nil
3037 "Matches newline followed by a headline with the DONE keyword.")
3038 (make-variable-buffer-local 'org-nl-done-regexp)
3039 (defvar org-looking-at-done-regexp nil
3040 "Matches the DONE keyword a point.")
3041 (make-variable-buffer-local 'org-looking-at-done-regexp)
3042 (defvar org-ds-keyword-length 12
3043 "Maximum length of the Deadline and SCHEDULED keywords.")
3044 (make-variable-buffer-local 'org-ds-keyword-length)
3045 (defvar org-deadline-regexp nil
3046 "Matches the DEADLINE keyword.")
3047 (make-variable-buffer-local 'org-deadline-regexp)
3048 (defvar org-deadline-time-regexp nil
3049 "Matches the DEADLINE keyword together with a time stamp.")
3050 (make-variable-buffer-local 'org-deadline-time-regexp)
3051 (defvar org-deadline-line-regexp nil
3052 "Matches the DEADLINE keyword and the rest of the line.")
3053 (make-variable-buffer-local 'org-deadline-line-regexp)
3054 (defvar org-scheduled-regexp nil
3055 "Matches the SCHEDULED keyword.")
3056 (make-variable-buffer-local 'org-scheduled-regexp)
3057 (defvar org-scheduled-time-regexp nil
3058 "Matches the SCHEDULED keyword together with a time stamp.")
3059 (make-variable-buffer-local 'org-scheduled-time-regexp)
3060 (defvar org-closed-time-regexp nil
3061 "Matches the CLOSED keyword together with a time stamp.")
3062 (make-variable-buffer-local 'org-closed-time-regexp)
3064 (defvar org-keyword-time-regexp nil
3065 "Matches any of the 4 keywords, together with the time stamp.")
3066 (make-variable-buffer-local 'org-keyword-time-regexp)
3067 (defvar org-keyword-time-not-clock-regexp nil
3068 "Matches any of the 3 keywords, together with the time stamp.")
3069 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3070 (defvar org-maybe-keyword-time-regexp nil
3071 "Matches a timestamp, possibly preceeded by a keyword.")
3072 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3073 (defvar org-planning-or-clock-line-re nil
3074 "Matches a line with planning or clock info.")
3075 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3077 (defconst org-plain-time-of-day-regexp
3078 (concat
3079 "\\(\\<[012]?[0-9]"
3080 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3081 "\\(--?"
3082 "\\(\\<[012]?[0-9]"
3083 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3084 "\\)?")
3085 "Regular expression to match a plain time or time range.
3086 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3087 groups carry important information:
3088 0 the full match
3089 1 the first time, range or not
3090 8 the second time, if it is a range.")
3092 (defconst org-plain-time-extension-regexp
3093 (concat
3094 "\\(\\<[012]?[0-9]"
3095 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3096 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3097 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3098 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3099 groups carry important information:
3100 0 the full match
3101 7 hours of duration
3102 9 minutes of duration")
3104 (defconst org-stamp-time-of-day-regexp
3105 (concat
3106 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3107 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3108 "\\(--?"
3109 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3110 "Regular expression to match a timestamp time or time range.
3111 After a match, the following groups carry important information:
3112 0 the full match
3113 1 date plus weekday, for backreferencing to make sure both times on same day
3114 2 the first time, range or not
3115 4 the second time, if it is a range.")
3117 (defconst org-startup-options
3118 '(("fold" org-startup-folded t)
3119 ("overview" org-startup-folded t)
3120 ("nofold" org-startup-folded nil)
3121 ("showall" org-startup-folded nil)
3122 ("content" org-startup-folded content)
3123 ("hidestars" org-hide-leading-stars t)
3124 ("showstars" org-hide-leading-stars nil)
3125 ("odd" org-odd-levels-only t)
3126 ("oddeven" org-odd-levels-only nil)
3127 ("align" org-startup-align-all-tables t)
3128 ("noalign" org-startup-align-all-tables nil)
3129 ("customtime" org-display-custom-times t)
3130 ("logdone" org-log-done time)
3131 ("lognotedone" org-log-done note)
3132 ("nologdone" org-log-done nil)
3133 ("lognoteclock-out" org-log-note-clock-out t)
3134 ("nolognoteclock-out" org-log-note-clock-out nil)
3135 ("logrepeat" org-log-repeat state)
3136 ("lognoterepeat" org-log-repeat note)
3137 ("nologrepeat" org-log-repeat nil)
3138 ("fninline" org-footnote-define-inline t)
3139 ("nofninline" org-footnote-define-inline nil)
3140 ("fnlocal" org-footnote-section nil)
3141 ("fnauto" org-footnote-auto-label t)
3142 ("fnprompt" org-footnote-auto-label nil)
3143 ("fnconfirm" org-footnote-auto-label confirm)
3144 ("fnplain" org-footnote-auto-label plain)
3145 ("constcgs" constants-unit-system cgs)
3146 ("constSI" constants-unit-system SI))
3147 "Variable associated with STARTUP options for org-mode.
3148 Each element is a list of three items: The startup options as written
3149 in the #+STARTUP line, the corresponding variable, and the value to
3150 set this variable to if the option is found. An optional forth element PUSH
3151 means to push this value onto the list in the variable.")
3153 (defun org-set-regexps-and-options ()
3154 "Precompute regular expressions for current buffer."
3155 (when (org-mode-p)
3156 (org-set-local 'org-todo-kwd-alist nil)
3157 (org-set-local 'org-todo-key-alist nil)
3158 (org-set-local 'org-todo-key-trigger nil)
3159 (org-set-local 'org-todo-keywords-1 nil)
3160 (org-set-local 'org-done-keywords nil)
3161 (org-set-local 'org-todo-heads nil)
3162 (org-set-local 'org-todo-sets nil)
3163 (org-set-local 'org-todo-log-states nil)
3164 (org-set-local 'org-file-properties nil)
3165 (org-set-local 'org-file-tags nil)
3166 (let ((re (org-make-options-regexp
3167 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3168 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3169 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3170 (splitre "[ \t]+")
3171 kwds kws0 kwsa key log value cat arch tags const links hw dws
3172 tail sep kws1 prio props ftags drawers
3173 ext-setup-or-nil setup-contents (start 0))
3174 (save-excursion
3175 (save-restriction
3176 (widen)
3177 (goto-char (point-min))
3178 (while (or (and ext-setup-or-nil
3179 (string-match re ext-setup-or-nil start)
3180 (setq start (match-end 0)))
3181 (and (setq ext-setup-or-nil nil start 0)
3182 (re-search-forward re nil t)))
3183 (setq key (upcase (match-string 1 ext-setup-or-nil))
3184 value (org-match-string-no-properties 2 ext-setup-or-nil))
3185 (cond
3186 ((equal key "CATEGORY")
3187 (if (string-match "[ \t]+$" value)
3188 (setq value (replace-match "" t t value)))
3189 (setq cat value))
3190 ((member key '("SEQ_TODO" "TODO"))
3191 (push (cons 'sequence (org-split-string value splitre)) kwds))
3192 ((equal key "TYP_TODO")
3193 (push (cons 'type (org-split-string value splitre)) kwds))
3194 ((equal key "TAGS")
3195 (setq tags (append tags (org-split-string value splitre))))
3196 ((equal key "COLUMNS")
3197 (org-set-local 'org-columns-default-format value))
3198 ((equal key "LINK")
3199 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3200 (push (cons (match-string 1 value)
3201 (org-trim (match-string 2 value)))
3202 links)))
3203 ((equal key "PRIORITIES")
3204 (setq prio (org-split-string value " +")))
3205 ((equal key "PROPERTY")
3206 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3207 (push (cons (match-string 1 value) (match-string 2 value))
3208 props)))
3209 ((equal key "FILETAGS")
3210 (when (string-match "\\S-" value)
3211 (setq ftags
3212 (append
3213 ftags
3214 (apply 'append
3215 (mapcar (lambda (x) (org-split-string x ":"))
3216 (org-split-string value)))))))
3217 ((equal key "DRAWERS")
3218 (setq drawers (org-split-string value splitre)))
3219 ((equal key "CONSTANTS")
3220 (setq const (append const (org-split-string value splitre))))
3221 ((equal key "STARTUP")
3222 (let ((opts (org-split-string value splitre))
3223 l var val)
3224 (while (setq l (pop opts))
3225 (when (setq l (assoc l org-startup-options))
3226 (setq var (nth 1 l) val (nth 2 l))
3227 (if (not (nth 3 l))
3228 (set (make-local-variable var) val)
3229 (if (not (listp (symbol-value var)))
3230 (set (make-local-variable var) nil))
3231 (set (make-local-variable var) (symbol-value var))
3232 (add-to-list var val))))))
3233 ((equal key "ARCHIVE")
3234 (string-match " *$" value)
3235 (setq arch (replace-match "" t t value))
3236 (remove-text-properties 0 (length arch)
3237 '(face t fontified t) arch))
3238 ((equal key "SETUPFILE")
3239 (setq setup-contents (org-file-contents
3240 (expand-file-name
3241 (org-remove-double-quotes value))
3242 'noerror))
3243 (if (not ext-setup-or-nil)
3244 (setq ext-setup-or-nil setup-contents start 0)
3245 (setq ext-setup-or-nil
3246 (concat (substring ext-setup-or-nil 0 start)
3247 "\n" setup-contents "\n"
3248 (substring ext-setup-or-nil start)))))
3249 ))))
3250 (when cat
3251 (org-set-local 'org-category (intern cat))
3252 (push (cons "CATEGORY" cat) props))
3253 (when prio
3254 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3255 (setq prio (mapcar 'string-to-char prio))
3256 (org-set-local 'org-highest-priority (nth 0 prio))
3257 (org-set-local 'org-lowest-priority (nth 1 prio))
3258 (org-set-local 'org-default-priority (nth 2 prio)))
3259 (and props (org-set-local 'org-file-properties (nreverse props)))
3260 (and ftags (org-set-local 'org-file-tags ftags))
3261 (and drawers (org-set-local 'org-drawers drawers))
3262 (and arch (org-set-local 'org-archive-location arch))
3263 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3264 ;; Process the TODO keywords
3265 (unless kwds
3266 ;; Use the global values as if they had been given locally.
3267 (setq kwds (default-value 'org-todo-keywords))
3268 (if (stringp (car kwds))
3269 (setq kwds (list (cons org-todo-interpretation
3270 (default-value 'org-todo-keywords)))))
3271 (setq kwds (reverse kwds)))
3272 (setq kwds (nreverse kwds))
3273 (let (inter kws kw)
3274 (while (setq kws (pop kwds))
3275 (setq inter (pop kws) sep (member "|" kws)
3276 kws0 (delete "|" (copy-sequence kws))
3277 kwsa nil
3278 kws1 (mapcar
3279 (lambda (x)
3280 ;; 1 2
3281 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3282 (progn
3283 (setq kw (match-string 1 x)
3284 key (and (match-end 2) (match-string 2 x))
3285 log (org-extract-log-state-settings x))
3286 (push (cons kw (and key (string-to-char key))) kwsa)
3287 (and log (push log org-todo-log-states))
3289 (error "Invalid TODO keyword %s" x)))
3290 kws0)
3291 kwsa (if kwsa (append '((:startgroup))
3292 (nreverse kwsa)
3293 '((:endgroup))))
3294 hw (car kws1)
3295 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3296 tail (list inter hw (car dws) (org-last dws)))
3297 (add-to-list 'org-todo-heads hw 'append)
3298 (push kws1 org-todo-sets)
3299 (setq org-done-keywords (append org-done-keywords dws nil))
3300 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3301 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3302 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3303 (setq org-todo-sets (nreverse org-todo-sets)
3304 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3305 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3306 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3307 ;; Process the constants
3308 (when const
3309 (let (e cst)
3310 (while (setq e (pop const))
3311 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3312 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3313 (setq org-table-formula-constants-local cst)))
3315 ;; Process the tags.
3316 (when tags
3317 (let (e tgs)
3318 (while (setq e (pop tags))
3319 (cond
3320 ((equal e "{") (push '(:startgroup) tgs))
3321 ((equal e "}") (push '(:endgroup) tgs))
3322 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3323 (push (cons (match-string 1 e)
3324 (string-to-char (match-string 2 e)))
3325 tgs))
3326 (t (push (list e) tgs))))
3327 (org-set-local 'org-tag-alist nil)
3328 (while (setq e (pop tgs))
3329 (or (and (stringp (car e))
3330 (assoc (car e) org-tag-alist))
3331 (push e org-tag-alist)))))
3333 ;; Compute the regular expressions and other local variables
3334 (if (not org-done-keywords)
3335 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3336 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3337 (length org-scheduled-string)
3338 (length org-clock-string)
3339 (length org-closed-string)))
3340 org-drawer-regexp
3341 (concat "^[ \t]*:\\("
3342 (mapconcat 'regexp-quote org-drawers "\\|")
3343 "\\):[ \t]*$")
3344 org-not-done-keywords
3345 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3346 org-todo-regexp
3347 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3348 "\\|") "\\)\\>")
3349 org-not-done-regexp
3350 (concat "\\<\\("
3351 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3352 "\\)\\>")
3353 org-todo-line-regexp
3354 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3355 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3356 "\\)\\>\\)?[ \t]*\\(.*\\)")
3357 org-complex-heading-regexp
3358 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3359 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3360 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3361 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3362 org-nl-done-regexp
3363 (concat "\n\\*+[ \t]+"
3364 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3365 "\\)" "\\>")
3366 org-todo-line-tags-regexp
3367 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3368 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3369 (org-re
3370 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3371 org-looking-at-done-regexp
3372 (concat "^" "\\(?:"
3373 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3374 "\\>")
3375 org-deadline-regexp (concat "\\<" org-deadline-string)
3376 org-deadline-time-regexp
3377 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3378 org-deadline-line-regexp
3379 (concat "\\<\\(" org-deadline-string "\\).*")
3380 org-scheduled-regexp
3381 (concat "\\<" org-scheduled-string)
3382 org-scheduled-time-regexp
3383 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3384 org-closed-time-regexp
3385 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3386 org-keyword-time-regexp
3387 (concat "\\<\\(" org-scheduled-string
3388 "\\|" org-deadline-string
3389 "\\|" org-closed-string
3390 "\\|" org-clock-string "\\)"
3391 " *[[<]\\([^]>]+\\)[]>]")
3392 org-keyword-time-not-clock-regexp
3393 (concat "\\<\\(" org-scheduled-string
3394 "\\|" org-deadline-string
3395 "\\|" org-closed-string
3396 "\\)"
3397 " *[[<]\\([^]>]+\\)[]>]")
3398 org-maybe-keyword-time-regexp
3399 (concat "\\(\\<\\(" org-scheduled-string
3400 "\\|" org-deadline-string
3401 "\\|" org-closed-string
3402 "\\|" org-clock-string "\\)\\)?"
3403 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3404 org-planning-or-clock-line-re
3405 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3406 "\\|" org-deadline-string
3407 "\\|" org-closed-string "\\|" org-clock-string
3408 "\\)\\>\\)")
3410 (org-compute-latex-and-specials-regexp)
3411 (org-set-font-lock-defaults))))
3413 (defun org-file-contents (file &optional noerror)
3414 "Return the contents of FILE, as a string."
3415 (if (or (not file)
3416 (not (file-readable-p file)))
3417 (if noerror
3418 (progn
3419 (message "Cannot read file %s" file)
3420 (ding) (sit-for 2)
3422 (error "Cannot read file %s" file))
3423 (with-temp-buffer
3424 (insert-file-contents file)
3425 (buffer-string))))
3427 (defun org-extract-log-state-settings (x)
3428 "Extract the log state setting from a TODO keyword string.
3429 This will extract info from a string like \"WAIT(w@/!)\"."
3430 (let (kw key log1 log2)
3431 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3432 (setq kw (match-string 1 x)
3433 key (and (match-end 2) (match-string 2 x))
3434 log1 (and (match-end 3) (match-string 3 x))
3435 log2 (and (match-end 4) (match-string 4 x)))
3436 (and (or log1 log2)
3437 (list kw
3438 (and log1 (if (equal log1 "!") 'time 'note))
3439 (and log2 (if (equal log2 "!") 'time 'note)))))))
3441 (defun org-remove-keyword-keys (list)
3442 "Remove a pair of parenthesis at the end of each string in LIST."
3443 (mapcar (lambda (x)
3444 (if (string-match "(.*)$" x)
3445 (substring x 0 (match-beginning 0))
3447 list))
3449 ;; FIXME: this could be done much better, using second characters etc.
3450 (defun org-assign-fast-keys (alist)
3451 "Assign fast keys to a keyword-key alist.
3452 Respect keys that are already there."
3453 (let (new e k c c1 c2 (char ?a))
3454 (while (setq e (pop alist))
3455 (cond
3456 ((equal e '(:startgroup)) (push e new))
3457 ((equal e '(:endgroup)) (push e new))
3459 (setq k (car e) c2 nil)
3460 (if (cdr e)
3461 (setq c (cdr e))
3462 ;; automatically assign a character.
3463 (setq c1 (string-to-char
3464 (downcase (substring
3465 k (if (= (string-to-char k) ?@) 1 0)))))
3466 (if (or (rassoc c1 new) (rassoc c1 alist))
3467 (while (or (rassoc char new) (rassoc char alist))
3468 (setq char (1+ char)))
3469 (setq c2 c1))
3470 (setq c (or c2 char)))
3471 (push (cons k c) new))))
3472 (nreverse new)))
3474 ;;; Some variables used in various places
3476 (defvar org-window-configuration nil
3477 "Used in various places to store a window configuration.")
3478 (defvar org-finish-function nil
3479 "Function to be called when `C-c C-c' is used.
3480 This is for getting out of special buffers like remember.")
3483 ;; FIXME: Occasionally check by commenting these, to make sure
3484 ;; no other functions uses these, forgetting to let-bind them.
3485 (defvar entry)
3486 (defvar state)
3487 (defvar last-state)
3488 (defvar date)
3489 (defvar description)
3491 ;; Defined somewhere in this file, but used before definition.
3492 (defvar org-html-entities)
3493 (defvar org-struct-menu)
3494 (defvar org-org-menu)
3495 (defvar org-tbl-menu)
3496 (defvar org-agenda-keymap)
3498 ;;;; Define the Org-mode
3500 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3501 (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."))
3504 ;; We use a before-change function to check if a table might need
3505 ;; an update.
3506 (defvar org-table-may-need-update t
3507 "Indicates that a table might need an update.
3508 This variable is set by `org-before-change-function'.
3509 `org-table-align' sets it back to nil.")
3510 (defun org-before-change-function (beg end)
3511 "Every change indicates that a table might need an update."
3512 (setq org-table-may-need-update t))
3513 (defvar org-mode-map)
3514 (defvar org-mode-hook nil
3515 "Mode hook for Org-mode, run after the mode was turned on.")
3516 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3517 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3518 (defvar org-table-buffer-is-an nil)
3519 (defconst org-outline-regexp "\\*+ ")
3521 ;;;###autoload
3522 (define-derived-mode org-mode outline-mode "Org"
3523 "Outline-based notes management and organizer, alias
3524 \"Carsten's outline-mode for keeping track of everything.\"
3526 Org-mode develops organizational tasks around a NOTES file which
3527 contains information about projects as plain text. Org-mode is
3528 implemented on top of outline-mode, which is ideal to keep the content
3529 of large files well structured. It supports ToDo items, deadlines and
3530 time stamps, which magically appear in the diary listing of the Emacs
3531 calendar. Tables are easily created with a built-in table editor.
3532 Plain text URL-like links connect to websites, emails (VM), Usenet
3533 messages (Gnus), BBDB entries, and any files related to the project.
3534 For printing and sharing of notes, an Org-mode file (or a part of it)
3535 can be exported as a structured ASCII or HTML file.
3537 The following commands are available:
3539 \\{org-mode-map}"
3541 ;; Get rid of Outline menus, they are not needed
3542 ;; Need to do this here because define-derived-mode sets up
3543 ;; the keymap so late. Still, it is a waste to call this each time
3544 ;; we switch another buffer into org-mode.
3545 (if (featurep 'xemacs)
3546 (when (boundp 'outline-mode-menu-heading)
3547 ;; Assume this is Greg's port, it used easymenu
3548 (easy-menu-remove outline-mode-menu-heading)
3549 (easy-menu-remove outline-mode-menu-show)
3550 (easy-menu-remove outline-mode-menu-hide))
3551 (define-key org-mode-map [menu-bar headings] 'undefined)
3552 (define-key org-mode-map [menu-bar hide] 'undefined)
3553 (define-key org-mode-map [menu-bar show] 'undefined))
3555 (org-load-modules-maybe)
3556 (easy-menu-add org-org-menu)
3557 (easy-menu-add org-tbl-menu)
3558 (org-install-agenda-files-menu)
3559 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3560 (org-add-to-invisibility-spec '(org-cwidth))
3561 (when (featurep 'xemacs)
3562 (org-set-local 'line-move-ignore-invisible t))
3563 (org-set-local 'outline-regexp org-outline-regexp)
3564 (org-set-local 'outline-level 'org-outline-level)
3565 (when (and org-ellipsis
3566 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3567 (fboundp 'make-glyph-code))
3568 (unless org-display-table
3569 (setq org-display-table (make-display-table)))
3570 (set-display-table-slot
3571 org-display-table 4
3572 (vconcat (mapcar
3573 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3574 org-ellipsis)))
3575 (if (stringp org-ellipsis) org-ellipsis "..."))))
3576 (setq buffer-display-table org-display-table))
3577 (org-set-regexps-and-options)
3578 (when (and org-tag-faces (not org-tags-special-faces-re))
3579 ;; tag faces set outside customize.... force initialization.
3580 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3581 ;; Calc embedded
3582 (org-set-local 'calc-embedded-open-mode "# ")
3583 (modify-syntax-entry ?# "<")
3584 (modify-syntax-entry ?@ "w")
3585 (if org-startup-truncated (setq truncate-lines t))
3586 (org-set-local 'font-lock-unfontify-region-function
3587 'org-unfontify-region)
3588 ;; Activate before-change-function
3589 (org-set-local 'org-table-may-need-update t)
3590 (org-add-hook 'before-change-functions 'org-before-change-function nil
3591 'local)
3592 ;; Check for running clock before killing a buffer
3593 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3594 ;; Paragraphs and auto-filling
3595 (org-set-autofill-regexps)
3596 (setq indent-line-function 'org-indent-line-function)
3597 (org-update-radio-target-regexp)
3599 ;; Comment characters
3600 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3601 (org-set-local 'comment-padding " ")
3603 ;; Align options lines
3604 (org-set-local
3605 'align-mode-rules-list
3606 '((org-in-buffer-settings
3607 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3608 (modes . '(org-mode)))))
3610 ;; Imenu
3611 (org-set-local 'imenu-create-index-function
3612 'org-imenu-get-tree)
3614 ;; Make isearch reveal context
3615 (if (or (featurep 'xemacs)
3616 (not (boundp 'outline-isearch-open-invisible-function)))
3617 ;; Emacs 21 and XEmacs make use of the hook
3618 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3619 ;; Emacs 22 deals with this through a special variable
3620 (org-set-local 'outline-isearch-open-invisible-function
3621 (lambda (&rest ignore) (org-show-context 'isearch))))
3623 ;; If empty file that did not turn on org-mode automatically, make it to.
3624 (if (and org-insert-mode-line-in-empty-file
3625 (interactive-p)
3626 (= (point-min) (point-max)))
3627 (insert "# -*- mode: org -*-\n\n"))
3629 (unless org-inhibit-startup
3630 (when org-startup-align-all-tables
3631 (let ((bmp (buffer-modified-p)))
3632 (org-table-map-tables 'org-table-align)
3633 (set-buffer-modified-p bmp)))
3634 (org-set-startup-visibility)))
3636 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3638 (defun org-current-time ()
3639 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3640 (if (> (car org-time-stamp-rounding-minutes) 1)
3641 (let ((r (car org-time-stamp-rounding-minutes))
3642 (time (decode-time)))
3643 (apply 'encode-time
3644 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3645 (nthcdr 2 time))))
3646 (current-time)))
3648 ;;;; Font-Lock stuff, including the activators
3650 (defvar org-mouse-map (make-sparse-keymap))
3651 (org-defkey org-mouse-map
3652 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3653 (org-defkey org-mouse-map
3654 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3655 (when org-mouse-1-follows-link
3656 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3657 (when org-tab-follows-link
3658 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3659 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3660 (when org-return-follows-link
3661 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3662 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3664 (require 'font-lock)
3666 (defconst org-non-link-chars "]\t\n\r<>")
3667 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3668 "shell" "elisp"))
3669 (defvar org-link-types-re nil
3670 "Matches a link that has a url-like prefix like \"http:\"")
3671 (defvar org-link-re-with-space nil
3672 "Matches a link with spaces, optional angular brackets around it.")
3673 (defvar org-link-re-with-space2 nil
3674 "Matches a link with spaces, optional angular brackets around it.")
3675 (defvar org-link-re-with-space3 nil
3676 "Matches a link with spaces, only for internal part in bracket links.")
3677 (defvar org-angle-link-re nil
3678 "Matches link with angular brackets, spaces are allowed.")
3679 (defvar org-plain-link-re nil
3680 "Matches plain link, without spaces.")
3681 (defvar org-bracket-link-regexp nil
3682 "Matches a link in double brackets.")
3683 (defvar org-bracket-link-analytic-regexp nil
3684 "Regular expression used to analyze links.
3685 Here is what the match groups contain after a match:
3686 1: http:
3687 2: http
3688 3: path
3689 4: [desc]
3690 5: desc")
3691 (defvar org-bracket-link-analytic-regexp++ nil
3692 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3693 (defvar org-any-link-re nil
3694 "Regular expression matching any link.")
3696 (defun org-make-link-regexps ()
3697 "Update the link regular expressions.
3698 This should be called after the variable `org-link-types' has changed."
3699 (setq org-link-types-re
3700 (concat
3701 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3702 org-link-re-with-space
3703 (concat
3704 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3705 "\\([^" org-non-link-chars " ]"
3706 "[^" org-non-link-chars "]*"
3707 "[^" org-non-link-chars " ]\\)>?")
3708 org-link-re-with-space2
3709 (concat
3710 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3711 "\\([^" org-non-link-chars " ]"
3712 "[^\t\n\r]*"
3713 "[^" org-non-link-chars " ]\\)>?")
3714 org-link-re-with-space3
3715 (concat
3716 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3717 "\\([^" org-non-link-chars " ]"
3718 "[^\t\n\r]*\\)")
3719 org-angle-link-re
3720 (concat
3721 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3722 "\\([^" org-non-link-chars " ]"
3723 "[^" org-non-link-chars "]*"
3724 "\\)>")
3725 org-plain-link-re
3726 (concat
3727 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3728 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3729 org-bracket-link-regexp
3730 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3731 org-bracket-link-analytic-regexp
3732 (concat
3733 "\\[\\["
3734 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3735 "\\([^]]+\\)"
3736 "\\]"
3737 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3738 "\\]")
3739 org-bracket-link-analytic-regexp++
3740 (concat
3741 "\\[\\["
3742 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3743 "\\([^]]+\\)"
3744 "\\]"
3745 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3746 "\\]")
3747 org-any-link-re
3748 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3749 org-angle-link-re "\\)\\|\\("
3750 org-plain-link-re "\\)")))
3752 (org-make-link-regexps)
3754 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3755 "Regular expression for fast time stamp matching.")
3756 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3757 "Regular expression for fast time stamp matching.")
3758 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3759 "Regular expression matching time strings for analysis.
3760 This one does not require the space after the date, so it can be used
3761 on a string that terminates immediately after the date.")
3762 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3763 "Regular expression matching time strings for analysis.")
3764 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3765 "Regular expression matching time stamps, with groups.")
3766 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3767 "Regular expression matching time stamps (also [..]), with groups.")
3768 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3769 "Regular expression matching a time stamp range.")
3770 (defconst org-tr-regexp-both
3771 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3772 "Regular expression matching a time stamp range.")
3773 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3774 org-ts-regexp "\\)?")
3775 "Regular expression matching a time stamp or time stamp range.")
3776 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3777 org-ts-regexp-both "\\)?")
3778 "Regular expression matching a time stamp or time stamp range.
3779 The time stamps may be either active or inactive.")
3781 (defvar org-emph-face nil)
3783 (defun org-do-emphasis-faces (limit)
3784 "Run through the buffer and add overlays to links."
3785 (let (rtn)
3786 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3787 (if (not (= (char-after (match-beginning 3))
3788 (char-after (match-beginning 4))))
3789 (progn
3790 (setq rtn t)
3791 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3792 'face
3793 (nth 1 (assoc (match-string 3)
3794 org-emphasis-alist)))
3795 (add-text-properties (match-beginning 2) (match-end 2)
3796 '(font-lock-multiline t))
3797 (when org-hide-emphasis-markers
3798 (add-text-properties (match-end 4) (match-beginning 5)
3799 '(invisible org-link))
3800 (add-text-properties (match-beginning 3) (match-end 3)
3801 '(invisible org-link)))))
3802 (backward-char 1))
3803 rtn))
3805 (defun org-emphasize (&optional char)
3806 "Insert or change an emphasis, i.e. a font like bold or italic.
3807 If there is an active region, change that region to a new emphasis.
3808 If there is no region, just insert the marker characters and position
3809 the cursor between them.
3810 CHAR should be either the marker character, or the first character of the
3811 HTML tag associated with that emphasis. If CHAR is a space, the means
3812 to remove the emphasis of the selected region.
3813 If char is not given (for example in an interactive call) it
3814 will be prompted for."
3815 (interactive)
3816 (let ((eal org-emphasis-alist) e det
3817 (erc org-emphasis-regexp-components)
3818 (prompt "")
3819 (string "") beg end move tag c s)
3820 (if (org-region-active-p)
3821 (setq beg (region-beginning) end (region-end)
3822 string (buffer-substring beg end))
3823 (setq move t))
3825 (while (setq e (pop eal))
3826 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3827 c (aref tag 0))
3828 (push (cons c (string-to-char (car e))) det)
3829 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3830 (substring tag 1)))))
3831 (setq det (nreverse det))
3832 (unless char
3833 (message "%s" (concat "Emphasis marker or tag:" prompt))
3834 (setq char (read-char-exclusive)))
3835 (setq char (or (cdr (assoc char det)) char))
3836 (if (equal char ?\ )
3837 (setq s "" move nil)
3838 (unless (assoc (char-to-string char) org-emphasis-alist)
3839 (error "No such emphasis marker: \"%c\"" char))
3840 (setq s (char-to-string char)))
3841 (while (and (> (length string) 1)
3842 (equal (substring string 0 1) (substring string -1))
3843 (assoc (substring string 0 1) org-emphasis-alist))
3844 (setq string (substring string 1 -1)))
3845 (setq string (concat s string s))
3846 (if beg (delete-region beg end))
3847 (unless (or (bolp)
3848 (string-match (concat "[" (nth 0 erc) "\n]")
3849 (char-to-string (char-before (point)))))
3850 (insert " "))
3851 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3852 (char-to-string (char-after (point))))
3853 (insert " ") (backward-char 1))
3854 (insert string)
3855 (and move (backward-char 1))))
3857 (defconst org-nonsticky-props
3858 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3861 (defun org-activate-plain-links (limit)
3862 "Run through the buffer and add overlays to links."
3863 (catch 'exit
3864 (let (f)
3865 (while (re-search-forward org-plain-link-re limit t)
3866 (setq f (get-text-property (match-beginning 0) 'face))
3867 (if (or (eq f 'org-tag)
3868 (and (listp f) (memq 'org-tag f)))
3870 (add-text-properties (match-beginning 0) (match-end 0)
3871 (list 'mouse-face 'highlight
3872 'rear-nonsticky org-nonsticky-props
3873 'keymap org-mouse-map
3875 (throw 'exit t))))))
3877 (defun org-activate-code (limit)
3878 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3879 (progn
3880 (remove-text-properties (match-beginning 0) (match-end 0)
3881 '(display t invisible t intangible t))
3882 t)))
3884 (defun org-activate-angle-links (limit)
3885 "Run through the buffer and add overlays to links."
3886 (if (re-search-forward org-angle-link-re limit t)
3887 (progn
3888 (add-text-properties (match-beginning 0) (match-end 0)
3889 (list 'mouse-face 'highlight
3890 'rear-nonsticky org-nonsticky-props
3891 'keymap org-mouse-map
3893 t)))
3895 (defun org-activate-footnote-links (limit)
3896 "Run through the buffer and add overlays to links."
3897 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3898 limit t)
3899 (progn
3900 (add-text-properties (match-beginning 2) (match-end 2)
3901 (list 'mouse-face 'highlight
3902 'rear-nonsticky org-nonsticky-props
3903 'keymap org-mouse-map
3904 'help-echo
3905 (if (= (point-at-bol) (match-beginning 2))
3906 "Footnote definition"
3907 "Footnote reference")
3909 t)))
3911 (defun org-activate-bracket-links (limit)
3912 "Run through the buffer and add overlays to bracketed links."
3913 (if (re-search-forward org-bracket-link-regexp limit t)
3914 (let* ((help (concat "LINK: "
3915 (org-match-string-no-properties 1)))
3916 ;; FIXME: above we should remove the escapes.
3917 ;; but that requires another match, protecting match data,
3918 ;; a lot of overhead for font-lock.
3919 (ip (org-maybe-intangible
3920 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3921 'keymap org-mouse-map 'mouse-face 'highlight
3922 'font-lock-multiline t 'help-echo help)))
3923 (vp (list 'rear-nonsticky org-nonsticky-props
3924 'keymap org-mouse-map 'mouse-face 'highlight
3925 ' font-lock-multiline t 'help-echo help)))
3926 ;; We need to remove the invisible property here. Table narrowing
3927 ;; may have made some of this invisible.
3928 (remove-text-properties (match-beginning 0) (match-end 0)
3929 '(invisible nil))
3930 (if (match-end 3)
3931 (progn
3932 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3933 (add-text-properties (match-beginning 3) (match-end 3) vp)
3934 (add-text-properties (match-end 3) (match-end 0) ip))
3935 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3936 (add-text-properties (match-beginning 1) (match-end 1) vp)
3937 (add-text-properties (match-end 1) (match-end 0) ip))
3938 t)))
3940 (defun org-activate-dates (limit)
3941 "Run through the buffer and add overlays to dates."
3942 (if (re-search-forward org-tsr-regexp-both limit t)
3943 (progn
3944 (add-text-properties (match-beginning 0) (match-end 0)
3945 (list 'mouse-face 'highlight
3946 'rear-nonsticky org-nonsticky-props
3947 'keymap org-mouse-map))
3948 (when org-display-custom-times
3949 (if (match-end 3)
3950 (org-display-custom-time (match-beginning 3) (match-end 3)))
3951 (org-display-custom-time (match-beginning 1) (match-end 1)))
3952 t)))
3954 (defvar org-target-link-regexp nil
3955 "Regular expression matching radio targets in plain text.")
3956 (make-variable-buffer-local 'org-target-link-regexp)
3957 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3958 "Regular expression matching a link target.")
3959 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3960 "Regular expression matching a radio target.")
3961 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3962 "Regular expression matching any target.")
3964 (defun org-activate-target-links (limit)
3965 "Run through the buffer and add overlays to target matches."
3966 (when org-target-link-regexp
3967 (let ((case-fold-search t))
3968 (if (re-search-forward org-target-link-regexp limit t)
3969 (progn
3970 (add-text-properties (match-beginning 0) (match-end 0)
3971 (list 'mouse-face 'highlight
3972 'rear-nonsticky org-nonsticky-props
3973 'keymap org-mouse-map
3974 'help-echo "Radio target link"
3975 'org-linked-text t))
3976 t)))))
3978 (defun org-update-radio-target-regexp ()
3979 "Find all radio targets in this file and update the regular expression."
3980 (interactive)
3981 (when (memq 'radio org-activate-links)
3982 (setq org-target-link-regexp
3983 (org-make-target-link-regexp (org-all-targets 'radio)))
3984 (org-restart-font-lock)))
3986 (defun org-hide-wide-columns (limit)
3987 (let (s e)
3988 (setq s (text-property-any (point) (or limit (point-max))
3989 'org-cwidth t))
3990 (when s
3991 (setq e (next-single-property-change s 'org-cwidth))
3992 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3993 (goto-char e)
3994 t)))
3996 (defvar org-latex-and-specials-regexp nil
3997 "Regular expression for highlighting export special stuff.")
3998 (defvar org-match-substring-regexp)
3999 (defvar org-match-substring-with-braces-regexp)
4000 (defvar org-export-html-special-string-regexps)
4002 (defun org-compute-latex-and-specials-regexp ()
4003 "Compute regular expression for stuff treated specially by exporters."
4004 (if (not org-highlight-latex-fragments-and-specials)
4005 (org-set-local 'org-latex-and-specials-regexp nil)
4006 (require 'org-exp)
4007 (let*
4008 ((matchers (plist-get org-format-latex-options :matchers))
4009 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4010 org-latex-regexps)))
4011 (options (org-combine-plists (org-default-export-plist)
4012 (org-infile-export-plist)))
4013 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4014 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4015 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4016 (org-export-html-expand (plist-get options :expand-quoted-html))
4017 (org-export-with-special-strings (plist-get options :special-strings))
4018 (re-sub
4019 (cond
4020 ((equal org-export-with-sub-superscripts '{})
4021 (list org-match-substring-with-braces-regexp))
4022 (org-export-with-sub-superscripts
4023 (list org-match-substring-regexp))
4024 (t nil)))
4025 (re-latex
4026 (if org-export-with-LaTeX-fragments
4027 (mapcar (lambda (x) (nth 1 x)) latexs)))
4028 (re-macros
4029 (if org-export-with-TeX-macros
4030 (list (concat "\\\\"
4031 (regexp-opt
4032 (append (mapcar 'car org-html-entities)
4033 (if (boundp 'org-latex-entities)
4034 org-latex-entities nil))
4035 'words))) ; FIXME
4037 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4038 (re-special (if org-export-with-special-strings
4039 (mapcar (lambda (x) (car x))
4040 org-export-html-special-string-regexps)))
4041 (re-rest
4042 (delq nil
4043 (list
4044 (if org-export-html-expand "@<[^>\n]+>")
4045 ))))
4046 (org-set-local
4047 'org-latex-and-specials-regexp
4048 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4049 re-rest) "\\|")))))
4051 (defun org-do-latex-and-special-faces (limit)
4052 "Run through the buffer and add overlays to links."
4053 (when org-latex-and-specials-regexp
4054 (let (rtn d)
4055 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4056 limit t))
4057 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4058 'face))
4059 '(org-code org-verbatim underline)))
4060 (progn
4061 (setq rtn t
4062 d (cond ((member (char-after (1+ (match-beginning 0)))
4063 '(?_ ?^)) 1)
4064 (t 0)))
4065 (font-lock-prepend-text-property
4066 (+ d (match-beginning 0)) (match-end 0)
4067 'face 'org-latex-and-export-specials)
4068 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4069 '(font-lock-multiline t)))))
4070 rtn)))
4072 (defun org-restart-font-lock ()
4073 "Restart font-lock-mode, to force refontification."
4074 (when (and (boundp 'font-lock-mode) font-lock-mode)
4075 (font-lock-mode -1)
4076 (font-lock-mode 1)))
4078 (defun org-all-targets (&optional radio)
4079 "Return a list of all targets in this file.
4080 With optional argument RADIO, only find radio targets."
4081 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4082 rtn)
4083 (save-excursion
4084 (goto-char (point-min))
4085 (while (re-search-forward re nil t)
4086 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4087 rtn)))
4089 (defun org-make-target-link-regexp (targets)
4090 "Make regular expression matching all strings in TARGETS.
4091 The regular expression finds the targets also if there is a line break
4092 between words."
4093 (and targets
4094 (concat
4095 "\\<\\("
4096 (mapconcat
4097 (lambda (x)
4098 (while (string-match " +" x)
4099 (setq x (replace-match "\\s-+" t t x)))
4101 targets
4102 "\\|")
4103 "\\)\\>")))
4105 (defun org-activate-tags (limit)
4106 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4107 (progn
4108 (add-text-properties (match-beginning 1) (match-end 1)
4109 (list 'mouse-face 'highlight
4110 'rear-nonsticky org-nonsticky-props
4111 'keymap org-mouse-map))
4112 t)))
4114 (defun org-outline-level ()
4115 (save-excursion
4116 (looking-at outline-regexp)
4117 (if (match-beginning 1)
4118 (+ (org-get-string-indentation (match-string 1)) 1000)
4119 (1- (- (match-end 0) (match-beginning 0))))))
4121 (defvar org-font-lock-keywords nil)
4123 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4124 "Regular expression matching a property line.")
4126 (defvar org-font-lock-hook nil
4127 "Functions to be called for special font lock stuff.")
4129 (defun org-font-lock-hook (limit)
4130 (run-hook-with-args 'org-font-lock-hook limit))
4132 (defun org-set-font-lock-defaults ()
4133 (let* ((em org-fontify-emphasized-text)
4134 (lk org-activate-links)
4135 (org-font-lock-extra-keywords
4136 (list
4137 ;; Call the hook
4138 '(org-font-lock-hook)
4139 ;; Headlines
4140 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4141 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4142 ;; Table lines
4143 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4144 (1 'org-table t))
4145 ;; Table internals
4146 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4147 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4148 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4149 ;; Drawers
4150 (list org-drawer-regexp '(0 'org-special-keyword t))
4151 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4152 ;; Properties
4153 (list org-property-re
4154 '(1 'org-special-keyword t)
4155 '(3 'org-property-value t))
4156 (if org-format-transports-properties-p
4157 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4158 ;; Links
4159 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4160 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4161 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4162 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4163 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4164 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4165 (if (memq 'footnote lk) '(org-activate-footnote-links
4166 (2 'org-footnote t)))
4167 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4168 '(org-hide-wide-columns (0 nil append))
4169 ;; TODO lines
4170 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4171 '(1 (org-get-todo-face 1) t))
4172 ;; DONE
4173 (if org-fontify-done-headline
4174 (list (concat "^[*]+ +\\<\\("
4175 (mapconcat 'regexp-quote org-done-keywords "\\|")
4176 "\\)\\(.*\\)")
4177 '(2 'org-headline-done t))
4178 nil)
4179 ;; Priorities
4180 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4181 ;; Tags
4182 '(org-font-lock-add-tag-faces)
4183 ;; Special keywords
4184 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4185 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4186 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4187 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4188 ;; Emphasis
4189 (if em
4190 (if (featurep 'xemacs)
4191 '(org-do-emphasis-faces (0 nil append))
4192 '(org-do-emphasis-faces)))
4193 ;; Checkboxes
4194 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4195 2 'bold prepend)
4196 (if org-provide-checkbox-statistics
4197 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4198 (0 (org-get-checkbox-statistics-face) t)))
4199 ;; Description list items
4200 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4201 2 'bold prepend)
4202 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4203 '(1 'org-archived prepend))
4204 ;; Specials
4205 '(org-do-latex-and-special-faces)
4206 ;; Code
4207 '(org-activate-code (1 'org-code t))
4208 ;; COMMENT
4209 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4210 "\\|" org-quote-string "\\)\\>")
4211 '(1 'org-special-keyword t))
4212 '("^#.*" (0 'font-lock-comment-face t))
4214 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4215 ;; Now set the full font-lock-keywords
4216 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4217 (org-set-local 'font-lock-defaults
4218 '(org-font-lock-keywords t nil nil backward-paragraph))
4219 (kill-local-variable 'font-lock-keywords) nil))
4221 (defvar org-m nil)
4222 (defvar org-l nil)
4223 (defvar org-f nil)
4224 (defun org-get-level-face (n)
4225 "Get the right face for match N in font-lock matching of headlines."
4226 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4227 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4228 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4229 (cond
4230 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4231 ((eq n 2) org-f)
4232 (t (if org-level-color-stars-only nil org-f))))
4234 (defun org-get-todo-face (kwd)
4235 "Get the right face for a TODO keyword KWD.
4236 If KWD is a number, get the corresponding match group."
4237 (if (numberp kwd) (setq kwd (match-string kwd)))
4238 (or (cdr (assoc kwd org-todo-keyword-faces))
4239 (and (member kwd org-done-keywords) 'org-done)
4240 'org-todo))
4242 (defun org-font-lock-add-tag-faces (limit)
4243 "Add the special tag faces."
4244 (when (and org-tag-faces org-tags-special-faces-re)
4245 (while (re-search-forward org-tags-special-faces-re limit t)
4246 (add-text-properties (match-beginning 1) (match-end 1)
4247 (list 'face (org-get-tag-face 1)
4248 'font-lock-fontified t))
4249 (backward-char 1))))
4251 (defun org-get-tag-face (kwd)
4252 "Get the right face for a TODO keyword KWD.
4253 If KWD is a number, get the corresponding match group."
4254 (if (numberp kwd) (setq kwd (match-string kwd)))
4255 (or (cdr (assoc kwd org-tag-faces))
4256 'org-tag))
4258 (defun org-unfontify-region (beg end &optional maybe_loudly)
4259 "Remove fontification and activation overlays from links."
4260 (font-lock-default-unfontify-region beg end)
4261 (let* ((buffer-undo-list t)
4262 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4263 (inhibit-modification-hooks t)
4264 deactivate-mark buffer-file-name buffer-file-truename)
4265 (remove-text-properties beg end
4266 '(mouse-face t keymap t org-linked-text t
4267 invisible t intangible t))))
4269 ;;;; Visibility cycling, including org-goto and indirect buffer
4271 ;;; Cycling
4273 (defvar org-cycle-global-status nil)
4274 (make-variable-buffer-local 'org-cycle-global-status)
4275 (defvar org-cycle-subtree-status nil)
4276 (make-variable-buffer-local 'org-cycle-subtree-status)
4278 ;;;###autoload
4279 (defun org-cycle (&optional arg)
4280 "Visibility cycling for Org-mode.
4282 - When this function is called with a prefix argument, rotate the entire
4283 buffer through 3 states (global cycling)
4284 1. OVERVIEW: Show only top-level headlines.
4285 2. CONTENTS: Show all headlines of all levels, but no body text.
4286 3. SHOW ALL: Show everything.
4287 When called with two C-u C-u prefixes, switch to the startup visibility,
4288 determined by the variable `org-startup-folded', and by any VISIBILITY
4289 properties in the buffer.
4290 When called with three C-u C-u C-u prefixed, show the entire buffer,
4291 including drawers.
4293 - When point is at the beginning of a headline, rotate the subtree started
4294 by this line through 3 different states (local cycling)
4295 1. FOLDED: Only the main headline is shown.
4296 2. CHILDREN: The main headline and the direct children are shown.
4297 From this state, you can move to one of the children
4298 and zoom in further.
4299 3. SUBTREE: Show the entire subtree, including body text.
4301 - When there is a numeric prefix, go up to a heading with level ARG, do
4302 a `show-subtree' and return to the previous cursor position. If ARG
4303 is negative, go up that many levels.
4305 - When point is not at the beginning of a headline, execute the global
4306 binding for TAB, which is re-indenting the line. See the option
4307 `org-cycle-emulate-tab' for details.
4309 - Special case: if point is at the beginning of the buffer and there is
4310 no headline in line 1, this function will act as if called with prefix arg.
4311 But only if also the variable `org-cycle-global-at-bob' is t."
4312 (interactive "P")
4313 (org-load-modules-maybe)
4314 (let* ((outline-regexp
4315 (if (and (org-mode-p) org-cycle-include-plain-lists)
4316 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4317 outline-regexp))
4318 (bob-special (and org-cycle-global-at-bob (bobp)
4319 (not (looking-at outline-regexp))))
4320 (org-cycle-hook
4321 (if bob-special
4322 (delq 'org-optimize-window-after-visibility-change
4323 (copy-sequence org-cycle-hook))
4324 org-cycle-hook))
4325 (pos (point)))
4327 (if (or bob-special (equal arg '(4)))
4328 ;; special case: use global cycling
4329 (setq arg t))
4331 (cond
4333 ((equal arg '(16))
4334 (org-set-startup-visibility)
4335 (message "Startup visibility, plus VISIBILITY properties"))
4337 ((equal arg '(64))
4338 (show-all)
4339 (message "Entire buffer visible, including drawers"))
4341 ((org-at-table-p 'any)
4342 ;; Enter the table or move to the next field in the table
4343 (or (org-table-recognize-table.el)
4344 (progn
4345 (if arg (org-table-edit-field t)
4346 (org-table-justify-field-maybe)
4347 (call-interactively 'org-table-next-field)))))
4349 ((eq arg t) ;; Global cycling
4351 (cond
4352 ((and (eq last-command this-command)
4353 (eq org-cycle-global-status 'overview))
4354 ;; We just created the overview - now do table of contents
4355 ;; This can be slow in very large buffers, so indicate action
4356 (message "CONTENTS...")
4357 (org-content)
4358 (message "CONTENTS...done")
4359 (setq org-cycle-global-status 'contents)
4360 (run-hook-with-args 'org-cycle-hook 'contents))
4362 ((and (eq last-command this-command)
4363 (eq org-cycle-global-status 'contents))
4364 ;; We just showed the table of contents - now show everything
4365 (show-all)
4366 (message "SHOW ALL")
4367 (setq org-cycle-global-status 'all)
4368 (run-hook-with-args 'org-cycle-hook 'all))
4371 ;; Default action: go to overview
4372 (org-overview)
4373 (message "OVERVIEW")
4374 (setq org-cycle-global-status 'overview)
4375 (run-hook-with-args 'org-cycle-hook 'overview))))
4377 ((and org-drawers org-drawer-regexp
4378 (save-excursion
4379 (beginning-of-line 1)
4380 (looking-at org-drawer-regexp)))
4381 ;; Toggle block visibility
4382 (org-flag-drawer
4383 (not (get-char-property (match-end 0) 'invisible))))
4385 ((integerp arg)
4386 ;; Show-subtree, ARG levels up from here.
4387 (save-excursion
4388 (org-back-to-heading)
4389 (outline-up-heading (if (< arg 0) (- arg)
4390 (- (funcall outline-level) arg)))
4391 (org-show-subtree)))
4393 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4394 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4395 ;; At a heading: rotate between three different views
4396 (org-back-to-heading)
4397 (let ((goal-column 0) eoh eol eos)
4398 ;; First, some boundaries
4399 (save-excursion
4400 (org-back-to-heading)
4401 (save-excursion
4402 (beginning-of-line 2)
4403 (while (and (not (eobp)) ;; this is like `next-line'
4404 (get-char-property (1- (point)) 'invisible))
4405 (beginning-of-line 2)) (setq eol (point)))
4406 (outline-end-of-heading) (setq eoh (point))
4407 (org-end-of-subtree t)
4408 (unless (eobp)
4409 (skip-chars-forward " \t\n")
4410 (beginning-of-line 1) ; in case this is an item
4412 (setq eos (1- (point))))
4413 ;; Find out what to do next and set `this-command'
4414 (cond
4415 ((= eos eoh)
4416 ;; Nothing is hidden behind this heading
4417 (message "EMPTY ENTRY")
4418 (setq org-cycle-subtree-status nil)
4419 (save-excursion
4420 (goto-char eos)
4421 (outline-next-heading)
4422 (if (org-invisible-p) (org-flag-heading nil))))
4423 ((or (>= eol eos)
4424 (not (string-match "\\S-" (buffer-substring eol eos))))
4425 ;; Entire subtree is hidden in one line: open it
4426 (org-show-entry)
4427 (show-children)
4428 (message "CHILDREN")
4429 (save-excursion
4430 (goto-char eos)
4431 (outline-next-heading)
4432 (if (org-invisible-p) (org-flag-heading nil)))
4433 (setq org-cycle-subtree-status 'children)
4434 (run-hook-with-args 'org-cycle-hook 'children))
4435 ((and (eq last-command this-command)
4436 (eq org-cycle-subtree-status 'children))
4437 ;; We just showed the children, now show everything.
4438 (org-show-subtree)
4439 (message "SUBTREE")
4440 (setq org-cycle-subtree-status 'subtree)
4441 (run-hook-with-args 'org-cycle-hook 'subtree))
4443 ;; Default action: hide the subtree.
4444 (hide-subtree)
4445 (message "FOLDED")
4446 (setq org-cycle-subtree-status 'folded)
4447 (run-hook-with-args 'org-cycle-hook 'folded)))))
4449 ;; TAB emulation and template completion
4450 (buffer-read-only (org-back-to-heading))
4452 ((org-try-structure-completion))
4454 ((org-try-cdlatex-tab))
4456 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4457 (or (not (bolp))
4458 (not (looking-at outline-regexp))))
4459 (call-interactively (global-key-binding "\t")))
4461 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4462 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4463 (or (and (eq org-cycle-emulate-tab 'white)
4464 (= (match-end 0) (point-at-eol)))
4465 (and (eq org-cycle-emulate-tab 'whitestart)
4466 (>= (match-end 0) pos))))
4468 (eq org-cycle-emulate-tab t))
4469 (call-interactively (global-key-binding "\t")))
4471 (t (save-excursion
4472 (org-back-to-heading)
4473 (org-cycle))))))
4475 ;;;###autoload
4476 (defun org-global-cycle (&optional arg)
4477 "Cycle the global visibility. For details see `org-cycle'.
4478 With C-u prefix arg, switch to startup visibility.
4479 With a numeric prefix, show all headlines up to that level."
4480 (interactive "P")
4481 (let ((org-cycle-include-plain-lists
4482 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4483 (cond
4484 ((integerp arg)
4485 (show-all)
4486 (hide-sublevels arg)
4487 (setq org-cycle-global-status 'contents))
4488 ((equal arg '(4))
4489 (org-set-startup-visibility)
4490 (message "Startup visibility, plus VISIBILITY properties."))
4492 (org-cycle '(4))))))
4494 (defun org-set-startup-visibility ()
4495 "Set the visibility required by startup options and properties."
4496 (cond
4497 ((eq org-startup-folded t)
4498 (org-cycle '(4)))
4499 ((eq org-startup-folded 'content)
4500 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4501 (org-cycle '(4)) (org-cycle '(4)))))
4502 (org-set-visibility-according-to-property 'no-cleanup)
4503 (org-cycle-hide-archived-subtrees 'all)
4504 (org-cycle-hide-drawers 'all)
4505 (org-cycle-show-empty-lines 'all))
4507 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4508 "Switch subtree visibilities according to :VISIBILITY: property."
4509 (interactive)
4510 (let (org-show-entry-below state)
4511 (save-excursion
4512 (goto-char (point-min))
4513 (while (re-search-forward
4514 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4515 nil t)
4516 (setq state (match-string 1))
4517 (save-excursion
4518 (org-back-to-heading t)
4519 (hide-subtree)
4520 (org-reveal)
4521 (cond
4522 ((equal state '("fold" "folded"))
4523 (hide-subtree))
4524 ((equal state "children")
4525 (org-show-hidden-entry)
4526 (show-children))
4527 ((equal state "content")
4528 (save-excursion
4529 (save-restriction
4530 (org-narrow-to-subtree)
4531 (org-content))))
4532 ((member state '("all" "showall"))
4533 (show-subtree)))))
4534 (unless no-cleanup
4535 (org-cycle-hide-archived-subtrees 'all)
4536 (org-cycle-hide-drawers 'all)
4537 (org-cycle-show-empty-lines 'all)))))
4539 (defun org-overview ()
4540 "Switch to overview mode, showing only top-level headlines.
4541 Really, this shows all headlines with level equal or greater than the level
4542 of the first headline in the buffer. This is important, because if the
4543 first headline is not level one, then (hide-sublevels 1) gives confusing
4544 results."
4545 (interactive)
4546 (let ((level (save-excursion
4547 (goto-char (point-min))
4548 (if (re-search-forward (concat "^" outline-regexp) nil t)
4549 (progn
4550 (goto-char (match-beginning 0))
4551 (funcall outline-level))))))
4552 (and level (hide-sublevels level))))
4554 (defun org-content (&optional arg)
4555 "Show all headlines in the buffer, like a table of contents.
4556 With numerical argument N, show content up to level N."
4557 (interactive "P")
4558 (save-excursion
4559 ;; Visit all headings and show their offspring
4560 (and (integerp arg) (org-overview))
4561 (goto-char (point-max))
4562 (catch 'exit
4563 (while (and (progn (condition-case nil
4564 (outline-previous-visible-heading 1)
4565 (error (goto-char (point-min))))
4567 (looking-at outline-regexp))
4568 (if (integerp arg)
4569 (show-children (1- arg))
4570 (show-branches))
4571 (if (bobp) (throw 'exit nil))))))
4574 (defun org-optimize-window-after-visibility-change (state)
4575 "Adjust the window after a change in outline visibility.
4576 This function is the default value of the hook `org-cycle-hook'."
4577 (when (get-buffer-window (current-buffer))
4578 (cond
4579 ; ((eq state 'overview) (org-first-headline-recenter 1))
4580 ; ((eq state 'overview) (org-beginning-of-line))
4581 ((eq state 'content) nil)
4582 ((eq state 'all) nil)
4583 ((eq state 'folded) nil)
4584 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4585 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4587 (defun org-compact-display-after-subtree-move ()
4588 "Show a compacter version of the tree of the entry's parent."
4589 (save-excursion
4590 (if (org-up-heading-safe)
4591 (progn
4592 (hide-subtree)
4593 (show-entry)
4594 (show-children)
4595 (org-cycle-show-empty-lines 'children)
4596 (org-cycle-hide-drawers 'children))
4597 (org-overview))))
4599 (defun org-cycle-show-empty-lines (state)
4600 "Show empty lines above all visible headlines.
4601 The region to be covered depends on STATE when called through
4602 `org-cycle-hook'. Lisp program can use t for STATE to get the
4603 entire buffer covered. Note that an empty line is only shown if there
4604 are at least `org-cycle-separator-lines' empty lines before the headline."
4605 (when (> org-cycle-separator-lines 0)
4606 (save-excursion
4607 (let* ((n org-cycle-separator-lines)
4608 (re (cond
4609 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4610 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4611 (t (let ((ns (number-to-string (- n 2))))
4612 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4613 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4614 beg end)
4615 (cond
4616 ((memq state '(overview contents t))
4617 (setq beg (point-min) end (point-max)))
4618 ((memq state '(children folded))
4619 (setq beg (point) end (progn (org-end-of-subtree t t)
4620 (beginning-of-line 2)
4621 (point)))))
4622 (when beg
4623 (goto-char beg)
4624 (while (re-search-forward re end t)
4625 (if (not (get-char-property (match-end 1) 'invisible))
4626 (outline-flag-region
4627 (match-beginning 1) (match-end 1) nil)))))))
4628 ;; Never hide empty lines at the end of the file.
4629 (save-excursion
4630 (goto-char (point-max))
4631 (outline-previous-heading)
4632 (outline-end-of-heading)
4633 (if (and (looking-at "[ \t\n]+")
4634 (= (match-end 0) (point-max)))
4635 (outline-flag-region (point) (match-end 0) nil))))
4637 (defun org-show-empty-lines-in-parent ()
4638 "Move to the parent and re-show empty lines before visible headlines."
4639 (save-excursion
4640 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4641 (org-cycle-show-empty-lines context))))
4643 (defun org-cycle-hide-drawers (state)
4644 "Re-hide all drawers after a visibility state change."
4645 (when (and (org-mode-p)
4646 (not (memq state '(overview folded))))
4647 (save-excursion
4648 (let* ((globalp (memq state '(contents all)))
4649 (beg (if globalp (point-min) (point)))
4650 (end (if globalp (point-max) (org-end-of-subtree t))))
4651 (goto-char beg)
4652 (while (re-search-forward org-drawer-regexp end t)
4653 (org-flag-drawer t))))))
4655 (defun org-flag-drawer (flag)
4656 (save-excursion
4657 (beginning-of-line 1)
4658 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4659 (let ((b (match-end 0))
4660 (outline-regexp org-outline-regexp))
4661 (if (re-search-forward
4662 "^[ \t]*:END:"
4663 (save-excursion (outline-next-heading) (point)) t)
4664 (outline-flag-region b (point-at-eol) flag)
4665 (error ":END: line missing"))))))
4667 (defun org-subtree-end-visible-p ()
4668 "Is the end of the current subtree visible?"
4669 (pos-visible-in-window-p
4670 (save-excursion (org-end-of-subtree t) (point))))
4672 (defun org-first-headline-recenter (&optional N)
4673 "Move cursor to the first headline and recenter the headline.
4674 Optional argument N means, put the headline into the Nth line of the window."
4675 (goto-char (point-min))
4676 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4677 (beginning-of-line)
4678 (recenter (prefix-numeric-value N))))
4680 ;;; Org-goto
4682 (defvar org-goto-window-configuration nil)
4683 (defvar org-goto-marker nil)
4684 (defvar org-goto-map
4685 (let ((map (make-sparse-keymap)))
4686 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4687 (while (setq cmd (pop cmds))
4688 (substitute-key-definition cmd cmd map global-map)))
4689 (suppress-keymap map)
4690 (org-defkey map "\C-m" 'org-goto-ret)
4691 (org-defkey map [(return)] 'org-goto-ret)
4692 (org-defkey map [(left)] 'org-goto-left)
4693 (org-defkey map [(right)] 'org-goto-right)
4694 (org-defkey map [(control ?g)] 'org-goto-quit)
4695 (org-defkey map "\C-i" 'org-cycle)
4696 (org-defkey map [(tab)] 'org-cycle)
4697 (org-defkey map [(down)] 'outline-next-visible-heading)
4698 (org-defkey map [(up)] 'outline-previous-visible-heading)
4699 (if org-goto-auto-isearch
4700 (if (fboundp 'define-key-after)
4701 (define-key-after map [t] 'org-goto-local-auto-isearch)
4702 nil)
4703 (org-defkey map "q" 'org-goto-quit)
4704 (org-defkey map "n" 'outline-next-visible-heading)
4705 (org-defkey map "p" 'outline-previous-visible-heading)
4706 (org-defkey map "f" 'outline-forward-same-level)
4707 (org-defkey map "b" 'outline-backward-same-level)
4708 (org-defkey map "u" 'outline-up-heading))
4709 (org-defkey map "/" 'org-occur)
4710 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4711 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4712 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4713 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4714 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4715 map))
4717 (defconst org-goto-help
4718 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4719 RET=jump to location [Q]uit and return to previous location
4720 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4722 (defvar org-goto-start-pos) ; dynamically scoped parameter
4724 ;; FIXME: Docstring doe not mention both interfaces
4725 (defun org-goto (&optional alternative-interface)
4726 "Look up a different location in the current file, keeping current visibility.
4728 When you want look-up or go to a different location in a document, the
4729 fastest way is often to fold the entire buffer and then dive into the tree.
4730 This method has the disadvantage, that the previous location will be folded,
4731 which may not be what you want.
4733 This command works around this by showing a copy of the current buffer
4734 in an indirect buffer, in overview mode. You can dive into the tree in
4735 that copy, use org-occur and incremental search to find a location.
4736 When pressing RET or `Q', the command returns to the original buffer in
4737 which the visibility is still unchanged. After RET is will also jump to
4738 the location selected in the indirect buffer and expose the
4739 the headline hierarchy above."
4740 (interactive "P")
4741 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4742 (org-refile-use-outline-path t)
4743 (interface
4744 (if (not alternative-interface)
4745 org-goto-interface
4746 (if (eq org-goto-interface 'outline)
4747 'outline-path-completion
4748 'outline)))
4749 (org-goto-start-pos (point))
4750 (selected-point
4751 (if (eq interface 'outline)
4752 (car (org-get-location (current-buffer) org-goto-help))
4753 (nth 3 (org-refile-get-location "Goto: ")))))
4754 (if selected-point
4755 (progn
4756 (org-mark-ring-push org-goto-start-pos)
4757 (goto-char selected-point)
4758 (if (or (org-invisible-p) (org-invisible-p2))
4759 (org-show-context 'org-goto)))
4760 (message "Quit"))))
4762 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4763 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4764 (defvar org-goto-local-auto-isearch-map) ; defined below
4766 (defun org-get-location (buf help)
4767 "Let the user select a location in the Org-mode buffer BUF.
4768 This function uses a recursive edit. It returns the selected position
4769 or nil."
4770 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4771 (isearch-hide-immediately nil)
4772 (isearch-search-fun-function
4773 (lambda () 'org-goto-local-search-headings))
4774 (org-goto-selected-point org-goto-exit-command))
4775 (save-excursion
4776 (save-window-excursion
4777 (delete-other-windows)
4778 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4779 (switch-to-buffer
4780 (condition-case nil
4781 (make-indirect-buffer (current-buffer) "*org-goto*")
4782 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4783 (with-output-to-temp-buffer "*Help*"
4784 (princ help))
4785 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4786 (setq buffer-read-only nil)
4787 (let ((org-startup-truncated t)
4788 (org-startup-folded nil)
4789 (org-startup-align-all-tables nil))
4790 (org-mode)
4791 (org-overview))
4792 (setq buffer-read-only t)
4793 (if (and (boundp 'org-goto-start-pos)
4794 (integer-or-marker-p org-goto-start-pos))
4795 (let ((org-show-hierarchy-above t)
4796 (org-show-siblings t)
4797 (org-show-following-heading t))
4798 (goto-char org-goto-start-pos)
4799 (and (org-invisible-p) (org-show-context)))
4800 (goto-char (point-min)))
4801 (org-beginning-of-line)
4802 (message "Select location and press RET")
4803 (use-local-map org-goto-map)
4804 (recursive-edit)
4806 (kill-buffer "*org-goto*")
4807 (cons org-goto-selected-point org-goto-exit-command)))
4809 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4810 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4811 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4812 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4814 (defun org-goto-local-search-headings (string bound noerror)
4815 "Search and make sure that any matches are in headlines."
4816 (catch 'return
4817 (while (if isearch-forward
4818 (search-forward string bound noerror)
4819 (search-backward string bound noerror))
4820 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4821 (and (member :headline context)
4822 (not (member :tags context))))
4823 (throw 'return (point))))))
4825 (defun org-goto-local-auto-isearch ()
4826 "Start isearch."
4827 (interactive)
4828 (goto-char (point-min))
4829 (let ((keys (this-command-keys)))
4830 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4831 (isearch-mode t)
4832 (isearch-process-search-char (string-to-char keys)))))
4834 (defun org-goto-ret (&optional arg)
4835 "Finish `org-goto' by going to the new location."
4836 (interactive "P")
4837 (setq org-goto-selected-point (point)
4838 org-goto-exit-command 'return)
4839 (throw 'exit nil))
4841 (defun org-goto-left ()
4842 "Finish `org-goto' by going to the new location."
4843 (interactive)
4844 (if (org-on-heading-p)
4845 (progn
4846 (beginning-of-line 1)
4847 (setq org-goto-selected-point (point)
4848 org-goto-exit-command 'left)
4849 (throw 'exit nil))
4850 (error "Not on a heading")))
4852 (defun org-goto-right ()
4853 "Finish `org-goto' by going to the new location."
4854 (interactive)
4855 (if (org-on-heading-p)
4856 (progn
4857 (setq org-goto-selected-point (point)
4858 org-goto-exit-command 'right)
4859 (throw 'exit nil))
4860 (error "Not on a heading")))
4862 (defun org-goto-quit ()
4863 "Finish `org-goto' without cursor motion."
4864 (interactive)
4865 (setq org-goto-selected-point nil)
4866 (setq org-goto-exit-command 'quit)
4867 (throw 'exit nil))
4869 ;;; Indirect buffer display of subtrees
4871 (defvar org-indirect-dedicated-frame nil
4872 "This is the frame being used for indirect tree display.")
4873 (defvar org-last-indirect-buffer nil)
4875 (defun org-tree-to-indirect-buffer (&optional arg)
4876 "Create indirect buffer and narrow it to current subtree.
4877 With numerical prefix ARG, go up to this level and then take that tree.
4878 If ARG is negative, go up that many levels.
4879 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4880 indirect buffer previously made with this command, to avoid proliferation of
4881 indirect buffers. However, when you call the command with a `C-u' prefix, or
4882 when `org-indirect-buffer-display' is `new-frame', the last buffer
4883 is kept so that you can work with several indirect buffers at the same time.
4884 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4885 requests that a new frame be made for the new buffer, so that the dedicated
4886 frame is not changed."
4887 (interactive "P")
4888 (let ((cbuf (current-buffer))
4889 (cwin (selected-window))
4890 (pos (point))
4891 beg end level heading ibuf)
4892 (save-excursion
4893 (org-back-to-heading t)
4894 (when (numberp arg)
4895 (setq level (org-outline-level))
4896 (if (< arg 0) (setq arg (+ level arg)))
4897 (while (> (setq level (org-outline-level)) arg)
4898 (outline-up-heading 1 t)))
4899 (setq beg (point)
4900 heading (org-get-heading))
4901 (org-end-of-subtree t) (setq end (point)))
4902 (if (and (buffer-live-p org-last-indirect-buffer)
4903 (not (eq org-indirect-buffer-display 'new-frame))
4904 (not arg))
4905 (kill-buffer org-last-indirect-buffer))
4906 (setq ibuf (org-get-indirect-buffer cbuf)
4907 org-last-indirect-buffer ibuf)
4908 (cond
4909 ((or (eq org-indirect-buffer-display 'new-frame)
4910 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4911 (select-frame (make-frame))
4912 (delete-other-windows)
4913 (switch-to-buffer ibuf)
4914 (org-set-frame-title heading))
4915 ((eq org-indirect-buffer-display 'dedicated-frame)
4916 (raise-frame
4917 (select-frame (or (and org-indirect-dedicated-frame
4918 (frame-live-p org-indirect-dedicated-frame)
4919 org-indirect-dedicated-frame)
4920 (setq org-indirect-dedicated-frame (make-frame)))))
4921 (delete-other-windows)
4922 (switch-to-buffer ibuf)
4923 (org-set-frame-title (concat "Indirect: " heading)))
4924 ((eq org-indirect-buffer-display 'current-window)
4925 (switch-to-buffer ibuf))
4926 ((eq org-indirect-buffer-display 'other-window)
4927 (pop-to-buffer ibuf))
4928 (t (error "Invalid value.")))
4929 (if (featurep 'xemacs)
4930 (save-excursion (org-mode) (turn-on-font-lock)))
4931 (narrow-to-region beg end)
4932 (show-all)
4933 (goto-char pos)
4934 (and (window-live-p cwin) (select-window cwin))))
4936 (defun org-get-indirect-buffer (&optional buffer)
4937 (setq buffer (or buffer (current-buffer)))
4938 (let ((n 1) (base (buffer-name buffer)) bname)
4939 (while (buffer-live-p
4940 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4941 (setq n (1+ n)))
4942 (condition-case nil
4943 (make-indirect-buffer buffer bname 'clone)
4944 (error (make-indirect-buffer buffer bname)))))
4946 (defun org-set-frame-title (title)
4947 "Set the title of the current frame to the string TITLE."
4948 ;; FIXME: how to name a single frame in XEmacs???
4949 (unless (featurep 'xemacs)
4950 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4952 ;;;; Structure editing
4954 ;;; Inserting headlines
4956 (defun org-previous-line-empty-p ()
4957 (save-excursion
4958 (and (not (bobp))
4959 (or (beginning-of-line 0) t)
4960 (save-match-data
4961 (looking-at "[ \t]*$")))))
4963 (defun org-insert-heading (&optional force-heading)
4964 "Insert a new heading or item with same depth at point.
4965 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4966 If point is at the beginning of a headline, insert a sibling before the
4967 current headline. If point is not at the beginning, do not split the line,
4968 but create the new headline after the current line."
4969 (interactive "P")
4970 (if (= (buffer-size) 0)
4971 (insert "\n* ")
4972 (when (or force-heading (not (org-insert-item)))
4973 (let* ((empty-line-p nil)
4974 (head (save-excursion
4975 (condition-case nil
4976 (progn
4977 (org-back-to-heading)
4978 (setq empty-line-p (org-previous-line-empty-p))
4979 (match-string 0))
4980 (error "*"))))
4981 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
4982 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
4983 pos hide-previous previous-pos)
4984 (cond
4985 ((and (org-on-heading-p) (bolp)
4986 (or (bobp)
4987 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4988 ;; insert before the current line
4989 (open-line (if blank 2 1)))
4990 ((and (bolp)
4991 (or (bobp)
4992 (save-excursion
4993 (backward-char 1) (not (org-invisible-p)))))
4994 ;; insert right here
4995 nil)
4997 ;; somewhere in the line
4998 (save-excursion
4999 (setq previous-pos (point-at-bol))
5000 (end-of-line)
5001 (setq hide-previous (org-invisible-p)))
5002 (and org-insert-heading-respect-content (org-show-subtree))
5003 (let ((split
5004 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5005 (save-excursion
5006 (let ((p (point)))
5007 (goto-char (point-at-bol))
5008 (and (looking-at org-complex-heading-regexp)
5009 (> p (match-beginning 4)))))))
5010 tags pos)
5011 (cond
5012 (org-insert-heading-respect-content
5013 (org-end-of-subtree nil t)
5014 (or (bolp) (newline))
5015 (or (org-previous-line-empty-p)
5016 (and blank (newline)))
5017 (open-line 1))
5018 ((org-on-heading-p)
5019 (when hide-previous
5020 (show-children)
5021 (org-show-entry))
5022 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5023 (setq tags (and (match-end 2) (match-string 2)))
5024 (and (match-end 1)
5025 (delete-region (match-beginning 1) (match-end 1)))
5026 (setq pos (point-at-bol))
5027 (or split (end-of-line 1))
5028 (delete-horizontal-space)
5029 (newline (if blank 2 1))
5030 (when tags
5031 (save-excursion
5032 (goto-char pos)
5033 (end-of-line 1)
5034 (insert " " tags)
5035 (org-set-tags nil 'align))))
5037 (or split (end-of-line 1))
5038 (newline (if blank 2 1)))))))
5039 (insert head) (just-one-space)
5040 (setq pos (point))
5041 (end-of-line 1)
5042 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5043 (when (and org-insert-heading-respect-content hide-previous)
5044 (save-excursion
5045 (goto-char previous-pos)
5046 (hide-subtree)))
5047 (run-hooks 'org-insert-heading-hook)))))
5049 (defun org-get-heading (&optional no-tags)
5050 "Return the heading of the current entry, without the stars."
5051 (save-excursion
5052 (org-back-to-heading t)
5053 (if (looking-at
5054 (if no-tags
5055 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5056 "\\*+[ \t]+\\([^\r\n]*\\)"))
5057 (match-string 1) "")))
5059 (defun org-heading-components ()
5060 "Return the components of the current heading.
5061 This is a list with the following elements:
5062 - the level as an integer
5063 - the reduced level, different if `org-odd-levels-only' is set.
5064 - the TODO keyword, or nil
5065 - the priority character, like ?A, or nil if no priority is given
5066 - the headline text itself, or the tags string if no headline text
5067 - the tags string, or nil."
5068 (save-excursion
5069 (org-back-to-heading t)
5070 (if (looking-at org-complex-heading-regexp)
5071 (list (length (match-string 1))
5072 (org-reduced-level (length (match-string 1)))
5073 (org-match-string-no-properties 2)
5074 (and (match-end 3) (aref (match-string 3) 2))
5075 (org-match-string-no-properties 4)
5076 (org-match-string-no-properties 5)))))
5078 (defun org-insert-heading-after-current ()
5079 "Insert a new heading with same level as current, after current subtree."
5080 (interactive)
5081 (org-back-to-heading)
5082 (org-insert-heading)
5083 (org-move-subtree-down)
5084 (end-of-line 1))
5086 (defun org-insert-heading-respect-content ()
5087 (interactive)
5088 (let ((org-insert-heading-respect-content t))
5089 (org-insert-heading t)))
5091 (defun org-insert-todo-heading-respect-content (&optional force-state)
5092 (interactive "P")
5093 (let ((org-insert-heading-respect-content t))
5094 (org-insert-todo-heading force-state t)))
5096 (defun org-insert-todo-heading (arg &optional force-heading)
5097 "Insert a new heading with the same level and TODO state as current heading.
5098 If the heading has no TODO state, or if the state is DONE, use the first
5099 state (TODO by default). Also with prefix arg, force first state."
5100 (interactive "P")
5101 (when (or force-heading (not (org-insert-item 'checkbox)))
5102 (org-insert-heading force-heading)
5103 (save-excursion
5104 (org-back-to-heading)
5105 (outline-previous-heading)
5106 (looking-at org-todo-line-regexp))
5107 (if (or arg
5108 (not (match-beginning 2))
5109 (member (match-string 2) org-done-keywords))
5110 (insert (car org-todo-keywords-1) " ")
5111 (insert (match-string 2) " "))
5112 (when org-provide-todo-statistics
5113 (org-update-parent-todo-statistics))))
5115 (defun org-insert-subheading (arg)
5116 "Insert a new subheading and demote it.
5117 Works for outline headings and for plain lists alike."
5118 (interactive "P")
5119 (org-insert-heading arg)
5120 (cond
5121 ((org-on-heading-p) (org-do-demote))
5122 ((org-at-item-p) (org-indent-item 1))))
5124 (defun org-insert-todo-subheading (arg)
5125 "Insert a new subheading with TODO keyword or checkbox and demote it.
5126 Works for outline headings and for plain lists alike."
5127 (interactive "P")
5128 (org-insert-todo-heading arg)
5129 (cond
5130 ((org-on-heading-p) (org-do-demote))
5131 ((org-at-item-p) (org-indent-item 1))))
5133 ;;; Promotion and Demotion
5135 (defun org-promote-subtree ()
5136 "Promote the entire subtree.
5137 See also `org-promote'."
5138 (interactive)
5139 (save-excursion
5140 (org-map-tree 'org-promote))
5141 (org-fix-position-after-promote))
5143 (defun org-demote-subtree ()
5144 "Demote the entire subtree. See `org-demote'.
5145 See also `org-promote'."
5146 (interactive)
5147 (save-excursion
5148 (org-map-tree 'org-demote))
5149 (org-fix-position-after-promote))
5152 (defun org-do-promote ()
5153 "Promote the current heading higher up the tree.
5154 If the region is active in `transient-mark-mode', promote all headings
5155 in the region."
5156 (interactive)
5157 (save-excursion
5158 (if (org-region-active-p)
5159 (org-map-region 'org-promote (region-beginning) (region-end))
5160 (org-promote)))
5161 (org-fix-position-after-promote))
5163 (defun org-do-demote ()
5164 "Demote the current heading lower down the tree.
5165 If the region is active in `transient-mark-mode', demote all headings
5166 in the region."
5167 (interactive)
5168 (save-excursion
5169 (if (org-region-active-p)
5170 (org-map-region 'org-demote (region-beginning) (region-end))
5171 (org-demote)))
5172 (org-fix-position-after-promote))
5174 (defun org-fix-position-after-promote ()
5175 "Make sure that after pro/demotion cursor position is right."
5176 (let ((pos (point)))
5177 (when (save-excursion
5178 (beginning-of-line 1)
5179 (looking-at org-todo-line-regexp)
5180 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5181 (cond ((eobp) (insert " "))
5182 ((eolp) (insert " "))
5183 ((equal (char-after) ?\ ) (forward-char 1))))))
5185 (defun org-reduced-level (l)
5186 "Compute the effective level of a heading.
5187 This takes into account the setting of `org-odd-levels-only'."
5188 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5190 (defun org-get-valid-level (level &optional change)
5191 "Rectify a level change under the influence of `org-odd-levels-only'
5192 LEVEL is a current level, CHANGE is by how much the level should be
5193 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5194 even level numbers will become the next higher odd number."
5195 (if org-odd-levels-only
5196 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5197 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5198 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5199 (max 1 (+ level change))))
5201 (if (boundp 'define-obsolete-function-alias)
5202 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5203 (define-obsolete-function-alias 'org-get-legal-level
5204 'org-get-valid-level)
5205 (define-obsolete-function-alias 'org-get-legal-level
5206 'org-get-valid-level "23.1")))
5208 (defun org-promote ()
5209 "Promote the current heading higher up the tree.
5210 If the region is active in `transient-mark-mode', promote all headings
5211 in the region."
5212 (org-back-to-heading t)
5213 (let* ((level (save-match-data (funcall outline-level)))
5214 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5215 (diff (abs (- level (length up-head) -1))))
5216 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5217 (replace-match up-head nil t)
5218 ;; Fixup tag positioning
5219 (and org-auto-align-tags (org-set-tags nil t))
5220 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5222 (defun org-demote ()
5223 "Demote the current heading lower down the tree.
5224 If the region is active in `transient-mark-mode', demote all headings
5225 in the region."
5226 (org-back-to-heading t)
5227 (let* ((level (save-match-data (funcall outline-level)))
5228 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5229 (diff (abs (- level (length down-head) -1))))
5230 (replace-match down-head nil t)
5231 ;; Fixup tag positioning
5232 (and org-auto-align-tags (org-set-tags nil t))
5233 (if org-adapt-indentation (org-fixup-indentation diff))))
5235 (defun org-map-tree (fun)
5236 "Call FUN for every heading underneath the current one."
5237 (org-back-to-heading)
5238 (let ((level (funcall outline-level)))
5239 (save-excursion
5240 (funcall fun)
5241 (while (and (progn
5242 (outline-next-heading)
5243 (> (funcall outline-level) level))
5244 (not (eobp)))
5245 (funcall fun)))))
5247 (defun org-map-region (fun beg end)
5248 "Call FUN for every heading between BEG and END."
5249 (let ((org-ignore-region t))
5250 (save-excursion
5251 (setq end (copy-marker end))
5252 (goto-char beg)
5253 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5254 (< (point) end))
5255 (funcall fun))
5256 (while (and (progn
5257 (outline-next-heading)
5258 (< (point) end))
5259 (not (eobp)))
5260 (funcall fun)))))
5262 (defun org-fixup-indentation (diff)
5263 "Change the indentation in the current entry by DIFF
5264 However, if any line in the current entry has no indentation, or if it
5265 would end up with no indentation after the change, nothing at all is done."
5266 (save-excursion
5267 (let ((end (save-excursion (outline-next-heading)
5268 (point-marker)))
5269 (prohibit (if (> diff 0)
5270 "^\\S-"
5271 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5272 col)
5273 (unless (save-excursion (end-of-line 1)
5274 (re-search-forward prohibit end t))
5275 (while (and (< (point) end)
5276 (re-search-forward "^[ \t]+" end t))
5277 (goto-char (match-end 0))
5278 (setq col (current-column))
5279 (if (< diff 0) (replace-match ""))
5280 (org-indent-to-column (+ diff col))))
5281 (move-marker end nil))))
5283 (defun org-convert-to-odd-levels ()
5284 "Convert an org-mode file with all levels allowed to one with odd levels.
5285 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5286 level 5 etc."
5287 (interactive)
5288 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5289 (let ((org-odd-levels-only nil) n)
5290 (save-excursion
5291 (goto-char (point-min))
5292 (while (re-search-forward "^\\*\\*+ " nil t)
5293 (setq n (- (length (match-string 0)) 2))
5294 (while (>= (setq n (1- n)) 0)
5295 (org-demote))
5296 (end-of-line 1))))))
5299 (defun org-convert-to-oddeven-levels ()
5300 "Convert an org-mode file with only odd levels to one with odd and even levels.
5301 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5302 section with an even level, conversion would destroy the structure of the file. An error
5303 is signaled in this case."
5304 (interactive)
5305 (goto-char (point-min))
5306 ;; First check if there are no even levels
5307 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5308 (org-show-context t)
5309 (error "Not all levels are odd in this file. Conversion not possible."))
5310 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
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 (/ (1- (length (match-string 0))) 2))
5316 (while (>= (setq n (1- n)) 0)
5317 (org-promote))
5318 (end-of-line 1))))))
5320 (defun org-tr-level (n)
5321 "Make N odd if required."
5322 (if org-odd-levels-only (1+ (/ n 2)) n))
5324 ;;; Vertical tree motion, cutting and pasting of subtrees
5326 (defun org-move-subtree-up (&optional arg)
5327 "Move the current subtree up past ARG headlines of the same level."
5328 (interactive "p")
5329 (org-move-subtree-down (- (prefix-numeric-value arg))))
5331 (defun org-move-subtree-down (&optional arg)
5332 "Move the current subtree down past ARG headlines of the same level."
5333 (interactive "p")
5334 (setq arg (prefix-numeric-value arg))
5335 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5336 'outline-get-last-sibling))
5337 (ins-point (make-marker))
5338 (cnt (abs arg))
5339 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5340 ;; Select the tree
5341 (org-back-to-heading)
5342 (setq beg0 (point))
5343 (save-excursion
5344 (setq ne-beg (org-back-over-empty-lines))
5345 (setq beg (point)))
5346 (save-match-data
5347 (save-excursion (outline-end-of-heading)
5348 (setq folded (org-invisible-p)))
5349 (outline-end-of-subtree))
5350 (outline-next-heading)
5351 (setq ne-end (org-back-over-empty-lines))
5352 (setq end (point))
5353 (goto-char beg0)
5354 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5355 ;; include less whitespace
5356 (save-excursion
5357 (goto-char beg)
5358 (forward-line (- ne-beg ne-end))
5359 (setq beg (point))))
5360 ;; Find insertion point, with error handling
5361 (while (> cnt 0)
5362 (or (and (funcall movfunc) (looking-at outline-regexp))
5363 (progn (goto-char beg0)
5364 (error "Cannot move past superior level or buffer limit")))
5365 (setq cnt (1- cnt)))
5366 (if (> arg 0)
5367 ;; Moving forward - still need to move over subtree
5368 (progn (org-end-of-subtree t t)
5369 (save-excursion
5370 (org-back-over-empty-lines)
5371 (or (bolp) (newline)))))
5372 (setq ne-ins (org-back-over-empty-lines))
5373 (move-marker ins-point (point))
5374 (setq txt (buffer-substring beg end))
5375 (org-save-markers-in-region beg end)
5376 (delete-region beg end)
5377 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5378 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5379 (let ((bbb (point)))
5380 (insert-before-markers txt)
5381 (org-reinstall-markers-in-region bbb)
5382 (move-marker ins-point bbb))
5383 (or (bolp) (insert "\n"))
5384 (setq ins-end (point))
5385 (goto-char ins-point)
5386 (org-skip-whitespace)
5387 (when (and (< arg 0)
5388 (org-first-sibling-p)
5389 (> ne-ins ne-beg))
5390 ;; Move whitespace back to beginning
5391 (save-excursion
5392 (goto-char ins-end)
5393 (let ((kill-whole-line t))
5394 (kill-line (- ne-ins ne-beg)) (point)))
5395 (insert (make-string (- ne-ins ne-beg) ?\n)))
5396 (move-marker ins-point nil)
5397 (org-compact-display-after-subtree-move)
5398 (org-show-empty-lines-in-parent)
5399 (unless folded
5400 (org-show-entry)
5401 (show-children)
5402 (org-cycle-hide-drawers 'children))))
5404 (defvar org-subtree-clip ""
5405 "Clipboard for cut and paste of subtrees.
5406 This is actually only a copy of the kill, because we use the normal kill
5407 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5409 (defvar org-subtree-clip-folded nil
5410 "Was the last copied subtree folded?
5411 This is used to fold the tree back after pasting.")
5413 (defun org-cut-subtree (&optional n)
5414 "Cut the current subtree into the clipboard.
5415 With prefix arg N, cut this many sequential subtrees.
5416 This is a short-hand for marking the subtree and then cutting it."
5417 (interactive "p")
5418 (org-copy-subtree n 'cut))
5420 (defun org-copy-subtree (&optional n cut force-store-markers)
5421 "Cut the current subtree into the clipboard.
5422 With prefix arg N, cut this many sequential subtrees.
5423 This is a short-hand for marking the subtree and then copying it.
5424 If CUT is non-nil, actually cut the subtree.
5425 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5426 of some markers in the region, even if CUT is non-nil. This is
5427 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5428 (interactive "p")
5429 (let (beg end folded (beg0 (point)))
5430 (if (interactive-p)
5431 (org-back-to-heading nil) ; take what looks like a subtree
5432 (org-back-to-heading t)) ; take what is really there
5433 (org-back-over-empty-lines)
5434 (setq beg (point))
5435 (skip-chars-forward " \t\r\n")
5436 (save-match-data
5437 (save-excursion (outline-end-of-heading)
5438 (setq folded (org-invisible-p)))
5439 (condition-case nil
5440 (outline-forward-same-level (1- n))
5441 (error nil))
5442 (org-end-of-subtree t t))
5443 (org-back-over-empty-lines)
5444 (setq end (point))
5445 (goto-char beg0)
5446 (when (> end beg)
5447 (setq org-subtree-clip-folded folded)
5448 (when (or cut force-store-markers)
5449 (org-save-markers-in-region beg end))
5450 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5451 (setq org-subtree-clip (current-kill 0))
5452 (message "%s: Subtree(s) with %d characters"
5453 (if cut "Cut" "Copied")
5454 (length org-subtree-clip)))))
5456 (defun org-paste-subtree (&optional level tree for-yank)
5457 "Paste the clipboard as a subtree, with modification of headline level.
5458 The entire subtree is promoted or demoted in order to match a new headline
5459 level.
5461 If the cursor is at the beginning of a headline, the same level as
5462 that headline is used to paste the tree
5464 If not, the new level is derived from the *visible* headings
5465 before and after the insertion point, and taken to be the inferior headline
5466 level of the two. So if the previous visible heading is level 3 and the
5467 next is level 4 (or vice versa), level 4 will be used for insertion.
5468 This makes sure that the subtree remains an independent subtree and does
5469 not swallow low level entries.
5471 You can also force a different level, either by using a numeric prefix
5472 argument, or by inserting the heading marker by hand. For example, if the
5473 cursor is after \"*****\", then the tree will be shifted to level 5.
5475 If optional TREE is given, use this text instead of the kill ring.
5477 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5478 move back over whitespace before inserting, and move point to the end of
5479 the inserted text when done."
5480 (interactive "P")
5481 (unless (org-kill-is-subtree-p tree)
5482 (error "%s"
5483 (substitute-command-keys
5484 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5485 (let* ((visp (not (org-invisible-p)))
5486 (txt (or tree (and kill-ring (current-kill 0))))
5487 (^re (concat "^\\(" outline-regexp "\\)"))
5488 (re (concat "\\(" outline-regexp "\\)"))
5489 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5491 (old-level (if (string-match ^re txt)
5492 (- (match-end 0) (match-beginning 0) 1)
5493 -1))
5494 (force-level (cond (level (prefix-numeric-value level))
5495 ((and (looking-at "[ \t]*$")
5496 (string-match
5497 ^re_ (buffer-substring
5498 (point-at-bol) (point))))
5499 (- (match-end 1) (match-beginning 1)))
5500 ((and (bolp)
5501 (looking-at org-outline-regexp))
5502 (- (match-end 0) (point) 1))
5503 (t nil)))
5504 (previous-level (save-excursion
5505 (condition-case nil
5506 (progn
5507 (outline-previous-visible-heading 1)
5508 (if (looking-at re)
5509 (- (match-end 0) (match-beginning 0) 1)
5511 (error 1))))
5512 (next-level (save-excursion
5513 (condition-case nil
5514 (progn
5515 (or (looking-at outline-regexp)
5516 (outline-next-visible-heading 1))
5517 (if (looking-at re)
5518 (- (match-end 0) (match-beginning 0) 1)
5520 (error 1))))
5521 (new-level (or force-level (max previous-level next-level)))
5522 (shift (if (or (= old-level -1)
5523 (= new-level -1)
5524 (= old-level new-level))
5526 (- new-level old-level)))
5527 (delta (if (> shift 0) -1 1))
5528 (func (if (> shift 0) 'org-demote 'org-promote))
5529 (org-odd-levels-only nil)
5530 beg end newend)
5531 ;; Remove the forced level indicator
5532 (if force-level
5533 (delete-region (point-at-bol) (point)))
5534 ;; Paste
5535 (beginning-of-line 1)
5536 (unless for-yank (org-back-over-empty-lines))
5537 (setq beg (point))
5538 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5539 (insert-before-markers txt)
5540 (unless (string-match "\n\\'" txt) (insert "\n"))
5541 (setq newend (point))
5542 (org-reinstall-markers-in-region beg)
5543 (setq end (point))
5544 (goto-char beg)
5545 (skip-chars-forward " \t\n\r")
5546 (setq beg (point))
5547 (if (and (org-invisible-p) visp)
5548 (save-excursion (outline-show-heading)))
5549 ;; Shift if necessary
5550 (unless (= shift 0)
5551 (save-restriction
5552 (narrow-to-region beg end)
5553 (while (not (= shift 0))
5554 (org-map-region func (point-min) (point-max))
5555 (setq shift (+ delta shift)))
5556 (goto-char (point-min))
5557 (setq newend (point-max))))
5558 (when (or (interactive-p) for-yank)
5559 (message "Clipboard pasted as level %d subtree" new-level))
5560 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5561 kill-ring
5562 (eq org-subtree-clip (current-kill 0))
5563 org-subtree-clip-folded)
5564 ;; The tree was folded before it was killed/copied
5565 (hide-subtree))
5566 (and for-yank (goto-char newend))))
5568 (defun org-kill-is-subtree-p (&optional txt)
5569 "Check if the current kill is an outline subtree, or a set of trees.
5570 Returns nil if kill does not start with a headline, or if the first
5571 headline level is not the largest headline level in the tree.
5572 So this will actually accept several entries of equal levels as well,
5573 which is OK for `org-paste-subtree'.
5574 If optional TXT is given, check this string instead of the current kill."
5575 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5576 (start-level (and kill
5577 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5578 org-outline-regexp "\\)")
5579 kill)
5580 (- (match-end 2) (match-beginning 2) 1)))
5581 (re (concat "^" org-outline-regexp))
5582 (start (1+ (or (match-beginning 2) -1))))
5583 (if (not start-level)
5584 (progn
5585 nil) ;; does not even start with a heading
5586 (catch 'exit
5587 (while (setq start (string-match re kill (1+ start)))
5588 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5589 (throw 'exit nil)))
5590 t))))
5592 (defvar org-markers-to-move nil
5593 "Markers that should be moved with a cut-and-paste operation.
5594 Those markers are stored together with their positions relative to
5595 the start of the region.")
5597 (defun org-save-markers-in-region (beg end)
5598 "Check markers in region.
5599 If these markers are between BEG and END, record their position relative
5600 to BEG, so that after moving the block of text, we can put the markers back
5601 into place.
5602 This function gets called just before an entry or tree gets cut from the
5603 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5604 called immediately, to move the markers with the entries."
5605 (setq org-markers-to-move nil)
5606 (when (featurep 'org-clock)
5607 (org-clock-save-markers-for-cut-and-paste beg end))
5608 (when (featurep 'org-agenda)
5609 (org-agenda-save-markers-for-cut-and-paste beg end)))
5611 (defun org-check-and-save-marker (marker beg end)
5612 "Check if MARKER is between BEG and END.
5613 If yes, remember the marker and the distance to BEG."
5614 (when (and (marker-buffer marker)
5615 (equal (marker-buffer marker) (current-buffer)))
5616 (if (and (>= marker beg) (< marker end))
5617 (push (cons marker (- marker beg)) org-markers-to-move))))
5619 (defun org-reinstall-markers-in-region (beg)
5620 "Move all remembered markers to their position relative to BEG."
5621 (mapc (lambda (x)
5622 (move-marker (car x) (+ beg (cdr x))))
5623 org-markers-to-move)
5624 (setq org-markers-to-move nil))
5626 (defun org-narrow-to-subtree ()
5627 "Narrow buffer to the current subtree."
5628 (interactive)
5629 (save-excursion
5630 (save-match-data
5631 (narrow-to-region
5632 (progn (org-back-to-heading) (point))
5633 (progn (org-end-of-subtree t) (point))))))
5636 ;;; Outline Sorting
5638 (defun org-sort (with-case)
5639 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5640 Optional argument WITH-CASE means sort case-sensitively."
5641 (interactive "P")
5642 (if (org-at-table-p)
5643 (org-call-with-arg 'org-table-sort-lines with-case)
5644 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5646 (defun org-sort-remove-invisible (s)
5647 (remove-text-properties 0 (length s) org-rm-props s)
5648 (while (string-match org-bracket-link-regexp s)
5649 (setq s (replace-match (if (match-end 2)
5650 (match-string 3 s)
5651 (match-string 1 s)) t t s)))
5654 (defvar org-priority-regexp) ; defined later in the file
5656 (defun org-sort-entries-or-items
5657 (&optional with-case sorting-type getkey-func compare-func property)
5658 "Sort entries on a certain level of an outline tree.
5659 If there is an active region, the entries in the region are sorted.
5660 Else, if the cursor is before the first entry, sort the top-level items.
5661 Else, the children of the entry at point are sorted.
5663 Sorting can be alphabetically, numerically, and by date/time as given by
5664 the first time stamp in the entry. The command prompts for the sorting
5665 type unless it has been given to the function through the SORTING-TYPE
5666 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5667 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5668 called with point at the beginning of the record. It must return either
5669 a string or a number that should serve as the sorting key for that record.
5671 Comparing entries ignores case by default. However, with an optional argument
5672 WITH-CASE, the sorting considers case as well."
5673 (interactive "P")
5674 (let ((case-func (if with-case 'identity 'downcase))
5675 start beg end stars re re2
5676 txt what tmp plain-list-p)
5677 ;; Find beginning and end of region to sort
5678 (cond
5679 ((org-region-active-p)
5680 ;; we will sort the region
5681 (setq end (region-end)
5682 what "region")
5683 (goto-char (region-beginning))
5684 (if (not (org-on-heading-p)) (outline-next-heading))
5685 (setq start (point)))
5686 ((org-at-item-p)
5687 ;; we will sort this plain list
5688 (org-beginning-of-item-list) (setq start (point))
5689 (org-end-of-item-list) (setq end (point))
5690 (goto-char start)
5691 (setq plain-list-p t
5692 what "plain list"))
5693 ((or (org-on-heading-p)
5694 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5695 ;; we will sort the children of the current headline
5696 (org-back-to-heading)
5697 (setq start (point)
5698 end (progn (org-end-of-subtree t t)
5699 (org-back-over-empty-lines)
5700 (point))
5701 what "children")
5702 (goto-char start)
5703 (show-subtree)
5704 (outline-next-heading))
5706 ;; we will sort the top-level entries in this file
5707 (goto-char (point-min))
5708 (or (org-on-heading-p) (outline-next-heading))
5709 (setq start (point) end (point-max) what "top-level")
5710 (goto-char start)
5711 (show-all)))
5713 (setq beg (point))
5714 (if (>= beg end) (error "Nothing to sort"))
5716 (unless plain-list-p
5717 (looking-at "\\(\\*+\\)")
5718 (setq stars (match-string 1)
5719 re (concat "^" (regexp-quote stars) " +")
5720 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5721 txt (buffer-substring beg end))
5722 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5723 (if (and (not (equal stars "*")) (string-match re2 txt))
5724 (error "Region to sort contains a level above the first entry")))
5726 (unless sorting-type
5727 (message
5728 (if plain-list-p
5729 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5730 "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:")
5731 what)
5732 (setq sorting-type (read-char-exclusive))
5734 (and (= (downcase sorting-type) ?f)
5735 (setq getkey-func
5736 (org-ido-completing-read "Sort using function: "
5737 obarray 'fboundp t nil nil))
5738 (setq getkey-func (intern getkey-func)))
5740 (and (= (downcase sorting-type) ?r)
5741 (setq property
5742 (org-ido-completing-read "Property: "
5743 (mapcar 'list (org-buffer-property-keys t))
5744 nil t))))
5746 (message "Sorting entries...")
5748 (save-restriction
5749 (narrow-to-region start end)
5751 (let ((dcst (downcase sorting-type))
5752 (now (current-time)))
5753 (sort-subr
5754 (/= dcst sorting-type)
5755 ;; This function moves to the beginning character of the "record" to
5756 ;; be sorted.
5757 (if plain-list-p
5758 (lambda nil
5759 (if (org-at-item-p) t (goto-char (point-max))))
5760 (lambda nil
5761 (if (re-search-forward re nil t)
5762 (goto-char (match-beginning 0))
5763 (goto-char (point-max)))))
5764 ;; This function moves to the last character of the "record" being
5765 ;; sorted.
5766 (if plain-list-p
5767 'org-end-of-item
5768 (lambda nil
5769 (save-match-data
5770 (condition-case nil
5771 (outline-forward-same-level 1)
5772 (error
5773 (goto-char (point-max)))))))
5775 ;; This function returns the value that gets sorted against.
5776 (if plain-list-p
5777 (lambda nil
5778 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5779 (cond
5780 ((= dcst ?n)
5781 (string-to-number (buffer-substring (match-end 0)
5782 (point-at-eol))))
5783 ((= dcst ?a)
5784 (buffer-substring (match-end 0) (point-at-eol)))
5785 ((= dcst ?t)
5786 (if (re-search-forward org-ts-regexp
5787 (point-at-eol) t)
5788 (org-time-string-to-time (match-string 0))
5789 now))
5790 ((= dcst ?f)
5791 (if getkey-func
5792 (progn
5793 (setq tmp (funcall getkey-func))
5794 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5795 tmp)
5796 (error "Invalid key function `%s'" getkey-func)))
5797 (t (error "Invalid sorting type `%c'" sorting-type)))))
5798 (lambda nil
5799 (cond
5800 ((= dcst ?n)
5801 (if (looking-at org-complex-heading-regexp)
5802 (string-to-number (match-string 4))
5803 nil))
5804 ((= dcst ?a)
5805 (if (looking-at org-complex-heading-regexp)
5806 (funcall case-func (match-string 4))
5807 nil))
5808 ((= dcst ?t)
5809 (if (re-search-forward org-ts-regexp
5810 (save-excursion
5811 (forward-line 2)
5812 (point)) t)
5813 (org-time-string-to-time (match-string 0))
5814 now))
5815 ((= dcst ?p)
5816 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5817 (string-to-char (match-string 2))
5818 org-default-priority))
5819 ((= dcst ?r)
5820 (or (org-entry-get nil property) ""))
5821 ((= dcst ?o)
5822 (if (looking-at org-complex-heading-regexp)
5823 (- 9999 (length (member (match-string 2)
5824 org-todo-keywords-1)))))
5825 ((= dcst ?f)
5826 (if getkey-func
5827 (progn
5828 (setq tmp (funcall getkey-func))
5829 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5830 tmp)
5831 (error "Invalid key function `%s'" getkey-func)))
5832 (t (error "Invalid sorting type `%c'" sorting-type)))))
5834 (cond
5835 ((= dcst ?a) 'string<)
5836 ((= dcst ?t) 'time-less-p)
5837 ((= dcst ?f) compare-func)
5838 (t nil)))))
5839 (message "Sorting entries...done")))
5841 (defun org-do-sort (table what &optional with-case sorting-type)
5842 "Sort TABLE of WHAT according to SORTING-TYPE.
5843 The user will be prompted for the SORTING-TYPE if the call to this
5844 function does not specify it. WHAT is only for the prompt, to indicate
5845 what is being sorted. The sorting key will be extracted from
5846 the car of the elements of the table.
5847 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5848 (unless sorting-type
5849 (message
5850 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5851 what)
5852 (setq sorting-type (read-char-exclusive)))
5853 (let ((dcst (downcase sorting-type))
5854 extractfun comparefun)
5855 ;; Define the appropriate functions
5856 (cond
5857 ((= dcst ?n)
5858 (setq extractfun 'string-to-number
5859 comparefun (if (= dcst sorting-type) '< '>)))
5860 ((= dcst ?a)
5861 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5862 (lambda(x) (downcase (org-sort-remove-invisible x))))
5863 comparefun (if (= dcst sorting-type)
5864 'string<
5865 (lambda (a b) (and (not (string< a b))
5866 (not (string= a b)))))))
5867 ((= dcst ?t)
5868 (setq extractfun
5869 (lambda (x)
5870 (if (string-match org-ts-regexp x)
5871 (time-to-seconds
5872 (org-time-string-to-time (match-string 0 x)))
5874 comparefun (if (= dcst sorting-type) '< '>)))
5875 (t (error "Invalid sorting type `%c'" sorting-type)))
5877 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5878 table)
5879 (lambda (a b) (funcall comparefun (car a) (car b))))))
5881 ;;; Editing source examples
5883 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5884 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5885 (defvar org-edit-src-force-single-line nil)
5886 (defvar org-edit-src-from-org-mode nil)
5887 (defvar org-edit-src-picture nil)
5889 (define-minor-mode org-exit-edit-mode
5890 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5892 (defun org-edit-src-code ()
5893 "Edit the source code example at point.
5894 An indirect buffer is created, and that buffer is then narrowed to the
5895 example at point and switched to the correct language mode. When done,
5896 exit by killing the buffer with \\[org-edit-src-exit]."
5897 (interactive)
5898 (let ((line (org-current-line))
5899 (case-fold-search t)
5900 (msg (substitute-command-keys
5901 "Edit, then exit with C-c ' (C-c and single quote)"))
5902 (info (org-edit-src-find-region-and-lang))
5903 (org-mode-p (eq major-mode 'org-mode))
5904 beg end lang lang-f single lfmt)
5905 (if (not info)
5907 (setq beg (nth 0 info)
5908 end (nth 1 info)
5909 lang (nth 2 info)
5910 single (nth 3 info)
5911 lfmt (nth 4 info)
5912 lang-f (intern (concat lang "-mode")))
5913 (unless (functionp lang-f)
5914 (error "No such language mode: %s" lang-f))
5915 (goto-line line)
5916 (if (get-buffer "*Org Edit Src Example*")
5917 (kill-buffer "*Org Edit Src Example*"))
5918 (switch-to-buffer (make-indirect-buffer (current-buffer)
5919 "*Org Edit Src Example*"))
5920 (narrow-to-region beg end)
5921 (remove-text-properties beg end '(display nil invisible nil
5922 intangible nil))
5923 (let ((org-inhibit-startup t))
5924 (funcall lang-f))
5925 (set (make-local-variable 'org-edit-src-force-single-line) single)
5926 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5927 (when lfmt
5928 (set (make-local-variable 'org-coderef-label-format) lfmt))
5929 (when org-mode-p
5930 (goto-char (point-min))
5931 (while (re-search-forward "^," nil t)
5932 (replace-match "")))
5933 (goto-line line)
5934 (org-exit-edit-mode)
5935 (org-set-local 'header-line-format msg)
5936 (message "%s" msg)
5937 t)))
5939 (defun org-edit-fixed-width-region ()
5940 "Edit the fixed-width ascii drawing at point.
5941 This must be a region where each line starts with a colon followed by
5942 a space character.
5943 An indirect buffer is created, and that buffer is then narrowed to the
5944 example at point and switched to artist-mode. When done,
5945 exit by killing the buffer with \\[org-edit-src-exit]."
5946 (interactive)
5947 (let ((line (org-current-line))
5948 (case-fold-search t)
5949 (msg (substitute-command-keys
5950 "Edit, then exit with C-c ' (C-c and single quote)"))
5951 (org-mode-p (eq major-mode 'org-mode))
5952 beg end)
5953 (beginning-of-line 1)
5954 (if (looking-at "[ \t]*[^:\n \t]")
5956 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5957 (setq beg (point) end beg)
5958 (save-excursion
5959 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5960 (setq beg (point-at-bol 2))
5961 (setq beg (point))))
5962 (save-excursion
5963 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5964 (setq end (1- (match-beginning 0)))
5965 (setq end (point))))
5966 (goto-line line))
5967 (if (get-buffer "*Org Edit Picture*")
5968 (kill-buffer "*Org Edit Picture*"))
5969 (switch-to-buffer (make-indirect-buffer (current-buffer)
5970 "*Org Edit Picture*"))
5971 (narrow-to-region beg end)
5972 (remove-text-properties beg end '(display nil invisible nil
5973 intangible nil))
5974 (when (fboundp 'font-lock-unfontify-region)
5975 (font-lock-unfontify-region (point-min) (point-max)))
5976 (cond
5977 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5978 (fundamental-mode)
5979 (artist-mode 1))
5980 (t (funcall org-edit-fixed-width-region-mode)))
5981 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5982 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5983 (set (make-local-variable 'org-edit-src-picture) t)
5984 (goto-char (point-min))
5985 (while (re-search-forward "^[ \t]*: ?" nil t)
5986 (replace-match ""))
5987 (goto-line line)
5988 (org-exit-edit-mode)
5989 (org-set-local 'header-line-format msg)
5990 (message "%s" msg)
5991 t)))
5994 (defun org-edit-src-find-region-and-lang ()
5995 "Find the region and language for a local edit.
5996 Return a list with beginning and end of the region, a string representing
5997 the language, a switch telling of the content should be in a single line."
5998 (let ((re-list
5999 (append
6000 org-edit-src-region-extra
6002 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6003 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6004 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6005 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6006 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6007 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6008 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6009 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6010 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6011 ("^#\\+html:" "\n" "html" single-line)
6012 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6013 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6014 ("^#\\+latex:" "\n" "latex" single-line)
6015 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6016 ("^#\\+ascii:" "\n" "ascii" single-line)
6018 (pos (point))
6019 re1 re2 single beg end lang lfmt match-re1)
6020 (catch 'exit
6021 (while (setq entry (pop re-list))
6022 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6023 single (nth 3 entry))
6024 (save-excursion
6025 (if (or (looking-at re1)
6026 (re-search-backward re1 nil t))
6027 (progn
6028 (setq match-re1 (match-string 0))
6029 (setq beg (match-end 0)
6030 lang (org-edit-src-get-lang lang)
6031 lfmt (org-edit-src-get-label-format match-re1))
6032 (if (and (re-search-forward re2 nil t)
6033 (>= (match-end 0) pos))
6034 (throw 'exit (list beg (match-beginning 0)
6035 lang single lfmt))))
6036 (if (or (looking-at re2)
6037 (re-search-forward re2 nil t))
6038 (progn
6039 (setq end (match-beginning 0))
6040 (if (and (re-search-backward re1 nil t)
6041 (<= (match-beginning 0) pos))
6042 (progn
6043 (setq lfmt (org-edit-src-get-label-format
6044 (match-string 0)))
6045 (throw 'exit
6046 (list (match-end 0) end
6047 (org-edit-src-get-lang lang)
6048 single lfmt))))))))))))
6050 (defun org-edit-src-get-lang (lang)
6051 "Extract the src language."
6052 (let ((m (match-string 0)))
6053 (cond
6054 ((stringp lang) lang)
6055 ((integerp lang) (match-string lang))
6056 ((and (eq lang 'lang)
6057 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6058 (match-string 1 m))
6059 ((and (eq lang 'style)
6060 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6061 (match-string 1 m))
6062 (t "fundamental"))))
6064 (defun org-edit-src-get-label-format (s)
6065 "Extract the label format."
6066 (save-match-data
6067 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6068 (match-string 1 s))))
6070 (defun org-edit-src-exit ()
6071 "Exit special edit and protect problematic lines."
6072 (interactive)
6073 (unless (buffer-base-buffer (current-buffer))
6074 (error "This is not an indirect buffer, something is wrong..."))
6075 (unless (> (point-min) 1)
6076 (error "This buffer is not narrowed, something is wrong..."))
6077 (goto-char (point-min))
6078 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6079 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6080 (when (org-bound-and-true-p org-edit-src-force-single-line)
6081 (goto-char (point-min))
6082 (while (re-search-forward "\n" nil t)
6083 (replace-match " "))
6084 (goto-char (point-min))
6085 (if (looking-at "\\s-*") (replace-match " "))
6086 (if (re-search-forward "\\s-+\\'" nil t)
6087 (replace-match "")))
6088 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6089 (goto-char (point-min))
6090 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6091 (replace-match ",\\1"))
6092 (when font-lock-mode
6093 (font-lock-unfontify-region (point-min) (point-max)))
6094 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6095 (when (org-bound-and-true-p org-edit-src-picture)
6096 (untabify (point-min) (point-max))
6097 (goto-char (point-min))
6098 (while (re-search-forward "^" nil t)
6099 (replace-match ": "))
6100 (when font-lock-mode
6101 (font-lock-unfontify-region (point-min) (point-max)))
6102 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6103 (kill-buffer (current-buffer))
6104 (and (org-mode-p) (org-restart-font-lock)))
6107 ;;; The orgstruct minor mode
6109 ;; Define a minor mode which can be used in other modes in order to
6110 ;; integrate the org-mode structure editing commands.
6112 ;; This is really a hack, because the org-mode structure commands use
6113 ;; keys which normally belong to the major mode. Here is how it
6114 ;; works: The minor mode defines all the keys necessary to operate the
6115 ;; structure commands, but wraps the commands into a function which
6116 ;; tests if the cursor is currently at a headline or a plain list
6117 ;; item. If that is the case, the structure command is used,
6118 ;; temporarily setting many Org-mode variables like regular
6119 ;; expressions for filling etc. However, when any of those keys is
6120 ;; used at a different location, function uses `key-binding' to look
6121 ;; up if the key has an associated command in another currently active
6122 ;; keymap (minor modes, major mode, global), and executes that
6123 ;; command. There might be problems if any of the keys is otherwise
6124 ;; used as a prefix key.
6126 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6127 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6128 ;; addresses this by checking explicitly for both bindings.
6130 (defvar orgstruct-mode-map (make-sparse-keymap)
6131 "Keymap for the minor `orgstruct-mode'.")
6133 (defvar org-local-vars nil
6134 "List of local variables, for use by `orgstruct-mode'")
6136 ;;;###autoload
6137 (define-minor-mode orgstruct-mode
6138 "Toggle the minor more `orgstruct-mode'.
6139 This mode is for using Org-mode structure commands in other modes.
6140 The following key behave as if Org-mode was active, if the cursor
6141 is on a headline, or on a plain list item (both in the definition
6142 of Org-mode).
6144 M-up Move entry/item up
6145 M-down Move entry/item down
6146 M-left Promote
6147 M-right Demote
6148 M-S-up Move entry/item up
6149 M-S-down Move entry/item down
6150 M-S-left Promote subtree
6151 M-S-right Demote subtree
6152 M-q Fill paragraph and items like in Org-mode
6153 C-c ^ Sort entries
6154 C-c - Cycle list bullet
6155 TAB Cycle item visibility
6156 M-RET Insert new heading/item
6157 S-M-RET Insert new TODO heading / Checkbox item
6158 C-c C-c Set tags / toggle checkbox"
6159 nil " OrgStruct" nil
6160 (org-load-modules-maybe)
6161 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6163 ;;;###autoload
6164 (defun turn-on-orgstruct ()
6165 "Unconditionally turn on `orgstruct-mode'."
6166 (orgstruct-mode 1))
6168 ;;;###autoload
6169 (defun turn-on-orgstruct++ ()
6170 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6171 In addition to setting orgstruct-mode, this also exports all indentation and
6172 autofilling variables from org-mode into the buffer. Note that turning
6173 off orgstruct-mode will *not* remove these additional settings."
6174 (orgstruct-mode 1)
6175 (let (var val)
6176 (mapc
6177 (lambda (x)
6178 (when (string-match
6179 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6180 (symbol-name (car x)))
6181 (setq var (car x) val (nth 1 x))
6182 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6183 org-local-vars)))
6185 (defun orgstruct-error ()
6186 "Error when there is no default binding for a structure key."
6187 (interactive)
6188 (error "This key has no function outside structure elements"))
6190 (defun orgstruct-setup ()
6191 "Setup orgstruct keymaps."
6192 (let ((nfunc 0)
6193 (bindings
6194 (list
6195 '([(meta up)] org-metaup)
6196 '([(meta down)] org-metadown)
6197 '([(meta left)] org-metaleft)
6198 '([(meta right)] org-metaright)
6199 '([(meta shift up)] org-shiftmetaup)
6200 '([(meta shift down)] org-shiftmetadown)
6201 '([(meta shift left)] org-shiftmetaleft)
6202 '([(meta shift right)] org-shiftmetaright)
6203 '([(shift up)] org-shiftup)
6204 '([(shift down)] org-shiftdown)
6205 '([(shift left)] org-shiftleft)
6206 '([(shift right)] org-shiftright)
6207 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6208 '("\M-q" fill-paragraph)
6209 '("\C-c^" org-sort)
6210 '("\C-c-" org-cycle-list-bullet)))
6211 elt key fun cmd)
6212 (while (setq elt (pop bindings))
6213 (setq nfunc (1+ nfunc))
6214 (setq key (org-key (car elt))
6215 fun (nth 1 elt)
6216 cmd (orgstruct-make-binding fun nfunc key))
6217 (org-defkey orgstruct-mode-map key cmd))
6219 ;; Special treatment needed for TAB and RET
6220 (org-defkey orgstruct-mode-map [(tab)]
6221 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6222 (org-defkey orgstruct-mode-map "\C-i"
6223 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6225 (org-defkey orgstruct-mode-map "\M-\C-m"
6226 (orgstruct-make-binding 'org-insert-heading 105
6227 "\M-\C-m" [(meta return)]))
6228 (org-defkey orgstruct-mode-map [(meta return)]
6229 (orgstruct-make-binding 'org-insert-heading 106
6230 [(meta return)] "\M-\C-m"))
6232 (org-defkey orgstruct-mode-map [(shift meta return)]
6233 (orgstruct-make-binding 'org-insert-todo-heading 107
6234 [(meta return)] "\M-\C-m"))
6236 (unless org-local-vars
6237 (setq org-local-vars (org-get-local-variables)))
6241 (defun orgstruct-make-binding (fun n &rest keys)
6242 "Create a function for binding in the structure minor mode.
6243 FUN is the command to call inside a table. N is used to create a unique
6244 command name. KEYS are keys that should be checked in for a command
6245 to execute outside of tables."
6246 (eval
6247 (list 'defun
6248 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6249 '(arg)
6250 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6251 "Outside of structure, run the binding of `"
6252 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6253 "'.")
6254 '(interactive "p")
6255 (list 'if
6256 '(org-context-p 'headline 'item)
6257 (list 'org-run-like-in-org-mode (list 'quote fun))
6258 (list 'let '(orgstruct-mode)
6259 (list 'call-interactively
6260 (append '(or)
6261 (mapcar (lambda (k)
6262 (list 'key-binding k))
6263 keys)
6264 '('orgstruct-error))))))))
6266 (defun org-context-p (&rest contexts)
6267 "Check if local context is any of CONTEXTS.
6268 Possible values in the list of contexts are `table', `headline', and `item'."
6269 (let ((pos (point)))
6270 (goto-char (point-at-bol))
6271 (prog1 (or (and (memq 'table contexts)
6272 (looking-at "[ \t]*|"))
6273 (and (memq 'headline contexts)
6274 ;;????????? (looking-at "\\*+"))
6275 (looking-at outline-regexp))
6276 (and (memq 'item contexts)
6277 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6278 (goto-char pos))))
6280 (defun org-get-local-variables ()
6281 "Return a list of all local variables in an org-mode buffer."
6282 (let (varlist)
6283 (with-current-buffer (get-buffer-create "*Org tmp*")
6284 (erase-buffer)
6285 (org-mode)
6286 (setq varlist (buffer-local-variables)))
6287 (kill-buffer "*Org tmp*")
6288 (delq nil
6289 (mapcar
6290 (lambda (x)
6291 (setq x
6292 (if (symbolp x)
6293 (list x)
6294 (list (car x) (list 'quote (cdr x)))))
6295 (if (string-match
6296 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6297 (symbol-name (car x)))
6298 x nil))
6299 varlist))))
6301 ;;;###autoload
6302 (defun org-run-like-in-org-mode (cmd)
6303 (org-load-modules-maybe)
6304 (unless org-local-vars
6305 (setq org-local-vars (org-get-local-variables)))
6306 (eval (list 'let org-local-vars
6307 (list 'call-interactively (list 'quote cmd)))))
6309 ;;;; Archiving
6311 (defun org-get-category (&optional pos)
6312 "Get the category applying to position POS."
6313 (get-text-property (or pos (point)) 'org-category))
6315 (defun org-refresh-category-properties ()
6316 "Refresh category text properties in the buffer."
6317 (let ((def-cat (cond
6318 ((null org-category)
6319 (if buffer-file-name
6320 (file-name-sans-extension
6321 (file-name-nondirectory buffer-file-name))
6322 "???"))
6323 ((symbolp org-category) (symbol-name org-category))
6324 (t org-category)))
6325 beg end cat pos optionp)
6326 (org-unmodified
6327 (save-excursion
6328 (save-restriction
6329 (widen)
6330 (goto-char (point-min))
6331 (put-text-property (point) (point-max) 'org-category def-cat)
6332 (while (re-search-forward
6333 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6334 (setq pos (match-end 0)
6335 optionp (equal (char-after (match-beginning 0)) ?#)
6336 cat (org-trim (match-string 2)))
6337 (if optionp
6338 (setq beg (point-at-bol) end (point-max))
6339 (org-back-to-heading t)
6340 (setq beg (point) end (org-end-of-subtree t t)))
6341 (put-text-property beg end 'org-category cat)
6342 (goto-char pos)))))))
6345 ;;;; Link Stuff
6347 ;;; Link abbreviations
6349 (defun org-link-expand-abbrev (link)
6350 "Apply replacements as defined in `org-link-abbrev-alist."
6351 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6352 (let* ((key (match-string 1 link))
6353 (as (or (assoc key org-link-abbrev-alist-local)
6354 (assoc key org-link-abbrev-alist)))
6355 (tag (and (match-end 2) (match-string 3 link)))
6356 rpl)
6357 (if (not as)
6358 link
6359 (setq rpl (cdr as))
6360 (cond
6361 ((symbolp rpl) (funcall rpl tag))
6362 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6363 ((string-match "%h" rpl)
6364 (replace-match (url-hexify-string (or tag "")) t t rpl))
6365 (t (concat rpl tag)))))
6366 link))
6368 ;;; Storing and inserting links
6370 (defvar org-insert-link-history nil
6371 "Minibuffer history for links inserted with `org-insert-link'.")
6373 (defvar org-stored-links nil
6374 "Contains the links stored with `org-store-link'.")
6376 (defvar org-store-link-plist nil
6377 "Plist with info about the most recently link created with `org-store-link'.")
6379 (defvar org-link-protocols nil
6380 "Link protocols added to Org-mode using `org-add-link-type'.")
6382 (defvar org-store-link-functions nil
6383 "List of functions that are called to create and store a link.
6384 Each function will be called in turn until one returns a non-nil
6385 value. Each function should check if it is responsible for creating
6386 this link (for example by looking at the major mode).
6387 If not, it must exit and return nil.
6388 If yes, it should return a non-nil value after a calling
6389 `org-store-link-props' with a list of properties and values.
6390 Special properties are:
6392 :type The link prefix. like \"http\". This must be given.
6393 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6394 This is obligatory as well.
6395 :description Optional default description for the second pair
6396 of brackets in an Org-mode link. The user can still change
6397 this when inserting this link into an Org-mode buffer.
6399 In addition to these, any additional properties can be specified
6400 and then used in remember templates.")
6402 (defun org-add-link-type (type &optional follow export)
6403 "Add TYPE to the list of `org-link-types'.
6404 Re-compute all regular expressions depending on `org-link-types'
6406 FOLLOW and EXPORT are two functions.
6408 FOLLOW should take the link path as the single argument and do whatever
6409 is necessary to follow the link, for example find a file or display
6410 a mail message.
6412 EXPORT should format the link path for export to one of the export formats.
6413 It should be a function accepting three arguments:
6415 path the path of the link, the text after the prefix (like \"http:\")
6416 desc the description of the link, if any, nil if there was no description
6417 format the export format, a symbol like `html' or `latex'.
6419 The function may use the FORMAT information to return different values
6420 depending on the format. The return value will be put literally into
6421 the exported file.
6422 Org-mode has a built-in default for exporting links. If you are happy with
6423 this default, there is no need to define an export function for the link
6424 type. For a simple example of an export function, see `org-bbdb.el'."
6425 (add-to-list 'org-link-types type t)
6426 (org-make-link-regexps)
6427 (if (assoc type org-link-protocols)
6428 (setcdr (assoc type org-link-protocols) (list follow export))
6429 (push (list type follow export) org-link-protocols)))
6431 ;;;###autoload
6432 (defun org-store-link (arg)
6433 "\\<org-mode-map>Store an org-link to the current location.
6434 This link is added to `org-stored-links' and can later be inserted
6435 into an org-buffer with \\[org-insert-link].
6437 For some link types, a prefix arg is interpreted:
6438 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6439 For file links, arg negates `org-context-in-file-links'."
6440 (interactive "P")
6441 (org-load-modules-maybe)
6442 (setq org-store-link-plist nil) ; reset
6443 (let (link cpltxt desc description search txt)
6444 (cond
6446 ((run-hook-with-args-until-success 'org-store-link-functions)
6447 (setq link (plist-get org-store-link-plist :link)
6448 desc (or (plist-get org-store-link-plist :description) link)))
6450 ((equal (buffer-name) "*Org Edit Src Example*")
6451 (let (label gc)
6452 (while (or (not label)
6453 (save-excursion
6454 (save-restriction
6455 (widen)
6456 (goto-char (point-min))
6457 (re-search-forward
6458 (regexp-quote (format org-coderef-label-format label))
6459 nil t))))
6460 (when label (message "Label exists already") (sit-for 2))
6461 (setq label (read-string "Code line label: " label)))
6462 (end-of-line 1)
6463 (setq link (format org-coderef-label-format label))
6464 (setq gc (- 79 (length link)))
6465 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6466 (insert link)
6467 (setq link (concat "(" label ")") desc nil)))
6469 ((eq major-mode 'calendar-mode)
6470 (let ((cd (calendar-cursor-to-date)))
6471 (setq link
6472 (format-time-string
6473 (car org-time-stamp-formats)
6474 (apply 'encode-time
6475 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6476 nil nil nil))))
6477 (org-store-link-props :type "calendar" :date cd)))
6479 ((eq major-mode 'w3-mode)
6480 (setq cpltxt (url-view-url t)
6481 link (org-make-link cpltxt))
6482 (org-store-link-props :type "w3" :url (url-view-url t)))
6484 ((eq major-mode 'w3m-mode)
6485 (setq cpltxt (or w3m-current-title w3m-current-url)
6486 link (org-make-link w3m-current-url))
6487 (org-store-link-props :type "w3m" :url (url-view-url t)))
6489 ((setq search (run-hook-with-args-until-success
6490 'org-create-file-search-functions))
6491 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6492 "::" search))
6493 (setq cpltxt (or description link)))
6495 ((eq major-mode 'image-mode)
6496 (setq cpltxt (concat "file:"
6497 (abbreviate-file-name buffer-file-name))
6498 link (org-make-link cpltxt))
6499 (org-store-link-props :type "image" :file buffer-file-name))
6501 ((eq major-mode 'dired-mode)
6502 ;; link to the file in the current line
6503 (setq cpltxt (concat "file:"
6504 (abbreviate-file-name
6505 (expand-file-name
6506 (dired-get-filename nil t))))
6507 link (org-make-link cpltxt)))
6509 ((and buffer-file-name (org-mode-p))
6510 (cond
6511 ((org-in-regexp "<<\\(.*?\\)>>")
6512 (setq cpltxt
6513 (concat "file:"
6514 (abbreviate-file-name buffer-file-name)
6515 "::" (match-string 1))
6516 link (org-make-link cpltxt)))
6517 ((and (featurep 'org-id)
6518 (or (eq org-link-to-org-use-id t)
6519 (and (eq org-link-to-org-use-id 'create-if-interactive)
6520 (interactive-p))
6521 (and org-link-to-org-use-id
6522 (condition-case nil
6523 (org-entry-get nil "ID")
6524 (error nil)))))
6525 ;; We can make a link using the ID.
6526 (setq link (condition-case nil
6527 (prog1 (org-id-store-link)
6528 (setq desc (plist-get org-store-link-plist
6529 :description)))
6530 (error
6531 ;; probably before first headline, link to file only
6532 (concat "file:"
6533 (abbreviate-file-name buffer-file-name))))))
6535 ;; Just link to current headline
6536 (setq cpltxt (concat "file:"
6537 (abbreviate-file-name buffer-file-name)))
6538 ;; Add a context search string
6539 (when (org-xor org-context-in-file-links arg)
6540 (setq txt (cond
6541 ((org-on-heading-p) nil)
6542 ((org-region-active-p)
6543 (buffer-substring (region-beginning) (region-end)))
6544 (t nil)))
6545 (when (or (null txt) (string-match "\\S-" txt))
6546 (setq cpltxt
6547 (concat cpltxt "::"
6548 (condition-case nil
6549 (org-make-org-heading-search-string txt)
6550 (error "")))
6551 desc "NONE")))
6552 (if (string-match "::\\'" cpltxt)
6553 (setq cpltxt (substring cpltxt 0 -2)))
6554 (setq link (org-make-link cpltxt)))))
6556 ((buffer-file-name (buffer-base-buffer))
6557 ;; Just link to this file here.
6558 (setq cpltxt (concat "file:"
6559 (abbreviate-file-name
6560 (buffer-file-name (buffer-base-buffer)))))
6561 ;; Add a context string
6562 (when (org-xor org-context-in-file-links arg)
6563 (setq txt (if (org-region-active-p)
6564 (buffer-substring (region-beginning) (region-end))
6565 (buffer-substring (point-at-bol) (point-at-eol))))
6566 ;; Only use search option if there is some text.
6567 (when (string-match "\\S-" txt)
6568 (setq cpltxt
6569 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6570 desc "NONE")))
6571 (setq link (org-make-link cpltxt)))
6573 ((interactive-p)
6574 (error "Cannot link to a buffer which is not visiting a file"))
6576 (t (setq link nil)))
6578 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6579 (setq link (or link cpltxt)
6580 desc (or desc cpltxt))
6581 (if (equal desc "NONE") (setq desc nil))
6583 (if (and (interactive-p) link)
6584 (progn
6585 (setq org-stored-links
6586 (cons (list link desc) org-stored-links))
6587 (message "Stored: %s" (or desc link)))
6588 (and link (org-make-link-string link desc)))))
6590 (defun org-store-link-props (&rest plist)
6591 "Store link properties, extract names and addresses."
6592 (let (x adr)
6593 (when (setq x (plist-get plist :from))
6594 (setq adr (mail-extract-address-components x))
6595 (setq plist (plist-put plist :fromname (car adr)))
6596 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6597 (when (setq x (plist-get plist :to))
6598 (setq adr (mail-extract-address-components x))
6599 (setq plist (plist-put plist :toname (car adr)))
6600 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6601 (let ((from (plist-get plist :from))
6602 (to (plist-get plist :to)))
6603 (when (and from to org-from-is-user-regexp)
6604 (setq plist
6605 (plist-put plist :fromto
6606 (if (string-match org-from-is-user-regexp from)
6607 (concat "to %t")
6608 (concat "from %f"))))))
6609 (setq org-store-link-plist plist))
6611 (defun org-add-link-props (&rest plist)
6612 "Add these properties to the link property list."
6613 (let (key value)
6614 (while plist
6615 (setq key (pop plist) value (pop plist))
6616 (setq org-store-link-plist
6617 (plist-put org-store-link-plist key value)))))
6619 (defun org-email-link-description (&optional fmt)
6620 "Return the description part of an email link.
6621 This takes information from `org-store-link-plist' and formats it
6622 according to FMT (default from `org-email-link-description-format')."
6623 (setq fmt (or fmt org-email-link-description-format))
6624 (let* ((p org-store-link-plist)
6625 (to (plist-get p :toaddress))
6626 (from (plist-get p :fromaddress))
6627 (table
6628 (list
6629 (cons "%c" (plist-get p :fromto))
6630 (cons "%F" (plist-get p :from))
6631 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6632 (cons "%T" (plist-get p :to))
6633 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6634 (cons "%s" (plist-get p :subject))
6635 (cons "%m" (plist-get p :message-id)))))
6636 (when (string-match "%c" fmt)
6637 ;; Check if the user wrote this message
6638 (if (and org-from-is-user-regexp from to
6639 (save-match-data (string-match org-from-is-user-regexp from)))
6640 (setq fmt (replace-match "to %t" t t fmt))
6641 (setq fmt (replace-match "from %f" t t fmt))))
6642 (org-replace-escapes fmt table)))
6644 (defun org-make-org-heading-search-string (&optional string heading)
6645 "Make search string for STRING or current headline."
6646 (interactive)
6647 (let ((s (or string (org-get-heading))))
6648 (unless (and string (not heading))
6649 ;; We are using a headline, clean up garbage in there.
6650 (if (string-match org-todo-regexp s)
6651 (setq s (replace-match "" t t s)))
6652 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6653 (setq s (replace-match "" t t s)))
6654 (setq s (org-trim s))
6655 (if (string-match (concat "^\\(" org-quote-string "\\|"
6656 org-comment-string "\\)") s)
6657 (setq s (replace-match "" t t s)))
6658 (while (string-match org-ts-regexp s)
6659 (setq s (replace-match "" t t s))))
6660 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6661 (setq s (replace-match " " t t s)))
6662 (or string (setq s (concat "*" s))) ; Add * for headlines
6663 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6665 (defun org-make-link (&rest strings)
6666 "Concatenate STRINGS."
6667 (apply 'concat strings))
6669 (defun org-make-link-string (link &optional description)
6670 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6671 (unless (string-match "\\S-" link)
6672 (error "Empty link"))
6673 (when (stringp description)
6674 ;; Remove brackets from the description, they are fatal.
6675 (while (string-match "\\[" description)
6676 (setq description (replace-match "{" t t description)))
6677 (while (string-match "\\]" description)
6678 (setq description (replace-match "}" t t description))))
6679 (when (equal (org-link-escape link) description)
6680 ;; No description needed, it is identical
6681 (setq description nil))
6682 (when (and (not description)
6683 (not (equal link (org-link-escape link))))
6684 (setq description (org-extract-attributes link)))
6685 (concat "[[" (org-link-escape link) "]"
6686 (if description (concat "[" description "]") "")
6687 "]"))
6689 (defconst org-link-escape-chars
6690 '((?\ . "%20")
6691 (?\[ . "%5B")
6692 (?\] . "%5D")
6693 (?\340 . "%E0") ; `a
6694 (?\342 . "%E2") ; ^a
6695 (?\347 . "%E7") ; ,c
6696 (?\350 . "%E8") ; `e
6697 (?\351 . "%E9") ; 'e
6698 (?\352 . "%EA") ; ^e
6699 (?\356 . "%EE") ; ^i
6700 (?\364 . "%F4") ; ^o
6701 (?\371 . "%F9") ; `u
6702 (?\373 . "%FB") ; ^u
6703 (?\; . "%3B")
6704 (?? . "%3F")
6705 (?= . "%3D")
6706 (?+ . "%2B")
6708 "Association list of escapes for some characters problematic in links.
6709 This is the list that is used for internal purposes.")
6711 (defconst org-link-escape-chars-browser
6712 '((?\ . "%20")) ; 32 for the SPC char
6713 "Association list of escapes for some characters problematic in links.
6714 This is the list that is used before handing over to the browser.")
6716 (defun org-link-escape (text &optional table)
6717 "Escape characters in TEXT that are problematic for links."
6718 (setq table (or table org-link-escape-chars))
6719 (when text
6720 (let ((re (mapconcat (lambda (x) (regexp-quote
6721 (char-to-string (car x))))
6722 table "\\|")))
6723 (while (string-match re text)
6724 (setq text
6725 (replace-match
6726 (cdr (assoc (string-to-char (match-string 0 text))
6727 table))
6728 t t text)))
6729 text)))
6731 (defun org-link-unescape (text &optional table)
6732 "Reverse the action of `org-link-escape'."
6733 (setq table (or table org-link-escape-chars))
6734 (when text
6735 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6736 table "\\|")))
6737 (while (string-match re text)
6738 (setq text
6739 (replace-match
6740 (char-to-string (car (rassoc (match-string 0 text) table)))
6741 t t text)))
6742 text)))
6744 (defun org-xor (a b)
6745 "Exclusive or."
6746 (if a (not b) b))
6748 (defun org-fixup-message-id-for-http (s)
6749 "Replace special characters in a message id, so it can be used in an http query."
6750 (while (string-match "<" s)
6751 (setq s (replace-match "%3C" t t s)))
6752 (while (string-match ">" s)
6753 (setq s (replace-match "%3E" t t s)))
6754 (while (string-match "@" s)
6755 (setq s (replace-match "%40" t t s)))
6758 ;;;###autoload
6759 (defun org-insert-link-global ()
6760 "Insert a link like Org-mode does.
6761 This command can be called in any mode to insert a link in Org-mode syntax."
6762 (interactive)
6763 (org-load-modules-maybe)
6764 (org-run-like-in-org-mode 'org-insert-link))
6766 (defun org-insert-link (&optional complete-file link-location)
6767 "Insert a link. At the prompt, enter the link.
6769 Completion can be used to insert any of the link protocol prefixes like
6770 http or ftp in use.
6772 The history can be used to select a link previously stored with
6773 `org-store-link'. When the empty string is entered (i.e. if you just
6774 press RET at the prompt), the link defaults to the most recently
6775 stored link. As SPC triggers completion in the minibuffer, you need to
6776 use M-SPC or C-q SPC to force the insertion of a space character.
6778 You will also be prompted for a description, and if one is given, it will
6779 be displayed in the buffer instead of the link.
6781 If there is already a link at point, this command will allow you to edit link
6782 and description parts.
6784 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6785 be selected using completion. The path to the file will be relative to the
6786 current directory if the file is in the current directory or a subdirectory.
6787 Otherwise, the link will be the absolute path as completed in the minibuffer
6788 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6789 option `org-link-file-path-type'.
6791 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6792 the current directory or below.
6794 With three \\[universal-argument] prefixes, negate the meaning of
6795 `org-keep-stored-link-after-insertion'.
6797 If `org-make-link-description-function' is non-nil, this function will be
6798 called with the link target, and the result will be the default
6799 link description.
6801 If the LINK-LOCATION parameter is non-nil, this value will be
6802 used as the link location instead of reading one interactively."
6803 (interactive "P")
6804 (let* ((wcf (current-window-configuration))
6805 (region (if (org-region-active-p)
6806 (buffer-substring (region-beginning) (region-end))))
6807 (remove (and region (list (region-beginning) (region-end))))
6808 (desc region)
6809 tmphist ; byte-compile incorrectly complains about this
6810 (link link-location)
6811 entry file)
6812 (cond
6813 (link-location) ; specified by arg, just use it.
6814 ((org-in-regexp org-bracket-link-regexp 1)
6815 ;; We do have a link at point, and we are going to edit it.
6816 (setq remove (list (match-beginning 0) (match-end 0)))
6817 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6818 (setq link (read-string "Link: "
6819 (org-link-unescape
6820 (org-match-string-no-properties 1)))))
6821 ((or (org-in-regexp org-angle-link-re)
6822 (org-in-regexp org-plain-link-re))
6823 ;; Convert to bracket link
6824 (setq remove (list (match-beginning 0) (match-end 0))
6825 link (read-string "Link: "
6826 (org-remove-angle-brackets (match-string 0)))))
6827 ((member complete-file '((4) (16)))
6828 ;; Completing read for file names.
6829 (setq file (read-file-name "File: "))
6830 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6831 (pwd1 (file-name-as-directory (abbreviate-file-name
6832 (expand-file-name ".")))))
6833 (cond
6834 ((equal complete-file '(16))
6835 (setq link (org-make-link
6836 "file:"
6837 (abbreviate-file-name (expand-file-name file)))))
6838 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6839 (setq link (org-make-link "file:" (match-string 1 file))))
6840 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6841 (expand-file-name file))
6842 (setq link (org-make-link
6843 "file:" (match-string 1 (expand-file-name file)))))
6844 (t (setq link (org-make-link "file:" file))))))
6846 ;; Read link, with completion for stored links.
6847 (with-output-to-temp-buffer "*Org Links*"
6848 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6849 (when org-stored-links
6850 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6851 (princ (mapconcat
6852 (lambda (x)
6853 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6854 (reverse org-stored-links) "\n"))))
6855 (let ((cw (selected-window)))
6856 (select-window (get-buffer-window "*Org Links*"))
6857 (setq truncate-lines t)
6858 (org-fit-window-to-buffer)
6859 (select-window cw))
6860 ;; Fake a link history, containing the stored links.
6861 (setq tmphist (append (mapcar 'car org-stored-links)
6862 org-insert-link-history))
6863 (unwind-protect
6864 (setq link
6865 (let ((org-completion-use-ido nil))
6866 (org-completing-read
6867 "Link: "
6868 (append
6869 (mapcar (lambda (x) (list (concat (car x) ":")))
6870 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6871 (mapcar (lambda (x) (list (concat x ":")))
6872 org-link-types))
6873 nil nil nil
6874 'tmphist
6875 (or (car (car org-stored-links))))))
6876 (set-window-configuration wcf)
6877 (kill-buffer "*Org Links*"))
6878 (setq entry (assoc link org-stored-links))
6879 (or entry (push link org-insert-link-history))
6880 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6881 (not org-keep-stored-link-after-insertion))
6882 (setq org-stored-links (delq (assoc link org-stored-links)
6883 org-stored-links)))
6884 (setq desc (or desc (nth 1 entry)))))
6886 (if (string-match org-plain-link-re link)
6887 ;; URL-like link, normalize the use of angular brackets.
6888 (setq link (org-make-link (org-remove-angle-brackets link))))
6890 ;; Check if we are linking to the current file with a search option
6891 ;; If yes, simplify the link by using only the search option.
6892 (when (and buffer-file-name
6893 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6894 (let* ((path (match-string 1 link))
6895 (case-fold-search nil)
6896 (search (match-string 2 link)))
6897 (save-match-data
6898 (if (equal (file-truename buffer-file-name) (file-truename path))
6899 ;; We are linking to this same file, with a search option
6900 (setq link search)))))
6902 ;; Check if we can/should use a relative path. If yes, simplify the link
6903 (when (string-match "^file:\\(.*\\)" link)
6904 (let* ((path (match-string 1 link))
6905 (origpath path)
6906 (case-fold-search nil))
6907 (cond
6908 ((or (eq org-link-file-path-type 'absolute)
6909 (equal complete-file '(16)))
6910 (setq path (abbreviate-file-name (expand-file-name path))))
6911 ((eq org-link-file-path-type 'noabbrev)
6912 (setq path (expand-file-name path)))
6913 ((eq org-link-file-path-type 'relative)
6914 (setq path (file-relative-name path)))
6916 (save-match-data
6917 (if (string-match (concat "^" (regexp-quote
6918 (file-name-as-directory
6919 (expand-file-name "."))))
6920 (expand-file-name path))
6921 ;; We are linking a file with relative path name.
6922 (setq path (substring (expand-file-name path)
6923 (match-end 0)))
6924 (setq path (abbreviate-file-name (expand-file-name path)))))))
6925 (setq link (concat "file:" path))
6926 (if (equal desc origpath)
6927 (setq desc path))))
6929 (if org-make-link-description-function
6930 (setq desc (funcall org-make-link-description-function link desc)))
6932 (setq desc (read-string "Description: " desc))
6933 (unless (string-match "\\S-" desc) (setq desc nil))
6934 (if remove (apply 'delete-region remove))
6935 (insert (org-make-link-string link desc))))
6937 (defun org-completing-read (&rest args)
6938 "Completing-read with SPACE being a normal character."
6939 (let ((minibuffer-local-completion-map
6940 (copy-keymap minibuffer-local-completion-map)))
6941 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6942 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
6943 (apply 'org-ido-completing-read args)))
6945 (defun org-ido-completing-read (&rest args)
6946 "Completing-read using `ido-mode' speedups if available"
6947 (if (and org-completion-use-ido
6948 (fboundp 'ido-completing-read)
6949 (boundp 'ido-mode) ido-mode
6950 (listp (second args)))
6951 (apply 'ido-completing-read (concat (car args)) (cdr args))
6952 (apply 'completing-read args)))
6954 (defun org-extract-attributes (s)
6955 "Extract the attributes cookie from a string and set as text property."
6956 (let (a attr (start 0) key value)
6957 (save-match-data
6958 (when (string-match "{{\\([^}]+\\)}}$" s)
6959 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6960 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6961 (setq key (match-string 1 a) value (match-string 2 a)
6962 start (match-end 0)
6963 attr (plist-put attr (intern key) value))))
6964 (org-add-props s nil 'org-attr attr))
6967 (defun org-attributes-to-string (plist)
6968 "Format a property list into an HTML attribute list."
6969 (let ((s "") key value)
6970 (while plist
6971 (setq key (pop plist) value (pop plist))
6972 (and value
6973 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6976 ;;; Opening/following a link
6978 (defvar org-link-search-failed nil)
6980 (defun org-next-link ()
6981 "Move forward to the next link.
6982 If the link is in hidden text, expose it."
6983 (interactive)
6984 (when (and org-link-search-failed (eq this-command last-command))
6985 (goto-char (point-min))
6986 (message "Link search wrapped back to beginning of buffer"))
6987 (setq org-link-search-failed nil)
6988 (let* ((pos (point))
6989 (ct (org-context))
6990 (a (assoc :link ct)))
6991 (if a (goto-char (nth 2 a)))
6992 (if (re-search-forward org-any-link-re nil t)
6993 (progn
6994 (goto-char (match-beginning 0))
6995 (if (org-invisible-p) (org-show-context)))
6996 (goto-char pos)
6997 (setq org-link-search-failed t)
6998 (error "No further link found"))))
7000 (defun org-previous-link ()
7001 "Move backward to the previous link.
7002 If the link is in hidden text, expose it."
7003 (interactive)
7004 (when (and org-link-search-failed (eq this-command last-command))
7005 (goto-char (point-max))
7006 (message "Link search wrapped back to end of buffer"))
7007 (setq org-link-search-failed nil)
7008 (let* ((pos (point))
7009 (ct (org-context))
7010 (a (assoc :link ct)))
7011 (if a (goto-char (nth 1 a)))
7012 (if (re-search-backward org-any-link-re nil t)
7013 (progn
7014 (goto-char (match-beginning 0))
7015 (if (org-invisible-p) (org-show-context)))
7016 (goto-char pos)
7017 (setq org-link-search-failed t)
7018 (error "No further link found"))))
7020 (defun org-translate-link (s)
7021 "Translate a link string if a translation function has been defined."
7022 (if (and org-link-translation-function
7023 (fboundp org-link-translation-function)
7024 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7025 (progn
7026 (setq s (funcall org-link-translation-function
7027 (match-string 1) (match-string 2)))
7028 (concat (car s) ":" (cdr s)))
7031 (defun org-translate-link-from-planner (type path)
7032 "Translate a link from Emacs Planner syntax so that Org can follow it.
7033 This is still an experimental function, your mileage may vary."
7034 (cond
7035 ((member type '("http" "https" "news" "ftp"))
7036 ;; standard Internet links are the same.
7037 nil)
7038 ((and (equal type "irc") (string-match "^//" path))
7039 ;; Planner has two / at the beginning of an irc link, we have 1.
7040 ;; We should have zero, actually....
7041 (setq path (substring path 1)))
7042 ((and (equal type "lisp") (string-match "^/" path))
7043 ;; Planner has a slash, we do not.
7044 (setq type "elisp" path (substring path 1)))
7045 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7046 ;; A typical message link. Planner has the id after the fina slash,
7047 ;; we separate it with a hash mark
7048 (setq path (concat (match-string 1 path) "#"
7049 (org-remove-angle-brackets (match-string 2 path)))))
7051 (cons type path))
7053 (defun org-find-file-at-mouse (ev)
7054 "Open file link or URL at mouse."
7055 (interactive "e")
7056 (mouse-set-point ev)
7057 (org-open-at-point 'in-emacs))
7059 (defun org-open-at-mouse (ev)
7060 "Open file link or URL at mouse."
7061 (interactive "e")
7062 (mouse-set-point ev)
7063 (if (eq major-mode 'org-agenda-mode)
7064 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7065 (org-open-at-point))
7067 (defvar org-window-config-before-follow-link nil
7068 "The window configuration before following a link.
7069 This is saved in case the need arises to restore it.")
7071 (defvar org-open-link-marker (make-marker)
7072 "Marker pointing to the location where `org-open-at-point; was called.")
7074 ;;;###autoload
7075 (defun org-open-at-point-global ()
7076 "Follow a link like Org-mode does.
7077 This command can be called in any mode to follow a link that has
7078 Org-mode syntax."
7079 (interactive)
7080 (org-run-like-in-org-mode 'org-open-at-point))
7082 ;;;###autoload
7083 (defun org-open-link-from-string (s &optional arg)
7084 "Open a link in the string S, as if it was in Org-mode."
7085 (interactive "sLink: \nP")
7086 (with-temp-buffer
7087 (let ((org-inhibit-startup t))
7088 (org-mode)
7089 (insert s)
7090 (goto-char (point-min))
7091 (org-open-at-point arg))))
7093 (defun org-open-at-point (&optional in-emacs)
7094 "Open link at or after point.
7095 If there is no link at point, this function will search forward up to
7096 the end of the current subtree.
7097 Normally, files will be opened by an appropriate application. If the
7098 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7099 With a double prefix argument, try to open outside of Emacs, in the
7100 application the system uses for this file type."
7101 (interactive "P")
7102 (org-load-modules-maybe)
7103 (move-marker org-open-link-marker (point))
7104 (setq org-window-config-before-follow-link (current-window-configuration))
7105 (org-remove-occur-highlights nil nil t)
7106 (cond
7107 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7108 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7109 (org-footnote-action))
7111 (let (type path link line search (pos (point)))
7112 (catch 'match
7113 (save-excursion
7114 (skip-chars-forward "^]\n\r")
7115 (when (org-in-regexp org-bracket-link-regexp)
7116 (setq link (org-extract-attributes
7117 (org-link-unescape (org-match-string-no-properties 1))))
7118 (while (string-match " *\n *" link)
7119 (setq link (replace-match " " t t link)))
7120 (setq link (org-link-expand-abbrev link))
7121 (cond
7122 ((or (file-name-absolute-p link)
7123 (string-match "^\\.\\.?/" link))
7124 (setq type "file" path link))
7125 ((string-match org-link-re-with-space3 link)
7126 (setq type (match-string 1 link) path (match-string 2 link)))
7127 (t (setq type "thisfile" path link)))
7128 (throw 'match t)))
7130 (when (get-text-property (point) 'org-linked-text)
7131 (setq type "thisfile"
7132 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7133 (1+ (point)) (point))
7134 path (buffer-substring
7135 (previous-single-property-change pos 'org-linked-text)
7136 (next-single-property-change pos 'org-linked-text)))
7137 (throw 'match t))
7139 (save-excursion
7140 (when (or (org-in-regexp org-angle-link-re)
7141 (org-in-regexp org-plain-link-re))
7142 (setq type (match-string 1) path (match-string 2))
7143 (throw 'match t)))
7144 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7145 (setq type "tree-match"
7146 path (match-string 1))
7147 (throw 'match t))
7148 (save-excursion
7149 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7150 (setq type "tags"
7151 path (match-string 1))
7152 (while (string-match ":" path)
7153 (setq path (replace-match "+" t t path)))
7154 (throw 'match t))))
7155 (unless path
7156 (error "No link found"))
7157 ;; Remove any trailing spaces in path
7158 (if (string-match " +\\'" path)
7159 (setq path (replace-match "" t t path)))
7160 (if (and org-link-translation-function
7161 (fboundp org-link-translation-function))
7162 ;; Check if we need to translate the link
7163 (let ((tmp (funcall org-link-translation-function type path)))
7164 (setq type (car tmp) path (cdr tmp))))
7166 (cond
7168 ((assoc type org-link-protocols)
7169 (funcall (nth 1 (assoc type org-link-protocols)) path))
7171 ((equal type "mailto")
7172 (let ((cmd (car org-link-mailto-program))
7173 (args (cdr org-link-mailto-program)) args1
7174 (address path) (subject "") a)
7175 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7176 (setq address (match-string 1 path)
7177 subject (org-link-escape (match-string 2 path))))
7178 (while args
7179 (cond
7180 ((not (stringp (car args))) (push (pop args) args1))
7181 (t (setq a (pop args))
7182 (if (string-match "%a" a)
7183 (setq a (replace-match address t t a)))
7184 (if (string-match "%s" a)
7185 (setq a (replace-match subject t t a)))
7186 (push a args1))))
7187 (apply cmd (nreverse args1))))
7189 ((member type '("http" "https" "ftp" "news"))
7190 (browse-url (concat type ":" (org-link-escape
7191 path org-link-escape-chars-browser))))
7193 ((member type '("message"))
7194 (browse-url (concat type ":" path)))
7196 ((string= type "tags")
7197 (org-tags-view in-emacs path))
7198 ((string= type "thisfile")
7199 (if in-emacs
7200 (switch-to-buffer-other-window
7201 (org-get-buffer-for-internal-link (current-buffer)))
7202 (org-mark-ring-push))
7203 (let ((cmd `(org-link-search
7204 ,path
7205 ,(cond ((equal in-emacs '(4)) 'occur)
7206 ((equal in-emacs '(16)) 'org-occur)
7207 (t nil))
7208 ,pos)))
7209 (condition-case nil (eval cmd)
7210 (error (progn (widen) (eval cmd))))))
7212 ((string= type "tree-match")
7213 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7215 ((string= type "file")
7216 (if (string-match "::\\([0-9]+\\)\\'" path)
7217 (setq line (string-to-number (match-string 1 path))
7218 path (substring path 0 (match-beginning 0)))
7219 (if (string-match "::\\(.+\\)\\'" path)
7220 (setq search (match-string 1 path)
7221 path (substring path 0 (match-beginning 0)))))
7222 (if (string-match "[*?{]" (file-name-nondirectory path))
7223 (dired path)
7224 (org-open-file path in-emacs line search)))
7226 ((string= type "news")
7227 (require 'org-gnus)
7228 (org-gnus-follow-link path))
7230 ((string= type "shell")
7231 (let ((cmd path))
7232 (if (or (not org-confirm-shell-link-function)
7233 (funcall org-confirm-shell-link-function
7234 (format "Execute \"%s\" in shell? "
7235 (org-add-props cmd nil
7236 'face 'org-warning))))
7237 (progn
7238 (message "Executing %s" cmd)
7239 (shell-command cmd))
7240 (error "Abort"))))
7242 ((string= type "elisp")
7243 (let ((cmd path))
7244 (if (or (not org-confirm-elisp-link-function)
7245 (funcall org-confirm-elisp-link-function
7246 (format "Execute \"%s\" as elisp? "
7247 (org-add-props cmd nil
7248 'face 'org-warning))))
7249 (message "%s => %s" cmd
7250 (if (equal (string-to-char cmd) ?\()
7251 (eval (read cmd))
7252 (call-interactively (read cmd))))
7253 (error "Abort"))))
7256 (browse-url-at-point))))))
7257 (move-marker org-open-link-marker nil)
7258 (run-hook-with-args 'org-follow-link-hook))
7260 ;;;; Time estimates
7262 (defun org-get-effort (&optional pom)
7263 "Get the effort estimate for the current entry."
7264 (org-entry-get pom org-effort-property))
7266 ;;; File search
7268 (defvar org-create-file-search-functions nil
7269 "List of functions to construct the right search string for a file link.
7270 These functions are called in turn with point at the location to
7271 which the link should point.
7273 A function in the hook should first test if it would like to
7274 handle this file type, for example by checking the major-mode or
7275 the file extension. If it decides not to handle this file, it
7276 should just return nil to give other functions a chance. If it
7277 does handle the file, it must return the search string to be used
7278 when following the link. The search string will be part of the
7279 file link, given after a double colon, and `org-open-at-point'
7280 will automatically search for it. If special measures must be
7281 taken to make the search successful, another function should be
7282 added to the companion hook `org-execute-file-search-functions',
7283 which see.
7285 A function in this hook may also use `setq' to set the variable
7286 `description' to provide a suggestion for the descriptive text to
7287 be used for this link when it gets inserted into an Org-mode
7288 buffer with \\[org-insert-link].")
7290 (defvar org-execute-file-search-functions nil
7291 "List of functions to execute a file search triggered by a link.
7293 Functions added to this hook must accept a single argument, the
7294 search string that was part of the file link, the part after the
7295 double colon. The function must first check if it would like to
7296 handle this search, for example by checking the major-mode or the
7297 file extension. If it decides not to handle this search, it
7298 should just return nil to give other functions a chance. If it
7299 does handle the search, it must return a non-nil value to keep
7300 other functions from trying.
7302 Each function can access the current prefix argument through the
7303 variable `current-prefix-argument'. Note that a single prefix is
7304 used to force opening a link in Emacs, so it may be good to only
7305 use a numeric or double prefix to guide the search function.
7307 In case this is needed, a function in this hook can also restore
7308 the window configuration before `org-open-at-point' was called using:
7310 (set-window-configuration org-window-config-before-follow-link)")
7312 (defun org-link-search (s &optional type avoid-pos)
7313 "Search for a link search option.
7314 If S is surrounded by forward slashes, it is interpreted as a
7315 regular expression. In org-mode files, this will create an `org-occur'
7316 sparse tree. In ordinary files, `occur' will be used to list matches.
7317 If the current buffer is in `dired-mode', grep will be used to search
7318 in all files. If AVOID-POS is given, ignore matches near that position."
7319 (let ((case-fold-search t)
7320 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7321 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7322 (append '(("") (" ") ("\t") ("\n"))
7323 org-emphasis-alist)
7324 "\\|") "\\)"))
7325 (pos (point))
7326 (pre nil) (post nil)
7327 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7328 (cond
7329 ;; First check if there are any special
7330 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7331 ;; Now try the builtin stuff
7332 ((save-excursion
7333 (goto-char (point-min))
7334 (and
7335 (re-search-forward
7336 (concat "<<" (regexp-quote s0) ">>") nil t)
7337 (setq type 'dedicated
7338 pos (match-beginning 0))))
7339 ;; There is an exact target for this
7340 (goto-char pos))
7341 ((and (string-match "^(\\(.*\\))$" s0)
7342 (save-excursion
7343 (goto-char (point-min))
7344 (and
7345 (re-search-forward
7346 (concat "[^[]" (regexp-quote
7347 (format org-coderef-label-format
7348 (match-string 1 s0))))
7349 nil t)
7350 (setq type 'dedicated
7351 pos (1+ (match-beginning 0))))))
7352 ;; There is a coderef target for this
7353 (goto-char pos))
7354 ((string-match "^/\\(.*\\)/$" s)
7355 ;; A regular expression
7356 (cond
7357 ((org-mode-p)
7358 (org-occur (match-string 1 s)))
7359 ;;((eq major-mode 'dired-mode)
7360 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7361 (t (org-do-occur (match-string 1 s)))))
7363 ;; A normal search strings
7364 (when (equal (string-to-char s) ?*)
7365 ;; Anchor on headlines, post may include tags.
7366 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7367 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7368 s (substring s 1)))
7369 (remove-text-properties
7370 0 (length s)
7371 '(face nil mouse-face nil keymap nil fontified nil) s)
7372 ;; Make a series of regular expressions to find a match
7373 (setq words (org-split-string s "[ \n\r\t]+")
7375 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7376 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7377 "\\)" markers)
7378 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7379 re2a (concat "[ \t\r\n]" re2a_)
7380 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7381 re4 (concat "[^a-zA-Z_]" re4_)
7383 re1 (concat pre re2 post)
7384 re3 (concat pre (if pre re4_ re4) post)
7385 re5 (concat pre ".*" re4)
7386 re2 (concat pre re2)
7387 re2a (concat pre (if pre re2a_ re2a))
7388 re4 (concat pre (if pre re4_ re4))
7389 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7390 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7391 re5 "\\)"
7393 (cond
7394 ((eq type 'org-occur) (org-occur reall))
7395 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7396 (t (goto-char (point-min))
7397 (setq type 'fuzzy)
7398 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7399 (org-search-not-self 1 re1 nil t)
7400 (org-search-not-self 1 re2 nil t)
7401 (org-search-not-self 1 re2a nil t)
7402 (org-search-not-self 1 re3 nil t)
7403 (org-search-not-self 1 re4 nil t)
7404 (org-search-not-self 1 re5 nil t)
7406 (goto-char (match-beginning 1))
7407 (goto-char pos)
7408 (error "No match")))))
7410 ;; Normal string-search
7411 (goto-char (point-min))
7412 (if (search-forward s nil t)
7413 (goto-char (match-beginning 0))
7414 (error "No match"))))
7415 (and (org-mode-p) (org-show-context 'link-search))
7416 type))
7418 (defun org-search-not-self (group &rest args)
7419 "Execute `re-search-forward', but only accept matches that do not
7420 enclose the position of `org-open-link-marker'."
7421 (let ((m org-open-link-marker))
7422 (catch 'exit
7423 (while (apply 're-search-forward args)
7424 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7425 (goto-char (match-end group))
7426 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7427 (> (match-beginning 0) (marker-position m))
7428 (< (match-end 0) (marker-position m)))
7429 (save-match-data
7430 (or (not (org-in-regexp
7431 org-bracket-link-analytic-regexp 1))
7432 (not (match-end 4)) ; no description
7433 (and (<= (match-beginning 4) (point))
7434 (>= (match-end 4) (point))))))
7435 (throw 'exit (point))))))))
7437 (defun org-get-buffer-for-internal-link (buffer)
7438 "Return a buffer to be used for displaying the link target of internal links."
7439 (cond
7440 ((not org-display-internal-link-with-indirect-buffer)
7441 buffer)
7442 ((string-match "(Clone)$" (buffer-name buffer))
7443 (message "Buffer is already a clone, not making another one")
7444 ;; we also do not modify visibility in this case
7445 buffer)
7446 (t ; make a new indirect buffer for displaying the link
7447 (let* ((bn (buffer-name buffer))
7448 (ibn (concat bn "(Clone)"))
7449 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7450 (with-current-buffer ib (org-overview))
7451 ib))))
7453 (defun org-do-occur (regexp &optional cleanup)
7454 "Call the Emacs command `occur'.
7455 If CLEANUP is non-nil, remove the printout of the regular expression
7456 in the *Occur* buffer. This is useful if the regex is long and not useful
7457 to read."
7458 (occur regexp)
7459 (when cleanup
7460 (let ((cwin (selected-window)) win beg end)
7461 (when (setq win (get-buffer-window "*Occur*"))
7462 (select-window win))
7463 (goto-char (point-min))
7464 (when (re-search-forward "match[a-z]+" nil t)
7465 (setq beg (match-end 0))
7466 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7467 (setq end (1- (match-beginning 0)))))
7468 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7469 (goto-char (point-min))
7470 (select-window cwin))))
7472 ;;; The mark ring for links jumps
7474 (defvar org-mark-ring nil
7475 "Mark ring for positions before jumps in Org-mode.")
7476 (defvar org-mark-ring-last-goto nil
7477 "Last position in the mark ring used to go back.")
7478 ;; Fill and close the ring
7479 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7480 (loop for i from 1 to org-mark-ring-length do
7481 (push (make-marker) org-mark-ring))
7482 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7483 org-mark-ring)
7485 (defun org-mark-ring-push (&optional pos buffer)
7486 "Put the current position or POS into the mark ring and rotate it."
7487 (interactive)
7488 (setq pos (or pos (point)))
7489 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7490 (move-marker (car org-mark-ring)
7491 (or pos (point))
7492 (or buffer (current-buffer)))
7493 (message "%s"
7494 (substitute-command-keys
7495 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7497 (defun org-mark-ring-goto (&optional n)
7498 "Jump to the previous position in the mark ring.
7499 With prefix arg N, jump back that many stored positions. When
7500 called several times in succession, walk through the entire ring.
7501 Org-mode commands jumping to a different position in the current file,
7502 or to another Org-mode file, automatically push the old position
7503 onto the ring."
7504 (interactive "p")
7505 (let (p m)
7506 (if (eq last-command this-command)
7507 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7508 (setq p org-mark-ring))
7509 (setq org-mark-ring-last-goto p)
7510 (setq m (car p))
7511 (switch-to-buffer (marker-buffer m))
7512 (goto-char m)
7513 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7515 (defun org-remove-angle-brackets (s)
7516 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7517 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7519 (defun org-add-angle-brackets (s)
7520 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7521 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7523 (defun org-remove-double-quotes (s)
7524 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7525 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7528 ;;; Following specific links
7530 (defun org-follow-timestamp-link ()
7531 (cond
7532 ((org-at-date-range-p t)
7533 (let ((org-agenda-start-on-weekday)
7534 (t1 (match-string 1))
7535 (t2 (match-string 2)))
7536 (setq t1 (time-to-days (org-time-string-to-time t1))
7537 t2 (time-to-days (org-time-string-to-time t2)))
7538 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7539 ((org-at-timestamp-p t)
7540 (org-agenda-list nil (time-to-days (org-time-string-to-time
7541 (substring (match-string 1) 0 10)))
7543 (t (error "This should not happen"))))
7546 ;;; Following file links
7547 (defvar org-wait nil)
7548 (defun org-open-file (path &optional in-emacs line search)
7549 "Open the file at PATH.
7550 First, this expands any special file name abbreviations. Then the
7551 configuration variable `org-file-apps' is checked if it contains an
7552 entry for this file type, and if yes, the corresponding command is launched.
7554 If no application is found, Emacs simply visits the file.
7556 With optional prefix argument IN-EMACS, Emacs will visit the file.
7557 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7558 and o use an external application to visit the file.
7560 Optional LINE specifies a line to go to, optional SEARCH a string to
7561 search for. If LINE or SEARCH is given, the file will always be
7562 opened in Emacs.
7563 If the file does not exist, an error is thrown."
7564 (setq in-emacs (or in-emacs line search))
7565 (let* ((file (if (equal path "")
7566 buffer-file-name
7567 (substitute-in-file-name (expand-file-name path))))
7568 (apps (append org-file-apps (org-default-apps)))
7569 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7570 (dirp (if remp nil (file-directory-p file)))
7571 (file (if (and dirp org-open-directory-means-index-dot-org)
7572 (concat (file-name-as-directory file) "index.org")
7573 file))
7574 (a-m-a-p (assq 'auto-mode apps))
7575 (dfile (downcase file))
7576 (old-buffer (current-buffer))
7577 (old-pos (point))
7578 (old-mode major-mode)
7579 ext cmd)
7580 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7581 (setq ext (match-string 1 dfile))
7582 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7583 (setq ext (match-string 1 dfile))))
7584 (cond
7585 ((equal in-emacs '(16))
7586 (setq cmd (cdr (assoc 'system apps))))
7587 (in-emacs (setq cmd 'emacs))
7589 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7590 (and dirp (cdr (assoc 'directory apps)))
7591 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7592 'string-match)
7593 (cdr (assoc ext apps))
7594 (cdr (assoc t apps))))))
7595 (when (eq cmd 'system)
7596 (setq cmd (cdr (assoc 'system apps))))
7597 (when (eq cmd 'default)
7598 (setq cmd (cdr (assoc t apps))))
7599 (when (eq cmd 'mailcap)
7600 (require 'mailcap)
7601 (mailcap-parse-mailcaps)
7602 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7603 (command (mailcap-mime-info mime-type)))
7604 (if (stringp command)
7605 (setq cmd command)
7606 (setq cmd 'emacs))))
7607 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7608 (not (file-exists-p file))
7609 (not org-open-non-existing-files))
7610 (error "No such file: %s" file))
7611 (cond
7612 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7613 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7614 (while (string-match "['\"]%s['\"]" cmd)
7615 (setq cmd (replace-match "%s" t t cmd)))
7616 (while (string-match "%s" cmd)
7617 (setq cmd (replace-match
7618 (save-match-data
7619 (shell-quote-argument
7620 (convert-standard-filename file)))
7621 t t cmd)))
7622 (save-window-excursion
7623 (start-process-shell-command cmd nil cmd)
7624 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7626 ((or (stringp cmd)
7627 (eq cmd 'emacs))
7628 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7629 (widen)
7630 (if line (goto-line line)
7631 (if search (org-link-search search))))
7632 ((consp cmd)
7633 (let ((file (convert-standard-filename file)))
7634 (eval cmd)))
7635 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7636 (and (org-mode-p) (eq old-mode 'org-mode)
7637 (or (not (equal old-buffer (current-buffer)))
7638 (not (equal old-pos (point))))
7639 (org-mark-ring-push old-pos old-buffer))))
7641 (defun org-default-apps ()
7642 "Return the default applications for this operating system."
7643 (cond
7644 ((eq system-type 'darwin)
7645 org-file-apps-defaults-macosx)
7646 ((eq system-type 'windows-nt)
7647 org-file-apps-defaults-windowsnt)
7648 (t org-file-apps-defaults-gnu)))
7650 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7651 "Convert extensions to regular expressions in the cars of LIST.
7652 Also, weed out any non-string entries, because the return value is used
7653 only for regexp matching.
7654 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7655 point to the symbol `emacs', indicating that the file should
7656 be opened in Emacs."
7657 (append
7658 (delq nil
7659 (mapcar (lambda (x)
7660 (if (not (stringp (car x)))
7662 (if (string-match "\\W" (car x))
7664 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7665 list))
7666 (if add-auto-mode
7667 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7669 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7670 (defun org-file-remote-p (file)
7671 "Test whether FILE specifies a location on a remote system.
7672 Return non-nil if the location is indeed remote.
7674 For example, the filename \"/user@host:/foo\" specifies a location
7675 on the system \"/user@host:\"."
7676 (cond ((fboundp 'file-remote-p)
7677 (file-remote-p file))
7678 ((fboundp 'tramp-handle-file-remote-p)
7679 (tramp-handle-file-remote-p file))
7680 ((and (boundp 'ange-ftp-name-format)
7681 (string-match (car ange-ftp-name-format) file))
7683 (t nil)))
7686 ;;;; Refiling
7688 (defun org-get-org-file ()
7689 "Read a filename, with default directory `org-directory'."
7690 (let ((default (or org-default-notes-file remember-data-file)))
7691 (read-file-name (format "File name [%s]: " default)
7692 (file-name-as-directory org-directory)
7693 default)))
7695 (defun org-notes-order-reversed-p ()
7696 "Check if the current file should receive notes in reversed order."
7697 (cond
7698 ((not org-reverse-note-order) nil)
7699 ((eq t org-reverse-note-order) t)
7700 ((not (listp org-reverse-note-order)) nil)
7701 (t (catch 'exit
7702 (let ((all org-reverse-note-order)
7703 entry)
7704 (while (setq entry (pop all))
7705 (if (string-match (car entry) buffer-file-name)
7706 (throw 'exit (cdr entry))))
7707 nil)))))
7709 (defvar org-refile-target-table nil
7710 "The list of refile targets, created by `org-refile'.")
7712 (defvar org-agenda-new-buffers nil
7713 "Buffers created to visit agenda files.")
7715 (defun org-get-refile-targets (&optional default-buffer)
7716 "Produce a table with refile targets."
7717 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7718 targets txt re files f desc descre fast-path-p level)
7719 (message "Getting targets...")
7720 (with-current-buffer (or default-buffer (current-buffer))
7721 (while (setq entry (pop entries))
7722 (setq files (car entry) desc (cdr entry))
7723 (setq fast-path-p nil)
7724 (cond
7725 ((null files) (setq files (list (current-buffer))))
7726 ((eq files 'org-agenda-files)
7727 (setq files (org-agenda-files 'unrestricted)))
7728 ((and (symbolp files) (fboundp files))
7729 (setq files (funcall files)))
7730 ((and (symbolp files) (boundp files))
7731 (setq files (symbol-value files))))
7732 (if (stringp files) (setq files (list files)))
7733 (cond
7734 ((eq (car desc) :tag)
7735 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7736 ((eq (car desc) :todo)
7737 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7738 ((eq (car desc) :regexp)
7739 (setq descre (cdr desc)))
7740 ((eq (car desc) :level)
7741 (setq descre (concat "^\\*\\{" (number-to-string
7742 (if org-odd-levels-only
7743 (1- (* 2 (cdr desc)))
7744 (cdr desc)))
7745 "\\}[ \t]")))
7746 ((eq (car desc) :maxlevel)
7747 (setq fast-path-p t)
7748 (setq descre (concat "^\\*\\{1," (number-to-string
7749 (if org-odd-levels-only
7750 (1- (* 2 (cdr desc)))
7751 (cdr desc)))
7752 "\\}[ \t]")))
7753 (t (error "Bad refiling target description %s" desc)))
7754 (while (setq f (pop files))
7755 (save-excursion
7756 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7757 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7758 (setq f (expand-file-name f))
7759 (save-excursion
7760 (save-restriction
7761 (widen)
7762 (goto-char (point-min))
7763 (while (re-search-forward descre nil t)
7764 (goto-char (point-at-bol))
7765 (when (looking-at org-complex-heading-regexp)
7766 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7767 txt (org-link-display-format (match-string 4))
7768 re (concat "^" (regexp-quote
7769 (buffer-substring (match-beginning 1)
7770 (match-end 4)))))
7771 (if (match-end 5) (setq re (concat re "[ \t]+"
7772 (regexp-quote
7773 (match-string 5)))))
7774 (setq re (concat re "[ \t]*$"))
7775 (when org-refile-use-outline-path
7776 (setq txt (mapconcat 'org-protect-slash
7777 (append
7778 (if (eq org-refile-use-outline-path 'file)
7779 (list (file-name-nondirectory
7780 (buffer-file-name (buffer-base-buffer))))
7781 (if (eq org-refile-use-outline-path 'full-file-path)
7782 (list (buffer-file-name (buffer-base-buffer)))))
7783 (org-get-outline-path fast-path-p level txt)
7784 (list txt))
7785 "/")))
7786 (push (list txt f re (point)) targets))
7787 (goto-char (point-at-eol))))))))
7788 (message "Getting targets...done")
7789 (nreverse targets))))
7791 (defun org-protect-slash (s)
7792 (while (string-match "/" s)
7793 (setq s (replace-match "\\" t t s)))
7796 (defvar org-olpa (make-vector 20 nil))
7798 (defun org-get-outline-path (&optional fastp level heading)
7799 "Return the outline path to the current entry, as a list."
7800 (if fastp
7801 (progn
7802 (if (> level 19)
7803 (error "Outline path failure, more than 19 levels."))
7804 (loop for i from level upto 19 do
7805 (aset org-olpa i nil))
7806 (prog1
7807 (delq nil (append org-olpa nil))
7808 (aset org-olpa level heading)))
7809 (let (rtn)
7810 (save-excursion
7811 (while (org-up-heading-safe)
7812 (when (looking-at org-complex-heading-regexp)
7813 (push (org-match-string-no-properties 4) rtn)))
7814 rtn))))
7816 (defvar org-refile-history nil
7817 "History for refiling operations.")
7819 (defun org-refile (&optional goto default-buffer)
7820 "Move the entry at point to another heading.
7821 The list of target headings is compiled using the information in
7822 `org-refile-targets', which see. This list is created before each use
7823 and will therefore always be up-to-date.
7825 At the target location, the entry is filed as a subitem of the target heading.
7826 Depending on `org-reverse-note-order', the new subitem will either be the
7827 first or the last subitem.
7829 If there is an active region, all entries in that region will be moved.
7830 However, the region must fulfil the requirement that the first heading
7831 is the first one sets the top-level of the moved text - at most siblings
7832 below it are allowed.
7834 With prefix arg GOTO, the command will only visit the target location,
7835 not actually move anything.
7836 With a double prefix `C-u C-u', go to the location where the last refiling
7837 operation has put the subtree."
7838 (interactive "P")
7839 (let* ((cbuf (current-buffer))
7840 (regionp (org-region-active-p))
7841 (region-start (and regionp (region-beginning)))
7842 (region-end (and regionp (region-end)))
7843 (region-length (and regionp (- region-end region-start)))
7844 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7845 pos it nbuf file re level reversed)
7846 (when regionp (goto-char region-start)
7847 (unless (org-kill-is-subtree-p
7848 (buffer-substring region-start region-end))
7849 (error "The region is not a (sequence of) subtree(s)")))
7850 (if (equal goto '(16))
7851 (org-refile-goto-last-stored)
7852 (when (setq it (org-refile-get-location
7853 (if goto "Goto: " "Refile to: ") default-buffer))
7854 (setq file (nth 1 it)
7855 re (nth 2 it)
7856 pos (nth 3 it))
7857 (if (and (equal (buffer-file-name) file)
7858 (if regionp
7859 (and (>= pos region-start)
7860 (<= pos region-end))
7861 (and (>= pos (point))
7862 (< pos (save-excursion
7863 (org-end-of-subtree t t))))))
7864 (error "Cannot refile to position inside the tree or region"))
7866 (setq nbuf (or (find-buffer-visiting file)
7867 (find-file-noselect file)))
7868 (if goto
7869 (progn
7870 (switch-to-buffer nbuf)
7871 (goto-char pos)
7872 (org-show-context 'org-goto))
7873 (if regionp
7874 (progn
7875 (kill-new (buffer-substring region-start region-end))
7876 (org-save-markers-in-region region-start region-end))
7877 (org-copy-subtree 1 nil t))
7878 (save-excursion
7879 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7880 (find-file-noselect file))))
7881 (setq reversed (org-notes-order-reversed-p))
7882 (save-excursion
7883 (save-restriction
7884 (widen)
7885 (goto-char pos)
7886 (looking-at outline-regexp)
7887 (setq level (org-get-valid-level (funcall outline-level) 1))
7888 (goto-char
7889 (if reversed
7890 (or (outline-next-heading) (point-max))
7891 (or (save-excursion (outline-get-next-sibling))
7892 (org-end-of-subtree t t)
7893 (point-max))))
7894 (if (not (bolp)) (newline))
7895 (bookmark-set "org-refile-last-stored")
7896 (org-paste-subtree level))))
7897 (if regionp
7898 (delete-region (point) (+ (point) region-length))
7899 (org-cut-subtree))
7900 (setq org-markers-to-move nil)
7901 (message "Refiled to \"%s\"" (car it)))))))
7903 (defun org-refile-goto-last-stored ()
7904 "Go to the location where the last refile was stored."
7905 (interactive)
7906 (bookmark-jump "org-refile-last-stored")
7907 (message "This is the location of the last refile"))
7909 (defun org-refile-get-location (&optional prompt default-buffer)
7910 "Prompt the user for a refile location, using PROMPT."
7911 (let ((org-refile-targets org-refile-targets)
7912 (org-refile-use-outline-path org-refile-use-outline-path))
7913 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7914 (unless org-refile-target-table
7915 (error "No refile targets"))
7916 (let* ((cbuf (current-buffer))
7917 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7918 (cfunc (if (and org-refile-use-outline-path
7919 org-outline-path-complete-in-steps)
7920 'org-olpath-completing-read
7921 'org-ido-completing-read))
7922 (extra (if org-refile-use-outline-path "/" ""))
7923 (filename (and cfn (expand-file-name cfn)))
7924 (tbl (mapcar
7925 (lambda (x)
7926 (if (not (equal filename (nth 1 x)))
7927 (cons (concat (car x) extra " ("
7928 (file-name-nondirectory (nth 1 x)) ")")
7929 (cdr x))
7930 (cons (concat (car x) extra) (cdr x))))
7931 org-refile-target-table))
7932 (completion-ignore-case t))
7933 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7934 tbl)))
7936 (defun org-olpath-completing-read (prompt collection &rest args)
7937 "Read an outline path like a file name."
7938 (let ((thetable collection))
7939 (apply
7940 'org-ido-completing-read prompt
7941 (lambda (string predicate &optional flag)
7942 (let (rtn r f (l (length string)))
7943 (cond
7944 ((eq flag nil)
7945 ;; try completion
7946 (try-completion string thetable))
7947 ((eq flag t)
7948 ;; all-completions
7949 (setq rtn (all-completions string thetable predicate))
7950 (mapcar
7951 (lambda (x)
7952 (setq r (substring x l))
7953 (if (string-match " ([^)]*)$" x)
7954 (setq f (match-string 0 x))
7955 (setq f ""))
7956 (if (string-match "/" r)
7957 (concat string (substring r 0 (match-end 0)) f)
7959 rtn))
7960 ((eq flag 'lambda)
7961 ;; exact match?
7962 (assoc string thetable)))
7964 args)))
7966 ;;;; Dynamic blocks
7968 (defun org-find-dblock (name)
7969 "Find the first dynamic block with name NAME in the buffer.
7970 If not found, stay at current position and return nil."
7971 (let (pos)
7972 (save-excursion
7973 (goto-char (point-min))
7974 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7975 nil t)
7976 (match-beginning 0))))
7977 (if pos (goto-char pos))
7978 pos))
7980 (defconst org-dblock-start-re
7981 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7982 "Matches the startline of a dynamic block, with parameters.")
7984 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7985 "Matches the end of a dynamic block.")
7987 (defun org-create-dblock (plist)
7988 "Create a dynamic block section, with parameters taken from PLIST.
7989 PLIST must contain a :name entry which is used as name of the block."
7990 (unless (bolp) (newline))
7991 (let ((name (plist-get plist :name)))
7992 (insert "#+BEGIN: " name)
7993 (while plist
7994 (if (eq (car plist) :name)
7995 (setq plist (cddr plist))
7996 (insert " " (prin1-to-string (pop plist)))))
7997 (insert "\n\n#+END:\n")
7998 (beginning-of-line -2)))
8000 (defun org-prepare-dblock ()
8001 "Prepare dynamic block for refresh.
8002 This empties the block, puts the cursor at the insert position and returns
8003 the property list including an extra property :name with the block name."
8004 (unless (looking-at org-dblock-start-re)
8005 (error "Not at a dynamic block"))
8006 (let* ((begdel (1+ (match-end 0)))
8007 (name (org-no-properties (match-string 1)))
8008 (params (append (list :name name)
8009 (read (concat "(" (match-string 3) ")")))))
8010 (unless (re-search-forward org-dblock-end-re nil t)
8011 (error "Dynamic block not terminated"))
8012 (setq params
8013 (append params
8014 (list :content (buffer-substring
8015 begdel (match-beginning 0)))))
8016 (delete-region begdel (match-beginning 0))
8017 (goto-char begdel)
8018 (open-line 1)
8019 params))
8021 (defun org-map-dblocks (&optional command)
8022 "Apply COMMAND to all dynamic blocks in the current buffer.
8023 If COMMAND is not given, use `org-update-dblock'."
8024 (let ((cmd (or command 'org-update-dblock))
8025 pos)
8026 (save-excursion
8027 (goto-char (point-min))
8028 (while (re-search-forward org-dblock-start-re nil t)
8029 (goto-char (setq pos (match-beginning 0)))
8030 (condition-case nil
8031 (funcall cmd)
8032 (error (message "Error during update of dynamic block")))
8033 (goto-char pos)
8034 (unless (re-search-forward org-dblock-end-re nil t)
8035 (error "Dynamic block not terminated"))))))
8037 (defun org-dblock-update (&optional arg)
8038 "User command for updating dynamic blocks.
8039 Update the dynamic block at point. With prefix ARG, update all dynamic
8040 blocks in the buffer."
8041 (interactive "P")
8042 (if arg
8043 (org-update-all-dblocks)
8044 (or (looking-at org-dblock-start-re)
8045 (org-beginning-of-dblock))
8046 (org-update-dblock)))
8048 (defun org-update-dblock ()
8049 "Update the dynamic block at point
8050 This means to empty the block, parse for parameters and then call
8051 the correct writing function."
8052 (save-window-excursion
8053 (let* ((pos (point))
8054 (line (org-current-line))
8055 (params (org-prepare-dblock))
8056 (name (plist-get params :name))
8057 (cmd (intern (concat "org-dblock-write:" name))))
8058 (message "Updating dynamic block `%s' at line %d..." name line)
8059 (funcall cmd params)
8060 (message "Updating dynamic block `%s' at line %d...done" name line)
8061 (goto-char pos))))
8063 (defun org-beginning-of-dblock ()
8064 "Find the beginning of the dynamic block at point.
8065 Error if there is no such block at point."
8066 (let ((pos (point))
8067 beg)
8068 (end-of-line 1)
8069 (if (and (re-search-backward org-dblock-start-re nil t)
8070 (setq beg (match-beginning 0))
8071 (re-search-forward org-dblock-end-re nil t)
8072 (> (match-end 0) pos))
8073 (goto-char beg)
8074 (goto-char pos)
8075 (error "Not in a dynamic block"))))
8077 (defun org-update-all-dblocks ()
8078 "Update all dynamic blocks in the buffer.
8079 This function can be used in a hook."
8080 (when (org-mode-p)
8081 (org-map-dblocks 'org-update-dblock)))
8084 ;;;; Completion
8086 (defconst org-additional-option-like-keywords
8087 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8088 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8089 "BEGIN_EXAMPLE" "END_EXAMPLE"
8090 "BEGIN_QUOTE" "END_QUOTE"
8091 "BEGIN_VERSE" "END_VERSE"
8092 "BEGIN_SRC" "END_SRC"
8093 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8095 (defcustom org-structure-template-alist
8097 ("s" "#+begin_src ?\n\n#+end_src"
8098 "<src lang=\"?\">\n\n</src>")
8099 ("e" "#+begin_example\n?\n#+end_example"
8100 "<example>\n?\n</example>")
8101 ("q" "#+begin_quote\n?\n#+end_quote"
8102 "<quote>\n?\n</quote>")
8103 ("v" "#+begin_verse\n?\n#+end_verse"
8104 "<verse>\n?\n/verse>")
8105 ("l" "#+begin_latex\n?\n#+end_latex"
8106 "<literal style=\"latex\">\n?\n</literal>")
8107 ("L" "#+latex: "
8108 "<literal style=\"latex\">?</literal>")
8109 ("h" "#+begin_html\n?\n#+end_html"
8110 "<literal style=\"html\">\n?\n</literal>")
8111 ("H" "#+html: "
8112 "<literal style=\"html\">?</literal>")
8113 ("a" "#+begin_ascii\n?\n#+end_ascii")
8114 ("A" "#+ascii: ")
8115 ("i" "#+include %file ?"
8116 "<include file=%file markup=\"?\">")
8118 "Structure completion elements.
8119 This is a list of abbreviation keys and values. The value gets inserted
8120 it you type @samp{.} followed by the key and then the completion key,
8121 usually `M-TAB'. %file will be replaced by a file name after prompting
8122 for the file using completion.
8123 There are two templates for each key, the first uses the original Org syntax,
8124 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8125 the default when the /org-mtags.el/ module has been loaded. See also the
8126 variable `org-mtags-prefer-muse-templates'.
8127 This is an experimental feature, it is undecided if it is going to stay in."
8128 :group 'org-completion
8129 :type '(repeat
8130 (string :tag "Key")
8131 (string :tag "Template")
8132 (string :tag "Muse Template")))
8134 (defun org-try-structure-completion ()
8135 "Try to complete a structure template before point.
8136 This looks for strings like \"<e\" on an otherwise empty line and
8137 expands them."
8138 (let ((l (buffer-substring (point-at-bol) (point)))
8140 (when (and (looking-at "[ \t]*$")
8141 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8142 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8143 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8144 (match-beginning 1)) a)
8145 t)))
8147 (defun org-complete-expand-structure-template (start cell)
8148 "Expand a structure template."
8149 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8150 (rpl (nth (if musep 2 1) cell)))
8151 (delete-region start (point))
8152 (when (string-match "\\`#\\+" rpl)
8153 (cond
8154 ((bolp))
8155 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8156 (delete-region (point-at-bol) (point)))
8157 (t (newline))))
8158 (setq start (point))
8159 (if (string-match "%file" rpl)
8160 (setq rpl (replace-match
8161 (concat
8162 "\""
8163 (save-match-data
8164 (abbreviate-file-name (read-file-name "Include file: ")))
8165 "\"")
8166 t t rpl)))
8167 (insert rpl)
8168 (if (re-search-backward "\\?" start t) (delete-char 1))))
8171 (defun org-complete (&optional arg)
8172 "Perform completion on word at point.
8173 At the beginning of a headline, this completes TODO keywords as given in
8174 `org-todo-keywords'.
8175 If the current word is preceded by a backslash, completes the TeX symbols
8176 that are supported for HTML support.
8177 If the current word is preceded by \"#+\", completes special words for
8178 setting file options.
8179 In the line after \"#+STARTUP:, complete valid keywords.\"
8180 At all other locations, this simply calls the value of
8181 `org-completion-fallback-command'."
8182 (interactive "P")
8183 (org-without-partial-completion
8184 (catch 'exit
8185 (let* ((a nil)
8186 (end (point))
8187 (beg1 (save-excursion
8188 (skip-chars-backward (org-re "[:alnum:]_@"))
8189 (point)))
8190 (beg (save-excursion
8191 (skip-chars-backward "a-zA-Z0-9_:$")
8192 (point)))
8193 (confirm (lambda (x) (stringp (car x))))
8194 (searchhead (equal (char-before beg) ?*))
8195 (struct
8196 (when (and (member (char-before beg1) '(?. ?<))
8197 (setq a (assoc (buffer-substring beg1 (point))
8198 org-structure-template-alist)))
8199 (org-complete-expand-structure-template (1- beg1) a)
8200 (throw 'exit t)))
8201 (tag (and (equal (char-before beg1) ?:)
8202 (equal (char-after (point-at-bol)) ?*)))
8203 (prop (and (equal (char-before beg1) ?:)
8204 (not (equal (char-after (point-at-bol)) ?*))))
8205 (texp (equal (char-before beg) ?\\))
8206 (link (equal (char-before beg) ?\[))
8207 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8208 beg)
8209 "#+"))
8210 (startup (string-match "^#\\+STARTUP:.*"
8211 (buffer-substring (point-at-bol) (point))))
8212 (completion-ignore-case opt)
8213 (type nil)
8214 (tbl nil)
8215 (table (cond
8216 (opt
8217 (setq type :opt)
8218 (require 'org-exp)
8219 (append
8220 (mapcar
8221 (lambda (x)
8222 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8223 (cons (match-string 2 x) (match-string 1 x)))
8224 (org-split-string (org-get-current-options) "\n"))
8225 (mapcar 'list org-additional-option-like-keywords)))
8226 (startup
8227 (setq type :startup)
8228 org-startup-options)
8229 (link (append org-link-abbrev-alist-local
8230 org-link-abbrev-alist))
8231 (texp
8232 (setq type :tex)
8233 org-html-entities)
8234 ((string-match "\\`\\*+[ \t]+\\'"
8235 (buffer-substring (point-at-bol) beg))
8236 (setq type :todo)
8237 (mapcar 'list org-todo-keywords-1))
8238 (searchhead
8239 (setq type :searchhead)
8240 (save-excursion
8241 (goto-char (point-min))
8242 (while (re-search-forward org-todo-line-regexp nil t)
8243 (push (list
8244 (org-make-org-heading-search-string
8245 (match-string 3) t))
8246 tbl)))
8247 tbl)
8248 (tag (setq type :tag beg beg1)
8249 (or org-tag-alist (org-get-buffer-tags)))
8250 (prop (setq type :prop beg beg1)
8251 (mapcar 'list (org-buffer-property-keys nil t t)))
8252 (t (progn
8253 (call-interactively org-completion-fallback-command)
8254 (throw 'exit nil)))))
8255 (pattern (buffer-substring-no-properties beg end))
8256 (completion (try-completion pattern table confirm)))
8257 (cond ((eq completion t)
8258 (if (not (assoc (upcase pattern) table))
8259 (message "Already complete")
8260 (if (and (equal type :opt)
8261 (not (member (car (assoc (upcase pattern) table))
8262 org-additional-option-like-keywords)))
8263 (insert (substring (cdr (assoc (upcase pattern) table))
8264 (length pattern)))
8265 (if (memq type '(:tag :prop)) (insert ":")))))
8266 ((null completion)
8267 (message "Can't find completion for \"%s\"" pattern)
8268 (ding))
8269 ((not (string= pattern completion))
8270 (delete-region beg end)
8271 (if (string-match " +$" completion)
8272 (setq completion (replace-match "" t t completion)))
8273 (insert completion)
8274 (if (get-buffer-window "*Completions*")
8275 (delete-window (get-buffer-window "*Completions*")))
8276 (if (assoc completion table)
8277 (if (eq type :todo) (insert " ")
8278 (if (memq type '(:tag :prop)) (insert ":"))))
8279 (if (and (equal type :opt) (assoc completion table))
8280 (message "%s" (substitute-command-keys
8281 "Press \\[org-complete] again to insert example settings"))))
8283 (message "Making completion list...")
8284 (let ((list (sort (all-completions pattern table confirm)
8285 'string<)))
8286 (with-output-to-temp-buffer "*Completions*"
8287 (condition-case nil
8288 ;; Protection needed for XEmacs and emacs 21
8289 (display-completion-list list pattern)
8290 (error (display-completion-list list)))))
8291 (message "Making completion list...%s" "done")))))))
8293 ;;;; TODO, DEADLINE, Comments
8295 (defun org-toggle-comment ()
8296 "Change the COMMENT state of an entry."
8297 (interactive)
8298 (save-excursion
8299 (org-back-to-heading)
8300 (let (case-fold-search)
8301 (if (looking-at (concat outline-regexp
8302 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8303 (replace-match "" t t nil 1)
8304 (if (looking-at outline-regexp)
8305 (progn
8306 (goto-char (match-end 0))
8307 (insert org-comment-string " ")))))))
8309 (defvar org-last-todo-state-is-todo nil
8310 "This is non-nil when the last TODO state change led to a TODO state.
8311 If the last change removed the TODO tag or switched to DONE, then
8312 this is nil.")
8314 (defvar org-setting-tags nil) ; dynamically skipped
8316 (defun org-parse-local-options (string var)
8317 "Parse STRING for startup setting relevant for variable VAR."
8318 (let ((rtn (symbol-value var))
8319 e opts)
8320 (save-match-data
8321 (if (or (not string) (not (string-match "\\S-" string)))
8323 (setq opts (delq nil (mapcar (lambda (x)
8324 (setq e (assoc x org-startup-options))
8325 (if (eq (nth 1 e) var) e nil))
8326 (org-split-string string "[ \t]+"))))
8327 (if (not opts)
8329 (setq rtn nil)
8330 (while (setq e (pop opts))
8331 (if (not (nth 3 e))
8332 (setq rtn (nth 2 e))
8333 (if (not (listp rtn)) (setq rtn nil))
8334 (push (nth 2 e) rtn)))
8335 rtn)))))
8337 (defvar org-agenda-headline-snapshot-before-repeat)
8338 (defun org-todo (&optional arg)
8339 "Change the TODO state of an item.
8340 The state of an item is given by a keyword at the start of the heading,
8341 like
8342 *** TODO Write paper
8343 *** DONE Call mom
8345 The different keywords are specified in the variable `org-todo-keywords'.
8346 By default the available states are \"TODO\" and \"DONE\".
8347 So for this example: when the item starts with TODO, it is changed to DONE.
8348 When it starts with DONE, the DONE is removed. And when neither TODO nor
8349 DONE are present, add TODO at the beginning of the heading.
8351 With C-u prefix arg, use completion to determine the new state.
8352 With numeric prefix arg, switch to that state.
8353 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8354 With a tripple C-u prefix, circumvent any state blocking.
8356 For calling through lisp, arg is also interpreted in the following way:
8357 'none -> empty state
8358 \"\"(empty string) -> switch to empty state
8359 'done -> switch to DONE
8360 'nextset -> switch to the next set of keywords
8361 'previousset -> switch to the previous set of keywords
8362 \"WAITING\" -> switch to the specified keyword, but only if it
8363 really is a member of `org-todo-keywords'."
8364 (interactive "P")
8365 (if (equal arg '(16)) (setq arg 'nextset))
8366 (let ((org-blocker-hook org-blocker-hook))
8367 (when (equal arg '(64))
8368 (setq arg nil org-blocker-hook nil))
8369 (save-excursion
8370 (catch 'exit
8371 (org-back-to-heading)
8372 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8373 (or (looking-at (concat " +" org-todo-regexp " *"))
8374 (looking-at " *"))
8375 (let* ((match-data (match-data))
8376 (startpos (point-at-bol))
8377 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8378 (org-log-done org-log-done)
8379 (org-log-repeat org-log-repeat)
8380 (org-todo-log-states org-todo-log-states)
8381 (this (match-string 1))
8382 (hl-pos (match-beginning 0))
8383 (head (org-get-todo-sequence-head this))
8384 (ass (assoc head org-todo-kwd-alist))
8385 (interpret (nth 1 ass))
8386 (done-word (nth 3 ass))
8387 (final-done-word (nth 4 ass))
8388 (last-state (or this ""))
8389 (completion-ignore-case t)
8390 (member (member this org-todo-keywords-1))
8391 (tail (cdr member))
8392 (state (cond
8393 ((and org-todo-key-trigger
8394 (or (and (equal arg '(4))
8395 (eq org-use-fast-todo-selection 'prefix))
8396 (and (not arg) org-use-fast-todo-selection
8397 (not (eq org-use-fast-todo-selection
8398 'prefix)))))
8399 ;; Use fast selection
8400 (org-fast-todo-selection))
8401 ((and (equal arg '(4))
8402 (or (not org-use-fast-todo-selection)
8403 (not org-todo-key-trigger)))
8404 ;; Read a state with completion
8405 (org-ido-completing-read
8406 "State: " (mapcar (lambda(x) (list x))
8407 org-todo-keywords-1)
8408 nil t))
8409 ((eq arg 'right)
8410 (if this
8411 (if tail (car tail) nil)
8412 (car org-todo-keywords-1)))
8413 ((eq arg 'left)
8414 (if (equal member org-todo-keywords-1)
8416 (if this
8417 (nth (- (length org-todo-keywords-1)
8418 (length tail) 2)
8419 org-todo-keywords-1)
8420 (org-last org-todo-keywords-1))))
8421 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8422 (setq arg nil))) ; hack to fall back to cycling
8423 (arg
8424 ;; user or caller requests a specific state
8425 (cond
8426 ((equal arg "") nil)
8427 ((eq arg 'none) nil)
8428 ((eq arg 'done) (or done-word (car org-done-keywords)))
8429 ((eq arg 'nextset)
8430 (or (car (cdr (member head org-todo-heads)))
8431 (car org-todo-heads)))
8432 ((eq arg 'previousset)
8433 (let ((org-todo-heads (reverse org-todo-heads)))
8434 (or (car (cdr (member head org-todo-heads)))
8435 (car org-todo-heads))))
8436 ((car (member arg org-todo-keywords-1)))
8437 ((nth (1- (prefix-numeric-value arg))
8438 org-todo-keywords-1))))
8439 ((null member) (or head (car org-todo-keywords-1)))
8440 ((equal this final-done-word) nil) ;; -> make empty
8441 ((null tail) nil) ;; -> first entry
8442 ((eq interpret 'sequence)
8443 (car tail))
8444 ((memq interpret '(type priority))
8445 (if (eq this-command last-command)
8446 (car tail)
8447 (if (> (length tail) 0)
8448 (or done-word (car org-done-keywords))
8449 nil)))
8450 (t nil)))
8451 (next (if state (concat " " state " ") " "))
8452 (change-plist (list :type 'todo-state-change :from this :to state
8453 :position startpos))
8454 dolog now-done-p)
8455 (when org-blocker-hook
8456 (setq org-last-todo-state-is-todo
8457 (not (member this org-done-keywords)))
8458 (unless (save-excursion
8459 (save-match-data
8460 (run-hook-with-args-until-failure
8461 'org-blocker-hook change-plist)))
8462 (if (interactive-p)
8463 (error "TODO state change from %s to %s blocked" this state)
8464 ;; fail silently
8465 (message "TODO state change from %s to %s blocked" this state)
8466 (throw 'exit nil))))
8467 (store-match-data match-data)
8468 (replace-match next t t)
8469 (unless (pos-visible-in-window-p hl-pos)
8470 (message "TODO state changed to %s" (org-trim next)))
8471 (unless head
8472 (setq head (org-get-todo-sequence-head state)
8473 ass (assoc head org-todo-kwd-alist)
8474 interpret (nth 1 ass)
8475 done-word (nth 3 ass)
8476 final-done-word (nth 4 ass)))
8477 (when (memq arg '(nextset previousset))
8478 (message "Keyword-Set %d/%d: %s"
8479 (- (length org-todo-sets) -1
8480 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8481 (length org-todo-sets)
8482 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8483 (setq org-last-todo-state-is-todo
8484 (not (member state org-done-keywords)))
8485 (setq now-done-p (and (member state org-done-keywords)
8486 (not (member this org-done-keywords))))
8487 (and logging (org-local-logging logging))
8488 (when (and (or org-todo-log-states org-log-done)
8489 (not (memq arg '(nextset previousset))))
8490 ;; we need to look at recording a time and note
8491 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8492 (nth 2 (assoc this org-todo-log-states))))
8493 (when (and state
8494 (member state org-not-done-keywords)
8495 (not (member this org-not-done-keywords)))
8496 ;; This is now a todo state and was not one before
8497 ;; If there was a CLOSED time stamp, get rid of it.
8498 (org-add-planning-info nil nil 'closed))
8499 (when (and now-done-p org-log-done)
8500 ;; It is now done, and it was not done before
8501 (org-add-planning-info 'closed (org-current-time))
8502 (if (and (not dolog) (eq 'note org-log-done))
8503 (org-add-log-setup 'done state 'findpos 'note)))
8504 (when (and state dolog)
8505 ;; This is a non-nil state, and we need to log it
8506 (org-add-log-setup 'state state 'findpos dolog)))
8507 ;; Fixup tag positioning
8508 (org-todo-trigger-tag-changes state)
8509 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8510 (when org-provide-todo-statistics
8511 (org-update-parent-todo-statistics))
8512 (run-hooks 'org-after-todo-state-change-hook)
8513 (if (and arg (not (member state org-done-keywords)))
8514 (setq head (org-get-todo-sequence-head state)))
8515 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8516 ;; Do we need to trigger a repeat?
8517 (when now-done-p
8518 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8519 ;; This is for the agenda, take a snapshot of the headline.
8520 (save-match-data
8521 (setq org-agenda-headline-snapshot-before-repeat
8522 (org-get-heading))))
8523 (org-auto-repeat-maybe state))
8524 ;; Fixup cursor location if close to the keyword
8525 (if (and (outline-on-heading-p)
8526 (not (bolp))
8527 (save-excursion (beginning-of-line 1)
8528 (looking-at org-todo-line-regexp))
8529 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8530 (progn
8531 (goto-char (or (match-end 2) (match-end 1)))
8532 (just-one-space)))
8533 (when org-trigger-hook
8534 (save-excursion
8535 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8537 (defun org-block-todo-from-children-or-siblings (change-plist)
8538 "Block turning an entry into a TODO, using the hierarchy.
8539 This checks whether the current task should be blocked from state
8540 changes. Such blocking occurs when:
8542 1. The task has children which are not all in a completed state.
8544 2. A task has a parent with the property :ORDERED:, and there
8545 are siblings prior to the current task with incomplete
8546 status."
8547 (catch 'dont-block
8548 ;; If this is not a todo state change, or if this entry is already DONE,
8549 ;; do not block
8550 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8551 (member (plist-get change-plist :from)
8552 (cons 'done org-done-keywords))
8553 (member (plist-get change-plist :to)
8554 (cons 'todo org-not-done-keywords)))
8555 (throw 'dont-block t))
8556 ;; If this task has children, and any are undone, it's blocked
8557 (save-excursion
8558 (org-back-to-heading t)
8559 (let ((this-level (funcall outline-level)))
8560 (outline-next-heading)
8561 (let ((child-level (funcall outline-level)))
8562 (while (and (not (eobp))
8563 (> child-level this-level))
8564 ;; this todo has children, check whether they are all
8565 ;; completed
8566 (if (and (not (org-entry-is-done-p))
8567 (org-entry-is-todo-p))
8568 (throw 'dont-block nil))
8569 (outline-next-heading)
8570 (setq child-level (funcall outline-level))))))
8571 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8572 ;; any previous siblings are undone, it's blocked
8573 (save-excursion
8574 (org-back-to-heading t)
8575 (when (save-excursion
8576 (ignore-errors
8577 (outline-up-heading 1)
8578 (org-entry-get (point) "ORDERED")))
8579 (let* ((this-level (funcall outline-level))
8580 (current-level this-level))
8581 (while (and (not (bobp))
8582 (= current-level this-level))
8583 (outline-previous-heading)
8584 (setq current-level (funcall outline-level))
8585 (if (= current-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 t)) ; don't block
8593 (defun org-toggle-ordered-property ()
8594 "Toggle the ORDERED property of the current entry."
8595 (interactive)
8596 (save-excursion
8597 (org-back-to-heading)
8598 (if (org-entry-get nil "ORDERED")
8599 (progn
8600 (org-delete-property "ORDERED")
8601 (message "Subtasks can be completed in arbitrary order or parallel"))
8602 (org-entry-put nil "ORDERED" "t")
8603 (message "Subtasks must be completed in sequence"))))
8605 (defun org-block-todo-from-checkboxes (change-plist)
8606 "Block turning an entry into a TODO, using checkboxes.
8607 This checks whether the current task should be blocked from state
8608 changes because there are uncheckd boxes in this entry."
8609 (catch 'dont-block
8610 ;; If this is not a todo state change, or if this entry is already DONE,
8611 ;; do not block
8612 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8613 (member (plist-get change-plist :from)
8614 (cons 'done org-done-keywords))
8615 (member (plist-get change-plist :to)
8616 (cons 'todo org-not-done-keywords)))
8617 (throw 'dont-block t))
8618 ;; If this task has checkboxes that are not checked, it's blocked
8619 (save-excursion
8620 (org-back-to-heading t)
8621 (let ((beg (point)) end)
8622 (outline-next-heading)
8623 (setq end (point))
8624 (goto-char beg)
8625 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8626 end t)
8627 (throw 'dont-block nil))))
8628 t)) ; do not block
8630 (defun org-update-parent-todo-statistics ()
8631 "Update any statistics cookie in the parent of the current headline."
8632 (interactive)
8633 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8634 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8635 (catch 'exit
8636 (save-excursion
8637 (setq level (org-up-heading-safe))
8638 (unless level
8639 (throw 'exit nil))
8640 (while (re-search-forward box-re (point-at-eol) t)
8641 (setq is-percent (match-end 2))
8642 (save-match-data
8643 (unless (outline-next-heading) (throw 'exit nil))
8644 (while (looking-at org-todo-line-regexp)
8645 (setq kwd (match-string 2))
8646 (and kwd (setq cnt-all (1+ cnt-all)))
8647 (and (member kwd org-done-keywords)
8648 (setq cnt-done (1+ cnt-done)))
8649 (condition-case nil
8650 (org-forward-same-level 1)
8651 (error (end-of-line 1)))))
8652 (replace-match
8653 (if is-percent
8654 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8655 (format "[%d/%d]" cnt-done cnt-all))))
8656 (run-hook-with-args 'org-after-todo-statistics-hook
8657 cnt-done (- cnt-all cnt-done))))))
8659 (defvar org-after-todo-statistics-hook nil
8660 "Hook that is called after a TODO statistics cookie has been updated.
8661 Each function is called with two arguments: the number of not-done entries
8662 and the number of done entries.
8664 For example, the following function, when added to this hook, will switch
8665 an entry to DONE when all children are done, and back to TODO when new
8666 entries are set to a TODO status. Note that this hook is only called
8667 when there is a statistics cookie in the headline!
8669 (defun org-summary-todo (n-done n-not-done)
8670 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8671 (let (org-log-done org-log-states) ; turn off logging
8672 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8675 (defun org-todo-trigger-tag-changes (state)
8676 "Apply the changes defined in `org-todo-state-tags-triggers'."
8677 (let ((l org-todo-state-tags-triggers)
8678 changes)
8679 (when (or (not state) (equal state ""))
8680 (setq changes (append changes (cdr (assoc "" l)))))
8681 (when (and (stringp state) (> (length state) 0))
8682 (setq changes (append changes (cdr (assoc state l)))))
8683 (when (member state org-not-done-keywords)
8684 (setq changes (append changes (cdr (assoc 'todo l)))))
8685 (when (member state org-done-keywords)
8686 (setq changes (append changes (cdr (assoc 'done l)))))
8687 (dolist (c changes)
8688 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8690 (defun org-local-logging (value)
8691 "Get logging settings from a property VALUE."
8692 (let* (words w a)
8693 ;; directly set the variables, they are already local.
8694 (setq org-log-done nil
8695 org-log-repeat nil
8696 org-todo-log-states nil)
8697 (setq words (org-split-string value))
8698 (while (setq w (pop words))
8699 (cond
8700 ((setq a (assoc w org-startup-options))
8701 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8702 (set (nth 1 a) (nth 2 a))))
8703 ((setq a (org-extract-log-state-settings w))
8704 (and (member (car a) org-todo-keywords-1)
8705 (push a org-todo-log-states)))))))
8707 (defun org-get-todo-sequence-head (kwd)
8708 "Return the head of the TODO sequence to which KWD belongs.
8709 If KWD is not set, check if there is a text property remembering the
8710 right sequence."
8711 (let (p)
8712 (cond
8713 ((not kwd)
8714 (or (get-text-property (point-at-bol) 'org-todo-head)
8715 (progn
8716 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8717 nil (point-at-eol)))
8718 (get-text-property p 'org-todo-head))))
8719 ((not (member kwd org-todo-keywords-1))
8720 (car org-todo-keywords-1))
8721 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8723 (defun org-fast-todo-selection ()
8724 "Fast TODO keyword selection with single keys.
8725 Returns the new TODO keyword, or nil if no state change should occur."
8726 (let* ((fulltable org-todo-key-alist)
8727 (done-keywords org-done-keywords) ;; needed for the faces.
8728 (maxlen (apply 'max (mapcar
8729 (lambda (x)
8730 (if (stringp (car x)) (string-width (car x)) 0))
8731 fulltable)))
8732 (expert nil)
8733 (fwidth (+ maxlen 3 1 3))
8734 (ncol (/ (- (window-width) 4) fwidth))
8735 tg cnt e c tbl
8736 groups ingroup)
8737 (save-excursion
8738 (save-window-excursion
8739 (if expert
8740 (set-buffer (get-buffer-create " *Org todo*"))
8741 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8742 (erase-buffer)
8743 (org-set-local 'org-done-keywords done-keywords)
8744 (setq tbl fulltable cnt 0)
8745 (while (setq e (pop tbl))
8746 (cond
8747 ((equal e '(:startgroup))
8748 (push '() groups) (setq ingroup t)
8749 (when (not (= cnt 0))
8750 (setq cnt 0)
8751 (insert "\n"))
8752 (insert "{ "))
8753 ((equal e '(:endgroup))
8754 (setq ingroup nil cnt 0)
8755 (insert "}\n"))
8757 (setq tg (car e) c (cdr e))
8758 (if ingroup (push tg (car groups)))
8759 (setq tg (org-add-props tg nil 'face
8760 (org-get-todo-face tg)))
8761 (if (and (= cnt 0) (not ingroup)) (insert " "))
8762 (insert "[" c "] " tg (make-string
8763 (- fwidth 4 (length tg)) ?\ ))
8764 (when (= (setq cnt (1+ cnt)) ncol)
8765 (insert "\n")
8766 (if ingroup (insert " "))
8767 (setq cnt 0)))))
8768 (insert "\n")
8769 (goto-char (point-min))
8770 (if (not expert) (org-fit-window-to-buffer))
8771 (message "[a-z..]:Set [SPC]:clear")
8772 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8773 (cond
8774 ((or (= c ?\C-g)
8775 (and (= c ?q) (not (rassoc c fulltable))))
8776 (setq quit-flag t))
8777 ((= c ?\ ) nil)
8778 ((setq e (rassoc c fulltable) tg (car e))
8780 (t (setq quit-flag t)))))))
8782 (defun org-entry-is-todo-p ()
8783 (member (org-get-todo-state) org-not-done-keywords))
8785 (defun org-entry-is-done-p ()
8786 (member (org-get-todo-state) org-done-keywords))
8788 (defun org-get-todo-state ()
8789 (save-excursion
8790 (org-back-to-heading t)
8791 (and (looking-at org-todo-line-regexp)
8792 (match-end 2)
8793 (match-string 2))))
8795 (defun org-at-date-range-p (&optional inactive-ok)
8796 "Is the cursor inside a date range?"
8797 (interactive)
8798 (save-excursion
8799 (catch 'exit
8800 (let ((pos (point)))
8801 (skip-chars-backward "^[<\r\n")
8802 (skip-chars-backward "<[")
8803 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8804 (>= (match-end 0) pos)
8805 (throw 'exit t))
8806 (skip-chars-backward "^<[\r\n")
8807 (skip-chars-backward "<[")
8808 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8809 (>= (match-end 0) pos)
8810 (throw 'exit t)))
8811 nil)))
8813 (defun org-get-repeat ()
8814 "Check if there is a deadline/schedule with repeater in this entry."
8815 (save-match-data
8816 (save-excursion
8817 (org-back-to-heading t)
8818 (if (re-search-forward
8819 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8820 (match-string 1)))))
8822 (defvar org-last-changed-timestamp)
8823 (defvar org-last-inserted-timestamp)
8824 (defvar org-log-post-message)
8825 (defvar org-log-note-purpose)
8826 (defvar org-log-note-how)
8827 (defvar org-log-note-extra)
8828 (defun org-auto-repeat-maybe (done-word)
8829 "Check if the current headline contains a repeated deadline/schedule.
8830 If yes, set TODO state back to what it was and change the base date
8831 of repeating deadline/scheduled time stamps to new date.
8832 This function is run automatically after each state change to a DONE state."
8833 ;; last-state is dynamically scoped into this function
8834 (let* ((repeat (org-get-repeat))
8835 (aa (assoc last-state org-todo-kwd-alist))
8836 (interpret (nth 1 aa))
8837 (head (nth 2 aa))
8838 (whata '(("d" . day) ("m" . month) ("y" . year)))
8839 (msg "Entry repeats: ")
8840 (org-log-done nil)
8841 (org-todo-log-states nil)
8842 (nshiftmax 10) (nshift 0)
8843 re type n what ts time)
8844 (when repeat
8845 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8846 (org-todo (if (eq interpret 'type) last-state head))
8847 (when org-log-repeat
8848 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8849 (memq 'org-add-log-note post-command-hook))
8850 ;; OK, we are already setup for some record
8851 (if (eq org-log-repeat 'note)
8852 ;; make sure we take a note, not only a time stamp
8853 (setq org-log-note-how 'note))
8854 ;; Set up for taking a record
8855 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8856 'findpos org-log-repeat)))
8857 (org-back-to-heading t)
8858 (org-add-planning-info nil nil 'closed)
8859 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8860 org-deadline-time-regexp "\\)\\|\\("
8861 org-ts-regexp "\\)"))
8862 (while (re-search-forward
8863 re (save-excursion (outline-next-heading) (point)) t)
8864 (setq type (if (match-end 1) org-scheduled-string
8865 (if (match-end 3) org-deadline-string "Plain:"))
8866 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
8867 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8868 (setq n (string-to-number (match-string 2 ts))
8869 what (match-string 3 ts))
8870 (if (equal what "w") (setq n (* n 7) what "d"))
8871 ;; Preparation, see if we need to modify the start date for the change
8872 (when (match-end 1)
8873 (setq time (save-match-data (org-time-string-to-time ts)))
8874 (cond
8875 ((equal (match-string 1 ts) ".")
8876 ;; Shift starting date to today
8877 (org-timestamp-change
8878 (- (time-to-days (current-time)) (time-to-days time))
8879 'day))
8880 ((equal (match-string 1 ts) "+")
8881 (while (or (= nshift 0)
8882 (<= (time-to-days time) (time-to-days (current-time))))
8883 (when (= (incf nshift) nshiftmax)
8884 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8885 (error "Abort")))
8886 (org-timestamp-change n (cdr (assoc what whata)))
8887 (org-at-timestamp-p t)
8888 (setq ts (match-string 1))
8889 (setq time (save-match-data (org-time-string-to-time ts))))
8890 (org-timestamp-change (- n) (cdr (assoc what whata)))
8891 ;; rematch, so that we have everything in place for the real shift
8892 (org-at-timestamp-p t)
8893 (setq ts (match-string 1))
8894 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8895 (org-timestamp-change n (cdr (assoc what whata)))
8896 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8897 (setq org-log-post-message msg)
8898 (message "%s" msg))))
8900 (defun org-show-todo-tree (arg)
8901 "Make a compact tree which shows all headlines marked with TODO.
8902 The tree will show the lines where the regexp matches, and all higher
8903 headlines above the match.
8904 With a \\[universal-argument] prefix, also show the DONE entries.
8905 With a numeric prefix N, construct a sparse tree for the Nth element
8906 of `org-todo-keywords-1'."
8907 (interactive "P")
8908 (let ((case-fold-search nil)
8909 (kwd-re
8910 (cond ((null arg) org-not-done-regexp)
8911 ((equal arg '(4))
8912 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8913 (mapcar 'list org-todo-keywords-1))))
8914 (concat "\\("
8915 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8916 "\\)\\>")))
8917 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8918 (regexp-quote (nth (1- (prefix-numeric-value arg))
8919 org-todo-keywords-1)))
8920 (t (error "Invalid prefix argument: %s" arg)))))
8921 (message "%d TODO entries found"
8922 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8924 (defun org-deadline (&optional remove time)
8925 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8926 With argument REMOVE, remove any deadline from the item.
8927 When TIME is set, it should be an internal time specification, and the
8928 scheduling will use the corresponding date."
8929 (interactive "P")
8930 (if remove
8931 (progn
8932 (org-remove-timestamp-with-keyword org-deadline-string)
8933 (message "Item no longer has a deadline."))
8934 (if (org-get-repeat)
8935 (error "Cannot change deadline on task with repeater, please do that by hand")
8936 (org-add-planning-info 'deadline time 'closed)
8937 (message "Deadline on %s" org-last-inserted-timestamp))))
8939 (defun org-schedule (&optional remove time)
8940 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8941 With argument REMOVE, remove any scheduling date from the item.
8942 When TIME is set, it should be an internal time specification, and the
8943 scheduling will use the corresponding date."
8944 (interactive "P")
8945 (if remove
8946 (progn
8947 (org-remove-timestamp-with-keyword org-scheduled-string)
8948 (message "Item is no longer scheduled."))
8949 (if (org-get-repeat)
8950 (error "Cannot reschedule task with repeater, please do that by hand")
8951 (org-add-planning-info 'scheduled time 'closed)
8952 (message "Scheduled to %s" org-last-inserted-timestamp))))
8954 (defun org-remove-timestamp-with-keyword (keyword)
8955 "Remove all time stamps with KEYWORD in the current entry."
8956 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8957 beg)
8958 (save-excursion
8959 (org-back-to-heading t)
8960 (setq beg (point))
8961 (org-end-of-subtree t t)
8962 (while (re-search-backward re beg t)
8963 (replace-match "")
8964 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8965 (equal (char-before) ?\ ))
8966 (backward-delete-char 1)
8967 (if (string-match "^[ \t]*$" (buffer-substring
8968 (point-at-bol) (point-at-eol)))
8969 (delete-region (point-at-bol)
8970 (min (point-max) (1+ (point-at-eol))))))))))
8972 (defun org-add-planning-info (what &optional time &rest remove)
8973 "Insert new timestamp with keyword in the line directly after the headline.
8974 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8975 If non is given, the user is prompted for a date.
8976 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8977 be removed."
8978 (interactive)
8979 (let (org-time-was-given org-end-time-was-given ts
8980 end default-time default-input)
8982 (when (and (not time) (memq what '(scheduled deadline)))
8983 ;; Try to get a default date/time from existing timestamp
8984 (save-excursion
8985 (org-back-to-heading t)
8986 (setq end (save-excursion (outline-next-heading) (point)))
8987 (when (re-search-forward (if (eq what 'scheduled)
8988 org-scheduled-time-regexp
8989 org-deadline-time-regexp)
8990 end t)
8991 (setq ts (match-string 1)
8992 default-time
8993 (apply 'encode-time (org-parse-time-string ts))
8994 default-input (and ts (org-get-compact-tod ts))))))
8995 (when what
8996 ;; If necessary, get the time from the user
8997 (setq time (or time (org-read-date nil 'to-time nil nil
8998 default-time default-input))))
9000 (when (and org-insert-labeled-timestamps-at-point
9001 (member what '(scheduled deadline)))
9002 (insert
9003 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9004 (org-insert-time-stamp time org-time-was-given
9005 nil nil nil (list org-end-time-was-given))
9006 (setq what nil))
9007 (save-excursion
9008 (save-restriction
9009 (let (col list elt ts buffer-invisibility-spec)
9010 (org-back-to-heading t)
9011 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9012 (goto-char (match-end 1))
9013 (setq col (current-column))
9014 (goto-char (match-end 0))
9015 (if (eobp) (insert "\n") (forward-char 1))
9016 (if (and (not (looking-at outline-regexp))
9017 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9018 "[^\r\n]*"))
9019 (not (equal (match-string 1) org-clock-string)))
9020 (narrow-to-region (match-beginning 0) (match-end 0))
9021 (insert-before-markers "\n")
9022 (backward-char 1)
9023 (narrow-to-region (point) (point))
9024 (and org-adapt-indentation (org-indent-to-column col)))
9025 ;; Check if we have to remove something.
9026 (setq list (cons what remove))
9027 (while list
9028 (setq elt (pop list))
9029 (goto-char (point-min))
9030 (when (or (and (eq elt 'scheduled)
9031 (re-search-forward org-scheduled-time-regexp nil t))
9032 (and (eq elt 'deadline)
9033 (re-search-forward org-deadline-time-regexp nil t))
9034 (and (eq elt 'closed)
9035 (re-search-forward org-closed-time-regexp nil t)))
9036 (replace-match "")
9037 (if (looking-at "--+<[^>]+>") (replace-match ""))
9038 (if (looking-at " +") (replace-match ""))))
9039 (goto-char (point-max))
9040 (when what
9041 (insert
9042 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9043 (cond ((eq what 'scheduled) org-scheduled-string)
9044 ((eq what 'deadline) org-deadline-string)
9045 ((eq what 'closed) org-closed-string))
9046 " ")
9047 (setq ts (org-insert-time-stamp
9048 time
9049 (or org-time-was-given
9050 (and (eq what 'closed) org-log-done-with-time))
9051 (eq what 'closed)
9052 nil nil (list org-end-time-was-given)))
9053 (end-of-line 1))
9054 (goto-char (point-min))
9055 (widen)
9056 (if (and (looking-at "[ \t]+\n")
9057 (equal (char-before) ?\n))
9058 (delete-region (1- (point)) (point-at-eol)))
9059 ts)))))
9061 (defvar org-log-note-marker (make-marker))
9062 (defvar org-log-note-purpose nil)
9063 (defvar org-log-note-state nil)
9064 (defvar org-log-note-how nil)
9065 (defvar org-log-note-extra nil)
9066 (defvar org-log-note-window-configuration nil)
9067 (defvar org-log-note-return-to (make-marker))
9068 (defvar org-log-post-message nil
9069 "Message to be displayed after a log note has been stored.
9070 The auto-repeater uses this.")
9072 (defun org-add-note ()
9073 "Add a note to the current entry.
9074 This is done in the same way as adding a state change note."
9075 (interactive)
9076 (org-add-log-setup 'note nil 'findpos nil))
9078 (defvar org-property-end-re)
9079 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
9080 "Set up the post command hook to take a note.
9081 If this is about to TODO state change, the new state is expected in STATE.
9082 When FINDPOS is non-nil, find the correct position for the note in
9083 the current entry. If not, assume that it can be inserted at point.
9084 HOW is an indicator what kind of note should be created.
9085 EXTRA is additional text that will be inserted into the notes buffer."
9086 (save-restriction
9087 (save-excursion
9088 (when findpos
9089 (org-back-to-heading t)
9090 (narrow-to-region (point) (save-excursion
9091 (outline-next-heading) (point)))
9092 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9093 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9094 "[^\r\n]*\\)?"))
9095 (goto-char (match-end 0))
9096 (when (and org-log-state-notes-insert-after-drawers
9097 (save-excursion
9098 (forward-line) (looking-at org-drawer-regexp)))
9099 (progn (forward-line)
9100 (while (looking-at org-drawer-regexp)
9101 (goto-char (match-end 0))
9102 (re-search-forward org-property-end-re (point-max) t)
9103 (forward-line))
9104 (forward-line -1)))
9105 (unless org-log-states-order-reversed
9106 (and (= (char-after) ?\n) (forward-char 1))
9107 (org-skip-over-state-notes)
9108 (skip-chars-backward " \t\n\r")))
9109 (move-marker org-log-note-marker (point))
9110 (setq org-log-note-purpose purpose
9111 org-log-note-state state
9112 org-log-note-how how
9113 org-log-note-extra extra)
9114 (add-hook 'post-command-hook 'org-add-log-note 'append))))
9116 (defun org-skip-over-state-notes ()
9117 "Skip past the list of State notes in an entry."
9118 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9119 (while (looking-at "[ \t]*- State")
9120 (condition-case nil
9121 (org-next-item)
9122 (error (org-end-of-item)))))
9124 (defun org-add-log-note (&optional purpose)
9125 "Pop up a window for taking a note, and add this note later at point."
9126 (remove-hook 'post-command-hook 'org-add-log-note)
9127 (setq org-log-note-window-configuration (current-window-configuration))
9128 (delete-other-windows)
9129 (move-marker org-log-note-return-to (point))
9130 (switch-to-buffer (marker-buffer org-log-note-marker))
9131 (goto-char org-log-note-marker)
9132 (org-switch-to-buffer-other-window "*Org Note*")
9133 (erase-buffer)
9134 (if (memq org-log-note-how '(time state))
9135 (let (current-prefix-arg) (org-store-log-note))
9136 (let ((org-inhibit-startup t)) (org-mode))
9137 (insert (format "# Insert note for %s.
9138 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9139 (cond
9140 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9141 ((eq org-log-note-purpose 'done) "closed todo item")
9142 ((eq org-log-note-purpose 'state)
9143 (format "state change to \"%s\"" org-log-note-state))
9144 ((eq org-log-note-purpose 'note)
9145 "this entry")
9146 (t (error "This should not happen")))))
9147 (if org-log-note-extra (insert org-log-note-extra))
9148 (org-set-local 'org-finish-function 'org-store-log-note)))
9150 (defvar org-note-abort nil) ; dynamically scoped
9151 (defun org-store-log-note ()
9152 "Finish taking a log note, and insert it to where it belongs."
9153 (let ((txt (buffer-string))
9154 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9155 lines ind)
9156 (kill-buffer (current-buffer))
9157 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9158 (setq txt (replace-match "" t t txt)))
9159 (if (string-match "\\s-+\\'" txt)
9160 (setq txt (replace-match "" t t txt)))
9161 (setq lines (org-split-string txt "\n"))
9162 (when (and note (string-match "\\S-" note))
9163 (setq note
9164 (org-replace-escapes
9165 note
9166 (list (cons "%u" (user-login-name))
9167 (cons "%U" user-full-name)
9168 (cons "%t" (format-time-string
9169 (org-time-stamp-format 'long 'inactive)
9170 (current-time)))
9171 (cons "%s" (if org-log-note-state
9172 (concat "\"" org-log-note-state "\"")
9173 "")))))
9174 (if lines (setq note (concat note " \\\\")))
9175 (push note lines))
9176 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9177 (when lines
9178 (save-excursion
9179 (set-buffer (marker-buffer org-log-note-marker))
9180 (save-excursion
9181 (goto-char org-log-note-marker)
9182 (move-marker org-log-note-marker nil)
9183 (end-of-line 1)
9184 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9185 (indent-relative nil)
9186 (insert "- " (pop lines))
9187 (org-indent-line-function)
9188 (beginning-of-line 1)
9189 (looking-at "[ \t]*")
9190 (setq ind (concat (match-string 0) " "))
9191 (end-of-line 1)
9192 (while lines (insert "\n" ind (pop lines)))))))
9193 (set-window-configuration org-log-note-window-configuration)
9194 (with-current-buffer (marker-buffer org-log-note-return-to)
9195 (goto-char org-log-note-return-to))
9196 (move-marker org-log-note-return-to nil)
9197 (and org-log-post-message (message "%s" org-log-post-message)))
9199 (defun org-sparse-tree (&optional arg)
9200 "Create a sparse tree, prompt for the details.
9201 This command can create sparse trees. You first need to select the type
9202 of match used to create the tree:
9204 t Show entries with a specific TODO keyword.
9205 T Show entries selected by a tags match.
9206 p Enter a property name and its value (both with completion on existing
9207 names/values) and show entries with that property.
9208 r Show entries matching a regular expression
9209 d Show deadlines due within `org-deadline-warning-days'."
9210 (interactive "P")
9211 (let (ans kwd value)
9212 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9213 (setq ans (read-char-exclusive))
9214 (cond
9215 ((equal ans ?d)
9216 (call-interactively 'org-check-deadlines))
9217 ((equal ans ?b)
9218 (call-interactively 'org-check-before-date))
9219 ((equal ans ?t)
9220 (org-show-todo-tree '(4)))
9221 ((equal ans ?T)
9222 (call-interactively 'org-tags-sparse-tree))
9223 ((member ans '(?p ?P))
9224 (setq kwd (org-ido-completing-read "Property: "
9225 (mapcar 'list (org-buffer-property-keys))))
9226 (setq value (org-ido-completing-read "Value: "
9227 (mapcar 'list (org-property-values kwd))))
9228 (unless (string-match "\\`{.*}\\'" value)
9229 (setq value (concat "\"" value "\"")))
9230 (org-tags-sparse-tree arg (concat kwd "=" value)))
9231 ((member ans '(?r ?R ?/))
9232 (call-interactively 'org-occur))
9233 (t (error "No such sparse tree command \"%c\"" ans)))))
9235 (defvar org-occur-highlights nil
9236 "List of overlays used for occur matches.")
9237 (make-variable-buffer-local 'org-occur-highlights)
9238 (defvar org-occur-parameters nil
9239 "Parameters of the active org-occur calls.
9240 This is a list, each call to org-occur pushes as cons cell,
9241 containing the regular expression and the callback, onto the list.
9242 The list can contain several entries if `org-occur' has been called
9243 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9244 will only contain one set of parameters. When the highlights are
9245 removed (for example with `C-c C-c', or with the next edit (depending
9246 on `org-remove-highlights-with-change'), this variable is emptied
9247 as well.")
9248 (make-variable-buffer-local 'org-occur-parameters)
9250 (defun org-occur (regexp &optional keep-previous callback)
9251 "Make a compact tree which shows all matches of REGEXP.
9252 The tree will show the lines where the regexp matches, and all higher
9253 headlines above the match. It will also show the heading after the match,
9254 to make sure editing the matching entry is easy.
9255 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9256 call to `org-occur' will be kept, to allow stacking of calls to this
9257 command.
9258 If CALLBACK is non-nil, it is a function which is called to confirm
9259 that the match should indeed be shown."
9260 (interactive "sRegexp: \nP")
9261 (unless keep-previous
9262 (org-remove-occur-highlights nil nil t))
9263 (push (cons regexp callback) org-occur-parameters)
9264 (let ((cnt 0))
9265 (save-excursion
9266 (goto-char (point-min))
9267 (if (or (not keep-previous) ; do not want to keep
9268 (not org-occur-highlights)) ; no previous matches
9269 ;; hide everything
9270 (org-overview))
9271 (while (re-search-forward regexp nil t)
9272 (when (or (not callback)
9273 (save-match-data (funcall callback)))
9274 (setq cnt (1+ cnt))
9275 (when org-highlight-sparse-tree-matches
9276 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9277 (org-show-context 'occur-tree))))
9278 (when org-remove-highlights-with-change
9279 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9280 nil 'local))
9281 (unless org-sparse-tree-open-archived-trees
9282 (org-hide-archived-subtrees (point-min) (point-max)))
9283 (run-hooks 'org-occur-hook)
9284 (if (interactive-p)
9285 (message "%d match(es) for regexp %s" cnt regexp))
9286 cnt))
9288 (defun org-show-context (&optional key)
9289 "Make sure point and context and visible.
9290 How much context is shown depends upon the variables
9291 `org-show-hierarchy-above', `org-show-following-heading'. and
9292 `org-show-siblings'."
9293 (let ((heading-p (org-on-heading-p t))
9294 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9295 (following-p (org-get-alist-option org-show-following-heading key))
9296 (entry-p (org-get-alist-option org-show-entry-below key))
9297 (siblings-p (org-get-alist-option org-show-siblings key)))
9298 (catch 'exit
9299 ;; Show heading or entry text
9300 (if (and heading-p (not entry-p))
9301 (org-flag-heading nil) ; only show the heading
9302 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9303 (org-show-hidden-entry))) ; show entire entry
9304 (when following-p
9305 ;; Show next sibling, or heading below text
9306 (save-excursion
9307 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9308 (org-flag-heading nil))))
9309 (when siblings-p (org-show-siblings))
9310 (when hierarchy-p
9311 ;; show all higher headings, possibly with siblings
9312 (save-excursion
9313 (while (and (condition-case nil
9314 (progn (org-up-heading-all 1) t)
9315 (error nil))
9316 (not (bobp)))
9317 (org-flag-heading nil)
9318 (when siblings-p (org-show-siblings))))))))
9320 (defun org-reveal (&optional siblings)
9321 "Show current entry, hierarchy above it, and the following headline.
9322 This can be used to show a consistent set of context around locations
9323 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9324 not t for the search context.
9326 With optional argument SIBLINGS, on each level of the hierarchy all
9327 siblings are shown. This repairs the tree structure to what it would
9328 look like when opened with hierarchical calls to `org-cycle'."
9329 (interactive "P")
9330 (let ((org-show-hierarchy-above t)
9331 (org-show-following-heading t)
9332 (org-show-siblings (if siblings t org-show-siblings)))
9333 (org-show-context nil)))
9335 (defun org-highlight-new-match (beg end)
9336 "Highlight from BEG to END and mark the highlight is an occur headline."
9337 (let ((ov (org-make-overlay beg end)))
9338 (org-overlay-put ov 'face 'secondary-selection)
9339 (push ov org-occur-highlights)))
9341 (defun org-remove-occur-highlights (&optional beg end noremove)
9342 "Remove the occur highlights from the buffer.
9343 BEG and END are ignored. If NOREMOVE is nil, remove this function
9344 from the `before-change-functions' in the current buffer."
9345 (interactive)
9346 (unless org-inhibit-highlight-removal
9347 (mapc 'org-delete-overlay org-occur-highlights)
9348 (setq org-occur-highlights nil)
9349 (setq org-occur-parameters nil)
9350 (unless noremove
9351 (remove-hook 'before-change-functions
9352 'org-remove-occur-highlights 'local))))
9354 ;;;; Priorities
9356 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9357 "Regular expression matching the priority indicator.")
9359 (defvar org-remove-priority-next-time nil)
9361 (defun org-priority-up ()
9362 "Increase the priority of the current item."
9363 (interactive)
9364 (org-priority 'up))
9366 (defun org-priority-down ()
9367 "Decrease the priority of the current item."
9368 (interactive)
9369 (org-priority 'down))
9371 (defun org-priority (&optional action)
9372 "Change the priority of an item by ARG.
9373 ACTION can be `set', `up', `down', or a character."
9374 (interactive)
9375 (setq action (or action 'set))
9376 (let (current new news have remove)
9377 (save-excursion
9378 (org-back-to-heading)
9379 (if (looking-at org-priority-regexp)
9380 (setq current (string-to-char (match-string 2))
9381 have t)
9382 (setq current org-default-priority))
9383 (cond
9384 ((or (eq action 'set)
9385 (if (featurep 'xemacs) (characterp action) (integerp action)))
9386 (if (not (eq action 'set))
9387 (setq new action)
9388 (message "Priority %c-%c, SPC to remove: "
9389 org-highest-priority org-lowest-priority)
9390 (setq new (read-char-exclusive)))
9391 (if (and (= (upcase org-highest-priority) org-highest-priority)
9392 (= (upcase org-lowest-priority) org-lowest-priority))
9393 (setq new (upcase new)))
9394 (cond ((equal new ?\ ) (setq remove t))
9395 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9396 (error "Priority must be between `%c' and `%c'"
9397 org-highest-priority org-lowest-priority))))
9398 ((eq action 'up)
9399 (if (and (not have) (eq last-command this-command))
9400 (setq new org-lowest-priority)
9401 (setq new (if (and org-priority-start-cycle-with-default (not have))
9402 org-default-priority (1- current)))))
9403 ((eq action 'down)
9404 (if (and (not have) (eq last-command this-command))
9405 (setq new org-highest-priority)
9406 (setq new (if (and org-priority-start-cycle-with-default (not have))
9407 org-default-priority (1+ current)))))
9408 (t (error "Invalid action")))
9409 (if (or (< (upcase new) org-highest-priority)
9410 (> (upcase new) org-lowest-priority))
9411 (setq remove t))
9412 (setq news (format "%c" new))
9413 (if have
9414 (if remove
9415 (replace-match "" t t nil 1)
9416 (replace-match news t t nil 2))
9417 (if remove
9418 (error "No priority cookie found in line")
9419 (looking-at org-todo-line-regexp)
9420 (if (match-end 2)
9421 (progn
9422 (goto-char (match-end 2))
9423 (insert " [#" news "]"))
9424 (goto-char (match-beginning 3))
9425 (insert "[#" news "] ")))))
9426 (org-preserve-lc (org-set-tags nil 'align))
9427 (if remove
9428 (message "Priority removed")
9429 (message "Priority of current item set to %s" news))))
9432 (defun org-get-priority (s)
9433 "Find priority cookie and return priority."
9434 (save-match-data
9435 (if (not (string-match org-priority-regexp s))
9436 (* 1000 (- org-lowest-priority org-default-priority))
9437 (* 1000 (- org-lowest-priority
9438 (string-to-char (match-string 2 s)))))))
9440 ;;;; Tags
9442 (defvar org-agenda-archives-mode)
9443 (defun org-scan-tags (action matcher &optional todo-only)
9444 "Scan headline tags with inheritance and produce output ACTION.
9446 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9447 or `agenda' to produce an entry list for an agenda view. It can also be
9448 a Lisp form or a function that should be called at each matched headline, in
9449 this case the return value is a list of all return values from these calls.
9451 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9452 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9453 only lines with a TODO keyword are included in the output."
9454 (require 'org-agenda)
9455 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9456 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9457 (org-re
9458 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9459 (props (list 'face 'default
9460 'done-face 'org-done
9461 'undone-face 'default
9462 'mouse-face 'highlight
9463 'org-not-done-regexp org-not-done-regexp
9464 'org-todo-regexp org-todo-regexp
9465 'keymap org-agenda-keymap
9466 'help-echo
9467 (format "mouse-2 or RET jump to org file %s"
9468 (abbreviate-file-name
9469 (or (buffer-file-name (buffer-base-buffer))
9470 (buffer-name (buffer-base-buffer)))))))
9471 (case-fold-search nil)
9472 lspos tags tags-list
9473 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9474 (llast 0) rtn rtn1 level category i txt
9475 todo marker entry priority)
9476 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9477 (setq action (list 'lambda nil action)))
9478 (save-excursion
9479 (goto-char (point-min))
9480 (when (eq action 'sparse-tree)
9481 (org-overview)
9482 (org-remove-occur-highlights))
9483 (while (re-search-forward re nil t)
9484 (catch :skip
9485 (setq todo (if (match-end 1) (match-string 2))
9486 tags (if (match-end 4) (match-string 4)))
9487 (goto-char (setq lspos (1+ (match-beginning 0))))
9488 (setq level (org-reduced-level (funcall outline-level))
9489 category (org-get-category))
9490 (setq i llast llast level)
9491 ;; remove tag lists from same and sublevels
9492 (while (>= i level)
9493 (when (setq entry (assoc i tags-alist))
9494 (setq tags-alist (delete entry tags-alist)))
9495 (setq i (1- i)))
9496 ;; add the next tags
9497 (when tags
9498 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9499 tags-alist
9500 (cons (cons level tags) tags-alist)))
9501 ;; compile tags for current headline
9502 (setq tags-list
9503 (if org-use-tag-inheritance
9504 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9505 tags))
9506 (when org-use-tag-inheritance
9507 (setcdr (car tags-alist)
9508 (mapcar (lambda (x)
9509 (setq x (copy-sequence x))
9510 (org-add-prop-inherited x))
9511 (cdar tags-alist))))
9512 (when (and tags org-use-tag-inheritance
9513 (not (eq t org-use-tag-inheritance)))
9514 ;; selective inheritance, remove uninherited ones
9515 (setcdr (car tags-alist)
9516 (org-remove-uniherited-tags (cdar tags-alist))))
9517 (when (and (or (not todo-only)
9518 (and (member todo org-not-done-keywords)
9519 (or (not org-agenda-tags-todo-honor-ignore-options)
9520 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9521 (let ((case-fold-search t)) (eval matcher))
9523 (not (member org-archive-tag tags-list))
9524 ;; we have an archive tag, should we use this anyway?
9525 (or (not org-agenda-skip-archived-trees)
9526 (and (eq action 'agenda) org-agenda-archives-mode))))
9527 (unless (eq action 'sparse-tree) (org-agenda-skip))
9529 ;; select this headline
9531 (cond
9532 ((eq action 'sparse-tree)
9533 (and org-highlight-sparse-tree-matches
9534 (org-get-heading) (match-end 0)
9535 (org-highlight-new-match
9536 (match-beginning 0) (match-beginning 1)))
9537 (org-show-context 'tags-tree))
9538 ((eq action 'agenda)
9539 (setq txt (org-format-agenda-item
9541 (concat
9542 (if org-tags-match-list-sublevels
9543 (make-string (1- level) ?.) "")
9544 (org-get-heading))
9545 category (org-get-tags-at))
9546 priority (org-get-priority txt))
9547 (goto-char lspos)
9548 (setq marker (org-agenda-new-marker))
9549 (org-add-props txt props
9550 'org-marker marker 'org-hd-marker marker 'org-category category
9551 'priority priority 'type "tagsmatch")
9552 (push txt rtn))
9553 ((functionp action)
9554 (save-excursion
9555 (setq rtn1 (funcall action))
9556 (push rtn1 rtn))
9557 (goto-char (point-at-eol)))
9558 (t (error "Invalid action")))
9560 ;; if we are to skip sublevels, jump to end of subtree
9561 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9562 (when (and (eq action 'sparse-tree)
9563 (not org-sparse-tree-open-archived-trees))
9564 (org-hide-archived-subtrees (point-min) (point-max)))
9565 (nreverse rtn)))
9567 (defun org-remove-uniherited-tags (tags)
9568 "Remove all tags that are not inherited from the list TAGS."
9569 (cond
9570 ((eq org-use-tag-inheritance t)
9571 (if org-tags-exclude-from-inheritance
9572 (org-delete-all org-tags-exclude-from-inheritance tags)
9573 tags))
9574 ((not org-use-tag-inheritance) nil)
9575 ((stringp org-use-tag-inheritance)
9576 (delq nil (mapcar
9577 (lambda (x)
9578 (if (and (string-match org-use-tag-inheritance x)
9579 (not (member x org-tags-exclude-from-inheritance)))
9580 x nil))
9581 tags)))
9582 ((listp org-use-tag-inheritance)
9583 (delq nil (mapcar
9584 (lambda (x)
9585 (if (member x org-use-tag-inheritance) x nil))
9586 tags)))))
9588 (defvar todo-only) ;; dynamically scoped
9590 (defun org-tags-sparse-tree (&optional todo-only match)
9591 "Create a sparse tree according to tags string MATCH.
9592 MATCH can contain positive and negative selection of tags, like
9593 \"+WORK+URGENT-WITHBOSS\".
9594 If optional argument TODO-ONLY is non-nil, only select lines that are
9595 also TODO lines."
9596 (interactive "P")
9597 (org-prepare-agenda-buffers (list (current-buffer)))
9598 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9600 (defvar org-cached-props nil)
9601 (defun org-cached-entry-get (pom property)
9602 (if (or (eq t org-use-property-inheritance)
9603 (and (stringp org-use-property-inheritance)
9604 (string-match org-use-property-inheritance property))
9605 (and (listp org-use-property-inheritance)
9606 (member property org-use-property-inheritance)))
9607 ;; Caching is not possible, check it directly
9608 (org-entry-get pom property 'inherit)
9609 ;; Get all properties, so that we can do complicated checks easily
9610 (cdr (assoc property (or org-cached-props
9611 (setq org-cached-props
9612 (org-entry-properties pom)))))))
9614 (defun org-global-tags-completion-table (&optional files)
9615 "Return the list of all tags in all agenda buffer/files."
9616 (save-excursion
9617 (org-uniquify
9618 (delq nil
9619 (apply 'append
9620 (mapcar
9621 (lambda (file)
9622 (set-buffer (find-file-noselect file))
9623 (append (org-get-buffer-tags)
9624 (mapcar (lambda (x) (if (stringp (car-safe x))
9625 (list (car-safe x)) nil))
9626 org-tag-alist)))
9627 (if (and files (car files))
9628 files
9629 (org-agenda-files))))))))
9631 (defun org-make-tags-matcher (match)
9632 "Create the TAGS//TODO matcher form for the selection string MATCH."
9633 ;; todo-only is scoped dynamically into this function, and the function
9634 ;; may change it if the matcher asks for it.
9635 (unless match
9636 ;; Get a new match request, with completion
9637 (let ((org-last-tags-completion-table
9638 (org-global-tags-completion-table)))
9639 (setq match (org-completing-read
9640 "Match: " 'org-tags-completion-function nil nil nil
9641 'org-tags-history))))
9643 ;; Parse the string and create a lisp form
9644 (let ((match0 match)
9645 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9646 minus tag mm
9647 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9648 orterms term orlist re-p str-p level-p level-op time-p
9649 prop-p pn pv po cat-p gv rest)
9650 (if (string-match "/+" match)
9651 ;; match contains also a todo-matching request
9652 (progn
9653 (setq tagsmatch (substring match 0 (match-beginning 0))
9654 todomatch (substring match (match-end 0)))
9655 (if (string-match "^!" todomatch)
9656 (setq todo-only t todomatch (substring todomatch 1)))
9657 (if (string-match "^\\s-*$" todomatch)
9658 (setq todomatch nil)))
9659 ;; only matching tags
9660 (setq tagsmatch match todomatch nil))
9662 ;; Make the tags matcher
9663 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9664 (setq tagsmatcher t)
9665 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9666 (while (setq term (pop orterms))
9667 (while (and (equal (substring term -1) "\\") orterms)
9668 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9669 (while (string-match re term)
9670 (setq rest (substring term (match-end 0))
9671 minus (and (match-end 1)
9672 (equal (match-string 1 term) "-"))
9673 tag (match-string 2 term)
9674 re-p (equal (string-to-char tag) ?{)
9675 level-p (match-end 4)
9676 prop-p (match-end 5)
9677 mm (cond
9678 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9679 (level-p
9680 (setq level-op (org-op-to-function (match-string 3 term)))
9681 `(,level-op level ,(string-to-number
9682 (match-string 4 term))))
9683 (prop-p
9684 (setq pn (match-string 5 term)
9685 po (match-string 6 term)
9686 pv (match-string 7 term)
9687 cat-p (equal pn "CATEGORY")
9688 re-p (equal (string-to-char pv) ?{)
9689 str-p (equal (string-to-char pv) ?\")
9690 time-p (save-match-data
9691 (string-match "^\"[[<].*[]>]\"$" pv))
9692 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9693 (if time-p (setq pv (org-matcher-time pv)))
9694 (setq po (org-op-to-function po (if time-p 'time str-p)))
9695 (cond
9696 ((equal pn "CATEGORY")
9697 (setq gv '(get-text-property (point) 'org-category)))
9698 ((equal pn "TODO")
9699 (setq gv 'todo))
9701 (setq gv `(org-cached-entry-get nil ,pn))))
9702 (if re-p
9703 (if (eq po 'org<>)
9704 `(not (string-match ,pv (or ,gv "")))
9705 `(string-match ,pv (or ,gv "")))
9706 (if str-p
9707 `(,po (or ,gv "") ,pv)
9708 `(,po (string-to-number (or ,gv ""))
9709 ,(string-to-number pv) ))))
9710 (t `(member ,(downcase tag) tags-list)))
9711 mm (if minus (list 'not mm) mm)
9712 term rest)
9713 (push mm tagsmatcher))
9714 (push (if (> (length tagsmatcher) 1)
9715 (cons 'and tagsmatcher)
9716 (car tagsmatcher))
9717 orlist)
9718 (setq tagsmatcher nil))
9719 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9720 (setq tagsmatcher
9721 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9722 ;; Make the todo matcher
9723 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9724 (setq todomatcher t)
9725 (setq orterms (org-split-string todomatch "|") orlist nil)
9726 (while (setq term (pop orterms))
9727 (while (string-match re term)
9728 (setq minus (and (match-end 1)
9729 (equal (match-string 1 term) "-"))
9730 kwd (match-string 2 term)
9731 re-p (equal (string-to-char kwd) ?{)
9732 term (substring term (match-end 0))
9733 mm (if re-p
9734 `(string-match ,(substring kwd 1 -1) todo)
9735 (list 'equal 'todo kwd))
9736 mm (if minus (list 'not mm) mm))
9737 (push mm todomatcher))
9738 (push (if (> (length todomatcher) 1)
9739 (cons 'and todomatcher)
9740 (car todomatcher))
9741 orlist)
9742 (setq todomatcher nil))
9743 (setq todomatcher (if (> (length orlist) 1)
9744 (cons 'or orlist) (car orlist))))
9746 ;; Return the string and lisp forms of the matcher
9747 (setq matcher (if todomatcher
9748 (list 'and tagsmatcher todomatcher)
9749 tagsmatcher))
9750 (cons match0 matcher)))
9752 (defun org-op-to-function (op &optional stringp)
9753 "Turn an operator into the appropriate function."
9754 (setq op
9755 (cond
9756 ((equal op "<" ) '(< string< org-time<))
9757 ((equal op ">" ) '(> org-string> org-time>))
9758 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9759 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9760 ((member op '("=" "==")) '(= string= org-time=))
9761 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9762 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9764 (defun org<> (a b) (not (= a b)))
9765 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9766 (defun org-string>= (a b) (not (string< a b)))
9767 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9768 (defun org-string<> (a b) (not (string= a b)))
9769 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9770 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9771 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9772 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9773 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9774 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9775 (defun org-2ft (s)
9776 "Convert S to a floating point time.
9777 If S is already a number, just return it. If it is a string, parse
9778 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9779 (cond
9780 ((numberp s) s)
9781 ((stringp s)
9782 (condition-case nil
9783 (float-time (apply 'encode-time (org-parse-time-string s)))
9784 (error 0.)))
9785 (t 0.)))
9787 (defun org-time-today ()
9788 "Time in seconds today at 0:00.
9789 Returns the float number of seconds since the beginning of the
9790 epoch to the beginning of today (00:00)."
9791 (float-time (apply 'encode-time
9792 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9794 (defun org-matcher-time (s)
9795 "Interpret a time comparison value."
9796 (save-match-data
9797 (cond
9798 ((string= s "<now>") (float-time))
9799 ((string= s "<today>") (org-time-today))
9800 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9801 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9802 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9803 (+ (org-time-today)
9804 (* (string-to-number (match-string 1 s))
9805 (cdr (assoc (match-string 2 s)
9806 '(("d" . 86400.0) ("w" . 604800.0)
9807 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9808 (t (org-2ft s)))))
9810 (defun org-match-any-p (re list)
9811 "Does re match any element of list?"
9812 (setq list (mapcar (lambda (x) (string-match re x)) list))
9813 (delq nil list))
9815 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9816 (defvar org-tags-overlay (org-make-overlay 1 1))
9817 (org-detach-overlay org-tags-overlay)
9819 (defun org-get-local-tags-at (&optional pos)
9820 "Get a list of tags defined in the current headline."
9821 (org-get-tags-at pos 'local))
9823 (defun org-get-local-tags ()
9824 "Get a list of tags defined in the current headline."
9825 (org-get-tags-at nil 'local))
9827 (defun org-get-tags-at (&optional pos local)
9828 "Get a list of all headline tags applicable at POS.
9829 POS defaults to point. If tags are inherited, the list contains
9830 the targets in the same sequence as the headlines appear, i.e.
9831 the tags of the current headline come last.
9832 When LOCAL is non-nil, only return tags from the current headline,
9833 ignore inherited ones."
9834 (interactive)
9835 (let (tags ltags lastpos parent)
9836 (save-excursion
9837 (save-restriction
9838 (widen)
9839 (goto-char (or pos (point)))
9840 (save-match-data
9841 (catch 'done
9842 (condition-case nil
9843 (progn
9844 (org-back-to-heading t)
9845 (while (not (equal lastpos (point)))
9846 (setq lastpos (point))
9847 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9848 (setq ltags (org-split-string
9849 (org-match-string-no-properties 1) ":"))
9850 (when parent
9851 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9852 (setq tags (append
9853 (if parent
9854 (org-remove-uniherited-tags ltags)
9855 ltags)
9856 tags)))
9857 (or org-use-tag-inheritance (throw 'done t))
9858 (if local (throw 'done t))
9859 (org-up-heading-all 1)
9860 (setq parent t)))
9861 (error nil)))))
9862 (append (org-remove-uniherited-tags org-file-tags) tags))))
9864 (defun org-add-prop-inherited (s)
9865 (add-text-properties 0 (length s) '(inherited t) s)
9868 (defun org-toggle-tag (tag &optional onoff)
9869 "Toggle the tag TAG for the current line.
9870 If ONOFF is `on' or `off', don't toggle but set to this state."
9871 (let (res current)
9872 (save-excursion
9873 (org-back-to-heading t)
9874 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9875 (point-at-eol) t)
9876 (progn
9877 (setq current (match-string 1))
9878 (replace-match ""))
9879 (setq current ""))
9880 (setq current (nreverse (org-split-string current ":")))
9881 (cond
9882 ((eq onoff 'on)
9883 (setq res t)
9884 (or (member tag current) (push tag current)))
9885 ((eq onoff 'off)
9886 (or (not (member tag current)) (setq current (delete tag current))))
9887 (t (if (member tag current)
9888 (setq current (delete tag current))
9889 (setq res t)
9890 (push tag current))))
9891 (end-of-line 1)
9892 (if current
9893 (progn
9894 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9895 (org-set-tags nil t))
9896 (delete-horizontal-space))
9897 (run-hooks 'org-after-tags-change-hook))
9898 res))
9900 (defun org-align-tags-here (to-col)
9901 ;; Assumes that this is a headline
9902 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9903 (beginning-of-line 1)
9904 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9905 (< pos (match-beginning 2)))
9906 (progn
9907 (setq tags-l (- (match-end 2) (match-beginning 2)))
9908 (goto-char (match-beginning 1))
9909 (insert " ")
9910 (delete-region (point) (1+ (match-beginning 2)))
9911 (setq ncol (max (1+ (current-column))
9912 (1+ col)
9913 (if (> to-col 0)
9914 to-col
9915 (- (abs to-col) tags-l))))
9916 (setq p (point))
9917 (insert (make-string (- ncol (current-column)) ?\ ))
9918 (setq ncol (current-column))
9919 (when indent-tabs-mode (tabify p (point-at-eol)))
9920 (org-move-to-column (min ncol col) t))
9921 (goto-char pos))))
9923 (defun org-set-tags-command (&optional arg just-align)
9924 "Call the set-tags command for the current entry."
9925 (interactive "P")
9926 (if (org-on-heading-p)
9927 (org-set-tags arg just-align)
9928 (save-excursion
9929 (org-back-to-heading t)
9930 (org-set-tags arg just-align))))
9932 (defun org-set-tags (&optional arg just-align)
9933 "Set the tags for the current headline.
9934 With prefix ARG, realign all tags in headings in the current buffer."
9935 (interactive "P")
9936 (let* ((re (concat "^" outline-regexp))
9937 (current (org-get-tags-string))
9938 (col (current-column))
9939 (org-setting-tags t)
9940 table current-tags inherited-tags ; computed below when needed
9941 tags p0 c0 c1 rpl)
9942 (if arg
9943 (save-excursion
9944 (goto-char (point-min))
9945 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9946 (while (re-search-forward re nil t)
9947 (org-set-tags nil t)
9948 (end-of-line 1)))
9949 (message "All tags realigned to column %d" org-tags-column))
9950 (if just-align
9951 (setq tags current)
9952 ;; Get a new set of tags from the user
9953 (save-excursion
9954 (setq table (or org-tag-alist (org-get-buffer-tags))
9955 org-last-tags-completion-table table
9956 current-tags (org-split-string current ":")
9957 inherited-tags (nreverse
9958 (nthcdr (length current-tags)
9959 (nreverse (org-get-tags-at))))
9960 tags
9961 (if (or (eq t org-use-fast-tag-selection)
9962 (and org-use-fast-tag-selection
9963 (delq nil (mapcar 'cdr table))))
9964 (org-fast-tag-selection
9965 current-tags inherited-tags table
9966 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9967 (let ((org-add-colon-after-tag-completion t))
9968 (org-trim
9969 (org-without-partial-completion
9970 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9971 nil nil current 'org-tags-history)))))))
9972 (while (string-match "[-+&]+" tags)
9973 ;; No boolean logic, just a list
9974 (setq tags (replace-match ":" t t tags))))
9976 (if (string-match "\\`[\t ]*\\'" tags)
9977 (setq tags "")
9978 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9979 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9981 ;; Insert new tags at the correct column
9982 (beginning-of-line 1)
9983 (cond
9984 ((and (equal current "") (equal tags "")))
9985 ((re-search-forward
9986 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9987 (point-at-eol) t)
9988 (if (equal tags "")
9989 (setq rpl "")
9990 (goto-char (match-beginning 0))
9991 (setq c0 (current-column) p0 (point)
9992 c1 (max (1+ c0) (if (> org-tags-column 0)
9993 org-tags-column
9994 (- (- org-tags-column) (length tags))))
9995 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9996 (replace-match rpl t t)
9997 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9998 tags)
9999 (t (error "Tags alignment failed")))
10000 (org-move-to-column col)
10001 (unless just-align
10002 (run-hooks 'org-after-tags-change-hook)))))
10004 (defun org-change-tag-in-region (beg end tag off)
10005 "Add or remove TAG for each entry in the region.
10006 This works in the agenda, and also in an org-mode buffer."
10007 (interactive
10008 (list (region-beginning) (region-end)
10009 (let ((org-last-tags-completion-table
10010 (if (org-mode-p)
10011 (org-get-buffer-tags)
10012 (org-global-tags-completion-table))))
10013 (org-ido-completing-read
10014 "Tag: " 'org-tags-completion-function nil nil nil
10015 'org-tags-history))
10016 (progn
10017 (message "[s]et or [r]emove? ")
10018 (equal (read-char-exclusive) ?r))))
10019 (if (fboundp 'deactivate-mark) (deactivate-mark))
10020 (let ((agendap (equal major-mode 'org-agenda-mode))
10021 l1 l2 m buf pos newhead (cnt 0))
10022 (goto-char end)
10023 (setq l2 (1- (org-current-line)))
10024 (goto-char beg)
10025 (setq l1 (org-current-line))
10026 (loop for l from l1 to l2 do
10027 (goto-line l)
10028 (setq m (get-text-property (point) 'org-hd-marker))
10029 (when (or (and (org-mode-p) (org-on-heading-p))
10030 (and agendap m))
10031 (setq buf (if agendap (marker-buffer m) (current-buffer))
10032 pos (if agendap m (point)))
10033 (with-current-buffer buf
10034 (save-excursion
10035 (save-restriction
10036 (goto-char pos)
10037 (setq cnt (1+ cnt))
10038 (org-toggle-tag tag (if off 'off 'on))
10039 (setq newhead (org-get-heading)))))
10040 (and agendap (org-agenda-change-all-lines newhead m))))
10041 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10043 (defun org-tags-completion-function (string predicate &optional flag)
10044 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10045 (confirm (lambda (x) (stringp (car x)))))
10046 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10047 (setq s1 (match-string 1 string)
10048 s2 (match-string 2 string))
10049 (setq s1 "" s2 string))
10050 (cond
10051 ((eq flag nil)
10052 ;; try completion
10053 (setq rtn (try-completion s2 ctable confirm))
10054 (if (stringp rtn)
10055 (setq rtn
10056 (concat s1 s2 (substring rtn (length s2))
10057 (if (and org-add-colon-after-tag-completion
10058 (assoc rtn ctable))
10059 ":" ""))))
10060 rtn)
10061 ((eq flag t)
10062 ;; all-completions
10063 (all-completions s2 ctable confirm)
10065 ((eq flag 'lambda)
10066 ;; exact match?
10067 (assoc s2 ctable)))
10070 (defun org-fast-tag-insert (kwd tags face &optional end)
10071 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10072 (insert (format "%-12s" (concat kwd ":"))
10073 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10074 (or end "")))
10076 (defun org-fast-tag-show-exit (flag)
10077 (save-excursion
10078 (goto-line 3)
10079 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10080 (replace-match ""))
10081 (when flag
10082 (end-of-line 1)
10083 (org-move-to-column (- (window-width) 19) t)
10084 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10086 (defun org-set-current-tags-overlay (current prefix)
10087 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10088 (if (featurep 'xemacs)
10089 (org-overlay-display org-tags-overlay (concat prefix s)
10090 'secondary-selection)
10091 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10092 (org-overlay-display org-tags-overlay (concat prefix s)))))
10094 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10095 "Fast tag selection with single keys.
10096 CURRENT is the current list of tags in the headline, INHERITED is the
10097 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10098 possibly with grouping information. TODO-TABLE is a similar table with
10099 TODO keywords, should these have keys assigned to them.
10100 If the keys are nil, a-z are automatically assigned.
10101 Returns the new tags string, or nil to not change the current settings."
10102 (let* ((fulltable (append table todo-table))
10103 (maxlen (apply 'max (mapcar
10104 (lambda (x)
10105 (if (stringp (car x)) (string-width (car x)) 0))
10106 fulltable)))
10107 (buf (current-buffer))
10108 (expert (eq org-fast-tag-selection-single-key 'expert))
10109 (buffer-tags nil)
10110 (fwidth (+ maxlen 3 1 3))
10111 (ncol (/ (- (window-width) 4) fwidth))
10112 (i-face 'org-done)
10113 (c-face 'org-todo)
10114 tg cnt e c char c1 c2 ntable tbl rtn
10115 ov-start ov-end ov-prefix
10116 (exit-after-next org-fast-tag-selection-single-key)
10117 (done-keywords org-done-keywords)
10118 groups ingroup)
10119 (save-excursion
10120 (beginning-of-line 1)
10121 (if (looking-at
10122 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10123 (setq ov-start (match-beginning 1)
10124 ov-end (match-end 1)
10125 ov-prefix "")
10126 (setq ov-start (1- (point-at-eol))
10127 ov-end (1+ ov-start))
10128 (skip-chars-forward "^\n\r")
10129 (setq ov-prefix
10130 (concat
10131 (buffer-substring (1- (point)) (point))
10132 (if (> (current-column) org-tags-column)
10134 (make-string (- org-tags-column (current-column)) ?\ ))))))
10135 (org-move-overlay org-tags-overlay ov-start ov-end)
10136 (save-window-excursion
10137 (if expert
10138 (set-buffer (get-buffer-create " *Org tags*"))
10139 (delete-other-windows)
10140 (split-window-vertically)
10141 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10142 (erase-buffer)
10143 (org-set-local 'org-done-keywords done-keywords)
10144 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10145 (org-fast-tag-insert "Current" current c-face "\n\n")
10146 (org-fast-tag-show-exit exit-after-next)
10147 (org-set-current-tags-overlay current ov-prefix)
10148 (setq tbl fulltable char ?a cnt 0)
10149 (while (setq e (pop tbl))
10150 (cond
10151 ((equal e '(:startgroup))
10152 (push '() groups) (setq ingroup t)
10153 (when (not (= cnt 0))
10154 (setq cnt 0)
10155 (insert "\n"))
10156 (insert "{ "))
10157 ((equal e '(:endgroup))
10158 (setq ingroup nil cnt 0)
10159 (insert "}\n"))
10161 (setq tg (car e) c2 nil)
10162 (if (cdr e)
10163 (setq c (cdr e))
10164 ;; automatically assign a character.
10165 (setq c1 (string-to-char
10166 (downcase (substring
10167 tg (if (= (string-to-char tg) ?@) 1 0)))))
10168 (if (or (rassoc c1 ntable) (rassoc c1 table))
10169 (while (or (rassoc char ntable) (rassoc char table))
10170 (setq char (1+ char)))
10171 (setq c2 c1))
10172 (setq c (or c2 char)))
10173 (if ingroup (push tg (car groups)))
10174 (setq tg (org-add-props tg nil 'face
10175 (cond
10176 ((not (assoc tg table))
10177 (org-get-todo-face tg))
10178 ((member tg current) c-face)
10179 ((member tg inherited) i-face)
10180 (t nil))))
10181 (if (and (= cnt 0) (not ingroup)) (insert " "))
10182 (insert "[" c "] " tg (make-string
10183 (- fwidth 4 (length tg)) ?\ ))
10184 (push (cons tg c) ntable)
10185 (when (= (setq cnt (1+ cnt)) ncol)
10186 (insert "\n")
10187 (if ingroup (insert " "))
10188 (setq cnt 0)))))
10189 (setq ntable (nreverse ntable))
10190 (insert "\n")
10191 (goto-char (point-min))
10192 (if (not expert) (org-fit-window-to-buffer))
10193 (setq rtn
10194 (catch 'exit
10195 (while t
10196 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10197 (if groups " [!] no groups" " [!]groups")
10198 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10199 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10200 (cond
10201 ((= c ?\r) (throw 'exit t))
10202 ((= c ?!)
10203 (setq groups (not groups))
10204 (goto-char (point-min))
10205 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10206 ((= c ?\C-c)
10207 (if (not expert)
10208 (org-fast-tag-show-exit
10209 (setq exit-after-next (not exit-after-next)))
10210 (setq expert nil)
10211 (delete-other-windows)
10212 (split-window-vertically)
10213 (org-switch-to-buffer-other-window " *Org tags*")
10214 (org-fit-window-to-buffer)))
10215 ((or (= c ?\C-g)
10216 (and (= c ?q) (not (rassoc c ntable))))
10217 (org-detach-overlay org-tags-overlay)
10218 (setq quit-flag t))
10219 ((= c ?\ )
10220 (setq current nil)
10221 (if exit-after-next (setq exit-after-next 'now)))
10222 ((= c ?\t)
10223 (condition-case nil
10224 (setq tg (org-ido-completing-read
10225 "Tag: "
10226 (or buffer-tags
10227 (with-current-buffer buf
10228 (org-get-buffer-tags)))))
10229 (quit (setq tg "")))
10230 (when (string-match "\\S-" tg)
10231 (add-to-list 'buffer-tags (list tg))
10232 (if (member tg current)
10233 (setq current (delete tg current))
10234 (push tg current)))
10235 (if exit-after-next (setq exit-after-next 'now)))
10236 ((setq e (rassoc c todo-table) tg (car e))
10237 (with-current-buffer buf
10238 (save-excursion (org-todo tg)))
10239 (if exit-after-next (setq exit-after-next 'now)))
10240 ((setq e (rassoc c ntable) tg (car e))
10241 (if (member tg current)
10242 (setq current (delete tg current))
10243 (loop for g in groups do
10244 (if (member tg g)
10245 (mapc (lambda (x)
10246 (setq current (delete x current)))
10247 g)))
10248 (push tg current))
10249 (if exit-after-next (setq exit-after-next 'now))))
10251 ;; Create a sorted list
10252 (setq current
10253 (sort current
10254 (lambda (a b)
10255 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10256 (if (eq exit-after-next 'now) (throw 'exit t))
10257 (goto-char (point-min))
10258 (beginning-of-line 2)
10259 (delete-region (point) (point-at-eol))
10260 (org-fast-tag-insert "Current" current c-face)
10261 (org-set-current-tags-overlay current ov-prefix)
10262 (while (re-search-forward
10263 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10264 (setq tg (match-string 1))
10265 (add-text-properties
10266 (match-beginning 1) (match-end 1)
10267 (list 'face
10268 (cond
10269 ((member tg current) c-face)
10270 ((member tg inherited) i-face)
10271 (t (get-text-property (match-beginning 1) 'face))))))
10272 (goto-char (point-min)))))
10273 (org-detach-overlay org-tags-overlay)
10274 (if rtn
10275 (mapconcat 'identity current ":")
10276 nil))))
10278 (defun org-get-tags-string ()
10279 "Get the TAGS string in the current headline."
10280 (unless (org-on-heading-p t)
10281 (error "Not on a heading"))
10282 (save-excursion
10283 (beginning-of-line 1)
10284 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10285 (org-match-string-no-properties 1)
10286 "")))
10288 (defun org-get-tags ()
10289 "Get the list of tags specified in the current headline."
10290 (org-split-string (org-get-tags-string) ":"))
10292 (defun org-get-buffer-tags ()
10293 "Get a table of all tags used in the buffer, for completion."
10294 (let (tags)
10295 (save-excursion
10296 (goto-char (point-min))
10297 (while (re-search-forward
10298 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10299 (when (equal (char-after (point-at-bol 0)) ?*)
10300 (mapc (lambda (x) (add-to-list 'tags x))
10301 (org-split-string (org-match-string-no-properties 1) ":")))))
10302 (mapcar 'list tags)))
10304 ;;;; The mapping API
10306 ;;;###autoload
10307 (defun org-map-entries (func &optional match scope &rest skip)
10308 "Call FUNC at each headline selected by MATCH in SCOPE.
10310 FUNC is a function or a lisp form. The function will be called without
10311 arguments, with the cursor positioned at the beginning of the headline.
10312 The return values of all calls to the function will be collected and
10313 returned as a list.
10315 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10316 Only headlines that are matched by this query will be considered during
10317 the iteration. When MATCH is nil or t, all headlines will be
10318 visited by the iteration.
10320 SCOPE determines the scope of this command. It can be any of:
10322 nil The current buffer, respecting the restriction if any
10323 tree The subtree started with the entry at point
10324 file The current buffer, without restriction
10325 file-with-archives
10326 The current buffer, and any archives associated with it
10327 agenda All agenda files
10328 agenda-with-archives
10329 All agenda files with any archive files associated with them
10330 \(file1 file2 ...)
10331 If this is a list, all files in the list will be scanned
10333 The remaining args are treated as settings for the skipping facilities of
10334 the scanner. The following items can be given here:
10336 archive skip trees with the archive tag.
10337 comment skip trees with the COMMENT keyword
10338 function or Emacs Lisp form:
10339 will be used as value for `org-agenda-skip-function', so whenever
10340 the the function returns t, FUNC will not be called for that
10341 entry and search will continue from the point where the
10342 function leaves it."
10343 (let* ((org-agenda-archives-mode nil) ; just to make sure
10344 (org-agenda-skip-archived-trees (memq 'archive skip))
10345 (org-agenda-skip-comment-trees (memq 'comment skip))
10346 (org-agenda-skip-function
10347 (car (org-delete-all '(comment archive) skip)))
10348 (org-tags-match-list-sublevels t)
10349 matcher file res
10350 org-todo-keywords-for-agenda
10351 org-done-keywords-for-agenda
10352 org-todo-keyword-alist-for-agenda
10353 org-tag-alist-for-agenda)
10355 (cond
10356 ((eq match t) (setq matcher t))
10357 ((eq match nil) (setq matcher t))
10358 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10360 (save-excursion
10361 (save-restriction
10362 (when (eq scope 'tree)
10363 (org-back-to-heading t)
10364 (org-narrow-to-subtree)
10365 (setq scope nil))
10367 (if (not scope)
10368 (progn
10369 (org-prepare-agenda-buffers
10370 (list (buffer-file-name (current-buffer))))
10371 (setq res (org-scan-tags func matcher)))
10372 ;; Get the right scope
10373 (cond
10374 ((and scope (listp scope) (symbolp (car scope)))
10375 (setq scope (eval scope)))
10376 ((eq scope 'agenda)
10377 (setq scope (org-agenda-files t)))
10378 ((eq scope 'agenda-with-archives)
10379 (setq scope (org-agenda-files t))
10380 (setq scope (org-add-archive-files scope)))
10381 ((eq scope 'file)
10382 (setq scope (list (buffer-file-name))))
10383 ((eq scope 'file-with-archives)
10384 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10385 (org-prepare-agenda-buffers scope)
10386 (while (setq file (pop scope))
10387 (with-current-buffer (org-find-base-buffer-visiting file)
10388 (save-excursion
10389 (save-restriction
10390 (widen)
10391 (goto-char (point-min))
10392 (setq res (append res (org-scan-tags func matcher))))))))))
10393 res))
10395 ;;;; Properties
10397 ;;; Setting and retrieving properties
10399 (defconst org-special-properties
10400 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10401 "TIMESTAMP" "TIMESTAMP_IA")
10402 "The special properties valid in Org-mode.
10404 These are properties that are not defined in the property drawer,
10405 but in some other way.")
10407 (defconst org-default-properties
10408 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10409 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10410 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10411 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10412 "Some properties that are used by Org-mode for various purposes.
10413 Being in this list makes sure that they are offered for completion.")
10415 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10416 "Regular expression matching the first line of a property drawer.")
10418 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10419 "Regular expression matching the first line of a property drawer.")
10421 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10422 "Regular expression matching the first line of a property drawer.")
10424 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10425 "Regular expression matching the first line of a property drawer.")
10427 (defconst org-property-drawer-re
10428 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10429 org-property-end-re "\\)\n?")
10430 "Matches an entire property drawer.")
10432 (defconst org-clock-drawer-re
10433 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10434 org-property-end-re "\\)\n?")
10435 "Matches an entire clock drawer.")
10437 (defun org-property-action ()
10438 "Do an action on properties."
10439 (interactive)
10440 (let (c)
10441 (org-at-property-p)
10442 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10443 (setq c (read-char-exclusive))
10444 (cond
10445 ((equal c ?s)
10446 (call-interactively 'org-set-property))
10447 ((equal c ?d)
10448 (call-interactively 'org-delete-property))
10449 ((equal c ?D)
10450 (call-interactively 'org-delete-property-globally))
10451 ((equal c ?c)
10452 (call-interactively 'org-compute-property-at-point))
10453 (t (error "No such property action %c" c)))))
10455 (defun org-at-property-p ()
10456 "Is the cursor in a property line?"
10457 ;; FIXME: Does not check if we are actually in the drawer.
10458 ;; FIXME: also returns true on any drawers.....
10459 ;; This is used by C-c C-c for property action.
10460 (save-excursion
10461 (beginning-of-line 1)
10462 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10464 (defun org-get-property-block (&optional beg end force)
10465 "Return the (beg . end) range of the body of the property drawer.
10466 BEG and END can be beginning and end of subtree, if not given
10467 they will be found.
10468 If the drawer does not exist and FORCE is non-nil, create the drawer."
10469 (catch 'exit
10470 (save-excursion
10471 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10472 (end (or end (progn (outline-next-heading) (point)))))
10473 (goto-char beg)
10474 (if (re-search-forward org-property-start-re end t)
10475 (setq beg (1+ (match-end 0)))
10476 (if force
10477 (save-excursion
10478 (org-insert-property-drawer)
10479 (setq end (progn (outline-next-heading) (point))))
10480 (throw 'exit nil))
10481 (goto-char beg)
10482 (if (re-search-forward org-property-start-re end t)
10483 (setq beg (1+ (match-end 0)))))
10484 (if (re-search-forward org-property-end-re end t)
10485 (setq end (match-beginning 0))
10486 (or force (throw 'exit nil))
10487 (goto-char beg)
10488 (setq end beg)
10489 (org-indent-line-function)
10490 (insert ":END:\n"))
10491 (cons beg end)))))
10493 (defun org-entry-properties (&optional pom which)
10494 "Get all properties of the entry at point-or-marker POM.
10495 This includes the TODO keyword, the tags, time strings for deadline,
10496 scheduled, and clocking, and any additional properties defined in the
10497 entry. The return value is an alist, keys may occur multiple times
10498 if the property key was used several times.
10499 POM may also be nil, in which case the current entry is used.
10500 If WHICH is nil or `all', get all properties. If WHICH is
10501 `special' or `standard', only get that subclass."
10502 (setq which (or which 'all))
10503 (org-with-point-at pom
10504 (let ((clockstr (substring org-clock-string 0 -1))
10505 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10506 beg end range props sum-props key value string clocksum)
10507 (save-excursion
10508 (when (condition-case nil
10509 (and (org-mode-p) (org-back-to-heading t))
10510 (error nil))
10511 (setq beg (point))
10512 (setq sum-props (get-text-property (point) 'org-summaries))
10513 (setq clocksum (get-text-property (point) :org-clock-minutes))
10514 (outline-next-heading)
10515 (setq end (point))
10516 (when (memq which '(all special))
10517 ;; Get the special properties, like TODO and tags
10518 (goto-char beg)
10519 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10520 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10521 (when (looking-at org-priority-regexp)
10522 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10523 (when (and (setq value (org-get-tags-string))
10524 (string-match "\\S-" value))
10525 (push (cons "TAGS" value) props))
10526 (when (setq value (org-get-tags-at))
10527 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10528 props))
10529 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10530 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10531 string (if (equal key clockstr)
10532 (org-no-properties
10533 (org-trim
10534 (buffer-substring
10535 (match-beginning 3) (goto-char (point-at-eol)))))
10536 (substring (org-match-string-no-properties 3) 1 -1)))
10537 (unless key
10538 (if (= (char-after (match-beginning 3)) ?\[)
10539 (setq key "TIMESTAMP_IA")
10540 (setq key "TIMESTAMP")))
10541 (when (or (equal key clockstr) (not (assoc key props)))
10542 (push (cons key string) props)))
10546 (when (memq which '(all standard))
10547 ;; Get the standard properties, like :PORP: ...
10548 (setq range (org-get-property-block beg end))
10549 (when range
10550 (goto-char (car range))
10551 (while (re-search-forward
10552 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10553 (cdr range) t)
10554 (setq key (org-match-string-no-properties 1)
10555 value (org-trim (or (org-match-string-no-properties 2) "")))
10556 (unless (member key excluded)
10557 (push (cons key (or value "")) props)))))
10558 (if clocksum
10559 (push (cons "CLOCKSUM"
10560 (org-columns-number-to-string (/ (float clocksum) 60.)
10561 'add_times))
10562 props))
10563 (unless (assoc "CATEGORY" props)
10564 (setq value (or (org-get-category)
10565 (progn (org-refresh-category-properties)
10566 (org-get-category))))
10567 (push (cons "CATEGORY" value) props))
10568 (append sum-props (nreverse props)))))))
10570 (defun org-entry-get (pom property &optional inherit)
10571 "Get value of PROPERTY for entry at point-or-marker POM.
10572 If INHERIT is non-nil and the entry does not have the property,
10573 then also check higher levels of the hierarchy.
10574 If INHERIT is the symbol `selective', use inheritance only if the setting
10575 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10576 If the property is present but empty, the return value is the empty string.
10577 If the property is not present at all, nil is returned."
10578 (org-with-point-at pom
10579 (if (and inherit (if (eq inherit 'selective)
10580 (org-property-inherit-p property)
10582 (org-entry-get-with-inheritance property)
10583 (if (member property org-special-properties)
10584 ;; We need a special property. Use brute force, get all properties.
10585 (cdr (assoc property (org-entry-properties nil 'special)))
10586 (let ((range (org-get-property-block)))
10587 (if (and range
10588 (goto-char (car range))
10589 (re-search-forward
10590 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10591 (cdr range) t))
10592 ;; Found the property, return it.
10593 (if (match-end 1)
10594 (org-match-string-no-properties 1)
10595 "")))))))
10597 (defun org-property-or-variable-value (var &optional inherit)
10598 "Check if there is a property fixing the value of VAR.
10599 If yes, return this value. If not, return the current value of the variable."
10600 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10601 (if (and prop (stringp prop) (string-match "\\S-" prop))
10602 (read prop)
10603 (symbol-value var))))
10605 (defun org-entry-delete (pom property)
10606 "Delete the property PROPERTY from entry at point-or-marker POM."
10607 (org-with-point-at pom
10608 (if (member property org-special-properties)
10609 nil ; cannot delete these properties.
10610 (let ((range (org-get-property-block)))
10611 (if (and range
10612 (goto-char (car range))
10613 (re-search-forward
10614 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10615 (cdr range) t))
10616 (progn
10617 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10619 nil)))))
10621 ;; Multi-values properties are properties that contain multiple values
10622 ;; These values are assumed to be single words, separated by whitespace.
10623 (defun org-entry-add-to-multivalued-property (pom property value)
10624 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10625 (let* ((old (org-entry-get pom property))
10626 (values (and old (org-split-string old "[ \t]"))))
10627 (setq value (org-entry-protect-space value))
10628 (unless (member value values)
10629 (setq values (cons value values))
10630 (org-entry-put pom property
10631 (mapconcat 'identity values " ")))))
10633 (defun org-entry-remove-from-multivalued-property (pom property value)
10634 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10635 (let* ((old (org-entry-get pom property))
10636 (values (and old (org-split-string old "[ \t]"))))
10637 (setq value (org-entry-protect-space value))
10638 (when (member value values)
10639 (setq values (delete value values))
10640 (org-entry-put pom property
10641 (mapconcat 'identity values " ")))))
10643 (defun org-entry-member-in-multivalued-property (pom property value)
10644 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10645 (let* ((old (org-entry-get pom property))
10646 (values (and old (org-split-string old "[ \t]"))))
10647 (setq value (org-entry-protect-space value))
10648 (member value values)))
10650 (defun org-entry-get-multivalued-property (pom property)
10651 "Return a list of values in a multivalued property."
10652 (let* ((value (org-entry-get pom property))
10653 (values (and value (org-split-string value "[ \t]"))))
10654 (mapcar 'org-entry-restore-space values)))
10656 (defun org-entry-put-multivalued-property (pom property &rest values)
10657 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10658 VALUES should be a list of strings. Spaces will be protected."
10659 (org-entry-put pom property
10660 (mapconcat 'org-entry-protect-space values " "))
10661 (let* ((value (org-entry-get pom property))
10662 (values (and value (org-split-string value "[ \t]"))))
10663 (mapcar 'org-entry-restore-space values)))
10665 (defun org-entry-protect-space (s)
10666 "Protect spaces and newline in string S."
10667 (while (string-match " " s)
10668 (setq s (replace-match "%20" t t s)))
10669 (while (string-match "\n" s)
10670 (setq s (replace-match "%0A" t t s)))
10673 (defun org-entry-restore-space (s)
10674 "Restore spaces and newline in string S."
10675 (while (string-match "%20" s)
10676 (setq s (replace-match " " t t s)))
10677 (while (string-match "%0A" s)
10678 (setq s (replace-match "\n" t t s)))
10681 (defvar org-entry-property-inherited-from (make-marker)
10682 "Marker pointing to the entry from where a property was inherited.
10683 Each call to `org-entry-get-with-inheritance' will set this marker to the
10684 location of the entry where the inheritance search matched. If there was
10685 no match, the marker will point nowhere.
10686 Note that also `org-entry-get' calls this function, if the INHERIT flag
10687 is set.")
10689 (defun org-entry-get-with-inheritance (property)
10690 "Get entry property, and search higher levels if not present."
10691 (move-marker org-entry-property-inherited-from nil)
10692 (let (tmp)
10693 (save-excursion
10694 (save-restriction
10695 (widen)
10696 (catch 'ex
10697 (while t
10698 (when (setq tmp (org-entry-get nil property))
10699 (org-back-to-heading t)
10700 (move-marker org-entry-property-inherited-from (point))
10701 (throw 'ex tmp))
10702 (or (org-up-heading-safe) (throw 'ex nil)))))
10703 (or tmp
10704 (cdr (assoc property org-file-properties))
10705 (cdr (assoc property org-global-properties))
10706 (cdr (assoc property org-global-properties-fixed))))))
10708 (defun org-entry-put (pom property value)
10709 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10710 (org-with-point-at pom
10711 (org-back-to-heading t)
10712 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10713 range)
10714 (cond
10715 ((equal property "TODO")
10716 (when (and (stringp value) (string-match "\\S-" value)
10717 (not (member value org-todo-keywords-1)))
10718 (error "\"%s\" is not a valid TODO state" value))
10719 (if (or (not value)
10720 (not (string-match "\\S-" value)))
10721 (setq value 'none))
10722 (org-todo value)
10723 (org-set-tags nil 'align))
10724 ((equal property "PRIORITY")
10725 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10726 (string-to-char value) ?\ ))
10727 (org-set-tags nil 'align))
10728 ((equal property "SCHEDULED")
10729 (if (re-search-forward org-scheduled-time-regexp end t)
10730 (cond
10731 ((eq value 'earlier) (org-timestamp-change -1 'day))
10732 ((eq value 'later) (org-timestamp-change 1 'day))
10733 (t (call-interactively 'org-schedule)))
10734 (call-interactively 'org-schedule)))
10735 ((equal property "DEADLINE")
10736 (if (re-search-forward org-deadline-time-regexp end t)
10737 (cond
10738 ((eq value 'earlier) (org-timestamp-change -1 'day))
10739 ((eq value 'later) (org-timestamp-change 1 'day))
10740 (t (call-interactively 'org-deadline)))
10741 (call-interactively 'org-deadline)))
10742 ((member property org-special-properties)
10743 (error "The %s property can not yet be set with `org-entry-put'"
10744 property))
10745 (t ; a non-special property
10746 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10747 (setq range (org-get-property-block beg end 'force))
10748 (goto-char (car range))
10749 (if (re-search-forward
10750 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10751 (progn
10752 (delete-region (match-beginning 1) (match-end 1))
10753 (goto-char (match-beginning 1)))
10754 (goto-char (cdr range))
10755 (insert "\n")
10756 (backward-char 1)
10757 (org-indent-line-function)
10758 (insert ":" property ":"))
10759 (and value (insert " " value))
10760 (org-indent-line-function)))))))
10762 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10763 "Get all property keys in the current buffer.
10764 With INCLUDE-SPECIALS, also list the special properties that reflect things
10765 like tags and TODO state.
10766 With INCLUDE-DEFAULTS, also include properties that has special meaning
10767 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10768 With INCLUDE-COLUMNS, also include property names given in COLUMN
10769 formats in the current buffer."
10770 (let (rtn range cfmt s p)
10771 (save-excursion
10772 (save-restriction
10773 (widen)
10774 (goto-char (point-min))
10775 (while (re-search-forward org-property-start-re nil t)
10776 (setq range (org-get-property-block))
10777 (goto-char (car range))
10778 (while (re-search-forward
10779 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10780 (cdr range) t)
10781 (add-to-list 'rtn (org-match-string-no-properties 1)))
10782 (outline-next-heading))))
10784 (when include-specials
10785 (setq rtn (append org-special-properties rtn)))
10787 (when include-defaults
10788 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10790 (when include-columns
10791 (save-excursion
10792 (save-restriction
10793 (widen)
10794 (goto-char (point-min))
10795 (while (re-search-forward
10796 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10797 nil t)
10798 (setq cfmt (match-string 2) s 0)
10799 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10800 cfmt s)
10801 (setq s (match-end 0)
10802 p (match-string 1 cfmt))
10803 (unless (or (equal p "ITEM")
10804 (member p org-special-properties))
10805 (add-to-list 'rtn (match-string 1 cfmt))))))))
10807 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10809 (defun org-property-values (key)
10810 "Return a list of all values of property KEY."
10811 (save-excursion
10812 (save-restriction
10813 (widen)
10814 (goto-char (point-min))
10815 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10816 values)
10817 (while (re-search-forward re nil t)
10818 (add-to-list 'values (org-trim (match-string 1))))
10819 (delete "" values)))))
10821 (defun org-insert-property-drawer ()
10822 "Insert a property drawer into the current entry."
10823 (interactive)
10824 (org-back-to-heading t)
10825 (looking-at outline-regexp)
10826 (let ((indent (- (match-end 0)(match-beginning 0)))
10827 (beg (point))
10828 (re (concat "^[ \t]*" org-keyword-time-regexp))
10829 end hiddenp)
10830 (outline-next-heading)
10831 (setq end (point))
10832 (goto-char beg)
10833 (while (re-search-forward re end t))
10834 (setq hiddenp (org-invisible-p))
10835 (end-of-line 1)
10836 (and (equal (char-after) ?\n) (forward-char 1))
10837 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10838 (beginning-of-line 2))
10839 (org-skip-over-state-notes)
10840 (skip-chars-backward " \t\n\r")
10841 (if (eq (char-before) ?*) (forward-char 1))
10842 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10843 (beginning-of-line 0)
10844 (org-indent-to-column indent)
10845 (beginning-of-line 2)
10846 (org-indent-to-column indent)
10847 (beginning-of-line 0)
10848 (if hiddenp
10849 (save-excursion
10850 (org-back-to-heading t)
10851 (hide-entry))
10852 (org-flag-drawer t))))
10854 (defun org-set-property (property value)
10855 "In the current entry, set PROPERTY to VALUE.
10856 When called interactively, this will prompt for a property name, offering
10857 completion on existing and default properties. And then it will prompt
10858 for a value, offering completion either on allowed values (via an inherited
10859 xxx_ALL property) or on existing values in other instances of this property
10860 in the current file."
10861 (interactive
10862 (let* ((completion-ignore-case t)
10863 (keys (org-buffer-property-keys nil t t))
10864 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10865 (prop (if (member prop0 keys)
10866 prop0
10867 (or (cdr (assoc (downcase prop0)
10868 (mapcar (lambda (x) (cons (downcase x) x))
10869 keys)))
10870 prop0)))
10871 (cur (org-entry-get nil prop))
10872 (allowed (org-property-get-allowed-values nil prop 'table))
10873 (existing (mapcar 'list (org-property-values prop)))
10874 (val (if allowed
10875 (org-completing-read "Value: " allowed nil 'req-match)
10876 (org-completing-read
10877 (concat "Value" (if (and cur (string-match "\\S-" cur))
10878 (concat "[" cur "]") "")
10879 ": ")
10880 existing nil nil "" nil cur))))
10881 (list prop (if (equal val "") cur val))))
10882 (unless (equal (org-entry-get nil property) value)
10883 (org-entry-put nil property value)))
10885 (defun org-delete-property (property)
10886 "In the current entry, delete PROPERTY."
10887 (interactive
10888 (let* ((completion-ignore-case t)
10889 (prop (org-ido-completing-read
10890 "Property: " (org-entry-properties nil 'standard))))
10891 (list prop)))
10892 (message "Property %s %s" property
10893 (if (org-entry-delete nil property)
10894 "deleted"
10895 "was not present in the entry")))
10897 (defun org-delete-property-globally (property)
10898 "Remove PROPERTY globally, from all entries."
10899 (interactive
10900 (let* ((completion-ignore-case t)
10901 (prop (org-ido-completing-read
10902 "Globally remove property: "
10903 (mapcar 'list (org-buffer-property-keys)))))
10904 (list prop)))
10905 (save-excursion
10906 (save-restriction
10907 (widen)
10908 (goto-char (point-min))
10909 (let ((cnt 0))
10910 (while (re-search-forward
10911 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10912 nil t)
10913 (setq cnt (1+ cnt))
10914 (replace-match ""))
10915 (message "Property \"%s\" removed from %d entries" property cnt)))))
10917 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10919 (defun org-compute-property-at-point ()
10920 "Compute the property at point.
10921 This looks for an enclosing column format, extracts the operator and
10922 then applies it to the property in the column format's scope."
10923 (interactive)
10924 (unless (org-at-property-p)
10925 (error "Not at a property"))
10926 (let ((prop (org-match-string-no-properties 2)))
10927 (org-columns-get-format-and-top-level)
10928 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10929 (error "No operator defined for property %s" prop))
10930 (org-columns-compute prop)))
10932 (defun org-property-get-allowed-values (pom property &optional table)
10933 "Get allowed values for the property PROPERTY.
10934 When TABLE is non-nil, return an alist that can directly be used for
10935 completion."
10936 (let (vals)
10937 (cond
10938 ((equal property "TODO")
10939 (setq vals (org-with-point-at pom
10940 (append org-todo-keywords-1 '("")))))
10941 ((equal property "PRIORITY")
10942 (let ((n org-lowest-priority))
10943 (while (>= n org-highest-priority)
10944 (push (char-to-string n) vals)
10945 (setq n (1- n)))))
10946 ((member property org-special-properties))
10948 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10950 (when (and vals (string-match "\\S-" vals))
10951 (setq vals (car (read-from-string (concat "(" vals ")"))))
10952 (setq vals (mapcar (lambda (x)
10953 (cond ((stringp x) x)
10954 ((numberp x) (number-to-string x))
10955 ((symbolp x) (symbol-name x))
10956 (t "???")))
10957 vals)))))
10958 (if table (mapcar 'list vals) vals)))
10960 (defun org-property-previous-allowed-value (&optional previous)
10961 "Switch to the next allowed value for this property."
10962 (interactive)
10963 (org-property-next-allowed-value t))
10965 (defun org-property-next-allowed-value (&optional previous)
10966 "Switch to the next allowed value for this property."
10967 (interactive)
10968 (unless (org-at-property-p)
10969 (error "Not at a property"))
10970 (let* ((key (match-string 2))
10971 (value (match-string 3))
10972 (allowed (or (org-property-get-allowed-values (point) key)
10973 (and (member value '("[ ]" "[-]" "[X]"))
10974 '("[ ]" "[X]"))))
10975 nval)
10976 (unless allowed
10977 (error "Allowed values for this property have not been defined"))
10978 (if previous (setq allowed (reverse allowed)))
10979 (if (member value allowed)
10980 (setq nval (car (cdr (member value allowed)))))
10981 (setq nval (or nval (car allowed)))
10982 (if (equal nval value)
10983 (error "Only one allowed value for this property"))
10984 (org-at-property-p)
10985 (replace-match (concat " :" key ": " nval) t t)
10986 (org-indent-line-function)
10987 (beginning-of-line 1)
10988 (skip-chars-forward " \t")))
10990 (defun org-find-entry-with-id (ident)
10991 "Locate the entry that contains the ID property with exact value IDENT.
10992 IDENT can be a string, a symbol or a number, this function will search for
10993 the string representation of it.
10994 Return the position where this entry starts, or nil if there is no such entry."
10995 (interactive "sID: ")
10996 (let ((id (cond
10997 ((stringp ident) ident)
10998 ((symbol-name ident) (symbol-name ident))
10999 ((numberp ident) (number-to-string ident))
11000 (t (error "IDENT %s must be a string, symbol or number" ident))))
11001 (case-fold-search nil))
11002 (save-excursion
11003 (save-restriction
11004 (widen)
11005 (goto-char (point-min))
11006 (when (re-search-forward
11007 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11008 nil t)
11009 (org-back-to-heading)
11010 (point))))))
11012 ;;;; Timestamps
11014 (defvar org-last-changed-timestamp nil)
11015 (defvar org-last-inserted-timestamp nil
11016 "The last time stamp inserted with `org-insert-time-stamp'.")
11017 (defvar org-time-was-given) ; dynamically scoped parameter
11018 (defvar org-end-time-was-given) ; dynamically scoped parameter
11019 (defvar org-ts-what) ; dynamically scoped parameter
11021 (defun org-time-stamp (arg &optional inactive)
11022 "Prompt for a date/time and insert a time stamp.
11023 If the user specifies a time like HH:MM, or if this command is called
11024 with a prefix argument, the time stamp will contain date and time.
11025 Otherwise, only the date will be included. All parts of a date not
11026 specified by the user will be filled in from the current date/time.
11027 So if you press just return without typing anything, the time stamp
11028 will represent the current date/time. If there is already a timestamp
11029 at the cursor, it will be modified."
11030 (interactive "P")
11031 (let* ((ts nil)
11032 (default-time
11033 ;; Default time is either today, or, when entering a range,
11034 ;; the range start.
11035 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11036 (save-excursion
11037 (re-search-backward
11038 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11039 (- (point) 20) t)))
11040 (apply 'encode-time (org-parse-time-string (match-string 1)))
11041 (current-time)))
11042 (default-input (and ts (org-get-compact-tod ts)))
11043 org-time-was-given org-end-time-was-given time)
11044 (cond
11045 ((and (org-at-timestamp-p t)
11046 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11047 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11048 (insert "--")
11049 (setq time (let ((this-command this-command))
11050 (org-read-date arg 'totime nil nil
11051 default-time default-input)))
11052 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11053 ((org-at-timestamp-p t)
11054 (setq time (let ((this-command this-command))
11055 (org-read-date arg 'totime nil nil default-time default-input)))
11056 (when (org-at-timestamp-p t) ; just to get the match data
11057 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11058 (replace-match "")
11059 (setq org-last-changed-timestamp
11060 (org-insert-time-stamp
11061 time (or org-time-was-given arg)
11062 inactive nil nil (list org-end-time-was-given))))
11063 (message "Timestamp updated"))
11065 (setq time (let ((this-command this-command))
11066 (org-read-date arg 'totime nil nil default-time default-input)))
11067 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11068 nil nil (list org-end-time-was-given))))))
11070 ;; FIXME: can we use this for something else, like computing time differences?
11071 (defun org-get-compact-tod (s)
11072 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11073 (let* ((t1 (match-string 1 s))
11074 (h1 (string-to-number (match-string 2 s)))
11075 (m1 (string-to-number (match-string 3 s)))
11076 (t2 (and (match-end 4) (match-string 5 s)))
11077 (h2 (and t2 (string-to-number (match-string 6 s))))
11078 (m2 (and t2 (string-to-number (match-string 7 s))))
11079 dh dm)
11080 (if (not t2)
11082 (setq dh (- h2 h1) dm (- m2 m1))
11083 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11084 (concat t1 "+" (number-to-string dh)
11085 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11087 (defun org-time-stamp-inactive (&optional arg)
11088 "Insert an inactive time stamp.
11089 An inactive time stamp is enclosed in square brackets instead of angle
11090 brackets. It is inactive in the sense that it does not trigger agenda entries,
11091 does not link to the calendar and cannot be changed with the S-cursor keys.
11092 So these are more for recording a certain time/date."
11093 (interactive "P")
11094 (org-time-stamp arg 'inactive))
11096 (defvar org-date-ovl (org-make-overlay 1 1))
11097 (org-overlay-put org-date-ovl 'face 'org-warning)
11098 (org-detach-overlay org-date-ovl)
11100 (defvar org-ans1) ; dynamically scoped parameter
11101 (defvar org-ans2) ; dynamically scoped parameter
11103 (defvar org-plain-time-of-day-regexp) ; defined below
11105 (defvar org-overriding-default-time nil) ; dynamically scoped
11106 (defvar org-read-date-overlay nil)
11107 (defvar org-dcst nil) ; dynamically scoped
11109 (defun org-read-date (&optional with-time to-time from-string prompt
11110 default-time default-input)
11111 "Read a date, possibly a time, and make things smooth for the user.
11112 The prompt will suggest to enter an ISO date, but you can also enter anything
11113 which will at least partially be understood by `parse-time-string'.
11114 Unrecognized parts of the date will default to the current day, month, year,
11115 hour and minute. If this command is called to replace a timestamp at point,
11116 of to enter the second timestamp of a range, the default time is taken from the
11117 existing stamp. For example,
11118 3-2-5 --> 2003-02-05
11119 feb 15 --> currentyear-02-15
11120 sep 12 9 --> 2009-09-12
11121 12:45 --> today 12:45
11122 22 sept 0:34 --> currentyear-09-22 0:34
11123 12 --> currentyear-currentmonth-12
11124 Fri --> nearest Friday (today or later)
11125 etc.
11127 Furthermore you can specify a relative date by giving, as the *first* thing
11128 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11129 change in days weeks, months, years.
11130 With a single plus or minus, the date is relative to today. With a double
11131 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11132 +4d --> four days from today
11133 +4 --> same as above
11134 +2w --> two weeks from today
11135 ++5 --> five days from default date
11137 The function understands only English month and weekday abbreviations,
11138 but this can be configured with the variables `parse-time-months' and
11139 `parse-time-weekdays'.
11141 While prompting, a calendar is popped up - you can also select the
11142 date with the mouse (button 1). The calendar shows a period of three
11143 months. To scroll it to other months, use the keys `>' and `<'.
11144 If you don't like the calendar, turn it off with
11145 \(setq org-read-date-popup-calendar nil)
11147 With optional argument TO-TIME, the date will immediately be converted
11148 to an internal time.
11149 With an optional argument WITH-TIME, the prompt will suggest to also
11150 insert a time. Note that when WITH-TIME is not set, you can still
11151 enter a time, and this function will inform the calling routine about
11152 this change. The calling routine may then choose to change the format
11153 used to insert the time stamp into the buffer to include the time.
11154 With optional argument FROM-STRING, read from this string instead from
11155 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11156 the time/date that is used for everything that is not specified by the
11157 user."
11158 (require 'parse-time)
11159 (let* ((org-time-stamp-rounding-minutes
11160 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11161 (org-dcst org-display-custom-times)
11162 (ct (org-current-time))
11163 (def (or org-overriding-default-time default-time ct))
11164 (defdecode (decode-time def))
11165 (dummy (progn
11166 (when (< (nth 2 defdecode) org-extend-today-until)
11167 (setcar (nthcdr 2 defdecode) -1)
11168 (setcar (nthcdr 1 defdecode) 59)
11169 (setq def (apply 'encode-time defdecode)
11170 defdecode (decode-time def)))))
11171 (calendar-move-hook nil)
11172 (calendar-view-diary-initially-flag nil)
11173 (view-diary-entries-initially nil)
11174 (calendar-view-holidays-initially-flag nil)
11175 (view-calendar-holidays-initially nil)
11176 (timestr (format-time-string
11177 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11178 (prompt (concat (if prompt (concat prompt " ") "")
11179 (format "Date+time [%s]: " timestr)))
11180 ans (org-ans0 "") org-ans1 org-ans2 final)
11182 (cond
11183 (from-string (setq ans from-string))
11184 (org-read-date-popup-calendar
11185 (save-excursion
11186 (save-window-excursion
11187 (calendar)
11188 (calendar-forward-day (- (time-to-days def)
11189 (calendar-absolute-from-gregorian
11190 (calendar-current-date))))
11191 (org-eval-in-calendar nil t)
11192 (let* ((old-map (current-local-map))
11193 (map (copy-keymap calendar-mode-map))
11194 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11195 (org-defkey map (kbd "RET") 'org-calendar-select)
11196 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11197 'org-calendar-select-mouse)
11198 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11199 'org-calendar-select-mouse)
11200 (org-defkey minibuffer-local-map [(meta shift left)]
11201 (lambda () (interactive)
11202 (org-eval-in-calendar '(calendar-backward-month 1))))
11203 (org-defkey minibuffer-local-map [(meta shift right)]
11204 (lambda () (interactive)
11205 (org-eval-in-calendar '(calendar-forward-month 1))))
11206 (org-defkey minibuffer-local-map [(meta shift up)]
11207 (lambda () (interactive)
11208 (org-eval-in-calendar '(calendar-backward-year 1))))
11209 (org-defkey minibuffer-local-map [(meta shift down)]
11210 (lambda () (interactive)
11211 (org-eval-in-calendar '(calendar-forward-year 1))))
11212 (org-defkey minibuffer-local-map [(shift up)]
11213 (lambda () (interactive)
11214 (org-eval-in-calendar '(calendar-backward-week 1))))
11215 (org-defkey minibuffer-local-map [(shift down)]
11216 (lambda () (interactive)
11217 (org-eval-in-calendar '(calendar-forward-week 1))))
11218 (org-defkey minibuffer-local-map [(shift left)]
11219 (lambda () (interactive)
11220 (org-eval-in-calendar '(calendar-backward-day 1))))
11221 (org-defkey minibuffer-local-map [(shift right)]
11222 (lambda () (interactive)
11223 (org-eval-in-calendar '(calendar-forward-day 1))))
11224 (org-defkey minibuffer-local-map ">"
11225 (lambda () (interactive)
11226 (org-eval-in-calendar '(scroll-calendar-left 1))))
11227 (org-defkey minibuffer-local-map "<"
11228 (lambda () (interactive)
11229 (org-eval-in-calendar '(scroll-calendar-right 1))))
11230 (unwind-protect
11231 (progn
11232 (use-local-map map)
11233 (add-hook 'post-command-hook 'org-read-date-display)
11234 (setq org-ans0 (read-string prompt default-input nil nil))
11235 ;; org-ans0: from prompt
11236 ;; org-ans1: from mouse click
11237 ;; org-ans2: from calendar motion
11238 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11239 (remove-hook 'post-command-hook 'org-read-date-display)
11240 (use-local-map old-map)
11241 (when org-read-date-overlay
11242 (org-delete-overlay org-read-date-overlay)
11243 (setq org-read-date-overlay nil)))))))
11245 (t ; Naked prompt only
11246 (unwind-protect
11247 (setq ans (read-string prompt default-input nil timestr))
11248 (when org-read-date-overlay
11249 (org-delete-overlay org-read-date-overlay)
11250 (setq org-read-date-overlay nil)))))
11252 (setq final (org-read-date-analyze ans def defdecode))
11254 (if to-time
11255 (apply 'encode-time final)
11256 (if (and (boundp 'org-time-was-given) org-time-was-given)
11257 (format "%04d-%02d-%02d %02d:%02d"
11258 (nth 5 final) (nth 4 final) (nth 3 final)
11259 (nth 2 final) (nth 1 final))
11260 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11261 (defvar def)
11262 (defvar defdecode)
11263 (defvar with-time)
11264 (defun org-read-date-display ()
11265 "Display the current date prompt interpretation in the minibuffer."
11266 (when org-read-date-display-live
11267 (when org-read-date-overlay
11268 (org-delete-overlay org-read-date-overlay))
11269 (let ((p (point)))
11270 (end-of-line 1)
11271 (while (not (equal (buffer-substring
11272 (max (point-min) (- (point) 4)) (point))
11273 " "))
11274 (insert " "))
11275 (goto-char p))
11276 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11277 " " (or org-ans1 org-ans2)))
11278 (org-end-time-was-given nil)
11279 (f (org-read-date-analyze ans def defdecode))
11280 (fmts (if org-dcst
11281 org-time-stamp-custom-formats
11282 org-time-stamp-formats))
11283 (fmt (if (or with-time
11284 (and (boundp 'org-time-was-given) org-time-was-given))
11285 (cdr fmts)
11286 (car fmts)))
11287 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11288 (when (and org-end-time-was-given
11289 (string-match org-plain-time-of-day-regexp txt))
11290 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11291 org-end-time-was-given
11292 (substring txt (match-end 0)))))
11293 (setq org-read-date-overlay
11294 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11295 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11297 (defun org-read-date-analyze (ans def defdecode)
11298 "Analyse the combined answer of the date prompt."
11299 ;; FIXME: cleanup and comment
11300 (let (delta deltan deltaw deltadef year month day
11301 hour minute second wday pm h2 m2 tl wday1
11302 iso-year iso-weekday iso-week iso-year iso-date)
11304 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11305 (setq ans "+0"))
11307 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11308 (setq ans (replace-match "" t t ans)
11309 deltan (car delta)
11310 deltaw (nth 1 delta)
11311 deltadef (nth 2 delta)))
11313 ;; Check if there is an iso week date in there
11314 ;; If yes, sore the info and postpone interpreting it until the rest
11315 ;; of the parsing is done
11316 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11317 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11318 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11319 iso-week (string-to-number (match-string 2 ans)))
11320 (setq ans (replace-match "" t t ans)))
11322 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11323 (when (string-match
11324 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11325 (setq year (if (match-end 2)
11326 (string-to-number (match-string 2 ans))
11327 (string-to-number (format-time-string "%Y")))
11328 month (string-to-number (match-string 3 ans))
11329 day (string-to-number (match-string 4 ans)))
11330 (if (< year 100) (setq year (+ 2000 year)))
11331 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11332 t nil ans)))
11333 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11334 ;; If there is a time with am/pm, and *no* time without it, we convert
11335 ;; so that matching will be successful.
11336 (loop for i from 1 to 2 do ; twice, for end time as well
11337 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11338 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11339 (setq hour (string-to-number (match-string 1 ans))
11340 minute (if (match-end 3)
11341 (string-to-number (match-string 3 ans))
11343 pm (equal ?p
11344 (string-to-char (downcase (match-string 4 ans)))))
11345 (if (and (= hour 12) (not pm))
11346 (setq hour 0)
11347 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11348 (setq ans (replace-match (format "%02d:%02d" hour minute)
11349 t t ans))))
11351 ;; Check if a time range is given as a duration
11352 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11353 (setq hour (string-to-number (match-string 1 ans))
11354 h2 (+ hour (string-to-number (match-string 3 ans)))
11355 minute (string-to-number (match-string 2 ans))
11356 m2 (+ minute (if (match-end 5) (string-to-number
11357 (match-string 5 ans))0)))
11358 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11359 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11360 t t ans)))
11362 ;; Check if there is a time range
11363 (when (boundp 'org-end-time-was-given)
11364 (setq org-time-was-given nil)
11365 (when (and (string-match org-plain-time-of-day-regexp ans)
11366 (match-end 8))
11367 (setq org-end-time-was-given (match-string 8 ans))
11368 (setq ans (concat (substring ans 0 (match-beginning 7))
11369 (substring ans (match-end 7))))))
11371 (setq tl (parse-time-string ans)
11372 day (or (nth 3 tl) (nth 3 defdecode))
11373 month (or (nth 4 tl)
11374 (if (and org-read-date-prefer-future
11375 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11376 (1+ (nth 4 defdecode))
11377 (nth 4 defdecode)))
11378 year (or (nth 5 tl)
11379 (if (and org-read-date-prefer-future
11380 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11381 (1+ (nth 5 defdecode))
11382 (nth 5 defdecode)))
11383 hour (or (nth 2 tl) (nth 2 defdecode))
11384 minute (or (nth 1 tl) (nth 1 defdecode))
11385 second (or (nth 0 tl) 0)
11386 wday (nth 6 tl))
11388 ;; Special date definitions below
11389 (cond
11390 (iso-week
11391 ;; There was an iso week
11392 (setq year (or iso-year year)
11393 day (or iso-weekday wday 1)
11394 wday nil ; to make sure that the trigger below does not match
11395 iso-date (calendar-gregorian-from-absolute
11396 (calendar-absolute-from-iso
11397 (list iso-week day year))))
11398 ; FIXME: Should we also push ISO weeks into the future?
11399 ; (when (and org-read-date-prefer-future
11400 ; (not iso-year)
11401 ; (< (calendar-absolute-from-gregorian iso-date)
11402 ; (time-to-days (current-time))))
11403 ; (setq year (1+ year)
11404 ; iso-date (calendar-gregorian-from-absolute
11405 ; (calendar-absolute-from-iso
11406 ; (list iso-week day year)))))
11407 (setq month (car iso-date)
11408 year (nth 2 iso-date)
11409 day (nth 1 iso-date)))
11410 (deltan
11411 (unless deltadef
11412 (let ((now (decode-time (current-time))))
11413 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11414 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11415 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11416 ((equal deltaw "m") (setq month (+ month deltan)))
11417 ((equal deltaw "y") (setq year (+ year deltan)))))
11418 ((and wday (not (nth 3 tl)))
11419 ;; Weekday was given, but no day, so pick that day in the week
11420 ;; on or after the derived date.
11421 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11422 (unless (equal wday wday1)
11423 (setq day (+ day (% (- wday wday1 -7) 7))))))
11424 (if (and (boundp 'org-time-was-given)
11425 (nth 2 tl))
11426 (setq org-time-was-given t))
11427 (if (< year 100) (setq year (+ 2000 year)))
11428 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11429 (list second minute hour day month year)))
11431 (defvar parse-time-weekdays)
11433 (defun org-read-date-get-relative (s today default)
11434 "Check string S for special relative date string.
11435 TODAY and DEFAULT are internal times, for today and for a default.
11436 Return shift list (N what def-flag)
11437 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11438 N is the number of WHATs to shift.
11439 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11440 the DEFAULT date rather than TODAY."
11441 (when (and
11442 (string-match
11443 (concat
11444 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11445 "\\([0-9]+\\)?"
11446 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11447 "\\([ \t]\\|$\\)") s)
11448 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11449 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11450 (string-to-char (substring (match-string 1 s) -1))
11451 ?+))
11452 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11453 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11454 (what (if (match-end 3) (match-string 3 s) "d"))
11455 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11456 (date (if rel default today))
11457 (wday (nth 6 (decode-time date)))
11458 delta)
11459 (if wday1
11460 (progn
11461 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11462 (if (= dir ?-) (setq delta (- delta 7)))
11463 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11464 (list delta "d" rel))
11465 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11467 (defun org-eval-in-calendar (form &optional keepdate)
11468 "Eval FORM in the calendar window and return to current window.
11469 Also, store the cursor date in variable org-ans2."
11470 (let ((sw (selected-window)))
11471 (select-window (get-buffer-window "*Calendar*"))
11472 (eval form)
11473 (when (and (not keepdate) (calendar-cursor-to-date))
11474 (let* ((date (calendar-cursor-to-date))
11475 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11476 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11477 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11478 (select-window sw)))
11480 (defun org-calendar-select ()
11481 "Return to `org-read-date' with the date currently selected.
11482 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11483 (interactive)
11484 (when (calendar-cursor-to-date)
11485 (let* ((date (calendar-cursor-to-date))
11486 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11487 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11488 (if (active-minibuffer-window) (exit-minibuffer))))
11490 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11491 "Insert a date stamp for the date given by the internal TIME.
11492 WITH-HM means, use the stamp format that includes the time of the day.
11493 INACTIVE means use square brackets instead of angular ones, so that the
11494 stamp will not contribute to the agenda.
11495 PRE and POST are optional strings to be inserted before and after the
11496 stamp.
11497 The command returns the inserted time stamp."
11498 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11499 stamp)
11500 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11501 (insert-before-markers (or pre ""))
11502 (insert-before-markers (setq stamp (format-time-string fmt time)))
11503 (when (listp extra)
11504 (setq extra (car extra))
11505 (if (and (stringp extra)
11506 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11507 (setq extra (format "-%02d:%02d"
11508 (string-to-number (match-string 1 extra))
11509 (string-to-number (match-string 2 extra))))
11510 (setq extra nil)))
11511 (when extra
11512 (backward-char 1)
11513 (insert-before-markers extra)
11514 (forward-char 1))
11515 (insert-before-markers (or post ""))
11516 (setq org-last-inserted-timestamp stamp)))
11518 (defun org-toggle-time-stamp-overlays ()
11519 "Toggle the use of custom time stamp formats."
11520 (interactive)
11521 (setq org-display-custom-times (not org-display-custom-times))
11522 (unless org-display-custom-times
11523 (let ((p (point-min)) (bmp (buffer-modified-p)))
11524 (while (setq p (next-single-property-change p 'display))
11525 (if (and (get-text-property p 'display)
11526 (eq (get-text-property p 'face) 'org-date))
11527 (remove-text-properties
11528 p (setq p (next-single-property-change p 'display))
11529 '(display t))))
11530 (set-buffer-modified-p bmp)))
11531 (if (featurep 'xemacs)
11532 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11533 (org-restart-font-lock)
11534 (setq org-table-may-need-update t)
11535 (if org-display-custom-times
11536 (message "Time stamps are overlayed with custom format")
11537 (message "Time stamp overlays removed")))
11539 (defun org-display-custom-time (beg end)
11540 "Overlay modified time stamp format over timestamp between BEG and END."
11541 (let* ((ts (buffer-substring beg end))
11542 t1 w1 with-hm tf time str w2 (off 0))
11543 (save-match-data
11544 (setq t1 (org-parse-time-string ts t))
11545 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11546 (setq off (- (match-end 0) (match-beginning 0)))))
11547 (setq end (- end off))
11548 (setq w1 (- end beg)
11549 with-hm (and (nth 1 t1) (nth 2 t1))
11550 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11551 time (org-fix-decoded-time t1)
11552 str (org-add-props
11553 (format-time-string
11554 (substring tf 1 -1) (apply 'encode-time time))
11555 nil 'mouse-face 'highlight)
11556 w2 (length str))
11557 (if (not (= w2 w1))
11558 (add-text-properties (1+ beg) (+ 2 beg)
11559 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11560 (if (featurep 'xemacs)
11561 (progn
11562 (put-text-property beg end 'invisible t)
11563 (put-text-property beg end 'end-glyph (make-glyph str)))
11564 (put-text-property beg end 'display str))))
11566 (defun org-translate-time (string)
11567 "Translate all timestamps in STRING to custom format.
11568 But do this only if the variable `org-display-custom-times' is set."
11569 (when org-display-custom-times
11570 (save-match-data
11571 (let* ((start 0)
11572 (re org-ts-regexp-both)
11573 t1 with-hm inactive tf time str beg end)
11574 (while (setq start (string-match re string start))
11575 (setq beg (match-beginning 0)
11576 end (match-end 0)
11577 t1 (save-match-data
11578 (org-parse-time-string (substring string beg end) t))
11579 with-hm (and (nth 1 t1) (nth 2 t1))
11580 inactive (equal (substring string beg (1+ beg)) "[")
11581 tf (funcall (if with-hm 'cdr 'car)
11582 org-time-stamp-custom-formats)
11583 time (org-fix-decoded-time t1)
11584 str (format-time-string
11585 (concat
11586 (if inactive "[" "<") (substring tf 1 -1)
11587 (if inactive "]" ">"))
11588 (apply 'encode-time time))
11589 string (replace-match str t t string)
11590 start (+ start (length str)))))))
11591 string)
11593 (defun org-fix-decoded-time (time)
11594 "Set 0 instead of nil for the first 6 elements of time.
11595 Don't touch the rest."
11596 (let ((n 0))
11597 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11599 (defun org-days-to-time (timestamp-string)
11600 "Difference between TIMESTAMP-STRING and now in days."
11601 (- (time-to-days (org-time-string-to-time timestamp-string))
11602 (time-to-days (current-time))))
11604 (defun org-deadline-close (timestamp-string &optional ndays)
11605 "Is the time in TIMESTAMP-STRING close to the current date?"
11606 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11607 (and (< (org-days-to-time timestamp-string) ndays)
11608 (not (org-entry-is-done-p))))
11610 (defun org-get-wdays (ts)
11611 "Get the deadline lead time appropriate for timestring TS."
11612 (cond
11613 ((<= org-deadline-warning-days 0)
11614 ;; 0 or negative, enforce this value no matter what
11615 (- org-deadline-warning-days))
11616 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11617 ;; lead time is specified.
11618 (floor (* (string-to-number (match-string 1 ts))
11619 (cdr (assoc (match-string 2 ts)
11620 '(("d" . 1) ("w" . 7)
11621 ("m" . 30.4) ("y" . 365.25)))))))
11622 ;; go for the default.
11623 (t org-deadline-warning-days)))
11625 (defun org-calendar-select-mouse (ev)
11626 "Return to `org-read-date' with the date currently selected.
11627 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11628 (interactive "e")
11629 (mouse-set-point ev)
11630 (when (calendar-cursor-to-date)
11631 (let* ((date (calendar-cursor-to-date))
11632 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11633 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11634 (if (active-minibuffer-window) (exit-minibuffer))))
11636 (defun org-check-deadlines (ndays)
11637 "Check if there are any deadlines due or past due.
11638 A deadline is considered due if it happens within `org-deadline-warning-days'
11639 days from today's date. If the deadline appears in an entry marked DONE,
11640 it is not shown. The prefix arg NDAYS can be used to test that many
11641 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11642 (interactive "P")
11643 (let* ((org-warn-days
11644 (cond
11645 ((equal ndays '(4)) 100000)
11646 (ndays (prefix-numeric-value ndays))
11647 (t (abs org-deadline-warning-days))))
11648 (case-fold-search nil)
11649 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11650 (callback
11651 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11653 (message "%d deadlines past-due or due within %d days"
11654 (org-occur regexp nil callback)
11655 org-warn-days)))
11657 (defun org-check-before-date (date)
11658 "Check if there are deadlines or scheduled entries before DATE."
11659 (interactive (list (org-read-date)))
11660 (let ((case-fold-search nil)
11661 (regexp (concat "\\<\\(" org-deadline-string
11662 "\\|" org-scheduled-string
11663 "\\) *<\\([^>]+\\)>"))
11664 (callback
11665 (lambda () (time-less-p
11666 (org-time-string-to-time (match-string 2))
11667 (org-time-string-to-time date)))))
11668 (message "%d entries before %s"
11669 (org-occur regexp nil callback) date)))
11671 (defun org-evaluate-time-range (&optional to-buffer)
11672 "Evaluate a time range by computing the difference between start and end.
11673 Normally the result is just printed in the echo area, but with prefix arg
11674 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11675 If the time range is actually in a table, the result is inserted into the
11676 next column.
11677 For time difference computation, a year is assumed to be exactly 365
11678 days in order to avoid rounding problems."
11679 (interactive "P")
11681 (org-clock-update-time-maybe)
11682 (save-excursion
11683 (unless (org-at-date-range-p t)
11684 (goto-char (point-at-bol))
11685 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11686 (if (not (org-at-date-range-p t))
11687 (error "Not at a time-stamp range, and none found in current line")))
11688 (let* ((ts1 (match-string 1))
11689 (ts2 (match-string 2))
11690 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11691 (match-end (match-end 0))
11692 (time1 (org-time-string-to-time ts1))
11693 (time2 (org-time-string-to-time ts2))
11694 (t1 (time-to-seconds time1))
11695 (t2 (time-to-seconds time2))
11696 (diff (abs (- t2 t1)))
11697 (negative (< (- t2 t1) 0))
11698 ;; (ys (floor (* 365 24 60 60)))
11699 (ds (* 24 60 60))
11700 (hs (* 60 60))
11701 (fy "%dy %dd %02d:%02d")
11702 (fy1 "%dy %dd")
11703 (fd "%dd %02d:%02d")
11704 (fd1 "%dd")
11705 (fh "%02d:%02d")
11706 y d h m align)
11707 (if havetime
11708 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11710 d (floor (/ diff ds)) diff (mod diff ds)
11711 h (floor (/ diff hs)) diff (mod diff hs)
11712 m (floor (/ diff 60)))
11713 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11715 d (floor (+ (/ diff ds) 0.5))
11716 h 0 m 0))
11717 (if (not to-buffer)
11718 (message "%s" (org-make-tdiff-string y d h m))
11719 (if (org-at-table-p)
11720 (progn
11721 (goto-char match-end)
11722 (setq align t)
11723 (and (looking-at " *|") (goto-char (match-end 0))))
11724 (goto-char match-end))
11725 (if (looking-at
11726 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11727 (replace-match ""))
11728 (if negative (insert " -"))
11729 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11730 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11731 (insert " " (format fh h m))))
11732 (if align (org-table-align))
11733 (message "Time difference inserted")))))
11735 (defun org-make-tdiff-string (y d h m)
11736 (let ((fmt "")
11737 (l nil))
11738 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11739 l (push y l)))
11740 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11741 l (push d l)))
11742 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11743 l (push h l)))
11744 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11745 l (push m l)))
11746 (apply 'format fmt (nreverse l))))
11748 (defun org-time-string-to-time (s)
11749 (apply 'encode-time (org-parse-time-string s)))
11751 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11752 "Convert a time stamp to an absolute day number.
11753 If there is a specifyer for a cyclic time stamp, get the closest date to
11754 DAYNR.
11755 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11756 (cond
11757 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11758 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11759 daynr
11760 (+ daynr 1000)))
11761 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11762 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11763 (time-to-days (current-time))) (match-string 0 s)
11764 prefer show-all))
11765 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11767 (defun org-days-to-iso-week (days)
11768 "Return the iso week number."
11769 (require 'cal-iso)
11770 (car (calendar-iso-from-absolute days)))
11772 (defun org-small-year-to-year (year)
11773 "Convert 2-digit years into 4-digit years.
11774 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11775 The year 2000 cannot be abbreviated. Any year larger than 99
11776 is returned unchanged."
11777 (if (< year 38)
11778 (setq year (+ 2000 year))
11779 (if (< year 100)
11780 (setq year (+ 1900 year))))
11781 year)
11783 (defun org-time-from-absolute (d)
11784 "Return the time corresponding to date D.
11785 D may be an absolute day number, or a calendar-type list (month day year)."
11786 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11787 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11789 (defun org-calendar-holiday ()
11790 "List of holidays, for Diary display in Org-mode."
11791 (require 'holidays)
11792 (let ((hl (funcall
11793 (if (fboundp 'calendar-check-holidays)
11794 'calendar-check-holidays 'check-calendar-holidays) date)))
11795 (if hl (mapconcat 'identity hl "; "))))
11797 (defun org-diary-sexp-entry (sexp entry date)
11798 "Process a SEXP diary ENTRY for DATE."
11799 (require 'diary-lib)
11800 (let ((result (if calendar-debug-sexp
11801 (let ((stack-trace-on-error t))
11802 (eval (car (read-from-string sexp))))
11803 (condition-case nil
11804 (eval (car (read-from-string sexp)))
11805 (error
11806 (beep)
11807 (message "Bad sexp at line %d in %s: %s"
11808 (org-current-line)
11809 (buffer-file-name) sexp)
11810 (sleep-for 2))))))
11811 (cond ((stringp result) result)
11812 ((and (consp result)
11813 (stringp (cdr result))) (cdr result))
11814 (result entry)
11815 (t nil))))
11817 (defun org-diary-to-ical-string (frombuf)
11818 "Get iCalendar entries from diary entries in buffer FROMBUF.
11819 This uses the icalendar.el library."
11820 (let* ((tmpdir (if (featurep 'xemacs)
11821 (temp-directory)
11822 temporary-file-directory))
11823 (tmpfile (make-temp-name
11824 (expand-file-name "orgics" tmpdir)))
11825 buf rtn b e)
11826 (save-excursion
11827 (set-buffer frombuf)
11828 (icalendar-export-region (point-min) (point-max) tmpfile)
11829 (setq buf (find-buffer-visiting tmpfile))
11830 (set-buffer buf)
11831 (goto-char (point-min))
11832 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11833 (setq b (match-beginning 0)))
11834 (goto-char (point-max))
11835 (if (re-search-backward "^END:VEVENT" nil t)
11836 (setq e (match-end 0)))
11837 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11838 (kill-buffer buf)
11839 (delete-file tmpfile)
11840 rtn))
11842 (defun org-closest-date (start current change prefer show-all)
11843 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11844 When PREFER is `past' return a date that is either CURRENT or past.
11845 When PREFER is `future', return a date that is either CURRENT or future.
11846 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11847 ;; Make the proper lists from the dates
11848 (catch 'exit
11849 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11850 dn dw sday cday n1 n2 n0
11851 d m y y1 y2 date1 date2 nmonths nm ny m2)
11853 (setq start (org-date-to-gregorian start)
11854 current (org-date-to-gregorian
11855 (if show-all
11856 current
11857 (time-to-days (current-time))))
11858 sday (calendar-absolute-from-gregorian start)
11859 cday (calendar-absolute-from-gregorian current))
11861 (if (<= cday sday) (throw 'exit sday))
11863 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11864 (setq dn (string-to-number (match-string 1 change))
11865 dw (cdr (assoc (match-string 2 change) a1)))
11866 (error "Invalid change specifyer: %s" change))
11867 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11868 (cond
11869 ((eq dw 'day)
11870 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11871 n2 (+ n1 dn)))
11872 ((eq dw 'year)
11873 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11874 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11875 (setq date1 (list m d y1)
11876 n1 (calendar-absolute-from-gregorian date1)
11877 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11878 n2 (calendar-absolute-from-gregorian date2)))
11879 ((eq dw 'month)
11880 ;; approx number of month between the two dates
11881 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11882 ;; How often does dn fit in there?
11883 (setq d (nth 1 start) m (car start) y (nth 2 start)
11884 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11885 m (+ m nm)
11886 ny (floor (/ m 12))
11887 y (+ y ny)
11888 m (- m (* ny 12)))
11889 (while (> m 12) (setq m (- m 12) y (1+ y)))
11890 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11891 (setq m2 (+ m dn) y2 y)
11892 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11893 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11894 (while (<= n2 cday)
11895 (setq n1 n2 m m2 y y2)
11896 (setq m2 (+ m dn) y2 y)
11897 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11898 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11899 ;; Make sure n1 is the earlier date
11900 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11901 (if show-all
11902 (cond
11903 ((eq prefer 'past) n1)
11904 ((eq prefer 'future) (if (= cday n1) n1 n2))
11905 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11906 (cond
11907 ((eq prefer 'past) n1)
11908 ((eq prefer 'future) (if (= cday n1) n1 n2))
11909 (t (if (= cday n1) n1 n2)))))))
11911 (defun org-date-to-gregorian (date)
11912 "Turn any specification of DATE into a gregorian date for the calendar."
11913 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11914 ((and (listp date) (= (length date) 3)) date)
11915 ((stringp date)
11916 (setq date (org-parse-time-string date))
11917 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11918 ((listp date)
11919 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11921 (defun org-parse-time-string (s &optional nodefault)
11922 "Parse the standard Org-mode time string.
11923 This should be a lot faster than the normal `parse-time-string'.
11924 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11925 hour and minute fields will be nil if not given."
11926 (if (string-match org-ts-regexp0 s)
11927 (list 0
11928 (if (or (match-beginning 8) (not nodefault))
11929 (string-to-number (or (match-string 8 s) "0")))
11930 (if (or (match-beginning 7) (not nodefault))
11931 (string-to-number (or (match-string 7 s) "0")))
11932 (string-to-number (match-string 4 s))
11933 (string-to-number (match-string 3 s))
11934 (string-to-number (match-string 2 s))
11935 nil nil nil)
11936 (make-list 9 0)))
11938 (defun org-timestamp-up (&optional arg)
11939 "Increase the date item at the cursor by one.
11940 If the cursor is on the year, change the year. If it is on the month or
11941 the day, change that.
11942 With prefix ARG, change by that many units."
11943 (interactive "p")
11944 (org-timestamp-change (prefix-numeric-value arg)))
11946 (defun org-timestamp-down (&optional arg)
11947 "Decrease the date item at the cursor by one.
11948 If the cursor is on the year, change the year. If it is on the month or
11949 the day, change that.
11950 With prefix ARG, change by that many units."
11951 (interactive "p")
11952 (org-timestamp-change (- (prefix-numeric-value arg))))
11954 (defun org-timestamp-up-day (&optional arg)
11955 "Increase the date in the time stamp by one day.
11956 With prefix ARG, change that many days."
11957 (interactive "p")
11958 (if (and (not (org-at-timestamp-p t))
11959 (org-on-heading-p))
11960 (org-todo 'up)
11961 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11963 (defun org-timestamp-down-day (&optional arg)
11964 "Decrease the date in the time stamp by one day.
11965 With prefix ARG, change that many days."
11966 (interactive "p")
11967 (if (and (not (org-at-timestamp-p t))
11968 (org-on-heading-p))
11969 (org-todo 'down)
11970 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11972 (defun org-at-timestamp-p (&optional inactive-ok)
11973 "Determine if the cursor is in or at a timestamp."
11974 (interactive)
11975 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11976 (pos (point))
11977 (ans (or (looking-at tsr)
11978 (save-excursion
11979 (skip-chars-backward "^[<\n\r\t")
11980 (if (> (point) (point-min)) (backward-char 1))
11981 (and (looking-at tsr)
11982 (> (- (match-end 0) pos) -1))))))
11983 (and ans
11984 (boundp 'org-ts-what)
11985 (setq org-ts-what
11986 (cond
11987 ((= pos (match-beginning 0)) 'bracket)
11988 ((= pos (1- (match-end 0))) 'bracket)
11989 ((org-pos-in-match-range pos 2) 'year)
11990 ((org-pos-in-match-range pos 3) 'month)
11991 ((org-pos-in-match-range pos 7) 'hour)
11992 ((org-pos-in-match-range pos 8) 'minute)
11993 ((or (org-pos-in-match-range pos 4)
11994 (org-pos-in-match-range pos 5)) 'day)
11995 ((and (> pos (or (match-end 8) (match-end 5)))
11996 (< pos (match-end 0)))
11997 (- pos (or (match-end 8) (match-end 5))))
11998 (t 'day))))
11999 ans))
12001 (defun org-toggle-timestamp-type ()
12002 "Toggle the type (<active> or [inactive]) of a time stamp."
12003 (interactive)
12004 (when (org-at-timestamp-p t)
12005 (let ((beg (match-beginning 0)) (end (match-end 0))
12006 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12007 (save-excursion
12008 (goto-char beg)
12009 (while (re-search-forward "[][<>]" end t)
12010 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12011 t t)))
12012 (message "Timestamp is now %sactive"
12013 (if (equal (char-after beg) ?<) "" "in")))))
12015 (defun org-timestamp-change (n &optional what)
12016 "Change the date in the time stamp at point.
12017 The date will be changed by N times WHAT. WHAT can be `day', `month',
12018 `year', `minute', `second'. If WHAT is not given, the cursor position
12019 in the timestamp determines what will be changed."
12020 (let ((pos (point))
12021 with-hm inactive
12022 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12023 org-ts-what
12024 extra rem
12025 ts time time0)
12026 (if (not (org-at-timestamp-p t))
12027 (error "Not at a timestamp"))
12028 (if (and (not what) (eq org-ts-what 'bracket))
12029 (org-toggle-timestamp-type)
12030 (if (and (not what) (not (eq org-ts-what 'day))
12031 org-display-custom-times
12032 (get-text-property (point) 'display)
12033 (not (get-text-property (1- (point)) 'display)))
12034 (setq org-ts-what 'day))
12035 (setq org-ts-what (or what org-ts-what)
12036 inactive (= (char-after (match-beginning 0)) ?\[)
12037 ts (match-string 0))
12038 (replace-match "")
12039 (if (string-match
12040 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12042 (setq extra (match-string 1 ts)))
12043 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12044 (setq with-hm t))
12045 (setq time0 (org-parse-time-string ts))
12046 (when (and (eq org-ts-what 'minute)
12047 (eq current-prefix-arg nil))
12048 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12049 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12050 (setcar (cdr time0) (+ (nth 1 time0)
12051 (if (> n 0) (- rem) (- dm rem))))))
12052 (setq time
12053 (encode-time (or (car time0) 0)
12054 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12055 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12056 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12057 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12058 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12059 (nthcdr 6 time0)))
12060 (when (integerp org-ts-what)
12061 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12062 (if (eq what 'calendar)
12063 (let ((cal-date (org-get-date-from-calendar)))
12064 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12065 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12066 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12067 (setcar time0 (or (car time0) 0))
12068 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12069 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12070 (setq time (apply 'encode-time time0))))
12071 (setq org-last-changed-timestamp
12072 (org-insert-time-stamp time with-hm inactive nil nil extra))
12073 (org-clock-update-time-maybe)
12074 (goto-char pos)
12075 ;; Try to recenter the calendar window, if any
12076 (if (and org-calendar-follow-timestamp-change
12077 (get-buffer-window "*Calendar*" t)
12078 (memq org-ts-what '(day month year)))
12079 (org-recenter-calendar (time-to-days time))))))
12081 (defun org-modify-ts-extra (s pos n dm)
12082 "Change the different parts of the lead-time and repeat fields in timestamp."
12083 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12084 ng h m new rem)
12085 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12086 (cond
12087 ((or (org-pos-in-match-range pos 2)
12088 (org-pos-in-match-range pos 3))
12089 (setq m (string-to-number (match-string 3 s))
12090 h (string-to-number (match-string 2 s)))
12091 (if (org-pos-in-match-range pos 2)
12092 (setq h (+ h n))
12093 (setq n (* dm (org-no-warnings (signum n))))
12094 (when (not (= 0 (setq rem (% m dm))))
12095 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12096 (setq m (+ m n)))
12097 (if (< m 0) (setq m (+ m 60) h (1- h)))
12098 (if (> m 59) (setq m (- m 60) h (1+ h)))
12099 (setq h (min 24 (max 0 h)))
12100 (setq ng 1 new (format "-%02d:%02d" h m)))
12101 ((org-pos-in-match-range pos 6)
12102 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12103 ((org-pos-in-match-range pos 5)
12104 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12106 ((org-pos-in-match-range pos 9)
12107 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12108 ((org-pos-in-match-range pos 8)
12109 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12111 (when ng
12112 (setq s (concat
12113 (substring s 0 (match-beginning ng))
12115 (substring s (match-end ng))))))
12118 (defun org-recenter-calendar (date)
12119 "If the calendar is visible, recenter it to DATE."
12120 (let* ((win (selected-window))
12121 (cwin (get-buffer-window "*Calendar*" t))
12122 (calendar-move-hook nil))
12123 (when cwin
12124 (select-window cwin)
12125 (calendar-goto-date (if (listp date) date
12126 (calendar-gregorian-from-absolute date)))
12127 (select-window win))))
12129 (defun org-goto-calendar (&optional arg)
12130 "Go to the Emacs calendar at the current date.
12131 If there is a time stamp in the current line, go to that date.
12132 A prefix ARG can be used to force the current date."
12133 (interactive "P")
12134 (let ((tsr org-ts-regexp) diff
12135 (calendar-move-hook nil)
12136 (calendar-view-holidays-initially-flag nil)
12137 (view-calendar-holidays-initially nil)
12138 (calendar-view-diary-initially-flag nil)
12139 (view-diary-entries-initially nil))
12140 (if (or (org-at-timestamp-p)
12141 (save-excursion
12142 (beginning-of-line 1)
12143 (looking-at (concat ".*" tsr))))
12144 (let ((d1 (time-to-days (current-time)))
12145 (d2 (time-to-days
12146 (org-time-string-to-time (match-string 1)))))
12147 (setq diff (- d2 d1))))
12148 (calendar)
12149 (calendar-goto-today)
12150 (if (and diff (not arg)) (calendar-forward-day diff))))
12152 (defun org-get-date-from-calendar ()
12153 "Return a list (month day year) of date at point in calendar."
12154 (with-current-buffer "*Calendar*"
12155 (save-match-data
12156 (calendar-cursor-to-date))))
12158 (defun org-date-from-calendar ()
12159 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12160 If there is already a time stamp at the cursor position, update it."
12161 (interactive)
12162 (if (org-at-timestamp-p t)
12163 (org-timestamp-change 0 'calendar)
12164 (let ((cal-date (org-get-date-from-calendar)))
12165 (org-insert-time-stamp
12166 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12168 (defun org-minutes-to-hh:mm-string (m)
12169 "Compute H:MM from a number of minutes."
12170 (let ((h (/ m 60)))
12171 (setq m (- m (* 60 h)))
12172 (format org-time-clocksum-format h m)))
12174 (defun org-hh:mm-string-to-minutes (s)
12175 "Convert a string H:MM to a number of minutes."
12176 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12177 (+ (* (string-to-number (match-string 1 s)) 60)
12178 (string-to-number (match-string 2 s)))
12181 ;;;; Agenda files
12183 ;;;###autoload
12184 (defun org-iswitchb (&optional arg)
12185 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12186 With a prefix argument, restrict available to files.
12187 With two prefix arguments, restrict available buffers to agenda files.
12189 Due to some yet unresolved reason, the global function
12190 `iswitchb-mode' needs to be active for this function to work."
12191 (interactive "P")
12192 (require 'iswitchb)
12193 (let ((enabled iswitchb-mode) blist)
12194 (or enabled (iswitchb-mode 1))
12195 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12196 ((equal arg '(16)) (org-buffer-list 'agenda))
12197 (t (org-buffer-list))))
12198 (unwind-protect
12199 (let ((iswitchb-make-buflist-hook
12200 (lambda ()
12201 (setq iswitchb-temp-buflist
12202 (mapcar 'buffer-name blist)))))
12203 (switch-to-buffer
12204 (iswitchb-read-buffer
12205 "Switch-to: " nil t))
12206 (or enabled (iswitchb-mode -1))))))
12208 ;;;###autoload
12209 (defun org-ido-switchb (&optional arg)
12210 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12211 With a prefix argument, restrict available to files.
12212 With two prefix arguments, restrict available buffers to agenda files."
12213 (interactive "P")
12214 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12215 ((equal arg '(16)) (org-buffer-list 'agenda))
12216 (t (org-buffer-list)))))
12217 (switch-to-buffer
12218 (org-ido-completing-read "Org buffer: "
12219 (mapcar 'buffer-name blist)
12220 nil t))))
12222 (defun org-buffer-list (&optional predicate exclude-tmp)
12223 "Return a list of Org buffers.
12224 PREDICATE can be `export', `files' or `agenda'.
12226 export restrict the list to Export buffers.
12227 files restrict the list to buffers visiting Org files.
12228 agenda restrict the list to buffers visiting agenda files.
12230 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12231 (let* ((bfn nil)
12232 (agenda-files (and (eq predicate 'agenda)
12233 (mapcar 'file-truename (org-agenda-files t))))
12234 (filter
12235 (cond
12236 ((eq predicate 'files)
12237 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12238 ((eq predicate 'export)
12239 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12240 ((eq predicate 'agenda)
12241 (lambda (b)
12242 (with-current-buffer b
12243 (and (eq major-mode 'org-mode)
12244 (setq bfn (buffer-file-name b))
12245 (member (file-truename bfn) agenda-files)))))
12246 (t (lambda (b) (with-current-buffer b
12247 (or (eq major-mode 'org-mode)
12248 (string-match "\*Org .*Export"
12249 (buffer-name b)))))))))
12250 (delq nil
12251 (mapcar
12252 (lambda(b)
12253 (if (and (funcall filter b)
12254 (or (not exclude-tmp)
12255 (not (string-match "tmp" (buffer-name b)))))
12257 nil))
12258 (buffer-list)))))
12260 (defun org-agenda-files (&optional unrestricted archives)
12261 "Get the list of agenda files.
12262 Optional UNRESTRICTED means return the full list even if a restriction
12263 is currently in place.
12264 When ARCHIVES is t, include all archive files hat are really being
12265 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12266 `org-agenda-archives-mode' is t."
12267 (let ((files
12268 (cond
12269 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12270 ((stringp org-agenda-files) (org-read-agenda-file-list))
12271 ((listp org-agenda-files) org-agenda-files)
12272 (t (error "Invalid value of `org-agenda-files'")))))
12273 (setq files (apply 'append
12274 (mapcar (lambda (f)
12275 (if (file-directory-p f)
12276 (directory-files
12277 f t org-agenda-file-regexp)
12278 (list f)))
12279 files)))
12280 (when org-agenda-skip-unavailable-files
12281 (setq files (delq nil
12282 (mapcar (function
12283 (lambda (file)
12284 (and (file-readable-p file) file)))
12285 files))))
12286 (when (or (eq archives t)
12287 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12288 (setq files (org-add-archive-files files)))
12289 files))
12291 (defun org-edit-agenda-file-list ()
12292 "Edit the list of agenda files.
12293 Depending on setup, this either uses customize to edit the variable
12294 `org-agenda-files', or it visits the file that is holding the list. In the
12295 latter case, the buffer is set up in a way that saving it automatically kills
12296 the buffer and restores the previous window configuration."
12297 (interactive)
12298 (if (stringp org-agenda-files)
12299 (let ((cw (current-window-configuration)))
12300 (find-file org-agenda-files)
12301 (org-set-local 'org-window-configuration cw)
12302 (org-add-hook 'after-save-hook
12303 (lambda ()
12304 (set-window-configuration
12305 (prog1 org-window-configuration
12306 (kill-buffer (current-buffer))))
12307 (org-install-agenda-files-menu)
12308 (message "New agenda file list installed"))
12309 nil 'local)
12310 (message "%s" (substitute-command-keys
12311 "Edit list and finish with \\[save-buffer]")))
12312 (customize-variable 'org-agenda-files)))
12314 (defun org-store-new-agenda-file-list (list)
12315 "Set new value for the agenda file list and save it correctly."
12316 (if (stringp org-agenda-files)
12317 (let ((f org-agenda-files) b)
12318 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12319 (with-temp-file f
12320 (insert (mapconcat 'identity list "\n") "\n")))
12321 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12322 (setq org-agenda-files list)
12323 (customize-save-variable 'org-agenda-files org-agenda-files))))
12325 (defun org-read-agenda-file-list ()
12326 "Read the list of agenda files from a file."
12327 (when (file-directory-p org-agenda-files)
12328 (error "`org-agenda-files' cannot be a single directory"))
12329 (when (stringp org-agenda-files)
12330 (with-temp-buffer
12331 (insert-file-contents org-agenda-files)
12332 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12335 ;;;###autoload
12336 (defun org-cycle-agenda-files ()
12337 "Cycle through the files in `org-agenda-files'.
12338 If the current buffer visits an agenda file, find the next one in the list.
12339 If the current buffer does not, find the first agenda file."
12340 (interactive)
12341 (let* ((fs (org-agenda-files t))
12342 (files (append fs (list (car fs))))
12343 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12344 file)
12345 (unless files (error "No agenda files"))
12346 (catch 'exit
12347 (while (setq file (pop files))
12348 (if (equal (file-truename file) tcf)
12349 (when (car files)
12350 (find-file (car files))
12351 (throw 'exit t))))
12352 (find-file (car fs)))
12353 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12355 (defun org-agenda-file-to-front (&optional to-end)
12356 "Move/add the current file to the top of the agenda file list.
12357 If the file is not present in the list, it is added to the front. If it is
12358 present, it is moved there. With optional argument TO-END, add/move to the
12359 end of the list."
12360 (interactive "P")
12361 (let ((org-agenda-skip-unavailable-files nil)
12362 (file-alist (mapcar (lambda (x)
12363 (cons (file-truename x) x))
12364 (org-agenda-files t)))
12365 (ctf (file-truename buffer-file-name))
12366 x had)
12367 (setq x (assoc ctf file-alist) had x)
12369 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12370 (if to-end
12371 (setq file-alist (append (delq x file-alist) (list x)))
12372 (setq file-alist (cons x (delq x file-alist))))
12373 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12374 (org-install-agenda-files-menu)
12375 (message "File %s to %s of agenda file list"
12376 (if had "moved" "added") (if to-end "end" "front"))))
12378 (defun org-remove-file (&optional file)
12379 "Remove current file from the list of files in variable `org-agenda-files'.
12380 These are the files which are being checked for agenda entries.
12381 Optional argument FILE means, use this file instead of the current."
12382 (interactive)
12383 (let* ((org-agenda-skip-unavailable-files nil)
12384 (file (or file buffer-file-name))
12385 (true-file (file-truename file))
12386 (afile (abbreviate-file-name file))
12387 (files (delq nil (mapcar
12388 (lambda (x)
12389 (if (equal true-file
12390 (file-truename x))
12391 nil x))
12392 (org-agenda-files t)))))
12393 (if (not (= (length files) (length (org-agenda-files t))))
12394 (progn
12395 (org-store-new-agenda-file-list files)
12396 (org-install-agenda-files-menu)
12397 (message "Removed file: %s" afile))
12398 (message "File was not in list: %s (not removed)" afile))))
12400 (defun org-file-menu-entry (file)
12401 (vector file (list 'find-file file) t))
12403 (defun org-check-agenda-file (file)
12404 "Make sure FILE exists. If not, ask user what to do."
12405 (when (not (file-exists-p file))
12406 (message "non-existent file %s. [R]emove from list or [A]bort?"
12407 (abbreviate-file-name file))
12408 (let ((r (downcase (read-char-exclusive))))
12409 (cond
12410 ((equal r ?r)
12411 (org-remove-file file)
12412 (throw 'nextfile t))
12413 (t (error "Abort"))))))
12415 (defun org-get-agenda-file-buffer (file)
12416 "Get a buffer visiting FILE. If the buffer needs to be created, add
12417 it to the list of buffers which might be released later."
12418 (let ((buf (org-find-base-buffer-visiting file)))
12419 (if buf
12420 buf ; just return it
12421 ;; Make a new buffer and remember it
12422 (setq buf (find-file-noselect file))
12423 (if buf (push buf org-agenda-new-buffers))
12424 buf)))
12426 (defun org-release-buffers (blist)
12427 "Release all buffers in list, asking the user for confirmation when needed.
12428 When a buffer is unmodified, it is just killed. When modified, it is saved
12429 \(if the user agrees) and then killed."
12430 (let (buf file)
12431 (while (setq buf (pop blist))
12432 (setq file (buffer-file-name buf))
12433 (when (and (buffer-modified-p buf)
12434 file
12435 (y-or-n-p (format "Save file %s? " file)))
12436 (with-current-buffer buf (save-buffer)))
12437 (kill-buffer buf))))
12439 (defun org-prepare-agenda-buffers (files)
12440 "Create buffers for all agenda files, protect archived trees and comments."
12441 (interactive)
12442 (let ((pa '(:org-archived t))
12443 (pc '(:org-comment t))
12444 (pall '(:org-archived t :org-comment t))
12445 (inhibit-read-only t)
12446 (rea (concat ":" org-archive-tag ":"))
12447 bmp file re)
12448 (save-excursion
12449 (save-restriction
12450 (while (setq file (pop files))
12451 (if (bufferp file)
12452 (set-buffer file)
12453 (org-check-agenda-file file)
12454 (set-buffer (org-get-agenda-file-buffer file)))
12455 (widen)
12456 (setq bmp (buffer-modified-p))
12457 (org-refresh-category-properties)
12458 (setq org-todo-keywords-for-agenda
12459 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12460 (setq org-done-keywords-for-agenda
12461 (append org-done-keywords-for-agenda org-done-keywords))
12462 (setq org-todo-keyword-alist-for-agenda
12463 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12464 (setq org-tag-alist-for-agenda
12465 (append org-tag-alist-for-agenda org-tag-alist))
12467 (save-excursion
12468 (remove-text-properties (point-min) (point-max) pall)
12469 (when org-agenda-skip-archived-trees
12470 (goto-char (point-min))
12471 (while (re-search-forward rea nil t)
12472 (if (org-on-heading-p t)
12473 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12474 (goto-char (point-min))
12475 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12476 (while (re-search-forward re nil t)
12477 (add-text-properties
12478 (match-beginning 0) (org-end-of-subtree t) pc)))
12479 (set-buffer-modified-p bmp))))
12480 (setq org-todo-keyword-alist-for-agenda
12481 (org-uniquify org-todo-keyword-alist-for-agenda)
12482 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12484 ;;;; Embedded LaTeX
12486 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12487 "Keymap for the minor `org-cdlatex-mode'.")
12489 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12490 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12491 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12492 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12493 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12495 (defvar org-cdlatex-texmathp-advice-is-done nil
12496 "Flag remembering if we have applied the advice to texmathp already.")
12498 (define-minor-mode org-cdlatex-mode
12499 "Toggle the minor `org-cdlatex-mode'.
12500 This mode supports entering LaTeX environment and math in LaTeX fragments
12501 in Org-mode.
12502 \\{org-cdlatex-mode-map}"
12503 nil " OCDL" nil
12504 (when org-cdlatex-mode (require 'cdlatex))
12505 (unless org-cdlatex-texmathp-advice-is-done
12506 (setq org-cdlatex-texmathp-advice-is-done t)
12507 (defadvice texmathp (around org-math-always-on activate)
12508 "Always return t in org-mode buffers.
12509 This is because we want to insert math symbols without dollars even outside
12510 the LaTeX math segments. If Orgmode thinks that point is actually inside
12511 an embedded LaTeX fragment, let texmathp do its job.
12512 \\[org-cdlatex-mode-map]"
12513 (interactive)
12514 (let (p)
12515 (cond
12516 ((not (org-mode-p)) ad-do-it)
12517 ((eq this-command 'cdlatex-math-symbol)
12518 (setq ad-return-value t
12519 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12521 (let ((p (org-inside-LaTeX-fragment-p)))
12522 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12523 (setq ad-return-value t
12524 texmathp-why '("Org-mode embedded math" . 0))
12525 (if p ad-do-it)))))))))
12527 (defun turn-on-org-cdlatex ()
12528 "Unconditionally turn on `org-cdlatex-mode'."
12529 (org-cdlatex-mode 1))
12531 (defun org-inside-LaTeX-fragment-p ()
12532 "Test if point is inside a LaTeX fragment.
12533 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12534 sequence appearing also before point.
12535 Even though the matchers for math are configurable, this function assumes
12536 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12537 delimiters are skipped when they have been removed by customization.
12538 The return value is nil, or a cons cell with the delimiter and
12539 and the position of this delimiter.
12541 This function does a reasonably good job, but can locally be fooled by
12542 for example currency specifications. For example it will assume being in
12543 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12544 fragments that are properly closed, but during editing, we have to live
12545 with the uncertainty caused by missing closing delimiters. This function
12546 looks only before point, not after."
12547 (catch 'exit
12548 (let ((pos (point))
12549 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12550 (lim (progn
12551 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12552 (point)))
12553 dd-on str (start 0) m re)
12554 (goto-char pos)
12555 (when dodollar
12556 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12557 re (nth 1 (assoc "$" org-latex-regexps)))
12558 (while (string-match re str start)
12559 (cond
12560 ((= (match-end 0) (length str))
12561 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12562 ((= (match-end 0) (- (length str) 5))
12563 (throw 'exit nil))
12564 (t (setq start (match-end 0))))))
12565 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12566 (goto-char pos)
12567 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12568 (and (match-beginning 2) (throw 'exit nil))
12569 ;; count $$
12570 (while (re-search-backward "\\$\\$" lim t)
12571 (setq dd-on (not dd-on)))
12572 (goto-char pos)
12573 (if dd-on (cons "$$" m))))))
12576 (defun org-try-cdlatex-tab ()
12577 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12578 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12579 - inside a LaTeX fragment, or
12580 - after the first word in a line, where an abbreviation expansion could
12581 insert a LaTeX environment."
12582 (when org-cdlatex-mode
12583 (cond
12584 ((save-excursion
12585 (skip-chars-backward "a-zA-Z0-9*")
12586 (skip-chars-backward " \t")
12587 (bolp))
12588 (cdlatex-tab) t)
12589 ((org-inside-LaTeX-fragment-p)
12590 (cdlatex-tab) t)
12591 (t nil))))
12593 (defun org-cdlatex-underscore-caret (&optional arg)
12594 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12595 Revert to the normal definition outside of these fragments."
12596 (interactive "P")
12597 (if (org-inside-LaTeX-fragment-p)
12598 (call-interactively 'cdlatex-sub-superscript)
12599 (let (org-cdlatex-mode)
12600 (call-interactively (key-binding (vector last-input-event))))))
12602 (defun org-cdlatex-math-modify (&optional arg)
12603 "Execute `cdlatex-math-modify' in LaTeX fragments.
12604 Revert to the normal definition outside of these fragments."
12605 (interactive "P")
12606 (if (org-inside-LaTeX-fragment-p)
12607 (call-interactively 'cdlatex-math-modify)
12608 (let (org-cdlatex-mode)
12609 (call-interactively (key-binding (vector last-input-event))))))
12611 (defvar org-latex-fragment-image-overlays nil
12612 "List of overlays carrying the images of latex fragments.")
12613 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12615 (defun org-remove-latex-fragment-image-overlays ()
12616 "Remove all overlays with LaTeX fragment images in current buffer."
12617 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12618 (setq org-latex-fragment-image-overlays nil))
12620 (defun org-preview-latex-fragment (&optional subtree)
12621 "Preview the LaTeX fragment at point, or all locally or globally.
12622 If the cursor is in a LaTeX fragment, create the image and overlay
12623 it over the source code. If there is no fragment at point, display
12624 all fragments in the current text, from one headline to the next. With
12625 prefix SUBTREE, display all fragments in the current subtree. With a
12626 double prefix `C-u C-u', or when the cursor is before the first headline,
12627 display all fragments in the buffer.
12628 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12629 (interactive "P")
12630 (org-remove-latex-fragment-image-overlays)
12631 (save-excursion
12632 (save-restriction
12633 (let (beg end at msg)
12634 (cond
12635 ((or (equal subtree '(16))
12636 (not (save-excursion
12637 (re-search-backward (concat "^" outline-regexp) nil t))))
12638 (setq beg (point-min) end (point-max)
12639 msg "Creating images for buffer...%s"))
12640 ((equal subtree '(4))
12641 (org-back-to-heading)
12642 (setq beg (point) end (org-end-of-subtree t)
12643 msg "Creating images for subtree...%s"))
12645 (if (setq at (org-inside-LaTeX-fragment-p))
12646 (goto-char (max (point-min) (- (cdr at) 2)))
12647 (org-back-to-heading))
12648 (setq beg (point) end (progn (outline-next-heading) (point))
12649 msg (if at "Creating image...%s"
12650 "Creating images for entry...%s"))))
12651 (message msg "")
12652 (narrow-to-region beg end)
12653 (goto-char beg)
12654 (org-format-latex
12655 (concat "ltxpng/" (file-name-sans-extension
12656 (file-name-nondirectory
12657 buffer-file-name)))
12658 default-directory 'overlays msg at 'forbuffer)
12659 (message msg "done. Use `C-c C-c' to remove images.")))))
12661 (defvar org-latex-regexps
12662 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12663 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12664 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12665 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12666 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12667 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12668 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12669 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12670 "Regular expressions for matching embedded LaTeX.")
12672 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12673 "Replace LaTeX fragments with links to an image, and produce images."
12674 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12675 (let* ((prefixnodir (file-name-nondirectory prefix))
12676 (absprefix (expand-file-name prefix dir))
12677 (todir (file-name-directory absprefix))
12678 (opt org-format-latex-options)
12679 (matchers (plist-get opt :matchers))
12680 (re-list org-latex-regexps)
12681 (cnt 0) txt link beg end re e checkdir
12682 m n block linkfile movefile ov)
12683 ;; Check if there are old images files with this prefix, and remove them
12684 (when (file-directory-p todir)
12685 (mapc 'delete-file
12686 (directory-files
12687 todir 'full
12688 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12689 ;; Check the different regular expressions
12690 (while (setq e (pop re-list))
12691 (setq m (car e) re (nth 1 e) n (nth 2 e)
12692 block (if (nth 3 e) "\n\n" ""))
12693 (when (member m matchers)
12694 (goto-char (point-min))
12695 (while (re-search-forward re nil t)
12696 (when (or (not at) (equal (cdr at) (match-beginning n)))
12697 (setq txt (match-string n)
12698 beg (match-beginning n) end (match-end n)
12699 cnt (1+ cnt)
12700 linkfile (format "%s_%04d.png" prefix cnt)
12701 movefile (format "%s_%04d.png" absprefix cnt)
12702 link (concat block "[[file:" linkfile "]]" block))
12703 (if msg (message msg cnt))
12704 (goto-char beg)
12705 (unless checkdir ; make sure the directory exists
12706 (setq checkdir t)
12707 (or (file-directory-p todir) (make-directory todir)))
12708 (org-create-formula-image
12709 txt movefile opt forbuffer)
12710 (if overlays
12711 (progn
12712 (setq ov (org-make-overlay beg end))
12713 (if (featurep 'xemacs)
12714 (progn
12715 (org-overlay-put ov 'invisible t)
12716 (org-overlay-put
12717 ov 'end-glyph
12718 (make-glyph (vector 'png :file movefile))))
12719 (org-overlay-put
12720 ov 'display
12721 (list 'image :type 'png :file movefile :ascent 'center)))
12722 (push ov org-latex-fragment-image-overlays)
12723 (goto-char end))
12724 (delete-region beg end)
12725 (insert link))))))))
12727 ;; This function borrows from Ganesh Swami's latex2png.el
12728 (defun org-create-formula-image (string tofile options buffer)
12729 (let* ((tmpdir (if (featurep 'xemacs)
12730 (temp-directory)
12731 temporary-file-directory))
12732 (texfilebase (make-temp-name
12733 (expand-file-name "orgtex" tmpdir)))
12734 (texfile (concat texfilebase ".tex"))
12735 (dvifile (concat texfilebase ".dvi"))
12736 (pngfile (concat texfilebase ".png"))
12737 (fnh (if (featurep 'xemacs)
12738 (font-height (get-face-font 'default))
12739 (face-attribute 'default :height nil)))
12740 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12741 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12742 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12743 "Black"))
12744 (bg (or (plist-get options (if buffer :background :html-background))
12745 "Transparent")))
12746 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12747 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12748 (with-temp-file texfile
12749 (insert org-format-latex-header
12750 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12751 (let ((dir default-directory))
12752 (condition-case nil
12753 (progn
12754 (cd tmpdir)
12755 (call-process "latex" nil nil nil texfile))
12756 (error nil))
12757 (cd dir))
12758 (if (not (file-exists-p dvifile))
12759 (progn (message "Failed to create dvi file from %s" texfile) nil)
12760 (condition-case nil
12761 (call-process "dvipng" nil nil nil
12762 "-E" "-fg" fg "-bg" bg
12763 "-D" dpi
12764 ;;"-x" scale "-y" scale
12765 "-T" "tight"
12766 "-o" pngfile
12767 dvifile)
12768 (error nil))
12769 (if (not (file-exists-p pngfile))
12770 (progn (message "Failed to create png file from %s" texfile) nil)
12771 ;; Use the requested file name and clean up
12772 (copy-file pngfile tofile 'replace)
12773 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12774 (delete-file (concat texfilebase e)))
12775 pngfile))))
12777 (defun org-dvipng-color (attr)
12778 "Return an rgb color specification for dvipng."
12779 (apply 'format "rgb %s %s %s"
12780 (mapcar 'org-normalize-color
12781 (color-values (face-attribute 'default attr nil)))))
12783 (defun org-normalize-color (value)
12784 "Return string to be used as color value for an RGB component."
12785 (format "%g" (/ value 65535.0)))
12787 ;;;; Key bindings
12789 ;; Make `C-c C-x' a prefix key
12790 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12792 ;; TAB key with modifiers
12793 (org-defkey org-mode-map "\C-i" 'org-cycle)
12794 (org-defkey org-mode-map [(tab)] 'org-cycle)
12795 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12796 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12797 (org-defkey org-mode-map "\M-\t" 'org-complete)
12798 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12799 ;; The following line is necessary under Suse GNU/Linux
12800 (unless (featurep 'xemacs)
12801 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12802 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12803 (define-key org-mode-map [backtab] 'org-shifttab)
12805 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12806 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12807 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12809 ;; Cursor keys with modifiers
12810 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12811 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12812 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12813 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12815 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12816 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12817 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12818 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12820 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12821 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12822 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12823 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12825 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12826 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12828 ;;; Extra keys for tty access.
12829 ;; We only set them when really needed because otherwise the
12830 ;; menus don't show the simple keys
12832 (when (or org-use-extra-keys
12833 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12834 (not window-system))
12835 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12836 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12837 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12838 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12839 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12840 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12841 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12842 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12843 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12844 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12845 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12846 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12847 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12848 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12849 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12850 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12851 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12852 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12853 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12854 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12855 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12856 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12858 ;; All the other keys
12860 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12861 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12862 (if (boundp 'narrow-map)
12863 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12864 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12865 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12866 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12867 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12868 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12869 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12870 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12871 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12872 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12873 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12874 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12875 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12876 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12877 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12878 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12879 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12880 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12881 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12882 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12883 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12884 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12885 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12886 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12887 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12888 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12889 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12890 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12891 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12892 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12893 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12894 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12895 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12896 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12897 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12898 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12899 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12900 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12901 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12902 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12903 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12904 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12905 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12906 (org-defkey org-mode-map "\C-c^" 'org-sort)
12907 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12908 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12909 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12910 (org-defkey org-mode-map "\C-m" 'org-return)
12911 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12912 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12913 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12914 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12915 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12916 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12917 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12918 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12919 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12920 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12921 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12922 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12923 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12924 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12925 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12926 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12927 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12929 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12930 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12931 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12932 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12934 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12935 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12936 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12937 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12938 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12939 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12940 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12941 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12942 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12943 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12944 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12945 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
12946 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12948 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12949 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12950 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12951 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
12953 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12955 (when (featurep 'xemacs)
12956 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12958 (defvar org-table-auto-blank-field) ; defined in org-table.el
12959 (defun org-self-insert-command (N)
12960 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12961 If the cursor is in a table looking at whitespace, the whitespace is
12962 overwritten, and the table is not marked as requiring realignment."
12963 (interactive "p")
12964 (if (and (org-table-p)
12965 (progn
12966 ;; check if we blank the field, and if that triggers align
12967 (and (featurep 'org-table) org-table-auto-blank-field
12968 (member last-command
12969 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12970 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12971 ;; got extra space, this field does not determine column width
12972 (let (org-table-may-need-update) (org-table-blank-field))
12973 ;; no extra space, this field may determine column width
12974 (org-table-blank-field)))
12976 (eq N 1)
12977 (looking-at "[^|\n]* |"))
12978 (let (org-table-may-need-update)
12979 (goto-char (1- (match-end 0)))
12980 (delete-backward-char 1)
12981 (goto-char (match-beginning 0))
12982 (self-insert-command N))
12983 (setq org-table-may-need-update t)
12984 (self-insert-command N)
12985 (org-fix-tags-on-the-fly)))
12987 (defun org-fix-tags-on-the-fly ()
12988 (when (and (equal (char-after (point-at-bol)) ?*)
12989 (org-on-heading-p))
12990 (org-align-tags-here org-tags-column)))
12992 (defun org-delete-backward-char (N)
12993 "Like `delete-backward-char', insert whitespace at field end in tables.
12994 When deleting backwards, in tables this function will insert whitespace in
12995 front of the next \"|\" separator, to keep the table aligned. The table will
12996 still be marked for re-alignment if the field did fill the entire column,
12997 because, in this case the deletion might narrow the column."
12998 (interactive "p")
12999 (if (and (org-table-p)
13000 (eq N 1)
13001 (string-match "|" (buffer-substring (point-at-bol) (point)))
13002 (looking-at ".*?|"))
13003 (let ((pos (point))
13004 (noalign (looking-at "[^|\n\r]* |"))
13005 (c org-table-may-need-update))
13006 (backward-delete-char N)
13007 (skip-chars-forward "^|")
13008 (insert " ")
13009 (goto-char (1- pos))
13010 ;; noalign: if there were two spaces at the end, this field
13011 ;; does not determine the width of the column.
13012 (if noalign (setq org-table-may-need-update c)))
13013 (backward-delete-char N)
13014 (org-fix-tags-on-the-fly)))
13016 (defun org-delete-char (N)
13017 "Like `delete-char', but insert whitespace at field end in tables.
13018 When deleting characters, in tables this function will insert whitespace in
13019 front of the next \"|\" separator, to keep the table aligned. The table will
13020 still be marked for re-alignment if the field did fill the entire column,
13021 because, in this case the deletion might narrow the column."
13022 (interactive "p")
13023 (if (and (org-table-p)
13024 (not (bolp))
13025 (not (= (char-after) ?|))
13026 (eq N 1))
13027 (if (looking-at ".*?|")
13028 (let ((pos (point))
13029 (noalign (looking-at "[^|\n\r]* |"))
13030 (c org-table-may-need-update))
13031 (replace-match (concat
13032 (substring (match-string 0) 1 -1)
13033 " |"))
13034 (goto-char pos)
13035 ;; noalign: if there were two spaces at the end, this field
13036 ;; does not determine the width of the column.
13037 (if noalign (setq org-table-may-need-update c)))
13038 (delete-char N))
13039 (delete-char N)
13040 (org-fix-tags-on-the-fly)))
13042 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13043 (put 'org-self-insert-command 'delete-selection t)
13044 (put 'orgtbl-self-insert-command 'delete-selection t)
13045 (put 'org-delete-char 'delete-selection 'supersede)
13046 (put 'org-delete-backward-char 'delete-selection 'supersede)
13047 (put 'org-yank 'delete-selection 'yank)
13049 ;; Make `flyspell-mode' delay after some commands
13050 (put 'org-self-insert-command 'flyspell-delayed t)
13051 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13052 (put 'org-delete-char 'flyspell-delayed t)
13053 (put 'org-delete-backward-char 'flyspell-delayed t)
13055 ;; Make pabbrev-mode expand after org-mode commands
13056 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13057 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13059 ;; How to do this: Measure non-white length of current string
13060 ;; If equal to column width, we should realign.
13062 (defun org-remap (map &rest commands)
13063 "In MAP, remap the functions given in COMMANDS.
13064 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13065 (let (new old)
13066 (while commands
13067 (setq old (pop commands) new (pop commands))
13068 (if (fboundp 'command-remapping)
13069 (org-defkey map (vector 'remap old) new)
13070 (substitute-key-definition old new map global-map)))))
13072 (when (eq org-enable-table-editor 'optimized)
13073 ;; If the user wants maximum table support, we need to hijack
13074 ;; some standard editing functions
13075 (org-remap org-mode-map
13076 'self-insert-command 'org-self-insert-command
13077 'delete-char 'org-delete-char
13078 'delete-backward-char 'org-delete-backward-char)
13079 (org-defkey org-mode-map "|" 'org-force-self-insert))
13081 (defun org-modifier-cursor-error ()
13082 "Throw an error, a modified cursor command was applied in wrong context."
13083 (error "This command is active in special context like tables, headlines or items"))
13085 (defun org-shiftselect-error ()
13086 "Throw an error because Shift-Cursor command was applied in wrong context."
13087 (if (and (boundp 'shift-select-mode) shift-select-mode)
13088 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13089 (error "This command works only in special context like headlines or timestamps.")))
13091 (defun org-call-for-shift-select (cmd)
13092 (let ((this-command-keys-shift-translated t))
13093 (call-interactively cmd)))
13095 (defun org-shifttab (&optional arg)
13096 "Global visibility cycling or move to previous table field.
13097 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13098 on context.
13099 See the individual commands for more information."
13100 (interactive "P")
13101 (cond
13102 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13103 ((integerp arg)
13104 (message "Content view to level: %d" arg)
13105 (org-content (prefix-numeric-value arg))
13106 (setq org-cycle-global-status 'overview))
13107 (t (call-interactively 'org-global-cycle))))
13109 (defun org-shiftmetaleft ()
13110 "Promote subtree or delete table column.
13111 Calls `org-promote-subtree', `org-outdent-item',
13112 or `org-table-delete-column', depending on context.
13113 See the individual commands for more information."
13114 (interactive)
13115 (cond
13116 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13117 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13118 ((org-at-item-p) (call-interactively 'org-outdent-item))
13119 (t (org-modifier-cursor-error))))
13121 (defun org-shiftmetaright ()
13122 "Demote subtree or insert table column.
13123 Calls `org-demote-subtree', `org-indent-item',
13124 or `org-table-insert-column', depending on context.
13125 See the individual commands for more information."
13126 (interactive)
13127 (cond
13128 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13129 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13130 ((org-at-item-p) (call-interactively 'org-indent-item))
13131 (t (org-modifier-cursor-error))))
13133 (defun org-shiftmetaup (&optional arg)
13134 "Move subtree up or kill table row.
13135 Calls `org-move-subtree-up' or `org-table-kill-row' or
13136 `org-move-item-up' depending on context. See the individual commands
13137 for more information."
13138 (interactive "P")
13139 (cond
13140 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13141 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13142 ((org-at-item-p) (call-interactively 'org-move-item-up))
13143 (t (org-modifier-cursor-error))))
13144 (defun org-shiftmetadown (&optional arg)
13145 "Move subtree down or insert table row.
13146 Calls `org-move-subtree-down' or `org-table-insert-row' or
13147 `org-move-item-down', depending on context. See the individual
13148 commands for more information."
13149 (interactive "P")
13150 (cond
13151 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13152 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13153 ((org-at-item-p) (call-interactively 'org-move-item-down))
13154 (t (org-modifier-cursor-error))))
13156 (defun org-metaleft (&optional arg)
13157 "Promote heading or move table column to left.
13158 Calls `org-do-promote' or `org-table-move-column', depending on context.
13159 With no specific context, calls the Emacs default `backward-word'.
13160 See the individual commands for more information."
13161 (interactive "P")
13162 (cond
13163 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13164 ((or (org-on-heading-p) (org-region-active-p))
13165 (call-interactively 'org-do-promote))
13166 ((org-at-item-p) (call-interactively 'org-outdent-item))
13167 (t (call-interactively 'backward-word))))
13169 (defun org-metaright (&optional arg)
13170 "Demote subtree or move table column to right.
13171 Calls `org-do-demote' or `org-table-move-column', depending on context.
13172 With no specific context, calls the Emacs default `forward-word'.
13173 See the individual commands for more information."
13174 (interactive "P")
13175 (cond
13176 ((org-at-table-p) (call-interactively 'org-table-move-column))
13177 ((or (org-on-heading-p) (org-region-active-p))
13178 (call-interactively 'org-do-demote))
13179 ((org-at-item-p) (call-interactively 'org-indent-item))
13180 (t (call-interactively 'forward-word))))
13182 (defun org-metaup (&optional arg)
13183 "Move subtree up or move table row up.
13184 Calls `org-move-subtree-up' or `org-table-move-row' or
13185 `org-move-item-up', depending on context. See the individual commands
13186 for more information."
13187 (interactive "P")
13188 (cond
13189 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13190 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13191 ((org-at-item-p) (call-interactively 'org-move-item-up))
13192 (t (transpose-lines 1) (beginning-of-line -1))))
13194 (defun org-metadown (&optional arg)
13195 "Move subtree down or move table row down.
13196 Calls `org-move-subtree-down' or `org-table-move-row' or
13197 `org-move-item-down', depending on context. See the individual
13198 commands for more information."
13199 (interactive "P")
13200 (cond
13201 ((org-at-table-p) (call-interactively 'org-table-move-row))
13202 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13203 ((org-at-item-p) (call-interactively 'org-move-item-down))
13204 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13206 (defun org-shiftup (&optional arg)
13207 "Increase item in timestamp or increase priority of current headline.
13208 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13209 depending on context. See the individual commands for more information."
13210 (interactive "P")
13211 (cond
13212 ((and org-support-shift-select (org-region-active-p))
13213 (org-call-for-shift-select 'previous-line))
13214 ((org-at-timestamp-p t)
13215 (call-interactively (if org-edit-timestamp-down-means-later
13216 'org-timestamp-down 'org-timestamp-up)))
13217 ((and (not (eq org-support-shift-select 'always))
13218 (org-on-heading-p))
13219 (call-interactively 'org-priority-up))
13220 ((and (not org-support-shift-select) (org-at-item-p))
13221 (call-interactively 'org-previous-item))
13222 ((org-clocktable-try-shift 'up arg))
13223 (org-support-shift-select
13224 (org-call-for-shift-select 'previous-line))
13225 (t (org-shiftselect-error))))
13227 (defun org-shiftdown (&optional arg)
13228 "Decrease item in timestamp or decrease priority of current headline.
13229 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13230 depending on context. See the individual commands for more information."
13231 (interactive "P")
13232 (cond
13233 ((and org-support-shift-select (org-region-active-p))
13234 (org-call-for-shift-select 'next-line))
13235 ((org-at-timestamp-p t)
13236 (call-interactively (if org-edit-timestamp-down-means-later
13237 'org-timestamp-up 'org-timestamp-down)))
13238 ((and (not (eq org-support-shift-select 'always))
13239 (org-on-heading-p))
13240 (call-interactively 'org-priority-down))
13241 ((and (not org-support-shift-select) (org-at-item-p))
13242 (call-interactively 'org-next-item))
13243 ((org-clocktable-try-shift 'down arg))
13244 (org-support-shift-select
13245 (org-call-for-shift-select 'next-line))
13246 (t (org-shiftselect-error))))
13248 (defun org-shiftright (&optional arg)
13249 "Cycle the thing at point or in the current line, depending on context.
13250 Depending on context, this does one of the following:
13252 - switch a timestamp at point one day into the future
13253 - on a headline, switch to the next TODO keyword.
13254 - on an item, switch entire list to the next bullet type
13255 - on a property line, switch to the next allowed value
13256 - on a clocktable definition line, move time block into the future"
13257 (interactive "P")
13258 (cond
13259 ((and org-support-shift-select (org-region-active-p))
13260 (org-call-for-shift-select 'forward-char))
13261 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13262 ((and (not (eq org-support-shift-select 'always))
13263 (org-on-heading-p))
13264 (org-call-with-arg 'org-todo 'right))
13265 ((or (and org-support-shift-select
13266 (not (eq org-support-shift-select 'always))
13267 (org-at-item-bullet-p))
13268 (and (not org-support-shift-select) (org-at-item-p)))
13269 (org-call-with-arg 'org-cycle-list-bullet nil))
13270 ((and (not (eq org-support-shift-select 'always))
13271 (org-at-property-p))
13272 (call-interactively 'org-property-next-allowed-value))
13273 ((org-clocktable-try-shift 'right arg))
13274 (org-support-shift-select
13275 (org-call-for-shift-select 'forward-char))
13276 (t (org-shiftselect-error))))
13278 (defun org-shiftleft (&optional arg)
13279 "Cycle the thing at point or in the current line, depending on context.
13280 Depending on context, this does one of the following:
13282 - switch a timestamp at point one day into the past
13283 - on a headline, switch to the previous TODO keyword.
13284 - on an item, switch entire list to the previous bullet type
13285 - on a property line, switch to the previous allowed value
13286 - on a clocktable definition line, move time block into the past"
13287 (interactive "P")
13288 (cond
13289 ((and org-support-shift-select (org-region-active-p))
13290 (org-call-for-shift-select 'backward-char))
13291 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13292 ((and (not (eq org-support-shift-select 'always))
13293 (org-on-heading-p))
13294 (org-call-with-arg 'org-todo 'left))
13295 ((or (and org-support-shift-select
13296 (not (eq org-support-shift-select 'always))
13297 (org-at-item-bullet-p))
13298 (and (not org-support-shift-select) (org-at-item-p)))
13299 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13300 ((and (not (eq org-support-shift-select 'always))
13301 (org-at-property-p))
13302 (call-interactively 'org-property-previous-allowed-value))
13303 ((org-clocktable-try-shift 'left arg))
13304 (org-support-shift-select
13305 (org-call-for-shift-select 'backward-char))
13306 (t (org-shiftselect-error))))
13308 (defun org-shiftcontrolright ()
13309 "Switch to next TODO set."
13310 (interactive)
13311 (cond
13312 ((and org-support-shift-select (org-region-active-p))
13313 (org-call-for-shift-select 'forward-word))
13314 ((and (not (eq org-support-shift-select 'always))
13315 (org-on-heading-p))
13316 (org-call-with-arg 'org-todo 'nextset))
13317 (org-support-shift-select
13318 (org-call-for-shift-select 'forward-word))
13319 (t (org-shiftselect-error))))
13321 (defun org-shiftcontrolleft ()
13322 "Switch to previous TODO set."
13323 (interactive)
13324 (cond
13325 ((and org-support-shift-select (org-region-active-p))
13326 (org-call-for-shift-select 'backward-word))
13327 ((and (not (eq org-support-shift-select 'always))
13328 (org-on-heading-p))
13329 (org-call-with-arg 'org-todo 'previousset))
13330 (org-support-shift-select
13331 (org-call-for-shift-select 'backward-word))
13332 (t (org-shiftselect-error))))
13334 (defun org-ctrl-c-ret ()
13335 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13336 (interactive)
13337 (cond
13338 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13339 (t (call-interactively 'org-insert-heading))))
13341 (defun org-copy-special ()
13342 "Copy region in table or copy current subtree.
13343 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13344 See the individual commands for more information."
13345 (interactive)
13346 (call-interactively
13347 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13349 (defun org-cut-special ()
13350 "Cut region in table or cut current subtree.
13351 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13352 See the individual commands for more information."
13353 (interactive)
13354 (call-interactively
13355 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13357 (defun org-paste-special (arg)
13358 "Paste rectangular region into table, or past subtree relative to level.
13359 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13360 See the individual commands for more information."
13361 (interactive "P")
13362 (if (org-at-table-p)
13363 (org-table-paste-rectangle)
13364 (org-paste-subtree arg)))
13366 (defun org-edit-special ()
13367 "Call a special editor for the stuff at point.
13368 When at a table, call the formula editor with `org-table-edit-formulas'.
13369 When at the first line of an src example, call `org-edit-src-code'.
13370 When in an #+include line, visit the include file. Otherwise call
13371 `ffap' to visit the file at point."
13372 (interactive)
13373 (cond
13374 ((org-at-table-p)
13375 (call-interactively 'org-table-edit-formulas))
13376 ((save-excursion
13377 (beginning-of-line 1)
13378 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13379 (find-file (org-trim (match-string 1))))
13380 ((org-edit-src-code))
13381 ((org-edit-fixed-width-region))
13382 (t (call-interactively 'ffap))))
13384 (defun org-ctrl-c-ctrl-c (&optional arg)
13385 "Set tags in headline, or update according to changed information at point.
13387 This command does many different things, depending on context:
13389 - If the cursor is in a headline, prompt for tags and insert them
13390 into the current line, aligned to `org-tags-column'. When called
13391 with prefix arg, realign all tags in the current buffer.
13393 - If the cursor is in one of the special #+KEYWORD lines, this
13394 triggers scanning the buffer for these lines and updating the
13395 information.
13397 - If the cursor is inside a table, realign the table. This command
13398 works even if the automatic table editor has been turned off.
13400 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13401 the entire table.
13403 - If the cursor is at a footnote reference or definition, jump to
13404 the corresponding definition or references, respectively.
13406 - If the cursor is a the beginning of a dynamic block, update it.
13408 - If the cursor is inside a table created by the table.el package,
13409 activate that table.
13411 - If the current buffer is a remember buffer, close note and file
13412 it. A prefix argument of 1 files to the default location
13413 without further interaction. A prefix argument of 2 files to
13414 the currently clocking task.
13416 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13417 links in this buffer.
13419 - If the cursor is on a numbered item in a plain list, renumber the
13420 ordered list.
13422 - If the cursor is on a checkbox, toggle it."
13423 (interactive "P")
13424 (let ((org-enable-table-editor t))
13425 (cond
13426 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13427 org-occur-highlights
13428 org-latex-fragment-image-overlays)
13429 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13430 (org-remove-occur-highlights)
13431 (org-remove-latex-fragment-image-overlays)
13432 (message "Temporary highlights/overlays removed from current buffer"))
13433 ((and (local-variable-p 'org-finish-function (current-buffer))
13434 (fboundp org-finish-function))
13435 (funcall org-finish-function))
13436 ((org-at-property-p)
13437 (call-interactively 'org-property-action))
13438 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13439 ((org-on-heading-p) (call-interactively 'org-set-tags))
13440 ((org-at-table.el-p)
13441 (require 'table)
13442 (beginning-of-line 1)
13443 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13444 (call-interactively 'table-recognize-table))
13445 ((org-at-table-p)
13446 (org-table-maybe-eval-formula)
13447 (if arg
13448 (call-interactively 'org-table-recalculate)
13449 (org-table-maybe-recalculate-line))
13450 (call-interactively 'org-table-align))
13451 ((or (org-footnote-at-reference-p)
13452 (org-footnote-at-definition-p))
13453 (call-interactively 'org-footnote-action))
13454 ((org-at-item-checkbox-p)
13455 (call-interactively 'org-toggle-checkbox))
13456 ((org-at-item-p)
13457 (call-interactively 'org-maybe-renumber-ordered-list))
13458 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13459 ;; Dynamic block
13460 (beginning-of-line 1)
13461 (save-excursion (org-update-dblock)))
13462 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13463 (cond
13464 ((equal (match-string 1) "TBLFM")
13465 ;; Recalculate the table before this line
13466 (save-excursion
13467 (beginning-of-line 1)
13468 (skip-chars-backward " \r\n\t")
13469 (if (org-at-table-p)
13470 (org-call-with-arg 'org-table-recalculate t))))
13472 ; (org-set-regexps-and-options)
13473 ; (org-restart-font-lock)
13474 (let ((org-inhibit-startup t)) (org-mode-restart))
13475 (message "Local setup has been refreshed"))))
13476 (t (error "C-c C-c can do nothing useful at this location.")))))
13478 (defun org-mode-restart ()
13479 "Restart Org-mode, to scan again for special lines.
13480 Also updates the keyword regular expressions."
13481 (interactive)
13482 (org-mode)
13483 (message "Org-mode restarted"))
13485 (defun org-kill-note-or-show-branches ()
13486 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13487 (interactive)
13488 (if (not org-finish-function)
13489 (call-interactively 'show-branches)
13490 (let ((org-note-abort t))
13491 (funcall org-finish-function))))
13493 (defun org-return (&optional indent)
13494 "Goto next table row or insert a newline.
13495 Calls `org-table-next-row' or `newline', depending on context.
13496 See the individual commands for more information."
13497 (interactive)
13498 (cond
13499 ((bobp) (if indent (newline-and-indent) (newline)))
13500 ((and (org-at-heading-p)
13501 (looking-at
13502 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13503 (org-show-entry)
13504 (end-of-line 1)
13505 (newline))
13506 ((org-at-table-p)
13507 (org-table-justify-field-maybe)
13508 (call-interactively 'org-table-next-row))
13509 (t (if indent (newline-and-indent) (newline)))))
13511 (defun org-return-indent ()
13512 "Goto next table row or insert a newline and indent.
13513 Calls `org-table-next-row' or `newline-and-indent', depending on
13514 context. See the individual commands for more information."
13515 (interactive)
13516 (org-return t))
13518 (defun org-ctrl-c-star ()
13519 "Compute table, or change heading status of lines.
13520 Calls `org-table-recalculate' or `org-toggle-heading',
13521 depending on context."
13522 (interactive)
13523 (cond
13524 ((org-at-table-p)
13525 (call-interactively 'org-table-recalculate))
13527 ;; Convert all lines in region to list items
13528 (call-interactively 'org-toggle-heading))))
13530 (defun org-ctrl-c-minus ()
13531 "Insert separator line in table or modify bullet status of line.
13532 Also turns a plain line or a region of lines into list items.
13533 Calls `org-table-insert-hline', `org-toggle-item', or
13534 `org-cycle-list-bullet', depending on context."
13535 (interactive)
13536 (cond
13537 ((org-at-table-p)
13538 (call-interactively 'org-table-insert-hline))
13539 ((org-region-active-p)
13540 (call-interactively 'org-toggle-item))
13541 ((org-in-item-p)
13542 (call-interactively 'org-cycle-list-bullet))
13544 (call-interactively 'org-toggle-item))))
13546 (defun org-toggle-item ()
13547 "Convert headings or normal lines to items, items to normal lines.
13548 If there is no active region, only the current line is considered.
13550 If the first line in the region is a headline, convert all headlines to items.
13552 If the first line in the region is an item, convert all items to normal lines.
13554 If the first line is normal text, add an item bullet to each line."
13555 (interactive)
13556 (let (l2 l beg end)
13557 (if (org-region-active-p)
13558 (setq beg (region-beginning) end (region-end))
13559 (setq beg (point-at-bol)
13560 end (min (1+ (point-at-eol)) (point-max))))
13561 (save-excursion
13562 (goto-char end)
13563 (setq l2 (org-current-line))
13564 (goto-char beg)
13565 (beginning-of-line 1)
13566 (setq l (1- (org-current-line)))
13567 (if (org-at-item-p)
13568 ;; We already have items, de-itemize
13569 (while (< (setq l (1+ l)) l2)
13570 (when (org-at-item-p)
13571 (goto-char (match-beginning 2))
13572 (delete-region (match-beginning 2) (match-end 2))
13573 (and (looking-at "[ \t]+") (replace-match "")))
13574 (beginning-of-line 2))
13575 (if (org-on-heading-p)
13576 ;; Headings, convert to items
13577 (while (< (setq l (1+ l)) l2)
13578 (if (looking-at org-outline-regexp)
13579 (replace-match "- " t t))
13580 (beginning-of-line 2))
13581 ;; normal lines, turn them into items
13582 (while (< (setq l (1+ l)) l2)
13583 (unless (org-at-item-p)
13584 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13585 (replace-match "\\1- \\2")))
13586 (beginning-of-line 2)))))))
13588 (defun org-toggle-heading (&optional nstars)
13589 "Convert headings to normal text, or items or text to headings.
13590 If there is no active region, only the current line is considered.
13592 If the first line is a heading, remove the stars from all headlines
13593 in the region.
13595 If the first line is a plain list item, turn all plain list items into
13596 headings.
13598 If the first line is a normal line, turn each and every line in the region
13599 into a heading.
13601 When converting a line into a heading, the number of stars is chosen
13602 such that the lines become children of the current entry. However, when
13603 a prefix argument is given, its value determines the number of stars to add."
13604 (interactive "P")
13605 (let (l2 l itemp beg end)
13606 (if (org-region-active-p)
13607 (setq beg (region-beginning) end (region-end))
13608 (setq beg (point-at-bol)
13609 end (min (1+ (point-at-eol)) (point-max))))
13610 (save-excursion
13611 (goto-char end)
13612 (setq l2 (org-current-line))
13613 (goto-char beg)
13614 (beginning-of-line 1)
13615 (setq l (1- (org-current-line)))
13616 (if (org-on-heading-p)
13617 ;; We already have headlines, de-star them
13618 (while (< (setq l (1+ l)) l2)
13619 (when (org-on-heading-p t)
13620 (and (looking-at outline-regexp) (replace-match "")))
13621 (beginning-of-line 2))
13622 (setq itemp (org-at-item-p))
13623 (let* ((stars
13624 (if nstars
13625 (make-string (prefix-numeric-value current-prefix-arg)
13627 (save-excursion
13628 (re-search-backward org-complex-heading-regexp nil t)
13629 (or (match-string 1) "*"))))
13630 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13631 (rpl (concat stars add-stars " ")))
13632 (while (< (setq l (1+ l)) l2)
13633 (if itemp
13634 (and (org-at-item-p) (replace-match rpl t t))
13635 (unless (org-on-heading-p)
13636 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13637 (replace-match (concat rpl (match-string 2))))))
13638 (beginning-of-line 2)))))))
13640 (defun org-meta-return (&optional arg)
13641 "Insert a new heading or wrap a region in a table.
13642 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13643 See the individual commands for more information."
13644 (interactive "P")
13645 (cond
13646 ((org-at-table-p)
13647 (call-interactively 'org-table-wrap-region))
13648 (t (call-interactively 'org-insert-heading))))
13650 ;;; Menu entries
13652 ;; Define the Org-mode menus
13653 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13654 '("Tbl"
13655 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13656 ["Next Field" org-cycle (org-at-table-p)]
13657 ["Previous Field" org-shifttab (org-at-table-p)]
13658 ["Next Row" org-return (org-at-table-p)]
13659 "--"
13660 ["Blank Field" org-table-blank-field (org-at-table-p)]
13661 ["Edit Field" org-table-edit-field (org-at-table-p)]
13662 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13663 "--"
13664 ("Column"
13665 ["Move Column Left" org-metaleft (org-at-table-p)]
13666 ["Move Column Right" org-metaright (org-at-table-p)]
13667 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13668 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13669 ("Row"
13670 ["Move Row Up" org-metaup (org-at-table-p)]
13671 ["Move Row Down" org-metadown (org-at-table-p)]
13672 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13673 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13674 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13675 "--"
13676 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13677 ("Rectangle"
13678 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13679 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13680 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13681 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13682 "--"
13683 ("Calculate"
13684 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13685 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13686 ["Edit Formulas" org-edit-special (org-at-table-p)]
13687 "--"
13688 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13689 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13690 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13691 "--"
13692 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13693 "--"
13694 ["Sum Column/Rectangle" org-table-sum
13695 (or (org-at-table-p) (org-region-active-p))]
13696 ["Which Column?" org-table-current-column (org-at-table-p)])
13697 ["Debug Formulas"
13698 org-table-toggle-formula-debugger
13699 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13700 ["Show Col/Row Numbers"
13701 org-table-toggle-coordinate-overlays
13702 :style toggle
13703 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13704 "--"
13705 ["Create" org-table-create (and (not (org-at-table-p))
13706 org-enable-table-editor)]
13707 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13708 ["Import from File" org-table-import (not (org-at-table-p))]
13709 ["Export to File" org-table-export (org-at-table-p)]
13710 "--"
13711 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13713 (easy-menu-define org-org-menu org-mode-map "Org menu"
13714 '("Org"
13715 ("Show/Hide"
13716 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13717 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13718 ["Sparse Tree..." org-sparse-tree t]
13719 ["Reveal Context" org-reveal t]
13720 ["Show All" show-all t]
13721 "--"
13722 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13723 "--"
13724 ["New Heading" org-insert-heading t]
13725 ("Navigate Headings"
13726 ["Up" outline-up-heading t]
13727 ["Next" outline-next-visible-heading t]
13728 ["Previous" outline-previous-visible-heading t]
13729 ["Next Same Level" outline-forward-same-level t]
13730 ["Previous Same Level" outline-backward-same-level t]
13731 "--"
13732 ["Jump" org-goto t])
13733 ("Edit Structure"
13734 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13735 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13736 "--"
13737 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13738 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13739 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13740 "--"
13741 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13742 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13743 ["Demote Heading" org-metaright (not (org-at-table-p))]
13744 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13745 "--"
13746 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13747 "--"
13748 ["Convert to odd levels" org-convert-to-odd-levels t]
13749 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13750 ("Editing"
13751 ["Emphasis..." org-emphasize t]
13752 ["Edit Source Example" org-edit-special t]
13753 "--"
13754 ["Footnote new/jump" org-footnote-action t]
13755 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13756 ("Archive"
13757 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13758 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13759 ; :active t :keys "C-u C-c C-x C-a"]
13760 ["Sparse trees open ARCHIVE trees"
13761 (setq org-sparse-tree-open-archived-trees
13762 (not org-sparse-tree-open-archived-trees))
13763 :style toggle :selected org-sparse-tree-open-archived-trees]
13764 ["Cycling opens ARCHIVE trees"
13765 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13766 :style toggle :selected org-cycle-open-archived-trees]
13767 "--"
13768 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13769 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13770 ; ["Check and Move Children" (org-archive-subtree '(4))
13771 ; :active t :keys "C-u C-c C-x C-s"]
13773 "--"
13774 ("TODO Lists"
13775 ["TODO/DONE/-" org-todo t]
13776 ("Select keyword"
13777 ["Next keyword" org-shiftright (org-on-heading-p)]
13778 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13779 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13780 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13781 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13782 ["Show TODO Tree" org-show-todo-tree t]
13783 ["Global TODO list" org-todo-list t]
13784 "--"
13785 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
13786 :selected org-enforce-todo-dependencies :style toggle :active t]
13787 "Settings for tree at point"
13788 ["Do Children sequentially" org-toggle-ordered-property :style radio
13789 :selected (ignore-errors (org-entry-get nil "ORDERED"))
13790 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13791 ["Do Children parallel" org-toggle-ordered-property :style radio
13792 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
13793 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13794 "--"
13795 ["Set Priority" org-priority t]
13796 ["Priority Up" org-shiftup t]
13797 ["Priority Down" org-shiftdown t])
13798 ("TAGS and Properties"
13799 ["Set Tags" org-set-tags-command t]
13800 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13801 "--"
13802 ["Set property" org-set-property t]
13803 ["Column view of properties" org-columns t]
13804 ["Insert Column View DBlock" org-insert-columns-dblock t])
13805 ("Dates and Scheduling"
13806 ["Timestamp" org-time-stamp t]
13807 ["Timestamp (inactive)" org-time-stamp-inactive t]
13808 ("Change Date"
13809 ["1 Day Later" org-shiftright t]
13810 ["1 Day Earlier" org-shiftleft t]
13811 ["1 ... Later" org-shiftup t]
13812 ["1 ... Earlier" org-shiftdown t])
13813 ["Compute Time Range" org-evaluate-time-range t]
13814 ["Schedule Item" org-schedule t]
13815 ["Deadline" org-deadline t]
13816 "--"
13817 ["Custom time format" org-toggle-time-stamp-overlays
13818 :style radio :selected org-display-custom-times]
13819 "--"
13820 ["Goto Calendar" org-goto-calendar t]
13821 ["Date from Calendar" org-date-from-calendar t]
13822 "--"
13823 ["Start/Restart Timer" org-timer-start t]
13824 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13825 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13826 ["Insert Timer String" org-timer t]
13827 ["Insert Timer Item" org-timer-item t])
13828 ("Logging work"
13829 ["Clock in" org-clock-in t]
13830 ["Clock out" org-clock-out t]
13831 ["Clock cancel" org-clock-cancel t]
13832 ["Goto running clock" org-clock-goto t]
13833 ["Display times" org-clock-display t]
13834 ["Create clock table" org-clock-report t]
13835 "--"
13836 ["Record DONE time"
13837 (progn (setq org-log-done (not org-log-done))
13838 (message "Switching to %s will %s record a timestamp"
13839 (car org-done-keywords)
13840 (if org-log-done "automatically" "not")))
13841 :style toggle :selected org-log-done])
13842 "--"
13843 ["Agenda Command..." org-agenda t]
13844 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13845 ("File List for Agenda")
13846 ("Special views current file"
13847 ["TODO Tree" org-show-todo-tree t]
13848 ["Check Deadlines" org-check-deadlines t]
13849 ["Timeline" org-timeline t]
13850 ["Tags Tree" org-tags-sparse-tree t])
13851 "--"
13852 ("Hyperlinks"
13853 ["Store Link (Global)" org-store-link t]
13854 ["Insert Link" org-insert-link t]
13855 ["Follow Link" org-open-at-point t]
13856 "--"
13857 ["Next link" org-next-link t]
13858 ["Previous link" org-previous-link t]
13859 "--"
13860 ["Descriptive Links"
13861 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13862 :style radio
13863 :selected (member '(org-link) buffer-invisibility-spec)]
13864 ["Literal Links"
13865 (progn
13866 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13867 :style radio
13868 :selected (not (member '(org-link) buffer-invisibility-spec))])
13869 "--"
13870 ["Export/Publish..." org-export t]
13871 ("LaTeX"
13872 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13873 :selected org-cdlatex-mode]
13874 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13875 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13876 ["Modify math symbol" org-cdlatex-math-modify
13877 (org-inside-LaTeX-fragment-p)]
13878 ["Export LaTeX fragments as images"
13879 (if (featurep 'org-exp)
13880 (setq org-export-with-LaTeX-fragments
13881 (not org-export-with-LaTeX-fragments))
13882 (require 'org-exp))
13883 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13884 org-export-with-LaTeX-fragments)])
13885 "--"
13886 ("Documentation"
13887 ["Show Version" org-version t]
13888 ["Info Documentation" org-info t])
13889 ("Customize"
13890 ["Browse Org Group" org-customize t]
13891 "--"
13892 ["Expand This Menu" org-create-customize-menu
13893 (fboundp 'customize-menu-create)])
13894 "--"
13895 ["Refresh setup" org-mode-restart t]
13898 (defun org-info (&optional node)
13899 "Read documentation for Org-mode in the info system.
13900 With optional NODE, go directly to that node."
13901 (interactive)
13902 (info (format "(org)%s" (or node ""))))
13904 (defun org-install-agenda-files-menu ()
13905 (let ((bl (buffer-list)))
13906 (save-excursion
13907 (while bl
13908 (set-buffer (pop bl))
13909 (if (org-mode-p) (setq bl nil)))
13910 (when (org-mode-p)
13911 (easy-menu-change
13912 '("Org") "File List for Agenda"
13913 (append
13914 (list
13915 ["Edit File List" (org-edit-agenda-file-list) t]
13916 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13917 ["Remove Current File from List" org-remove-file t]
13918 ["Cycle through agenda files" org-cycle-agenda-files t]
13919 ["Occur in all agenda files" org-occur-in-agenda-files t]
13920 "--")
13921 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13923 ;;;; Documentation
13925 ;;;###autoload
13926 (defun org-require-autoloaded-modules ()
13927 (interactive)
13928 (mapc 'require
13929 '(org-agenda org-archive org-attach org-clock org-colview
13930 org-exp org-id org-export-latex org-publish
13931 org-remember org-table org-timer)))
13933 ;;;###autoload
13934 (defun org-customize ()
13935 "Call the customize function with org as argument."
13936 (interactive)
13937 (org-load-modules-maybe)
13938 (org-require-autoloaded-modules)
13939 (customize-browse 'org))
13941 (defun org-create-customize-menu ()
13942 "Create a full customization menu for Org-mode, insert it into the menu."
13943 (interactive)
13944 (org-load-modules-maybe)
13945 (org-require-autoloaded-modules)
13946 (if (fboundp 'customize-menu-create)
13947 (progn
13948 (easy-menu-change
13949 '("Org") "Customize"
13950 `(["Browse Org group" org-customize t]
13951 "--"
13952 ,(customize-menu-create 'org)
13953 ["Set" Custom-set t]
13954 ["Save" Custom-save t]
13955 ["Reset to Current" Custom-reset-current t]
13956 ["Reset to Saved" Custom-reset-saved t]
13957 ["Reset to Standard Settings" Custom-reset-standard t]))
13958 (message "\"Org\"-menu now contains full customization menu"))
13959 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13961 ;;;; Miscellaneous stuff
13963 ;;; Generally useful functions
13965 (defun org-find-text-property-in-string (prop s)
13966 "Return the first non-nil value of property PROP in string S."
13967 (or (get-text-property 0 prop s)
13968 (get-text-property (or (next-single-property-change 0 prop s) 0)
13969 prop s)))
13971 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13972 "Display the given MESSAGE as a warning."
13973 (if (fboundp 'display-warning)
13974 (display-warning 'org message
13975 (if (featurep 'xemacs)
13976 'warning
13977 :warning))
13978 (let ((buf (get-buffer-create "*Org warnings*")))
13979 (with-current-buffer buf
13980 (goto-char (point-max))
13981 (insert "Warning (Org): " message)
13982 (unless (bolp)
13983 (newline)))
13984 (display-buffer buf)
13985 (sit-for 0))))
13987 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13988 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13989 (if (and marker (marker-buffer marker)
13990 (buffer-live-p (marker-buffer marker)))
13991 (progn
13992 (switch-to-buffer (marker-buffer marker))
13993 (if (or (> marker (point-max)) (< marker (point-min)))
13994 (widen))
13995 (goto-char marker)
13996 (org-show-context 'org-goto))
13997 (if bookmark
13998 (bookmark-jump bookmark)
13999 (error "Cannot find location"))))
14001 (defun org-quote-csv-field (s)
14002 "Quote field for inclusion in CSV material."
14003 (if (string-match "[\",]" s)
14004 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14007 (defun org-plist-delete (plist property)
14008 "Delete PROPERTY from PLIST.
14009 This is in contrast to merely setting it to 0."
14010 (let (p)
14011 (while plist
14012 (if (not (eq property (car plist)))
14013 (setq p (plist-put p (car plist) (nth 1 plist))))
14014 (setq plist (cddr plist)))
14017 (defun org-force-self-insert (N)
14018 "Needed to enforce self-insert under remapping."
14019 (interactive "p")
14020 (self-insert-command N))
14022 (defun org-string-width (s)
14023 "Compute width of string, ignoring invisible characters.
14024 This ignores character with invisibility property `org-link', and also
14025 characters with property `org-cwidth', because these will become invisible
14026 upon the next fontification round."
14027 (let (b l)
14028 (when (or (eq t buffer-invisibility-spec)
14029 (assq 'org-link buffer-invisibility-spec))
14030 (while (setq b (text-property-any 0 (length s)
14031 'invisible 'org-link s))
14032 (setq s (concat (substring s 0 b)
14033 (substring s (or (next-single-property-change
14034 b 'invisible s) (length s)))))))
14035 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14036 (setq s (concat (substring s 0 b)
14037 (substring s (or (next-single-property-change
14038 b 'org-cwidth s) (length s))))))
14039 (setq l (string-width s) b -1)
14040 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14041 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14044 (defun org-get-indentation (&optional line)
14045 "Get the indentation of the current line, interpreting tabs.
14046 When LINE is given, assume it represents a line and compute its indentation."
14047 (if line
14048 (if (string-match "^ *" (org-remove-tabs line))
14049 (match-end 0))
14050 (save-excursion
14051 (beginning-of-line 1)
14052 (skip-chars-forward " \t")
14053 (current-column))))
14055 (defun org-remove-tabs (s &optional width)
14056 "Replace tabulators in S with spaces.
14057 Assumes that s is a single line, starting in column 0."
14058 (setq width (or width tab-width))
14059 (while (string-match "\t" s)
14060 (setq s (replace-match
14061 (make-string
14062 (- (* width (/ (+ (match-beginning 0) width) width))
14063 (match-beginning 0)) ?\ )
14064 t t s)))
14067 (defun org-fix-indentation (line ind)
14068 "Fix indentation in LINE.
14069 IND is a cons cell with target and minimum indentation.
14070 If the current indentation in LINE is smaller than the minimum,
14071 leave it alone. If it is larger than ind, set it to the target."
14072 (let* ((l (org-remove-tabs line))
14073 (i (org-get-indentation l))
14074 (i1 (car ind)) (i2 (cdr ind)))
14075 (if (>= i i2) (setq l (substring line i2)))
14076 (if (> i1 0)
14077 (concat (make-string i1 ?\ ) l)
14078 l)))
14080 (defun org-base-buffer (buffer)
14081 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14082 (if (not buffer)
14083 buffer
14084 (or (buffer-base-buffer buffer)
14085 buffer)))
14087 (defun org-trim (s)
14088 "Remove whitespace at beginning and end of string."
14089 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14090 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14093 (defun org-wrap (string &optional width lines)
14094 "Wrap string to either a number of lines, or a width in characters.
14095 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14096 that costs. If there is a word longer than WIDTH, the text is actually
14097 wrapped to the length of that word.
14098 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14099 many lines, whatever width that takes.
14100 The return value is a list of lines, without newlines at the end."
14101 (let* ((words (org-split-string string "[ \t\n]+"))
14102 (maxword (apply 'max (mapcar 'org-string-width words)))
14103 w ll)
14104 (cond (width
14105 (org-do-wrap words (max maxword width)))
14106 (lines
14107 (setq w maxword)
14108 (setq ll (org-do-wrap words maxword))
14109 (if (<= (length ll) lines)
14111 (setq ll words)
14112 (while (> (length ll) lines)
14113 (setq w (1+ w))
14114 (setq ll (org-do-wrap words w)))
14115 ll))
14116 (t (error "Cannot wrap this")))))
14118 (defun org-do-wrap (words width)
14119 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14120 (let (lines line)
14121 (while words
14122 (setq line (pop words))
14123 (while (and words (< (+ (length line) (length (car words))) width))
14124 (setq line (concat line " " (pop words))))
14125 (setq lines (push line lines)))
14126 (nreverse lines)))
14128 (defun org-split-string (string &optional separators)
14129 "Splits STRING into substrings at SEPARATORS.
14130 No empty strings are returned if there are matches at the beginning
14131 and end of string."
14132 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14133 (start 0)
14134 notfirst
14135 (list nil))
14136 (while (and (string-match rexp string
14137 (if (and notfirst
14138 (= start (match-beginning 0))
14139 (< start (length string)))
14140 (1+ start) start))
14141 (< (match-beginning 0) (length string)))
14142 (setq notfirst t)
14143 (or (eq (match-beginning 0) 0)
14144 (and (eq (match-beginning 0) (match-end 0))
14145 (eq (match-beginning 0) start))
14146 (setq list
14147 (cons (substring string start (match-beginning 0))
14148 list)))
14149 (setq start (match-end 0)))
14150 (or (eq start (length string))
14151 (setq list
14152 (cons (substring string start)
14153 list)))
14154 (nreverse list)))
14156 (defun org-context ()
14157 "Return a list of contexts of the current cursor position.
14158 If several contexts apply, all are returned.
14159 Each context entry is a list with a symbol naming the context, and
14160 two positions indicating start and end of the context. Possible
14161 contexts are:
14163 :headline anywhere in a headline
14164 :headline-stars on the leading stars in a headline
14165 :todo-keyword on a TODO keyword (including DONE) in a headline
14166 :tags on the TAGS in a headline
14167 :priority on the priority cookie in a headline
14168 :item on the first line of a plain list item
14169 :item-bullet on the bullet/number of a plain list item
14170 :checkbox on the checkbox in a plain list item
14171 :table in an org-mode table
14172 :table-special on a special filed in a table
14173 :table-table in a table.el table
14174 :link on a hyperlink
14175 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14176 :target on a <<target>>
14177 :radio-target on a <<<radio-target>>>
14178 :latex-fragment on a LaTeX fragment
14179 :latex-preview on a LaTeX fragment with overlayed preview image
14181 This function expects the position to be visible because it uses font-lock
14182 faces as a help to recognize the following contexts: :table-special, :link,
14183 and :keyword."
14184 (let* ((f (get-text-property (point) 'face))
14185 (faces (if (listp f) f (list f)))
14186 (p (point)) clist o)
14187 ;; First the large context
14188 (cond
14189 ((org-on-heading-p t)
14190 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14191 (when (progn
14192 (beginning-of-line 1)
14193 (looking-at org-todo-line-tags-regexp))
14194 (push (org-point-in-group p 1 :headline-stars) clist)
14195 (push (org-point-in-group p 2 :todo-keyword) clist)
14196 (push (org-point-in-group p 4 :tags) clist))
14197 (goto-char p)
14198 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14199 (if (looking-at "\\[#[A-Z0-9]\\]")
14200 (push (org-point-in-group p 0 :priority) clist)))
14202 ((org-at-item-p)
14203 (push (org-point-in-group p 2 :item-bullet) clist)
14204 (push (list :item (point-at-bol)
14205 (save-excursion (org-end-of-item) (point)))
14206 clist)
14207 (and (org-at-item-checkbox-p)
14208 (push (org-point-in-group p 0 :checkbox) clist)))
14210 ((org-at-table-p)
14211 (push (list :table (org-table-begin) (org-table-end)) clist)
14212 (if (memq 'org-formula faces)
14213 (push (list :table-special
14214 (previous-single-property-change p 'face)
14215 (next-single-property-change p 'face)) clist)))
14216 ((org-at-table-p 'any)
14217 (push (list :table-table) clist)))
14218 (goto-char p)
14220 ;; Now the small context
14221 (cond
14222 ((org-at-timestamp-p)
14223 (push (org-point-in-group p 0 :timestamp) clist))
14224 ((memq 'org-link faces)
14225 (push (list :link
14226 (previous-single-property-change p 'face)
14227 (next-single-property-change p 'face)) clist))
14228 ((memq 'org-special-keyword faces)
14229 (push (list :keyword
14230 (previous-single-property-change p 'face)
14231 (next-single-property-change p 'face)) clist))
14232 ((org-on-target-p)
14233 (push (org-point-in-group p 0 :target) clist)
14234 (goto-char (1- (match-beginning 0)))
14235 (if (looking-at org-radio-target-regexp)
14236 (push (org-point-in-group p 0 :radio-target) clist))
14237 (goto-char p))
14238 ((setq o (car (delq nil
14239 (mapcar
14240 (lambda (x)
14241 (if (memq x org-latex-fragment-image-overlays) x))
14242 (org-overlays-at (point))))))
14243 (push (list :latex-fragment
14244 (org-overlay-start o) (org-overlay-end o)) clist)
14245 (push (list :latex-preview
14246 (org-overlay-start o) (org-overlay-end o)) clist))
14247 ((org-inside-LaTeX-fragment-p)
14248 ;; FIXME: positions wrong.
14249 (push (list :latex-fragment (point) (point)) clist)))
14251 (setq clist (nreverse (delq nil clist)))
14252 clist))
14254 ;; FIXME: Compare with at-regexp-p Do we need both?
14255 (defun org-in-regexp (re &optional nlines visually)
14256 "Check if point is inside a match of regexp.
14257 Normally only the current line is checked, but you can include NLINES extra
14258 lines both before and after point into the search.
14259 If VISUALLY is set, require that the cursor is not after the match but
14260 really on, so that the block visually is on the match."
14261 (catch 'exit
14262 (let ((pos (point))
14263 (eol (point-at-eol (+ 1 (or nlines 0))))
14264 (inc (if visually 1 0)))
14265 (save-excursion
14266 (beginning-of-line (- 1 (or nlines 0)))
14267 (while (re-search-forward re eol t)
14268 (if (and (<= (match-beginning 0) pos)
14269 (>= (+ inc (match-end 0)) pos))
14270 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14272 (defun org-at-regexp-p (regexp)
14273 "Is point inside a match of REGEXP in the current line?"
14274 (catch 'exit
14275 (save-excursion
14276 (let ((pos (point)) (end (point-at-eol)))
14277 (beginning-of-line 1)
14278 (while (re-search-forward regexp end t)
14279 (if (and (<= (match-beginning 0) pos)
14280 (>= (match-end 0) pos))
14281 (throw 'exit t)))
14282 nil))))
14284 (defun org-occur-in-agenda-files (regexp &optional nlines)
14285 "Call `multi-occur' with buffers for all agenda files."
14286 (interactive "sOrg-files matching: \np")
14287 (let* ((files (org-agenda-files))
14288 (tnames (mapcar 'file-truename files))
14289 (extra org-agenda-text-search-extra-files)
14291 (when (eq (car extra) 'agenda-archives)
14292 (setq extra (cdr extra))
14293 (setq files (org-add-archive-files files)))
14294 (while (setq f (pop extra))
14295 (unless (member (file-truename f) tnames)
14296 (add-to-list 'files f 'append)
14297 (add-to-list 'tnames (file-truename f) 'append)))
14298 (multi-occur
14299 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14300 regexp)))
14302 (if (boundp 'occur-mode-find-occurrence-hook)
14303 ;; Emacs 23
14304 (add-hook 'occur-mode-find-occurrence-hook
14305 (lambda ()
14306 (when (org-mode-p)
14307 (org-reveal))))
14308 ;; Emacs 22
14309 (defadvice occur-mode-goto-occurrence
14310 (after org-occur-reveal activate)
14311 (and (org-mode-p) (org-reveal)))
14312 (defadvice occur-mode-goto-occurrence-other-window
14313 (after org-occur-reveal activate)
14314 (and (org-mode-p) (org-reveal)))
14315 (defadvice occur-mode-display-occurrence
14316 (after org-occur-reveal activate)
14317 (when (org-mode-p)
14318 (let ((pos (occur-mode-find-occurrence)))
14319 (with-current-buffer (marker-buffer pos)
14320 (save-excursion
14321 (goto-char pos)
14322 (org-reveal)))))))
14324 (defun org-uniquify (list)
14325 "Remove duplicate elements from LIST."
14326 (let (res)
14327 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14328 res))
14330 (defun org-delete-all (elts list)
14331 "Remove all elements in ELTS from LIST."
14332 (while elts
14333 (setq list (delete (pop elts) list)))
14334 list)
14336 (defun org-back-over-empty-lines ()
14337 "Move backwards over whitespace, to the beginning of the first empty line.
14338 Returns the number of empty lines passed."
14339 (let ((pos (point)))
14340 (skip-chars-backward " \t\n\r")
14341 (beginning-of-line 2)
14342 (goto-char (min (point) pos))
14343 (count-lines (point) pos)))
14345 (defun org-skip-whitespace ()
14346 (skip-chars-forward " \t\n\r"))
14348 (defun org-point-in-group (point group &optional context)
14349 "Check if POINT is in match-group GROUP.
14350 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14351 match. If the match group does ot exist or point is not inside it,
14352 return nil."
14353 (and (match-beginning group)
14354 (>= point (match-beginning group))
14355 (<= point (match-end group))
14356 (if context
14357 (list context (match-beginning group) (match-end group))
14358 t)))
14360 (defun org-switch-to-buffer-other-window (&rest args)
14361 "Switch to buffer in a second window on the current frame.
14362 In particular, do not allow pop-up frames."
14363 (let (pop-up-frames special-display-buffer-names special-display-regexps
14364 special-display-function)
14365 (apply 'switch-to-buffer-other-window args)))
14367 (defun org-combine-plists (&rest plists)
14368 "Create a single property list from all plists in PLISTS.
14369 The process starts by copying the first list, and then setting properties
14370 from the other lists. Settings in the last list are the most significant
14371 ones and overrule settings in the other lists."
14372 (let ((rtn (copy-sequence (pop plists)))
14373 p v ls)
14374 (while plists
14375 (setq ls (pop plists))
14376 (while ls
14377 (setq p (pop ls) v (pop ls))
14378 (setq rtn (plist-put rtn p v))))
14379 rtn))
14381 (defun org-move-line-down (arg)
14382 "Move the current line down. With prefix argument, move it past ARG lines."
14383 (interactive "p")
14384 (let ((col (current-column))
14385 beg end pos)
14386 (beginning-of-line 1) (setq beg (point))
14387 (beginning-of-line 2) (setq end (point))
14388 (beginning-of-line (+ 1 arg))
14389 (setq pos (move-marker (make-marker) (point)))
14390 (insert (delete-and-extract-region beg end))
14391 (goto-char pos)
14392 (org-move-to-column col)))
14394 (defun org-move-line-up (arg)
14395 "Move the current line up. With prefix argument, move it past ARG lines."
14396 (interactive "p")
14397 (let ((col (current-column))
14398 beg end pos)
14399 (beginning-of-line 1) (setq beg (point))
14400 (beginning-of-line 2) (setq end (point))
14401 (beginning-of-line (- arg))
14402 (setq pos (move-marker (make-marker) (point)))
14403 (insert (delete-and-extract-region beg end))
14404 (goto-char pos)
14405 (org-move-to-column col)))
14407 (defun org-replace-escapes (string table)
14408 "Replace %-escapes in STRING with values in TABLE.
14409 TABLE is an association list with keys like \"%a\" and string values.
14410 The sequences in STRING may contain normal field width and padding information,
14411 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14412 so values can contain further %-escapes if they are define later in TABLE."
14413 (let ((case-fold-search nil)
14414 e re rpl)
14415 (while (setq e (pop table))
14416 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14417 (while (string-match re string)
14418 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14419 (cdr e)))
14420 (setq string (replace-match rpl t t string))))
14421 string))
14424 (defun org-sublist (list start end)
14425 "Return a section of LIST, from START to END.
14426 Counting starts at 1."
14427 (let (rtn (c start))
14428 (setq list (nthcdr (1- start) list))
14429 (while (and list (<= c end))
14430 (push (pop list) rtn)
14431 (setq c (1+ c)))
14432 (nreverse rtn)))
14434 (defun org-find-base-buffer-visiting (file)
14435 "Like `find-buffer-visiting' but alway return the base buffer and
14436 not an indirect buffer."
14437 (let ((buf (find-buffer-visiting file)))
14438 (if buf
14439 (or (buffer-base-buffer buf) buf)
14440 nil)))
14442 (defun org-image-file-name-regexp (&optional extensions)
14443 "Return regexp matching the file names of images.
14444 If EXTENSIONS is given, only match these."
14445 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14446 (image-file-name-regexp)
14447 (let ((image-file-name-extensions
14448 (or extensions
14449 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14450 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14451 (concat "\\."
14452 (regexp-opt (nconc (mapcar 'upcase
14453 image-file-name-extensions)
14454 image-file-name-extensions)
14456 "\\'"))))
14458 (defun org-file-image-p (file &optional extensions)
14459 "Return non-nil if FILE is an image."
14460 (save-match-data
14461 (string-match (org-image-file-name-regexp extensions) file)))
14463 (defun org-get-cursor-date ()
14464 "Return the date at cursor in as a time.
14465 This works in the calendar and in the agenda, anywhere else it just
14466 returns the current time."
14467 (let (date day defd)
14468 (cond
14469 ((eq major-mode 'calendar-mode)
14470 (setq date (calendar-cursor-to-date)
14471 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14472 ((eq major-mode 'org-agenda-mode)
14473 (setq day (get-text-property (point) 'day))
14474 (if day
14475 (setq date (calendar-gregorian-from-absolute day)
14476 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14477 (nth 2 date))))))
14478 (or defd (current-time))))
14480 (defvar org-agenda-action-marker (make-marker)
14481 "Marker pointing to the entry for the next agenda action.")
14483 (defun org-mark-entry-for-agenda-action ()
14484 "Mark the current entry as target of an agenda action.
14485 Agenda actions are actions executed from the agenda with the key `k',
14486 which make use of the date at the cursor."
14487 (interactive)
14488 (move-marker org-agenda-action-marker
14489 (save-excursion (org-back-to-heading t) (point))
14490 (current-buffer))
14491 (message
14492 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14494 ;;; Paragraph filling stuff.
14495 ;; We want this to be just right, so use the full arsenal.
14497 (defun org-indent-line-function ()
14498 "Indent line like previous, but further if previous was headline or item."
14499 (interactive)
14500 (let* ((pos (point))
14501 (itemp (org-at-item-p))
14502 column bpos bcol tpos tcol bullet btype bullet-type)
14503 ;; Find the previous relevant line
14504 (beginning-of-line 1)
14505 (cond
14506 ((looking-at "#") (setq column 0))
14507 ((looking-at "\\*+ ") (setq column 0))
14509 (beginning-of-line 0)
14510 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14511 (beginning-of-line 0))
14512 (cond
14513 ((looking-at "\\*+[ \t]+")
14514 (if (not org-adapt-indentation)
14515 (setq column 0)
14516 (goto-char (match-end 0))
14517 (setq column (current-column))))
14518 ((org-in-item-p)
14519 (org-beginning-of-item)
14520 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14521 (setq bpos (match-beginning 1) tpos (match-end 0)
14522 bcol (progn (goto-char bpos) (current-column))
14523 tcol (progn (goto-char tpos) (current-column))
14524 bullet (match-string 1)
14525 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14526 (if (> tcol (+ bcol org-description-max-indent))
14527 (setq tcol (+ bcol 5)))
14528 (if (not itemp)
14529 (setq column tcol)
14530 (goto-char pos)
14531 (beginning-of-line 1)
14532 (if (looking-at "\\S-")
14533 (progn
14534 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14535 (setq bullet (match-string 1)
14536 btype (if (string-match "[0-9]" bullet) "n" bullet))
14537 (setq column (if (equal btype bullet-type) bcol tcol)))
14538 (setq column (org-get-indentation)))))
14539 (t (setq column (org-get-indentation))))))
14540 (goto-char pos)
14541 (if (<= (current-column) (current-indentation))
14542 (org-indent-line-to column)
14543 (save-excursion (org-indent-line-to column)))
14544 (setq column (current-column))
14545 (beginning-of-line 1)
14546 (if (looking-at
14547 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14548 (replace-match (concat "\\1" (format org-property-format
14549 (match-string 2) (match-string 3)))
14550 t nil))
14551 (org-move-to-column column)))
14553 (defun org-set-autofill-regexps ()
14554 (interactive)
14555 ;; In the paragraph separator we include headlines, because filling
14556 ;; text in a line directly attached to a headline would otherwise
14557 ;; fill the headline as well.
14558 (org-set-local 'comment-start-skip "^#+[ \t]*")
14559 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14560 ;; The paragraph starter includes hand-formatted lists.
14561 (org-set-local 'paragraph-start
14562 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14563 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14564 ;; But only if the user has not turned off tables or fixed-width regions
14565 (org-set-local
14566 'auto-fill-inhibit-regexp
14567 (concat "\\*+ \\|#\\+"
14568 "\\|[ \t]*" org-keyword-time-regexp
14569 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14570 (concat
14571 "\\|[ \t]*["
14572 (if org-enable-table-editor "|" "")
14573 (if org-enable-fixed-width-editor ":" "")
14574 "]"))))
14575 ;; We use our own fill-paragraph function, to make sure that tables
14576 ;; and fixed-width regions are not wrapped. That function will pass
14577 ;; through to `fill-paragraph' when appropriate.
14578 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14579 ; Adaptive filling: To get full control, first make sure that
14580 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14581 (org-set-local 'adaptive-fill-regexp "\000")
14582 (org-set-local 'adaptive-fill-function
14583 'org-adaptive-fill-function)
14584 (org-set-local
14585 'align-mode-rules-list
14586 '((org-in-buffer-settings
14587 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14588 (modes . '(org-mode))))))
14590 (defun org-fill-paragraph (&optional justify)
14591 "Re-align a table, pass through to fill-paragraph if no table."
14592 (let ((table-p (org-at-table-p))
14593 (table.el-p (org-at-table.el-p)))
14594 (cond ((and (equal (char-after (point-at-bol)) ?*)
14595 (save-excursion (goto-char (point-at-bol))
14596 (looking-at outline-regexp)))
14597 t) ; skip headlines
14598 (table.el-p t) ; skip table.el tables
14599 (table-p (org-table-align) t) ; align org-mode tables
14600 (t nil)))) ; call paragraph-fill
14602 ;; For reference, this is the default value of adaptive-fill-regexp
14603 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14605 (defun org-adaptive-fill-function ()
14606 "Return a fill prefix for org-mode files.
14607 In particular, this makes sure hanging paragraphs for hand-formatted lists
14608 work correctly."
14609 (cond ((looking-at "#[ \t]+")
14610 (match-string 0))
14611 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14612 (save-excursion
14613 (if (> (match-end 1) (+ (match-beginning 1)
14614 org-description-max-indent))
14615 (goto-char (+ (match-beginning 1) 5))
14616 (goto-char (match-end 0)))
14617 (make-string (current-column) ?\ )))
14618 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14619 (save-excursion
14620 (goto-char (match-end 0))
14621 (make-string (current-column) ?\ )))
14622 (t nil)))
14624 ;;; Other stuff.
14626 (defun org-toggle-fixed-width-section (arg)
14627 "Toggle the fixed-width export.
14628 If there is no active region, the QUOTE keyword at the current headline is
14629 inserted or removed. When present, it causes the text between this headline
14630 and the next to be exported as fixed-width text, and unmodified.
14631 If there is an active region, this command adds or removes a colon as the
14632 first character of this line. If the first character of a line is a colon,
14633 this line is also exported in fixed-width font."
14634 (interactive "P")
14635 (let* ((cc 0)
14636 (regionp (org-region-active-p))
14637 (beg (if regionp (region-beginning) (point)))
14638 (end (if regionp (region-end)))
14639 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14640 (case-fold-search nil)
14641 (re "[ \t]*\\(:\\)")
14642 off)
14643 (if regionp
14644 (save-excursion
14645 (goto-char beg)
14646 (setq cc (current-column))
14647 (beginning-of-line 1)
14648 (setq off (looking-at re))
14649 (while (> nlines 0)
14650 (setq nlines (1- nlines))
14651 (beginning-of-line 1)
14652 (cond
14653 (arg
14654 (org-move-to-column cc t)
14655 (insert ":\n")
14656 (forward-line -1))
14657 ((and off (looking-at re))
14658 (replace-match "" t t nil 1))
14659 ((not off) (org-move-to-column cc t) (insert ":")))
14660 (forward-line 1)))
14661 (save-excursion
14662 (org-back-to-heading)
14663 (if (looking-at (concat outline-regexp
14664 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14665 (replace-match "" t t nil 1)
14666 (if (looking-at outline-regexp)
14667 (progn
14668 (goto-char (match-end 0))
14669 (insert org-quote-string " "))))))))
14671 ;;;; Functions extending outline functionality
14673 (defun org-beginning-of-line (&optional arg)
14674 "Go to the beginning of the current line. If that is invisible, continue
14675 to a visible line beginning. This makes the function of C-a more intuitive.
14676 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14677 first attempt, and only move to after the tags when the cursor is already
14678 beyond the end of the headline."
14679 (interactive "P")
14680 (let ((pos (point)) refpos)
14681 (beginning-of-line 1)
14682 (if (bobp)
14684 (backward-char 1)
14685 (if (org-invisible-p)
14686 (while (and (not (bobp)) (org-invisible-p))
14687 (backward-char 1)
14688 (beginning-of-line 1))
14689 (forward-char 1)))
14690 (when org-special-ctrl-a/e
14691 (cond
14692 ((and (looking-at org-complex-heading-regexp)
14693 (= (char-after (match-end 1)) ?\ ))
14694 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14695 (point-at-eol)))
14696 (goto-char
14697 (if (eq org-special-ctrl-a/e t)
14698 (cond ((> pos refpos) refpos)
14699 ((= pos (point)) refpos)
14700 (t (point)))
14701 (cond ((> pos (point)) (point))
14702 ((not (eq last-command this-command)) (point))
14703 (t refpos)))))
14704 ((org-at-item-p)
14705 (goto-char
14706 (if (eq org-special-ctrl-a/e t)
14707 (cond ((> pos (match-end 4)) (match-end 4))
14708 ((= pos (point)) (match-end 4))
14709 (t (point)))
14710 (cond ((> pos (point)) (point))
14711 ((not (eq last-command this-command)) (point))
14712 (t (match-end 4))))))))
14713 (org-no-warnings
14714 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14716 (defun org-end-of-line (&optional arg)
14717 "Go to the end of the line.
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 (if (or (not org-special-ctrl-a/e)
14723 (not (org-on-heading-p)))
14724 (end-of-line arg)
14725 (let ((pos (point)))
14726 (beginning-of-line 1)
14727 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14728 (if (eq org-special-ctrl-a/e t)
14729 (if (or (< pos (match-beginning 1))
14730 (= pos (match-end 0)))
14731 (goto-char (match-beginning 1))
14732 (goto-char (match-end 0)))
14733 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14734 (goto-char (match-end 0))
14735 (goto-char (match-beginning 1))))
14736 (end-of-line arg))))
14737 (org-no-warnings
14738 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14741 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14742 (define-key org-mode-map "\C-e" 'org-end-of-line)
14744 (defun org-kill-line (&optional arg)
14745 "Kill line, to tags or end of line."
14746 (interactive "P")
14747 (cond
14748 ((or (not org-special-ctrl-k)
14749 (bolp)
14750 (not (org-on-heading-p)))
14751 (call-interactively 'kill-line))
14752 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14753 (kill-region (point) (match-beginning 1))
14754 (org-set-tags nil t))
14755 (t (kill-region (point) (point-at-eol)))))
14757 (define-key org-mode-map "\C-k" 'org-kill-line)
14759 (defun org-yank (&optional arg)
14760 "Yank. If the kill is a subtree, treat it specially.
14761 This command will look at the current kill and check if is a single
14762 subtree, or a series of subtrees[1]. If it passes the test, and if the
14763 cursor is at the beginning of a line or after the stars of a currently
14764 empty headline, then the yank is handled specially. How exactly depends
14765 on the value of the following variables, both set by default.
14767 org-yank-folded-subtrees
14768 When set, the subtree(s) will be folded after insertion, but only
14769 if doing so would now swallow text after the yanked text.
14771 org-yank-adjusted-subtrees
14772 When set, the subtree will be promoted or demoted in order to
14773 fit into the local outline tree structure, which means that the level
14774 will be adjusted so that it becomes the smaller one of the two
14775 *visible* surrounding headings.
14777 Any prefix to this command will cause `yank' to be called directly with
14778 no special treatment. In particular, a simple `C-u' prefix will just
14779 plainly yank the text as it is.
14781 \[1] Basically, the test checks if the first non-white line is a heading
14782 and if there are no other headings with fewer stars."
14783 (interactive "P")
14784 (setq this-command 'yank)
14785 (if arg
14786 (call-interactively 'yank)
14787 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14788 (and (org-kill-is-subtree-p)
14789 (or (bolp)
14790 (and (looking-at "[ \t]*$")
14791 (string-match
14792 "\\`\\*+\\'"
14793 (buffer-substring (point-at-bol) (point)))))))
14794 swallowp)
14795 (cond
14796 ((and subtreep org-yank-folded-subtrees)
14797 (let ((beg (point))
14798 end)
14799 (if (and subtreep org-yank-adjusted-subtrees)
14800 (org-paste-subtree nil nil 'for-yank)
14801 (call-interactively 'yank))
14802 (setq end (point))
14803 (goto-char beg)
14804 (when (and (bolp) subtreep
14805 (not (setq swallowp
14806 (org-yank-folding-would-swallow-text beg end))))
14807 (or (looking-at outline-regexp)
14808 (re-search-forward (concat "^" outline-regexp) end t))
14809 (while (and (< (point) end) (looking-at outline-regexp))
14810 (hide-subtree)
14811 (org-cycle-show-empty-lines 'folded)
14812 (condition-case nil
14813 (outline-forward-same-level 1)
14814 (error (goto-char end)))))
14815 (when swallowp
14816 (message
14817 "Yanked text not folded because that would swallow text"))
14818 (goto-char end)
14819 (skip-chars-forward " \t\n\r")
14820 (beginning-of-line 1)
14821 (push-mark beg 'nomsg)))
14822 ((and subtreep org-yank-adjusted-subtrees)
14823 (let ((beg (point-at-bol)))
14824 (org-paste-subtree nil nil 'for-yank)
14825 (push-mark beg 'nomsg)))
14827 (call-interactively 'yank))))))
14829 (defun org-yank-folding-would-swallow-text (beg end)
14830 "Would hide-subtree at BEG swallow any text after END?"
14831 (let (level)
14832 (save-excursion
14833 (goto-char beg)
14834 (when (or (looking-at outline-regexp)
14835 (re-search-forward (concat "^" outline-regexp) end t))
14836 (setq level (org-outline-level)))
14837 (goto-char end)
14838 (skip-chars-forward " \t\r\n\v\f")
14839 (if (or (eobp)
14840 (and (bolp) (looking-at org-outline-regexp)
14841 (<= (org-outline-level) level)))
14842 nil ; Nothing would be swallowed
14843 t)))) ; something would swallow
14845 (define-key org-mode-map "\C-y" 'org-yank)
14847 (defun org-invisible-p ()
14848 "Check if point is at a character currently not visible."
14849 ;; Early versions of noutline don't have `outline-invisible-p'.
14850 (if (fboundp 'outline-invisible-p)
14851 (outline-invisible-p)
14852 (get-char-property (point) 'invisible)))
14854 (defun org-invisible-p2 ()
14855 "Check if point is at a character currently not visible."
14856 (save-excursion
14857 (if (and (eolp) (not (bobp))) (backward-char 1))
14858 ;; Early versions of noutline don't have `outline-invisible-p'.
14859 (if (fboundp 'outline-invisible-p)
14860 (outline-invisible-p)
14861 (get-char-property (point) 'invisible))))
14863 (defun org-back-to-heading (&optional invisible-ok)
14864 "Call `outline-back-to-heading', but provide a better error message."
14865 (condition-case nil
14866 (outline-back-to-heading invisible-ok)
14867 (error (error "Before first headline at position %d in buffer %s"
14868 (point) (current-buffer)))))
14870 (defun org-before-first-heading-p ()
14871 "Before first heading?"
14872 (save-excursion
14873 (null (re-search-backward "^\\*+ " nil t))))
14875 (defalias 'org-on-heading-p 'outline-on-heading-p)
14876 (defalias 'org-at-heading-p 'outline-on-heading-p)
14877 (defun org-at-heading-or-item-p ()
14878 (or (org-on-heading-p) (org-at-item-p)))
14880 (defun org-on-target-p ()
14881 (or (org-in-regexp org-radio-target-regexp)
14882 (org-in-regexp org-target-regexp)))
14884 (defun org-up-heading-all (arg)
14885 "Move to the heading line of which the present line is a subheading.
14886 This function considers both visible and invisible heading lines.
14887 With argument, move up ARG levels."
14888 (if (fboundp 'outline-up-heading-all)
14889 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14890 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14892 (defun org-up-heading-safe ()
14893 "Move to the heading line of which the present line is a subheading.
14894 This version will not throw an error. It will return the level of the
14895 headline found, or nil if no higher level is found."
14896 (let (start-level re)
14897 (org-back-to-heading t)
14898 (setq start-level (funcall outline-level))
14899 (if (equal start-level 1)
14901 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14902 (if (re-search-backward re nil t)
14903 (funcall outline-level)))))
14905 (defun org-first-sibling-p ()
14906 "Is this heading the first child of its parents?"
14907 (interactive)
14908 (let ((re (concat "^" outline-regexp))
14909 level l)
14910 (unless (org-at-heading-p t)
14911 (error "Not at a heading"))
14912 (setq level (funcall outline-level))
14913 (save-excursion
14914 (if (not (re-search-backward re nil t))
14916 (setq l (funcall outline-level))
14917 (< l level)))))
14919 (defun org-goto-sibling (&optional previous)
14920 "Goto the next sibling, even if it is invisible.
14921 When PREVIOUS is set, go to the previous sibling instead. Returns t
14922 when a sibling was found. When none is found, return nil and don't
14923 move point."
14924 (let ((fun (if previous 're-search-backward 're-search-forward))
14925 (pos (point))
14926 (re (concat "^" outline-regexp))
14927 level l)
14928 (when (condition-case nil (org-back-to-heading t) (error nil))
14929 (setq level (funcall outline-level))
14930 (catch 'exit
14931 (or previous (forward-char 1))
14932 (while (funcall fun re nil t)
14933 (setq l (funcall outline-level))
14934 (when (< l level) (goto-char pos) (throw 'exit nil))
14935 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14936 (goto-char pos)
14937 nil))))
14939 (defun org-show-siblings ()
14940 "Show all siblings of the current headline."
14941 (save-excursion
14942 (while (org-goto-sibling) (org-flag-heading nil)))
14943 (save-excursion
14944 (while (org-goto-sibling 'previous)
14945 (org-flag-heading nil))))
14947 (defun org-show-hidden-entry ()
14948 "Show an entry where even the heading is hidden."
14949 (save-excursion
14950 (org-show-entry)))
14952 (defun org-flag-heading (flag &optional entry)
14953 "Flag the current heading. FLAG non-nil means make invisible.
14954 When ENTRY is non-nil, show the entire entry."
14955 (save-excursion
14956 (org-back-to-heading t)
14957 ;; Check if we should show the entire entry
14958 (if entry
14959 (progn
14960 (org-show-entry)
14961 (save-excursion
14962 (and (outline-next-heading)
14963 (org-flag-heading nil))))
14964 (outline-flag-region (max (point-min) (1- (point)))
14965 (save-excursion (outline-end-of-heading) (point))
14966 flag))))
14968 (defun org-forward-same-level (arg)
14969 "Move forward to the ARG'th subheading at same level as this one.
14970 Stop at the first and last subheadings of a superior heading.
14971 This is like outline-forward-same-level, but invisible headings are ok."
14972 (interactive "p")
14973 (org-back-to-heading t)
14974 (while (> arg 0)
14975 (let ((point-to-move-to (save-excursion
14976 (org-get-next-sibling))))
14977 (if point-to-move-to
14978 (progn
14979 (goto-char point-to-move-to)
14980 (setq arg (1- arg)))
14981 (progn
14982 (setq arg 0)
14983 (error "No following same-level heading"))))))
14985 (defun org-get-next-sibling ()
14986 "Move to next heading of the same level, and return point.
14987 If there is no such heading, return nil.
14988 This is like outline-next-sibling, but invisible headings are ok."
14989 (let ((level (funcall outline-level)))
14990 (outline-next-heading)
14991 (while (and (not (eobp)) (> (funcall outline-level) level))
14992 (outline-next-heading))
14993 (if (or (eobp) (< (funcall outline-level) level))
14995 (point))))
14997 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14998 ;; This is an exact copy of the original function, but it uses
14999 ;; `org-back-to-heading', to make it work also in invisible
15000 ;; trees. And is uses an invisible-OK argument.
15001 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15002 (org-back-to-heading invisible-OK)
15003 (let ((first t)
15004 (level (funcall outline-level)))
15005 (while (and (not (eobp))
15006 (or first (> (funcall outline-level) level)))
15007 (setq first nil)
15008 (outline-next-heading))
15009 (unless to-heading
15010 (if (memq (preceding-char) '(?\n ?\^M))
15011 (progn
15012 ;; Go to end of line before heading
15013 (forward-char -1)
15014 (if (memq (preceding-char) '(?\n ?\^M))
15015 ;; leave blank line before heading
15016 (forward-char -1))))))
15017 (point))
15019 (defun org-show-subtree ()
15020 "Show everything after this heading at deeper levels."
15021 (outline-flag-region
15022 (point)
15023 (save-excursion
15024 (outline-end-of-subtree) (outline-next-heading) (point))
15025 nil))
15027 (defun org-show-entry ()
15028 "Show the body directly following this heading.
15029 Show the heading too, if it is currently invisible."
15030 (interactive)
15031 (save-excursion
15032 (condition-case nil
15033 (progn
15034 (org-back-to-heading t)
15035 (outline-flag-region
15036 (max (point-min) (1- (point)))
15037 (save-excursion
15038 (re-search-forward
15039 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
15040 (or (match-beginning 1) (point-max)))
15041 nil))
15042 (error nil))))
15044 (defun org-make-options-regexp (kwds)
15045 "Make a regular expression for keyword lines."
15046 (concat
15048 "#?[ \t]*\\+\\("
15049 (mapconcat 'regexp-quote kwds "\\|")
15050 "\\):[ \t]*"
15051 "\\(.+\\)"))
15053 ;; Make isearch reveal the necessary context
15054 (defun org-isearch-end ()
15055 "Reveal context after isearch exits."
15056 (when isearch-success ; only if search was successful
15057 (if (featurep 'xemacs)
15058 ;; Under XEmacs, the hook is run in the correct place,
15059 ;; we directly show the context.
15060 (org-show-context 'isearch)
15061 ;; In Emacs the hook runs *before* restoring the overlays.
15062 ;; So we have to use a one-time post-command-hook to do this.
15063 ;; (Emacs 22 has a special variable, see function `org-mode')
15064 (unless (and (boundp 'isearch-mode-end-hook-quit)
15065 isearch-mode-end-hook-quit)
15066 ;; Only when the isearch was not quitted.
15067 (org-add-hook 'post-command-hook 'org-isearch-post-command
15068 'append 'local)))))
15070 (defun org-isearch-post-command ()
15071 "Remove self from hook, and show context."
15072 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15073 (org-show-context 'isearch))
15076 ;;;; Integration with and fixes for other packages
15078 ;;; Imenu support
15080 (defvar org-imenu-markers nil
15081 "All markers currently used by Imenu.")
15082 (make-variable-buffer-local 'org-imenu-markers)
15084 (defun org-imenu-new-marker (&optional pos)
15085 "Return a new marker for use by Imenu, and remember the marker."
15086 (let ((m (make-marker)))
15087 (move-marker m (or pos (point)))
15088 (push m org-imenu-markers)
15091 (defun org-imenu-get-tree ()
15092 "Produce the index for Imenu."
15093 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15094 (setq org-imenu-markers nil)
15095 (let* ((n org-imenu-depth)
15096 (re (concat "^" outline-regexp))
15097 (subs (make-vector (1+ n) nil))
15098 (last-level 0)
15099 m level head)
15100 (save-excursion
15101 (save-restriction
15102 (widen)
15103 (goto-char (point-max))
15104 (while (re-search-backward re nil t)
15105 (setq level (org-reduced-level (funcall outline-level)))
15106 (when (<= level n)
15107 (looking-at org-complex-heading-regexp)
15108 (setq head (org-link-display-format
15109 (org-match-string-no-properties 4))
15110 m (org-imenu-new-marker))
15111 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15112 (if (>= level last-level)
15113 (push (cons head m) (aref subs level))
15114 (push (cons head (aref subs (1+ level))) (aref subs level))
15115 (loop for i from (1+ level) to n do (aset subs i nil)))
15116 (setq last-level level)))))
15117 (aref subs 1)))
15119 (eval-after-load "imenu"
15120 '(progn
15121 (add-hook 'imenu-after-jump-hook
15122 (lambda ()
15123 (if (eq major-mode 'org-mode)
15124 (org-show-context 'org-goto))))))
15126 (defun org-link-display-format (link)
15127 "Replace a link with either the description, or the link target
15128 if no description is present"
15129 (save-match-data
15130 (if (string-match org-bracket-link-analytic-regexp link)
15131 (replace-match (or (match-string 5 link)
15132 (concat (match-string 1 link)
15133 (match-string 3 link)))
15134 nil nil link)
15135 link)))
15137 ;; Speedbar support
15139 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15140 "Overlay marking the agenda restriction line in speedbar.")
15141 (org-overlay-put org-speedbar-restriction-lock-overlay
15142 'face 'org-agenda-restriction-lock)
15143 (org-overlay-put org-speedbar-restriction-lock-overlay
15144 'help-echo "Agendas are currently limited to this item.")
15145 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15147 (defun org-speedbar-set-agenda-restriction ()
15148 "Restrict future agenda commands to the location at point in speedbar.
15149 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15150 (interactive)
15151 (require 'org-agenda)
15152 (let (p m tp np dir txt)
15153 (cond
15154 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15155 'org-imenu t))
15156 (setq m (get-text-property p 'org-imenu-marker))
15157 (save-excursion
15158 (save-restriction
15159 (set-buffer (marker-buffer m))
15160 (goto-char m)
15161 (org-agenda-set-restriction-lock 'subtree))))
15162 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15163 'speedbar-function 'speedbar-find-file))
15164 (setq tp (previous-single-property-change
15165 (1+ p) 'speedbar-function)
15166 np (next-single-property-change
15167 tp 'speedbar-function)
15168 dir (speedbar-line-directory)
15169 txt (buffer-substring-no-properties (or tp (point-min))
15170 (or np (point-max))))
15171 (save-excursion
15172 (save-restriction
15173 (set-buffer (find-file-noselect
15174 (let ((default-directory dir))
15175 (expand-file-name txt))))
15176 (unless (org-mode-p)
15177 (error "Cannot restrict to non-Org-mode file"))
15178 (org-agenda-set-restriction-lock 'file))))
15179 (t (error "Don't know how to restrict Org-mode's agenda")))
15180 (org-move-overlay org-speedbar-restriction-lock-overlay
15181 (point-at-bol) (point-at-eol))
15182 (setq current-prefix-arg nil)
15183 (org-agenda-maybe-redo)))
15185 (eval-after-load "speedbar"
15186 '(progn
15187 (speedbar-add-supported-extension ".org")
15188 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15189 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15190 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15191 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15192 (add-hook 'speedbar-visiting-tag-hook
15193 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15196 ;;; Fixes and Hacks for problems with other packages
15198 ;; Make flyspell not check words in links, to not mess up our keymap
15199 (defun org-mode-flyspell-verify ()
15200 "Don't let flyspell put overlays at active buttons."
15201 (not (get-text-property (point) 'keymap)))
15203 ;; Make `bookmark-jump' show the jump location if it was hidden.
15204 (eval-after-load "bookmark"
15205 '(if (boundp 'bookmark-after-jump-hook)
15206 ;; We can use the hook
15207 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15208 ;; Hook not available, use advice
15209 (defadvice bookmark-jump (after org-make-visible activate)
15210 "Make the position visible."
15211 (org-bookmark-jump-unhide))))
15213 ;; Make sure saveplace show the location if it was hidden
15214 (eval-after-load "saveplace"
15215 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15216 "Make the position visible."
15217 (org-bookmark-jump-unhide)))
15219 (defun org-bookmark-jump-unhide ()
15220 "Unhide the current position, to show the bookmark location."
15221 (and (org-mode-p)
15222 (or (org-invisible-p)
15223 (save-excursion (goto-char (max (point-min) (1- (point))))
15224 (org-invisible-p)))
15225 (org-show-context 'bookmark-jump)))
15227 ;; Make session.el ignore our circular variable
15228 (eval-after-load "session"
15229 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15231 ;;;; Experimental code
15233 (defun org-closed-in-range ()
15234 "Sparse tree of items closed in a certain time range.
15235 Still experimental, may disappear in the future."
15236 (interactive)
15237 ;; Get the time interval from the user.
15238 (let* ((time1 (time-to-seconds
15239 (org-read-date nil 'to-time nil "Starting date: ")))
15240 (time2 (time-to-seconds
15241 (org-read-date nil 'to-time nil "End date:")))
15242 ;; callback function
15243 (callback (lambda ()
15244 (let ((time
15245 (time-to-seconds
15246 (apply 'encode-time
15247 (org-parse-time-string
15248 (match-string 1))))))
15249 ;; check if time in interval
15250 (and (>= time time1) (<= time time2))))))
15251 ;; make tree, check each match with the callback
15252 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15255 ;;;; Finish up
15257 (provide 'org)
15259 (run-hooks 'org-load-hook)
15261 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15263 ;;; org.el ends here