Fix docstring
[org-mode.git] / lisp / org.el
blob892dd42c576af63bf1834e0a8b2dc3ad487d9b66
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.26trans
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.26trans"
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 " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
171 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
172 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
173 (const :tag " mew Links to Mew folders/messages" org-mew)
174 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
175 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
176 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
177 (const :tag " vm: Links to VM folders/messages" org-vm)
178 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
179 (const :tag " w3m: Special cut/paste from w3m to Org." org-w3m)
180 (const :tag " mouse: Additional mouse support" org-mouse)
182 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
183 (const :tag "C annotation-helper: Call Remember directly from Browser (OBSOLETE, use org-protocol)" org-annotation-helper)
184 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
185 (const :tag "C browser-url: Store link, directly from Browser (OBSOLETE, use org-protocol)" org-browser-url)
186 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
187 (const :tag "C collector: Collect properties into tables" org-collector)
188 (const :tag "C depend: TODO dependencies for Org-mode (PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
189 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
190 (const :tag "C eval: Include command output as text" org-eval)
191 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
192 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
193 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
194 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
195 (const :tag "C interactive-query: Interactive modification of tags query (PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
196 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
197 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
198 (const :tag "C mtags: Support for muse-like tags" org-mtags)
199 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
200 (const :tag "C R: Computation using the R language" org-R)
201 (const :tag "C registry: A registry for Org links" org-registry)
202 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
203 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
204 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
205 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
206 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
208 (defcustom org-support-shift-select nil
209 "Non-nil means, make shift-cursor commands select text when possible.
211 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
212 selecting a region, or enlarge thusly regions started in this way.
213 In Org-mode, in special contexts, these same keys are used for other
214 purposes, important enough to compete with shift selection. Org tries
215 to balance these needs by supporting `shift-select-mode' outside these
216 special contexts, under control of this variable.
218 The default of this variable is nil, to avoid confusing behavior. Shifted
219 cursor keys will then execute Org commands in the following contexts:
220 - on a headline, changing TODO state (left/right) and priority (up/down)
221 - on a time stamp, changing the time
222 - in a plain list item, changing the bullet type
223 - in a property definition line, switching between allowed values
224 - in the BEGIN line of a clock table (changing the time block).
225 Outside these contexts, the commands will throw an error.
227 When this variable is t and the cursor is not in a special context,
228 Org-mode will support shift-selection for making and enlarging regions.
229 To make this more effective, the bullet cycling will no longer happen
230 anywhere in an item line, but only if the cursor is exactly on the bullet.
232 If you set this variable to the symbol `always', then the keys
233 will not be special in headlines, property lines, and item lines, to make
234 shift selection work there as well. If this is what you want, you can
235 use the following alternative commands: `C-c C-t' and `C-c ,' to
236 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
237 TODO sets, `C-c -' to cycle item bullet types, and properties can be
238 edited by hand or in column view.
240 However, when the cursor is on a timestamp, shift-cursor commands
241 will still edit the time stamp - this is just too good to give up.
243 XEmacs user should have this variable set to nil, because shift-select-mode
244 is Emacs 23 only."
245 :group 'org
246 :type '(choice
247 (const :tag "Never" nil)
248 (const :tag "When outside special context" t)
249 (const :tag "Everywhere except timestamps" always)))
251 (defgroup org-startup nil
252 "Options concerning startup of Org-mode."
253 :tag "Org Startup"
254 :group 'org)
256 (defcustom org-startup-folded t
257 "Non-nil means, entering Org-mode will switch to OVERVIEW.
258 This can also be configured on a per-file basis by adding one of
259 the following lines anywhere in the buffer:
261 #+STARTUP: fold
262 #+STARTUP: nofold
263 #+STARTUP: content"
264 :group 'org-startup
265 :type '(choice
266 (const :tag "nofold: show all" nil)
267 (const :tag "fold: overview" t)
268 (const :tag "content: all headlines" content)))
270 (defcustom org-startup-truncated t
271 "Non-nil means, entering Org-mode will set `truncate-lines'.
272 This is useful since some lines containing links can be very long and
273 uninteresting. Also tables look terrible when wrapped."
274 :group 'org-startup
275 :type 'boolean)
277 (defcustom org-startup-align-all-tables nil
278 "Non-nil means, align all tables when visiting a file.
279 This is useful when the column width in tables is forced with <N> cookies
280 in table fields. Such tables will look correct only after the first re-align.
281 This can also be configured on a per-file basis by adding one of
282 the following lines anywhere in the buffer:
283 #+STARTUP: align
284 #+STARTUP: noalign"
285 :group 'org-startup
286 :type 'boolean)
288 (defcustom org-insert-mode-line-in-empty-file nil
289 "Non-nil means insert the first line setting Org-mode in empty files.
290 When the function `org-mode' is called interactively in an empty file, this
291 normally means that the file name does not automatically trigger Org-mode.
292 To ensure that the file will always be in Org-mode in the future, a
293 line enforcing Org-mode will be inserted into the buffer, if this option
294 has been set."
295 :group 'org-startup
296 :type 'boolean)
298 (defcustom org-replace-disputed-keys nil
299 "Non-nil means use alternative key bindings for some keys.
300 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
301 These keys are also used by other packages like shift-selection-mode'
302 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
303 If you want to use Org-mode together with one of these other modes,
304 or more generally if you would like to move some Org-mode commands to
305 other keys, set this variable and configure the keys with the variable
306 `org-disputed-keys'.
308 This option is only relevant at load-time of Org-mode, and must be set
309 *before* org.el is loaded. Changing it requires a restart of Emacs to
310 become effective."
311 :group 'org-startup
312 :type 'boolean)
314 (defcustom org-use-extra-keys nil
315 "Non-nil means use extra key sequence definitions for certain
316 commands. This happens automatically if you run XEmacs or if
317 window-system is nil. This variable lets you do the same
318 manually. You must set it before loading org.
320 Example: on Carbon Emacs 22 running graphically, with an external
321 keyboard on a Powerbook, the default way of setting M-left might
322 not work for either Alt or ESC. Setting this variable will make
323 it work for ESC."
324 :group 'org-startup
325 :type 'boolean)
327 (if (fboundp 'defvaralias)
328 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
330 (defcustom org-disputed-keys
331 '(([(shift up)] . [(meta p)])
332 ([(shift down)] . [(meta n)])
333 ([(shift left)] . [(meta -)])
334 ([(shift right)] . [(meta +)])
335 ([(control shift right)] . [(meta shift +)])
336 ([(control shift left)] . [(meta shift -)]))
337 "Keys for which Org-mode and other modes compete.
338 This is an alist, cars are the default keys, second element specifies
339 the alternative to use when `org-replace-disputed-keys' is t.
341 Keys can be specified in any syntax supported by `define-key'.
342 The value of this option takes effect only at Org-mode's startup,
343 therefore you'll have to restart Emacs to apply it after changing."
344 :group 'org-startup
345 :type 'alist)
347 (defun org-key (key)
348 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
349 Or return the original if not disputed."
350 (if org-replace-disputed-keys
351 (let* ((nkey (key-description key))
352 (x (org-find-if (lambda (x)
353 (equal (key-description (car x)) nkey))
354 org-disputed-keys)))
355 (if x (cdr x) key))
356 key))
358 (defun org-find-if (predicate seq)
359 (catch 'exit
360 (while seq
361 (if (funcall predicate (car seq))
362 (throw 'exit (car seq))
363 (pop seq)))))
365 (defun org-defkey (keymap key def)
366 "Define a key, possibly translated, as returned by `org-key'."
367 (define-key keymap (org-key key) def))
369 (defcustom org-ellipsis nil
370 "The ellipsis to use in the Org-mode outline.
371 When nil, just use the standard three dots. When a string, use that instead,
372 When a face, use the standard 3 dots, but with the specified face.
373 The change affects only Org-mode (which will then use its own display table).
374 Changing this requires executing `M-x org-mode' in a buffer to become
375 effective."
376 :group 'org-startup
377 :type '(choice (const :tag "Default" nil)
378 (face :tag "Face" :value org-warning)
379 (string :tag "String" :value "...#")))
381 (defvar org-display-table nil
382 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
384 (defgroup org-keywords nil
385 "Keywords in Org-mode."
386 :tag "Org Keywords"
387 :group 'org)
389 (defcustom org-deadline-string "DEADLINE:"
390 "String to mark deadline entries.
391 A deadline is this string, followed by a time stamp. Should be a word,
392 terminated by a colon. You can insert a schedule keyword and
393 a timestamp with \\[org-deadline].
394 Changes become only effective after restarting Emacs."
395 :group 'org-keywords
396 :type 'string)
398 (defcustom org-scheduled-string "SCHEDULED:"
399 "String to mark scheduled TODO entries.
400 A schedule is this string, followed by a time stamp. Should be a word,
401 terminated by a colon. You can insert a schedule keyword and
402 a timestamp with \\[org-schedule].
403 Changes become only effective after restarting Emacs."
404 :group 'org-keywords
405 :type 'string)
407 (defcustom org-closed-string "CLOSED:"
408 "String used as the prefix for timestamps logging closing a TODO entry."
409 :group 'org-keywords
410 :type 'string)
412 (defcustom org-clock-string "CLOCK:"
413 "String used as prefix for timestamps clocking work hours on an item."
414 :group 'org-keywords
415 :type 'string)
417 (defcustom org-comment-string "COMMENT"
418 "Entries starting with this keyword will never be exported.
419 An entry can be toggled between COMMENT and normal with
420 \\[org-toggle-comment].
421 Changes become only effective after restarting Emacs."
422 :group 'org-keywords
423 :type 'string)
425 (defcustom org-quote-string "QUOTE"
426 "Entries starting with this keyword will be exported in fixed-width font.
427 Quoting applies only to the text in the entry following the headline, and does
428 not extend beyond the next headline, even if that is lower level.
429 An entry can be toggled between QUOTE and normal with
430 \\[org-toggle-fixed-width-section]."
431 :group 'org-keywords
432 :type 'string)
434 (defconst org-repeat-re
435 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
436 "Regular expression for specifying repeated events.
437 After a match, group 1 contains the repeat expression.")
439 (defgroup org-structure nil
440 "Options concerning the general structure of Org-mode files."
441 :tag "Org Structure"
442 :group 'org)
444 (defgroup org-reveal-location nil
445 "Options about how to make context of a location visible."
446 :tag "Org Reveal Location"
447 :group 'org-structure)
449 (defconst org-context-choice
450 '(choice
451 (const :tag "Always" t)
452 (const :tag "Never" nil)
453 (repeat :greedy t :tag "Individual contexts"
454 (cons
455 (choice :tag "Context"
456 (const agenda)
457 (const org-goto)
458 (const occur-tree)
459 (const tags-tree)
460 (const link-search)
461 (const mark-goto)
462 (const bookmark-jump)
463 (const isearch)
464 (const default))
465 (boolean))))
466 "Contexts for the reveal options.")
468 (defcustom org-show-hierarchy-above '((default . t))
469 "Non-nil means, show full hierarchy when revealing a location.
470 Org-mode often shows locations in an org-mode file which might have
471 been invisible before. When this is set, the hierarchy of headings
472 above the exposed location is shown.
473 Turning this off for example for sparse trees makes them very compact.
474 Instead of t, this can also be an alist specifying this option for different
475 contexts. Valid contexts are
476 agenda when exposing an entry from the agenda
477 org-goto when using the command `org-goto' on key C-c C-j
478 occur-tree when using the command `org-occur' on key C-c /
479 tags-tree when constructing a sparse tree based on tags matches
480 link-search when exposing search matches associated with a link
481 mark-goto when exposing the jump goal of a mark
482 bookmark-jump when exposing a bookmark location
483 isearch when exiting from an incremental search
484 default default for all contexts not set explicitly"
485 :group 'org-reveal-location
486 :type org-context-choice)
488 (defcustom org-show-following-heading '((default . nil))
489 "Non-nil means, show following heading when revealing a location.
490 Org-mode often shows locations in an org-mode file which might have
491 been invisible before. When this is set, the heading following the
492 match is shown.
493 Turning this off for example for sparse trees makes them very compact,
494 but makes it harder to edit the location of the match. In such a case,
495 use the command \\[org-reveal] to show more context.
496 Instead of t, this can also be an alist specifying this option for different
497 contexts. See `org-show-hierarchy-above' for valid contexts."
498 :group 'org-reveal-location
499 :type org-context-choice)
501 (defcustom org-show-siblings '((default . nil) (isearch t))
502 "Non-nil means, show all sibling heading when revealing a location.
503 Org-mode often shows locations in an org-mode file which might have
504 been invisible before. When this is set, the sibling of the current entry
505 heading are all made visible. If `org-show-hierarchy-above' is t,
506 the same happens on each level of the hierarchy above the current entry.
508 By default this is on for the isearch context, off for all other contexts.
509 Turning this off for example for sparse trees makes them very compact,
510 but makes it harder to edit the location of the match. In such a case,
511 use the command \\[org-reveal] to show more context.
512 Instead of t, this can also be an alist specifying this option for different
513 contexts. See `org-show-hierarchy-above' for valid contexts."
514 :group 'org-reveal-location
515 :type org-context-choice)
517 (defcustom org-show-entry-below '((default . nil))
518 "Non-nil means, show the entry below a headline when revealing a location.
519 Org-mode often shows locations in an org-mode file which might have
520 been invisible before. When this is set, the text below the headline that is
521 exposed is also shown.
523 By default this is off for all contexts.
524 Instead of t, this can also be an alist specifying this option for different
525 contexts. See `org-show-hierarchy-above' for valid contexts."
526 :group 'org-reveal-location
527 :type org-context-choice)
529 (defcustom org-indirect-buffer-display 'other-window
530 "How should indirect tree buffers be displayed?
531 This applies to indirect buffers created with the commands
532 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
533 Valid values are:
534 current-window Display in the current window
535 other-window Just display in another window.
536 dedicated-frame Create one new frame, and re-use it each time.
537 new-frame Make a new frame each time. Note that in this case
538 previously-made indirect buffers are kept, and you need to
539 kill these buffers yourself."
540 :group 'org-structure
541 :group 'org-agenda-windows
542 :type '(choice
543 (const :tag "In current window" current-window)
544 (const :tag "In current frame, other window" other-window)
545 (const :tag "Each time a new frame" new-frame)
546 (const :tag "One dedicated frame" dedicated-frame)))
548 (defgroup org-cycle nil
549 "Options concerning visibility cycling in Org-mode."
550 :tag "Org Cycle"
551 :group 'org-structure)
553 (defcustom org-cycle-max-level nil
554 "Maximum level which should still be subject to visibility cycling.
555 Levels higher than this will, for cycling, be treated as text, not a headline.
556 When `org-odd-levels-only' is set, a value of N in this variable actually
557 means 2N-1 stars as the limiting headline.
558 When nil, cycle all levels.
559 Note that the limiting level of cycling is also influenced by
560 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
561 `org-inlinetask-min-level' is, cycling will be limited to levels one less
562 than its value."
563 :group 'org-cycle
564 :type '(choice
565 (const :tag "No limit" nil)
566 (integer :tag "Maximum level")))
568 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
569 "Names of drawers. Drawers are not opened by cycling on the headline above.
570 Drawers only open with a TAB on the drawer line itself. A drawer looks like
571 this:
572 :DRAWERNAME:
573 .....
574 :END:
575 The drawer \"PROPERTIES\" is special for capturing properties through
576 the property API.
578 Drawers can be defined on the per-file basis with a line like:
580 #+DRAWERS: HIDDEN STATE PROPERTIES"
581 :group 'org-structure
582 :group 'org-cycle
583 :type '(repeat (string :tag "Drawer Name")))
585 (defcustom org-cycle-global-at-bob nil
586 "Cycle globally if cursor is at beginning of buffer and not at a headline.
587 This makes it possible to do global cycling without having to use S-TAB or
588 C-u TAB. For this special case to work, the first line of the buffer
589 must not be a headline - it may be empty or some other text. When used in
590 this way, `org-cycle-hook' is disables temporarily, to make sure the
591 cursor stays at the beginning of the buffer.
592 When this option is nil, don't do anything special at the beginning
593 of the buffer."
594 :group 'org-cycle
595 :type 'boolean)
597 (defcustom org-cycle-emulate-tab t
598 "Where should `org-cycle' emulate TAB.
599 nil Never
600 white Only in completely white lines
601 whitestart Only at the beginning of lines, before the first non-white char
602 t Everywhere except in headlines
603 exc-hl-bol Everywhere except at the start of a headline
604 If TAB is used in a place where it does not emulate TAB, the current subtree
605 visibility is cycled."
606 :group 'org-cycle
607 :type '(choice (const :tag "Never" nil)
608 (const :tag "Only in completely white lines" white)
609 (const :tag "Before first char in a line" whitestart)
610 (const :tag "Everywhere except in headlines" t)
611 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
614 (defcustom org-cycle-separator-lines 2
615 "Number of empty lines needed to keep an empty line between collapsed trees.
616 If you leave an empty line between the end of a subtree and the following
617 headline, this empty line is hidden when the subtree is folded.
618 Org-mode will leave (exactly) one empty line visible if the number of
619 empty lines is equal or larger to the number given in this variable.
620 So the default 2 means, at least 2 empty lines after the end of a subtree
621 are needed to produce free space between a collapsed subtree and the
622 following headline.
624 Special case: when 0, never leave empty lines in collapsed view."
625 :group 'org-cycle
626 :type 'integer)
627 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
629 (defcustom org-pre-cycle-hook nil
630 "Hook that is run before visibility cycling is happening.
631 The function(s) in this hook must accept a single argument which indicates
632 the new state that will be set right after running this hook. The
633 argument is a symbol. Before a global state change, it can have the values
634 `overview', `content', or `all'. Before a local state change, it can have
635 the values `folded', `children', or `subtree'."
636 :group 'org-cycle
637 :type 'hook)
639 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
640 org-cycle-hide-drawers
641 org-cycle-show-empty-lines
642 org-optimize-window-after-visibility-change)
643 "Hook that is run after `org-cycle' has changed the buffer visibility.
644 The function(s) in this hook must accept a single argument which indicates
645 the new state that was set by the most recent `org-cycle' command. The
646 argument is a symbol. After a global state change, it can have the values
647 `overview', `content', or `all'. After a local state change, it can have
648 the values `folded', `children', or `subtree'."
649 :group 'org-cycle
650 :type 'hook)
652 (defgroup org-edit-structure nil
653 "Options concerning structure editing in Org-mode."
654 :tag "Org Edit Structure"
655 :group 'org-structure)
657 (defcustom org-odd-levels-only nil
658 "Non-nil means, skip even levels and only use odd levels for the outline.
659 This has the effect that two stars are being added/taken away in
660 promotion/demotion commands. It also influences how levels are
661 handled by the exporters.
662 Changing it requires restart of `font-lock-mode' to become effective
663 for fontification also in regions already fontified.
664 You may also set this on a per-file basis by adding one of the following
665 lines to the buffer:
667 #+STARTUP: odd
668 #+STARTUP: oddeven"
669 :group 'org-edit-structure
670 :group 'org-font-lock
671 :type 'boolean)
673 (defcustom org-adapt-indentation t
674 "Non-nil means, adapt indentation when promoting and demoting.
675 When this is set and the *entire* text in an entry is indented, the
676 indentation is increased by one space in a demotion command, and
677 decreased by one in a promotion command. If any line in the entry
678 body starts at column 0, indentation is not changed at all."
679 :group 'org-edit-structure
680 :type 'boolean)
682 (defcustom org-special-ctrl-a/e nil
683 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
685 When t, `C-a' will bring back the cursor to the beginning of the
686 headline text, i.e. after the stars and after a possible TODO keyword.
687 In an item, this will be the position after the bullet.
688 When the cursor is already at that position, another `C-a' will bring
689 it to the beginning of the line.
691 `C-e' will jump to the end of the headline, ignoring the presence of tags
692 in the headline. A second `C-e' will then jump to the true end of the
693 line, after any tags.
695 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
696 and only a directly following, identical keypress will bring the cursor
697 to the special positions.
699 This may also be a cons cell where the behavior for `C-a' and `C-e' is
700 set separately."
701 :group 'org-edit-structure
702 :type '(choice
703 (const :tag "off" nil)
704 (const :tag "after stars/bullet and before tags first" t)
705 (const :tag "true line boundary first" reversed)
706 (cons :tag "Set C-a and C-e separately"
707 (choice :tag "Special C-a"
708 (const :tag "off" nil)
709 (const :tag "after stars/bullet first" t)
710 (const :tag "before stars/bullet first" reversed))
711 (choice :tag "Special C-e"
712 (const :tag "off" nil)
713 (const :tag "before tags first" t)
714 (const :tag "after tags first" reversed)))))
715 (if (fboundp 'defvaralias)
716 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
718 (defcustom org-special-ctrl-k nil
719 "Non-nil means `C-k' will behave specially in headlines.
720 When nil, `C-k' will call the default `kill-line' command.
721 When t, the following will happen while the cursor is in the headline:
723 - When the cursor is at the beginning of a headline, kill the entire
724 line and possible the folded subtree below the line.
725 - When in the middle of the headline text, kill the headline up to the tags.
726 - When after the headline text, kill the tags."
727 :group 'org-edit-structure
728 :type 'boolean)
730 (defcustom org-yank-folded-subtrees t
731 "Non-nil means, when yanking subtrees, fold them.
732 If the kill is a single subtree, or a sequence of subtrees, i.e. if
733 it starts with a heading and all other headings in it are either children
734 or siblings, then fold all the subtrees. However, do this only if no
735 text after the yank would be swallowed into a folded tree by this action."
736 :group 'org-edit-structure
737 :type 'boolean)
739 (defcustom org-yank-adjusted-subtrees nil
740 "Non-nil means, when yanking subtrees, adjust the level.
741 With this setting, `org-paste-subtree' is used to insert the subtree, see
742 this function for details."
743 :group 'org-edit-structure
744 :type 'boolean)
746 (defcustom org-M-RET-may-split-line '((default . t))
747 "Non-nil means, M-RET will split the line at the cursor position.
748 When nil, it will go to the end of the line before making a
749 new line.
750 You may also set this option in a different way for different
751 contexts. Valid contexts are:
753 headline when creating a new headline
754 item when creating a new item
755 table in a table field
756 default the value to be used for all contexts not explicitly
757 customized"
758 :group 'org-structure
759 :group 'org-table
760 :type '(choice
761 (const :tag "Always" t)
762 (const :tag "Never" nil)
763 (repeat :greedy t :tag "Individual contexts"
764 (cons
765 (choice :tag "Context"
766 (const headline)
767 (const item)
768 (const table)
769 (const default))
770 (boolean)))))
773 (defcustom org-insert-heading-respect-content nil
774 "Non-nil means, insert new headings after the current subtree.
775 When nil, the new heading is created directly after the current line.
776 The commands \\[org-insert-heading-respect-content] and
777 \\[org-insert-todo-heading-respect-content] turn this variable on
778 for the duration of the command."
779 :group 'org-structure
780 :type 'boolean)
782 (defcustom org-blank-before-new-entry '((heading . auto)
783 (plain-list-item . auto))
784 "Should `org-insert-heading' leave a blank line before new heading/item?
785 The value is an alist, with `heading' and `plain-list-item' as car,
786 and a boolean flag as cdr. For plain lists, if the variable
787 `org-empty-line-terminates-plain-lists' is set, the setting here
788 is ignored and no empty line is inserted, to keep the list in tact."
789 :group 'org-edit-structure
790 :type '(list
791 (cons (const heading)
792 (choice (const :tag "Never" nil)
793 (const :tag "Always" t)
794 (const :tag "Auto" auto)))
795 (cons (const plain-list-item)
796 (choice (const :tag "Never" nil)
797 (const :tag "Always" t)
798 (const :tag "Auto" auto)))))
800 (defcustom org-insert-heading-hook nil
801 "Hook being run after inserting a new heading."
802 :group 'org-edit-structure
803 :type 'hook)
805 (defcustom org-enable-fixed-width-editor t
806 "Non-nil means, lines starting with \":\" are treated as fixed-width.
807 This currently only means, they are never auto-wrapped.
808 When nil, such lines will be treated like ordinary lines.
809 See also the QUOTE keyword."
810 :group 'org-edit-structure
811 :type 'boolean)
813 (defcustom org-edit-src-region-extra nil
814 "Additional regexps to identify regions for editing with `org-edit-src-code'.
815 For examples see the function `org-edit-src-find-region-and-lang'.
816 The regular expression identifying the begin marker should end with a newline,
817 and the regexp marking the end line should start with a newline, to make sure
818 there are kept outside the narrowed region."
819 :group 'org-edit-structure
820 :type '(repeat
821 (list
822 (regexp :tag "begin regexp")
823 (regexp :tag "end regexp")
824 (choice :tag "language"
825 (string :tag "specify")
826 (integer :tag "from match group")
827 (const :tag "from `lang' element")
828 (const :tag "from `style' element")))))
830 (defcustom org-coderef-label-format "(ref:%s)"
831 "The default coderef format.
832 This format string will be used to search for coderef labels in literal
833 examples (EXAMPLE and SRC blocks). The format can be overwritten
834 an individual literal example with the -f option, like
836 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
838 #+END_SRC
840 If you want to use this for HTML export, make sure that the format does
841 not introduce special font-locking, and avoid the HTML special
842 characters `<', `>', and `&'. The reason for this restriction is that
843 the labels are searched for only after htmlize has done its job."
844 :group 'org-edit-structure ; FIXME this is not in the right group
845 :type 'string)
847 (defcustom org-edit-fixed-width-region-mode 'artist-mode
848 "The mode that should be used to edit fixed-width regions.
849 These are the regions where each line starts with a colon."
850 :group 'org-edit-structure
851 :type '(choice
852 (const artist-mode)
853 (const picture-mode)
854 (const fundamental-mode)
855 (function :tag "Other (specify)")))
857 (defcustom org-goto-auto-isearch t
858 "Non-nil means, typing characters in org-goto starts incremental search."
859 :group 'org-edit-structure
860 :type 'boolean)
862 (defgroup org-sparse-trees nil
863 "Options concerning sparse trees in Org-mode."
864 :tag "Org Sparse Trees"
865 :group 'org-structure)
867 (defcustom org-highlight-sparse-tree-matches t
868 "Non-nil means, highlight all matches that define a sparse tree.
869 The highlights will automatically disappear the next time the buffer is
870 changed by an edit command."
871 :group 'org-sparse-trees
872 :type 'boolean)
874 (defcustom org-remove-highlights-with-change t
875 "Non-nil means, any change to the buffer will remove temporary highlights.
876 Such highlights are created by `org-occur' and `org-clock-display'.
877 When nil, `C-c C-c needs to be used to get rid of the highlights.
878 The highlights created by `org-preview-latex-fragment' always need
879 `C-c C-c' to be removed."
880 :group 'org-sparse-trees
881 :group 'org-time
882 :type 'boolean)
885 (defcustom org-occur-hook '(org-first-headline-recenter)
886 "Hook that is run after `org-occur' has constructed a sparse tree.
887 This can be used to recenter the window to show as much of the structure
888 as possible."
889 :group 'org-sparse-trees
890 :type 'hook)
892 (defgroup org-imenu-and-speedbar nil
893 "Options concerning imenu and speedbar in Org-mode."
894 :tag "Org Imenu and Speedbar"
895 :group 'org-structure)
897 (defcustom org-imenu-depth 2
898 "The maximum level for Imenu access to Org-mode headlines.
899 This also applied for speedbar access."
900 :group 'org-imenu-and-speedbar
901 :type 'integer)
903 (defgroup org-table nil
904 "Options concerning tables in Org-mode."
905 :tag "Org Table"
906 :group 'org)
908 (defcustom org-enable-table-editor 'optimized
909 "Non-nil means, lines starting with \"|\" are handled by the table editor.
910 When nil, such lines will be treated like ordinary lines.
912 When equal to the symbol `optimized', the table editor will be optimized to
913 do the following:
914 - Automatic overwrite mode in front of whitespace in table fields.
915 This makes the structure of the table stay in tact as long as the edited
916 field does not exceed the column width.
917 - Minimize the number of realigns. Normally, the table is aligned each time
918 TAB or RET are pressed to move to another field. With optimization this
919 happens only if changes to a field might have changed the column width.
920 Optimization requires replacing the functions `self-insert-command',
921 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
922 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
923 very good at guessing when a re-align will be necessary, but you can always
924 force one with \\[org-ctrl-c-ctrl-c].
926 If you would like to use the optimized version in Org-mode, but the
927 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
929 This variable can be used to turn on and off the table editor during a session,
930 but in order to toggle optimization, a restart is required.
932 See also the variable `org-table-auto-blank-field'."
933 :group 'org-table
934 :type '(choice
935 (const :tag "off" nil)
936 (const :tag "on" t)
937 (const :tag "on, optimized" optimized)))
939 (defcustom org-self-insert-cluster-for-undo t
940 "Non-nil means cluster self-insert commands for undo when possible.
941 If this is set, then, like in the Emacs command loop, 20 consequtive
942 characters will be undone together.
943 This is configurable, because there is some impact on typing performance."
944 :group 'org-table
945 :type 'boolean)
947 (defcustom org-table-tab-recognizes-table.el t
948 "Non-nil means, TAB will automatically notice a table.el table.
949 When it sees such a table, it moves point into it and - if necessary -
950 calls `table-recognize-table'."
951 :group 'org-table-editing
952 :type 'boolean)
954 (defgroup org-link nil
955 "Options concerning links in Org-mode."
956 :tag "Org Link"
957 :group 'org)
959 (defvar org-link-abbrev-alist-local nil
960 "Buffer-local version of `org-link-abbrev-alist', which see.
961 The value of this is taken from the #+LINK lines.")
962 (make-variable-buffer-local 'org-link-abbrev-alist-local)
964 (defcustom org-link-abbrev-alist nil
965 "Alist of link abbreviations.
966 The car of each element is a string, to be replaced at the start of a link.
967 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
968 links in Org-mode buffers can have an optional tag after a double colon, e.g.
970 [[linkkey:tag][description]]
972 The 'linkkey' must be a word word, starting with a letter, followed
973 by letters, numbers, '-' or '_'.
975 If REPLACE is a string, the tag will simply be appended to create the link.
976 If the string contains \"%s\", the tag will be inserted there. Alternatively,
977 the placeholder \"%h\" will cause a url-encoded version of the tag to
978 be inserted at that point (see the function `url-hexify-string').
980 REPLACE may also be a function that will be called with the tag as the
981 only argument to create the link, which should be returned as a string.
983 See the manual for examples."
984 :group 'org-link
985 :type '(repeat
986 (cons
987 (string :tag "Protocol")
988 (choice
989 (string :tag "Format")
990 (function)))))
992 (defcustom org-descriptive-links t
993 "Non-nil means, hide link part and only show description of bracket links.
994 Bracket links are like [[link][description]]. This variable sets the initial
995 state in new org-mode buffers. The setting can then be toggled on a
996 per-buffer basis from the Org->Hyperlinks menu."
997 :group 'org-link
998 :type 'boolean)
1000 (defcustom org-link-file-path-type 'adaptive
1001 "How the path name in file links should be stored.
1002 Valid values are:
1004 relative Relative to the current directory, i.e. the directory of the file
1005 into which the link is being inserted.
1006 absolute Absolute path, if possible with ~ for home directory.
1007 noabbrev Absolute path, no abbreviation of home directory.
1008 adaptive Use relative path for files in the current directory and sub-
1009 directories of it. For other files, use an absolute path."
1010 :group 'org-link
1011 :type '(choice
1012 (const relative)
1013 (const absolute)
1014 (const noabbrev)
1015 (const adaptive)))
1017 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1018 "Types of links that should be activated in Org-mode files.
1019 This is a list of symbols, each leading to the activation of a certain link
1020 type. In principle, it does not hurt to turn on most link types - there may
1021 be a small gain when turning off unused link types. The types are:
1023 bracket The recommended [[link][description]] or [[link]] links with hiding.
1024 angular Links in angular brackets that may contain whitespace like
1025 <bbdb:Carsten Dominik>.
1026 plain Plain links in normal text, no whitespace, like http://google.com.
1027 radio Text that is matched by a radio target, see manual for details.
1028 tag Tag settings in a headline (link to tag search).
1029 date Time stamps (link to calendar).
1030 footnote Footnote labels.
1032 Changing this variable requires a restart of Emacs to become effective."
1033 :group 'org-link
1034 :type '(set :greedy t
1035 (const :tag "Double bracket links (new style)" bracket)
1036 (const :tag "Angular bracket links (old style)" angular)
1037 (const :tag "Plain text links" plain)
1038 (const :tag "Radio target matches" radio)
1039 (const :tag "Tags" tag)
1040 (const :tag "Timestamps" date)
1041 (const :tag "Footnotes" footnote)))
1043 (defcustom org-make-link-description-function nil
1044 "Function to use to generate link descriptions from links. If
1045 nil the link location will be used. This function must take two
1046 parameters; the first is the link and the second the description
1047 org-insert-link has generated, and should return the description
1048 to use."
1049 :group 'org-link
1050 :type 'function)
1052 (defgroup org-link-store nil
1053 "Options concerning storing links in Org-mode."
1054 :tag "Org Store Link"
1055 :group 'org-link)
1057 (defcustom org-email-link-description-format "Email %c: %.30s"
1058 "Format of the description part of a link to an email or usenet message.
1059 The following %-escapes will be replaced by corresponding information:
1061 %F full \"From\" field
1062 %f name, taken from \"From\" field, address if no name
1063 %T full \"To\" field
1064 %t first name in \"To\" field, address if no name
1065 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1066 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1067 %s subject
1068 %m message-id.
1070 You may use normal field width specification between the % and the letter.
1071 This is for example useful to limit the length of the subject.
1073 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1074 :group 'org-link-store
1075 :type 'string)
1077 (defcustom org-from-is-user-regexp
1078 (let (r1 r2)
1079 (when (and user-mail-address (not (string= user-mail-address "")))
1080 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1081 (when (and user-full-name (not (string= user-full-name "")))
1082 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1083 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1084 "Regexp matched against the \"From:\" header of an email or usenet message.
1085 It should match if the message is from the user him/herself."
1086 :group 'org-link-store
1087 :type 'regexp)
1089 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1090 "Non-nil means, storing a link to an Org file will use entry IDs.
1092 Note that before this variable is even considered, org-id must be loaded,
1093 to please customize `org-modules' and turn it on.
1095 The variable can have the following values:
1097 t Create an ID if needed to make a link to the current entry.
1099 create-if-interactive
1100 If `org-store-link' is called directly (interactively, as a user
1101 command), do create an ID to support the link. But when doing the
1102 job for remember, only use the ID if it already exists. The
1103 purpose of this setting is to avoid proliferation of unwanted
1104 IDs, just because you happen to be in an Org file when you
1105 call `org-remember' that automatically and preemptively
1106 creates a link. If you do want to get an ID link in a remember
1107 template to an entry not having an ID, create it first by
1108 explicitly creating a link to it, using `C-c C-l' first.
1110 use-existing
1111 Use existing ID, do not create one.
1113 nil Never use an ID to make a link, instead link using a text search for
1114 the headline text."
1115 :group 'org-link-store
1116 :type '(choice
1117 (const :tag "Create ID to make link" t)
1118 (const :tag "Create if storing link interactively"
1119 create-if-interactive)
1120 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1121 create-if-interactive-and-no-custom-id)
1122 (const :tag "Only use existing" use-existing)
1123 (const :tag "Do not use ID to create link" nil)))
1125 (defcustom org-context-in-file-links t
1126 "Non-nil means, file links from `org-store-link' contain context.
1127 A search string will be added to the file name with :: as separator and
1128 used to find the context when the link is activated by the command
1129 `org-open-at-point'.
1130 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1131 negates this setting for the duration of the command."
1132 :group 'org-link-store
1133 :type 'boolean)
1135 (defcustom org-keep-stored-link-after-insertion nil
1136 "Non-nil means, keep link in list for entire session.
1138 The command `org-store-link' adds a link pointing to the current
1139 location to an internal list. These links accumulate during a session.
1140 The command `org-insert-link' can be used to insert links into any
1141 Org-mode file (offering completion for all stored links). When this
1142 option is nil, every link which has been inserted once using \\[org-insert-link]
1143 will be removed from the list, to make completing the unused links
1144 more efficient."
1145 :group 'org-link-store
1146 :type 'boolean)
1148 (defgroup org-link-follow nil
1149 "Options concerning following links in Org-mode."
1150 :tag "Org Follow Link"
1151 :group 'org-link)
1153 (defcustom org-link-translation-function nil
1154 "Function to translate links with different syntax to Org syntax.
1155 This can be used to translate links created for example by the Planner
1156 or emacs-wiki packages to Org syntax.
1157 The function must accept two parameters, a TYPE containing the link
1158 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1159 which is everything after the link protocol. It should return a cons
1160 with possibly modified values of type and path.
1161 Org contains a function for this, so if you set this variable to
1162 `org-translate-link-from-planner', you should be able follow many
1163 links created by planner."
1164 :group 'org-link-follow
1165 :type 'function)
1167 (defcustom org-follow-link-hook nil
1168 "Hook that is run after a link has been followed."
1169 :group 'org-link-follow
1170 :type 'hook)
1172 (defcustom org-tab-follows-link nil
1173 "Non-nil means, on links TAB will follow the link.
1174 Needs to be set before org.el is loaded.
1175 This really should not be used, it does not make sense, and the
1176 implementation is bad."
1177 :group 'org-link-follow
1178 :type 'boolean)
1180 (defcustom org-return-follows-link nil
1181 "Non-nil means, on links RET will follow the link.
1182 Needs to be set before org.el is loaded."
1183 :group 'org-link-follow
1184 :type 'boolean)
1186 (defcustom org-mouse-1-follows-link
1187 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1188 "Non-nil means, mouse-1 on a link will follow the link.
1189 A longer mouse click will still set point. Does not work on XEmacs.
1190 Needs to be set before org.el is loaded."
1191 :group 'org-link-follow
1192 :type 'boolean)
1194 (defcustom org-mark-ring-length 4
1195 "Number of different positions to be recorded in the ring
1196 Changing this requires a restart of Emacs to work correctly."
1197 :group 'org-link-follow
1198 :type 'integer)
1200 (defcustom org-link-frame-setup
1201 '((vm . vm-visit-folder-other-frame)
1202 (gnus . gnus-other-frame)
1203 (file . find-file-other-window))
1204 "Setup the frame configuration for following links.
1205 When following a link with Emacs, it may often be useful to display
1206 this link in another window or frame. This variable can be used to
1207 set this up for the different types of links.
1208 For VM, use any of
1209 `vm-visit-folder'
1210 `vm-visit-folder-other-frame'
1211 For Gnus, use any of
1212 `gnus'
1213 `gnus-other-frame'
1214 `org-gnus-no-new-news'
1215 For FILE, use any of
1216 `find-file'
1217 `find-file-other-window'
1218 `find-file-other-frame'
1219 For the calendar, use the variable `calendar-setup'.
1220 For BBDB, it is currently only possible to display the matches in
1221 another window."
1222 :group 'org-link-follow
1223 :type '(list
1224 (cons (const vm)
1225 (choice
1226 (const vm-visit-folder)
1227 (const vm-visit-folder-other-window)
1228 (const vm-visit-folder-other-frame)))
1229 (cons (const gnus)
1230 (choice
1231 (const gnus)
1232 (const gnus-other-frame)
1233 (const org-gnus-no-new-news)))
1234 (cons (const file)
1235 (choice
1236 (const find-file)
1237 (const find-file-other-window)
1238 (const find-file-other-frame)))))
1240 (defcustom org-display-internal-link-with-indirect-buffer nil
1241 "Non-nil means, use indirect buffer to display infile links.
1242 Activating internal links (from one location in a file to another location
1243 in the same file) normally just jumps to the location. When the link is
1244 activated with a C-u prefix (or with mouse-3), the link is displayed in
1245 another window. When this option is set, the other window actually displays
1246 an indirect buffer clone of the current buffer, to avoid any visibility
1247 changes to the current buffer."
1248 :group 'org-link-follow
1249 :type 'boolean)
1251 (defcustom org-open-non-existing-files nil
1252 "Non-nil means, `org-open-file' will open non-existing files.
1253 When nil, an error will be generated."
1254 :group 'org-link-follow
1255 :type 'boolean)
1257 (defcustom org-open-directory-means-index-dot-org nil
1258 "Non-nil means, a link to a directory really means to index.org.
1259 When nil, following a directory link will run dired or open a finder/explorer
1260 window on that directory."
1261 :group 'org-link-follow
1262 :type 'boolean)
1264 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1265 "Function and arguments to call for following mailto links.
1266 This is a list with the first element being a lisp function, and the
1267 remaining elements being arguments to the function. In string arguments,
1268 %a will be replaced by the address, and %s will be replaced by the subject
1269 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1270 :group 'org-link-follow
1271 :type '(choice
1272 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1273 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1274 (const :tag "message-mail" (message-mail "%a" "%s"))
1275 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1277 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1278 "Non-nil means, ask for confirmation before executing shell links.
1279 Shell links can be dangerous: just think about a link
1281 [[shell:rm -rf ~/*][Google Search]]
1283 This link would show up in your Org-mode document as \"Google Search\",
1284 but really it would remove your entire home directory.
1285 Therefore we advise against setting this variable to nil.
1286 Just change it to `y-or-n-p' if you want to confirm with a
1287 single keystroke rather than having to type \"yes\"."
1288 :group 'org-link-follow
1289 :type '(choice
1290 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1291 (const :tag "with y-or-n (faster)" y-or-n-p)
1292 (const :tag "no confirmation (dangerous)" nil)))
1294 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1295 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1296 Elisp links can be dangerous: just think about a link
1298 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1300 This link would show up in your Org-mode document as \"Google Search\",
1301 but really it would remove your entire home directory.
1302 Therefore we advise against setting this variable to nil.
1303 Just change it to `y-or-n-p' if you want to confirm with a
1304 single keystroke rather than having to type \"yes\"."
1305 :group 'org-link-follow
1306 :type '(choice
1307 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1308 (const :tag "with y-or-n (faster)" y-or-n-p)
1309 (const :tag "no confirmation (dangerous)" nil)))
1311 (defconst org-file-apps-defaults-gnu
1312 '((remote . emacs)
1313 (system . mailcap)
1314 (t . mailcap))
1315 "Default file applications on a UNIX or GNU/Linux system.
1316 See `org-file-apps'.")
1318 (defconst org-file-apps-defaults-macosx
1319 '((remote . emacs)
1320 (t . "open %s")
1321 (system . "open %s")
1322 ("ps.gz" . "gv %s")
1323 ("eps.gz" . "gv %s")
1324 ("dvi" . "xdvi %s")
1325 ("fig" . "xfig %s"))
1326 "Default file applications on a MacOS X system.
1327 The system \"open\" is known as a default, but we use X11 applications
1328 for some files for which the OS does not have a good default.
1329 See `org-file-apps'.")
1331 (defconst org-file-apps-defaults-windowsnt
1332 (list
1333 '(remote . emacs)
1334 (cons t
1335 (list (if (featurep 'xemacs)
1336 'mswindows-shell-execute
1337 'w32-shell-execute)
1338 "open" 'file))
1339 (cons 'system
1340 (list (if (featurep 'xemacs)
1341 'mswindows-shell-execute
1342 'w32-shell-execute)
1343 "open" 'file)))
1344 "Default file applications on a Windows NT system.
1345 The system \"open\" is used for most files.
1346 See `org-file-apps'.")
1348 (defcustom org-file-apps
1350 (auto-mode . emacs)
1351 ("\\.x?html?\\'" . default)
1352 ("\\.pdf\\'" . default)
1354 "External applications for opening `file:path' items in a document.
1355 Org-mode uses system defaults for different file types, but
1356 you can use this variable to set the application for a given file
1357 extension. The entries in this list are cons cells where the car identifies
1358 files and the cdr the corresponding command. Possible values for the
1359 file identifier are
1360 \"regex\" Regular expression matched against the file name. For backward
1361 compatibility, this can also be a string with only alphanumeric
1362 characters, which is then interpreted as an extension.
1363 `directory' Matches a directory
1364 `remote' Matches a remote file, accessible through tramp or efs.
1365 Remote files most likely should be visited through Emacs
1366 because external applications cannot handle such paths.
1367 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1368 so all files Emacs knows how to handle. Using this with
1369 command `emacs' will open most files in Emacs. Beware that this
1370 will also open html files inside Emacs, unless you add
1371 (\"html\" . default) to the list as well.
1372 t Default for files not matched by any of the other options.
1373 `system' The system command to open files, like `open' on Windows
1374 and Mac OS X, and mailcap under GNU/Linux. This is the command
1375 that will be selected if you call `C-c C-o' with a double
1376 `C-u C-u' prefix.
1378 Possible values for the command are:
1379 `emacs' The file will be visited by the current Emacs process.
1380 `default' Use the default application for this file type, which is the
1381 association for t in the list, most likely in the system-specific
1382 part.
1383 This can be used to overrule an unwanted setting in the
1384 system-specific variable.
1385 `system' Use the system command for opening files, like \"open\".
1386 This command is specified by the entry whose car is `system'.
1387 Most likely, the system-specific version of this variable
1388 does define this command, but you can overrule/replace it
1389 here.
1390 string A command to be executed by a shell; %s will be replaced
1391 by the path to the file.
1392 sexp A Lisp form which will be evaluated. The file path will
1393 be available in the Lisp variable `file'.
1394 For more examples, see the system specific constants
1395 `org-file-apps-defaults-macosx'
1396 `org-file-apps-defaults-windowsnt'
1397 `org-file-apps-defaults-gnu'."
1398 :group 'org-link-follow
1399 :type '(repeat
1400 (cons (choice :value ""
1401 (string :tag "Extension")
1402 (const :tag "System command to open files" system)
1403 (const :tag "Default for unrecognized files" t)
1404 (const :tag "Remote file" remote)
1405 (const :tag "Links to a directory" directory)
1406 (const :tag "Any files that have Emacs modes"
1407 auto-mode))
1408 (choice :value ""
1409 (const :tag "Visit with Emacs" emacs)
1410 (const :tag "Use default" default)
1411 (const :tag "Use the system command" system)
1412 (string :tag "Command")
1413 (sexp :tag "Lisp form")))))
1415 (defgroup org-refile nil
1416 "Options concerning refiling entries in Org-mode."
1417 :tag "Org Refile"
1418 :group 'org)
1420 (defcustom org-directory "~/org"
1421 "Directory with org files.
1422 This is just a default location to look for Org files. There is no need
1423 at all to put your files into this directory. It is only used in the
1424 following situations:
1426 1. When a remember template specifies a target file that is not an
1427 absolute path. The path will then be interpreted relative to
1428 `org-directory'
1429 2. When a remember note is filed away in an interactive way (when exiting the
1430 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1431 with `org-directory' as the default path."
1432 :group 'org-refile
1433 :group 'org-remember
1434 :type 'directory)
1436 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1437 "Default target for storing notes.
1438 Used by the hooks for remember.el. This can be a string, or nil to mean
1439 the value of `remember-data-file'.
1440 You can set this on a per-template basis with the variable
1441 `org-remember-templates'."
1442 :group 'org-refile
1443 :group 'org-remember
1444 :type '(choice
1445 (const :tag "Default from remember-data-file" nil)
1446 file))
1448 (defcustom org-goto-interface 'outline
1449 "The default interface to be used for `org-goto'.
1450 Allowed values are:
1451 outline The interface shows an outline of the relevant file
1452 and the correct heading is found by moving through
1453 the outline or by searching with incremental search.
1454 outline-path-completion Headlines in the current buffer are offered via
1455 completion. This is the interface also used by
1456 the refile command."
1457 :group 'org-refile
1458 :type '(choice
1459 (const :tag "Outline" outline)
1460 (const :tag "Outline-path-completion" outline-path-completion)))
1462 (defcustom org-goto-max-level 5
1463 "Maximum level to be considered when running org-goto with refile interface."
1464 :group 'org-refile
1465 :type 'integer)
1467 (defcustom org-reverse-note-order nil
1468 "Non-nil means, store new notes at the beginning of a file or entry.
1469 When nil, new notes will be filed to the end of a file or entry.
1470 This can also be a list with cons cells of regular expressions that
1471 are matched against file names, and values."
1472 :group 'org-remember
1473 :group 'org-refile
1474 :type '(choice
1475 (const :tag "Reverse always" t)
1476 (const :tag "Reverse never" nil)
1477 (repeat :tag "By file name regexp"
1478 (cons regexp boolean))))
1480 (defcustom org-refile-targets nil
1481 "Targets for refiling entries with \\[org-refile].
1482 This is list of cons cells. Each cell contains:
1483 - a specification of the files to be considered, either a list of files,
1484 or a symbol whose function or variable value will be used to retrieve
1485 a file name or a list of file names. If you use `org-agenda-files' for
1486 that, all agenda files will be scanned for targets. Nil means, consider
1487 headings in the current buffer.
1488 - A specification of how to find candidate refile targets. This may be
1489 any of:
1490 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1491 This tag has to be present in all target headlines, inheritance will
1492 not be considered.
1493 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1494 todo keyword.
1495 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1496 headlines that are refiling targets.
1497 - a cons cell (:level . N). Any headline of level N is considered a target.
1498 Note that, when `org-odd-levels-only' is set, level corresponds to
1499 order in hierarchy, not to the number of stars.
1500 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1501 Note that, when `org-odd-levels-only' is set, level corresponds to
1502 order in hierarchy, not to the number of stars.
1504 You can set the variable `org-refile-target-verify-function' to a function
1505 to verify each headline found by the simple critery above.
1507 When this variable is nil, all top-level headlines in the current buffer
1508 are used, equivalent to the value `((nil . (:level . 1))'."
1509 :group 'org-refile
1510 :type '(repeat
1511 (cons
1512 (choice :value org-agenda-files
1513 (const :tag "All agenda files" org-agenda-files)
1514 (const :tag "Current buffer" nil)
1515 (function) (variable) (file))
1516 (choice :tag "Identify target headline by"
1517 (cons :tag "Specific tag" (const :value :tag) (string))
1518 (cons :tag "TODO keyword" (const :value :todo) (string))
1519 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1520 (cons :tag "Level number" (const :value :level) (integer))
1521 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1523 (defcustom org-refile-target-verify-function nil
1524 "Function to verify if the headline at point should be a refile target.
1525 The function will be called without arguments, with point at the
1526 beginning of the headline. It should return t and leave point
1527 where it is if the headline is a valid target for refiling.
1529 If the target should not be selected, the function must return nil.
1530 In addition to this, it may move point to a place from where the search
1531 should be continued. For example, the function may decide that the entire
1532 subtree of the current entry should be excluded and move point to the end
1533 of the subtree."
1534 :group 'org-refile
1535 :type 'function)
1537 (defcustom org-refile-use-outline-path nil
1538 "Non-nil means, provide refile targets as paths.
1539 So a level 3 headline will be available as level1/level2/level3.
1541 When the value is `file', also include the file name (without directory)
1542 into the path. In this case, you can also stop the completion after
1543 the file name, to get entries inserted as top level in the file.
1545 When `full-file-path', include the full file path."
1546 :group 'org-refile
1547 :type '(choice
1548 (const :tag "Not" nil)
1549 (const :tag "Yes" t)
1550 (const :tag "Start with file name" file)
1551 (const :tag "Start with full file path" full-file-path)))
1553 (defcustom org-outline-path-complete-in-steps t
1554 "Non-nil means, complete the outline path in hierarchical steps.
1555 When Org-mode uses the refile interface to select an outline path
1556 \(see variable `org-refile-use-outline-path'), the completion of
1557 the path can be done is a single go, or if can be done in steps down
1558 the headline hierarchy. Going in steps is probably the best if you
1559 do not use a special completion package like `ido' or `icicles'.
1560 However, when using these packages, going in one step can be very
1561 fast, while still showing the whole path to the entry."
1562 :group 'org-refile
1563 :type 'boolean)
1565 (defcustom org-refile-allow-creating-parent-nodes nil
1566 "Non-nil means, allow to create new nodes as refile targets.
1567 New nodes are then created by adding \"/new node name\" to the completion
1568 of an existing node. When the value of this variable is `confirm',
1569 new node creation must be confirmed by the user (recommended)
1570 When nil, the completion must match an existing entry.
1572 Note that, if the new heading is not seen by the criteria
1573 listed in `org-refile-targets', multiple instances of the same
1574 heading would be created by trying again to file under the new
1575 heading."
1576 :group 'org-refile
1577 :type '(choice
1578 (const :tag "Never" nil)
1579 (const :tag "Always" t)
1580 (const :tag "Prompt for confirmation" confirm)))
1582 (defgroup org-todo nil
1583 "Options concerning TODO items in Org-mode."
1584 :tag "Org TODO"
1585 :group 'org)
1587 (defgroup org-progress nil
1588 "Options concerning Progress logging in Org-mode."
1589 :tag "Org Progress"
1590 :group 'org-time)
1592 (defvar org-todo-interpretation-widgets
1594 (:tag "Sequence (cycling hits every state)" sequence)
1595 (:tag "Type (cycling directly to DONE)" type))
1596 "The available interpretation symbols for customizing
1597 `org-todo-keywords'.
1598 Interested libraries should add to this list.")
1600 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1601 "List of TODO entry keyword sequences and their interpretation.
1602 \\<org-mode-map>This is a list of sequences.
1604 Each sequence starts with a symbol, either `sequence' or `type',
1605 indicating if the keywords should be interpreted as a sequence of
1606 action steps, or as different types of TODO items. The first
1607 keywords are states requiring action - these states will select a headline
1608 for inclusion into the global TODO list Org-mode produces. If one of
1609 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1610 signify that no further action is necessary. If \"|\" is not found,
1611 the last keyword is treated as the only DONE state of the sequence.
1613 The command \\[org-todo] cycles an entry through these states, and one
1614 additional state where no keyword is present. For details about this
1615 cycling, see the manual.
1617 TODO keywords and interpretation can also be set on a per-file basis with
1618 the special #+SEQ_TODO and #+TYP_TODO lines.
1620 Each keyword can optionally specify a character for fast state selection
1621 \(in combination with the variable `org-use-fast-todo-selection')
1622 and specifiers for state change logging, using the same syntax
1623 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1624 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1625 indicates to record a time stamp each time this state is selected.
1627 Each keyword may also specify if a timestamp or a note should be
1628 recorded when entering or leaving the state, by adding additional
1629 characters in the parenthesis after the keyword. This looks like this:
1630 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1631 record only the time of the state change. With X and Y being either
1632 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1633 Y when leaving the state if and only if the *target* state does not
1634 define X. You may omit any of the fast-selection key or X or /Y,
1635 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1637 For backward compatibility, this variable may also be just a list
1638 of keywords - in this case the interpretation (sequence or type) will be
1639 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1640 :group 'org-todo
1641 :group 'org-keywords
1642 :type '(choice
1643 (repeat :tag "Old syntax, just keywords"
1644 (string :tag "Keyword"))
1645 (repeat :tag "New syntax"
1646 (cons
1647 (choice
1648 :tag "Interpretation"
1649 ;;Quick and dirty way to see
1650 ;;`org-todo-interpretations'. This takes the
1651 ;;place of item arguments
1652 :convert-widget
1653 (lambda (widget)
1654 (widget-put widget
1655 :args (mapcar
1656 #'(lambda (x)
1657 (widget-convert
1658 (cons 'const x)))
1659 org-todo-interpretation-widgets))
1660 widget))
1661 (repeat
1662 (string :tag "Keyword"))))))
1664 (defvar org-todo-keywords-1 nil
1665 "All TODO and DONE keywords active in a buffer.")
1666 (make-variable-buffer-local 'org-todo-keywords-1)
1667 (defvar org-todo-keywords-for-agenda nil)
1668 (defvar org-done-keywords-for-agenda nil)
1669 (defvar org-todo-keyword-alist-for-agenda nil)
1670 (defvar org-tag-alist-for-agenda nil)
1671 (defvar org-agenda-contributing-files nil)
1672 (defvar org-not-done-keywords nil)
1673 (make-variable-buffer-local 'org-not-done-keywords)
1674 (defvar org-done-keywords nil)
1675 (make-variable-buffer-local 'org-done-keywords)
1676 (defvar org-todo-heads nil)
1677 (make-variable-buffer-local 'org-todo-heads)
1678 (defvar org-todo-sets nil)
1679 (make-variable-buffer-local 'org-todo-sets)
1680 (defvar org-todo-log-states nil)
1681 (make-variable-buffer-local 'org-todo-log-states)
1682 (defvar org-todo-kwd-alist nil)
1683 (make-variable-buffer-local 'org-todo-kwd-alist)
1684 (defvar org-todo-key-alist nil)
1685 (make-variable-buffer-local 'org-todo-key-alist)
1686 (defvar org-todo-key-trigger nil)
1687 (make-variable-buffer-local 'org-todo-key-trigger)
1689 (defcustom org-todo-interpretation 'sequence
1690 "Controls how TODO keywords are interpreted.
1691 This variable is in principle obsolete and is only used for
1692 backward compatibility, if the interpretation of todo keywords is
1693 not given already in `org-todo-keywords'. See that variable for
1694 more information."
1695 :group 'org-todo
1696 :group 'org-keywords
1697 :type '(choice (const sequence)
1698 (const type)))
1700 (defcustom org-use-fast-todo-selection t
1701 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1702 This variable describes if and under what circumstances the cycling
1703 mechanism for TODO keywords will be replaced by a single-key, direct
1704 selection scheme.
1706 When nil, fast selection is never used.
1708 When the symbol `prefix', it will be used when `org-todo' is called with
1709 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1710 in an agenda buffer.
1712 When t, fast selection is used by default. In this case, the prefix
1713 argument forces cycling instead.
1715 In all cases, the special interface is only used if access keys have actually
1716 been assigned by the user, i.e. if keywords in the configuration are followed
1717 by a letter in parenthesis, like TODO(t)."
1718 :group 'org-todo
1719 :type '(choice
1720 (const :tag "Never" nil)
1721 (const :tag "By default" t)
1722 (const :tag "Only with C-u C-c C-t" prefix)))
1724 (defcustom org-provide-todo-statistics t
1725 "Non-nil means, update todo statistics after insert and toggle.
1726 When this is set, todo statistics is updated in the parent of the current
1727 entry each time a todo state is changed."
1728 :group 'org-todo
1729 :type 'boolean)
1731 (defcustom org-after-todo-state-change-hook nil
1732 "Hook which is run after the state of a TODO item was changed.
1733 The new state (a string with a TODO keyword, or nil) is available in the
1734 Lisp variable `state'."
1735 :group 'org-todo
1736 :type 'hook)
1738 (defvar org-blocker-hook nil
1739 "Hook for functions that are allowed to block a state change.
1741 Each function gets as its single argument a property list, see
1742 `org-trigger-hook' for more information about this list.
1744 If any of the functions in this hook returns nil, the state change
1745 is blocked.")
1747 (defvar org-trigger-hook nil
1748 "Hook for functions that are triggered by a state change.
1750 Each function gets as its single argument a property list with at least
1751 the following elements:
1753 (:type type-of-change :position pos-at-entry-start
1754 :from old-state :to new-state)
1756 Depending on the type, more properties may be present.
1758 This mechanism is currently implemented for:
1760 TODO state changes
1761 ------------------
1762 :type todo-state-change
1763 :from previous state (keyword as a string), or nil, or a symbol
1764 'todo' or 'done', to indicate the general type of state.
1765 :to new state, like in :from")
1767 (defcustom org-enforce-todo-dependencies nil
1768 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1769 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1770 be blocked if any prior sibling is not yet done.
1771 Finally, if the parent is blocked because of ordered siblings of its own,
1772 the child will also be blocked.
1773 This variable needs to be set before org.el is loaded, and you need to
1774 restart Emacs after a change to make the change effective. The only way
1775 to change is while Emacs is running is through the customize interface."
1776 :set (lambda (var val)
1777 (set var val)
1778 (if val
1779 (add-hook 'org-blocker-hook
1780 'org-block-todo-from-children-or-siblings-or-parent)
1781 (remove-hook 'org-blocker-hook
1782 'org-block-todo-from-children-or-siblings-or-parent)))
1783 :group 'org-todo
1784 :type 'boolean)
1786 (defcustom org-enforce-todo-checkbox-dependencies nil
1787 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1788 When this is nil, checkboxes have no influence on switching TODO states.
1789 When non-nil, you first need to check off all check boxes before the TODO
1790 entry can be switched to DONE.
1791 This variable needs to be set before org.el is loaded, and you need to
1792 restart Emacs after a change to make the change effective. The only way
1793 to change is while Emacs is running is through the customize interface."
1794 :set (lambda (var val)
1795 (set var val)
1796 (if val
1797 (add-hook 'org-blocker-hook
1798 'org-block-todo-from-checkboxes)
1799 (remove-hook 'org-blocker-hook
1800 'org-block-todo-from-checkboxes)))
1801 :group 'org-todo
1802 :type 'boolean)
1804 (defcustom org-todo-state-tags-triggers nil
1805 "Tag changes that should be triggered by TODO state changes.
1806 This is a list. Each entry is
1808 (state-change (tag . flag) .......)
1810 State-change can be a string with a state, and empty string to indicate the
1811 state that has no TODO keyword, or it can be one of the symbols `todo'
1812 or `done', meaning any not-done or done state, respectively."
1813 :group 'org-todo
1814 :group 'org-tags
1815 :type '(repeat
1816 (cons (choice :tag "When changing to"
1817 (const :tag "Not-done state" todo)
1818 (const :tag "Done state" done)
1819 (string :tag "State"))
1820 (repeat
1821 (cons :tag "Tag action"
1822 (string :tag "Tag")
1823 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1825 (defcustom org-log-done nil
1826 "Information to record when a task moves to the DONE state.
1828 Possible values are:
1830 nil Don't add anything, just change the keyword
1831 time Add a time stamp to the task
1832 note Prompt a closing note and add it with template `org-log-note-headings'
1834 This option can also be set with on a per-file-basis with
1836 #+STARTUP: nologdone
1837 #+STARTUP: logdone
1838 #+STARTUP: lognotedone
1840 You can have local logging settings for a subtree by setting the LOGGING
1841 property to one or more of these keywords."
1842 :group 'org-todo
1843 :group 'org-progress
1844 :type '(choice
1845 (const :tag "No logging" nil)
1846 (const :tag "Record CLOSED timestamp" time)
1847 (const :tag "Record CLOSED timestamp with closing note." note)))
1849 ;; Normalize old uses of org-log-done.
1850 (cond
1851 ((eq org-log-done t) (setq org-log-done 'time))
1852 ((and (listp org-log-done) (memq 'done org-log-done))
1853 (setq org-log-done 'note)))
1855 (defcustom org-log-note-clock-out nil
1856 "Non-nil means, record a note when clocking out of an item.
1857 This can also be configured on a per-file basis by adding one of
1858 the following lines anywhere in the buffer:
1860 #+STARTUP: lognoteclock-out
1861 #+STARTUP: nolognoteclock-out"
1862 :group 'org-todo
1863 :group 'org-progress
1864 :type 'boolean)
1866 (defcustom org-log-done-with-time t
1867 "Non-nil means, the CLOSED time stamp will contain date and time.
1868 When nil, only the date will be recorded."
1869 :group 'org-progress
1870 :type 'boolean)
1872 (defcustom org-log-note-headings
1873 '((done . "CLOSING NOTE %t")
1874 (state . "State %-12s from %-12S %t")
1875 (note . "Note taken on %t")
1876 (clock-out . ""))
1877 "Headings for notes added to entries.
1878 The value is an alist, with the car being a symbol indicating the note
1879 context, and the cdr is the heading to be used. The heading may also be the
1880 empty string.
1881 %t in the heading will be replaced by a time stamp.
1882 %s will be replaced by the new TODO state, in double quotes.
1883 %S will be replaced by the old TODO state, in double quotes.
1884 %u will be replaced by the user name.
1885 %U will be replaced by the full user name."
1886 :group 'org-todo
1887 :group 'org-progress
1888 :type '(list :greedy t
1889 (cons (const :tag "Heading when closing an item" done) string)
1890 (cons (const :tag
1891 "Heading when changing todo state (todo sequence only)"
1892 state) string)
1893 (cons (const :tag "Heading when just taking a note" note) string)
1894 (cons (const :tag "Heading when clocking out" clock-out) string)))
1896 (unless (assq 'note org-log-note-headings)
1897 (push '(note . "%t") org-log-note-headings))
1899 (defcustom org-log-into-drawer nil
1900 "Non-nil means, insert state change notes and time stamps into a drawer.
1901 When nil, state changes notes will be inserted after the headline and
1902 any scheduling and clock lines, but not inside a drawer.
1904 The value of this variable should be the name of the drawer to use.
1905 LOGBOOK is proposed at the default drawer for this purpose, you can
1906 also set this to a string to define the drawer of your choice.
1908 A value of t is also allowed, representing \"LOGBOOK\".
1910 If this variable is set, `org-log-state-notes-insert-after-drawers'
1911 will be ignored."
1912 :group 'org-todo
1913 :group 'org-progress
1914 :type '(choice
1915 (const :tag "Not into a drawer" nil)
1916 (const :tag "LOGBOOK" t)
1917 (string :tag "Other")))
1919 (if (fboundp 'defvaralias)
1920 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1922 (defcustom org-log-state-notes-insert-after-drawers nil
1923 "Non-nil means, insert state change notes after any drawers in entry.
1924 Only the drawers that *immediately* follow the headline and the
1925 deadline/scheduled line are skipped.
1926 When nil, insert notes right after the heading and perhaps the line
1927 with deadline/scheduling if present.
1929 This variable will have no effect if `org-log-into-drawer' is
1930 set."
1931 :group 'org-todo
1932 :group 'org-progress
1933 :type 'boolean)
1935 (defcustom org-log-states-order-reversed t
1936 "Non-nil means, the latest state change note will be directly after heading.
1937 When nil, the notes will be orderer according to time."
1938 :group 'org-todo
1939 :group 'org-progress
1940 :type 'boolean)
1942 (defcustom org-log-repeat 'time
1943 "Non-nil means, record moving through the DONE state when triggering repeat.
1944 An auto-repeating tasks is immediately switched back to TODO when marked
1945 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1946 the TODO keyword definition, or recording a closing note by setting
1947 `org-log-done', there will be no record of the task moving through DONE.
1948 This variable forces taking a note anyway. Possible values are:
1950 nil Don't force a record
1951 time Record a time stamp
1952 note Record a note
1954 This option can also be set with on a per-file-basis with
1956 #+STARTUP: logrepeat
1957 #+STARTUP: lognoterepeat
1958 #+STARTUP: nologrepeat
1960 You can have local logging settings for a subtree by setting the LOGGING
1961 property to one or more of these keywords."
1962 :group 'org-todo
1963 :group 'org-progress
1964 :type '(choice
1965 (const :tag "Don't force a record" nil)
1966 (const :tag "Force recording the DONE state" time)
1967 (const :tag "Force recording a note with the DONE state" note)))
1970 (defgroup org-priorities nil
1971 "Priorities in Org-mode."
1972 :tag "Org Priorities"
1973 :group 'org-todo)
1975 (defcustom org-highest-priority ?A
1976 "The highest priority of TODO items. A character like ?A, ?B etc.
1977 Must have a smaller ASCII number than `org-lowest-priority'."
1978 :group 'org-priorities
1979 :type 'character)
1981 (defcustom org-lowest-priority ?C
1982 "The lowest priority of TODO items. A character like ?A, ?B etc.
1983 Must have a larger ASCII number than `org-highest-priority'."
1984 :group 'org-priorities
1985 :type 'character)
1987 (defcustom org-default-priority ?B
1988 "The default priority of TODO items.
1989 This is the priority an item get if no explicit priority is given."
1990 :group 'org-priorities
1991 :type 'character)
1993 (defcustom org-priority-start-cycle-with-default t
1994 "Non-nil means, start with default priority when starting to cycle.
1995 When this is nil, the first step in the cycle will be (depending on the
1996 command used) one higher or lower that the default priority."
1997 :group 'org-priorities
1998 :type 'boolean)
2000 (defgroup org-time nil
2001 "Options concerning time stamps and deadlines in Org-mode."
2002 :tag "Org Time"
2003 :group 'org)
2005 (defcustom org-insert-labeled-timestamps-at-point nil
2006 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2007 When nil, these labeled time stamps are forces into the second line of an
2008 entry, just after the headline. When scheduling from the global TODO list,
2009 the time stamp will always be forced into the second line."
2010 :group 'org-time
2011 :type 'boolean)
2013 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2014 "Formats for `format-time-string' which are used for time stamps.
2015 It is not recommended to change this constant.")
2017 (defcustom org-time-stamp-rounding-minutes '(0 5)
2018 "Number of minutes to round time stamps to.
2019 These are two values, the first applies when first creating a time stamp.
2020 The second applies when changing it with the commands `S-up' and `S-down'.
2021 When changing the time stamp, this means that it will change in steps
2022 of N minutes, as given by the second value.
2024 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2025 numbers should be factors of 60, so for example 5, 10, 15.
2027 When this is larger than 1, you can still force an exact time-stamp by using
2028 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2029 and by using a prefix arg to `S-up/down' to specify the exact number
2030 of minutes to shift."
2031 :group 'org-time
2032 :get '(lambda (var) ; Make sure all entries have 5 elements
2033 (if (integerp (default-value var))
2034 (list (default-value var) 5)
2035 (default-value var)))
2036 :type '(list
2037 (integer :tag "when inserting times")
2038 (integer :tag "when modifying times")))
2040 ;; Normalize old customizations of this variable.
2041 (when (integerp org-time-stamp-rounding-minutes)
2042 (setq org-time-stamp-rounding-minutes
2043 (list org-time-stamp-rounding-minutes
2044 org-time-stamp-rounding-minutes)))
2046 (defcustom org-display-custom-times nil
2047 "Non-nil means, overlay custom formats over all time stamps.
2048 The formats are defined through the variable `org-time-stamp-custom-formats'.
2049 To turn this on on a per-file basis, insert anywhere in the file:
2050 #+STARTUP: customtime"
2051 :group 'org-time
2052 :set 'set-default
2053 :type 'sexp)
2054 (make-variable-buffer-local 'org-display-custom-times)
2056 (defcustom org-time-stamp-custom-formats
2057 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2058 "Custom formats for time stamps. See `format-time-string' for the syntax.
2059 These are overlayed over the default ISO format if the variable
2060 `org-display-custom-times' is set. Time like %H:%M should be at the
2061 end of the second format. The custom formats are also honored by export
2062 commands, if custom time display is turned on at the time of export."
2063 :group 'org-time
2064 :type 'sexp)
2066 (defun org-time-stamp-format (&optional long inactive)
2067 "Get the right format for a time string."
2068 (let ((f (if long (cdr org-time-stamp-formats)
2069 (car org-time-stamp-formats))))
2070 (if inactive
2071 (concat "[" (substring f 1 -1) "]")
2072 f)))
2074 (defcustom org-time-clocksum-format "%d:%02d"
2075 "The format string used when creating CLOCKSUM lines, or when
2076 org-mode generates a time duration."
2077 :group 'org-time
2078 :type 'string)
2080 (defcustom org-deadline-warning-days 14
2081 "No. of days before expiration during which a deadline becomes active.
2082 This variable governs the display in sparse trees and in the agenda.
2083 When 0 or negative, it means use this number (the absolute value of it)
2084 even if a deadline has a different individual lead time specified.
2086 Custom commands can set this variable in the options section."
2087 :group 'org-time
2088 :group 'org-agenda-daily/weekly
2089 :type 'integer)
2091 (defcustom org-read-date-prefer-future t
2092 "Non-nil means, assume future for incomplete date input from user.
2093 This affects the following situations:
2094 1. The user gives a day, but no month.
2095 For example, if today is the 15th, and you enter \"3\", Org-mode will
2096 read this as the third of *next* month. However, if you enter \"17\",
2097 it will be considered as *this* month.
2098 2. The user gives a month but not a year.
2099 For example, if it is april and you enter \"feb 2\", this will be read
2100 as feb 2, *next* year. \"May 5\", however, will be this year.
2102 Currently this does not work for ISO week specifications.
2104 When this option is nil, the current month and year will always be used
2105 as defaults."
2106 :group 'org-time
2107 :type 'boolean)
2109 (defcustom org-read-date-display-live t
2110 "Non-nil means, display current interpretation of date prompt live.
2111 This display will be in an overlay, in the minibuffer."
2112 :group 'org-time
2113 :type 'boolean)
2115 (defcustom org-read-date-popup-calendar t
2116 "Non-nil means, pop up a calendar when prompting for a date.
2117 In the calendar, the date can be selected with mouse-1. However, the
2118 minibuffer will also be active, and you can simply enter the date as well.
2119 When nil, only the minibuffer will be available."
2120 :group 'org-time
2121 :type 'boolean)
2122 (if (fboundp 'defvaralias)
2123 (defvaralias 'org-popup-calendar-for-date-prompt
2124 'org-read-date-popup-calendar))
2126 (defcustom org-read-date-minibuffer-setup-hook nil
2127 "Hook to be used to set up keys for the date/time interface.
2128 Add key definitions to `minibuffer-local-map', which will be a temporary
2129 copy."
2130 :group 'org-time
2131 :type 'hook)
2133 (defcustom org-extend-today-until 0
2134 "The hour when your day really ends. Must be an integer.
2135 This has influence for the following applications:
2136 - When switching the agenda to \"today\". It it is still earlier than
2137 the time given here, the day recognized as TODAY is actually yesterday.
2138 - When a date is read from the user and it is still before the time given
2139 here, the current date and time will be assumed to be yesterday, 23:59.
2140 Also, timestamps inserted in remember templates follow this rule.
2142 IMPORTANT: This is a feature whose implementation is and likely will
2143 remain incomplete. Really, it is only here because past midnight seems to
2144 be the favorite working time of John Wiegley :-)"
2145 :group 'org-time
2146 :type 'integer)
2148 (defcustom org-edit-timestamp-down-means-later nil
2149 "Non-nil means, S-down will increase the time in a time stamp.
2150 When nil, S-up will increase."
2151 :group 'org-time
2152 :type 'boolean)
2154 (defcustom org-calendar-follow-timestamp-change t
2155 "Non-nil means, make the calendar window follow timestamp changes.
2156 When a timestamp is modified and the calendar window is visible, it will be
2157 moved to the new date."
2158 :group 'org-time
2159 :type 'boolean)
2161 (defgroup org-tags nil
2162 "Options concerning tags in Org-mode."
2163 :tag "Org Tags"
2164 :group 'org)
2166 (defcustom org-tag-alist nil
2167 "List of tags allowed in Org-mode files.
2168 When this list is nil, Org-mode will base TAG input on what is already in the
2169 buffer.
2170 The value of this variable is an alist, the car of each entry must be a
2171 keyword as a string, the cdr may be a character that is used to select
2172 that tag through the fast-tag-selection interface.
2173 See the manual for details."
2174 :group 'org-tags
2175 :type '(repeat
2176 (choice
2177 (cons (string :tag "Tag name")
2178 (character :tag "Access char"))
2179 (const :tag "Start radio group" (:startgroup))
2180 (const :tag "End radio group" (:endgroup))
2181 (const :tag "New line" (:newline)))))
2183 (defcustom org-tag-persistent-alist nil
2184 "List of tags that will always appear in all Org-mode files.
2185 This is in addition to any in buffer settings or customizations
2186 of `org-tag-alist'.
2187 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2188 The value of this variable is an alist, the car of each entry must be a
2189 keyword as a string, the cdr may be a character that is used to select
2190 that tag through the fast-tag-selection interface.
2191 See the manual for details.
2192 To disable these tags on a per-file basis, insert anywhere in the file:
2193 #+STARTUP: noptag"
2194 :group 'org-tags
2195 :type '(repeat
2196 (choice
2197 (cons (string :tag "Tag name")
2198 (character :tag "Access char"))
2199 (const :tag "Start radio group" (:startgroup))
2200 (const :tag "End radio group" (:endgroup))
2201 (const :tag "New line" (:newline)))))
2203 (defvar org-file-tags nil
2204 "List of tags that can be inherited by all entries in the file.
2205 The tags will be inherited if the variable `org-use-tag-inheritance'
2206 says they should be.
2207 This variable is populated from #+TAG lines.")
2209 (defcustom org-use-fast-tag-selection 'auto
2210 "Non-nil means, use fast tag selection scheme.
2211 This is a special interface to select and deselect tags with single keys.
2212 When nil, fast selection is never used.
2213 When the symbol `auto', fast selection is used if and only if selection
2214 characters for tags have been configured, either through the variable
2215 `org-tag-alist' or through a #+TAGS line in the buffer.
2216 When t, fast selection is always used and selection keys are assigned
2217 automatically if necessary."
2218 :group 'org-tags
2219 :type '(choice
2220 (const :tag "Always" t)
2221 (const :tag "Never" nil)
2222 (const :tag "When selection characters are configured" 'auto)))
2224 (defcustom org-fast-tag-selection-single-key nil
2225 "Non-nil means, fast tag selection exits after first change.
2226 When nil, you have to press RET to exit it.
2227 During fast tag selection, you can toggle this flag with `C-c'.
2228 This variable can also have the value `expert'. In this case, the window
2229 displaying the tags menu is not even shown, until you press C-c again."
2230 :group 'org-tags
2231 :type '(choice
2232 (const :tag "No" nil)
2233 (const :tag "Yes" t)
2234 (const :tag "Expert" expert)))
2236 (defvar org-fast-tag-selection-include-todo nil
2237 "Non-nil means, fast tags selection interface will also offer TODO states.
2238 This is an undocumented feature, you should not rely on it.")
2240 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2241 "The column to which tags should be indented in a headline.
2242 If this number is positive, it specifies the column. If it is negative,
2243 it means that the tags should be flushright to that column. For example,
2244 -80 works well for a normal 80 character screen."
2245 :group 'org-tags
2246 :type 'integer)
2248 (defcustom org-auto-align-tags t
2249 "Non-nil means, realign tags after pro/demotion of TODO state change.
2250 These operations change the length of a headline and therefore shift
2251 the tags around. With this options turned on, after each such operation
2252 the tags are again aligned to `org-tags-column'."
2253 :group 'org-tags
2254 :type 'boolean)
2256 (defcustom org-use-tag-inheritance t
2257 "Non-nil means, tags in levels apply also for sublevels.
2258 When nil, only the tags directly given in a specific line apply there.
2259 This may also be a list of tags that should be inherited, or a regexp that
2260 matches tags that should be inherited. Additional control is possible
2261 with the variable `org-tags-exclude-from-inheritance' which gives an
2262 explicit list of tags to be excluded from inheritance., even if the value of
2263 `org-use-tag-inheritance' would select it for inheritance.
2265 If this option is t, a match early-on in a tree can lead to a large
2266 number of matches in the subtree when constructing the agenda or creating
2267 a sparse tree. If you only want to see the first match in a tree during
2268 a search, check out the variable `org-tags-match-list-sublevels'."
2269 :group 'org-tags
2270 :type '(choice
2271 (const :tag "Not" nil)
2272 (const :tag "Always" t)
2273 (repeat :tag "Specific tags" (string :tag "Tag"))
2274 (regexp :tag "Tags matched by regexp")))
2276 (defcustom org-tags-exclude-from-inheritance nil
2277 "List of tags that should never be inherited.
2278 This is a way to exclude a few tags from inheritance. For way to do
2279 the opposite, to actively allow inheritance for selected tags,
2280 see the variable `org-use-tag-inheritance'."
2281 :group 'org-tags
2282 :type '(repeat (string :tag "Tag")))
2284 (defun org-tag-inherit-p (tag)
2285 "Check if TAG is one that should be inherited."
2286 (cond
2287 ((member tag org-tags-exclude-from-inheritance) nil)
2288 ((eq org-use-tag-inheritance t) t)
2289 ((not org-use-tag-inheritance) nil)
2290 ((stringp org-use-tag-inheritance)
2291 (string-match org-use-tag-inheritance tag))
2292 ((listp org-use-tag-inheritance)
2293 (member tag org-use-tag-inheritance))
2294 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2296 (defcustom org-tags-match-list-sublevels t
2297 "Non-nil means list also sublevels of headlines matching a search.
2298 This variable applies to tags/property searches, and also to stuck
2299 projects because this search is based on a tags match as well.
2301 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2302 the sublevels of a headline matching a tag search often also match
2303 the same search. Listing all of them can create very long lists.
2304 Setting this variable to nil causes subtrees of a match to be skipped.
2306 As a special case, if the tag search is restricted to TODO items, the
2307 value of this variable is ignored and sublevels are always checked, to
2308 make sure all corresponding TODO items find their way into the list.
2310 This variable is semi-obsolete and probably should always be true. It
2311 is better to limit inheritance to certain tags using the variables
2312 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2313 :group 'org-tags
2314 :type '(choice
2315 (const :tag "No, don't list them" nil)
2316 (const :tag "Yes, do list them" t)
2317 (const :tag "List them, indented with leading dots" indented)))
2319 (defvar org-tags-history nil
2320 "History of minibuffer reads for tags.")
2321 (defvar org-last-tags-completion-table nil
2322 "The last used completion table for tags.")
2323 (defvar org-after-tags-change-hook nil
2324 "Hook that is run after the tags in a line have changed.")
2326 (defgroup org-properties nil
2327 "Options concerning properties in Org-mode."
2328 :tag "Org Properties"
2329 :group 'org)
2331 (defcustom org-property-format "%-10s %s"
2332 "How property key/value pairs should be formatted by `indent-line'.
2333 When `indent-line' hits a property definition, it will format the line
2334 according to this format, mainly to make sure that the values are
2335 lined-up with respect to each other."
2336 :group 'org-properties
2337 :type 'string)
2339 (defcustom org-use-property-inheritance nil
2340 "Non-nil means, properties apply also for sublevels.
2342 This setting is chiefly used during property searches. Turning it on can
2343 cause significant overhead when doing a search, which is why it is not
2344 on by default.
2346 When nil, only the properties directly given in the current entry count.
2347 When t, every property is inherited. The value may also be a list of
2348 properties that should have inheritance, or a regular expression matching
2349 properties that should be inherited.
2351 However, note that some special properties use inheritance under special
2352 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2353 and the properties ending in \"_ALL\" when they are used as descriptor
2354 for valid values of a property.
2356 Note for programmers:
2357 When querying an entry with `org-entry-get', you can control if inheritance
2358 should be used. By default, `org-entry-get' looks only at the local
2359 properties. You can request inheritance by setting the inherit argument
2360 to t (to force inheritance) or to `selective' (to respect the setting
2361 in this variable)."
2362 :group 'org-properties
2363 :type '(choice
2364 (const :tag "Not" nil)
2365 (const :tag "Always" t)
2366 (repeat :tag "Specific properties" (string :tag "Property"))
2367 (regexp :tag "Properties matched by regexp")))
2369 (defun org-property-inherit-p (property)
2370 "Check if PROPERTY is one that should be inherited."
2371 (cond
2372 ((eq org-use-property-inheritance t) t)
2373 ((not org-use-property-inheritance) nil)
2374 ((stringp org-use-property-inheritance)
2375 (string-match org-use-property-inheritance property))
2376 ((listp org-use-property-inheritance)
2377 (member property org-use-property-inheritance))
2378 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2380 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2381 "The default column format, if no other format has been defined.
2382 This variable can be set on the per-file basis by inserting a line
2384 #+COLUMNS: %25ITEM ....."
2385 :group 'org-properties
2386 :type 'string)
2388 (defcustom org-columns-ellipses ".."
2389 "The ellipses to be used when a field in column view is truncated.
2390 When this is the empty string, as many characters as possible are shown,
2391 but then there will be no visual indication that the field has been truncated.
2392 When this is a string of length N, the last N characters of a truncated
2393 field are replaced by this string. If the column is narrower than the
2394 ellipses string, only part of the ellipses string will be shown."
2395 :group 'org-properties
2396 :type 'string)
2398 (defcustom org-columns-modify-value-for-display-function nil
2399 "Function that modifies values for display in column view.
2400 For example, it can be used to cut out a certain part from a time stamp.
2401 The function must take 2 arguments:
2403 column-title The title of the column (*not* the property name)
2404 value The value that should be modified.
2406 The function should return the value that should be displayed,
2407 or nil if the normal value should be used."
2408 :group 'org-properties
2409 :type 'function)
2411 (defcustom org-effort-property "Effort"
2412 "The property that is being used to keep track of effort estimates.
2413 Effort estimates given in this property need to have the format H:MM."
2414 :group 'org-properties
2415 :group 'org-progress
2416 :type '(string :tag "Property"))
2418 (defconst org-global-properties-fixed
2419 '(("VISIBILITY_ALL" . "folded children content all"))
2420 "List of property/value pairs that can be inherited by any entry.
2422 These are fixed values, for the preset properties. The user variable
2423 that can be used to add to this list is `org-global-properties'.
2425 The entries in this list are cons cells where the car is a property
2426 name and cdr is a string with the value. If the value represents
2427 multiple items like an \"_ALL\" property, separate the items by
2428 spaces.")
2430 (defcustom org-global-properties nil
2431 "List of property/value pairs that can be inherited by any entry.
2433 This list will be combined with the constant `org-global-properties-fixed'.
2435 The entries in this list are cons cells where the car is a property
2436 name and cdr is a string with the value.
2438 You can set buffer-local values for the same purpose in the variable
2439 `org-file-properties' this by adding lines like
2441 #+PROPERTY: NAME VALUE"
2442 :group 'org-properties
2443 :type '(repeat
2444 (cons (string :tag "Property")
2445 (string :tag "Value"))))
2447 (defvar org-file-properties nil
2448 "List of property/value pairs that can be inherited by any entry.
2449 Valid for the current buffer.
2450 This variable is populated from #+PROPERTY lines.")
2451 (make-variable-buffer-local 'org-file-properties)
2453 (defgroup org-agenda nil
2454 "Options concerning agenda views in Org-mode."
2455 :tag "Org Agenda"
2456 :group 'org)
2458 (defvar org-category nil
2459 "Variable used by org files to set a category for agenda display.
2460 Such files should use a file variable to set it, for example
2462 # -*- mode: org; org-category: \"ELisp\"
2464 or contain a special line
2466 #+CATEGORY: ELisp
2468 If the file does not specify a category, then file's base name
2469 is used instead.")
2470 (make-variable-buffer-local 'org-category)
2471 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2473 (defcustom org-agenda-files nil
2474 "The files to be used for agenda display.
2475 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2476 \\[org-remove-file]. You can also use customize to edit the list.
2478 If an entry is a directory, all files in that directory that are matched by
2479 `org-agenda-file-regexp' will be part of the file list.
2481 If the value of the variable is not a list but a single file name, then
2482 the list of agenda files is actually stored and maintained in that file, one
2483 agenda file per line."
2484 :group 'org-agenda
2485 :type '(choice
2486 (repeat :tag "List of files and directories" file)
2487 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2489 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2490 "Regular expression to match files for `org-agenda-files'.
2491 If any element in the list in that variable contains a directory instead
2492 of a normal file, all files in that directory that are matched by this
2493 regular expression will be included."
2494 :group 'org-agenda
2495 :type 'regexp)
2497 (defcustom org-agenda-text-search-extra-files nil
2498 "List of extra files to be searched by text search commands.
2499 These files will be search in addition to the agenda files by the
2500 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2501 Note that these files will only be searched for text search commands,
2502 not for the other agenda views like todo lists, tag searches or the weekly
2503 agenda. This variable is intended to list notes and possibly archive files
2504 that should also be searched by these two commands.
2505 In fact, if the first element in the list is the symbol `agenda-archives',
2506 than all archive files of all agenda files will be added to the search
2507 scope."
2508 :group 'org-agenda
2509 :type '(set :greedy t
2510 (const :tag "Agenda Archives" agenda-archives)
2511 (repeat :inline t (file))))
2513 (if (fboundp 'defvaralias)
2514 (defvaralias 'org-agenda-multi-occur-extra-files
2515 'org-agenda-text-search-extra-files))
2517 (defcustom org-agenda-skip-unavailable-files nil
2518 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2519 A nil value means to remove them, after a query, from the list."
2520 :group 'org-agenda
2521 :type 'boolean)
2523 (defcustom org-calendar-to-agenda-key [?c]
2524 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2525 The command `org-calendar-goto-agenda' will be bound to this key. The
2526 default is the character `c' because then `c' can be used to switch back and
2527 forth between agenda and calendar."
2528 :group 'org-agenda
2529 :type 'sexp)
2531 (defcustom org-calendar-agenda-action-key [?k]
2532 "The key to be installed in `calendar-mode-map' for agenda-action.
2533 The command `org-agenda-action' will be bound to this key. The
2534 default is the character `k' because we use the same key in the agenda."
2535 :group 'org-agenda
2536 :type 'sexp)
2538 (eval-after-load "calendar"
2539 '(progn
2540 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2541 'org-calendar-goto-agenda)
2542 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2543 'org-agenda-action)))
2545 (defgroup org-latex nil
2546 "Options for embedding LaTeX code into Org-mode."
2547 :tag "Org LaTeX"
2548 :group 'org)
2550 (defcustom org-format-latex-options
2551 '(:foreground default :background default :scale 1.0
2552 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2553 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2554 "Options for creating images from LaTeX fragments.
2555 This is a property list with the following properties:
2556 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2557 `default' means use the foreground of the default face.
2558 :background the background color, or \"Transparent\".
2559 `default' means use the background of the default face.
2560 :scale a scaling factor for the size of the images.
2561 :html-foreground, :html-background, :html-scale
2562 the same numbers for HTML export.
2563 :matchers a list indicating which matchers should be used to
2564 find LaTeX fragments. Valid members of this list are:
2565 \"begin\" find environments
2566 \"$1\" find single characters surrounded by $.$
2567 \"$\" find math expressions surrounded by $...$
2568 \"$$\" find math expressions surrounded by $$....$$
2569 \"\\(\" find math expressions surrounded by \\(...\\)
2570 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2571 :group 'org-latex
2572 :type 'plist)
2574 (defcustom org-format-latex-header "\\documentclass{article}
2575 \\usepackage{fullpage} % do not remove
2576 \\usepackage{amssymb}
2577 \\usepackage[usenames]{color}
2578 \\usepackage{amsmath}
2579 \\usepackage{latexsym}
2580 \\usepackage[mathscr]{eucal}
2581 \\pagestyle{empty} % do not remove"
2582 "The document header used for processing LaTeX fragments."
2583 :group 'org-latex
2584 :type 'string)
2587 (defgroup org-font-lock nil
2588 "Font-lock settings for highlighting in Org-mode."
2589 :tag "Org Font Lock"
2590 :group 'org)
2592 (defcustom org-level-color-stars-only nil
2593 "Non-nil means fontify only the stars in each headline.
2594 When nil, the entire headline is fontified.
2595 Changing it requires restart of `font-lock-mode' to become effective
2596 also in regions already fontified."
2597 :group 'org-font-lock
2598 :type 'boolean)
2600 (defcustom org-hide-leading-stars nil
2601 "Non-nil means, hide the first N-1 stars in a headline.
2602 This works by using the face `org-hide' for these stars. This
2603 face is white for a light background, and black for a dark
2604 background. You may have to customize the face `org-hide' to
2605 make this work.
2606 Changing it requires restart of `font-lock-mode' to become effective
2607 also in regions already fontified.
2608 You may also set this on a per-file basis by adding one of the following
2609 lines to the buffer:
2611 #+STARTUP: hidestars
2612 #+STARTUP: showstars"
2613 :group 'org-font-lock
2614 :type 'boolean)
2616 (defcustom org-fontify-done-headline nil
2617 "Non-nil means, change the face of a headline if it is marked DONE.
2618 Normally, only the TODO/DONE keyword indicates the state of a headline.
2619 When this is non-nil, the headline after the keyword is set to the
2620 `org-headline-done' as an additional indication."
2621 :group 'org-font-lock
2622 :type 'boolean)
2624 (defcustom org-fontify-emphasized-text t
2625 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2626 Changing this variable requires a restart of Emacs to take effect."
2627 :group 'org-font-lock
2628 :type 'boolean)
2630 (defcustom org-highlight-latex-fragments-and-specials nil
2631 "Non-nil means, fontify what is treated specially by the exporters."
2632 :group 'org-font-lock
2633 :type 'boolean)
2635 (defcustom org-hide-emphasis-markers nil
2636 "Non-nil mean font-lock should hide the emphasis marker characters."
2637 :group 'org-font-lock
2638 :type 'boolean)
2640 (defvar org-emph-re nil
2641 "Regular expression for matching emphasis.")
2642 (defvar org-verbatim-re nil
2643 "Regular expression for matching verbatim text.")
2644 (defvar org-emphasis-regexp-components) ; defined just below
2645 (defvar org-emphasis-alist) ; defined just below
2646 (defun org-set-emph-re (var val)
2647 "Set variable and compute the emphasis regular expression."
2648 (set var val)
2649 (when (and (boundp 'org-emphasis-alist)
2650 (boundp 'org-emphasis-regexp-components)
2651 org-emphasis-alist org-emphasis-regexp-components)
2652 (let* ((e org-emphasis-regexp-components)
2653 (pre (car e))
2654 (post (nth 1 e))
2655 (border (nth 2 e))
2656 (body (nth 3 e))
2657 (nl (nth 4 e))
2658 (body1 (concat body "*?"))
2659 (markers (mapconcat 'car org-emphasis-alist ""))
2660 (vmarkers (mapconcat
2661 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2662 org-emphasis-alist "")))
2663 ;; make sure special characters appear at the right position in the class
2664 (if (string-match "\\^" markers)
2665 (setq markers (concat (replace-match "" t t markers) "^")))
2666 (if (string-match "-" markers)
2667 (setq markers (concat (replace-match "" t t markers) "-")))
2668 (if (string-match "\\^" vmarkers)
2669 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2670 (if (string-match "-" vmarkers)
2671 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2672 (if (> nl 0)
2673 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2674 (int-to-string nl) "\\}")))
2675 ;; Make the regexp
2676 (setq org-emph-re
2677 (concat "\\([" pre "]\\|^\\)"
2678 "\\("
2679 "\\([" markers "]\\)"
2680 "\\("
2681 "[^" border "]\\|"
2682 "[^" border "]"
2683 body1
2684 "[^" border "]"
2685 "\\)"
2686 "\\3\\)"
2687 "\\([" post "]\\|$\\)"))
2688 (setq org-verbatim-re
2689 (concat "\\([" pre "]\\|^\\)"
2690 "\\("
2691 "\\([" vmarkers "]\\)"
2692 "\\("
2693 "[^" border "]\\|"
2694 "[^" border "]"
2695 body1
2696 "[^" border "]"
2697 "\\)"
2698 "\\3\\)"
2699 "\\([" post "]\\|$\\)")))))
2701 (defcustom org-emphasis-regexp-components
2702 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2703 "Components used to build the regular expression for emphasis.
2704 This is a list with 6 entries. Terminology: In an emphasis string
2705 like \" *strong word* \", we call the initial space PREMATCH, the final
2706 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2707 and \"trong wor\" is the body. The different components in this variable
2708 specify what is allowed/forbidden in each part:
2710 pre Chars allowed as prematch. Beginning of line will be allowed too.
2711 post Chars allowed as postmatch. End of line will be allowed too.
2712 border The chars *forbidden* as border characters.
2713 body-regexp A regexp like \".\" to match a body character. Don't use
2714 non-shy groups here, and don't allow newline here.
2715 newline The maximum number of newlines allowed in an emphasis exp.
2717 Use customize to modify this, or restart Emacs after changing it."
2718 :group 'org-font-lock
2719 :set 'org-set-emph-re
2720 :type '(list
2721 (sexp :tag "Allowed chars in pre ")
2722 (sexp :tag "Allowed chars in post ")
2723 (sexp :tag "Forbidden chars in border ")
2724 (sexp :tag "Regexp for body ")
2725 (integer :tag "number of newlines allowed")
2726 (option (boolean :tag "Please ignore this button"))))
2728 (defcustom org-emphasis-alist
2729 `(("*" bold "<b>" "</b>")
2730 ("/" italic "<i>" "</i>")
2731 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2732 ("=" org-code "<code>" "</code>" verbatim)
2733 ("~" org-verbatim "<code>" "</code>" verbatim)
2734 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2735 "<del>" "</del>")
2737 "Special syntax for emphasized text.
2738 Text starting and ending with a special character will be emphasized, for
2739 example *bold*, _underlined_ and /italic/. This variable sets the marker
2740 characters, the face to be used by font-lock for highlighting in Org-mode
2741 Emacs buffers, and the HTML tags to be used for this.
2742 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2743 Use customize to modify this, or restart Emacs after changing it."
2744 :group 'org-font-lock
2745 :set 'org-set-emph-re
2746 :type '(repeat
2747 (list
2748 (string :tag "Marker character")
2749 (choice
2750 (face :tag "Font-lock-face")
2751 (plist :tag "Face property list"))
2752 (string :tag "HTML start tag")
2753 (string :tag "HTML end tag")
2754 (option (const verbatim)))))
2756 ;;; Miscellaneous options
2758 (defgroup org-completion nil
2759 "Completion in Org-mode."
2760 :tag "Org Completion"
2761 :group 'org)
2763 (defcustom org-completion-use-ido nil
2764 "Non-nil means, use ido completion wherever possible.
2765 Note that `ido-mode' must be active for this variable to be relevant.
2766 If you decide to turn this variable on, you might well want to turn off
2767 `org-outline-path-complete-in-steps'."
2768 :group 'org-completion
2769 :type 'boolean)
2771 (defcustom org-completion-fallback-command 'hippie-expand
2772 "The expansion command called by \\[org-complete] in normal context.
2773 Normal means, no org-mode-specific context."
2774 :group 'org-completion
2775 :type 'function)
2777 ;;; Functions and variables from ther packages
2778 ;; Declared here to avoid compiler warnings
2780 ;; XEmacs only
2781 (defvar outline-mode-menu-heading)
2782 (defvar outline-mode-menu-show)
2783 (defvar outline-mode-menu-hide)
2784 (defvar zmacs-regions) ; XEmacs regions
2786 ;; Emacs only
2787 (defvar mark-active)
2789 ;; Various packages
2790 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2791 (declare-function calendar-forward-day "cal-move" (arg))
2792 (declare-function calendar-goto-date "cal-move" (date))
2793 (declare-function calendar-goto-today "cal-move" ())
2794 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2795 (defvar calc-embedded-close-formula)
2796 (defvar calc-embedded-open-formula)
2797 (declare-function cdlatex-tab "ext:cdlatex" ())
2798 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2799 (defvar font-lock-unfontify-region-function)
2800 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2801 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2802 (defvar iswitchb-temp-buflist)
2803 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2804 (defvar org-agenda-tags-todo-honor-ignore-options)
2805 (declare-function org-agenda-skip "org-agenda" ())
2806 (declare-function org-format-agenda-item "org-agenda"
2807 (extra txt &optional category tags dotime noprefix remove-re))
2808 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2809 (declare-function org-agenda-change-all-lines "org-agenda"
2810 (newhead hdmarker &optional fixface just-this))
2811 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2812 (declare-function org-agenda-maybe-redo "org-agenda" ())
2813 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2814 (beg end))
2815 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2816 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2817 "org-agenda" (&optional end))
2819 (declare-function parse-time-string "parse-time" (string))
2820 (declare-function remember "remember" (&optional initial))
2821 (declare-function remember-buffer-desc "remember" ())
2822 (declare-function remember-finalize "remember" ())
2823 (defvar remember-save-after-remembering)
2824 (defvar remember-data-file)
2825 (defvar remember-register)
2826 (defvar remember-buffer)
2827 (defvar remember-handler-functions)
2828 (defvar remember-annotation-functions)
2829 (defvar texmathp-why)
2830 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2831 (declare-function table--at-cell-p "table" (position &optional object at-column))
2833 (defvar w3m-current-url)
2834 (defvar w3m-current-title)
2836 (defvar org-latex-regexps)
2838 ;;; Autoload and prepare some org modules
2840 ;; Some table stuff that needs to be defined here, because it is used
2841 ;; by the functions setting up org-mode or checking for table context.
2843 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2844 "Detects an org-type or table-type table.")
2845 (defconst org-table-line-regexp "^[ \t]*|"
2846 "Detects an org-type table line.")
2847 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2848 "Detects an org-type table line.")
2849 (defconst org-table-hline-regexp "^[ \t]*|-"
2850 "Detects an org-type table hline.")
2851 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2852 "Detects a table-type table hline.")
2853 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2854 "Searching from within a table (any type) this finds the first line
2855 outside the table.")
2857 ;; Autoload the functions in org-table.el that are needed by functions here.
2859 (eval-and-compile
2860 (org-autoload "org-table"
2861 '(org-table-align org-table-begin org-table-blank-field
2862 org-table-convert org-table-convert-region org-table-copy-down
2863 org-table-copy-region org-table-create
2864 org-table-create-or-convert-from-region
2865 org-table-create-with-table.el org-table-current-dline
2866 org-table-cut-region org-table-delete-column org-table-edit-field
2867 org-table-edit-formulas org-table-end org-table-eval-formula
2868 org-table-export org-table-field-info
2869 org-table-get-stored-formulas org-table-goto-column
2870 org-table-hline-and-move org-table-import org-table-insert-column
2871 org-table-insert-hline org-table-insert-row org-table-iterate
2872 org-table-justify-field-maybe org-table-kill-row
2873 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2874 org-table-move-column org-table-move-column-left
2875 org-table-move-column-right org-table-move-row
2876 org-table-move-row-down org-table-move-row-up
2877 org-table-next-field org-table-next-row org-table-paste-rectangle
2878 org-table-previous-field org-table-recalculate
2879 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2880 org-table-toggle-coordinate-overlays
2881 org-table-toggle-formula-debugger org-table-wrap-region
2882 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2884 (defun org-at-table-p (&optional table-type)
2885 "Return t if the cursor is inside an org-type table.
2886 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2887 (if org-enable-table-editor
2888 (save-excursion
2889 (beginning-of-line 1)
2890 (looking-at (if table-type org-table-any-line-regexp
2891 org-table-line-regexp)))
2892 nil))
2893 (defsubst org-table-p () (org-at-table-p))
2895 (defun org-at-table.el-p ()
2896 "Return t if and only if we are at a table.el table."
2897 (and (org-at-table-p 'any)
2898 (save-excursion
2899 (goto-char (org-table-begin 'any))
2900 (looking-at org-table1-hline-regexp))))
2901 (defun org-table-recognize-table.el ()
2902 "If there is a table.el table nearby, recognize it and move into it."
2903 (if org-table-tab-recognizes-table.el
2904 (if (org-at-table.el-p)
2905 (progn
2906 (beginning-of-line 1)
2907 (if (looking-at org-table-dataline-regexp)
2909 (if (looking-at org-table1-hline-regexp)
2910 (progn
2911 (beginning-of-line 2)
2912 (if (looking-at org-table-any-border-regexp)
2913 (beginning-of-line -1)))))
2914 (if (re-search-forward "|" (org-table-end t) t)
2915 (progn
2916 (require 'table)
2917 (if (table--at-cell-p (point))
2919 (message "recognizing table.el table...")
2920 (table-recognize-table)
2921 (message "recognizing table.el table...done")))
2922 (error "This should not happen..."))
2924 nil)
2925 nil))
2927 (defun org-at-table-hline-p ()
2928 "Return t if the cursor is inside a hline in a table."
2929 (if org-enable-table-editor
2930 (save-excursion
2931 (beginning-of-line 1)
2932 (looking-at org-table-hline-regexp))
2933 nil))
2935 (defvar org-table-clean-did-remove-column nil)
2937 (defun org-table-map-tables (function)
2938 "Apply FUNCTION to the start of all tables in the buffer."
2939 (save-excursion
2940 (save-restriction
2941 (widen)
2942 (goto-char (point-min))
2943 (while (re-search-forward org-table-any-line-regexp nil t)
2944 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2945 (beginning-of-line 1)
2946 (if (looking-at org-table-line-regexp)
2947 (save-excursion (funcall function)))
2948 (re-search-forward org-table-any-border-regexp nil 1))))
2949 (message "Mapping tables: done"))
2951 ;; Declare and autoload functions from org-exp.el & Co
2953 (declare-function org-default-export-plist "org-exp")
2954 (declare-function org-infile-export-plist "org-exp")
2955 (declare-function org-get-current-options "org-exp")
2956 (eval-and-compile
2957 (org-autoload "org-exp"
2958 '(org-export org-export-visible
2959 org-insert-export-options-template
2960 org-table-clean-before-export))
2961 (org-autoload "org-ascii"
2962 '(org-export-as-ascii org-export-ascii-preprocess))
2963 (org-autoload "org-html"
2964 '(org-export-as-html-and-open
2965 org-export-as-html-batch org-export-as-html-to-buffer
2966 org-replace-region-by-html org-export-region-as-html
2967 org-export-as-html))
2968 (org-autoload "org-icalendar"
2969 '(org-export-icalendar-this-file
2970 org-export-icalendar-all-agenda-files
2971 org-export-icalendar-combine-agenda-files))
2972 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
2974 ;; Declare and autoload functions from org-agenda.el
2976 (eval-and-compile
2977 (org-autoload "org-agenda"
2978 '(org-agenda org-agenda-list org-search-view
2979 org-todo-list org-tags-view org-agenda-list-stuck-projects
2980 org-diary org-agenda-to-appt
2981 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2983 ;; Autoload org-remember
2985 (eval-and-compile
2986 (org-autoload "org-remember"
2987 '(org-remember-insinuate org-remember-annotation
2988 org-remember-apply-template org-remember org-remember-handler)))
2990 ;; Autoload org-clock.el
2993 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2994 (beg end))
2995 (declare-function org-clock-update-mode-line "org-clock" ())
2996 (defvar org-clock-start-time)
2997 (defvar org-clock-marker (make-marker)
2998 "Marker recording the last clock-in.")
3000 (eval-and-compile
3001 (org-autoload
3002 "org-clock"
3003 '(org-clock-in org-clock-out org-clock-cancel
3004 org-clock-goto org-clock-sum org-clock-display
3005 org-clock-remove-overlays org-clock-report
3006 org-clocktable-shift org-dblock-write:clocktable
3007 org-get-clocktable)))
3009 (defun org-clock-update-time-maybe ()
3010 "If this is a CLOCK line, update it and return t.
3011 Otherwise, return nil."
3012 (interactive)
3013 (save-excursion
3014 (beginning-of-line 1)
3015 (skip-chars-forward " \t")
3016 (when (looking-at org-clock-string)
3017 (let ((re (concat "[ \t]*" org-clock-string
3018 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3019 "\\([ \t]*=>.*\\)?\\)?"))
3020 ts te h m s neg)
3021 (cond
3022 ((not (looking-at re))
3023 nil)
3024 ((not (match-end 2))
3025 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3026 (> org-clock-marker (point))
3027 (<= org-clock-marker (point-at-eol)))
3028 ;; The clock is running here
3029 (setq org-clock-start-time
3030 (apply 'encode-time
3031 (org-parse-time-string (match-string 1))))
3032 (org-clock-update-mode-line)))
3034 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3035 (end-of-line 1)
3036 (setq ts (match-string 1)
3037 te (match-string 3))
3038 (setq s (- (time-to-seconds
3039 (apply 'encode-time (org-parse-time-string te)))
3040 (time-to-seconds
3041 (apply 'encode-time (org-parse-time-string ts))))
3042 neg (< s 0)
3043 s (abs s)
3044 h (floor (/ s 3600))
3045 s (- s (* 3600 h))
3046 m (floor (/ s 60))
3047 s (- s (* 60 s)))
3048 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3049 t))))))
3051 (defun org-check-running-clock ()
3052 "Check if the current buffer contains the running clock.
3053 If yes, offer to stop it and to save the buffer with the changes."
3054 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3055 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3056 (buffer-name))))
3057 (org-clock-out)
3058 (when (y-or-n-p "Save changed buffer?")
3059 (save-buffer))))
3061 (defun org-clocktable-try-shift (dir n)
3062 "Check if this line starts a clock table, if yes, shift the time block."
3063 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3064 (org-clocktable-shift dir n)))
3066 ;; Autoload org-timer.el
3068 (eval-and-compile
3069 (org-autoload
3070 "org-timer"
3071 '(org-timer-start org-timer org-timer-item
3072 org-timer-change-times-in-region)))
3074 ;; Autoload org-feed.el
3076 (eval-and-compile
3077 (org-autoload
3078 "org-feed"
3079 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3082 ;; Autoload archiving code
3083 ;; The stuff that is needed for cycling and tags has to be defined here.
3085 (defgroup org-archive nil
3086 "Options concerning archiving in Org-mode."
3087 :tag "Org Archive"
3088 :group 'org-structure)
3090 (defcustom org-archive-location "%s_archive::"
3091 "The location where subtrees should be archived.
3093 The value of this variable is a string, consisting of two parts,
3094 separated by a double-colon. The first part is a filename and
3095 the second part is a headline.
3097 When the filename is omitted, archiving happens in the same file.
3098 %s in the filename will be replaced by the current file
3099 name (without the directory part). Archiving to a different file
3100 is useful to keep archived entries from contributing to the
3101 Org-mode Agenda.
3103 The archived entries will be filed as subtrees of the specified
3104 headline. When the headline is omitted, the subtrees are simply
3105 filed away at the end of the file, as top-level entries. Also in
3106 the heading you can use %s to represent the file name, this can be
3107 useful when using the same archive for a number of different files.
3109 Here are a few examples:
3110 \"%s_archive::\"
3111 If the current file is Projects.org, archive in file
3112 Projects.org_archive, as top-level trees. This is the default.
3114 \"::* Archived Tasks\"
3115 Archive in the current file, under the top-level headline
3116 \"* Archived Tasks\".
3118 \"~/org/archive.org::\"
3119 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3121 \"~/org/archive.org::From %s\"
3122 Archive in file ~/org/archive.org (absolute path), und headlines
3123 \"From FILENAME\" where file name is the current file name.
3125 \"basement::** Finished Tasks\"
3126 Archive in file ./basement (relative path), as level 3 trees
3127 below the level 2 heading \"** Finished Tasks\".
3129 You may set this option on a per-file basis by adding to the buffer a
3130 line like
3132 #+ARCHIVE: basement::** Finished Tasks
3134 You may also define it locally for a subtree by setting an ARCHIVE property
3135 in the entry. If such a property is found in an entry, or anywhere up
3136 the hierarchy, it will be used."
3137 :group 'org-archive
3138 :type 'string)
3140 (defcustom org-archive-tag "ARCHIVE"
3141 "The tag that marks a subtree as archived.
3142 An archived subtree does not open during visibility cycling, and does
3143 not contribute to the agenda listings.
3144 After changing this, font-lock must be restarted in the relevant buffers to
3145 get the proper fontification."
3146 :group 'org-archive
3147 :group 'org-keywords
3148 :type 'string)
3150 (defcustom org-agenda-skip-archived-trees t
3151 "Non-nil means, the agenda will skip any items located in archived trees.
3152 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3153 variable is no longer recommended, you should leave it at the value t.
3154 Instead, use the key `v' to cycle the archives-mode in the agenda."
3155 :group 'org-archive
3156 :group 'org-agenda-skip
3157 :type 'boolean)
3159 (defcustom org-columns-skip-arrchived-trees t
3160 "Non-nil means, irgnore archived trees when creating column view."
3161 :group 'org-archive
3162 :group 'org-properties
3163 :type 'boolean)
3165 (defcustom org-cycle-open-archived-trees nil
3166 "Non-nil means, `org-cycle' will open archived trees.
3167 An archived tree is a tree marked with the tag ARCHIVE.
3168 When nil, archived trees will stay folded. You can still open them with
3169 normal outline commands like `show-all', but not with the cycling commands."
3170 :group 'org-archive
3171 :group 'org-cycle
3172 :type 'boolean)
3174 (defcustom org-sparse-tree-open-archived-trees nil
3175 "Non-nil means sparse tree construction shows matches in archived trees.
3176 When nil, matches in these trees are highlighted, but the trees are kept in
3177 collapsed state."
3178 :group 'org-archive
3179 :group 'org-sparse-trees
3180 :type 'boolean)
3182 (defun org-cycle-hide-archived-subtrees (state)
3183 "Re-hide all archived subtrees after a visibility state change."
3184 (when (and (not org-cycle-open-archived-trees)
3185 (not (memq state '(overview folded))))
3186 (save-excursion
3187 (let* ((globalp (memq state '(contents all)))
3188 (beg (if globalp (point-min) (point)))
3189 (end (if globalp (point-max) (org-end-of-subtree t))))
3190 (org-hide-archived-subtrees beg end)
3191 (goto-char beg)
3192 (if (looking-at (concat ".*:" org-archive-tag ":"))
3193 (message "%s" (substitute-command-keys
3194 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3196 (defun org-force-cycle-archived ()
3197 "Cycle subtree even if it is archived."
3198 (interactive)
3199 (setq this-command 'org-cycle)
3200 (let ((org-cycle-open-archived-trees t))
3201 (call-interactively 'org-cycle)))
3203 (defun org-hide-archived-subtrees (beg end)
3204 "Re-hide all archived subtrees after a visibility state change."
3205 (save-excursion
3206 (let* ((re (concat ":" org-archive-tag ":")))
3207 (goto-char beg)
3208 (while (re-search-forward re end t)
3209 (and (org-on-heading-p) (hide-subtree))
3210 (org-end-of-subtree t)))))
3212 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3214 (eval-and-compile
3215 (org-autoload "org-archive"
3216 '(org-add-archive-files org-archive-subtree
3217 org-archive-to-archive-sibling org-toggle-archive-tag)))
3219 ;; Autoload Column View Code
3221 (declare-function org-columns-number-to-string "org-colview")
3222 (declare-function org-columns-get-format-and-top-level "org-colview")
3223 (declare-function org-columns-compute "org-colview")
3225 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3226 '(org-columns-number-to-string org-columns-get-format-and-top-level
3227 org-columns-compute org-agenda-columns org-columns-remove-overlays
3228 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3230 ;; Autoload ID code
3232 (declare-function org-id-store-link "org-id")
3233 (declare-function org-id-locations-load "org-id")
3234 (declare-function org-id-locations-save "org-id")
3235 (defvar org-id-track-globally)
3236 (org-autoload "org-id"
3237 '(org-id-get-create org-id-new org-id-copy org-id-get
3238 org-id-get-with-outline-path-completion
3239 org-id-get-with-outline-drilling
3240 org-id-goto org-id-find org-id-store-link))
3242 ;; Autoload Plotting Code
3244 (org-autoload "org-plot"
3245 '(org-plot/gnuplot))
3247 ;;; Variables for pre-computed regular expressions, all buffer local
3249 (defvar org-drawer-regexp nil
3250 "Matches first line of a hidden block.")
3251 (make-variable-buffer-local 'org-drawer-regexp)
3252 (defvar org-todo-regexp nil
3253 "Matches any of the TODO state keywords.")
3254 (make-variable-buffer-local 'org-todo-regexp)
3255 (defvar org-not-done-regexp nil
3256 "Matches any of the TODO state keywords except the last one.")
3257 (make-variable-buffer-local 'org-not-done-regexp)
3258 (defvar org-not-done-heading-regexp nil
3259 "Matches a TODO headline that is not done.")
3260 (make-variable-buffer-local 'org-not-done-regexp)
3261 (defvar org-todo-line-regexp nil
3262 "Matches a headline and puts TODO state into group 2 if present.")
3263 (make-variable-buffer-local 'org-todo-line-regexp)
3264 (defvar org-complex-heading-regexp nil
3265 "Matches a headline and puts everything into groups:
3266 group 1: the stars
3267 group 2: The todo keyword, maybe
3268 group 3: Priority cookie
3269 group 4: True headline
3270 group 5: Tags")
3271 (make-variable-buffer-local 'org-complex-heading-regexp)
3272 (defvar org-todo-line-tags-regexp nil
3273 "Matches a headline and puts TODO state into group 2 if present.
3274 Also put tags into group 4 if tags are present.")
3275 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3276 (defvar org-nl-done-regexp nil
3277 "Matches newline followed by a headline with the DONE keyword.")
3278 (make-variable-buffer-local 'org-nl-done-regexp)
3279 (defvar org-looking-at-done-regexp nil
3280 "Matches the DONE keyword a point.")
3281 (make-variable-buffer-local 'org-looking-at-done-regexp)
3282 (defvar org-ds-keyword-length 12
3283 "Maximum length of the Deadline and SCHEDULED keywords.")
3284 (make-variable-buffer-local 'org-ds-keyword-length)
3285 (defvar org-deadline-regexp nil
3286 "Matches the DEADLINE keyword.")
3287 (make-variable-buffer-local 'org-deadline-regexp)
3288 (defvar org-deadline-time-regexp nil
3289 "Matches the DEADLINE keyword together with a time stamp.")
3290 (make-variable-buffer-local 'org-deadline-time-regexp)
3291 (defvar org-deadline-line-regexp nil
3292 "Matches the DEADLINE keyword and the rest of the line.")
3293 (make-variable-buffer-local 'org-deadline-line-regexp)
3294 (defvar org-scheduled-regexp nil
3295 "Matches the SCHEDULED keyword.")
3296 (make-variable-buffer-local 'org-scheduled-regexp)
3297 (defvar org-scheduled-time-regexp nil
3298 "Matches the SCHEDULED keyword together with a time stamp.")
3299 (make-variable-buffer-local 'org-scheduled-time-regexp)
3300 (defvar org-closed-time-regexp nil
3301 "Matches the CLOSED keyword together with a time stamp.")
3302 (make-variable-buffer-local 'org-closed-time-regexp)
3304 (defvar org-keyword-time-regexp nil
3305 "Matches any of the 4 keywords, together with the time stamp.")
3306 (make-variable-buffer-local 'org-keyword-time-regexp)
3307 (defvar org-keyword-time-not-clock-regexp nil
3308 "Matches any of the 3 keywords, together with the time stamp.")
3309 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3310 (defvar org-maybe-keyword-time-regexp nil
3311 "Matches a timestamp, possibly preceeded by a keyword.")
3312 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3313 (defvar org-planning-or-clock-line-re nil
3314 "Matches a line with planning or clock info.")
3315 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3317 (defconst org-plain-time-of-day-regexp
3318 (concat
3319 "\\(\\<[012]?[0-9]"
3320 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3321 "\\(--?"
3322 "\\(\\<[012]?[0-9]"
3323 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3324 "\\)?")
3325 "Regular expression to match a plain time or time range.
3326 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3327 groups carry important information:
3328 0 the full match
3329 1 the first time, range or not
3330 8 the second time, if it is a range.")
3332 (defconst org-plain-time-extension-regexp
3333 (concat
3334 "\\(\\<[012]?[0-9]"
3335 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3336 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3337 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3338 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3339 groups carry important information:
3340 0 the full match
3341 7 hours of duration
3342 9 minutes of duration")
3344 (defconst org-stamp-time-of-day-regexp
3345 (concat
3346 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3347 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3348 "\\(--?"
3349 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3350 "Regular expression to match a timestamp time or time range.
3351 After a match, the following groups carry important information:
3352 0 the full match
3353 1 date plus weekday, for backreferencing to make sure both times on same day
3354 2 the first time, range or not
3355 4 the second time, if it is a range.")
3357 (defconst org-startup-options
3358 '(("fold" org-startup-folded t)
3359 ("overview" org-startup-folded t)
3360 ("nofold" org-startup-folded nil)
3361 ("showall" org-startup-folded nil)
3362 ("content" org-startup-folded content)
3363 ("hidestars" org-hide-leading-stars t)
3364 ("showstars" org-hide-leading-stars nil)
3365 ("odd" org-odd-levels-only t)
3366 ("oddeven" org-odd-levels-only nil)
3367 ("align" org-startup-align-all-tables t)
3368 ("noalign" org-startup-align-all-tables nil)
3369 ("customtime" org-display-custom-times t)
3370 ("logdone" org-log-done time)
3371 ("lognotedone" org-log-done note)
3372 ("nologdone" org-log-done nil)
3373 ("lognoteclock-out" org-log-note-clock-out t)
3374 ("nolognoteclock-out" org-log-note-clock-out nil)
3375 ("logrepeat" org-log-repeat state)
3376 ("lognoterepeat" org-log-repeat note)
3377 ("nologrepeat" org-log-repeat nil)
3378 ("fninline" org-footnote-define-inline t)
3379 ("nofninline" org-footnote-define-inline nil)
3380 ("fnlocal" org-footnote-section nil)
3381 ("fnauto" org-footnote-auto-label t)
3382 ("fnprompt" org-footnote-auto-label nil)
3383 ("fnconfirm" org-footnote-auto-label confirm)
3384 ("fnplain" org-footnote-auto-label plain)
3385 ("constcgs" constants-unit-system cgs)
3386 ("constSI" constants-unit-system SI)
3387 ("noptag" org-tag-persistent-alist nil))
3388 "Variable associated with STARTUP options for org-mode.
3389 Each element is a list of three items: The startup options as written
3390 in the #+STARTUP line, the corresponding variable, and the value to
3391 set this variable to if the option is found. An optional forth element PUSH
3392 means to push this value onto the list in the variable.")
3394 (defun org-set-regexps-and-options ()
3395 "Precompute regular expressions for current buffer."
3396 (when (org-mode-p)
3397 (org-set-local 'org-todo-kwd-alist nil)
3398 (org-set-local 'org-todo-key-alist nil)
3399 (org-set-local 'org-todo-key-trigger nil)
3400 (org-set-local 'org-todo-keywords-1 nil)
3401 (org-set-local 'org-done-keywords nil)
3402 (org-set-local 'org-todo-heads nil)
3403 (org-set-local 'org-todo-sets nil)
3404 (org-set-local 'org-todo-log-states nil)
3405 (org-set-local 'org-file-properties nil)
3406 (org-set-local 'org-file-tags nil)
3407 (let ((re (org-make-options-regexp
3408 '("CATEGORY" "TODO" "COLUMNS"
3409 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3410 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3411 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3412 (splitre "[ \t]+")
3413 kwds kws0 kwsa key log value cat arch tags const links hw dws
3414 tail sep kws1 prio props ftags drawers
3415 ext-setup-or-nil setup-contents (start 0))
3416 (save-excursion
3417 (save-restriction
3418 (widen)
3419 (goto-char (point-min))
3420 (while (or (and ext-setup-or-nil
3421 (string-match re ext-setup-or-nil start)
3422 (setq start (match-end 0)))
3423 (and (setq ext-setup-or-nil nil start 0)
3424 (re-search-forward re nil t)))
3425 (setq key (upcase (match-string 1 ext-setup-or-nil))
3426 value (org-match-string-no-properties 2 ext-setup-or-nil))
3427 (cond
3428 ((equal key "CATEGORY")
3429 (if (string-match "[ \t]+$" value)
3430 (setq value (replace-match "" t t value)))
3431 (setq cat value))
3432 ((member key '("SEQ_TODO" "TODO"))
3433 (push (cons 'sequence (org-split-string value splitre)) kwds))
3434 ((equal key "TYP_TODO")
3435 (push (cons 'type (org-split-string value splitre)) kwds))
3436 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3437 ;; general TODO-like setup
3438 (push (cons (intern (downcase (match-string 1 key)))
3439 (org-split-string value splitre)) kwds))
3440 ((equal key "TAGS")
3441 (setq tags (append tags (if tags '("\\n") nil)
3442 (org-split-string value splitre))))
3443 ((equal key "COLUMNS")
3444 (org-set-local 'org-columns-default-format value))
3445 ((equal key "LINK")
3446 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3447 (push (cons (match-string 1 value)
3448 (org-trim (match-string 2 value)))
3449 links)))
3450 ((equal key "PRIORITIES")
3451 (setq prio (org-split-string value " +")))
3452 ((equal key "PROPERTY")
3453 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3454 (push (cons (match-string 1 value) (match-string 2 value))
3455 props)))
3456 ((equal key "FILETAGS")
3457 (when (string-match "\\S-" value)
3458 (setq ftags
3459 (append
3460 ftags
3461 (apply 'append
3462 (mapcar (lambda (x) (org-split-string x ":"))
3463 (org-split-string value)))))))
3464 ((equal key "DRAWERS")
3465 (setq drawers (org-split-string value splitre)))
3466 ((equal key "CONSTANTS")
3467 (setq const (append const (org-split-string value splitre))))
3468 ((equal key "STARTUP")
3469 (let ((opts (org-split-string value splitre))
3470 l var val)
3471 (while (setq l (pop opts))
3472 (when (setq l (assoc l org-startup-options))
3473 (setq var (nth 1 l) val (nth 2 l))
3474 (if (not (nth 3 l))
3475 (set (make-local-variable var) val)
3476 (if (not (listp (symbol-value var)))
3477 (set (make-local-variable var) nil))
3478 (set (make-local-variable var) (symbol-value var))
3479 (add-to-list var val))))))
3480 ((equal key "ARCHIVE")
3481 (string-match " *$" value)
3482 (setq arch (replace-match "" t t value))
3483 (remove-text-properties 0 (length arch)
3484 '(face t fontified t) arch))
3485 ((equal key "SETUPFILE")
3486 (setq setup-contents (org-file-contents
3487 (expand-file-name
3488 (org-remove-double-quotes value))
3489 'noerror))
3490 (if (not ext-setup-or-nil)
3491 (setq ext-setup-or-nil setup-contents start 0)
3492 (setq ext-setup-or-nil
3493 (concat (substring ext-setup-or-nil 0 start)
3494 "\n" setup-contents "\n"
3495 (substring ext-setup-or-nil start)))))
3496 ))))
3497 (when cat
3498 (org-set-local 'org-category (intern cat))
3499 (push (cons "CATEGORY" cat) props))
3500 (when prio
3501 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3502 (setq prio (mapcar 'string-to-char prio))
3503 (org-set-local 'org-highest-priority (nth 0 prio))
3504 (org-set-local 'org-lowest-priority (nth 1 prio))
3505 (org-set-local 'org-default-priority (nth 2 prio)))
3506 (and props (org-set-local 'org-file-properties (nreverse props)))
3507 (and ftags (org-set-local 'org-file-tags
3508 (mapcar 'org-add-prop-inherited ftags)))
3509 (and drawers (org-set-local 'org-drawers drawers))
3510 (and arch (org-set-local 'org-archive-location arch))
3511 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3512 ;; Process the TODO keywords
3513 (unless kwds
3514 ;; Use the global values as if they had been given locally.
3515 (setq kwds (default-value 'org-todo-keywords))
3516 (if (stringp (car kwds))
3517 (setq kwds (list (cons org-todo-interpretation
3518 (default-value 'org-todo-keywords)))))
3519 (setq kwds (reverse kwds)))
3520 (setq kwds (nreverse kwds))
3521 (let (inter kws kw)
3522 (while (setq kws (pop kwds))
3523 (let ((kws (or
3524 (run-hook-with-args-until-success
3525 'org-todo-setup-filter-hook kws)
3526 kws)))
3527 (setq inter (pop kws) sep (member "|" kws)
3528 kws0 (delete "|" (copy-sequence kws))
3529 kwsa nil
3530 kws1 (mapcar
3531 (lambda (x)
3532 ;; 1 2
3533 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3534 (progn
3535 (setq kw (match-string 1 x)
3536 key (and (match-end 2) (match-string 2 x))
3537 log (org-extract-log-state-settings x))
3538 (push (cons kw (and key (string-to-char key))) kwsa)
3539 (and log (push log org-todo-log-states))
3541 (error "Invalid TODO keyword %s" x)))
3542 kws0)
3543 kwsa (if kwsa (append '((:startgroup))
3544 (nreverse kwsa)
3545 '((:endgroup))))
3546 hw (car kws1)
3547 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3548 tail (list inter hw (car dws) (org-last dws))))
3549 (add-to-list 'org-todo-heads hw 'append)
3550 (push kws1 org-todo-sets)
3551 (setq org-done-keywords (append org-done-keywords dws nil))
3552 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3553 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3554 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3555 (setq org-todo-sets (nreverse org-todo-sets)
3556 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3557 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3558 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3559 ;; Process the constants
3560 (when const
3561 (let (e cst)
3562 (while (setq e (pop const))
3563 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3564 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3565 (setq org-table-formula-constants-local cst)))
3567 ;; Process the tags.
3568 (when tags
3569 (let (e tgs)
3570 (while (setq e (pop tags))
3571 (cond
3572 ((equal e "{") (push '(:startgroup) tgs))
3573 ((equal e "}") (push '(:endgroup) tgs))
3574 ((equal e "\\n") (push '(:newline) tgs))
3575 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3576 (push (cons (match-string 1 e)
3577 (string-to-char (match-string 2 e)))
3578 tgs))
3579 (t (push (list e) tgs))))
3580 (org-set-local 'org-tag-alist nil)
3581 (while (setq e (pop tgs))
3582 (or (and (stringp (car e))
3583 (assoc (car e) org-tag-alist))
3584 (push e org-tag-alist)))))
3586 ;; Compute the regular expressions and other local variables
3587 (if (not org-done-keywords)
3588 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3589 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3590 (length org-scheduled-string)
3591 (length org-clock-string)
3592 (length org-closed-string)))
3593 org-drawer-regexp
3594 (concat "^[ \t]*:\\("
3595 (mapconcat 'regexp-quote org-drawers "\\|")
3596 "\\):[ \t]*$")
3597 org-not-done-keywords
3598 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3599 org-todo-regexp
3600 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3601 "\\|") "\\)\\>")
3602 org-not-done-regexp
3603 (concat "\\<\\("
3604 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3605 "\\)\\>")
3606 org-not-done-heading-regexp
3607 (concat "^\\(\\*+\\)[ \t]+\\("
3608 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3609 "\\)\\>")
3610 org-todo-line-regexp
3611 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3612 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3613 "\\)\\>\\)?[ \t]*\\(.*\\)")
3614 org-complex-heading-regexp
3615 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3616 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3617 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3618 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3619 org-nl-done-regexp
3620 (concat "\n\\*+[ \t]+"
3621 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3622 "\\)" "\\>")
3623 org-todo-line-tags-regexp
3624 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3625 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3626 (org-re
3627 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3628 org-looking-at-done-regexp
3629 (concat "^" "\\(?:"
3630 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3631 "\\>")
3632 org-deadline-regexp (concat "\\<" org-deadline-string)
3633 org-deadline-time-regexp
3634 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3635 org-deadline-line-regexp
3636 (concat "\\<\\(" org-deadline-string "\\).*")
3637 org-scheduled-regexp
3638 (concat "\\<" org-scheduled-string)
3639 org-scheduled-time-regexp
3640 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3641 org-closed-time-regexp
3642 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3643 org-keyword-time-regexp
3644 (concat "\\<\\(" org-scheduled-string
3645 "\\|" org-deadline-string
3646 "\\|" org-closed-string
3647 "\\|" org-clock-string "\\)"
3648 " *[[<]\\([^]>]+\\)[]>]")
3649 org-keyword-time-not-clock-regexp
3650 (concat "\\<\\(" org-scheduled-string
3651 "\\|" org-deadline-string
3652 "\\|" org-closed-string
3653 "\\)"
3654 " *[[<]\\([^]>]+\\)[]>]")
3655 org-maybe-keyword-time-regexp
3656 (concat "\\(\\<\\(" org-scheduled-string
3657 "\\|" org-deadline-string
3658 "\\|" org-closed-string
3659 "\\|" org-clock-string "\\)\\)?"
3660 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3661 org-planning-or-clock-line-re
3662 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3663 "\\|" org-deadline-string
3664 "\\|" org-closed-string "\\|" org-clock-string
3665 "\\)\\>\\)")
3667 (org-compute-latex-and-specials-regexp)
3668 (org-set-font-lock-defaults))))
3670 (defun org-file-contents (file &optional noerror)
3671 "Return the contents of FILE, as a string."
3672 (if (or (not file)
3673 (not (file-readable-p file)))
3674 (if noerror
3675 (progn
3676 (message "Cannot read file %s" file)
3677 (ding) (sit-for 2)
3679 (error "Cannot read file %s" file))
3680 (with-temp-buffer
3681 (insert-file-contents file)
3682 (buffer-string))))
3684 (defun org-extract-log-state-settings (x)
3685 "Extract the log state setting from a TODO keyword string.
3686 This will extract info from a string like \"WAIT(w@/!)\"."
3687 (let (kw key log1 log2)
3688 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3689 (setq kw (match-string 1 x)
3690 key (and (match-end 2) (match-string 2 x))
3691 log1 (and (match-end 3) (match-string 3 x))
3692 log2 (and (match-end 4) (match-string 4 x)))
3693 (and (or log1 log2)
3694 (list kw
3695 (and log1 (if (equal log1 "!") 'time 'note))
3696 (and log2 (if (equal log2 "!") 'time 'note)))))))
3698 (defun org-remove-keyword-keys (list)
3699 "Remove a pair of parenthesis at the end of each string in LIST."
3700 (mapcar (lambda (x)
3701 (if (string-match "(.*)$" x)
3702 (substring x 0 (match-beginning 0))
3704 list))
3706 ;; FIXME: this could be done much better, using second characters etc.
3707 (defun org-assign-fast-keys (alist)
3708 "Assign fast keys to a keyword-key alist.
3709 Respect keys that are already there."
3710 (let (new e k c c1 c2 (char ?a))
3711 (while (setq e (pop alist))
3712 (cond
3713 ((equal e '(:startgroup)) (push e new))
3714 ((equal e '(:endgroup)) (push e new))
3715 ((equal e '(:newline)) (push e new))
3717 (setq k (car e) c2 nil)
3718 (if (cdr e)
3719 (setq c (cdr e))
3720 ;; automatically assign a character.
3721 (setq c1 (string-to-char
3722 (downcase (substring
3723 k (if (= (string-to-char k) ?@) 1 0)))))
3724 (if (or (rassoc c1 new) (rassoc c1 alist))
3725 (while (or (rassoc char new) (rassoc char alist))
3726 (setq char (1+ char)))
3727 (setq c2 c1))
3728 (setq c (or c2 char)))
3729 (push (cons k c) new))))
3730 (nreverse new)))
3732 ;;; Some variables used in various places
3734 (defvar org-window-configuration nil
3735 "Used in various places to store a window configuration.")
3736 (defvar org-finish-function nil
3737 "Function to be called when `C-c C-c' is used.
3738 This is for getting out of special buffers like remember.")
3741 ;; FIXME: Occasionally check by commenting these, to make sure
3742 ;; no other functions uses these, forgetting to let-bind them.
3743 (defvar entry)
3744 (defvar state)
3745 (defvar last-state)
3746 (defvar date)
3747 (defvar description)
3749 ;; Defined somewhere in this file, but used before definition.
3750 (defvar org-html-entities)
3751 (defvar org-struct-menu)
3752 (defvar org-org-menu)
3753 (defvar org-tbl-menu)
3754 (defvar org-agenda-keymap)
3756 ;;;; Define the Org-mode
3758 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3759 (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."))
3762 ;; We use a before-change function to check if a table might need
3763 ;; an update.
3764 (defvar org-table-may-need-update t
3765 "Indicates that a table might need an update.
3766 This variable is set by `org-before-change-function'.
3767 `org-table-align' sets it back to nil.")
3768 (defun org-before-change-function (beg end)
3769 "Every change indicates that a table might need an update."
3770 (setq org-table-may-need-update t))
3771 (defvar org-mode-map)
3772 (defvar org-mode-hook nil
3773 "Mode hook for Org-mode, run after the mode was turned on.")
3774 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3775 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3776 (defvar org-table-buffer-is-an nil)
3777 (defconst org-outline-regexp "\\*+ ")
3779 ;;;###autoload
3780 (define-derived-mode org-mode outline-mode "Org"
3781 "Outline-based notes management and organizer, alias
3782 \"Carsten's outline-mode for keeping track of everything.\"
3784 Org-mode develops organizational tasks around a NOTES file which
3785 contains information about projects as plain text. Org-mode is
3786 implemented on top of outline-mode, which is ideal to keep the content
3787 of large files well structured. It supports ToDo items, deadlines and
3788 time stamps, which magically appear in the diary listing of the Emacs
3789 calendar. Tables are easily created with a built-in table editor.
3790 Plain text URL-like links connect to websites, emails (VM), Usenet
3791 messages (Gnus), BBDB entries, and any files related to the project.
3792 For printing and sharing of notes, an Org-mode file (or a part of it)
3793 can be exported as a structured ASCII or HTML file.
3795 The following commands are available:
3797 \\{org-mode-map}"
3799 ;; Get rid of Outline menus, they are not needed
3800 ;; Need to do this here because define-derived-mode sets up
3801 ;; the keymap so late. Still, it is a waste to call this each time
3802 ;; we switch another buffer into org-mode.
3803 (if (featurep 'xemacs)
3804 (when (boundp 'outline-mode-menu-heading)
3805 ;; Assume this is Greg's port, it used easymenu
3806 (easy-menu-remove outline-mode-menu-heading)
3807 (easy-menu-remove outline-mode-menu-show)
3808 (easy-menu-remove outline-mode-menu-hide))
3809 (define-key org-mode-map [menu-bar headings] 'undefined)
3810 (define-key org-mode-map [menu-bar hide] 'undefined)
3811 (define-key org-mode-map [menu-bar show] 'undefined))
3813 (org-load-modules-maybe)
3814 (easy-menu-add org-org-menu)
3815 (easy-menu-add org-tbl-menu)
3816 (org-install-agenda-files-menu)
3817 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3818 (org-add-to-invisibility-spec '(org-cwidth))
3819 (when (featurep 'xemacs)
3820 (org-set-local 'line-move-ignore-invisible t))
3821 (org-set-local 'outline-regexp org-outline-regexp)
3822 (org-set-local 'outline-level 'org-outline-level)
3823 (when (and org-ellipsis
3824 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3825 (fboundp 'make-glyph-code))
3826 (unless org-display-table
3827 (setq org-display-table (make-display-table)))
3828 (set-display-table-slot
3829 org-display-table 4
3830 (vconcat (mapcar
3831 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3832 org-ellipsis)))
3833 (if (stringp org-ellipsis) org-ellipsis "..."))))
3834 (setq buffer-display-table org-display-table))
3835 (org-set-regexps-and-options)
3836 (when (and org-tag-faces (not org-tags-special-faces-re))
3837 ;; tag faces set outside customize.... force initialization.
3838 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3839 ;; Calc embedded
3840 (org-set-local 'calc-embedded-open-mode "# ")
3841 (modify-syntax-entry ?# "<")
3842 (modify-syntax-entry ?@ "w")
3843 (if org-startup-truncated (setq truncate-lines t))
3844 (org-set-local 'font-lock-unfontify-region-function
3845 'org-unfontify-region)
3846 ;; Activate before-change-function
3847 (org-set-local 'org-table-may-need-update t)
3848 (org-add-hook 'before-change-functions 'org-before-change-function nil
3849 'local)
3850 ;; Check for running clock before killing a buffer
3851 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3852 ;; Paragraphs and auto-filling
3853 (org-set-autofill-regexps)
3854 (setq indent-line-function 'org-indent-line-function)
3855 (org-update-radio-target-regexp)
3856 ;; Make sure dependence stuff works reliably, even for users who set it
3857 ;; too late :-(
3858 (if org-enforce-todo-dependencies
3859 (add-hook 'org-blocker-hook
3860 'org-block-todo-from-children-or-siblings-or-parent)
3861 (remove-hook 'org-blocker-hook
3862 'org-block-todo-from-children-or-siblings-or-parent))
3863 (if org-enforce-todo-checkbox-dependencies
3864 (add-hook 'org-blocker-hook
3865 'org-block-todo-from-checkboxes)
3866 (remove-hook 'org-blocker-hook
3867 'org-block-todo-from-checkboxes))
3869 ;; Comment characters
3870 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3871 (org-set-local 'comment-padding " ")
3873 ;; Align options lines
3874 (org-set-local
3875 'align-mode-rules-list
3876 '((org-in-buffer-settings
3877 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3878 (modes . '(org-mode)))))
3880 ;; Imenu
3881 (org-set-local 'imenu-create-index-function
3882 'org-imenu-get-tree)
3884 ;; Make isearch reveal context
3885 (if (or (featurep 'xemacs)
3886 (not (boundp 'outline-isearch-open-invisible-function)))
3887 ;; Emacs 21 and XEmacs make use of the hook
3888 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3889 ;; Emacs 22 deals with this through a special variable
3890 (org-set-local 'outline-isearch-open-invisible-function
3891 (lambda (&rest ignore) (org-show-context 'isearch))))
3893 ;; If empty file that did not turn on org-mode automatically, make it to.
3894 (if (and org-insert-mode-line-in-empty-file
3895 (interactive-p)
3896 (= (point-min) (point-max)))
3897 (insert "# -*- mode: org -*-\n\n"))
3899 (unless org-inhibit-startup
3900 (when org-startup-align-all-tables
3901 (let ((bmp (buffer-modified-p)))
3902 (org-table-map-tables 'org-table-align)
3903 (set-buffer-modified-p bmp)))
3904 (org-set-startup-visibility)))
3906 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3908 (defun org-current-time ()
3909 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3910 (if (> (car org-time-stamp-rounding-minutes) 1)
3911 (let ((r (car org-time-stamp-rounding-minutes))
3912 (time (decode-time)))
3913 (apply 'encode-time
3914 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3915 (nthcdr 2 time))))
3916 (current-time)))
3918 ;;;; Font-Lock stuff, including the activators
3920 (defvar org-mouse-map (make-sparse-keymap))
3921 (org-defkey org-mouse-map
3922 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3923 (org-defkey org-mouse-map
3924 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3925 (when org-mouse-1-follows-link
3926 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3927 (when org-tab-follows-link
3928 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3929 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3931 (require 'font-lock)
3933 (defconst org-non-link-chars "]\t\n\r<>")
3934 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3935 "shell" "elisp"))
3936 (defvar org-link-types-re nil
3937 "Matches a link that has a url-like prefix like \"http:\"")
3938 (defvar org-link-re-with-space nil
3939 "Matches a link with spaces, optional angular brackets around it.")
3940 (defvar org-link-re-with-space2 nil
3941 "Matches a link with spaces, optional angular brackets around it.")
3942 (defvar org-link-re-with-space3 nil
3943 "Matches a link with spaces, only for internal part in bracket links.")
3944 (defvar org-angle-link-re nil
3945 "Matches link with angular brackets, spaces are allowed.")
3946 (defvar org-plain-link-re nil
3947 "Matches plain link, without spaces.")
3948 (defvar org-bracket-link-regexp nil
3949 "Matches a link in double brackets.")
3950 (defvar org-bracket-link-analytic-regexp nil
3951 "Regular expression used to analyze links.
3952 Here is what the match groups contain after a match:
3953 1: http:
3954 2: http
3955 3: path
3956 4: [desc]
3957 5: desc")
3958 (defvar org-bracket-link-analytic-regexp++ nil
3959 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3960 (defvar org-any-link-re nil
3961 "Regular expression matching any link.")
3963 (defun org-make-link-regexps ()
3964 "Update the link regular expressions.
3965 This should be called after the variable `org-link-types' has changed."
3966 (setq org-link-types-re
3967 (concat
3968 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3969 org-link-re-with-space
3970 (concat
3971 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3972 "\\([^" org-non-link-chars " ]"
3973 "[^" org-non-link-chars "]*"
3974 "[^" org-non-link-chars " ]\\)>?")
3975 org-link-re-with-space2
3976 (concat
3977 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3978 "\\([^" org-non-link-chars " ]"
3979 "[^\t\n\r]*"
3980 "[^" org-non-link-chars " ]\\)>?")
3981 org-link-re-with-space3
3982 (concat
3983 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3984 "\\([^" org-non-link-chars " ]"
3985 "[^\t\n\r]*\\)")
3986 org-angle-link-re
3987 (concat
3988 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3989 "\\([^" org-non-link-chars " ]"
3990 "[^" org-non-link-chars "]*"
3991 "\\)>")
3992 org-plain-link-re
3993 (concat
3994 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3995 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3996 org-bracket-link-regexp
3997 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3998 org-bracket-link-analytic-regexp
3999 (concat
4000 "\\[\\["
4001 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4002 "\\([^]]+\\)"
4003 "\\]"
4004 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4005 "\\]")
4006 org-bracket-link-analytic-regexp++
4007 (concat
4008 "\\[\\["
4009 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4010 "\\([^]]+\\)"
4011 "\\]"
4012 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4013 "\\]")
4014 org-any-link-re
4015 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4016 org-angle-link-re "\\)\\|\\("
4017 org-plain-link-re "\\)")))
4019 (org-make-link-regexps)
4021 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4022 "Regular expression for fast time stamp matching.")
4023 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4024 "Regular expression for fast time stamp matching.")
4025 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4026 "Regular expression matching time strings for analysis.
4027 This one does not require the space after the date, so it can be used
4028 on a string that terminates immediately after the date.")
4029 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4030 "Regular expression matching time strings for analysis.")
4031 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4032 "Regular expression matching time stamps, with groups.")
4033 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4034 "Regular expression matching time stamps (also [..]), with groups.")
4035 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4036 "Regular expression matching a time stamp range.")
4037 (defconst org-tr-regexp-both
4038 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4039 "Regular expression matching a time stamp range.")
4040 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4041 org-ts-regexp "\\)?")
4042 "Regular expression matching a time stamp or time stamp range.")
4043 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4044 org-ts-regexp-both "\\)?")
4045 "Regular expression matching a time stamp or time stamp range.
4046 The time stamps may be either active or inactive.")
4048 (defvar org-emph-face nil)
4050 (defun org-do-emphasis-faces (limit)
4051 "Run through the buffer and add overlays to links."
4052 (let (rtn)
4053 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4054 (if (not (= (char-after (match-beginning 3))
4055 (char-after (match-beginning 4))))
4056 (progn
4057 (setq rtn t)
4058 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4059 'face
4060 (nth 1 (assoc (match-string 3)
4061 org-emphasis-alist)))
4062 (add-text-properties (match-beginning 2) (match-end 2)
4063 '(font-lock-multiline t))
4064 (when org-hide-emphasis-markers
4065 (add-text-properties (match-end 4) (match-beginning 5)
4066 '(invisible org-link))
4067 (add-text-properties (match-beginning 3) (match-end 3)
4068 '(invisible org-link)))))
4069 (backward-char 1))
4070 rtn))
4072 (defun org-emphasize (&optional char)
4073 "Insert or change an emphasis, i.e. a font like bold or italic.
4074 If there is an active region, change that region to a new emphasis.
4075 If there is no region, just insert the marker characters and position
4076 the cursor between them.
4077 CHAR should be either the marker character, or the first character of the
4078 HTML tag associated with that emphasis. If CHAR is a space, the means
4079 to remove the emphasis of the selected region.
4080 If char is not given (for example in an interactive call) it
4081 will be prompted for."
4082 (interactive)
4083 (let ((eal org-emphasis-alist) e det
4084 (erc org-emphasis-regexp-components)
4085 (prompt "")
4086 (string "") beg end move tag c s)
4087 (if (org-region-active-p)
4088 (setq beg (region-beginning) end (region-end)
4089 string (buffer-substring beg end))
4090 (setq move t))
4092 (while (setq e (pop eal))
4093 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4094 c (aref tag 0))
4095 (push (cons c (string-to-char (car e))) det)
4096 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4097 (substring tag 1)))))
4098 (setq det (nreverse det))
4099 (unless char
4100 (message "%s" (concat "Emphasis marker or tag:" prompt))
4101 (setq char (read-char-exclusive)))
4102 (setq char (or (cdr (assoc char det)) char))
4103 (if (equal char ?\ )
4104 (setq s "" move nil)
4105 (unless (assoc (char-to-string char) org-emphasis-alist)
4106 (error "No such emphasis marker: \"%c\"" char))
4107 (setq s (char-to-string char)))
4108 (while (and (> (length string) 1)
4109 (equal (substring string 0 1) (substring string -1))
4110 (assoc (substring string 0 1) org-emphasis-alist))
4111 (setq string (substring string 1 -1)))
4112 (setq string (concat s string s))
4113 (if beg (delete-region beg end))
4114 (unless (or (bolp)
4115 (string-match (concat "[" (nth 0 erc) "\n]")
4116 (char-to-string (char-before (point)))))
4117 (insert " "))
4118 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4119 (char-to-string (char-after (point))))
4120 (insert " ") (backward-char 1))
4121 (insert string)
4122 (and move (backward-char 1))))
4124 (defconst org-nonsticky-props
4125 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4127 (defsubst org-rear-nonsticky-at (pos)
4128 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4130 (defun org-activate-plain-links (limit)
4131 "Run through the buffer and add overlays to links."
4132 (catch 'exit
4133 (let (f)
4134 (while (re-search-forward org-plain-link-re limit t)
4135 (setq f (get-text-property (match-beginning 0) 'face))
4136 (if (or (eq f 'org-tag)
4137 (and (listp f) (memq 'org-tag f)))
4139 (add-text-properties (match-beginning 0) (match-end 0)
4140 (list 'mouse-face 'highlight
4141 'keymap org-mouse-map))
4142 (org-rear-nonsticky-at (match-end 0))
4143 (throw 'exit t))))))
4145 (defun org-activate-code (limit)
4146 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4147 (progn
4148 (remove-text-properties (match-beginning 0) (match-end 0)
4149 '(display t invisible t intangible t))
4150 t)))
4152 (defun org-activate-angle-links (limit)
4153 "Run through the buffer and add overlays to links."
4154 (if (re-search-forward org-angle-link-re limit t)
4155 (progn
4156 (add-text-properties (match-beginning 0) (match-end 0)
4157 (list 'mouse-face 'highlight
4158 'keymap org-mouse-map))
4159 (org-rear-nonsticky-at (match-end 0))
4160 t)))
4162 (defun org-activate-footnote-links (limit)
4163 "Run through the buffer and add overlays to links."
4164 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4165 limit t)
4166 (progn
4167 (add-text-properties (match-beginning 2) (match-end 2)
4168 (list 'mouse-face 'highlight
4169 'keymap org-mouse-map
4170 'help-echo
4171 (if (= (point-at-bol) (match-beginning 2))
4172 "Footnote definition"
4173 "Footnote reference")
4175 (org-rear-nonsticky-at (match-end 2))
4176 t)))
4178 (defun org-activate-bracket-links (limit)
4179 "Run through the buffer and add overlays to bracketed links."
4180 (if (re-search-forward org-bracket-link-regexp limit t)
4181 (let* ((help (concat "LINK: "
4182 (org-match-string-no-properties 1)))
4183 ;; FIXME: above we should remove the escapes.
4184 ;; but that requires another match, protecting match data,
4185 ;; a lot of overhead for font-lock.
4186 (ip (org-maybe-intangible
4187 (list 'invisible 'org-link
4188 'keymap org-mouse-map 'mouse-face 'highlight
4189 'font-lock-multiline t 'help-echo help)))
4190 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4191 'font-lock-multiline t 'help-echo help)))
4192 ;; We need to remove the invisible property here. Table narrowing
4193 ;; may have made some of this invisible.
4194 (remove-text-properties (match-beginning 0) (match-end 0)
4195 '(invisible nil))
4196 (if (match-end 3)
4197 (progn
4198 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4199 (org-rear-nonsticky-at (match-beginning 3))
4200 (add-text-properties (match-beginning 3) (match-end 3) vp)
4201 (org-rear-nonsticky-at (match-end 3))
4202 (add-text-properties (match-end 3) (match-end 0) ip)
4203 (org-rear-nonsticky-at (match-end 0)))
4204 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4205 (org-rear-nonsticky-at (match-beginning 1))
4206 (add-text-properties (match-beginning 1) (match-end 1) vp)
4207 (org-rear-nonsticky-at (match-end 1))
4208 (add-text-properties (match-end 1) (match-end 0) ip)
4209 (org-rear-nonsticky-at (match-end 0)))
4210 t)))
4212 (defun org-activate-dates (limit)
4213 "Run through the buffer and add overlays to dates."
4214 (if (re-search-forward org-tsr-regexp-both limit t)
4215 (progn
4216 (add-text-properties (match-beginning 0) (match-end 0)
4217 (list 'mouse-face 'highlight
4218 'keymap org-mouse-map))
4219 (org-rear-nonsticky-at (match-end 0))
4220 (when org-display-custom-times
4221 (if (match-end 3)
4222 (org-display-custom-time (match-beginning 3) (match-end 3)))
4223 (org-display-custom-time (match-beginning 1) (match-end 1)))
4224 t)))
4226 (defvar org-target-link-regexp nil
4227 "Regular expression matching radio targets in plain text.")
4228 (make-variable-buffer-local 'org-target-link-regexp)
4229 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4230 "Regular expression matching a link target.")
4231 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4232 "Regular expression matching a radio target.")
4233 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4234 "Regular expression matching any target.")
4236 (defun org-activate-target-links (limit)
4237 "Run through the buffer and add overlays to target matches."
4238 (when org-target-link-regexp
4239 (let ((case-fold-search t))
4240 (if (re-search-forward org-target-link-regexp limit t)
4241 (progn
4242 (add-text-properties (match-beginning 0) (match-end 0)
4243 (list 'mouse-face 'highlight
4244 'keymap org-mouse-map
4245 'help-echo "Radio target link"
4246 'org-linked-text t))
4247 (org-rear-nonsticky-at (match-end 0))
4248 t)))))
4250 (defun org-update-radio-target-regexp ()
4251 "Find all radio targets in this file and update the regular expression."
4252 (interactive)
4253 (when (memq 'radio org-activate-links)
4254 (setq org-target-link-regexp
4255 (org-make-target-link-regexp (org-all-targets 'radio)))
4256 (org-restart-font-lock)))
4258 (defun org-hide-wide-columns (limit)
4259 (let (s e)
4260 (setq s (text-property-any (point) (or limit (point-max))
4261 'org-cwidth t))
4262 (when s
4263 (setq e (next-single-property-change s 'org-cwidth))
4264 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4265 (goto-char e)
4266 t)))
4268 (defvar org-latex-and-specials-regexp nil
4269 "Regular expression for highlighting export special stuff.")
4270 (defvar org-match-substring-regexp)
4271 (defvar org-match-substring-with-braces-regexp)
4272 (defvar org-export-html-special-string-regexps)
4274 (defun org-compute-latex-and-specials-regexp ()
4275 "Compute regular expression for stuff treated specially by exporters."
4276 (if (not org-highlight-latex-fragments-and-specials)
4277 (org-set-local 'org-latex-and-specials-regexp nil)
4278 (require 'org-exp)
4279 (let*
4280 ((matchers (plist-get org-format-latex-options :matchers))
4281 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4282 org-latex-regexps)))
4283 (options (org-combine-plists (org-default-export-plist)
4284 (org-infile-export-plist)))
4285 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4286 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4287 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4288 (org-export-html-expand (plist-get options :expand-quoted-html))
4289 (org-export-with-special-strings (plist-get options :special-strings))
4290 (re-sub
4291 (cond
4292 ((equal org-export-with-sub-superscripts '{})
4293 (list org-match-substring-with-braces-regexp))
4294 (org-export-with-sub-superscripts
4295 (list org-match-substring-regexp))
4296 (t nil)))
4297 (re-latex
4298 (if org-export-with-LaTeX-fragments
4299 (mapcar (lambda (x) (nth 1 x)) latexs)))
4300 (re-macros
4301 (if org-export-with-TeX-macros
4302 (list (concat "\\\\"
4303 (regexp-opt
4304 (append (mapcar 'car org-html-entities)
4305 (if (boundp 'org-latex-entities)
4306 org-latex-entities nil))
4307 'words))) ; FIXME
4309 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4310 (re-special (if org-export-with-special-strings
4311 (mapcar (lambda (x) (car x))
4312 org-export-html-special-string-regexps)))
4313 (re-rest
4314 (delq nil
4315 (list
4316 (if org-export-html-expand "@<[^>\n]+>")
4317 ))))
4318 (org-set-local
4319 'org-latex-and-specials-regexp
4320 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4321 re-rest) "\\|")))))
4323 (defun org-do-latex-and-special-faces (limit)
4324 "Run through the buffer and add overlays to links."
4325 (when org-latex-and-specials-regexp
4326 (let (rtn d)
4327 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4328 limit t))
4329 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4330 'face))
4331 '(org-code org-verbatim underline)))
4332 (progn
4333 (setq rtn t
4334 d (cond ((member (char-after (1+ (match-beginning 0)))
4335 '(?_ ?^)) 1)
4336 (t 0)))
4337 (font-lock-prepend-text-property
4338 (+ d (match-beginning 0)) (match-end 0)
4339 'face 'org-latex-and-export-specials)
4340 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4341 '(font-lock-multiline t)))))
4342 rtn)))
4344 (defun org-restart-font-lock ()
4345 "Restart font-lock-mode, to force refontification."
4346 (when (and (boundp 'font-lock-mode) font-lock-mode)
4347 (font-lock-mode -1)
4348 (font-lock-mode 1)))
4350 (defun org-all-targets (&optional radio)
4351 "Return a list of all targets in this file.
4352 With optional argument RADIO, only find radio targets."
4353 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4354 rtn)
4355 (save-excursion
4356 (goto-char (point-min))
4357 (while (re-search-forward re nil t)
4358 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4359 rtn)))
4361 (defun org-make-target-link-regexp (targets)
4362 "Make regular expression matching all strings in TARGETS.
4363 The regular expression finds the targets also if there is a line break
4364 between words."
4365 (and targets
4366 (concat
4367 "\\<\\("
4368 (mapconcat
4369 (lambda (x)
4370 (while (string-match " +" x)
4371 (setq x (replace-match "\\s-+" t t x)))
4373 targets
4374 "\\|")
4375 "\\)\\>")))
4377 (defun org-activate-tags (limit)
4378 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4379 (progn
4380 (add-text-properties (match-beginning 1) (match-end 1)
4381 (list 'mouse-face 'highlight
4382 'keymap org-mouse-map))
4383 (org-rear-nonsticky-at (match-end 1))
4384 t)))
4386 (defun org-outline-level ()
4387 (save-excursion
4388 (looking-at outline-regexp)
4389 (if (match-beginning 1)
4390 (+ (org-get-string-indentation (match-string 1)) 1000)
4391 (1- (- (match-end 0) (match-beginning 0))))))
4393 (defvar org-font-lock-keywords nil)
4395 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4396 "Regular expression matching a property line.")
4398 (defvar org-font-lock-hook nil
4399 "Functions to be called for special font lock stuff.")
4401 (defun org-font-lock-hook (limit)
4402 (run-hook-with-args 'org-font-lock-hook limit))
4404 (defun org-set-font-lock-defaults ()
4405 (let* ((em org-fontify-emphasized-text)
4406 (lk org-activate-links)
4407 (org-font-lock-extra-keywords
4408 (list
4409 ;; Call the hook
4410 '(org-font-lock-hook)
4411 ;; Headlines
4412 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4413 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4414 ;; Table lines
4415 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4416 (1 'org-table t))
4417 ;; Table internals
4418 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4419 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4420 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4421 ;; Drawers
4422 (list org-drawer-regexp '(0 'org-special-keyword t))
4423 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4424 ;; Properties
4425 (list org-property-re
4426 '(1 'org-special-keyword t)
4427 '(3 'org-property-value t))
4428 (if org-format-transports-properties-p
4429 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4430 ;; Links
4431 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4432 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4433 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4434 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4435 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4436 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4437 (if (memq 'footnote lk) '(org-activate-footnote-links
4438 (2 'org-footnote t)))
4439 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4440 '(org-hide-wide-columns (0 nil append))
4441 ;; TODO lines
4442 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4443 '(1 (org-get-todo-face 1) t))
4444 ;; DONE
4445 (if org-fontify-done-headline
4446 (list (concat "^[*]+ +\\<\\("
4447 (mapconcat 'regexp-quote org-done-keywords "\\|")
4448 "\\)\\(.*\\)")
4449 '(2 'org-headline-done t))
4450 nil)
4451 ;; Priorities
4452 '(org-font-lock-add-priority-faces)
4453 ;; Tags
4454 '(org-font-lock-add-tag-faces)
4455 ;; Special keywords
4456 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4457 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4458 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4459 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4460 ;; Emphasis
4461 (if em
4462 (if (featurep 'xemacs)
4463 '(org-do-emphasis-faces (0 nil append))
4464 '(org-do-emphasis-faces)))
4465 ;; Checkboxes
4466 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4467 2 'org-checkbox prepend)
4468 (if org-provide-checkbox-statistics
4469 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4470 (0 (org-get-checkbox-statistics-face) t)))
4471 ;; Description list items
4472 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4473 2 'bold prepend)
4474 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4475 '(1 'org-archived prepend))
4476 ;; Specials
4477 '(org-do-latex-and-special-faces)
4478 ;; Code
4479 '(org-activate-code (1 'org-code t))
4480 ;; COMMENT
4481 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4482 "\\|" org-quote-string "\\)\\>")
4483 '(1 'org-special-keyword t))
4484 '("^#.*" (0 'font-lock-comment-face t))
4486 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4487 ;; Now set the full font-lock-keywords
4488 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4489 (org-set-local 'font-lock-defaults
4490 '(org-font-lock-keywords t nil nil backward-paragraph))
4491 (kill-local-variable 'font-lock-keywords) nil))
4493 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4494 "Fontify string S like in Org-mode"
4495 (with-temp-buffer
4496 (insert s)
4497 (let ((org-odd-levels-only odd-levels))
4498 (org-mode)
4499 (font-lock-fontify-buffer)
4500 (buffer-string))))
4502 (defvar org-m nil)
4503 (defvar org-l nil)
4504 (defvar org-f nil)
4505 (defun org-get-level-face (n)
4506 "Get the right face for match N in font-lock matching of headlines."
4507 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4508 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4509 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4510 (cond
4511 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4512 ((eq n 2) org-f)
4513 (t (if org-level-color-stars-only nil org-f))))
4515 (defun org-get-todo-face (kwd)
4516 "Get the right face for a TODO keyword KWD.
4517 If KWD is a number, get the corresponding match group."
4518 (if (numberp kwd) (setq kwd (match-string kwd)))
4519 (or (cdr (assoc kwd org-todo-keyword-faces))
4520 (and (member kwd org-done-keywords) 'org-done)
4521 'org-todo))
4523 (defun org-font-lock-add-tag-faces (limit)
4524 "Add the special tag faces."
4525 (when (and org-tag-faces org-tags-special-faces-re)
4526 (while (re-search-forward org-tags-special-faces-re limit t)
4527 (add-text-properties (match-beginning 1) (match-end 1)
4528 (list 'face (org-get-tag-face 1)
4529 'font-lock-fontified t))
4530 (backward-char 1))))
4532 (defun org-font-lock-add-priority-faces (limit)
4533 "Add the special priority faces."
4534 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4535 (add-text-properties
4536 (match-beginning 0) (match-end 0)
4537 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4538 org-priority-faces))
4539 'org-special-keyword)
4540 'font-lock-fontified t))))
4542 (defun org-get-tag-face (kwd)
4543 "Get the right face for a TODO keyword KWD.
4544 If KWD is a number, get the corresponding match group."
4545 (if (numberp kwd) (setq kwd (match-string kwd)))
4546 (or (cdr (assoc kwd org-tag-faces))
4547 'org-tag))
4549 (defun org-unfontify-region (beg end &optional maybe_loudly)
4550 "Remove fontification and activation overlays from links."
4551 (font-lock-default-unfontify-region beg end)
4552 (let* ((buffer-undo-list t)
4553 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4554 (inhibit-modification-hooks t)
4555 deactivate-mark buffer-file-name buffer-file-truename)
4556 (remove-text-properties beg end
4557 '(mouse-face t keymap t org-linked-text t
4558 invisible t intangible t))))
4560 ;;;; Visibility cycling, including org-goto and indirect buffer
4562 ;;; Cycling
4564 (defvar org-cycle-global-status nil)
4565 (make-variable-buffer-local 'org-cycle-global-status)
4566 (defvar org-cycle-subtree-status nil)
4567 (make-variable-buffer-local 'org-cycle-subtree-status)
4569 ;;;###autoload
4571 (defvar org-inlinetask-min-level)
4573 (defun org-cycle (&optional arg)
4574 "TAB-action and visibility cycling for Org-mode.
4576 This is the command invoked in Org-moe by the TAB key. It's main purpose
4577 is outine visibility cycling, but it also invokes other actions
4578 in special contexts.
4580 - When this function is called with a prefix argument, rotate the entire
4581 buffer through 3 states (global cycling)
4582 1. OVERVIEW: Show only top-level headlines.
4583 2. CONTENTS: Show all headlines of all levels, but no body text.
4584 3. SHOW ALL: Show everything.
4585 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4586 determined by the variable `org-startup-folded', and by any VISIBILITY
4587 properties in the buffer.
4588 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4589 including any drawers.
4591 - When inside a table, re-align the table and move to the next field.
4593 - When point is at the beginning of a headline, rotate the subtree started
4594 by this line through 3 different states (local cycling)
4595 1. FOLDED: Only the main headline is shown.
4596 2. CHILDREN: The main headline and the direct children are shown.
4597 From this state, you can move to one of the children
4598 and zoom in further.
4599 3. SUBTREE: Show the entire subtree, including body text.
4601 - When there is a numeric prefix, go up to a heading with level ARG, do
4602 a `show-subtree' and return to the previous cursor position. If ARG
4603 is negative, go up that many levels.
4605 - When point is not at the beginning of a headline, execute the global
4606 binding for TAB, which is re-indenting the line. See the option
4607 `org-cycle-emulate-tab' for details.
4609 - Special case: if point is at the beginning of the buffer and there is
4610 no headline in line 1, this function will act as if called with prefix arg.
4611 But only if also the variable `org-cycle-global-at-bob' is t."
4612 (interactive "P")
4613 (org-load-modules-maybe)
4614 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4615 (let* ((limit-level
4616 (or org-cycle-max-level
4617 (and (boundp 'org-inlinetask-min-level)
4618 org-inlinetask-min-level
4619 (1- org-inlinetask-min-level))))
4620 (nstars (and limit-level
4621 (if org-odd-levels-only
4622 (and limit-level (1- (* limit-level 2)))
4623 limit-level)))
4624 (outline-regexp
4625 (cond
4626 ((not (org-mode-p)) outline-regexp)
4627 (org-cycle-include-plain-lists
4628 (concat "\\(?:\\*"
4629 (if nstars (format "\\{1,%d\\} " nstars) "+")
4630 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4631 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4632 (bob-special (and org-cycle-global-at-bob (bobp)
4633 (not (looking-at outline-regexp))))
4634 (org-cycle-hook
4635 (if bob-special
4636 (delq 'org-optimize-window-after-visibility-change
4637 (copy-sequence org-cycle-hook))
4638 org-cycle-hook))
4639 (pos (point)))
4641 (if (or bob-special (equal arg '(4)))
4642 ;; special case: use global cycling
4643 (setq arg t))
4645 (cond
4647 ((equal arg '(16))
4648 (org-set-startup-visibility)
4649 (message "Startup visibility, plus VISIBILITY properties"))
4651 ((equal arg '(64))
4652 (show-all)
4653 (message "Entire buffer visible, including drawers"))
4655 ((org-at-table-p 'any)
4656 ;; Enter the table or move to the next field in the table
4657 (or (org-table-recognize-table.el)
4658 (progn
4659 (if arg (org-table-edit-field t)
4660 (org-table-justify-field-maybe)
4661 (call-interactively 'org-table-next-field)))))
4663 ((run-hook-with-args-until-success
4664 'org-tab-after-check-for-table-hook))
4666 ((eq arg t) ;; Global cycling
4667 (org-cycle-internal-global))
4669 ((and org-drawers org-drawer-regexp
4670 (save-excursion
4671 (beginning-of-line 1)
4672 (looking-at org-drawer-regexp)))
4673 ;; Toggle block visibility
4674 (org-flag-drawer
4675 (not (get-char-property (match-end 0) 'invisible))))
4677 ((integerp arg)
4678 ;; Show-subtree, ARG levels up from here.
4679 (save-excursion
4680 (org-back-to-heading)
4681 (outline-up-heading (if (< arg 0) (- arg)
4682 (- (funcall outline-level) arg)))
4683 (org-show-subtree)))
4685 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4686 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4688 (org-cycle-internal-local))
4690 ;; TAB emulation and template completion
4691 (buffer-read-only (org-back-to-heading))
4693 ((run-hook-with-args-until-success
4694 'org-tab-after-check-for-cycling-hook))
4696 ((org-try-structure-completion))
4698 ((org-try-cdlatex-tab))
4700 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4701 (or (not (bolp))
4702 (not (looking-at outline-regexp))))
4703 (call-interactively (global-key-binding "\t")))
4705 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4706 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4707 (or (and (eq org-cycle-emulate-tab 'white)
4708 (= (match-end 0) (point-at-eol)))
4709 (and (eq org-cycle-emulate-tab 'whitestart)
4710 (>= (match-end 0) pos))))
4712 (eq org-cycle-emulate-tab t))
4713 (call-interactively (global-key-binding "\t")))
4715 (t (save-excursion
4716 (org-back-to-heading)
4717 (org-cycle)))))))
4719 (defun org-cycle-internal-global ()
4720 "Do the global cycling action."
4721 (cond
4722 ((and (eq last-command this-command)
4723 (eq org-cycle-global-status 'overview))
4724 ;; We just created the overview - now do table of contents
4725 ;; This can be slow in very large buffers, so indicate action
4726 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4727 (message "CONTENTS...")
4728 (org-content)
4729 (message "CONTENTS...done")
4730 (setq org-cycle-global-status 'contents)
4731 (run-hook-with-args 'org-cycle-hook 'contents))
4733 ((and (eq last-command this-command)
4734 (eq org-cycle-global-status 'contents))
4735 ;; We just showed the table of contents - now show everything
4736 (run-hook-with-args 'org-pre-cycle-hook 'all)
4737 (show-all)
4738 (message "SHOW ALL")
4739 (setq org-cycle-global-status 'all)
4740 (run-hook-with-args 'org-cycle-hook 'all))
4743 ;; Default action: go to overview
4744 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4745 (org-overview)
4746 (message "OVERVIEW")
4747 (setq org-cycle-global-status 'overview)
4748 (run-hook-with-args 'org-cycle-hook 'overview))))
4750 (defun org-cycle-internal-local ()
4751 "Do the local cycling action."
4752 (org-back-to-heading)
4753 (let ((goal-column 0) eoh eol eos)
4754 ;; First, some boundaries
4755 (save-excursion
4756 (org-back-to-heading)
4757 (save-excursion
4758 (beginning-of-line 2)
4759 (while (and (not (eobp)) ;; this is like `next-line'
4760 (get-char-property (1- (point)) 'invisible))
4761 (beginning-of-line 2)) (setq eol (point)))
4762 (outline-end-of-heading) (setq eoh (point))
4763 (org-end-of-subtree t)
4764 (unless (eobp)
4765 (skip-chars-forward " \t\n")
4766 (beginning-of-line 1) ; in case this is an item
4768 (setq eos (1- (point))))
4769 ;; Find out what to do next and set `this-command'
4770 (cond
4771 ((= eos eoh)
4772 ;; Nothing is hidden behind this heading
4773 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4774 (message "EMPTY ENTRY")
4775 (setq org-cycle-subtree-status nil)
4776 (save-excursion
4777 (goto-char eos)
4778 (outline-next-heading)
4779 (if (org-invisible-p) (org-flag-heading nil))))
4780 ((or (>= eol eos)
4781 (not (string-match "\\S-" (buffer-substring eol eos))))
4782 ;; Entire subtree is hidden in one line: open it
4783 (run-hook-with-args 'org-pre-cycle-hook 'children)
4784 (org-show-entry)
4785 (show-children)
4786 (message "CHILDREN")
4787 (save-excursion
4788 (goto-char eos)
4789 (outline-next-heading)
4790 (if (org-invisible-p) (org-flag-heading nil)))
4791 (setq org-cycle-subtree-status 'children)
4792 (run-hook-with-args 'org-cycle-hook 'children))
4793 ((and (eq last-command this-command)
4794 (eq org-cycle-subtree-status 'children))
4795 ;; We just showed the children, now show everything.
4796 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
4797 (org-show-subtree)
4798 (message "SUBTREE")
4799 (setq org-cycle-subtree-status 'subtree)
4800 (run-hook-with-args 'org-cycle-hook 'subtree))
4802 ;; Default action: hide the subtree.
4803 (run-hook-with-args 'org-pre-cycle-hook 'folded)
4804 (hide-subtree)
4805 (message "FOLDED")
4806 (setq org-cycle-subtree-status 'folded)
4807 (run-hook-with-args 'org-cycle-hook 'folded)))))
4809 ;;;###autoload
4810 (defun org-global-cycle (&optional arg)
4811 "Cycle the global visibility. For details see `org-cycle'.
4812 With C-u prefix arg, switch to startup visibility.
4813 With a numeric prefix, show all headlines up to that level."
4814 (interactive "P")
4815 (let ((org-cycle-include-plain-lists
4816 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4817 (cond
4818 ((integerp arg)
4819 (show-all)
4820 (hide-sublevels arg)
4821 (setq org-cycle-global-status 'contents))
4822 ((equal arg '(4))
4823 (org-set-startup-visibility)
4824 (message "Startup visibility, plus VISIBILITY properties."))
4826 (org-cycle '(4))))))
4828 (defun org-set-startup-visibility ()
4829 "Set the visibility required by startup options and properties."
4830 (cond
4831 ((eq org-startup-folded t)
4832 (org-cycle '(4)))
4833 ((eq org-startup-folded 'content)
4834 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4835 (org-cycle '(4)) (org-cycle '(4)))))
4836 (org-set-visibility-according-to-property 'no-cleanup)
4837 (org-cycle-hide-archived-subtrees 'all)
4838 (org-cycle-hide-drawers 'all)
4839 (org-cycle-show-empty-lines 'all))
4841 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4842 "Switch subtree visibilities according to :VISIBILITY: property."
4843 (interactive)
4844 (let (org-show-entry-below state)
4845 (save-excursion
4846 (goto-char (point-min))
4847 (while (re-search-forward
4848 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4849 nil t)
4850 (setq state (match-string 1))
4851 (save-excursion
4852 (org-back-to-heading t)
4853 (hide-subtree)
4854 (org-reveal)
4855 (cond
4856 ((equal state '("fold" "folded"))
4857 (hide-subtree))
4858 ((equal state "children")
4859 (org-show-hidden-entry)
4860 (show-children))
4861 ((equal state "content")
4862 (save-excursion
4863 (save-restriction
4864 (org-narrow-to-subtree)
4865 (org-content))))
4866 ((member state '("all" "showall"))
4867 (show-subtree)))))
4868 (unless no-cleanup
4869 (org-cycle-hide-archived-subtrees 'all)
4870 (org-cycle-hide-drawers 'all)
4871 (org-cycle-show-empty-lines 'all)))))
4873 (defun org-overview ()
4874 "Switch to overview mode, showing only top-level headlines.
4875 Really, this shows all headlines with level equal or greater than the level
4876 of the first headline in the buffer. This is important, because if the
4877 first headline is not level one, then (hide-sublevels 1) gives confusing
4878 results."
4879 (interactive)
4880 (let ((level (save-excursion
4881 (goto-char (point-min))
4882 (if (re-search-forward (concat "^" outline-regexp) nil t)
4883 (progn
4884 (goto-char (match-beginning 0))
4885 (funcall outline-level))))))
4886 (and level (hide-sublevels level))))
4888 (defun org-content (&optional arg)
4889 "Show all headlines in the buffer, like a table of contents.
4890 With numerical argument N, show content up to level N."
4891 (interactive "P")
4892 (save-excursion
4893 ;; Visit all headings and show their offspring
4894 (and (integerp arg) (org-overview))
4895 (goto-char (point-max))
4896 (catch 'exit
4897 (while (and (progn (condition-case nil
4898 (outline-previous-visible-heading 1)
4899 (error (goto-char (point-min))))
4901 (looking-at outline-regexp))
4902 (if (integerp arg)
4903 (show-children (1- arg))
4904 (show-branches))
4905 (if (bobp) (throw 'exit nil))))))
4908 (defun org-optimize-window-after-visibility-change (state)
4909 "Adjust the window after a change in outline visibility.
4910 This function is the default value of the hook `org-cycle-hook'."
4911 (when (get-buffer-window (current-buffer))
4912 (cond
4913 ((eq state 'content) nil)
4914 ((eq state 'all) nil)
4915 ((eq state 'folded) nil)
4916 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4917 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4919 (defun org-compact-display-after-subtree-move ()
4920 "Show a compacter version of the tree of the entry's parent."
4921 (save-excursion
4922 (if (org-up-heading-safe)
4923 (progn
4924 (hide-subtree)
4925 (show-entry)
4926 (show-children)
4927 (org-cycle-show-empty-lines 'children)
4928 (org-cycle-hide-drawers 'children))
4929 (org-overview))))
4931 (defun org-cycle-show-empty-lines (state)
4932 "Show empty lines above all visible headlines.
4933 The region to be covered depends on STATE when called through
4934 `org-cycle-hook'. Lisp program can use t for STATE to get the
4935 entire buffer covered. Note that an empty line is only shown if there
4936 are at least `org-cycle-separator-lines' empty lines before the headline."
4937 (when (> org-cycle-separator-lines 0)
4938 (save-excursion
4939 (let* ((n org-cycle-separator-lines)
4940 (re (cond
4941 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4942 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4943 (t (let ((ns (number-to-string (- n 2))))
4944 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4945 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4946 beg end)
4947 (cond
4948 ((memq state '(overview contents t))
4949 (setq beg (point-min) end (point-max)))
4950 ((memq state '(children folded))
4951 (setq beg (point) end (progn (org-end-of-subtree t t)
4952 (beginning-of-line 2)
4953 (point)))))
4954 (when beg
4955 (goto-char beg)
4956 (while (re-search-forward re end t)
4957 (if (not (get-char-property (match-end 1) 'invisible))
4958 (outline-flag-region
4959 (match-beginning 1) (match-end 1) nil)))))))
4960 ;; Never hide empty lines at the end of the file.
4961 (save-excursion
4962 (goto-char (point-max))
4963 (outline-previous-heading)
4964 (outline-end-of-heading)
4965 (if (and (looking-at "[ \t\n]+")
4966 (= (match-end 0) (point-max)))
4967 (outline-flag-region (point) (match-end 0) nil))))
4969 (defun org-show-empty-lines-in-parent ()
4970 "Move to the parent and re-show empty lines before visible headlines."
4971 (save-excursion
4972 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4973 (org-cycle-show-empty-lines context))))
4975 (defun org-cycle-hide-drawers (state)
4976 "Re-hide all drawers after a visibility state change."
4977 (when (and (org-mode-p)
4978 (not (memq state '(overview folded))))
4979 (save-excursion
4980 (let* ((globalp (memq state '(contents all)))
4981 (beg (if globalp (point-min) (point)))
4982 (end (if globalp (point-max) (org-end-of-subtree t))))
4983 (goto-char beg)
4984 (while (re-search-forward org-drawer-regexp end t)
4985 (org-flag-drawer t))))))
4987 (defun org-flag-drawer (flag)
4988 (save-excursion
4989 (beginning-of-line 1)
4990 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4991 (let ((b (match-end 0))
4992 (outline-regexp org-outline-regexp))
4993 (if (re-search-forward
4994 "^[ \t]*:END:"
4995 (save-excursion (outline-next-heading) (point)) t)
4996 (outline-flag-region b (point-at-eol) flag)
4997 (error ":END: line missing"))))))
4999 (defun org-subtree-end-visible-p ()
5000 "Is the end of the current subtree visible?"
5001 (pos-visible-in-window-p
5002 (save-excursion (org-end-of-subtree t) (point))))
5004 (defun org-first-headline-recenter (&optional N)
5005 "Move cursor to the first headline and recenter the headline.
5006 Optional argument N means, put the headline into the Nth line of the window."
5007 (goto-char (point-min))
5008 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5009 (beginning-of-line)
5010 (recenter (prefix-numeric-value N))))
5012 ;;; Org-goto
5014 (defvar org-goto-window-configuration nil)
5015 (defvar org-goto-marker nil)
5016 (defvar org-goto-map
5017 (let ((map (make-sparse-keymap)))
5018 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5019 (while (setq cmd (pop cmds))
5020 (substitute-key-definition cmd cmd map global-map)))
5021 (suppress-keymap map)
5022 (org-defkey map "\C-m" 'org-goto-ret)
5023 (org-defkey map [(return)] 'org-goto-ret)
5024 (org-defkey map [(left)] 'org-goto-left)
5025 (org-defkey map [(right)] 'org-goto-right)
5026 (org-defkey map [(control ?g)] 'org-goto-quit)
5027 (org-defkey map "\C-i" 'org-cycle)
5028 (org-defkey map [(tab)] 'org-cycle)
5029 (org-defkey map [(down)] 'outline-next-visible-heading)
5030 (org-defkey map [(up)] 'outline-previous-visible-heading)
5031 (if org-goto-auto-isearch
5032 (if (fboundp 'define-key-after)
5033 (define-key-after map [t] 'org-goto-local-auto-isearch)
5034 nil)
5035 (org-defkey map "q" 'org-goto-quit)
5036 (org-defkey map "n" 'outline-next-visible-heading)
5037 (org-defkey map "p" 'outline-previous-visible-heading)
5038 (org-defkey map "f" 'outline-forward-same-level)
5039 (org-defkey map "b" 'outline-backward-same-level)
5040 (org-defkey map "u" 'outline-up-heading))
5041 (org-defkey map "/" 'org-occur)
5042 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5043 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5044 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5045 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5046 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5047 map))
5049 (defconst org-goto-help
5050 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5051 RET=jump to location [Q]uit and return to previous location
5052 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5054 (defvar org-goto-start-pos) ; dynamically scoped parameter
5056 ;; FIXME: Docstring doe not mention both interfaces
5057 (defun org-goto (&optional alternative-interface)
5058 "Look up a different location in the current file, keeping current visibility.
5060 When you want look-up or go to a different location in a document, the
5061 fastest way is often to fold the entire buffer and then dive into the tree.
5062 This method has the disadvantage, that the previous location will be folded,
5063 which may not be what you want.
5065 This command works around this by showing a copy of the current buffer
5066 in an indirect buffer, in overview mode. You can dive into the tree in
5067 that copy, use org-occur and incremental search to find a location.
5068 When pressing RET or `Q', the command returns to the original buffer in
5069 which the visibility is still unchanged. After RET is will also jump to
5070 the location selected in the indirect buffer and expose the
5071 the headline hierarchy above."
5072 (interactive "P")
5073 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5074 (org-refile-use-outline-path t)
5075 (org-refile-target-verify-function nil)
5076 (interface
5077 (if (not alternative-interface)
5078 org-goto-interface
5079 (if (eq org-goto-interface 'outline)
5080 'outline-path-completion
5081 'outline)))
5082 (org-goto-start-pos (point))
5083 (selected-point
5084 (if (eq interface 'outline)
5085 (car (org-get-location (current-buffer) org-goto-help))
5086 (nth 3 (org-refile-get-location "Goto: ")))))
5087 (if selected-point
5088 (progn
5089 (org-mark-ring-push org-goto-start-pos)
5090 (goto-char selected-point)
5091 (if (or (org-invisible-p) (org-invisible-p2))
5092 (org-show-context 'org-goto)))
5093 (message "Quit"))))
5095 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5096 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5097 (defvar org-goto-local-auto-isearch-map) ; defined below
5099 (defun org-get-location (buf help)
5100 "Let the user select a location in the Org-mode buffer BUF.
5101 This function uses a recursive edit. It returns the selected position
5102 or nil."
5103 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5104 (isearch-hide-immediately nil)
5105 (isearch-search-fun-function
5106 (lambda () 'org-goto-local-search-headings))
5107 (org-goto-selected-point org-goto-exit-command))
5108 (save-excursion
5109 (save-window-excursion
5110 (delete-other-windows)
5111 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5112 (switch-to-buffer
5113 (condition-case nil
5114 (make-indirect-buffer (current-buffer) "*org-goto*")
5115 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5116 (with-output-to-temp-buffer "*Help*"
5117 (princ help))
5118 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5119 (setq buffer-read-only nil)
5120 (let ((org-startup-truncated t)
5121 (org-startup-folded nil)
5122 (org-startup-align-all-tables nil))
5123 (org-mode)
5124 (org-overview))
5125 (setq buffer-read-only t)
5126 (if (and (boundp 'org-goto-start-pos)
5127 (integer-or-marker-p org-goto-start-pos))
5128 (let ((org-show-hierarchy-above t)
5129 (org-show-siblings t)
5130 (org-show-following-heading t))
5131 (goto-char org-goto-start-pos)
5132 (and (org-invisible-p) (org-show-context)))
5133 (goto-char (point-min)))
5134 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5135 (message "Select location and press RET")
5136 (use-local-map org-goto-map)
5137 (recursive-edit)
5139 (kill-buffer "*org-goto*")
5140 (cons org-goto-selected-point org-goto-exit-command)))
5142 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5143 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5144 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5145 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5147 (defun org-goto-local-search-headings (string bound noerror)
5148 "Search and make sure that any matches are in headlines."
5149 (catch 'return
5150 (while (if isearch-forward
5151 (search-forward string bound noerror)
5152 (search-backward string bound noerror))
5153 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5154 (and (member :headline context)
5155 (not (member :tags context))))
5156 (throw 'return (point))))))
5158 (defun org-goto-local-auto-isearch ()
5159 "Start isearch."
5160 (interactive)
5161 (goto-char (point-min))
5162 (let ((keys (this-command-keys)))
5163 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5164 (isearch-mode t)
5165 (isearch-process-search-char (string-to-char keys)))))
5167 (defun org-goto-ret (&optional arg)
5168 "Finish `org-goto' by going to the new location."
5169 (interactive "P")
5170 (setq org-goto-selected-point (point)
5171 org-goto-exit-command 'return)
5172 (throw 'exit nil))
5174 (defun org-goto-left ()
5175 "Finish `org-goto' by going to the new location."
5176 (interactive)
5177 (if (org-on-heading-p)
5178 (progn
5179 (beginning-of-line 1)
5180 (setq org-goto-selected-point (point)
5181 org-goto-exit-command 'left)
5182 (throw 'exit nil))
5183 (error "Not on a heading")))
5185 (defun org-goto-right ()
5186 "Finish `org-goto' by going to the new location."
5187 (interactive)
5188 (if (org-on-heading-p)
5189 (progn
5190 (setq org-goto-selected-point (point)
5191 org-goto-exit-command 'right)
5192 (throw 'exit nil))
5193 (error "Not on a heading")))
5195 (defun org-goto-quit ()
5196 "Finish `org-goto' without cursor motion."
5197 (interactive)
5198 (setq org-goto-selected-point nil)
5199 (setq org-goto-exit-command 'quit)
5200 (throw 'exit nil))
5202 ;;; Indirect buffer display of subtrees
5204 (defvar org-indirect-dedicated-frame nil
5205 "This is the frame being used for indirect tree display.")
5206 (defvar org-last-indirect-buffer nil)
5208 (defun org-tree-to-indirect-buffer (&optional arg)
5209 "Create indirect buffer and narrow it to current subtree.
5210 With numerical prefix ARG, go up to this level and then take that tree.
5211 If ARG is negative, go up that many levels.
5212 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5213 indirect buffer previously made with this command, to avoid proliferation of
5214 indirect buffers. However, when you call the command with a `C-u' prefix, or
5215 when `org-indirect-buffer-display' is `new-frame', the last buffer
5216 is kept so that you can work with several indirect buffers at the same time.
5217 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5218 requests that a new frame be made for the new buffer, so that the dedicated
5219 frame is not changed."
5220 (interactive "P")
5221 (let ((cbuf (current-buffer))
5222 (cwin (selected-window))
5223 (pos (point))
5224 beg end level heading ibuf)
5225 (save-excursion
5226 (org-back-to-heading t)
5227 (when (numberp arg)
5228 (setq level (org-outline-level))
5229 (if (< arg 0) (setq arg (+ level arg)))
5230 (while (> (setq level (org-outline-level)) arg)
5231 (outline-up-heading 1 t)))
5232 (setq beg (point)
5233 heading (org-get-heading))
5234 (org-end-of-subtree t) (setq end (point)))
5235 (if (and (buffer-live-p org-last-indirect-buffer)
5236 (not (eq org-indirect-buffer-display 'new-frame))
5237 (not arg))
5238 (kill-buffer org-last-indirect-buffer))
5239 (setq ibuf (org-get-indirect-buffer cbuf)
5240 org-last-indirect-buffer ibuf)
5241 (cond
5242 ((or (eq org-indirect-buffer-display 'new-frame)
5243 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5244 (select-frame (make-frame))
5245 (delete-other-windows)
5246 (switch-to-buffer ibuf)
5247 (org-set-frame-title heading))
5248 ((eq org-indirect-buffer-display 'dedicated-frame)
5249 (raise-frame
5250 (select-frame (or (and org-indirect-dedicated-frame
5251 (frame-live-p org-indirect-dedicated-frame)
5252 org-indirect-dedicated-frame)
5253 (setq org-indirect-dedicated-frame (make-frame)))))
5254 (delete-other-windows)
5255 (switch-to-buffer ibuf)
5256 (org-set-frame-title (concat "Indirect: " heading)))
5257 ((eq org-indirect-buffer-display 'current-window)
5258 (switch-to-buffer ibuf))
5259 ((eq org-indirect-buffer-display 'other-window)
5260 (pop-to-buffer ibuf))
5261 (t (error "Invalid value.")))
5262 (if (featurep 'xemacs)
5263 (save-excursion (org-mode) (turn-on-font-lock)))
5264 (narrow-to-region beg end)
5265 (show-all)
5266 (goto-char pos)
5267 (and (window-live-p cwin) (select-window cwin))))
5269 (defun org-get-indirect-buffer (&optional buffer)
5270 (setq buffer (or buffer (current-buffer)))
5271 (let ((n 1) (base (buffer-name buffer)) bname)
5272 (while (buffer-live-p
5273 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5274 (setq n (1+ n)))
5275 (condition-case nil
5276 (make-indirect-buffer buffer bname 'clone)
5277 (error (make-indirect-buffer buffer bname)))))
5279 (defun org-set-frame-title (title)
5280 "Set the title of the current frame to the string TITLE."
5281 ;; FIXME: how to name a single frame in XEmacs???
5282 (unless (featurep 'xemacs)
5283 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5285 ;;;; Structure editing
5287 ;;; Inserting headlines
5289 (defun org-previous-line-empty-p ()
5290 (save-excursion
5291 (and (not (bobp))
5292 (or (beginning-of-line 0) t)
5293 (save-match-data
5294 (looking-at "[ \t]*$")))))
5296 (defun org-insert-heading (&optional force-heading)
5297 "Insert a new heading or item with same depth at point.
5298 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5299 If point is at the beginning of a headline, insert a sibling before the
5300 current headline. If point is not at the beginning, do not split the line,
5301 but create the new headline after the current line."
5302 (interactive "P")
5303 (if (= (buffer-size) 0)
5304 (insert "\n* ")
5305 (when (or force-heading (not (org-insert-item)))
5306 (let* ((empty-line-p nil)
5307 (head (save-excursion
5308 (condition-case nil
5309 (progn
5310 (org-back-to-heading)
5311 (setq empty-line-p (org-previous-line-empty-p))
5312 (match-string 0))
5313 (error "*"))))
5314 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5315 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5316 pos hide-previous previous-pos)
5317 (cond
5318 ((and (org-on-heading-p) (bolp)
5319 (or (bobp)
5320 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5321 ;; insert before the current line
5322 (open-line (if blank 2 1)))
5323 ((and (bolp)
5324 (or (bobp)
5325 (save-excursion
5326 (backward-char 1) (not (org-invisible-p)))))
5327 ;; insert right here
5328 nil)
5330 ;; somewhere in the line
5331 (save-excursion
5332 (setq previous-pos (point-at-bol))
5333 (end-of-line)
5334 (setq hide-previous (org-invisible-p)))
5335 (and org-insert-heading-respect-content (org-show-subtree))
5336 (let ((split
5337 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5338 (save-excursion
5339 (let ((p (point)))
5340 (goto-char (point-at-bol))
5341 (and (looking-at org-complex-heading-regexp)
5342 (> p (match-beginning 4)))))))
5343 tags pos)
5344 (cond
5345 (org-insert-heading-respect-content
5346 (org-end-of-subtree nil t)
5347 (or (bolp) (newline))
5348 (or (org-previous-line-empty-p)
5349 (and blank (newline)))
5350 (open-line 1))
5351 ((org-on-heading-p)
5352 (when hide-previous
5353 (show-children)
5354 (org-show-entry))
5355 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5356 (setq tags (and (match-end 2) (match-string 2)))
5357 (and (match-end 1)
5358 (delete-region (match-beginning 1) (match-end 1)))
5359 (setq pos (point-at-bol))
5360 (or split (end-of-line 1))
5361 (delete-horizontal-space)
5362 (newline (if blank 2 1))
5363 (when tags
5364 (save-excursion
5365 (goto-char pos)
5366 (end-of-line 1)
5367 (insert " " tags)
5368 (org-set-tags nil 'align))))
5370 (or split (end-of-line 1))
5371 (newline (if blank 2 1)))))))
5372 (insert head) (just-one-space)
5373 (setq pos (point))
5374 (end-of-line 1)
5375 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5376 (when (and org-insert-heading-respect-content hide-previous)
5377 (save-excursion
5378 (goto-char previous-pos)
5379 (hide-subtree)))
5380 (run-hooks 'org-insert-heading-hook)))))
5382 (defun org-get-heading (&optional no-tags)
5383 "Return the heading of the current entry, without the stars."
5384 (save-excursion
5385 (org-back-to-heading t)
5386 (if (looking-at
5387 (if no-tags
5388 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5389 "\\*+[ \t]+\\([^\r\n]*\\)"))
5390 (match-string 1) "")))
5392 (defun org-heading-components ()
5393 "Return the components of the current heading.
5394 This is a list with the following elements:
5395 - the level as an integer
5396 - the reduced level, different if `org-odd-levels-only' is set.
5397 - the TODO keyword, or nil
5398 - the priority character, like ?A, or nil if no priority is given
5399 - the headline text itself, or the tags string if no headline text
5400 - the tags string, or nil."
5401 (save-excursion
5402 (org-back-to-heading t)
5403 (if (looking-at org-complex-heading-regexp)
5404 (list (length (match-string 1))
5405 (org-reduced-level (length (match-string 1)))
5406 (org-match-string-no-properties 2)
5407 (and (match-end 3) (aref (match-string 3) 2))
5408 (org-match-string-no-properties 4)
5409 (org-match-string-no-properties 5)))))
5411 (defun org-get-entry ()
5412 "Get the entry text, after heading, entire subtree."
5413 (save-excursion
5414 (org-back-to-heading t)
5415 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5417 (defun org-insert-heading-after-current ()
5418 "Insert a new heading with same level as current, after current subtree."
5419 (interactive)
5420 (org-back-to-heading)
5421 (org-insert-heading)
5422 (org-move-subtree-down)
5423 (end-of-line 1))
5425 (defun org-insert-heading-respect-content ()
5426 (interactive)
5427 (let ((org-insert-heading-respect-content t))
5428 (org-insert-heading t)))
5430 (defun org-insert-todo-heading-respect-content (&optional force-state)
5431 (interactive "P")
5432 (let ((org-insert-heading-respect-content t))
5433 (org-insert-todo-heading force-state t)))
5435 (defun org-insert-todo-heading (arg &optional force-heading)
5436 "Insert a new heading with the same level and TODO state as current heading.
5437 If the heading has no TODO state, or if the state is DONE, use the first
5438 state (TODO by default). Also with prefix arg, force first state."
5439 (interactive "P")
5440 (when (or force-heading (not (org-insert-item 'checkbox)))
5441 (org-insert-heading force-heading)
5442 (save-excursion
5443 (org-back-to-heading)
5444 (outline-previous-heading)
5445 (looking-at org-todo-line-regexp))
5446 (let*
5447 ((new-mark-x
5448 (if (or arg
5449 (not (match-beginning 2))
5450 (member (match-string 2) org-done-keywords))
5451 (car org-todo-keywords-1)
5452 (match-string 2)))
5453 (new-mark
5455 (run-hook-with-args-until-success
5456 'org-todo-get-default-hook new-mark-x nil)
5457 new-mark-x)))
5458 (beginning-of-line 1)
5459 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5460 (insert new-mark " ")))
5461 (when org-provide-todo-statistics
5462 (org-update-parent-todo-statistics))))
5464 (defun org-insert-subheading (arg)
5465 "Insert a new subheading and demote it.
5466 Works for outline headings and for plain lists alike."
5467 (interactive "P")
5468 (org-insert-heading arg)
5469 (cond
5470 ((org-on-heading-p) (org-do-demote))
5471 ((org-at-item-p) (org-indent-item 1))))
5473 (defun org-insert-todo-subheading (arg)
5474 "Insert a new subheading with TODO keyword or checkbox and demote it.
5475 Works for outline headings and for plain lists alike."
5476 (interactive "P")
5477 (org-insert-todo-heading arg)
5478 (cond
5479 ((org-on-heading-p) (org-do-demote))
5480 ((org-at-item-p) (org-indent-item 1))))
5482 ;;; Promotion and Demotion
5484 (defun org-promote-subtree ()
5485 "Promote the entire subtree.
5486 See also `org-promote'."
5487 (interactive)
5488 (save-excursion
5489 (org-map-tree 'org-promote))
5490 (org-fix-position-after-promote))
5492 (defun org-demote-subtree ()
5493 "Demote the entire subtree. See `org-demote'.
5494 See also `org-promote'."
5495 (interactive)
5496 (save-excursion
5497 (org-map-tree 'org-demote))
5498 (org-fix-position-after-promote))
5501 (defun org-do-promote ()
5502 "Promote the current heading higher up the tree.
5503 If the region is active in `transient-mark-mode', promote all headings
5504 in the region."
5505 (interactive)
5506 (save-excursion
5507 (if (org-region-active-p)
5508 (org-map-region 'org-promote (region-beginning) (region-end))
5509 (org-promote)))
5510 (org-fix-position-after-promote))
5512 (defun org-do-demote ()
5513 "Demote the current heading lower down the tree.
5514 If the region is active in `transient-mark-mode', demote all headings
5515 in the region."
5516 (interactive)
5517 (save-excursion
5518 (if (org-region-active-p)
5519 (org-map-region 'org-demote (region-beginning) (region-end))
5520 (org-demote)))
5521 (org-fix-position-after-promote))
5523 (defun org-fix-position-after-promote ()
5524 "Make sure that after pro/demotion cursor position is right."
5525 (let ((pos (point)))
5526 (when (save-excursion
5527 (beginning-of-line 1)
5528 (looking-at org-todo-line-regexp)
5529 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5530 (cond ((eobp) (insert " "))
5531 ((eolp) (insert " "))
5532 ((equal (char-after) ?\ ) (forward-char 1))))))
5534 (defun org-reduced-level (l)
5535 "Compute the effective level of a heading.
5536 This takes into account the setting of `org-odd-levels-only'."
5537 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5539 (defun org-get-valid-level (level &optional change)
5540 "Rectify a level change under the influence of `org-odd-levels-only'
5541 LEVEL is a current level, CHANGE is by how much the level should be
5542 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5543 even level numbers will become the next higher odd number."
5544 (if org-odd-levels-only
5545 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5546 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5547 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5548 (max 1 (+ level (or change 0)))))
5550 (if (boundp 'define-obsolete-function-alias)
5551 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5552 (define-obsolete-function-alias 'org-get-legal-level
5553 'org-get-valid-level)
5554 (define-obsolete-function-alias 'org-get-legal-level
5555 'org-get-valid-level "23.1")))
5557 (defun org-promote ()
5558 "Promote the current heading higher up the tree.
5559 If the region is active in `transient-mark-mode', promote all headings
5560 in the region."
5561 (org-back-to-heading t)
5562 (let* ((level (save-match-data (funcall outline-level)))
5563 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5564 (diff (abs (- level (length up-head) -1))))
5565 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5566 (replace-match up-head nil t)
5567 ;; Fixup tag positioning
5568 (and org-auto-align-tags (org-set-tags nil t))
5569 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5571 (defun org-demote ()
5572 "Demote the current heading lower down the tree.
5573 If the region is active in `transient-mark-mode', demote all headings
5574 in the region."
5575 (org-back-to-heading t)
5576 (let* ((level (save-match-data (funcall outline-level)))
5577 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5578 (diff (abs (- level (length down-head) -1))))
5579 (replace-match down-head nil t)
5580 ;; Fixup tag positioning
5581 (and org-auto-align-tags (org-set-tags nil t))
5582 (if org-adapt-indentation (org-fixup-indentation diff))))
5584 (defun org-map-tree (fun)
5585 "Call FUN for every heading underneath the current one."
5586 (org-back-to-heading)
5587 (let ((level (funcall outline-level)))
5588 (save-excursion
5589 (funcall fun)
5590 (while (and (progn
5591 (outline-next-heading)
5592 (> (funcall outline-level) level))
5593 (not (eobp)))
5594 (funcall fun)))))
5596 (defun org-map-region (fun beg end)
5597 "Call FUN for every heading between BEG and END."
5598 (let ((org-ignore-region t))
5599 (save-excursion
5600 (setq end (copy-marker end))
5601 (goto-char beg)
5602 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5603 (< (point) end))
5604 (funcall fun))
5605 (while (and (progn
5606 (outline-next-heading)
5607 (< (point) end))
5608 (not (eobp)))
5609 (funcall fun)))))
5611 (defun org-fixup-indentation (diff)
5612 "Change the indentation in the current entry by DIFF
5613 However, if any line in the current entry has no indentation, or if it
5614 would end up with no indentation after the change, nothing at all is done."
5615 (save-excursion
5616 (let ((end (save-excursion (outline-next-heading)
5617 (point-marker)))
5618 (prohibit (if (> diff 0)
5619 "^\\S-"
5620 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5621 col)
5622 (unless (save-excursion (end-of-line 1)
5623 (re-search-forward prohibit end t))
5624 (while (and (< (point) end)
5625 (re-search-forward "^[ \t]+" end t))
5626 (goto-char (match-end 0))
5627 (setq col (current-column))
5628 (if (< diff 0) (replace-match ""))
5629 (org-indent-to-column (+ diff col))))
5630 (move-marker end nil))))
5632 (defun org-convert-to-odd-levels ()
5633 "Convert an org-mode file with all levels allowed to one with odd levels.
5634 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5635 level 5 etc."
5636 (interactive)
5637 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5638 (let ((org-odd-levels-only nil) n)
5639 (save-excursion
5640 (goto-char (point-min))
5641 (while (re-search-forward "^\\*\\*+ " nil t)
5642 (setq n (- (length (match-string 0)) 2))
5643 (while (>= (setq n (1- n)) 0)
5644 (org-demote))
5645 (end-of-line 1))))))
5648 (defun org-convert-to-oddeven-levels ()
5649 "Convert an org-mode file with only odd levels to one with odd and even levels.
5650 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5651 section with an even level, conversion would destroy the structure of the file. An error
5652 is signaled in this case."
5653 (interactive)
5654 (goto-char (point-min))
5655 ;; First check if there are no even levels
5656 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5657 (org-show-context t)
5658 (error "Not all levels are odd in this file. Conversion not possible."))
5659 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5660 (let ((org-odd-levels-only nil) n)
5661 (save-excursion
5662 (goto-char (point-min))
5663 (while (re-search-forward "^\\*\\*+ " nil t)
5664 (setq n (/ (1- (length (match-string 0))) 2))
5665 (while (>= (setq n (1- n)) 0)
5666 (org-promote))
5667 (end-of-line 1))))))
5669 (defun org-tr-level (n)
5670 "Make N odd if required."
5671 (if org-odd-levels-only (1+ (/ n 2)) n))
5673 ;;; Vertical tree motion, cutting and pasting of subtrees
5675 (defun org-move-subtree-up (&optional arg)
5676 "Move the current subtree up past ARG headlines of the same level."
5677 (interactive "p")
5678 (org-move-subtree-down (- (prefix-numeric-value arg))))
5680 (defun org-move-subtree-down (&optional arg)
5681 "Move the current subtree down past ARG headlines of the same level."
5682 (interactive "p")
5683 (setq arg (prefix-numeric-value arg))
5684 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5685 'outline-get-last-sibling))
5686 (ins-point (make-marker))
5687 (cnt (abs arg))
5688 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5689 ;; Select the tree
5690 (org-back-to-heading)
5691 (setq beg0 (point))
5692 (save-excursion
5693 (setq ne-beg (org-back-over-empty-lines))
5694 (setq beg (point)))
5695 (save-match-data
5696 (save-excursion (outline-end-of-heading)
5697 (setq folded (org-invisible-p)))
5698 (outline-end-of-subtree))
5699 (outline-next-heading)
5700 (setq ne-end (org-back-over-empty-lines))
5701 (setq end (point))
5702 (goto-char beg0)
5703 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5704 ;; include less whitespace
5705 (save-excursion
5706 (goto-char beg)
5707 (forward-line (- ne-beg ne-end))
5708 (setq beg (point))))
5709 ;; Find insertion point, with error handling
5710 (while (> cnt 0)
5711 (or (and (funcall movfunc) (looking-at outline-regexp))
5712 (progn (goto-char beg0)
5713 (error "Cannot move past superior level or buffer limit")))
5714 (setq cnt (1- cnt)))
5715 (if (> arg 0)
5716 ;; Moving forward - still need to move over subtree
5717 (progn (org-end-of-subtree t t)
5718 (save-excursion
5719 (org-back-over-empty-lines)
5720 (or (bolp) (newline)))))
5721 (setq ne-ins (org-back-over-empty-lines))
5722 (move-marker ins-point (point))
5723 (setq txt (buffer-substring beg end))
5724 (org-save-markers-in-region beg end)
5725 (delete-region beg end)
5726 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5727 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5728 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5729 (let ((bbb (point)))
5730 (insert-before-markers txt)
5731 (org-reinstall-markers-in-region bbb)
5732 (move-marker ins-point bbb))
5733 (or (bolp) (insert "\n"))
5734 (setq ins-end (point))
5735 (goto-char ins-point)
5736 (org-skip-whitespace)
5737 (when (and (< arg 0)
5738 (org-first-sibling-p)
5739 (> ne-ins ne-beg))
5740 ;; Move whitespace back to beginning
5741 (save-excursion
5742 (goto-char ins-end)
5743 (let ((kill-whole-line t))
5744 (kill-line (- ne-ins ne-beg)) (point)))
5745 (insert (make-string (- ne-ins ne-beg) ?\n)))
5746 (move-marker ins-point nil)
5747 (org-compact-display-after-subtree-move)
5748 (org-show-empty-lines-in-parent)
5749 (unless folded
5750 (org-show-entry)
5751 (show-children)
5752 (org-cycle-hide-drawers 'children))))
5754 (defvar org-subtree-clip ""
5755 "Clipboard for cut and paste of subtrees.
5756 This is actually only a copy of the kill, because we use the normal kill
5757 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5759 (defvar org-subtree-clip-folded nil
5760 "Was the last copied subtree folded?
5761 This is used to fold the tree back after pasting.")
5763 (defun org-cut-subtree (&optional n)
5764 "Cut the current subtree into the clipboard.
5765 With prefix arg N, cut this many sequential subtrees.
5766 This is a short-hand for marking the subtree and then cutting it."
5767 (interactive "p")
5768 (org-copy-subtree n 'cut))
5770 (defun org-copy-subtree (&optional n cut force-store-markers)
5771 "Cut the current subtree into the clipboard.
5772 With prefix arg N, cut this many sequential subtrees.
5773 This is a short-hand for marking the subtree and then copying it.
5774 If CUT is non-nil, actually cut the subtree.
5775 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5776 of some markers in the region, even if CUT is non-nil. This is
5777 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5778 (interactive "p")
5779 (let (beg end folded (beg0 (point)))
5780 (if (interactive-p)
5781 (org-back-to-heading nil) ; take what looks like a subtree
5782 (org-back-to-heading t)) ; take what is really there
5783 (org-back-over-empty-lines)
5784 (setq beg (point))
5785 (skip-chars-forward " \t\r\n")
5786 (save-match-data
5787 (save-excursion (outline-end-of-heading)
5788 (setq folded (org-invisible-p)))
5789 (condition-case nil
5790 (outline-forward-same-level (1- n))
5791 (error nil))
5792 (org-end-of-subtree t t))
5793 (org-back-over-empty-lines)
5794 (setq end (point))
5795 (goto-char beg0)
5796 (when (> end beg)
5797 (setq org-subtree-clip-folded folded)
5798 (when (or cut force-store-markers)
5799 (org-save-markers-in-region beg end))
5800 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5801 (setq org-subtree-clip (current-kill 0))
5802 (message "%s: Subtree(s) with %d characters"
5803 (if cut "Cut" "Copied")
5804 (length org-subtree-clip)))))
5806 (defun org-paste-subtree (&optional level tree for-yank)
5807 "Paste the clipboard as a subtree, with modification of headline level.
5808 The entire subtree is promoted or demoted in order to match a new headline
5809 level.
5811 If the cursor is at the beginning of a headline, the same level as
5812 that headline is used to paste the tree
5814 If not, the new level is derived from the *visible* headings
5815 before and after the insertion point, and taken to be the inferior headline
5816 level of the two. So if the previous visible heading is level 3 and the
5817 next is level 4 (or vice versa), level 4 will be used for insertion.
5818 This makes sure that the subtree remains an independent subtree and does
5819 not swallow low level entries.
5821 You can also force a different level, either by using a numeric prefix
5822 argument, or by inserting the heading marker by hand. For example, if the
5823 cursor is after \"*****\", then the tree will be shifted to level 5.
5825 If optional TREE is given, use this text instead of the kill ring.
5827 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5828 move back over whitespace before inserting, and move point to the end of
5829 the inserted text when done."
5830 (interactive "P")
5831 (unless (org-kill-is-subtree-p tree)
5832 (error "%s"
5833 (substitute-command-keys
5834 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5835 (let* ((visp (not (org-invisible-p)))
5836 (txt (or tree (and kill-ring (current-kill 0))))
5837 (^re (concat "^\\(" outline-regexp "\\)"))
5838 (re (concat "\\(" outline-regexp "\\)"))
5839 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5841 (old-level (if (string-match ^re txt)
5842 (- (match-end 0) (match-beginning 0) 1)
5843 -1))
5844 (force-level (cond (level (prefix-numeric-value level))
5845 ((and (looking-at "[ \t]*$")
5846 (string-match
5847 ^re_ (buffer-substring
5848 (point-at-bol) (point))))
5849 (- (match-end 1) (match-beginning 1)))
5850 ((and (bolp)
5851 (looking-at org-outline-regexp))
5852 (- (match-end 0) (point) 1))
5853 (t nil)))
5854 (previous-level (save-excursion
5855 (condition-case nil
5856 (progn
5857 (outline-previous-visible-heading 1)
5858 (if (looking-at re)
5859 (- (match-end 0) (match-beginning 0) 1)
5861 (error 1))))
5862 (next-level (save-excursion
5863 (condition-case nil
5864 (progn
5865 (or (looking-at outline-regexp)
5866 (outline-next-visible-heading 1))
5867 (if (looking-at re)
5868 (- (match-end 0) (match-beginning 0) 1)
5870 (error 1))))
5871 (new-level (or force-level (max previous-level next-level)))
5872 (shift (if (or (= old-level -1)
5873 (= new-level -1)
5874 (= old-level new-level))
5876 (- new-level old-level)))
5877 (delta (if (> shift 0) -1 1))
5878 (func (if (> shift 0) 'org-demote 'org-promote))
5879 (org-odd-levels-only nil)
5880 beg end newend)
5881 ;; Remove the forced level indicator
5882 (if force-level
5883 (delete-region (point-at-bol) (point)))
5884 ;; Paste
5885 (beginning-of-line 1)
5886 (unless for-yank (org-back-over-empty-lines))
5887 (setq beg (point))
5888 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5889 (insert-before-markers txt)
5890 (unless (string-match "\n\\'" txt) (insert "\n"))
5891 (setq newend (point))
5892 (org-reinstall-markers-in-region beg)
5893 (setq end (point))
5894 (goto-char beg)
5895 (skip-chars-forward " \t\n\r")
5896 (setq beg (point))
5897 (if (and (org-invisible-p) visp)
5898 (save-excursion (outline-show-heading)))
5899 ;; Shift if necessary
5900 (unless (= shift 0)
5901 (save-restriction
5902 (narrow-to-region beg end)
5903 (while (not (= shift 0))
5904 (org-map-region func (point-min) (point-max))
5905 (setq shift (+ delta shift)))
5906 (goto-char (point-min))
5907 (setq newend (point-max))))
5908 (when (or (interactive-p) for-yank)
5909 (message "Clipboard pasted as level %d subtree" new-level))
5910 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5911 kill-ring
5912 (eq org-subtree-clip (current-kill 0))
5913 org-subtree-clip-folded)
5914 ;; The tree was folded before it was killed/copied
5915 (hide-subtree))
5916 (and for-yank (goto-char newend))))
5918 (defun org-kill-is-subtree-p (&optional txt)
5919 "Check if the current kill is an outline subtree, or a set of trees.
5920 Returns nil if kill does not start with a headline, or if the first
5921 headline level is not the largest headline level in the tree.
5922 So this will actually accept several entries of equal levels as well,
5923 which is OK for `org-paste-subtree'.
5924 If optional TXT is given, check this string instead of the current kill."
5925 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5926 (start-level (and kill
5927 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5928 org-outline-regexp "\\)")
5929 kill)
5930 (- (match-end 2) (match-beginning 2) 1)))
5931 (re (concat "^" org-outline-regexp))
5932 (start (1+ (or (match-beginning 2) -1))))
5933 (if (not start-level)
5934 (progn
5935 nil) ;; does not even start with a heading
5936 (catch 'exit
5937 (while (setq start (string-match re kill (1+ start)))
5938 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5939 (throw 'exit nil)))
5940 t))))
5942 (defvar org-markers-to-move nil
5943 "Markers that should be moved with a cut-and-paste operation.
5944 Those markers are stored together with their positions relative to
5945 the start of the region.")
5947 (defun org-save-markers-in-region (beg end)
5948 "Check markers in region.
5949 If these markers are between BEG and END, record their position relative
5950 to BEG, so that after moving the block of text, we can put the markers back
5951 into place.
5952 This function gets called just before an entry or tree gets cut from the
5953 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5954 called immediately, to move the markers with the entries."
5955 (setq org-markers-to-move nil)
5956 (when (featurep 'org-clock)
5957 (org-clock-save-markers-for-cut-and-paste beg end))
5958 (when (featurep 'org-agenda)
5959 (org-agenda-save-markers-for-cut-and-paste beg end)))
5961 (defun org-check-and-save-marker (marker beg end)
5962 "Check if MARKER is between BEG and END.
5963 If yes, remember the marker and the distance to BEG."
5964 (when (and (marker-buffer marker)
5965 (equal (marker-buffer marker) (current-buffer)))
5966 (if (and (>= marker beg) (< marker end))
5967 (push (cons marker (- marker beg)) org-markers-to-move))))
5969 (defun org-reinstall-markers-in-region (beg)
5970 "Move all remembered markers to their position relative to BEG."
5971 (mapc (lambda (x)
5972 (move-marker (car x) (+ beg (cdr x))))
5973 org-markers-to-move)
5974 (setq org-markers-to-move nil))
5976 (defun org-narrow-to-subtree ()
5977 "Narrow buffer to the current subtree."
5978 (interactive)
5979 (save-excursion
5980 (save-match-data
5981 (narrow-to-region
5982 (progn (org-back-to-heading) (point))
5983 (progn (org-end-of-subtree t) (point))))))
5985 (defun org-clone-subtree-with-time-shift (n &optional shift)
5986 "Clone the task (subtree) at point N times.
5987 The clones will be inserted as siblings.
5989 In interactive use, the user will be prompted for the number of clones
5990 to be produced, and for a time SHIFT, which may be a repeater as used
5991 in time stamps, for example `+3d'.
5993 When a valid repeater is given and the entry contains any time stamps,
5994 the clones will become a sequence in time, with time stamps in the
5995 subtree shifted for each clone produced. If SHIFT is nil or the
5996 empty string, time stamps will be left alone.
5998 If the original subtree did contain time stamps with a repeater,
5999 the following will happen:
6000 - the repeater will be removed in each clone
6001 - an additional clone will be produced, with the current, unshifted
6002 date(s) in the entry.
6003 - the original entry will be placed *after* all the clones, with
6004 repeater intact.
6005 - the start days in the repeater in the original entry will be shifted
6006 to past the last clone.
6007 I this way you can spell out a number of instances of a repeating task,
6008 and still retain the repeater to cover future instances of the task."
6009 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6010 (let (beg end template task
6011 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6012 (if (not (and (integerp n) (> n 0)))
6013 (error "Invalid number of replications %s" n))
6014 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6015 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6016 shift)))
6017 (error "Invalid shift specification %s" shift))
6018 (when doshift
6019 (setq shift-n (string-to-number (match-string 1 shift))
6020 shift-what (cdr (assoc (match-string 2 shift)
6021 '(("d" . day) ("w" . week)
6022 ("m" . month) ("y" . year))))))
6023 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6024 (setq nmin 1 nmax n)
6025 (org-back-to-heading t)
6026 (setq beg (point))
6027 (org-end-of-subtree t t)
6028 (setq end (point))
6029 (setq template (buffer-substring beg end))
6030 (when (and doshift
6031 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6032 (delete-region beg end)
6033 (setq end beg)
6034 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6035 (goto-char end)
6036 (loop for n from nmin to nmax do
6037 (if (not doshift)
6038 (setq task template)
6039 (with-temp-buffer
6040 (insert template)
6041 (org-mode)
6042 (goto-char (point-min))
6043 (while (re-search-forward org-ts-regexp nil t)
6044 (org-timestamp-change (* n shift-n) shift-what))
6045 (unless (= n n-no-remove)
6046 (goto-char (point-min))
6047 (while (re-search-forward org-ts-regexp nil t)
6048 (save-excursion
6049 (goto-char (match-beginning 0))
6050 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6051 (delete-region (match-beginning 1) (match-end 1))))))
6052 (setq task (buffer-string))))
6053 (insert task))
6054 (goto-char beg)))
6056 ;;; Outline Sorting
6058 (defun org-sort (with-case)
6059 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6060 Optional argument WITH-CASE means sort case-sensitively.
6061 With a double prefix argument, also remove duplicate entries."
6062 (interactive "P")
6063 (if (org-at-table-p)
6064 (org-call-with-arg 'org-table-sort-lines with-case)
6065 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6067 (defun org-sort-remove-invisible (s)
6068 (remove-text-properties 0 (length s) org-rm-props s)
6069 (while (string-match org-bracket-link-regexp s)
6070 (setq s (replace-match (if (match-end 2)
6071 (match-string 3 s)
6072 (match-string 1 s)) t t s)))
6075 (defvar org-priority-regexp) ; defined later in the file
6077 (defun org-sort-entries-or-items
6078 (&optional with-case sorting-type getkey-func compare-func property)
6079 "Sort entries on a certain level of an outline tree.
6080 If there is an active region, the entries in the region are sorted.
6081 Else, if the cursor is before the first entry, sort the top-level items.
6082 Else, the children of the entry at point are sorted.
6084 Sorting can be alphabetically, numerically, and by date/time as given by
6085 the first time stamp in the entry. The command prompts for the sorting
6086 type unless it has been given to the function through the SORTING-TYPE
6087 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6088 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6089 called with point at the beginning of the record. It must return either
6090 a string or a number that should serve as the sorting key for that record.
6092 Comparing entries ignores case by default. However, with an optional argument
6093 WITH-CASE, the sorting considers case as well."
6094 (interactive "P")
6095 (let ((case-func (if with-case 'identity 'downcase))
6096 start beg end stars re re2
6097 txt what tmp plain-list-p)
6098 ;; Find beginning and end of region to sort
6099 (cond
6100 ((org-region-active-p)
6101 ;; we will sort the region
6102 (setq end (region-end)
6103 what "region")
6104 (goto-char (region-beginning))
6105 (if (not (org-on-heading-p)) (outline-next-heading))
6106 (setq start (point)))
6107 ((org-at-item-p)
6108 ;; we will sort this plain list
6109 (org-beginning-of-item-list) (setq start (point))
6110 (org-end-of-item-list) (setq end (point))
6111 (goto-char start)
6112 (setq plain-list-p t
6113 what "plain list"))
6114 ((or (org-on-heading-p)
6115 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6116 ;; we will sort the children of the current headline
6117 (org-back-to-heading)
6118 (setq start (point)
6119 end (progn (org-end-of-subtree t t)
6120 (org-back-over-empty-lines)
6121 (point))
6122 what "children")
6123 (goto-char start)
6124 (show-subtree)
6125 (outline-next-heading))
6127 ;; we will sort the top-level entries in this file
6128 (goto-char (point-min))
6129 (or (org-on-heading-p) (outline-next-heading))
6130 (setq start (point) end (point-max) what "top-level")
6131 (goto-char start)
6132 (show-all)))
6134 (setq beg (point))
6135 (if (>= beg end) (error "Nothing to sort"))
6137 (unless plain-list-p
6138 (looking-at "\\(\\*+\\)")
6139 (setq stars (match-string 1)
6140 re (concat "^" (regexp-quote stars) " +")
6141 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6142 txt (buffer-substring beg end))
6143 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6144 (if (and (not (equal stars "*")) (string-match re2 txt))
6145 (error "Region to sort contains a level above the first entry")))
6147 (unless sorting-type
6148 (message
6149 (if plain-list-p
6150 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6151 "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:")
6152 what)
6153 (setq sorting-type (read-char-exclusive))
6155 (and (= (downcase sorting-type) ?f)
6156 (setq getkey-func
6157 (org-ido-completing-read "Sort using function: "
6158 obarray 'fboundp t nil nil))
6159 (setq getkey-func (intern getkey-func)))
6161 (and (= (downcase sorting-type) ?r)
6162 (setq property
6163 (org-ido-completing-read "Property: "
6164 (mapcar 'list (org-buffer-property-keys t))
6165 nil t))))
6167 (message "Sorting entries...")
6169 (save-restriction
6170 (narrow-to-region start end)
6172 (let ((dcst (downcase sorting-type))
6173 (case-fold-search nil)
6174 (now (current-time)))
6175 (sort-subr
6176 (/= dcst sorting-type)
6177 ;; This function moves to the beginning character of the "record" to
6178 ;; be sorted.
6179 (if plain-list-p
6180 (lambda nil
6181 (if (org-at-item-p) t (goto-char (point-max))))
6182 (lambda nil
6183 (if (re-search-forward re nil t)
6184 (goto-char (match-beginning 0))
6185 (goto-char (point-max)))))
6186 ;; This function moves to the last character of the "record" being
6187 ;; sorted.
6188 (if plain-list-p
6189 'org-end-of-item
6190 (lambda nil
6191 (save-match-data
6192 (condition-case nil
6193 (outline-forward-same-level 1)
6194 (error
6195 (goto-char (point-max)))))))
6197 ;; This function returns the value that gets sorted against.
6198 (if plain-list-p
6199 (lambda nil
6200 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6201 (cond
6202 ((= dcst ?n)
6203 (string-to-number (buffer-substring (match-end 0)
6204 (point-at-eol))))
6205 ((= dcst ?a)
6206 (buffer-substring (match-end 0) (point-at-eol)))
6207 ((= dcst ?t)
6208 (if (re-search-forward org-ts-regexp
6209 (point-at-eol) t)
6210 (org-time-string-to-time (match-string 0))
6211 now))
6212 ((= dcst ?f)
6213 (if getkey-func
6214 (progn
6215 (setq tmp (funcall getkey-func))
6216 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6217 tmp)
6218 (error "Invalid key function `%s'" getkey-func)))
6219 (t (error "Invalid sorting type `%c'" sorting-type)))))
6220 (lambda nil
6221 (cond
6222 ((= dcst ?n)
6223 (if (looking-at org-complex-heading-regexp)
6224 (string-to-number (match-string 4))
6225 nil))
6226 ((= dcst ?a)
6227 (if (looking-at org-complex-heading-regexp)
6228 (funcall case-func (match-string 4))
6229 nil))
6230 ((= dcst ?t)
6231 (if (re-search-forward org-ts-regexp
6232 (save-excursion
6233 (forward-line 2)
6234 (point)) t)
6235 (org-time-string-to-time (match-string 0))
6236 now))
6237 ((= dcst ?p)
6238 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6239 (string-to-char (match-string 2))
6240 org-default-priority))
6241 ((= dcst ?r)
6242 (or (org-entry-get nil property) ""))
6243 ((= dcst ?o)
6244 (if (looking-at org-complex-heading-regexp)
6245 (- 9999 (length (member (match-string 2)
6246 org-todo-keywords-1)))))
6247 ((= dcst ?f)
6248 (if getkey-func
6249 (progn
6250 (setq tmp (funcall getkey-func))
6251 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6252 tmp)
6253 (error "Invalid key function `%s'" getkey-func)))
6254 (t (error "Invalid sorting type `%c'" sorting-type)))))
6256 (cond
6257 ((= dcst ?a) 'string<)
6258 ((= dcst ?t) 'time-less-p)
6259 ((= dcst ?f) compare-func)
6260 ((= dcst ?p) '<)
6261 (t nil)))))
6262 (message "Sorting entries...done")))
6264 (defun org-do-sort (table what &optional with-case sorting-type)
6265 "Sort TABLE of WHAT according to SORTING-TYPE.
6266 The user will be prompted for the SORTING-TYPE if the call to this
6267 function does not specify it. WHAT is only for the prompt, to indicate
6268 what is being sorted. The sorting key will be extracted from
6269 the car of the elements of the table.
6270 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6271 (unless sorting-type
6272 (message
6273 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6274 what)
6275 (setq sorting-type (read-char-exclusive)))
6276 (let ((dcst (downcase sorting-type))
6277 extractfun comparefun)
6278 ;; Define the appropriate functions
6279 (cond
6280 ((= dcst ?n)
6281 (setq extractfun 'string-to-number
6282 comparefun (if (= dcst sorting-type) '< '>)))
6283 ((= dcst ?a)
6284 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6285 (lambda(x) (downcase (org-sort-remove-invisible x))))
6286 comparefun (if (= dcst sorting-type)
6287 'string<
6288 (lambda (a b) (and (not (string< a b))
6289 (not (string= a b)))))))
6290 ((= dcst ?t)
6291 (setq extractfun
6292 (lambda (x)
6293 (if (or (string-match org-ts-regexp x)
6294 (string-match org-ts-regexp-both x))
6295 (time-to-seconds
6296 (org-time-string-to-time (match-string 0 x)))
6298 comparefun (if (= dcst sorting-type) '< '>)))
6299 (t (error "Invalid sorting type `%c'" sorting-type)))
6301 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6302 table)
6303 (lambda (a b) (funcall comparefun (car a) (car b))))))
6305 ;;; Editing source examples
6307 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6308 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6309 (defvar org-edit-src-force-single-line nil)
6310 (defvar org-edit-src-from-org-mode nil)
6311 (defvar org-edit-src-picture nil)
6312 (defvar org-edit-src-beg-marker nil)
6313 (defvar org-edit-src-end-marker nil)
6315 (define-minor-mode org-exit-edit-mode
6316 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6318 (defun org-edit-src-code ()
6319 "Edit the source code example at point.
6320 The example is copied to a separate buffer, and that buffer is switched
6321 to the correct language mode. When done, exit with \\[org-edit-src-exit].
6322 This will remove the original code in the Org buffer, and replace it with
6323 the edited version."
6324 (interactive)
6325 (let ((line (org-current-line))
6326 (case-fold-search t)
6327 (msg (substitute-command-keys
6328 "Edit, then exit with C-c ' (C-c and single quote)"))
6329 (info (org-edit-src-find-region-and-lang))
6330 (org-mode-p (eq major-mode 'org-mode))
6331 (beg (make-marker))
6332 (end (make-marker))
6333 lang lang-f single lfmt code begline)
6334 (if (not info)
6336 (setq beg (move-marker beg (nth 0 info))
6337 end (move-marker end (nth 1 info))
6338 code (buffer-substring-no-properties beg end)
6339 lang (nth 2 info)
6340 single (nth 3 info)
6341 lfmt (nth 4 info)
6342 lang-f (intern (concat lang "-mode"))
6343 begline (save-excursion (goto-char beg) (org-current-line)))
6344 (unless (functionp lang-f)
6345 (error "No such language mode: %s" lang-f))
6346 (goto-line line)
6347 (if (get-buffer "*Org Edit Src Example*")
6348 (kill-buffer "*Org Edit Src Example*"))
6349 (switch-to-buffer (get-buffer-create "*Org Edit Src Example*"))
6350 (insert code)
6351 (remove-text-properties (point-min) (point-max)
6352 '(display nil invisible nil intangible nil))
6353 (let ((org-inhibit-startup t))
6354 (funcall lang-f))
6355 (set (make-local-variable 'org-edit-src-force-single-line) single)
6356 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6357 (when lfmt
6358 (set (make-local-variable 'org-coderef-label-format) lfmt))
6359 (when org-mode-p
6360 (goto-char (point-min))
6361 (while (re-search-forward "^," nil t)
6362 (replace-match "")))
6363 (goto-line (1+ (- line begline)))
6364 (org-exit-edit-mode)
6365 (org-set-local 'org-edit-src-beg-marker beg)
6366 (org-set-local 'org-edit-src-end-marker end)
6367 (org-set-local 'header-line-format msg)
6368 (message "%s" msg)
6369 t)))
6371 (defun org-edit-fixed-width-region ()
6372 "Edit the fixed-width ascii drawing at point.
6373 This must be a region where each line starts with a colon followed by
6374 a space character.
6375 An indirect buffer is created, and that buffer is then narrowed to the
6376 example at point and switched to artist-mode. When done,
6377 exit by killing the buffer with \\[org-edit-src-exit]."
6378 (interactive)
6379 (let ((line (org-current-line))
6380 (case-fold-search t)
6381 (msg (substitute-command-keys
6382 "Edit, then exit with C-c ' (C-c and single quote)"))
6383 (org-mode-p (eq major-mode 'org-mode))
6384 (beg (make-marker))
6385 (end (make-marker))
6386 beg1 end1 code begline)
6387 (beginning-of-line 1)
6388 (if (looking-at "[ \t]*[^:\n \t]")
6390 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6391 (setq beg1 (point) end1 beg1)
6392 (save-excursion
6393 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6394 (setq beg1 (point-at-bol 2))
6395 (setq beg1 (point))))
6396 (save-excursion
6397 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6398 (setq end1 (1- (match-beginning 0)))
6399 (setq end1 (point))))
6400 (goto-line line))
6401 (setq beg (move-marker beg beg1)
6402 end (move-marker end end1)
6403 code (buffer-substring-no-properties beg end)
6404 begline (save-excursion (goto-char beg) (org-current-line)))
6405 (if (get-buffer "*Org Edit Picture*")
6406 (kill-buffer "*Org Edit Picture*"))
6407 (switch-to-buffer (get-buffer-create "*Org Edit Picture*"))
6408 (insert code)
6409 (remove-text-properties (point-min) (point-max)
6410 '(display nil invisible nil intangible nil))
6411 (cond
6412 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6413 (fundamental-mode)
6414 (artist-mode 1))
6415 (t (funcall org-edit-fixed-width-region-mode)))
6416 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6417 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6418 (set (make-local-variable 'org-edit-src-picture) t)
6419 (goto-char (point-min))
6420 (while (re-search-forward "^[ \t]*: ?" nil t)
6421 (replace-match ""))
6422 (goto-line (1+ (- line begline)))
6423 (org-exit-edit-mode)
6424 (org-set-local 'org-edit-src-beg-marker beg)
6425 (org-set-local 'org-edit-src-end-marker end)
6426 (org-set-local 'header-line-format msg)
6427 (message "%s" msg)
6428 t)))
6430 (defun org-edit-src-find-region-and-lang ()
6431 "Find the region and language for a local edit.
6432 Return a list with beginning and end of the region, a string representing
6433 the language, a switch telling of the content should be in a single line."
6434 (let ((re-list
6435 (append
6436 org-edit-src-region-extra
6438 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6439 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6440 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6441 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6442 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6443 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6444 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6445 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6446 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6447 ("^#\\+html:" "\n" "html" single-line)
6448 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6449 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6450 ("^#\\+latex:" "\n" "latex" single-line)
6451 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6452 ("^#\\+ascii:" "\n" "ascii" single-line)
6454 (pos (point))
6455 re1 re2 single beg end lang lfmt match-re1)
6456 (catch 'exit
6457 (while (setq entry (pop re-list))
6458 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6459 single (nth 3 entry))
6460 (save-excursion
6461 (if (or (looking-at re1)
6462 (re-search-backward re1 nil t))
6463 (progn
6464 (setq match-re1 (match-string 0))
6465 (setq beg (match-end 0)
6466 lang (org-edit-src-get-lang lang)
6467 lfmt (org-edit-src-get-label-format match-re1))
6468 (if (and (re-search-forward re2 nil t)
6469 (>= (match-end 0) pos))
6470 (throw 'exit (list beg (match-beginning 0)
6471 lang single lfmt))))
6472 (if (or (looking-at re2)
6473 (re-search-forward re2 nil t))
6474 (progn
6475 (setq end (match-beginning 0))
6476 (if (and (re-search-backward re1 nil t)
6477 (<= (match-beginning 0) pos))
6478 (progn
6479 (setq lfmt (org-edit-src-get-label-format
6480 (match-string 0)))
6481 (throw 'exit
6482 (list (match-end 0) end
6483 (org-edit-src-get-lang lang)
6484 single lfmt))))))))))))
6486 (defun org-edit-src-get-lang (lang)
6487 "Extract the src language."
6488 (let ((m (match-string 0)))
6489 (cond
6490 ((stringp lang) lang)
6491 ((integerp lang) (match-string lang))
6492 ((and (eq lang 'lang)
6493 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6494 (match-string 1 m))
6495 ((and (eq lang 'style)
6496 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6497 (match-string 1 m))
6498 (t "fundamental"))))
6500 (defun org-edit-src-get-label-format (s)
6501 "Extract the label format."
6502 (save-match-data
6503 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6504 (match-string 1 s))))
6506 (defun org-edit-src-exit ()
6507 "Exit special edit and protect problematic lines."
6508 (interactive)
6509 (unless (member (buffer-name)
6510 '("*Org Edit Src Example*" "*Org Edit Picture*"))
6511 (error "This is not an sub-editing buffer, something is wrong..."))
6512 (let ((line (if (org-bound-and-true-p org-edit-src-force-single-line)
6514 (org-current-line)))
6515 (beg org-edit-src-beg-marker)
6516 (end org-edit-src-end-marker)
6517 (buffer (current-buffer))
6518 code)
6519 (goto-char (point-min))
6520 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6521 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6522 (when (org-bound-and-true-p org-edit-src-force-single-line)
6523 (goto-char (point-min))
6524 (while (re-search-forward "\n" nil t)
6525 (replace-match " "))
6526 (goto-char (point-min))
6527 (if (looking-at "\\s-*") (replace-match " "))
6528 (if (re-search-forward "\\s-+\\'" nil t)
6529 (replace-match "")))
6530 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6531 (goto-char (point-min))
6532 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6533 (replace-match ",\\1"))
6534 (when font-lock-mode
6535 (font-lock-unfontify-region (point-min) (point-max)))
6536 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6537 (when (org-bound-and-true-p org-edit-src-picture)
6538 (untabify (point-min) (point-max))
6539 (goto-char (point-min))
6540 (while (re-search-forward "^" nil t)
6541 (replace-match ": "))
6542 (when font-lock-mode
6543 (font-lock-unfontify-region (point-min) (point-max)))
6544 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6545 (setq code (buffer-string))
6546 (switch-to-buffer (marker-buffer beg))
6547 (kill-buffer buffer)
6548 (goto-char beg)
6549 (delete-region beg end)
6550 (insert code)
6551 (goto-char beg)
6552 (goto-line (1- (+ (org-current-line) line)))
6553 (move-marker beg nil)
6554 (move-marker end nil)))
6557 ;;; The orgstruct minor mode
6559 ;; Define a minor mode which can be used in other modes in order to
6560 ;; integrate the org-mode structure editing commands.
6562 ;; This is really a hack, because the org-mode structure commands use
6563 ;; keys which normally belong to the major mode. Here is how it
6564 ;; works: The minor mode defines all the keys necessary to operate the
6565 ;; structure commands, but wraps the commands into a function which
6566 ;; tests if the cursor is currently at a headline or a plain list
6567 ;; item. If that is the case, the structure command is used,
6568 ;; temporarily setting many Org-mode variables like regular
6569 ;; expressions for filling etc. However, when any of those keys is
6570 ;; used at a different location, function uses `key-binding' to look
6571 ;; up if the key has an associated command in another currently active
6572 ;; keymap (minor modes, major mode, global), and executes that
6573 ;; command. There might be problems if any of the keys is otherwise
6574 ;; used as a prefix key.
6576 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6577 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6578 ;; addresses this by checking explicitly for both bindings.
6580 (defvar orgstruct-mode-map (make-sparse-keymap)
6581 "Keymap for the minor `orgstruct-mode'.")
6583 (defvar org-local-vars nil
6584 "List of local variables, for use by `orgstruct-mode'")
6586 ;;;###autoload
6587 (define-minor-mode orgstruct-mode
6588 "Toggle the minor more `orgstruct-mode'.
6589 This mode is for using Org-mode structure commands in other modes.
6590 The following key behave as if Org-mode was active, if the cursor
6591 is on a headline, or on a plain list item (both in the definition
6592 of Org-mode).
6594 M-up Move entry/item up
6595 M-down Move entry/item down
6596 M-left Promote
6597 M-right Demote
6598 M-S-up Move entry/item up
6599 M-S-down Move entry/item down
6600 M-S-left Promote subtree
6601 M-S-right Demote subtree
6602 M-q Fill paragraph and items like in Org-mode
6603 C-c ^ Sort entries
6604 C-c - Cycle list bullet
6605 TAB Cycle item visibility
6606 M-RET Insert new heading/item
6607 S-M-RET Insert new TODO heading / Checkbox item
6608 C-c C-c Set tags / toggle checkbox"
6609 nil " OrgStruct" nil
6610 (org-load-modules-maybe)
6611 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6613 ;;;###autoload
6614 (defun turn-on-orgstruct ()
6615 "Unconditionally turn on `orgstruct-mode'."
6616 (orgstruct-mode 1))
6618 (defun orgstruct++-mode (&optional arg)
6619 "Toggle `orgstruct-mode', the enhanced version of it.
6620 In addition to setting orgstruct-mode, this also exports all indentation and
6621 autofilling variables from org-mode into the buffer. It will also
6622 recognize item context in multiline items.
6623 Note that turning off orgstruct-mode will *not* remove the
6624 indentation/paragraph settings. This can only be done by refreshing the
6625 major mode, for example with \[normal-mode]."
6626 (interactive "P")
6627 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6628 (if (< arg 1)
6629 (orgstruct-mode -1)
6630 (orgstruct-mode 1)
6631 (let (var val)
6632 (mapc
6633 (lambda (x)
6634 (when (string-match
6635 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6636 (symbol-name (car x)))
6637 (setq var (car x) val (nth 1 x))
6638 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6639 org-local-vars)
6640 (org-set-local 'orgstruct-is-++ t))))
6642 (defvar orgstruct-is-++ nil
6643 "Is orgstruct-mode in ++ version in the current-buffer?")
6644 (make-variable-buffer-local 'orgstruct-is-++)
6646 ;;;###autoload
6647 (defun turn-on-orgstruct++ ()
6648 "Unconditionally turn on `orgstruct++-mode'."
6649 (orgstruct++-mode 1))
6651 (defun orgstruct-error ()
6652 "Error when there is no default binding for a structure key."
6653 (interactive)
6654 (error "This key has no function outside structure elements"))
6656 (defun orgstruct-setup ()
6657 "Setup orgstruct keymaps."
6658 (let ((nfunc 0)
6659 (bindings
6660 (list
6661 '([(meta up)] org-metaup)
6662 '([(meta down)] org-metadown)
6663 '([(meta left)] org-metaleft)
6664 '([(meta right)] org-metaright)
6665 '([(meta shift up)] org-shiftmetaup)
6666 '([(meta shift down)] org-shiftmetadown)
6667 '([(meta shift left)] org-shiftmetaleft)
6668 '([(meta shift right)] org-shiftmetaright)
6669 '([(shift up)] org-shiftup)
6670 '([(shift down)] org-shiftdown)
6671 '([(shift left)] org-shiftleft)
6672 '([(shift right)] org-shiftright)
6673 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6674 '("\M-q" fill-paragraph)
6675 '("\C-c^" org-sort)
6676 '("\C-c-" org-cycle-list-bullet)))
6677 elt key fun cmd)
6678 (while (setq elt (pop bindings))
6679 (setq nfunc (1+ nfunc))
6680 (setq key (org-key (car elt))
6681 fun (nth 1 elt)
6682 cmd (orgstruct-make-binding fun nfunc key))
6683 (org-defkey orgstruct-mode-map key cmd))
6685 ;; Special treatment needed for TAB and RET
6686 (org-defkey orgstruct-mode-map [(tab)]
6687 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6688 (org-defkey orgstruct-mode-map "\C-i"
6689 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6691 (org-defkey orgstruct-mode-map "\M-\C-m"
6692 (orgstruct-make-binding 'org-insert-heading 105
6693 "\M-\C-m" [(meta return)]))
6694 (org-defkey orgstruct-mode-map [(meta return)]
6695 (orgstruct-make-binding 'org-insert-heading 106
6696 [(meta return)] "\M-\C-m"))
6698 (org-defkey orgstruct-mode-map [(shift meta return)]
6699 (orgstruct-make-binding 'org-insert-todo-heading 107
6700 [(meta return)] "\M-\C-m"))
6702 (unless org-local-vars
6703 (setq org-local-vars (org-get-local-variables)))
6707 (defun orgstruct-make-binding (fun n &rest keys)
6708 "Create a function for binding in the structure minor mode.
6709 FUN is the command to call inside a table. N is used to create a unique
6710 command name. KEYS are keys that should be checked in for a command
6711 to execute outside of tables."
6712 (eval
6713 (list 'defun
6714 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6715 '(arg)
6716 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6717 "Outside of structure, run the binding of `"
6718 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6719 "'.")
6720 '(interactive "p")
6721 (list 'if
6722 `(org-context-p 'headline 'item
6723 (and orgstruct-is-++
6724 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6725 'item-body))
6726 (list 'org-run-like-in-org-mode (list 'quote fun))
6727 (list 'let '(orgstruct-mode)
6728 (list 'call-interactively
6729 (append '(or)
6730 (mapcar (lambda (k)
6731 (list 'key-binding k))
6732 keys)
6733 '('orgstruct-error))))))))
6735 (defun org-context-p (&rest contexts)
6736 "Check if local context is any of CONTEXTS.
6737 Possible values in the list of contexts are `table', `headline', and `item'."
6738 (let ((pos (point)))
6739 (goto-char (point-at-bol))
6740 (prog1 (or (and (memq 'table contexts)
6741 (looking-at "[ \t]*|"))
6742 (and (memq 'headline contexts)
6743 ;;????????? (looking-at "\\*+"))
6744 (looking-at outline-regexp))
6745 (and (memq 'item contexts)
6746 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6747 (and (memq 'item-body contexts)
6748 (org-in-item-p)))
6749 (goto-char pos))))
6751 (defun org-get-local-variables ()
6752 "Return a list of all local variables in an org-mode buffer."
6753 (let (varlist)
6754 (with-current-buffer (get-buffer-create "*Org tmp*")
6755 (erase-buffer)
6756 (org-mode)
6757 (setq varlist (buffer-local-variables)))
6758 (kill-buffer "*Org tmp*")
6759 (delq nil
6760 (mapcar
6761 (lambda (x)
6762 (setq x
6763 (if (symbolp x)
6764 (list x)
6765 (list (car x) (list 'quote (cdr x)))))
6766 (if (string-match
6767 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6768 (symbol-name (car x)))
6769 x nil))
6770 varlist))))
6772 ;;;###autoload
6773 (defun org-run-like-in-org-mode (cmd)
6774 "Run a command, pretending that the current buffer is in Org-mode.
6775 This will temporarily bind local variables that are typically bound in
6776 Org-mode to the values they have in Org-mode, and then interactively
6777 call CMD."
6778 (org-load-modules-maybe)
6779 (unless org-local-vars
6780 (setq org-local-vars (org-get-local-variables)))
6781 (eval (list 'let org-local-vars
6782 (list 'call-interactively (list 'quote cmd)))))
6784 ;;;; Archiving
6786 (defun org-get-category (&optional pos)
6787 "Get the category applying to position POS."
6788 (get-text-property (or pos (point)) 'org-category))
6790 (defun org-refresh-category-properties ()
6791 "Refresh category text properties in the buffer."
6792 (let ((def-cat (cond
6793 ((null org-category)
6794 (if buffer-file-name
6795 (file-name-sans-extension
6796 (file-name-nondirectory buffer-file-name))
6797 "???"))
6798 ((symbolp org-category) (symbol-name org-category))
6799 (t org-category)))
6800 beg end cat pos optionp)
6801 (org-unmodified
6802 (save-excursion
6803 (save-restriction
6804 (widen)
6805 (goto-char (point-min))
6806 (put-text-property (point) (point-max) 'org-category def-cat)
6807 (while (re-search-forward
6808 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6809 (setq pos (match-end 0)
6810 optionp (equal (char-after (match-beginning 0)) ?#)
6811 cat (org-trim (match-string 2)))
6812 (if optionp
6813 (setq beg (point-at-bol) end (point-max))
6814 (org-back-to-heading t)
6815 (setq beg (point) end (org-end-of-subtree t t)))
6816 (put-text-property beg end 'org-category cat)
6817 (goto-char pos)))))))
6820 ;;;; Link Stuff
6822 ;;; Link abbreviations
6824 (defun org-link-expand-abbrev (link)
6825 "Apply replacements as defined in `org-link-abbrev-alist."
6826 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6827 (let* ((key (match-string 1 link))
6828 (as (or (assoc key org-link-abbrev-alist-local)
6829 (assoc key org-link-abbrev-alist)))
6830 (tag (and (match-end 2) (match-string 3 link)))
6831 rpl)
6832 (if (not as)
6833 link
6834 (setq rpl (cdr as))
6835 (cond
6836 ((symbolp rpl) (funcall rpl tag))
6837 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6838 ((string-match "%h" rpl)
6839 (replace-match (url-hexify-string (or tag "")) t t rpl))
6840 (t (concat rpl tag)))))
6841 link))
6843 ;;; Storing and inserting links
6845 (defvar org-insert-link-history nil
6846 "Minibuffer history for links inserted with `org-insert-link'.")
6848 (defvar org-stored-links nil
6849 "Contains the links stored with `org-store-link'.")
6851 (defvar org-store-link-plist nil
6852 "Plist with info about the most recently link created with `org-store-link'.")
6854 (defvar org-link-protocols nil
6855 "Link protocols added to Org-mode using `org-add-link-type'.")
6857 (defvar org-store-link-functions nil
6858 "List of functions that are called to create and store a link.
6859 Each function will be called in turn until one returns a non-nil
6860 value. Each function should check if it is responsible for creating
6861 this link (for example by looking at the major mode).
6862 If not, it must exit and return nil.
6863 If yes, it should return a non-nil value after a calling
6864 `org-store-link-props' with a list of properties and values.
6865 Special properties are:
6867 :type The link prefix. like \"http\". This must be given.
6868 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6869 This is obligatory as well.
6870 :description Optional default description for the second pair
6871 of brackets in an Org-mode link. The user can still change
6872 this when inserting this link into an Org-mode buffer.
6874 In addition to these, any additional properties can be specified
6875 and then used in remember templates.")
6877 (defun org-add-link-type (type &optional follow export)
6878 "Add TYPE to the list of `org-link-types'.
6879 Re-compute all regular expressions depending on `org-link-types'
6881 FOLLOW and EXPORT are two functions.
6883 FOLLOW should take the link path as the single argument and do whatever
6884 is necessary to follow the link, for example find a file or display
6885 a mail message.
6887 EXPORT should format the link path for export to one of the export formats.
6888 It should be a function accepting three arguments:
6890 path the path of the link, the text after the prefix (like \"http:\")
6891 desc the description of the link, if any, nil if there was no description
6892 format the export format, a symbol like `html' or `latex'.
6894 The function may use the FORMAT information to return different values
6895 depending on the format. The return value will be put literally into
6896 the exported file.
6897 Org-mode has a built-in default for exporting links. If you are happy with
6898 this default, there is no need to define an export function for the link
6899 type. For a simple example of an export function, see `org-bbdb.el'."
6900 (add-to-list 'org-link-types type t)
6901 (org-make-link-regexps)
6902 (if (assoc type org-link-protocols)
6903 (setcdr (assoc type org-link-protocols) (list follow export))
6904 (push (list type follow export) org-link-protocols)))
6906 ;;;###autoload
6907 (defun org-store-link (arg)
6908 "\\<org-mode-map>Store an org-link to the current location.
6909 This link is added to `org-stored-links' and can later be inserted
6910 into an org-buffer with \\[org-insert-link].
6912 For some link types, a prefix arg is interpreted:
6913 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6914 For file links, arg negates `org-context-in-file-links'."
6915 (interactive "P")
6916 (org-load-modules-maybe)
6917 (setq org-store-link-plist nil) ; reset
6918 (let (link cpltxt desc description search txt custom-id)
6919 (cond
6921 ((run-hook-with-args-until-success 'org-store-link-functions)
6922 (setq link (plist-get org-store-link-plist :link)
6923 desc (or (plist-get org-store-link-plist :description) link)))
6925 ((equal (buffer-name) "*Org Edit Src Example*")
6926 (let (label gc)
6927 (while (or (not label)
6928 (save-excursion
6929 (save-restriction
6930 (widen)
6931 (goto-char (point-min))
6932 (re-search-forward
6933 (regexp-quote (format org-coderef-label-format label))
6934 nil t))))
6935 (when label (message "Label exists already") (sit-for 2))
6936 (setq label (read-string "Code line label: " label)))
6937 (end-of-line 1)
6938 (setq link (format org-coderef-label-format label))
6939 (setq gc (- 79 (length link)))
6940 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6941 (insert link)
6942 (setq link (concat "(" label ")") desc nil)))
6944 ((eq major-mode 'calendar-mode)
6945 (let ((cd (calendar-cursor-to-date)))
6946 (setq link
6947 (format-time-string
6948 (car org-time-stamp-formats)
6949 (apply 'encode-time
6950 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6951 nil nil nil))))
6952 (org-store-link-props :type "calendar" :date cd)))
6954 ((eq major-mode 'w3-mode)
6955 (setq cpltxt (if (and (buffer-name)
6956 (not (string-match "Untitled" (buffer-name))))
6957 (buffer-name)
6958 (url-view-url t))
6959 link (org-make-link (url-view-url t)))
6960 (org-store-link-props :type "w3" :url (url-view-url t)))
6962 ((eq major-mode 'w3m-mode)
6963 (setq cpltxt (or w3m-current-title w3m-current-url)
6964 link (org-make-link w3m-current-url))
6965 (org-store-link-props :type "w3m" :url (url-view-url t)))
6967 ((setq search (run-hook-with-args-until-success
6968 'org-create-file-search-functions))
6969 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6970 "::" search))
6971 (setq cpltxt (or description link)))
6973 ((eq major-mode 'image-mode)
6974 (setq cpltxt (concat "file:"
6975 (abbreviate-file-name buffer-file-name))
6976 link (org-make-link cpltxt))
6977 (org-store-link-props :type "image" :file buffer-file-name))
6979 ((eq major-mode 'dired-mode)
6980 ;; link to the file in the current line
6981 (setq cpltxt (concat "file:"
6982 (abbreviate-file-name
6983 (expand-file-name
6984 (dired-get-filename nil t))))
6985 link (org-make-link cpltxt)))
6987 ((and buffer-file-name (org-mode-p))
6988 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
6989 (cond
6990 ((org-in-regexp "<<\\(.*?\\)>>")
6991 (setq cpltxt
6992 (concat "file:"
6993 (abbreviate-file-name buffer-file-name)
6994 "::" (match-string 1))
6995 link (org-make-link cpltxt)))
6996 ((and (featurep 'org-id)
6997 (or (eq org-link-to-org-use-id t)
6998 (and (eq org-link-to-org-use-id 'create-if-interactive)
6999 (interactive-p))
7000 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7001 (interactive-p)
7002 (not custom-id))
7003 (and org-link-to-org-use-id
7004 (condition-case nil
7005 (org-entry-get nil "ID")
7006 (error nil)))))
7007 ;; We can make a link using the ID.
7008 (setq link (condition-case nil
7009 (prog1 (org-id-store-link)
7010 (setq desc (plist-get org-store-link-plist
7011 :description)))
7012 (error
7013 ;; probably before first headline, link to file only
7014 (concat "file:"
7015 (abbreviate-file-name buffer-file-name))))))
7017 ;; Just link to current headline
7018 (setq cpltxt (concat "file:"
7019 (abbreviate-file-name buffer-file-name)))
7020 ;; Add a context search string
7021 (when (org-xor org-context-in-file-links arg)
7022 (setq txt (cond
7023 ((org-on-heading-p) nil)
7024 ((org-region-active-p)
7025 (buffer-substring (region-beginning) (region-end)))
7026 (t nil)))
7027 (when (or (null txt) (string-match "\\S-" txt))
7028 (setq cpltxt
7029 (concat cpltxt "::"
7030 (condition-case nil
7031 (org-make-org-heading-search-string txt)
7032 (error "")))
7033 desc "NONE")))
7034 (if (string-match "::\\'" cpltxt)
7035 (setq cpltxt (substring cpltxt 0 -2)))
7036 (setq link (org-make-link cpltxt)))))
7038 ((buffer-file-name (buffer-base-buffer))
7039 ;; Just link to this file here.
7040 (setq cpltxt (concat "file:"
7041 (abbreviate-file-name
7042 (buffer-file-name (buffer-base-buffer)))))
7043 ;; Add a context string
7044 (when (org-xor org-context-in-file-links arg)
7045 (setq txt (if (org-region-active-p)
7046 (buffer-substring (region-beginning) (region-end))
7047 (buffer-substring (point-at-bol) (point-at-eol))))
7048 ;; Only use search option if there is some text.
7049 (when (string-match "\\S-" txt)
7050 (setq cpltxt
7051 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7052 desc "NONE")))
7053 (setq link (org-make-link cpltxt)))
7055 ((interactive-p)
7056 (error "Cannot link to a buffer which is not visiting a file"))
7058 (t (setq link nil)))
7060 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7061 (setq link (or link cpltxt)
7062 desc (or desc cpltxt))
7063 (if (equal desc "NONE") (setq desc nil))
7065 (if (and (interactive-p) link)
7066 (progn
7067 (setq org-stored-links
7068 (cons (list link desc) org-stored-links))
7069 (message "Stored: %s" (or desc link))
7070 (when custom-id
7071 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7072 "::#" custom-id))
7073 (setq org-stored-links
7074 (cons (list link desc) org-stored-links))))
7075 (and link (org-make-link-string link desc)))))
7077 (defun org-store-link-props (&rest plist)
7078 "Store link properties, extract names and addresses."
7079 (let (x adr)
7080 (when (setq x (plist-get plist :from))
7081 (setq adr (mail-extract-address-components x))
7082 (setq plist (plist-put plist :fromname (car adr)))
7083 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7084 (when (setq x (plist-get plist :to))
7085 (setq adr (mail-extract-address-components x))
7086 (setq plist (plist-put plist :toname (car adr)))
7087 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7088 (let ((from (plist-get plist :from))
7089 (to (plist-get plist :to)))
7090 (when (and from to org-from-is-user-regexp)
7091 (setq plist
7092 (plist-put plist :fromto
7093 (if (string-match org-from-is-user-regexp from)
7094 (concat "to %t")
7095 (concat "from %f"))))))
7096 (setq org-store-link-plist plist))
7098 (defun org-add-link-props (&rest plist)
7099 "Add these properties to the link property list."
7100 (let (key value)
7101 (while plist
7102 (setq key (pop plist) value (pop plist))
7103 (setq org-store-link-plist
7104 (plist-put org-store-link-plist key value)))))
7106 (defun org-email-link-description (&optional fmt)
7107 "Return the description part of an email link.
7108 This takes information from `org-store-link-plist' and formats it
7109 according to FMT (default from `org-email-link-description-format')."
7110 (setq fmt (or fmt org-email-link-description-format))
7111 (let* ((p org-store-link-plist)
7112 (to (plist-get p :toaddress))
7113 (from (plist-get p :fromaddress))
7114 (table
7115 (list
7116 (cons "%c" (plist-get p :fromto))
7117 (cons "%F" (plist-get p :from))
7118 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7119 (cons "%T" (plist-get p :to))
7120 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7121 (cons "%s" (plist-get p :subject))
7122 (cons "%m" (plist-get p :message-id)))))
7123 (when (string-match "%c" fmt)
7124 ;; Check if the user wrote this message
7125 (if (and org-from-is-user-regexp from to
7126 (save-match-data (string-match org-from-is-user-regexp from)))
7127 (setq fmt (replace-match "to %t" t t fmt))
7128 (setq fmt (replace-match "from %f" t t fmt))))
7129 (org-replace-escapes fmt table)))
7131 (defun org-make-org-heading-search-string (&optional string heading)
7132 "Make search string for STRING or current headline."
7133 (interactive)
7134 (let ((s (or string (org-get-heading))))
7135 (unless (and string (not heading))
7136 ;; We are using a headline, clean up garbage in there.
7137 (if (string-match org-todo-regexp s)
7138 (setq s (replace-match "" t t s)))
7139 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7140 (setq s (replace-match "" t t s)))
7141 (setq s (org-trim s))
7142 (if (string-match (concat "^\\(" org-quote-string "\\|"
7143 org-comment-string "\\)") s)
7144 (setq s (replace-match "" t t s)))
7145 (while (string-match org-ts-regexp s)
7146 (setq s (replace-match "" t t s))))
7147 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7148 (setq s (replace-match " " t t s)))
7149 (or string (setq s (concat "*" s))) ; Add * for headlines
7150 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7152 (defun org-make-link (&rest strings)
7153 "Concatenate STRINGS."
7154 (apply 'concat strings))
7156 (defun org-make-link-string (link &optional description)
7157 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7158 (unless (string-match "\\S-" link)
7159 (error "Empty link"))
7160 (when (stringp description)
7161 ;; Remove brackets from the description, they are fatal.
7162 (while (string-match "\\[" description)
7163 (setq description (replace-match "{" t t description)))
7164 (while (string-match "\\]" description)
7165 (setq description (replace-match "}" t t description))))
7166 (when (equal (org-link-escape link) description)
7167 ;; No description needed, it is identical
7168 (setq description nil))
7169 (when (and (not description)
7170 (not (equal link (org-link-escape link))))
7171 (setq description (org-extract-attributes link)))
7172 (concat "[[" (org-link-escape link) "]"
7173 (if description (concat "[" description "]") "")
7174 "]"))
7176 (defconst org-link-escape-chars
7177 '((?\ . "%20")
7178 (?\[ . "%5B")
7179 (?\] . "%5D")
7180 (?\340 . "%E0") ; `a
7181 (?\342 . "%E2") ; ^a
7182 (?\347 . "%E7") ; ,c
7183 (?\350 . "%E8") ; `e
7184 (?\351 . "%E9") ; 'e
7185 (?\352 . "%EA") ; ^e
7186 (?\356 . "%EE") ; ^i
7187 (?\364 . "%F4") ; ^o
7188 (?\371 . "%F9") ; `u
7189 (?\373 . "%FB") ; ^u
7190 (?\; . "%3B")
7191 (?? . "%3F")
7192 (?= . "%3D")
7193 (?+ . "%2B")
7195 "Association list of escapes for some characters problematic in links.
7196 This is the list that is used for internal purposes.")
7198 (defvar org-url-encoding-use-url-hexify nil)
7200 (defconst org-link-escape-chars-browser
7201 '((?\ . "%20")) ; 32 for the SPC char
7202 "Association list of escapes for some characters problematic in links.
7203 This is the list that is used before handing over to the browser.")
7205 (defun org-link-escape (text &optional table)
7206 "Escape characters in TEXT that are problematic for links."
7207 (if org-url-encoding-use-url-hexify
7208 (url-hexify-string text)
7209 (setq table (or table org-link-escape-chars))
7210 (when text
7211 (let ((re (mapconcat (lambda (x) (regexp-quote
7212 (char-to-string (car x))))
7213 table "\\|")))
7214 (while (string-match re text)
7215 (setq text
7216 (replace-match
7217 (cdr (assoc (string-to-char (match-string 0 text))
7218 table))
7219 t t text)))
7220 text))))
7222 (defun org-link-unescape (text &optional table)
7223 "Reverse the action of `org-link-escape'."
7224 (if org-url-encoding-use-url-hexify
7225 (url-unhex-string text)
7226 (setq table (or table org-link-escape-chars))
7227 (when text
7228 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7229 table "\\|")))
7230 (while (string-match re text)
7231 (setq text
7232 (replace-match
7233 (char-to-string (car (rassoc (match-string 0 text) table)))
7234 t t text)))
7235 text))))
7237 (defun org-xor (a b)
7238 "Exclusive or."
7239 (if a (not b) b))
7241 (defun org-fixup-message-id-for-http (s)
7242 "Replace special characters in a message id, so it can be used in an http query."
7243 (while (string-match "<" s)
7244 (setq s (replace-match "%3C" t t s)))
7245 (while (string-match ">" s)
7246 (setq s (replace-match "%3E" t t s)))
7247 (while (string-match "@" s)
7248 (setq s (replace-match "%40" t t s)))
7251 ;;;###autoload
7252 (defun org-insert-link-global ()
7253 "Insert a link like Org-mode does.
7254 This command can be called in any mode to insert a link in Org-mode syntax."
7255 (interactive)
7256 (org-load-modules-maybe)
7257 (org-run-like-in-org-mode 'org-insert-link))
7259 (defun org-insert-link (&optional complete-file link-location)
7260 "Insert a link. At the prompt, enter the link.
7262 Completion can be used to insert any of the link protocol prefixes like
7263 http or ftp in use.
7265 The history can be used to select a link previously stored with
7266 `org-store-link'. When the empty string is entered (i.e. if you just
7267 press RET at the prompt), the link defaults to the most recently
7268 stored link. As SPC triggers completion in the minibuffer, you need to
7269 use M-SPC or C-q SPC to force the insertion of a space character.
7271 You will also be prompted for a description, and if one is given, it will
7272 be displayed in the buffer instead of the link.
7274 If there is already a link at point, this command will allow you to edit link
7275 and description parts.
7277 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7278 be selected using completion. The path to the file will be relative to the
7279 current directory if the file is in the current directory or a subdirectory.
7280 Otherwise, the link will be the absolute path as completed in the minibuffer
7281 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7282 option `org-link-file-path-type'.
7284 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7285 the current directory or below.
7287 With three \\[universal-argument] prefixes, negate the meaning of
7288 `org-keep-stored-link-after-insertion'.
7290 If `org-make-link-description-function' is non-nil, this function will be
7291 called with the link target, and the result will be the default
7292 link description.
7294 If the LINK-LOCATION parameter is non-nil, this value will be
7295 used as the link location instead of reading one interactively."
7296 (interactive "P")
7297 (let* ((wcf (current-window-configuration))
7298 (region (if (org-region-active-p)
7299 (buffer-substring (region-beginning) (region-end))))
7300 (remove (and region (list (region-beginning) (region-end))))
7301 (desc region)
7302 tmphist ; byte-compile incorrectly complains about this
7303 (link link-location)
7304 entry file)
7305 (cond
7306 (link-location) ; specified by arg, just use it.
7307 ((org-in-regexp org-bracket-link-regexp 1)
7308 ;; We do have a link at point, and we are going to edit it.
7309 (setq remove (list (match-beginning 0) (match-end 0)))
7310 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7311 (setq link (read-string "Link: "
7312 (org-link-unescape
7313 (org-match-string-no-properties 1)))))
7314 ((or (org-in-regexp org-angle-link-re)
7315 (org-in-regexp org-plain-link-re))
7316 ;; Convert to bracket link
7317 (setq remove (list (match-beginning 0) (match-end 0))
7318 link (read-string "Link: "
7319 (org-remove-angle-brackets (match-string 0)))))
7320 ((member complete-file '((4) (16)))
7321 ;; Completing read for file names.
7322 (setq file (read-file-name "File: "))
7323 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7324 (pwd1 (file-name-as-directory (abbreviate-file-name
7325 (expand-file-name ".")))))
7326 (cond
7327 ((equal complete-file '(16))
7328 (setq link (org-make-link
7329 "file:"
7330 (abbreviate-file-name (expand-file-name file)))))
7331 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7332 (setq link (org-make-link "file:" (match-string 1 file))))
7333 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7334 (expand-file-name file))
7335 (setq link (org-make-link
7336 "file:" (match-string 1 (expand-file-name file)))))
7337 (t (setq link (org-make-link "file:" file))))))
7339 ;; Read link, with completion for stored links.
7340 (with-output-to-temp-buffer "*Org Links*"
7341 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7342 (when org-stored-links
7343 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7344 (princ (mapconcat
7345 (lambda (x)
7346 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7347 (reverse org-stored-links) "\n"))))
7348 (let ((cw (selected-window)))
7349 (select-window (get-buffer-window "*Org Links*"))
7350 (setq truncate-lines t)
7351 (org-fit-window-to-buffer)
7352 (select-window cw))
7353 ;; Fake a link history, containing the stored links.
7354 (setq tmphist (append (mapcar 'car org-stored-links)
7355 org-insert-link-history))
7356 (unwind-protect
7357 (setq link
7358 (let ((org-completion-use-ido nil))
7359 (org-completing-read
7360 "Link: "
7361 (append
7362 (mapcar (lambda (x) (list (concat (car x) ":")))
7363 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7364 (mapcar (lambda (x) (list (concat x ":")))
7365 org-link-types))
7366 nil nil nil
7367 'tmphist
7368 (or (car (car org-stored-links))))))
7369 (set-window-configuration wcf)
7370 (kill-buffer "*Org Links*"))
7371 (setq entry (assoc link org-stored-links))
7372 (or entry (push link org-insert-link-history))
7373 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7374 (not org-keep-stored-link-after-insertion))
7375 (setq org-stored-links (delq (assoc link org-stored-links)
7376 org-stored-links)))
7377 (setq desc (or desc (nth 1 entry)))))
7379 (if (string-match org-plain-link-re link)
7380 ;; URL-like link, normalize the use of angular brackets.
7381 (setq link (org-make-link (org-remove-angle-brackets link))))
7383 ;; Check if we are linking to the current file with a search option
7384 ;; If yes, simplify the link by using only the search option.
7385 (when (and buffer-file-name
7386 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7387 (let* ((path (match-string 1 link))
7388 (case-fold-search nil)
7389 (search (match-string 2 link)))
7390 (save-match-data
7391 (if (equal (file-truename buffer-file-name) (file-truename path))
7392 ;; We are linking to this same file, with a search option
7393 (setq link search)))))
7395 ;; Check if we can/should use a relative path. If yes, simplify the link
7396 (when (string-match "^file:\\(.*\\)" link)
7397 (let* ((path (match-string 1 link))
7398 (origpath path)
7399 (case-fold-search nil))
7400 (cond
7401 ((or (eq org-link-file-path-type 'absolute)
7402 (equal complete-file '(16)))
7403 (setq path (abbreviate-file-name (expand-file-name path))))
7404 ((eq org-link-file-path-type 'noabbrev)
7405 (setq path (expand-file-name path)))
7406 ((eq org-link-file-path-type 'relative)
7407 (setq path (file-relative-name path)))
7409 (save-match-data
7410 (if (string-match (concat "^" (regexp-quote
7411 (file-name-as-directory
7412 (expand-file-name "."))))
7413 (expand-file-name path))
7414 ;; We are linking a file with relative path name.
7415 (setq path (substring (expand-file-name path)
7416 (match-end 0)))
7417 (setq path (abbreviate-file-name (expand-file-name path)))))))
7418 (setq link (concat "file:" path))
7419 (if (equal desc origpath)
7420 (setq desc path))))
7422 (if org-make-link-description-function
7423 (setq desc (funcall org-make-link-description-function link desc)))
7425 (setq desc (read-string "Description: " desc))
7426 (unless (string-match "\\S-" desc) (setq desc nil))
7427 (if remove (apply 'delete-region remove))
7428 (insert (org-make-link-string link desc))))
7430 (defun org-completing-read (&rest args)
7431 "Completing-read with SPACE being a normal character."
7432 (let ((minibuffer-local-completion-map
7433 (copy-keymap minibuffer-local-completion-map)))
7434 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7435 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7436 (apply 'org-ido-completing-read args)))
7438 (defun org-completing-read-no-ido (&rest args)
7439 (let (org-completion-use-ido)
7440 (apply 'org-completing-read args)))
7442 (defun org-ido-completing-read (&rest args)
7443 "Completing-read using `ido-mode' speedups if available"
7444 (if (and org-completion-use-ido
7445 (fboundp 'ido-completing-read)
7446 (boundp 'ido-mode) ido-mode
7447 (listp (second args)))
7448 (let ((ido-enter-matching-directory nil))
7449 (apply 'ido-completing-read (concat (car args))
7450 (mapcar (lambda (x) (car x)) (nth 1 args))
7451 (cddr args)))
7452 (apply 'completing-read args)))
7454 (defun org-extract-attributes (s)
7455 "Extract the attributes cookie from a string and set as text property."
7456 (let (a attr (start 0) key value)
7457 (save-match-data
7458 (when (string-match "{{\\([^}]+\\)}}$" s)
7459 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7460 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7461 (setq key (match-string 1 a) value (match-string 2 a)
7462 start (match-end 0)
7463 attr (plist-put attr (intern key) value))))
7464 (org-add-props s nil 'org-attr attr))
7467 (defun org-extract-attributes-from-string (tag)
7468 (let (key value attr)
7469 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7470 (setq key (match-string 1 tag) value (match-string 2 tag)
7471 tag (replace-match "" t t tag)
7472 attr (plist-put attr (intern key) value)))
7473 (cons tag attr)))
7475 (defun org-attributes-to-string (plist)
7476 "Format a property list into an HTML attribute list."
7477 (let ((s "") key value)
7478 (while plist
7479 (setq key (pop plist) value (pop plist))
7480 (and value
7481 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7484 ;;; Opening/following a link
7486 (defvar org-link-search-failed nil)
7488 (defun org-next-link ()
7489 "Move forward to the next link.
7490 If the link is in hidden text, expose it."
7491 (interactive)
7492 (when (and org-link-search-failed (eq this-command last-command))
7493 (goto-char (point-min))
7494 (message "Link search wrapped back to beginning of buffer"))
7495 (setq org-link-search-failed nil)
7496 (let* ((pos (point))
7497 (ct (org-context))
7498 (a (assoc :link ct)))
7499 (if a (goto-char (nth 2 a)))
7500 (if (re-search-forward org-any-link-re nil t)
7501 (progn
7502 (goto-char (match-beginning 0))
7503 (if (org-invisible-p) (org-show-context)))
7504 (goto-char pos)
7505 (setq org-link-search-failed t)
7506 (error "No further link found"))))
7508 (defun org-previous-link ()
7509 "Move backward to the previous link.
7510 If the link is in hidden text, expose it."
7511 (interactive)
7512 (when (and org-link-search-failed (eq this-command last-command))
7513 (goto-char (point-max))
7514 (message "Link search wrapped back to end of buffer"))
7515 (setq org-link-search-failed nil)
7516 (let* ((pos (point))
7517 (ct (org-context))
7518 (a (assoc :link ct)))
7519 (if a (goto-char (nth 1 a)))
7520 (if (re-search-backward org-any-link-re nil t)
7521 (progn
7522 (goto-char (match-beginning 0))
7523 (if (org-invisible-p) (org-show-context)))
7524 (goto-char pos)
7525 (setq org-link-search-failed t)
7526 (error "No further link found"))))
7528 (defun org-translate-link (s)
7529 "Translate a link string if a translation function has been defined."
7530 (if (and org-link-translation-function
7531 (fboundp org-link-translation-function)
7532 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7533 (progn
7534 (setq s (funcall org-link-translation-function
7535 (match-string 1) (match-string 2)))
7536 (concat (car s) ":" (cdr s)))
7539 (defun org-translate-link-from-planner (type path)
7540 "Translate a link from Emacs Planner syntax so that Org can follow it.
7541 This is still an experimental function, your mileage may vary."
7542 (cond
7543 ((member type '("http" "https" "news" "ftp"))
7544 ;; standard Internet links are the same.
7545 nil)
7546 ((and (equal type "irc") (string-match "^//" path))
7547 ;; Planner has two / at the beginning of an irc link, we have 1.
7548 ;; We should have zero, actually....
7549 (setq path (substring path 1)))
7550 ((and (equal type "lisp") (string-match "^/" path))
7551 ;; Planner has a slash, we do not.
7552 (setq type "elisp" path (substring path 1)))
7553 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7554 ;; A typical message link. Planner has the id after the fina slash,
7555 ;; we separate it with a hash mark
7556 (setq path (concat (match-string 1 path) "#"
7557 (org-remove-angle-brackets (match-string 2 path)))))
7559 (cons type path))
7561 (defun org-find-file-at-mouse (ev)
7562 "Open file link or URL at mouse."
7563 (interactive "e")
7564 (mouse-set-point ev)
7565 (org-open-at-point 'in-emacs))
7567 (defun org-open-at-mouse (ev)
7568 "Open file link or URL at mouse."
7569 (interactive "e")
7570 (mouse-set-point ev)
7571 (if (eq major-mode 'org-agenda-mode)
7572 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7573 (org-open-at-point))
7575 (defvar org-window-config-before-follow-link nil
7576 "The window configuration before following a link.
7577 This is saved in case the need arises to restore it.")
7579 (defvar org-open-link-marker (make-marker)
7580 "Marker pointing to the location where `org-open-at-point; was called.")
7582 ;;;###autoload
7583 (defun org-open-at-point-global ()
7584 "Follow a link like Org-mode does.
7585 This command can be called in any mode to follow a link that has
7586 Org-mode syntax."
7587 (interactive)
7588 (org-run-like-in-org-mode 'org-open-at-point))
7590 ;;;###autoload
7591 (defun org-open-link-from-string (s &optional arg)
7592 "Open a link in the string S, as if it was in Org-mode."
7593 (interactive "sLink: \nP")
7594 (let ((reference-buffer (current-buffer)))
7595 (with-temp-buffer
7596 (let ((org-inhibit-startup t))
7597 (org-mode)
7598 (insert s)
7599 (goto-char (point-min))
7600 (org-open-at-point arg reference-buffer)))))
7602 (defun org-open-at-point (&optional in-emacs reference-buffer)
7603 "Open link at or after point.
7604 If there is no link at point, this function will search forward up to
7605 the end of the current line.
7606 Normally, files will be opened by an appropriate application. If the
7607 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7608 With a double prefix argument, try to open outside of Emacs, in the
7609 application the system uses for this file type."
7610 (interactive "P")
7611 (org-load-modules-maybe)
7612 (move-marker org-open-link-marker (point))
7613 (setq org-window-config-before-follow-link (current-window-configuration))
7614 (org-remove-occur-highlights nil nil t)
7615 (cond
7616 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7617 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7618 (org-footnote-action))
7620 (let (type path link line search (pos (point)))
7621 (catch 'match
7622 (save-excursion
7623 (skip-chars-forward "^]\n\r")
7624 (when (org-in-regexp org-bracket-link-regexp)
7625 (setq link (org-extract-attributes
7626 (org-link-unescape (org-match-string-no-properties 1))))
7627 (while (string-match " *\n *" link)
7628 (setq link (replace-match " " t t link)))
7629 (setq link (org-link-expand-abbrev link))
7630 (cond
7631 ((or (file-name-absolute-p link)
7632 (string-match "^\\.\\.?/" link))
7633 (setq type "file" path link))
7634 ((string-match org-link-re-with-space3 link)
7635 (setq type (match-string 1 link) path (match-string 2 link)))
7636 (t (setq type "thisfile" path link)))
7637 (throw 'match t)))
7639 (when (get-text-property (point) 'org-linked-text)
7640 (setq type "thisfile"
7641 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7642 (1+ (point)) (point))
7643 path (buffer-substring
7644 (previous-single-property-change pos 'org-linked-text)
7645 (next-single-property-change pos 'org-linked-text)))
7646 (throw 'match t))
7648 (save-excursion
7649 (when (or (org-in-regexp org-angle-link-re)
7650 (org-in-regexp org-plain-link-re))
7651 (setq type (match-string 1) path (match-string 2))
7652 (throw 'match t)))
7653 (save-excursion
7654 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7655 (setq type "tags"
7656 path (match-string 1))
7657 (while (string-match ":" path)
7658 (setq path (replace-match "+" t t path)))
7659 (throw 'match t)))
7660 (when (org-in-regexp "<\\([^><\n]+\\)>")
7661 (setq type "tree-match"
7662 path (match-string 1))
7663 (throw 'match t)))
7664 (unless path
7665 (error "No link found"))
7667 ;; switch back to reference buffer
7668 ;; needed when if called in a temporary buffer through
7669 ;; org-open-link-from-string
7670 (and reference-buffer (switch-to-buffer reference-buffer))
7672 ;; Remove any trailing spaces in path
7673 (if (string-match " +\\'" path)
7674 (setq path (replace-match "" t t path)))
7675 (if (and org-link-translation-function
7676 (fboundp org-link-translation-function))
7677 ;; Check if we need to translate the link
7678 (let ((tmp (funcall org-link-translation-function type path)))
7679 (setq type (car tmp) path (cdr tmp))))
7681 (cond
7683 ((assoc type org-link-protocols)
7684 (funcall (nth 1 (assoc type org-link-protocols)) path))
7686 ((equal type "mailto")
7687 (let ((cmd (car org-link-mailto-program))
7688 (args (cdr org-link-mailto-program)) args1
7689 (address path) (subject "") a)
7690 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7691 (setq address (match-string 1 path)
7692 subject (org-link-escape (match-string 2 path))))
7693 (while args
7694 (cond
7695 ((not (stringp (car args))) (push (pop args) args1))
7696 (t (setq a (pop args))
7697 (if (string-match "%a" a)
7698 (setq a (replace-match address t t a)))
7699 (if (string-match "%s" a)
7700 (setq a (replace-match subject t t a)))
7701 (push a args1))))
7702 (apply cmd (nreverse args1))))
7704 ((member type '("http" "https" "ftp" "news"))
7705 (browse-url (concat type ":" (org-link-escape
7706 path org-link-escape-chars-browser))))
7708 ((member type '("message"))
7709 (browse-url (concat type ":" path)))
7711 ((string= type "tags")
7712 (org-tags-view in-emacs path))
7713 ((string= type "thisfile")
7714 (if in-emacs
7715 (switch-to-buffer-other-window
7716 (org-get-buffer-for-internal-link (current-buffer)))
7717 (org-mark-ring-push))
7718 (let ((cmd `(org-link-search
7719 ,path
7720 ,(cond ((equal in-emacs '(4)) 'occur)
7721 ((equal in-emacs '(16)) 'org-occur)
7722 (t nil))
7723 ,pos)))
7724 (condition-case nil (eval cmd)
7725 (error (progn (widen) (eval cmd))))))
7727 ((string= type "tree-match")
7728 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7730 ((string= type "file")
7731 (if (string-match "::\\([0-9]+\\)\\'" path)
7732 (setq line (string-to-number (match-string 1 path))
7733 path (substring path 0 (match-beginning 0)))
7734 (if (string-match "::\\(.+\\)\\'" path)
7735 (setq search (match-string 1 path)
7736 path (substring path 0 (match-beginning 0)))))
7737 (if (string-match "[*?{]" (file-name-nondirectory path))
7738 (dired path)
7739 (org-open-file path in-emacs line search)))
7741 ((string= type "news")
7742 (require 'org-gnus)
7743 (org-gnus-follow-link path))
7745 ((string= type "shell")
7746 (let ((cmd path))
7747 (if (or (not org-confirm-shell-link-function)
7748 (funcall org-confirm-shell-link-function
7749 (format "Execute \"%s\" in shell? "
7750 (org-add-props cmd nil
7751 'face 'org-warning))))
7752 (progn
7753 (message "Executing %s" cmd)
7754 (shell-command cmd))
7755 (error "Abort"))))
7757 ((string= type "elisp")
7758 (let ((cmd path))
7759 (if (or (not org-confirm-elisp-link-function)
7760 (funcall org-confirm-elisp-link-function
7761 (format "Execute \"%s\" as elisp? "
7762 (org-add-props cmd nil
7763 'face 'org-warning))))
7764 (message "%s => %s" cmd
7765 (if (equal (string-to-char cmd) ?\()
7766 (eval (read cmd))
7767 (call-interactively (read cmd))))
7768 (error "Abort"))))
7771 (browse-url-at-point))))))
7772 (move-marker org-open-link-marker nil)
7773 (run-hook-with-args 'org-follow-link-hook))
7775 ;;;; Time estimates
7777 (defun org-get-effort (&optional pom)
7778 "Get the effort estimate for the current entry."
7779 (org-entry-get pom org-effort-property))
7781 ;;; File search
7783 (defvar org-create-file-search-functions nil
7784 "List of functions to construct the right search string for a file link.
7785 These functions are called in turn with point at the location to
7786 which the link should point.
7788 A function in the hook should first test if it would like to
7789 handle this file type, for example by checking the major-mode or
7790 the file extension. If it decides not to handle this file, it
7791 should just return nil to give other functions a chance. If it
7792 does handle the file, it must return the search string to be used
7793 when following the link. The search string will be part of the
7794 file link, given after a double colon, and `org-open-at-point'
7795 will automatically search for it. If special measures must be
7796 taken to make the search successful, another function should be
7797 added to the companion hook `org-execute-file-search-functions',
7798 which see.
7800 A function in this hook may also use `setq' to set the variable
7801 `description' to provide a suggestion for the descriptive text to
7802 be used for this link when it gets inserted into an Org-mode
7803 buffer with \\[org-insert-link].")
7805 (defvar org-execute-file-search-functions nil
7806 "List of functions to execute a file search triggered by a link.
7808 Functions added to this hook must accept a single argument, the
7809 search string that was part of the file link, the part after the
7810 double colon. The function must first check if it would like to
7811 handle this search, for example by checking the major-mode or the
7812 file extension. If it decides not to handle this search, it
7813 should just return nil to give other functions a chance. If it
7814 does handle the search, it must return a non-nil value to keep
7815 other functions from trying.
7817 Each function can access the current prefix argument through the
7818 variable `current-prefix-argument'. Note that a single prefix is
7819 used to force opening a link in Emacs, so it may be good to only
7820 use a numeric or double prefix to guide the search function.
7822 In case this is needed, a function in this hook can also restore
7823 the window configuration before `org-open-at-point' was called using:
7825 (set-window-configuration org-window-config-before-follow-link)")
7827 (defun org-link-search (s &optional type avoid-pos)
7828 "Search for a link search option.
7829 If S is surrounded by forward slashes, it is interpreted as a
7830 regular expression. In org-mode files, this will create an `org-occur'
7831 sparse tree. In ordinary files, `occur' will be used to list matches.
7832 If the current buffer is in `dired-mode', grep will be used to search
7833 in all files. If AVOID-POS is given, ignore matches near that position."
7834 (let ((case-fold-search t)
7835 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7836 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7837 (append '(("") (" ") ("\t") ("\n"))
7838 org-emphasis-alist)
7839 "\\|") "\\)"))
7840 (pos (point))
7841 (pre nil) (post nil)
7842 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7843 (cond
7844 ;; First check if there are any special
7845 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7846 ;; Now try the builtin stuff
7847 ((and (equal (string-to-char s0) ?#)
7848 (> (length s0) 1)
7849 (save-excursion
7850 (goto-char (point-min))
7851 (and
7852 (re-search-forward
7853 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
7854 (setq type 'dedicated
7855 pos (match-beginning 0))))
7856 ;; There is an exact target for this
7857 (goto-char pos)
7858 (org-back-to-heading t)))
7859 ((save-excursion
7860 (goto-char (point-min))
7861 (and
7862 (re-search-forward
7863 (concat "<<" (regexp-quote s0) ">>") nil t)
7864 (setq type 'dedicated
7865 pos (match-beginning 0))))
7866 ;; There is an exact target for this
7867 (goto-char pos))
7868 ((and (string-match "^(\\(.*\\))$" s0)
7869 (save-excursion
7870 (goto-char (point-min))
7871 (and
7872 (re-search-forward
7873 (concat "[^[]" (regexp-quote
7874 (format org-coderef-label-format
7875 (match-string 1 s0))))
7876 nil t)
7877 (setq type 'dedicated
7878 pos (1+ (match-beginning 0))))))
7879 ;; There is a coderef target for this
7880 (goto-char pos))
7881 ((string-match "^/\\(.*\\)/$" s)
7882 ;; A regular expression
7883 (cond
7884 ((org-mode-p)
7885 (org-occur (match-string 1 s)))
7886 ;;((eq major-mode 'dired-mode)
7887 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7888 (t (org-do-occur (match-string 1 s)))))
7890 ;; A normal search strings
7891 (when (equal (string-to-char s) ?*)
7892 ;; Anchor on headlines, post may include tags.
7893 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7894 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7895 s (substring s 1)))
7896 (remove-text-properties
7897 0 (length s)
7898 '(face nil mouse-face nil keymap nil fontified nil) s)
7899 ;; Make a series of regular expressions to find a match
7900 (setq words (org-split-string s "[ \n\r\t]+")
7902 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7903 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7904 "\\)" markers)
7905 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7906 re2a (concat "[ \t\r\n]" re2a_)
7907 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7908 re4 (concat "[^a-zA-Z_]" re4_)
7910 re1 (concat pre re2 post)
7911 re3 (concat pre (if pre re4_ re4) post)
7912 re5 (concat pre ".*" re4)
7913 re2 (concat pre re2)
7914 re2a (concat pre (if pre re2a_ re2a))
7915 re4 (concat pre (if pre re4_ re4))
7916 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7917 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7918 re5 "\\)"
7920 (cond
7921 ((eq type 'org-occur) (org-occur reall))
7922 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7923 (t (goto-char (point-min))
7924 (setq type 'fuzzy)
7925 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7926 (org-search-not-self 1 re1 nil t)
7927 (org-search-not-self 1 re2 nil t)
7928 (org-search-not-self 1 re2a nil t)
7929 (org-search-not-self 1 re3 nil t)
7930 (org-search-not-self 1 re4 nil t)
7931 (org-search-not-self 1 re5 nil t)
7933 (goto-char (match-beginning 1))
7934 (goto-char pos)
7935 (error "No match")))))
7937 ;; Normal string-search
7938 (goto-char (point-min))
7939 (if (search-forward s nil t)
7940 (goto-char (match-beginning 0))
7941 (error "No match"))))
7942 (and (org-mode-p) (org-show-context 'link-search))
7943 type))
7945 (defun org-search-not-self (group &rest args)
7946 "Execute `re-search-forward', but only accept matches that do not
7947 enclose the position of `org-open-link-marker'."
7948 (let ((m org-open-link-marker))
7949 (catch 'exit
7950 (while (apply 're-search-forward args)
7951 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7952 (goto-char (match-end group))
7953 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7954 (> (match-beginning 0) (marker-position m))
7955 (< (match-end 0) (marker-position m)))
7956 (save-match-data
7957 (or (not (org-in-regexp
7958 org-bracket-link-analytic-regexp 1))
7959 (not (match-end 4)) ; no description
7960 (and (<= (match-beginning 4) (point))
7961 (>= (match-end 4) (point))))))
7962 (throw 'exit (point))))))))
7964 (defun org-get-buffer-for-internal-link (buffer)
7965 "Return a buffer to be used for displaying the link target of internal links."
7966 (cond
7967 ((not org-display-internal-link-with-indirect-buffer)
7968 buffer)
7969 ((string-match "(Clone)$" (buffer-name buffer))
7970 (message "Buffer is already a clone, not making another one")
7971 ;; we also do not modify visibility in this case
7972 buffer)
7973 (t ; make a new indirect buffer for displaying the link
7974 (let* ((bn (buffer-name buffer))
7975 (ibn (concat bn "(Clone)"))
7976 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7977 (with-current-buffer ib (org-overview))
7978 ib))))
7980 (defun org-do-occur (regexp &optional cleanup)
7981 "Call the Emacs command `occur'.
7982 If CLEANUP is non-nil, remove the printout of the regular expression
7983 in the *Occur* buffer. This is useful if the regex is long and not useful
7984 to read."
7985 (occur regexp)
7986 (when cleanup
7987 (let ((cwin (selected-window)) win beg end)
7988 (when (setq win (get-buffer-window "*Occur*"))
7989 (select-window win))
7990 (goto-char (point-min))
7991 (when (re-search-forward "match[a-z]+" nil t)
7992 (setq beg (match-end 0))
7993 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7994 (setq end (1- (match-beginning 0)))))
7995 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7996 (goto-char (point-min))
7997 (select-window cwin))))
7999 ;;; The mark ring for links jumps
8001 (defvar org-mark-ring nil
8002 "Mark ring for positions before jumps in Org-mode.")
8003 (defvar org-mark-ring-last-goto nil
8004 "Last position in the mark ring used to go back.")
8005 ;; Fill and close the ring
8006 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8007 (loop for i from 1 to org-mark-ring-length do
8008 (push (make-marker) org-mark-ring))
8009 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8010 org-mark-ring)
8012 (defun org-mark-ring-push (&optional pos buffer)
8013 "Put the current position or POS into the mark ring and rotate it."
8014 (interactive)
8015 (setq pos (or pos (point)))
8016 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8017 (move-marker (car org-mark-ring)
8018 (or pos (point))
8019 (or buffer (current-buffer)))
8020 (message "%s"
8021 (substitute-command-keys
8022 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8024 (defun org-mark-ring-goto (&optional n)
8025 "Jump to the previous position in the mark ring.
8026 With prefix arg N, jump back that many stored positions. When
8027 called several times in succession, walk through the entire ring.
8028 Org-mode commands jumping to a different position in the current file,
8029 or to another Org-mode file, automatically push the old position
8030 onto the ring."
8031 (interactive "p")
8032 (let (p m)
8033 (if (eq last-command this-command)
8034 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8035 (setq p org-mark-ring))
8036 (setq org-mark-ring-last-goto p)
8037 (setq m (car p))
8038 (switch-to-buffer (marker-buffer m))
8039 (goto-char m)
8040 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8042 (defun org-remove-angle-brackets (s)
8043 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8044 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8046 (defun org-add-angle-brackets (s)
8047 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8048 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8050 (defun org-remove-double-quotes (s)
8051 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8052 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8055 ;;; Following specific links
8057 (defun org-follow-timestamp-link ()
8058 (cond
8059 ((org-at-date-range-p t)
8060 (let ((org-agenda-start-on-weekday)
8061 (t1 (match-string 1))
8062 (t2 (match-string 2)))
8063 (setq t1 (time-to-days (org-time-string-to-time t1))
8064 t2 (time-to-days (org-time-string-to-time t2)))
8065 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8066 ((org-at-timestamp-p t)
8067 (org-agenda-list nil (time-to-days (org-time-string-to-time
8068 (substring (match-string 1) 0 10)))
8070 (t (error "This should not happen"))))
8073 ;;; Following file links
8074 (defvar org-wait nil)
8075 (defun org-open-file (path &optional in-emacs line search)
8076 "Open the file at PATH.
8077 First, this expands any special file name abbreviations. Then the
8078 configuration variable `org-file-apps' is checked if it contains an
8079 entry for this file type, and if yes, the corresponding command is launched.
8081 If no application is found, Emacs simply visits the file.
8083 With optional prefix argument IN-EMACS, Emacs will visit the file.
8084 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8085 and o use an external application to visit the file.
8087 Optional LINE specifies a line to go to, optional SEARCH a string to
8088 search for. If LINE or SEARCH is given, the file will always be
8089 opened in Emacs.
8090 If the file does not exist, an error is thrown."
8091 (setq in-emacs (or in-emacs line search))
8092 (let* ((file (if (equal path "")
8093 buffer-file-name
8094 (substitute-in-file-name (expand-file-name path))))
8095 (apps (append org-file-apps (org-default-apps)))
8096 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8097 (dirp (if remp nil (file-directory-p file)))
8098 (file (if (and dirp org-open-directory-means-index-dot-org)
8099 (concat (file-name-as-directory file) "index.org")
8100 file))
8101 (a-m-a-p (assq 'auto-mode apps))
8102 (dfile (downcase file))
8103 (old-buffer (current-buffer))
8104 (old-pos (point))
8105 (old-mode major-mode)
8106 ext cmd)
8107 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8108 (setq ext (match-string 1 dfile))
8109 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8110 (setq ext (match-string 1 dfile))))
8111 (cond
8112 ((equal in-emacs '(16))
8113 (setq cmd (cdr (assoc 'system apps))))
8114 (in-emacs (setq cmd 'emacs))
8116 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8117 (and dirp (cdr (assoc 'directory apps)))
8118 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8119 'string-match)
8120 (cdr (assoc ext apps))
8121 (cdr (assoc t apps))))))
8122 (when (eq cmd 'system)
8123 (setq cmd (cdr (assoc 'system apps))))
8124 (when (eq cmd 'default)
8125 (setq cmd (cdr (assoc t apps))))
8126 (when (eq cmd 'mailcap)
8127 (require 'mailcap)
8128 (mailcap-parse-mailcaps)
8129 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8130 (command (mailcap-mime-info mime-type)))
8131 (if (stringp command)
8132 (setq cmd command)
8133 (setq cmd 'emacs))))
8134 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8135 (not (file-exists-p file))
8136 (not org-open-non-existing-files))
8137 (error "No such file: %s" file))
8138 (cond
8139 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8140 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8141 (while (string-match "['\"]%s['\"]" cmd)
8142 (setq cmd (replace-match "%s" t t cmd)))
8143 (while (string-match "%s" cmd)
8144 (setq cmd (replace-match
8145 (save-match-data
8146 (shell-quote-argument
8147 (convert-standard-filename file)))
8148 t t cmd)))
8149 (save-window-excursion
8150 (start-process-shell-command cmd nil cmd)
8151 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8153 ((or (stringp cmd)
8154 (eq cmd 'emacs))
8155 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8156 (widen)
8157 (if line (goto-line line)
8158 (if search (org-link-search search))))
8159 ((consp cmd)
8160 (let ((file (convert-standard-filename file)))
8161 (eval cmd)))
8162 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8163 (and (org-mode-p) (eq old-mode 'org-mode)
8164 (or (not (equal old-buffer (current-buffer)))
8165 (not (equal old-pos (point))))
8166 (org-mark-ring-push old-pos old-buffer))))
8168 (defun org-default-apps ()
8169 "Return the default applications for this operating system."
8170 (cond
8171 ((eq system-type 'darwin)
8172 org-file-apps-defaults-macosx)
8173 ((eq system-type 'windows-nt)
8174 org-file-apps-defaults-windowsnt)
8175 (t org-file-apps-defaults-gnu)))
8177 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8178 "Convert extensions to regular expressions in the cars of LIST.
8179 Also, weed out any non-string entries, because the return value is used
8180 only for regexp matching.
8181 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8182 point to the symbol `emacs', indicating that the file should
8183 be opened in Emacs."
8184 (append
8185 (delq nil
8186 (mapcar (lambda (x)
8187 (if (not (stringp (car x)))
8189 (if (string-match "\\W" (car x))
8191 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8192 list))
8193 (if add-auto-mode
8194 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8196 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8197 (defun org-file-remote-p (file)
8198 "Test whether FILE specifies a location on a remote system.
8199 Return non-nil if the location is indeed remote.
8201 For example, the filename \"/user@host:/foo\" specifies a location
8202 on the system \"/user@host:\"."
8203 (cond ((fboundp 'file-remote-p)
8204 (file-remote-p file))
8205 ((fboundp 'tramp-handle-file-remote-p)
8206 (tramp-handle-file-remote-p file))
8207 ((and (boundp 'ange-ftp-name-format)
8208 (string-match (car ange-ftp-name-format) file))
8210 (t nil)))
8213 ;;;; Refiling
8215 (defun org-get-org-file ()
8216 "Read a filename, with default directory `org-directory'."
8217 (let ((default (or org-default-notes-file remember-data-file)))
8218 (read-file-name (format "File name [%s]: " default)
8219 (file-name-as-directory org-directory)
8220 default)))
8222 (defun org-notes-order-reversed-p ()
8223 "Check if the current file should receive notes in reversed order."
8224 (cond
8225 ((not org-reverse-note-order) nil)
8226 ((eq t org-reverse-note-order) t)
8227 ((not (listp org-reverse-note-order)) nil)
8228 (t (catch 'exit
8229 (let ((all org-reverse-note-order)
8230 entry)
8231 (while (setq entry (pop all))
8232 (if (string-match (car entry) buffer-file-name)
8233 (throw 'exit (cdr entry))))
8234 nil)))))
8236 (defvar org-refile-target-table nil
8237 "The list of refile targets, created by `org-refile'.")
8239 (defvar org-agenda-new-buffers nil
8240 "Buffers created to visit agenda files.")
8242 (defun org-get-refile-targets (&optional default-buffer)
8243 "Produce a table with refile targets."
8244 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8245 targets txt re files f desc descre fast-path-p level pos0)
8246 (message "Getting targets...")
8247 (with-current-buffer (or default-buffer (current-buffer))
8248 (while (setq entry (pop entries))
8249 (setq files (car entry) desc (cdr entry))
8250 (setq fast-path-p nil)
8251 (cond
8252 ((null files) (setq files (list (current-buffer))))
8253 ((eq files 'org-agenda-files)
8254 (setq files (org-agenda-files 'unrestricted)))
8255 ((and (symbolp files) (fboundp files))
8256 (setq files (funcall files)))
8257 ((and (symbolp files) (boundp files))
8258 (setq files (symbol-value files))))
8259 (if (stringp files) (setq files (list files)))
8260 (cond
8261 ((eq (car desc) :tag)
8262 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8263 ((eq (car desc) :todo)
8264 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8265 ((eq (car desc) :regexp)
8266 (setq descre (cdr desc)))
8267 ((eq (car desc) :level)
8268 (setq descre (concat "^\\*\\{" (number-to-string
8269 (if org-odd-levels-only
8270 (1- (* 2 (cdr desc)))
8271 (cdr desc)))
8272 "\\}[ \t]")))
8273 ((eq (car desc) :maxlevel)
8274 (setq fast-path-p t)
8275 (setq descre (concat "^\\*\\{1," (number-to-string
8276 (if org-odd-levels-only
8277 (1- (* 2 (cdr desc)))
8278 (cdr desc)))
8279 "\\}[ \t]")))
8280 (t (error "Bad refiling target description %s" desc)))
8281 (while (setq f (pop files))
8282 (save-excursion
8283 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8284 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8285 (setq f (expand-file-name f))
8286 (if (eq org-refile-use-outline-path 'file)
8287 (push (list (file-name-nondirectory f) f nil nil) targets))
8288 (save-excursion
8289 (save-restriction
8290 (widen)
8291 (goto-char (point-min))
8292 (while (re-search-forward descre nil t)
8293 (goto-char (setq pos0 (point-at-bol)))
8294 (catch 'next
8295 (when org-refile-target-verify-function
8296 (save-match-data
8297 (or (funcall org-refile-target-verify-function)
8298 (throw 'next t))))
8299 (when (looking-at org-complex-heading-regexp)
8300 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8301 txt (org-link-display-format (match-string 4))
8302 re (concat "^" (regexp-quote
8303 (buffer-substring (match-beginning 1)
8304 (match-end 4)))))
8305 (if (match-end 5) (setq re (concat re "[ \t]+"
8306 (regexp-quote
8307 (match-string 5)))))
8308 (setq re (concat re "[ \t]*$"))
8309 (when org-refile-use-outline-path
8310 (setq txt (mapconcat 'org-protect-slash
8311 (append
8312 (if (eq org-refile-use-outline-path 'file)
8313 (list (file-name-nondirectory
8314 (buffer-file-name (buffer-base-buffer))))
8315 (if (eq org-refile-use-outline-path 'full-file-path)
8316 (list (buffer-file-name (buffer-base-buffer)))))
8317 (org-get-outline-path fast-path-p level txt)
8318 (list txt))
8319 "/")))
8320 (push (list txt f re (point)) targets)))
8321 (when (= (point) pos0)
8322 ;; verification function has not moved point
8323 (goto-char (point-at-eol))))))))))
8324 (message "Getting targets...done")
8325 (nreverse targets)))
8327 (defun org-protect-slash (s)
8328 (while (string-match "/" s)
8329 (setq s (replace-match "\\" t t s)))
8332 (defvar org-olpa (make-vector 20 nil))
8334 (defun org-get-outline-path (&optional fastp level heading)
8335 "Return the outline path to the current entry, as a list."
8336 (if fastp
8337 (progn
8338 (if (> level 19)
8339 (error "Outline path failure, more than 19 levels."))
8340 (loop for i from level upto 19 do
8341 (aset org-olpa i nil))
8342 (prog1
8343 (delq nil (append org-olpa nil))
8344 (aset org-olpa level heading)))
8345 (let (rtn)
8346 (save-excursion
8347 (while (org-up-heading-safe)
8348 (when (looking-at org-complex-heading-regexp)
8349 (push (org-match-string-no-properties 4) rtn)))
8350 rtn))))
8352 (defvar org-refile-history nil
8353 "History for refiling operations.")
8355 (defun org-refile (&optional goto default-buffer)
8356 "Move the entry at point to another heading.
8357 The list of target headings is compiled using the information in
8358 `org-refile-targets', which see. This list is created before each use
8359 and will therefore always be up-to-date.
8361 At the target location, the entry is filed as a subitem of the target heading.
8362 Depending on `org-reverse-note-order', the new subitem will either be the
8363 first or the last subitem.
8365 If there is an active region, all entries in that region will be moved.
8366 However, the region must fulfil the requirement that the first heading
8367 is the first one sets the top-level of the moved text - at most siblings
8368 below it are allowed.
8370 With prefix arg GOTO, the command will only visit the target location,
8371 not actually move anything.
8372 With a double prefix `C-u C-u', go to the location where the last refiling
8373 operation has put the subtree.
8375 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8376 (interactive "P")
8377 (let* ((cbuf (current-buffer))
8378 (regionp (org-region-active-p))
8379 (region-start (and regionp (region-beginning)))
8380 (region-end (and regionp (region-end)))
8381 (region-length (and regionp (- region-end region-start)))
8382 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8383 pos it nbuf file re level reversed)
8384 (when regionp (goto-char region-start)
8385 (unless (org-kill-is-subtree-p
8386 (buffer-substring region-start region-end))
8387 (error "The region is not a (sequence of) subtree(s)")))
8388 (if (equal goto '(16))
8389 (org-refile-goto-last-stored)
8390 (when (setq it (org-refile-get-location
8391 (if goto "Goto: " "Refile to: ") default-buffer
8392 org-refile-allow-creating-parent-nodes))
8393 (setq file (nth 1 it)
8394 re (nth 2 it)
8395 pos (nth 3 it))
8396 (if (and (not goto)
8398 (equal (buffer-file-name) file)
8399 (if regionp
8400 (and (>= pos region-start)
8401 (<= pos region-end))
8402 (and (>= pos (point))
8403 (< pos (save-excursion
8404 (org-end-of-subtree t t))))))
8405 (error "Cannot refile to position inside the tree or region"))
8407 (setq nbuf (or (find-buffer-visiting file)
8408 (find-file-noselect file)))
8409 (if goto
8410 (progn
8411 (switch-to-buffer nbuf)
8412 (goto-char pos)
8413 (org-show-context 'org-goto))
8414 (if regionp
8415 (progn
8416 (kill-new (buffer-substring region-start region-end))
8417 (org-save-markers-in-region region-start region-end))
8418 (org-copy-subtree 1 nil t))
8419 (save-excursion
8420 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8421 (find-file-noselect file))))
8422 (setq reversed (org-notes-order-reversed-p))
8423 (save-excursion
8424 (save-restriction
8425 (widen)
8426 (if pos
8427 (progn
8428 (goto-char pos)
8429 (looking-at outline-regexp)
8430 (setq level (org-get-valid-level (funcall outline-level) 1))
8431 (goto-char
8432 (if reversed
8433 (or (outline-next-heading) (point-max))
8434 (or (save-excursion (outline-get-next-sibling))
8435 (org-end-of-subtree t t)
8436 (point-max)))))
8437 (setq level 1)
8438 (if (not reversed)
8439 (goto-char (point-max))
8440 (goto-char (point-min))
8441 (or (outline-next-heading) (goto-char (point-max)))))
8442 (if (not (bolp)) (newline))
8443 (bookmark-set "org-refile-last-stored")
8444 (org-paste-subtree level))))
8445 (if regionp
8446 (delete-region (point) (+ (point) region-length))
8447 (org-cut-subtree))
8448 (setq org-markers-to-move nil)
8449 (message "Refiled to \"%s\"" (car it))))))
8450 (org-reveal))
8452 (defun org-refile-goto-last-stored ()
8453 "Go to the location where the last refile was stored."
8454 (interactive)
8455 (bookmark-jump "org-refile-last-stored")
8456 (message "This is the location of the last refile"))
8458 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8459 "Prompt the user for a refile location, using PROMPT."
8460 (let ((org-refile-targets org-refile-targets)
8461 (org-refile-use-outline-path org-refile-use-outline-path))
8462 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8463 (unless org-refile-target-table
8464 (error "No refile targets"))
8465 (let* ((cbuf (current-buffer))
8466 (partial-completion-mode nil)
8467 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8468 (cfunc (if (and org-refile-use-outline-path
8469 org-outline-path-complete-in-steps)
8470 'org-olpath-completing-read
8471 'org-ido-completing-read))
8472 (extra (if org-refile-use-outline-path "/" ""))
8473 (filename (and cfn (expand-file-name cfn)))
8474 (tbl (mapcar
8475 (lambda (x)
8476 (if (and (not (member org-refile-use-outline-path
8477 '(file full-file-path)))
8478 (not (equal filename (nth 1 x))))
8479 (cons (concat (car x) extra " ("
8480 (file-name-nondirectory (nth 1 x)) ")")
8481 (cdr x))
8482 (cons (concat (car x) extra) (cdr x))))
8483 org-refile-target-table))
8484 (completion-ignore-case t)
8485 pa answ parent-target child parent)
8486 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8487 nil 'org-refile-history))
8488 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8489 (if pa
8491 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8492 (setq parent (match-string 1 answ)
8493 child (match-string 2 answ))
8494 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8495 (when (and parent-target
8496 (or (eq new-nodes t)
8497 (and (eq new-nodes 'confirm)
8498 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8499 (org-refile-new-child parent-target child))))))
8501 (defun org-refile-new-child (parent-target child)
8502 "Use refile target PARENT-TARGET to add new CHILD below it."
8503 (unless parent-target
8504 (error "Cannot find parent for new node"))
8505 (let ((file (nth 1 parent-target))
8506 (pos (nth 3 parent-target))
8507 level)
8508 (with-current-buffer (or (find-buffer-visiting file)
8509 (find-file-noselect file))
8510 (save-excursion
8511 (save-restriction
8512 (widen)
8513 (if pos
8514 (goto-char pos)
8515 (goto-char (point-max))
8516 (if (not (bolp)) (newline)))
8517 (when (looking-at outline-regexp)
8518 (setq level (funcall outline-level))
8519 (org-end-of-subtree t t))
8520 (org-back-over-empty-lines)
8521 (insert "\n" (make-string
8522 (if pos (org-get-valid-level level 1) 1) ?*)
8523 " " child "\n")
8524 (beginning-of-line 0)
8525 (list (concat (car parent-target) "/" child) file "" (point)))))))
8527 (defun org-olpath-completing-read (prompt collection &rest args)
8528 "Read an outline path like a file name."
8529 (let ((thetable collection)
8530 (org-completion-use-ido nil)) ; does not work with ido.
8531 (apply
8532 'org-ido-completing-read prompt
8533 (lambda (string predicate &optional flag)
8534 (let (rtn r f (l (length string)))
8535 (cond
8536 ((eq flag nil)
8537 ;; try completion
8538 (try-completion string thetable))
8539 ((eq flag t)
8540 ;; all-completions
8541 (setq rtn (all-completions string thetable predicate))
8542 (mapcar
8543 (lambda (x)
8544 (setq r (substring x l))
8545 (if (string-match " ([^)]*)$" x)
8546 (setq f (match-string 0 x))
8547 (setq f ""))
8548 (if (string-match "/" r)
8549 (concat string (substring r 0 (match-end 0)) f)
8551 rtn))
8552 ((eq flag 'lambda)
8553 ;; exact match?
8554 (assoc string thetable)))
8556 args)))
8558 ;;;; Dynamic blocks
8560 (defun org-find-dblock (name)
8561 "Find the first dynamic block with name NAME in the buffer.
8562 If not found, stay at current position and return nil."
8563 (let (pos)
8564 (save-excursion
8565 (goto-char (point-min))
8566 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8567 nil t)
8568 (match-beginning 0))))
8569 (if pos (goto-char pos))
8570 pos))
8572 (defconst org-dblock-start-re
8573 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8574 "Matches the startline of a dynamic block, with parameters.")
8576 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8577 "Matches the end of a dynamic block.")
8579 (defun org-create-dblock (plist)
8580 "Create a dynamic block section, with parameters taken from PLIST.
8581 PLIST must contain a :name entry which is used as name of the block."
8582 (unless (bolp) (newline))
8583 (let ((name (plist-get plist :name)))
8584 (insert "#+BEGIN: " name)
8585 (while plist
8586 (if (eq (car plist) :name)
8587 (setq plist (cddr plist))
8588 (insert " " (prin1-to-string (pop plist)))))
8589 (insert "\n\n#+END:\n")
8590 (beginning-of-line -2)))
8592 (defun org-prepare-dblock ()
8593 "Prepare dynamic block for refresh.
8594 This empties the block, puts the cursor at the insert position and returns
8595 the property list including an extra property :name with the block name."
8596 (unless (looking-at org-dblock-start-re)
8597 (error "Not at a dynamic block"))
8598 (let* ((begdel (1+ (match-end 0)))
8599 (name (org-no-properties (match-string 1)))
8600 (params (append (list :name name)
8601 (read (concat "(" (match-string 3) ")")))))
8602 (unless (re-search-forward org-dblock-end-re nil t)
8603 (error "Dynamic block not terminated"))
8604 (setq params
8605 (append params
8606 (list :content (buffer-substring
8607 begdel (match-beginning 0)))))
8608 (delete-region begdel (match-beginning 0))
8609 (goto-char begdel)
8610 (open-line 1)
8611 params))
8613 (defun org-map-dblocks (&optional command)
8614 "Apply COMMAND to all dynamic blocks in the current buffer.
8615 If COMMAND is not given, use `org-update-dblock'."
8616 (let ((cmd (or command 'org-update-dblock))
8617 pos)
8618 (save-excursion
8619 (goto-char (point-min))
8620 (while (re-search-forward org-dblock-start-re nil t)
8621 (goto-char (setq pos (match-beginning 0)))
8622 (condition-case nil
8623 (funcall cmd)
8624 (error (message "Error during update of dynamic block")))
8625 (goto-char pos)
8626 (unless (re-search-forward org-dblock-end-re nil t)
8627 (error "Dynamic block not terminated"))))))
8629 (defun org-dblock-update (&optional arg)
8630 "User command for updating dynamic blocks.
8631 Update the dynamic block at point. With prefix ARG, update all dynamic
8632 blocks in the buffer."
8633 (interactive "P")
8634 (if arg
8635 (org-update-all-dblocks)
8636 (or (looking-at org-dblock-start-re)
8637 (org-beginning-of-dblock))
8638 (org-update-dblock)))
8640 (defun org-update-dblock ()
8641 "Update the dynamic block at point
8642 This means to empty the block, parse for parameters and then call
8643 the correct writing function."
8644 (save-window-excursion
8645 (let* ((pos (point))
8646 (line (org-current-line))
8647 (params (org-prepare-dblock))
8648 (name (plist-get params :name))
8649 (cmd (intern (concat "org-dblock-write:" name))))
8650 (message "Updating dynamic block `%s' at line %d..." name line)
8651 (funcall cmd params)
8652 (message "Updating dynamic block `%s' at line %d...done" name line)
8653 (goto-char pos))))
8655 (defun org-beginning-of-dblock ()
8656 "Find the beginning of the dynamic block at point.
8657 Error if there is no such block at point."
8658 (let ((pos (point))
8659 beg)
8660 (end-of-line 1)
8661 (if (and (re-search-backward org-dblock-start-re nil t)
8662 (setq beg (match-beginning 0))
8663 (re-search-forward org-dblock-end-re nil t)
8664 (> (match-end 0) pos))
8665 (goto-char beg)
8666 (goto-char pos)
8667 (error "Not in a dynamic block"))))
8669 (defun org-update-all-dblocks ()
8670 "Update all dynamic blocks in the buffer.
8671 This function can be used in a hook."
8672 (when (org-mode-p)
8673 (org-map-dblocks 'org-update-dblock)))
8676 ;;;; Completion
8678 (defconst org-additional-option-like-keywords
8679 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8680 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8681 "LATEX_HEADER:"
8682 "BEGIN_EXAMPLE" "END_EXAMPLE"
8683 "BEGIN_QUOTE" "END_QUOTE"
8684 "BEGIN_VERSE" "END_VERSE"
8685 "BEGIN_CENTER" "END_CENTER"
8686 "BEGIN_SRC" "END_SRC"
8687 "CATEGORY" "COLUMNS"
8688 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8690 (defcustom org-structure-template-alist
8692 ("s" "#+begin_src ?\n\n#+end_src"
8693 "<src lang=\"?\">\n\n</src>")
8694 ("e" "#+begin_example\n?\n#+end_example"
8695 "<example>\n?\n</example>")
8696 ("q" "#+begin_quote\n?\n#+end_quote"
8697 "<quote>\n?\n</quote>")
8698 ("v" "#+begin_verse\n?\n#+end_verse"
8699 "<verse>\n?\n/verse>")
8700 ("c" "#+begin_center\n?\n#+end_center"
8701 "<center>\n?\n/center>")
8702 ("l" "#+begin_latex\n?\n#+end_latex"
8703 "<literal style=\"latex\">\n?\n</literal>")
8704 ("L" "#+latex: "
8705 "<literal style=\"latex\">?</literal>")
8706 ("h" "#+begin_html\n?\n#+end_html"
8707 "<literal style=\"html\">\n?\n</literal>")
8708 ("H" "#+html: "
8709 "<literal style=\"html\">?</literal>")
8710 ("a" "#+begin_ascii\n?\n#+end_ascii")
8711 ("A" "#+ascii: ")
8712 ("i" "#+include %file ?"
8713 "<include file=%file markup=\"?\">")
8715 "Structure completion elements.
8716 This is a list of abbreviation keys and values. The value gets inserted
8717 it you type @samp{.} followed by the key and then the completion key,
8718 usually `M-TAB'. %file will be replaced by a file name after prompting
8719 for the file using completion.
8720 There are two templates for each key, the first uses the original Org syntax,
8721 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8722 the default when the /org-mtags.el/ module has been loaded. See also the
8723 variable `org-mtags-prefer-muse-templates'.
8724 This is an experimental feature, it is undecided if it is going to stay in."
8725 :group 'org-completion
8726 :type '(repeat
8727 (string :tag "Key")
8728 (string :tag "Template")
8729 (string :tag "Muse Template")))
8731 (defun org-try-structure-completion ()
8732 "Try to complete a structure template before point.
8733 This looks for strings like \"<e\" on an otherwise empty line and
8734 expands them."
8735 (let ((l (buffer-substring (point-at-bol) (point)))
8737 (when (and (looking-at "[ \t]*$")
8738 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8739 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8740 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8741 (match-beginning 1)) a)
8742 t)))
8744 (defun org-complete-expand-structure-template (start cell)
8745 "Expand a structure template."
8746 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8747 (rpl (nth (if musep 2 1) cell)))
8748 (delete-region start (point))
8749 (when (string-match "\\`#\\+" rpl)
8750 (cond
8751 ((bolp))
8752 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8753 (delete-region (point-at-bol) (point)))
8754 (t (newline))))
8755 (setq start (point))
8756 (if (string-match "%file" rpl)
8757 (setq rpl (replace-match
8758 (concat
8759 "\""
8760 (save-match-data
8761 (abbreviate-file-name (read-file-name "Include file: ")))
8762 "\"")
8763 t t rpl)))
8764 (insert rpl)
8765 (if (re-search-backward "\\?" start t) (delete-char 1))))
8768 (defun org-complete (&optional arg)
8769 "Perform completion on word at point.
8770 At the beginning of a headline, this completes TODO keywords as given in
8771 `org-todo-keywords'.
8772 If the current word is preceded by a backslash, completes the TeX symbols
8773 that are supported for HTML support.
8774 If the current word is preceded by \"#+\", completes special words for
8775 setting file options.
8776 In the line after \"#+STARTUP:, complete valid keywords.\"
8777 At all other locations, this simply calls the value of
8778 `org-completion-fallback-command'."
8779 (interactive "P")
8780 (org-without-partial-completion
8781 (catch 'exit
8782 (let* ((a nil)
8783 (end (point))
8784 (beg1 (save-excursion
8785 (skip-chars-backward (org-re "[:alnum:]_@"))
8786 (point)))
8787 (beg (save-excursion
8788 (skip-chars-backward "a-zA-Z0-9_:$")
8789 (point)))
8790 (confirm (lambda (x) (stringp (car x))))
8791 (searchhead (equal (char-before beg) ?*))
8792 (struct
8793 (when (and (member (char-before beg1) '(?. ?<))
8794 (setq a (assoc (buffer-substring beg1 (point))
8795 org-structure-template-alist)))
8796 (org-complete-expand-structure-template (1- beg1) a)
8797 (throw 'exit t)))
8798 (tag (and (equal (char-before beg1) ?:)
8799 (equal (char-after (point-at-bol)) ?*)))
8800 (prop (and (equal (char-before beg1) ?:)
8801 (not (equal (char-after (point-at-bol)) ?*))))
8802 (texp (equal (char-before beg) ?\\))
8803 (link (equal (char-before beg) ?\[))
8804 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8805 beg)
8806 "#+"))
8807 (startup (string-match "^#\\+STARTUP:.*"
8808 (buffer-substring (point-at-bol) (point))))
8809 (completion-ignore-case opt)
8810 (type nil)
8811 (tbl nil)
8812 (table (cond
8813 (opt
8814 (setq type :opt)
8815 (require 'org-exp)
8816 (append
8817 (mapcar
8818 (lambda (x)
8819 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8820 (cons (match-string 2 x) (match-string 1 x)))
8821 (org-split-string (org-get-current-options) "\n"))
8822 (mapcar 'list org-additional-option-like-keywords)))
8823 (startup
8824 (setq type :startup)
8825 org-startup-options)
8826 (link (append org-link-abbrev-alist-local
8827 org-link-abbrev-alist))
8828 (texp
8829 (setq type :tex)
8830 org-html-entities)
8831 ((string-match "\\`\\*+[ \t]+\\'"
8832 (buffer-substring (point-at-bol) beg))
8833 (setq type :todo)
8834 (mapcar 'list org-todo-keywords-1))
8835 (searchhead
8836 (setq type :searchhead)
8837 (save-excursion
8838 (goto-char (point-min))
8839 (while (re-search-forward org-todo-line-regexp nil t)
8840 (push (list
8841 (org-make-org-heading-search-string
8842 (match-string 3) t))
8843 tbl)))
8844 tbl)
8845 (tag (setq type :tag beg beg1)
8846 (or org-tag-alist (org-get-buffer-tags)))
8847 (prop (setq type :prop beg beg1)
8848 (mapcar 'list (org-buffer-property-keys nil t t)))
8849 (t (progn
8850 (call-interactively org-completion-fallback-command)
8851 (throw 'exit nil)))))
8852 (pattern (buffer-substring-no-properties beg end))
8853 (completion (try-completion pattern table confirm)))
8854 (cond ((eq completion t)
8855 (if (not (assoc (upcase pattern) table))
8856 (message "Already complete")
8857 (if (and (equal type :opt)
8858 (not (member (car (assoc (upcase pattern) table))
8859 org-additional-option-like-keywords)))
8860 (insert (substring (cdr (assoc (upcase pattern) table))
8861 (length pattern)))
8862 (if (memq type '(:tag :prop)) (insert ":")))))
8863 ((null completion)
8864 (message "Can't find completion for \"%s\"" pattern)
8865 (ding))
8866 ((not (string= pattern completion))
8867 (delete-region beg end)
8868 (if (string-match " +$" completion)
8869 (setq completion (replace-match "" t t completion)))
8870 (insert completion)
8871 (if (get-buffer-window "*Completions*")
8872 (delete-window (get-buffer-window "*Completions*")))
8873 (if (assoc completion table)
8874 (if (eq type :todo) (insert " ")
8875 (if (memq type '(:tag :prop)) (insert ":"))))
8876 (if (and (equal type :opt) (assoc completion table))
8877 (message "%s" (substitute-command-keys
8878 "Press \\[org-complete] again to insert example settings"))))
8880 (message "Making completion list...")
8881 (let ((list (sort (all-completions pattern table confirm)
8882 'string<)))
8883 (with-output-to-temp-buffer "*Completions*"
8884 (condition-case nil
8885 ;; Protection needed for XEmacs and emacs 21
8886 (display-completion-list list pattern)
8887 (error (display-completion-list list)))))
8888 (message "Making completion list...%s" "done")))))))
8890 ;;;; TODO, DEADLINE, Comments
8892 (defun org-toggle-comment ()
8893 "Change the COMMENT state of an entry."
8894 (interactive)
8895 (save-excursion
8896 (org-back-to-heading)
8897 (let (case-fold-search)
8898 (if (looking-at (concat outline-regexp
8899 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8900 (replace-match "" t t nil 1)
8901 (if (looking-at outline-regexp)
8902 (progn
8903 (goto-char (match-end 0))
8904 (insert org-comment-string " ")))))))
8906 (defvar org-last-todo-state-is-todo nil
8907 "This is non-nil when the last TODO state change led to a TODO state.
8908 If the last change removed the TODO tag or switched to DONE, then
8909 this is nil.")
8911 (defvar org-setting-tags nil) ; dynamically skipped
8913 (defun org-parse-local-options (string var)
8914 "Parse STRING for startup setting relevant for variable VAR."
8915 (let ((rtn (symbol-value var))
8916 e opts)
8917 (save-match-data
8918 (if (or (not string) (not (string-match "\\S-" string)))
8920 (setq opts (delq nil (mapcar (lambda (x)
8921 (setq e (assoc x org-startup-options))
8922 (if (eq (nth 1 e) var) e nil))
8923 (org-split-string string "[ \t]+"))))
8924 (if (not opts)
8926 (setq rtn nil)
8927 (while (setq e (pop opts))
8928 (if (not (nth 3 e))
8929 (setq rtn (nth 2 e))
8930 (if (not (listp rtn)) (setq rtn nil))
8931 (push (nth 2 e) rtn)))
8932 rtn)))))
8934 (defvar org-todo-setup-filter-hook nil
8935 "Hook for functions that pre-filter todo specs.
8937 Each function takes a todo spec and returns either `nil' or the spec
8938 transformed into canonical form." )
8940 (defvar org-todo-get-default-hook nil
8941 "Hook for functions that get a default item for todo.
8943 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8944 `nil' or a string to be used for the todo mark." )
8946 (defvar org-agenda-headline-snapshot-before-repeat)
8947 (defun org-todo (&optional arg)
8948 "Change the TODO state of an item.
8949 The state of an item is given by a keyword at the start of the heading,
8950 like
8951 *** TODO Write paper
8952 *** DONE Call mom
8954 The different keywords are specified in the variable `org-todo-keywords'.
8955 By default the available states are \"TODO\" and \"DONE\".
8956 So for this example: when the item starts with TODO, it is changed to DONE.
8957 When it starts with DONE, the DONE is removed. And when neither TODO nor
8958 DONE are present, add TODO at the beginning of the heading.
8960 With C-u prefix arg, use completion to determine the new state.
8961 With numeric prefix arg, switch to that state.
8962 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8963 With a tripple C-u prefix, circumvent any state blocking.
8965 For calling through lisp, arg is also interpreted in the following way:
8966 'none -> empty state
8967 \"\"(empty string) -> switch to empty state
8968 'done -> switch to DONE
8969 'nextset -> switch to the next set of keywords
8970 'previousset -> switch to the previous set of keywords
8971 \"WAITING\" -> switch to the specified keyword, but only if it
8972 really is a member of `org-todo-keywords'."
8973 (interactive "P")
8974 (if (equal arg '(16)) (setq arg 'nextset))
8975 (let ((org-blocker-hook org-blocker-hook)
8976 (case-fold-search nil))
8977 (when (equal arg '(64))
8978 (setq arg nil org-blocker-hook nil))
8979 (when (and org-blocker-hook
8980 (org-entry-get nil "NOBLOCKING"))
8981 (setq org-blocker-hook nil))
8982 (save-excursion
8983 (catch 'exit
8984 (org-back-to-heading)
8985 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8986 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
8987 (looking-at " *"))
8988 (let* ((match-data (match-data))
8989 (startpos (point-at-bol))
8990 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8991 (org-log-done org-log-done)
8992 (org-log-repeat org-log-repeat)
8993 (org-todo-log-states org-todo-log-states)
8994 (this (match-string 1))
8995 (hl-pos (match-beginning 0))
8996 (head (org-get-todo-sequence-head this))
8997 (ass (assoc head org-todo-kwd-alist))
8998 (interpret (nth 1 ass))
8999 (done-word (nth 3 ass))
9000 (final-done-word (nth 4 ass))
9001 (last-state (or this ""))
9002 (completion-ignore-case t)
9003 (member (member this org-todo-keywords-1))
9004 (tail (cdr member))
9005 (state (cond
9006 ((and org-todo-key-trigger
9007 (or (and (equal arg '(4))
9008 (eq org-use-fast-todo-selection 'prefix))
9009 (and (not arg) org-use-fast-todo-selection
9010 (not (eq org-use-fast-todo-selection
9011 'prefix)))))
9012 ;; Use fast selection
9013 (org-fast-todo-selection))
9014 ((and (equal arg '(4))
9015 (or (not org-use-fast-todo-selection)
9016 (not org-todo-key-trigger)))
9017 ;; Read a state with completion
9018 (org-ido-completing-read
9019 "State: " (mapcar (lambda(x) (list x))
9020 org-todo-keywords-1)
9021 nil t))
9022 ((eq arg 'right)
9023 (if this
9024 (if tail (car tail) nil)
9025 (car org-todo-keywords-1)))
9026 ((eq arg 'left)
9027 (if (equal member org-todo-keywords-1)
9029 (if this
9030 (nth (- (length org-todo-keywords-1)
9031 (length tail) 2)
9032 org-todo-keywords-1)
9033 (org-last org-todo-keywords-1))))
9034 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9035 (setq arg nil))) ; hack to fall back to cycling
9036 (arg
9037 ;; user or caller requests a specific state
9038 (cond
9039 ((equal arg "") nil)
9040 ((eq arg 'none) nil)
9041 ((eq arg 'done) (or done-word (car org-done-keywords)))
9042 ((eq arg 'nextset)
9043 (or (car (cdr (member head org-todo-heads)))
9044 (car org-todo-heads)))
9045 ((eq arg 'previousset)
9046 (let ((org-todo-heads (reverse org-todo-heads)))
9047 (or (car (cdr (member head org-todo-heads)))
9048 (car org-todo-heads))))
9049 ((car (member arg org-todo-keywords-1)))
9050 ((nth (1- (prefix-numeric-value arg))
9051 org-todo-keywords-1))))
9052 ((null member) (or head (car org-todo-keywords-1)))
9053 ((equal this final-done-word) nil) ;; -> make empty
9054 ((null tail) nil) ;; -> first entry
9055 ((memq interpret '(type priority))
9056 (if (eq this-command last-command)
9057 (car tail)
9058 (if (> (length tail) 0)
9059 (or done-word (car org-done-keywords))
9060 nil)))
9062 (car tail))))
9063 (state (or
9064 (run-hook-with-args-until-success
9065 'org-todo-get-default-hook state last-state)
9066 state))
9067 (next (if state (concat " " state " ") " "))
9068 (change-plist (list :type 'todo-state-change :from this :to state
9069 :position startpos))
9070 dolog now-done-p)
9071 (when org-blocker-hook
9072 (setq org-last-todo-state-is-todo
9073 (not (member this org-done-keywords)))
9074 (unless (save-excursion
9075 (save-match-data
9076 (run-hook-with-args-until-failure
9077 'org-blocker-hook change-plist)))
9078 (if (interactive-p)
9079 (error "TODO state change from %s to %s blocked" this state)
9080 ;; fail silently
9081 (message "TODO state change from %s to %s blocked" this state)
9082 (throw 'exit nil))))
9083 (store-match-data match-data)
9084 (replace-match next t t)
9085 (unless (pos-visible-in-window-p hl-pos)
9086 (message "TODO state changed to %s" (org-trim next)))
9087 (unless head
9088 (setq head (org-get-todo-sequence-head state)
9089 ass (assoc head org-todo-kwd-alist)
9090 interpret (nth 1 ass)
9091 done-word (nth 3 ass)
9092 final-done-word (nth 4 ass)))
9093 (when (memq arg '(nextset previousset))
9094 (message "Keyword-Set %d/%d: %s"
9095 (- (length org-todo-sets) -1
9096 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9097 (length org-todo-sets)
9098 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9099 (setq org-last-todo-state-is-todo
9100 (not (member state org-done-keywords)))
9101 (setq now-done-p (and (member state org-done-keywords)
9102 (not (member this org-done-keywords))))
9103 (and logging (org-local-logging logging))
9104 (when (and (or org-todo-log-states org-log-done)
9105 (not (memq arg '(nextset previousset))))
9106 ;; we need to look at recording a time and note
9107 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9108 (nth 2 (assoc this org-todo-log-states))))
9109 (when (and state
9110 (member state org-not-done-keywords)
9111 (not (member this org-not-done-keywords)))
9112 ;; This is now a todo state and was not one before
9113 ;; If there was a CLOSED time stamp, get rid of it.
9114 (org-add-planning-info nil nil 'closed))
9115 (when (and now-done-p org-log-done)
9116 ;; It is now done, and it was not done before
9117 (org-add-planning-info 'closed (org-current-time))
9118 (if (and (not dolog) (eq 'note org-log-done))
9119 (org-add-log-setup 'done state this 'findpos 'note)))
9120 (when (and state dolog)
9121 ;; This is a non-nil state, and we need to log it
9122 (org-add-log-setup 'state state this 'findpos dolog)))
9123 ;; Fixup tag positioning
9124 (org-todo-trigger-tag-changes state)
9125 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9126 (when org-provide-todo-statistics
9127 (org-update-parent-todo-statistics))
9128 (run-hooks 'org-after-todo-state-change-hook)
9129 (if (and arg (not (member state org-done-keywords)))
9130 (setq head (org-get-todo-sequence-head state)))
9131 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9132 ;; Do we need to trigger a repeat?
9133 (when now-done-p
9134 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9135 ;; This is for the agenda, take a snapshot of the headline.
9136 (save-match-data
9137 (setq org-agenda-headline-snapshot-before-repeat
9138 (org-get-heading))))
9139 (org-auto-repeat-maybe state))
9140 ;; Fixup cursor location if close to the keyword
9141 (if (and (outline-on-heading-p)
9142 (not (bolp))
9143 (save-excursion (beginning-of-line 1)
9144 (looking-at org-todo-line-regexp))
9145 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9146 (progn
9147 (goto-char (or (match-end 2) (match-end 1)))
9148 (and (looking-at " ") (just-one-space))))
9149 (when org-trigger-hook
9150 (save-excursion
9151 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9153 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9154 "Block turning an entry into a TODO, using the hierarchy.
9155 This checks whether the current task should be blocked from state
9156 changes. Such blocking occurs when:
9158 1. The task has children which are not all in a completed state.
9160 2. A task has a parent with the property :ORDERED:, and there
9161 are siblings prior to the current task with incomplete
9162 status.
9164 3. The parent of the task is blocked because it has siblings that should
9165 be done first, or is child of a block grandparent TODO entry."
9167 (catch 'dont-block
9168 ;; If this is not a todo state change, or if this entry is already DONE,
9169 ;; do not block
9170 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9171 (member (plist-get change-plist :from)
9172 (cons 'done org-done-keywords))
9173 (member (plist-get change-plist :to)
9174 (cons 'todo org-not-done-keywords)))
9175 (throw 'dont-block t))
9176 ;; If this task has children, and any are undone, it's blocked
9177 (save-excursion
9178 (org-back-to-heading t)
9179 (let ((this-level (funcall outline-level)))
9180 (outline-next-heading)
9181 (let ((child-level (funcall outline-level)))
9182 (while (and (not (eobp))
9183 (> child-level this-level))
9184 ;; this todo has children, check whether they are all
9185 ;; completed
9186 (if (and (not (org-entry-is-done-p))
9187 (org-entry-is-todo-p))
9188 (throw 'dont-block nil))
9189 (outline-next-heading)
9190 (setq child-level (funcall outline-level))))))
9191 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9192 ;; any previous siblings are undone, it's blocked
9193 (save-excursion
9194 (org-back-to-heading t)
9195 (let* ((pos (point))
9196 (parent-pos (and (org-up-heading-safe) (point))))
9197 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9198 (when (and (org-entry-get (point) "ORDERED")
9199 (forward-line 1)
9200 (re-search-forward org-not-done-heading-regexp pos t))
9201 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9202 ;; Search further up the hierarchy, to see if an anchestor is blocked
9203 (while t
9204 (goto-char parent-pos)
9205 (if (not (looking-at org-not-done-heading-regexp))
9206 (throw 'dont-block t)) ; do not block, parent is not a TODO
9207 (setq pos (point))
9208 (setq parent-pos (and (org-up-heading-safe) (point)))
9209 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9210 (when (and (org-entry-get (point) "ORDERED")
9211 (forward-line 1)
9212 (re-search-forward org-not-done-heading-regexp pos t))
9213 (throw 'dont-block nil))))))) ; block, older sibling not done.
9215 (defcustom org-track-ordered-property-with-tag nil
9216 "Should the ORDERED property also be shown as a tag?
9217 The ORDERED property decides if an entry should require subtasks to be
9218 completed in sequence. Since a property is not very visible, setting
9219 this option means that toggling the ORDERED property with the command
9220 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9221 not relevant for the behavior, but it makes things more visible.
9223 Note that toggling the tag with tags commands will not change the property
9224 and therefore not influence behavior!
9226 This can be t, meaning the tag ORDERED should be used, It can also be a
9227 string to select a different tag for this task."
9228 :group 'org-todo
9229 :type '(choice
9230 (const :tag "No tracking" nil)
9231 (const :tag "Track with ORDERED tag" t)
9232 (string :tag "Use other tag")))
9234 (defun org-toggle-ordered-property ()
9235 "Toggle the ORDERED property of the current entry.
9236 For better visibility, you can track the value of this property with a tag.
9237 See variable `org-track-ordered-property-with-tag'."
9238 (interactive)
9239 (let* ((t1 org-track-ordered-property-with-tag)
9240 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9241 (save-excursion
9242 (org-back-to-heading)
9243 (if (org-entry-get nil "ORDERED")
9244 (progn
9245 (org-delete-property "ORDERED")
9246 (and tag (org-toggle-tag tag 'off))
9247 (message "Subtasks can be completed in arbitrary order"))
9248 (org-entry-put nil "ORDERED" "t")
9249 (and tag (org-toggle-tag tag 'on))
9250 (message "Subtasks must be completed in sequence")))))
9252 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9253 (defun org-block-todo-from-checkboxes (change-plist)
9254 "Block turning an entry into a TODO, using checkboxes.
9255 This checks whether the current task should be blocked from state
9256 changes because there are uncheckd boxes in this entry."
9257 (catch 'dont-block
9258 ;; If this is not a todo state change, or if this entry is already DONE,
9259 ;; do not block
9260 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9261 (member (plist-get change-plist :from)
9262 (cons 'done org-done-keywords))
9263 (member (plist-get change-plist :to)
9264 (cons 'todo org-not-done-keywords)))
9265 (throw 'dont-block t))
9266 ;; If this task has checkboxes that are not checked, it's blocked
9267 (save-excursion
9268 (org-back-to-heading t)
9269 (let ((beg (point)) end)
9270 (outline-next-heading)
9271 (setq end (point))
9272 (goto-char beg)
9273 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9274 end t)
9275 (progn
9276 (if (boundp 'org-blocked-by-checkboxes)
9277 (setq org-blocked-by-checkboxes t))
9278 (throw 'dont-block nil)))))
9279 t)) ; do not block
9281 (defun org-update-parent-todo-statistics ()
9282 "Update any statistics cookie in the parent of the current headline."
9283 (interactive)
9284 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9285 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9286 (catch 'exit
9287 (save-excursion
9288 (setq level (org-up-heading-safe))
9289 (unless (and level
9290 (not (equal (downcase
9291 (or (org-entry-get
9292 nil "COOKIE_DATA")
9293 ""))
9294 "checkbox")))
9295 (throw 'exit nil))
9296 (while (re-search-forward box-re (point-at-eol) t)
9297 (setq cnt-all 0 cnt-done 0 cookie-present t)
9298 (setq is-percent (match-end 2))
9299 (save-match-data
9300 (unless (outline-next-heading) (throw 'exit nil))
9301 (while (looking-at org-todo-line-regexp)
9302 (setq kwd (match-string 2))
9303 (and kwd (setq cnt-all (1+ cnt-all)))
9304 (and (member kwd org-done-keywords)
9305 (setq cnt-done (1+ cnt-done)))
9306 (condition-case nil
9307 (org-forward-same-level 1)
9308 (error (end-of-line 1)))))
9309 (replace-match
9310 (if is-percent
9311 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9312 (format "[%d/%d]" cnt-done cnt-all))))
9313 (when cookie-present
9314 (run-hook-with-args 'org-after-todo-statistics-hook
9315 cnt-done (- cnt-all cnt-done)))))))
9317 (defvar org-after-todo-statistics-hook nil
9318 "Hook that is called after a TODO statistics cookie has been updated.
9319 Each function is called with two arguments: the number of not-done entries
9320 and the number of done entries.
9322 For example, the following function, when added to this hook, will switch
9323 an entry to DONE when all children are done, and back to TODO when new
9324 entries are set to a TODO status. Note that this hook is only called
9325 when there is a statistics cookie in the headline!
9327 (defun org-summary-todo (n-done n-not-done)
9328 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9329 (let (org-log-done org-log-states) ; turn off logging
9330 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9333 (defun org-todo-trigger-tag-changes (state)
9334 "Apply the changes defined in `org-todo-state-tags-triggers'."
9335 (let ((l org-todo-state-tags-triggers)
9336 changes)
9337 (when (or (not state) (equal state ""))
9338 (setq changes (append changes (cdr (assoc "" l)))))
9339 (when (and (stringp state) (> (length state) 0))
9340 (setq changes (append changes (cdr (assoc state l)))))
9341 (when (member state org-not-done-keywords)
9342 (setq changes (append changes (cdr (assoc 'todo l)))))
9343 (when (member state org-done-keywords)
9344 (setq changes (append changes (cdr (assoc 'done l)))))
9345 (dolist (c changes)
9346 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9348 (defun org-local-logging (value)
9349 "Get logging settings from a property VALUE."
9350 (let* (words w a)
9351 ;; directly set the variables, they are already local.
9352 (setq org-log-done nil
9353 org-log-repeat nil
9354 org-todo-log-states nil)
9355 (setq words (org-split-string value))
9356 (while (setq w (pop words))
9357 (cond
9358 ((setq a (assoc w org-startup-options))
9359 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9360 (set (nth 1 a) (nth 2 a))))
9361 ((setq a (org-extract-log-state-settings w))
9362 (and (member (car a) org-todo-keywords-1)
9363 (push a org-todo-log-states)))))))
9365 (defun org-get-todo-sequence-head (kwd)
9366 "Return the head of the TODO sequence to which KWD belongs.
9367 If KWD is not set, check if there is a text property remembering the
9368 right sequence."
9369 (let (p)
9370 (cond
9371 ((not kwd)
9372 (or (get-text-property (point-at-bol) 'org-todo-head)
9373 (progn
9374 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9375 nil (point-at-eol)))
9376 (get-text-property p 'org-todo-head))))
9377 ((not (member kwd org-todo-keywords-1))
9378 (car org-todo-keywords-1))
9379 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9381 (defun org-fast-todo-selection ()
9382 "Fast TODO keyword selection with single keys.
9383 Returns the new TODO keyword, or nil if no state change should occur."
9384 (let* ((fulltable org-todo-key-alist)
9385 (done-keywords org-done-keywords) ;; needed for the faces.
9386 (maxlen (apply 'max (mapcar
9387 (lambda (x)
9388 (if (stringp (car x)) (string-width (car x)) 0))
9389 fulltable)))
9390 (expert nil)
9391 (fwidth (+ maxlen 3 1 3))
9392 (ncol (/ (- (window-width) 4) fwidth))
9393 tg cnt e c tbl
9394 groups ingroup)
9395 (save-excursion
9396 (save-window-excursion
9397 (if expert
9398 (set-buffer (get-buffer-create " *Org todo*"))
9399 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9400 (erase-buffer)
9401 (org-set-local 'org-done-keywords done-keywords)
9402 (setq tbl fulltable cnt 0)
9403 (while (setq e (pop tbl))
9404 (cond
9405 ((equal e '(:startgroup))
9406 (push '() groups) (setq ingroup t)
9407 (when (not (= cnt 0))
9408 (setq cnt 0)
9409 (insert "\n"))
9410 (insert "{ "))
9411 ((equal e '(:endgroup))
9412 (setq ingroup nil cnt 0)
9413 (insert "}\n"))
9414 ((equal e '(:newline))
9415 (when (not (= cnt 0))
9416 (setq cnt 0)
9417 (insert "\n")
9418 (setq e (car tbl))
9419 (while (equal (car tbl) '(:newline))
9420 (insert "\n")
9421 (setq tbl (cdr tbl)))))
9423 (setq tg (car e) c (cdr e))
9424 (if ingroup (push tg (car groups)))
9425 (setq tg (org-add-props tg nil 'face
9426 (org-get-todo-face tg)))
9427 (if (and (= cnt 0) (not ingroup)) (insert " "))
9428 (insert "[" c "] " tg (make-string
9429 (- fwidth 4 (length tg)) ?\ ))
9430 (when (= (setq cnt (1+ cnt)) ncol)
9431 (insert "\n")
9432 (if ingroup (insert " "))
9433 (setq cnt 0)))))
9434 (insert "\n")
9435 (goto-char (point-min))
9436 (if (not expert) (org-fit-window-to-buffer))
9437 (message "[a-z..]:Set [SPC]:clear")
9438 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9439 (cond
9440 ((or (= c ?\C-g)
9441 (and (= c ?q) (not (rassoc c fulltable))))
9442 (setq quit-flag t))
9443 ((= c ?\ ) nil)
9444 ((setq e (rassoc c fulltable) tg (car e))
9446 (t (setq quit-flag t)))))))
9448 (defun org-entry-is-todo-p ()
9449 (member (org-get-todo-state) org-not-done-keywords))
9451 (defun org-entry-is-done-p ()
9452 (member (org-get-todo-state) org-done-keywords))
9454 (defun org-get-todo-state ()
9455 (save-excursion
9456 (org-back-to-heading t)
9457 (and (looking-at org-todo-line-regexp)
9458 (match-end 2)
9459 (match-string 2))))
9461 (defun org-at-date-range-p (&optional inactive-ok)
9462 "Is the cursor inside a date range?"
9463 (interactive)
9464 (save-excursion
9465 (catch 'exit
9466 (let ((pos (point)))
9467 (skip-chars-backward "^[<\r\n")
9468 (skip-chars-backward "<[")
9469 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9470 (>= (match-end 0) pos)
9471 (throw 'exit t))
9472 (skip-chars-backward "^<[\r\n")
9473 (skip-chars-backward "<[")
9474 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9475 (>= (match-end 0) pos)
9476 (throw 'exit t)))
9477 nil)))
9479 (defun org-get-repeat ()
9480 "Check if there is a deadline/schedule with repeater in this entry."
9481 (save-match-data
9482 (save-excursion
9483 (org-back-to-heading t)
9484 (if (re-search-forward
9485 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9486 (match-string 1)))))
9488 (defvar org-last-changed-timestamp)
9489 (defvar org-last-inserted-timestamp)
9490 (defvar org-log-post-message)
9491 (defvar org-log-note-purpose)
9492 (defvar org-log-note-how)
9493 (defvar org-log-note-extra)
9494 (defun org-auto-repeat-maybe (done-word)
9495 "Check if the current headline contains a repeated deadline/schedule.
9496 If yes, set TODO state back to what it was and change the base date
9497 of repeating deadline/scheduled time stamps to new date.
9498 This function is run automatically after each state change to a DONE state."
9499 ;; last-state is dynamically scoped into this function
9500 (let* ((repeat (org-get-repeat))
9501 (aa (assoc last-state org-todo-kwd-alist))
9502 (interpret (nth 1 aa))
9503 (head (nth 2 aa))
9504 (whata '(("d" . day) ("m" . month) ("y" . year)))
9505 (msg "Entry repeats: ")
9506 (org-log-done nil)
9507 (org-todo-log-states nil)
9508 (nshiftmax 10) (nshift 0)
9509 re type n what ts time)
9510 (when repeat
9511 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9512 (org-todo (if (eq interpret 'type) last-state head))
9513 (when org-log-repeat
9514 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9515 (memq 'org-add-log-note post-command-hook))
9516 ;; OK, we are already setup for some record
9517 (if (eq org-log-repeat 'note)
9518 ;; make sure we take a note, not only a time stamp
9519 (setq org-log-note-how 'note))
9520 ;; Set up for taking a record
9521 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9522 last-state
9523 'findpos org-log-repeat)))
9524 (org-back-to-heading t)
9525 (org-add-planning-info nil nil 'closed)
9526 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9527 org-deadline-time-regexp "\\)\\|\\("
9528 org-ts-regexp "\\)"))
9529 (while (re-search-forward
9530 re (save-excursion (outline-next-heading) (point)) t)
9531 (setq type (if (match-end 1) org-scheduled-string
9532 (if (match-end 3) org-deadline-string "Plain:"))
9533 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9534 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9535 (setq n (string-to-number (match-string 2 ts))
9536 what (match-string 3 ts))
9537 (if (equal what "w") (setq n (* n 7) what "d"))
9538 ;; Preparation, see if we need to modify the start date for the change
9539 (when (match-end 1)
9540 (setq time (save-match-data (org-time-string-to-time ts)))
9541 (cond
9542 ((equal (match-string 1 ts) ".")
9543 ;; Shift starting date to today
9544 (org-timestamp-change
9545 (- (time-to-days (current-time)) (time-to-days time))
9546 'day))
9547 ((equal (match-string 1 ts) "+")
9548 (while (or (= nshift 0)
9549 (<= (time-to-days time) (time-to-days (current-time))))
9550 (when (= (incf nshift) nshiftmax)
9551 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9552 (error "Abort")))
9553 (org-timestamp-change n (cdr (assoc what whata)))
9554 (org-at-timestamp-p t)
9555 (setq ts (match-string 1))
9556 (setq time (save-match-data (org-time-string-to-time ts))))
9557 (org-timestamp-change (- n) (cdr (assoc what whata)))
9558 ;; rematch, so that we have everything in place for the real shift
9559 (org-at-timestamp-p t)
9560 (setq ts (match-string 1))
9561 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9562 (org-timestamp-change n (cdr (assoc what whata)))
9563 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9564 (setq org-log-post-message msg)
9565 (message "%s" msg))))
9567 (defun org-show-todo-tree (arg)
9568 "Make a compact tree which shows all headlines marked with TODO.
9569 The tree will show the lines where the regexp matches, and all higher
9570 headlines above the match.
9571 With a \\[universal-argument] prefix, also show the DONE entries.
9572 With a numeric prefix N, construct a sparse tree for the Nth element
9573 of `org-todo-keywords-1'."
9574 (interactive "P")
9575 (let ((case-fold-search nil)
9576 (kwd-re
9577 (cond ((null arg) org-not-done-regexp)
9578 ((equal arg '(4))
9579 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9580 (mapcar 'list org-todo-keywords-1))))
9581 (concat "\\("
9582 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9583 "\\)\\>")))
9584 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9585 (regexp-quote (nth (1- (prefix-numeric-value arg))
9586 org-todo-keywords-1)))
9587 (t (error "Invalid prefix argument: %s" arg)))))
9588 (message "%d TODO entries found"
9589 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9591 (defun org-deadline (&optional remove time)
9592 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9593 With argument REMOVE, remove any deadline from the item.
9594 When TIME is set, it should be an internal time specification, and the
9595 scheduling will use the corresponding date."
9596 (interactive "P")
9597 (if remove
9598 (progn
9599 (org-remove-timestamp-with-keyword org-deadline-string)
9600 (message "Item no longer has a deadline."))
9601 (if (org-get-repeat)
9602 (error "Cannot change deadline on task with repeater, please do that by hand")
9603 (org-add-planning-info 'deadline time 'closed)
9604 (message "Deadline on %s" org-last-inserted-timestamp))))
9606 (defun org-schedule (&optional remove time)
9607 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9608 With argument REMOVE, remove any scheduling date from the item.
9609 When TIME is set, it should be an internal time specification, and the
9610 scheduling will use the corresponding date."
9611 (interactive "P")
9612 (if remove
9613 (progn
9614 (org-remove-timestamp-with-keyword org-scheduled-string)
9615 (message "Item is no longer scheduled."))
9616 (if (org-get-repeat)
9617 (error "Cannot reschedule task with repeater, please do that by hand")
9618 (org-add-planning-info 'scheduled time 'closed)
9619 (message "Scheduled to %s" org-last-inserted-timestamp))))
9621 (defun org-get-scheduled-time (pom &optional inherit)
9622 "Get the scheduled time as a time tuple, of a format suitable
9623 for calling org-schedule with, or if there is no scheduling,
9624 returns nil."
9625 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9626 (when time
9627 (apply 'encode-time (org-parse-time-string time)))))
9629 (defun org-get-deadline-time (pom &optional inherit)
9630 "Get the deadine as a time tuple, of a format suitable for
9631 calling org-deadlin with, or if there is no scheduling, returns
9632 nil."
9633 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9634 (when time
9635 (apply 'encode-time (org-parse-time-string time)))))
9637 (defun org-remove-timestamp-with-keyword (keyword)
9638 "Remove all time stamps with KEYWORD in the current entry."
9639 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9640 beg)
9641 (save-excursion
9642 (org-back-to-heading t)
9643 (setq beg (point))
9644 (org-end-of-subtree t t)
9645 (while (re-search-backward re beg t)
9646 (replace-match "")
9647 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9648 (equal (char-before) ?\ ))
9649 (backward-delete-char 1)
9650 (if (string-match "^[ \t]*$" (buffer-substring
9651 (point-at-bol) (point-at-eol)))
9652 (delete-region (point-at-bol)
9653 (min (point-max) (1+ (point-at-eol))))))))))
9655 (defun org-add-planning-info (what &optional time &rest remove)
9656 "Insert new timestamp with keyword in the line directly after the headline.
9657 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9658 If non is given, the user is prompted for a date.
9659 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9660 be removed."
9661 (interactive)
9662 (let (org-time-was-given org-end-time-was-given ts
9663 end default-time default-input)
9665 (catch 'exit
9666 (when (and (not time) (memq what '(scheduled deadline)))
9667 ;; Try to get a default date/time from existing timestamp
9668 (save-excursion
9669 (org-back-to-heading t)
9670 (setq end (save-excursion (outline-next-heading) (point)))
9671 (when (re-search-forward (if (eq what 'scheduled)
9672 org-scheduled-time-regexp
9673 org-deadline-time-regexp)
9674 end t)
9675 (setq ts (match-string 1)
9676 default-time
9677 (apply 'encode-time (org-parse-time-string ts))
9678 default-input (and ts (org-get-compact-tod ts))))))
9679 (when what
9680 ;; If necessary, get the time from the user
9681 (setq time (or time (org-read-date nil 'to-time nil nil
9682 default-time default-input))))
9684 (when (and org-insert-labeled-timestamps-at-point
9685 (member what '(scheduled deadline)))
9686 (insert
9687 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9688 (org-insert-time-stamp time org-time-was-given
9689 nil nil nil (list org-end-time-was-given))
9690 (setq what nil))
9691 (save-excursion
9692 (save-restriction
9693 (let (col list elt ts buffer-invisibility-spec)
9694 (org-back-to-heading t)
9695 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9696 (goto-char (match-end 1))
9697 (setq col (current-column))
9698 (goto-char (match-end 0))
9699 (if (eobp) (insert "\n") (forward-char 1))
9700 (when (and (not what)
9701 (not (looking-at
9702 (concat "[ \t]*"
9703 org-keyword-time-not-clock-regexp))))
9704 ;; Nothing to add, nothing to remove...... :-)
9705 (throw 'exit nil))
9706 (if (and (not (looking-at outline-regexp))
9707 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9708 "[^\r\n]*"))
9709 (not (equal (match-string 1) org-clock-string)))
9710 (narrow-to-region (match-beginning 0) (match-end 0))
9711 (insert-before-markers "\n")
9712 (backward-char 1)
9713 (narrow-to-region (point) (point))
9714 (and org-adapt-indentation (org-indent-to-column col)))
9715 ;; Check if we have to remove something.
9716 (setq list (cons what remove))
9717 (while list
9718 (setq elt (pop list))
9719 (goto-char (point-min))
9720 (when (or (and (eq elt 'scheduled)
9721 (re-search-forward org-scheduled-time-regexp nil t))
9722 (and (eq elt 'deadline)
9723 (re-search-forward org-deadline-time-regexp nil t))
9724 (and (eq elt 'closed)
9725 (re-search-forward org-closed-time-regexp nil t)))
9726 (replace-match "")
9727 (if (looking-at "--+<[^>]+>") (replace-match ""))
9728 (if (looking-at " +") (replace-match ""))))
9729 (goto-char (point-max))
9730 (when what
9731 (insert
9732 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9733 (cond ((eq what 'scheduled) org-scheduled-string)
9734 ((eq what 'deadline) org-deadline-string)
9735 ((eq what 'closed) org-closed-string))
9736 " ")
9737 (setq ts (org-insert-time-stamp
9738 time
9739 (or org-time-was-given
9740 (and (eq what 'closed) org-log-done-with-time))
9741 (eq what 'closed)
9742 nil nil (list org-end-time-was-given)))
9743 (end-of-line 1))
9744 (goto-char (point-min))
9745 (widen)
9746 (if (and (looking-at "[ \t]+\n")
9747 (equal (char-before) ?\n))
9748 (delete-region (1- (point)) (point-at-eol)))
9749 ts))))))
9751 (defvar org-log-note-marker (make-marker))
9752 (defvar org-log-note-purpose nil)
9753 (defvar org-log-note-state nil)
9754 (defvar org-log-note-previous-state nil)
9755 (defvar org-log-note-how nil)
9756 (defvar org-log-note-extra nil)
9757 (defvar org-log-note-window-configuration nil)
9758 (defvar org-log-note-return-to (make-marker))
9759 (defvar org-log-post-message nil
9760 "Message to be displayed after a log note has been stored.
9761 The auto-repeater uses this.")
9763 (defun org-add-note ()
9764 "Add a note to the current entry.
9765 This is done in the same way as adding a state change note."
9766 (interactive)
9767 (org-add-log-setup 'note nil nil 'findpos nil))
9769 (defvar org-property-end-re)
9770 (defun org-add-log-setup (&optional purpose state prev-state
9771 findpos how &optional extra)
9772 "Set up the post command hook to take a note.
9773 If this is about to TODO state change, the new state is expected in STATE.
9774 When FINDPOS is non-nil, find the correct position for the note in
9775 the current entry. If not, assume that it can be inserted at point.
9776 HOW is an indicator what kind of note should be created.
9777 EXTRA is additional text that will be inserted into the notes buffer."
9778 (let ((drawer (cond ((stringp org-log-into-drawer)
9779 org-log-into-drawer)
9780 (org-log-into-drawer "LOGBOOK")
9781 (t nil))))
9782 (save-restriction
9783 (save-excursion
9784 (when findpos
9785 (org-back-to-heading t)
9786 (narrow-to-region (point) (save-excursion
9787 (outline-next-heading) (point)))
9788 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9789 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9790 "[^\r\n]*\\)?"))
9791 (goto-char (match-end 0))
9792 (cond
9793 (drawer
9794 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9795 nil t)
9796 (progn
9797 (goto-char (match-end 0))
9798 (or org-log-states-order-reversed
9799 (and (re-search-forward org-property-end-re nil t)
9800 (goto-char (1- (match-beginning 0))))))
9801 (insert "\n:" drawer ":\n:END:")
9802 (beginning-of-line 0)
9803 (org-indent-line-function)
9804 (beginning-of-line 2)
9805 (org-indent-line-function)
9806 (end-of-line 0)))
9807 ((and org-log-state-notes-insert-after-drawers
9808 (save-excursion
9809 (forward-line) (looking-at org-drawer-regexp)))
9810 (forward-line)
9811 (while (looking-at org-drawer-regexp)
9812 (goto-char (match-end 0))
9813 (re-search-forward org-property-end-re (point-max) t)
9814 (forward-line))
9815 (forward-line -1)))
9816 (unless org-log-states-order-reversed
9817 (and (= (char-after) ?\n) (forward-char 1))
9818 (org-skip-over-state-notes)
9819 (skip-chars-backward " \t\n\r")))
9820 (move-marker org-log-note-marker (point))
9821 (setq org-log-note-purpose purpose
9822 org-log-note-state state
9823 org-log-note-previous-state prev-state
9824 org-log-note-how how
9825 org-log-note-extra extra)
9826 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9828 (defun org-skip-over-state-notes ()
9829 "Skip past the list of State notes in an entry."
9830 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9831 (while (looking-at "[ \t]*- State")
9832 (condition-case nil
9833 (org-next-item)
9834 (error (org-end-of-item)))))
9836 (defun org-add-log-note (&optional purpose)
9837 "Pop up a window for taking a note, and add this note later at point."
9838 (remove-hook 'post-command-hook 'org-add-log-note)
9839 (setq org-log-note-window-configuration (current-window-configuration))
9840 (delete-other-windows)
9841 (move-marker org-log-note-return-to (point))
9842 (switch-to-buffer (marker-buffer org-log-note-marker))
9843 (goto-char org-log-note-marker)
9844 (org-switch-to-buffer-other-window "*Org Note*")
9845 (erase-buffer)
9846 (if (memq org-log-note-how '(time state))
9847 (let (current-prefix-arg) (org-store-log-note))
9848 (let ((org-inhibit-startup t)) (org-mode))
9849 (insert (format "# Insert note for %s.
9850 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9851 (cond
9852 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9853 ((eq org-log-note-purpose 'done) "closed todo item")
9854 ((eq org-log-note-purpose 'state)
9855 (format "state change from \"%s\" to \"%s\""
9856 (or org-log-note-previous-state "")
9857 (or org-log-note-state "")))
9858 ((eq org-log-note-purpose 'note)
9859 "this entry")
9860 (t (error "This should not happen")))))
9861 (if org-log-note-extra (insert org-log-note-extra))
9862 (org-set-local 'org-finish-function 'org-store-log-note)))
9864 (defvar org-note-abort nil) ; dynamically scoped
9865 (defun org-store-log-note ()
9866 "Finish taking a log note, and insert it to where it belongs."
9867 (let ((txt (buffer-string))
9868 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9869 lines ind)
9870 (kill-buffer (current-buffer))
9871 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9872 (setq txt (replace-match "" t t txt)))
9873 (if (string-match "\\s-+\\'" txt)
9874 (setq txt (replace-match "" t t txt)))
9875 (setq lines (org-split-string txt "\n"))
9876 (when (and note (string-match "\\S-" note))
9877 (setq note
9878 (org-replace-escapes
9879 note
9880 (list (cons "%u" (user-login-name))
9881 (cons "%U" user-full-name)
9882 (cons "%t" (format-time-string
9883 (org-time-stamp-format 'long 'inactive)
9884 (current-time)))
9885 (cons "%s" (if org-log-note-state
9886 (concat "\"" org-log-note-state "\"")
9887 ""))
9888 (cons "%S" (if org-log-note-previous-state
9889 (concat "\"" org-log-note-previous-state "\"")
9890 "\"\"")))))
9891 (if lines (setq note (concat note " \\\\")))
9892 (push note lines))
9893 (when (or current-prefix-arg org-note-abort)
9894 (when org-log-into-drawer
9895 (org-remove-empty-drawer-at
9896 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
9897 org-log-note-marker))
9898 (setq lines nil))
9899 (when lines
9900 (save-excursion
9901 (set-buffer (marker-buffer org-log-note-marker))
9902 (save-excursion
9903 (goto-char org-log-note-marker)
9904 (move-marker org-log-note-marker nil)
9905 (end-of-line 1)
9906 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9907 (insert "- " (pop lines))
9908 (org-indent-line-function)
9909 (beginning-of-line 1)
9910 (looking-at "[ \t]*")
9911 (setq ind (concat (match-string 0) " "))
9912 (end-of-line 1)
9913 (while lines (insert "\n" ind (pop lines)))
9914 (message "Note stored")
9915 (org-back-to-heading t)
9916 (org-cycle-hide-drawers 'children)))))
9917 (set-window-configuration org-log-note-window-configuration)
9918 (with-current-buffer (marker-buffer org-log-note-return-to)
9919 (goto-char org-log-note-return-to))
9920 (move-marker org-log-note-return-to nil)
9921 (and org-log-post-message (message "%s" org-log-post-message)))
9923 (defun org-remove-empty-drawer-at (drawer pos)
9924 "Remove an emptyr DARWER drawer at position POS.
9925 POS may also be a marker."
9926 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
9927 (save-excursion
9928 (save-restriction
9929 (widen)
9930 (goto-char pos)
9931 (if (org-in-regexp
9932 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
9933 (replace-match ""))))))
9935 (defun org-sparse-tree (&optional arg)
9936 "Create a sparse tree, prompt for the details.
9937 This command can create sparse trees. You first need to select the type
9938 of match used to create the tree:
9940 t Show entries with a specific TODO keyword.
9941 m Show entries selected by a tags/property match.
9942 p Enter a property name and its value (both with completion on existing
9943 names/values) and show entries with that property.
9944 r Show entries matching a regular expression.
9945 d Show deadlines due within `org-deadline-warning-days'.
9946 b Show deadlines and scheduled items before a date.
9947 a Show deadlines and scheduled items after a date."
9948 (interactive "P")
9949 (let (ans kwd value)
9950 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
9951 (setq ans (read-char-exclusive))
9952 (cond
9953 ((equal ans ?d)
9954 (call-interactively 'org-check-deadlines))
9955 ((equal ans ?b)
9956 (call-interactively 'org-check-before-date))
9957 ((equal ans ?a)
9958 (call-interactively 'org-check-after-date))
9959 ((equal ans ?t)
9960 (org-show-todo-tree '(4)))
9961 ((member ans '(?T ?m))
9962 (call-interactively 'org-match-sparse-tree))
9963 ((member ans '(?p ?P))
9964 (setq kwd (org-ido-completing-read "Property: "
9965 (mapcar 'list (org-buffer-property-keys))))
9966 (setq value (org-ido-completing-read "Value: "
9967 (mapcar 'list (org-property-values kwd))))
9968 (unless (string-match "\\`{.*}\\'" value)
9969 (setq value (concat "\"" value "\"")))
9970 (org-match-sparse-tree arg (concat kwd "=" value)))
9971 ((member ans '(?r ?R ?/))
9972 (call-interactively 'org-occur))
9973 (t (error "No such sparse tree command \"%c\"" ans)))))
9975 (defvar org-occur-highlights nil
9976 "List of overlays used for occur matches.")
9977 (make-variable-buffer-local 'org-occur-highlights)
9978 (defvar org-occur-parameters nil
9979 "Parameters of the active org-occur calls.
9980 This is a list, each call to org-occur pushes as cons cell,
9981 containing the regular expression and the callback, onto the list.
9982 The list can contain several entries if `org-occur' has been called
9983 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9984 will only contain one set of parameters. When the highlights are
9985 removed (for example with `C-c C-c', or with the next edit (depending
9986 on `org-remove-highlights-with-change'), this variable is emptied
9987 as well.")
9988 (make-variable-buffer-local 'org-occur-parameters)
9990 (defun org-occur (regexp &optional keep-previous callback)
9991 "Make a compact tree which shows all matches of REGEXP.
9992 The tree will show the lines where the regexp matches, and all higher
9993 headlines above the match. It will also show the heading after the match,
9994 to make sure editing the matching entry is easy.
9995 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9996 call to `org-occur' will be kept, to allow stacking of calls to this
9997 command.
9998 If CALLBACK is non-nil, it is a function which is called to confirm
9999 that the match should indeed be shown."
10000 (interactive "sRegexp: \nP")
10001 (unless keep-previous
10002 (org-remove-occur-highlights nil nil t))
10003 (push (cons regexp callback) org-occur-parameters)
10004 (let ((cnt 0))
10005 (save-excursion
10006 (goto-char (point-min))
10007 (if (or (not keep-previous) ; do not want to keep
10008 (not org-occur-highlights)) ; no previous matches
10009 ;; hide everything
10010 (org-overview))
10011 (while (re-search-forward regexp nil t)
10012 (when (or (not callback)
10013 (save-match-data (funcall callback)))
10014 (setq cnt (1+ cnt))
10015 (when org-highlight-sparse-tree-matches
10016 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10017 (org-show-context 'occur-tree))))
10018 (when org-remove-highlights-with-change
10019 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10020 nil 'local))
10021 (unless org-sparse-tree-open-archived-trees
10022 (org-hide-archived-subtrees (point-min) (point-max)))
10023 (run-hooks 'org-occur-hook)
10024 (if (interactive-p)
10025 (message "%d match(es) for regexp %s" cnt regexp))
10026 cnt))
10028 (defun org-show-context (&optional key)
10029 "Make sure point and context and visible.
10030 How much context is shown depends upon the variables
10031 `org-show-hierarchy-above', `org-show-following-heading'. and
10032 `org-show-siblings'."
10033 (let ((heading-p (org-on-heading-p t))
10034 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10035 (following-p (org-get-alist-option org-show-following-heading key))
10036 (entry-p (org-get-alist-option org-show-entry-below key))
10037 (siblings-p (org-get-alist-option org-show-siblings key)))
10038 (catch 'exit
10039 ;; Show heading or entry text
10040 (if (and heading-p (not entry-p))
10041 (org-flag-heading nil) ; only show the heading
10042 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10043 (org-show-hidden-entry))) ; show entire entry
10044 (when following-p
10045 ;; Show next sibling, or heading below text
10046 (save-excursion
10047 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10048 (org-flag-heading nil))))
10049 (when siblings-p (org-show-siblings))
10050 (when hierarchy-p
10051 ;; show all higher headings, possibly with siblings
10052 (save-excursion
10053 (while (and (condition-case nil
10054 (progn (org-up-heading-all 1) t)
10055 (error nil))
10056 (not (bobp)))
10057 (org-flag-heading nil)
10058 (when siblings-p (org-show-siblings))))))))
10060 (defun org-reveal (&optional siblings)
10061 "Show current entry, hierarchy above it, and the following headline.
10062 This can be used to show a consistent set of context around locations
10063 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10064 not t for the search context.
10066 With optional argument SIBLINGS, on each level of the hierarchy all
10067 siblings are shown. This repairs the tree structure to what it would
10068 look like when opened with hierarchical calls to `org-cycle'."
10069 (interactive "P")
10070 (let ((org-show-hierarchy-above t)
10071 (org-show-following-heading t)
10072 (org-show-siblings (if siblings t org-show-siblings)))
10073 (org-show-context nil)))
10075 (defun org-highlight-new-match (beg end)
10076 "Highlight from BEG to END and mark the highlight is an occur headline."
10077 (let ((ov (org-make-overlay beg end)))
10078 (org-overlay-put ov 'face 'secondary-selection)
10079 (push ov org-occur-highlights)))
10081 (defun org-remove-occur-highlights (&optional beg end noremove)
10082 "Remove the occur highlights from the buffer.
10083 BEG and END are ignored. If NOREMOVE is nil, remove this function
10084 from the `before-change-functions' in the current buffer."
10085 (interactive)
10086 (unless org-inhibit-highlight-removal
10087 (mapc 'org-delete-overlay org-occur-highlights)
10088 (setq org-occur-highlights nil)
10089 (setq org-occur-parameters nil)
10090 (unless noremove
10091 (remove-hook 'before-change-functions
10092 'org-remove-occur-highlights 'local))))
10094 ;;;; Priorities
10096 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10097 "Regular expression matching the priority indicator.")
10099 (defvar org-remove-priority-next-time nil)
10101 (defun org-priority-up ()
10102 "Increase the priority of the current item."
10103 (interactive)
10104 (org-priority 'up))
10106 (defun org-priority-down ()
10107 "Decrease the priority of the current item."
10108 (interactive)
10109 (org-priority 'down))
10111 (defun org-priority (&optional action)
10112 "Change the priority of an item by ARG.
10113 ACTION can be `set', `up', `down', or a character."
10114 (interactive)
10115 (setq action (or action 'set))
10116 (let (current new news have remove)
10117 (save-excursion
10118 (org-back-to-heading t)
10119 (if (looking-at org-priority-regexp)
10120 (setq current (string-to-char (match-string 2))
10121 have t)
10122 (setq current org-default-priority))
10123 (cond
10124 ((or (eq action 'set)
10125 (if (featurep 'xemacs) (characterp action) (integerp action)))
10126 (if (not (eq action 'set))
10127 (setq new action)
10128 (message "Priority %c-%c, SPC to remove: "
10129 org-highest-priority org-lowest-priority)
10130 (setq new (read-char-exclusive)))
10131 (if (and (= (upcase org-highest-priority) org-highest-priority)
10132 (= (upcase org-lowest-priority) org-lowest-priority))
10133 (setq new (upcase new)))
10134 (cond ((equal new ?\ ) (setq remove t))
10135 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10136 (error "Priority must be between `%c' and `%c'"
10137 org-highest-priority org-lowest-priority))))
10138 ((eq action 'up)
10139 (if (and (not have) (eq last-command this-command))
10140 (setq new org-lowest-priority)
10141 (setq new (if (and org-priority-start-cycle-with-default (not have))
10142 org-default-priority (1- current)))))
10143 ((eq action 'down)
10144 (if (and (not have) (eq last-command this-command))
10145 (setq new org-highest-priority)
10146 (setq new (if (and org-priority-start-cycle-with-default (not have))
10147 org-default-priority (1+ current)))))
10148 (t (error "Invalid action")))
10149 (if (or (< (upcase new) org-highest-priority)
10150 (> (upcase new) org-lowest-priority))
10151 (setq remove t))
10152 (setq news (format "%c" new))
10153 (if have
10154 (if remove
10155 (replace-match "" t t nil 1)
10156 (replace-match news t t nil 2))
10157 (if remove
10158 (error "No priority cookie found in line")
10159 (let ((case-fold-search nil))
10160 (looking-at org-todo-line-regexp))
10161 (if (match-end 2)
10162 (progn
10163 (goto-char (match-end 2))
10164 (insert " [#" news "]"))
10165 (goto-char (match-beginning 3))
10166 (insert "[#" news "] ")))))
10167 (org-preserve-lc (org-set-tags nil 'align))
10168 (if remove
10169 (message "Priority removed")
10170 (message "Priority of current item set to %s" news))))
10173 (defun org-get-priority (s)
10174 "Find priority cookie and return priority."
10175 (save-match-data
10176 (if (not (string-match org-priority-regexp s))
10177 (* 1000 (- org-lowest-priority org-default-priority))
10178 (* 1000 (- org-lowest-priority
10179 (string-to-char (match-string 2 s)))))))
10181 ;;;; Tags
10183 (defvar org-agenda-archives-mode)
10184 (defvar org-map-continue-from nil
10185 "Position from where mapping should continue.
10186 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10188 (defvar org-scanner-tags nil
10189 "The current tag list while the tags scanner is running.")
10190 (defvar org-trust-scanner-tags nil
10191 "Should `org-get-tags-at' use the tags fro the scanner.
10192 This is for internal dynamical scoping only.
10193 When this is non-nil, the function `org-get-tags-at' will return the value
10194 of `org-scanner-tags' instead of building the list by itself. This
10195 can lead to large speed-ups when the tags scanner is used in a file with
10196 many entries, and when the list of tags is retrieved, for example to
10197 obtain a list of properties. Building the tags list for each entry in such
10198 a file becomes an N^2 operation - but with this variable set, it scales
10199 as N.")
10201 (defun org-scan-tags (action matcher &optional todo-only)
10202 "Scan headline tags with inheritance and produce output ACTION.
10204 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10205 or `agenda' to produce an entry list for an agenda view. It can also be
10206 a Lisp form or a function that should be called at each matched headline, in
10207 this case the return value is a list of all return values from these calls.
10209 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10210 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10211 only lines with a TODO keyword are included in the output."
10212 (require 'org-agenda)
10213 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10214 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10215 (org-re
10216 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10217 (props (list 'face 'default
10218 'done-face 'org-agenda-done
10219 'undone-face 'default
10220 'mouse-face 'highlight
10221 'org-not-done-regexp org-not-done-regexp
10222 'org-todo-regexp org-todo-regexp
10223 'keymap org-agenda-keymap
10224 'help-echo
10225 (format "mouse-2 or RET jump to org file %s"
10226 (abbreviate-file-name
10227 (or (buffer-file-name (buffer-base-buffer))
10228 (buffer-name (buffer-base-buffer)))))))
10229 (case-fold-search nil)
10230 (org-map-continue-from nil)
10231 lspos tags tags-list
10232 (tags-alist (list (cons 0 org-file-tags)))
10233 (llast 0) rtn rtn1 level category i txt
10234 todo marker entry priority)
10235 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10236 (setq action (list 'lambda nil action)))
10237 (save-excursion
10238 (goto-char (point-min))
10239 (when (eq action 'sparse-tree)
10240 (org-overview)
10241 (org-remove-occur-highlights))
10242 (while (re-search-forward re nil t)
10243 (catch :skip
10244 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10245 tags (if (match-end 4) (org-match-string-no-properties 4)))
10246 (goto-char (setq lspos (match-beginning 0)))
10247 (setq level (org-reduced-level (funcall outline-level))
10248 category (org-get-category))
10249 (setq i llast llast level)
10250 ;; remove tag lists from same and sublevels
10251 (while (>= i level)
10252 (when (setq entry (assoc i tags-alist))
10253 (setq tags-alist (delete entry tags-alist)))
10254 (setq i (1- i)))
10255 ;; add the next tags
10256 (when tags
10257 (setq tags (org-split-string tags ":")
10258 tags-alist
10259 (cons (cons level tags) tags-alist)))
10260 ;; compile tags for current headline
10261 (setq tags-list
10262 (if org-use-tag-inheritance
10263 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10264 tags)
10265 org-scanner-tags tags-list)
10266 (when org-use-tag-inheritance
10267 (setcdr (car tags-alist)
10268 (mapcar (lambda (x)
10269 (setq x (copy-sequence x))
10270 (org-add-prop-inherited x))
10271 (cdar tags-alist))))
10272 (when (and tags org-use-tag-inheritance
10273 (or (not (eq t org-use-tag-inheritance))
10274 org-tags-exclude-from-inheritance))
10275 ;; selective inheritance, remove uninherited ones
10276 (setcdr (car tags-alist)
10277 (org-remove-uniherited-tags (cdar tags-alist))))
10278 (when (and (or (not todo-only)
10279 (and (member todo org-not-done-keywords)
10280 (or (not org-agenda-tags-todo-honor-ignore-options)
10281 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10282 (let ((case-fold-search t)) (eval matcher))
10284 (not (member org-archive-tag tags-list))
10285 ;; we have an archive tag, should we use this anyway?
10286 (or (not org-agenda-skip-archived-trees)
10287 (and (eq action 'agenda) org-agenda-archives-mode))))
10288 (unless (eq action 'sparse-tree) (org-agenda-skip))
10290 ;; select this headline
10292 (cond
10293 ((eq action 'sparse-tree)
10294 (and org-highlight-sparse-tree-matches
10295 (org-get-heading) (match-end 0)
10296 (org-highlight-new-match
10297 (match-beginning 0) (match-beginning 1)))
10298 (org-show-context 'tags-tree))
10299 ((eq action 'agenda)
10300 (setq txt (org-format-agenda-item
10302 (concat
10303 (if (eq org-tags-match-list-sublevels 'indented)
10304 (make-string (1- level) ?.) "")
10305 (org-get-heading))
10306 category
10307 tags-list
10309 priority (org-get-priority txt))
10310 (goto-char lspos)
10311 (setq marker (org-agenda-new-marker))
10312 (org-add-props txt props
10313 'org-marker marker 'org-hd-marker marker 'org-category category
10314 'todo-state todo
10315 'priority priority 'type "tagsmatch")
10316 (push txt rtn))
10317 ((functionp action)
10318 (setq org-map-continue-from nil)
10319 (save-excursion
10320 (setq rtn1 (funcall action))
10321 (push rtn1 rtn)))
10322 (t (error "Invalid action")))
10324 ;; if we are to skip sublevels, jump to end of subtree
10325 (unless org-tags-match-list-sublevels
10326 (org-end-of-subtree t)
10327 (backward-char 1))))
10328 ;; Get the correct position from where to continue
10329 (if org-map-continue-from
10330 (goto-char org-map-continue-from)
10331 (and (= (point) lspos) (end-of-line 1)))))
10332 (when (and (eq action 'sparse-tree)
10333 (not org-sparse-tree-open-archived-trees))
10334 (org-hide-archived-subtrees (point-min) (point-max)))
10335 (nreverse rtn)))
10337 (defun org-remove-uniherited-tags (tags)
10338 "Remove all tags that are not inherited from the list TAGS."
10339 (cond
10340 ((eq org-use-tag-inheritance t)
10341 (if org-tags-exclude-from-inheritance
10342 (org-delete-all org-tags-exclude-from-inheritance tags)
10343 tags))
10344 ((not org-use-tag-inheritance) nil)
10345 ((stringp org-use-tag-inheritance)
10346 (delq nil (mapcar
10347 (lambda (x)
10348 (if (and (string-match org-use-tag-inheritance x)
10349 (not (member x org-tags-exclude-from-inheritance)))
10350 x nil))
10351 tags)))
10352 ((listp org-use-tag-inheritance)
10353 (delq nil (mapcar
10354 (lambda (x)
10355 (if (member x org-use-tag-inheritance) x nil))
10356 tags)))))
10358 (defvar todo-only) ;; dynamically scoped
10360 (defun org-match-sparse-tree (&optional todo-only match)
10361 "Create a sparse tree according to tags string MATCH.
10362 MATCH can contain positive and negative selection of tags, like
10363 \"+WORK+URGENT-WITHBOSS\".
10364 If optional argument TODO-ONLY is non-nil, only select lines that are
10365 also TODO lines."
10366 (interactive "P")
10367 (org-prepare-agenda-buffers (list (current-buffer)))
10368 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10370 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10372 (defvar org-cached-props nil)
10373 (defun org-cached-entry-get (pom property)
10374 (if (or (eq t org-use-property-inheritance)
10375 (and (stringp org-use-property-inheritance)
10376 (string-match org-use-property-inheritance property))
10377 (and (listp org-use-property-inheritance)
10378 (member property org-use-property-inheritance)))
10379 ;; Caching is not possible, check it directly
10380 (org-entry-get pom property 'inherit)
10381 ;; Get all properties, so that we can do complicated checks easily
10382 (cdr (assoc property (or org-cached-props
10383 (setq org-cached-props
10384 (org-entry-properties pom)))))))
10386 (defun org-global-tags-completion-table (&optional files)
10387 "Return the list of all tags in all agenda buffer/files."
10388 (save-excursion
10389 (org-uniquify
10390 (delq nil
10391 (apply 'append
10392 (mapcar
10393 (lambda (file)
10394 (set-buffer (find-file-noselect file))
10395 (append (org-get-buffer-tags)
10396 (mapcar (lambda (x) (if (stringp (car-safe x))
10397 (list (car-safe x)) nil))
10398 org-tag-alist)))
10399 (if (and files (car files))
10400 files
10401 (org-agenda-files))))))))
10403 (defun org-make-tags-matcher (match)
10404 "Create the TAGS//TODO matcher form for the selection string MATCH."
10405 ;; todo-only is scoped dynamically into this function, and the function
10406 ;; may change it if the matcher asks for it.
10407 (unless match
10408 ;; Get a new match request, with completion
10409 (let ((org-last-tags-completion-table
10410 (org-global-tags-completion-table)))
10411 (setq match (org-completing-read-no-ido
10412 "Match: " 'org-tags-completion-function nil nil nil
10413 'org-tags-history))))
10415 ;; Parse the string and create a lisp form
10416 (let ((match0 match)
10417 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10418 minus tag mm
10419 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10420 orterms term orlist re-p str-p level-p level-op time-p
10421 prop-p pn pv po cat-p gv rest)
10422 (if (string-match "/+" match)
10423 ;; match contains also a todo-matching request
10424 (progn
10425 (setq tagsmatch (substring match 0 (match-beginning 0))
10426 todomatch (substring match (match-end 0)))
10427 (if (string-match "^!" todomatch)
10428 (setq todo-only t todomatch (substring todomatch 1)))
10429 (if (string-match "^\\s-*$" todomatch)
10430 (setq todomatch nil)))
10431 ;; only matching tags
10432 (setq tagsmatch match todomatch nil))
10434 ;; Make the tags matcher
10435 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10436 (setq tagsmatcher t)
10437 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10438 (while (setq term (pop orterms))
10439 (while (and (equal (substring term -1) "\\") orterms)
10440 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10441 (while (string-match re term)
10442 (setq rest (substring term (match-end 0))
10443 minus (and (match-end 1)
10444 (equal (match-string 1 term) "-"))
10445 tag (match-string 2 term)
10446 re-p (equal (string-to-char tag) ?{)
10447 level-p (match-end 4)
10448 prop-p (match-end 5)
10449 mm (cond
10450 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10451 (level-p
10452 (setq level-op (org-op-to-function (match-string 3 term)))
10453 `(,level-op level ,(string-to-number
10454 (match-string 4 term))))
10455 (prop-p
10456 (setq pn (match-string 5 term)
10457 po (match-string 6 term)
10458 pv (match-string 7 term)
10459 cat-p (equal pn "CATEGORY")
10460 re-p (equal (string-to-char pv) ?{)
10461 str-p (equal (string-to-char pv) ?\")
10462 time-p (save-match-data
10463 (string-match "^\"[[<].*[]>]\"$" pv))
10464 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10465 (if time-p (setq pv (org-matcher-time pv)))
10466 (setq po (org-op-to-function po (if time-p 'time str-p)))
10467 (cond
10468 ((equal pn "CATEGORY")
10469 (setq gv '(get-text-property (point) 'org-category)))
10470 ((equal pn "TODO")
10471 (setq gv 'todo))
10473 (setq gv `(org-cached-entry-get nil ,pn))))
10474 (if re-p
10475 (if (eq po 'org<>)
10476 `(not (string-match ,pv (or ,gv "")))
10477 `(string-match ,pv (or ,gv "")))
10478 (if str-p
10479 `(,po (or ,gv "") ,pv)
10480 `(,po (string-to-number (or ,gv ""))
10481 ,(string-to-number pv) ))))
10482 (t `(member ,tag tags-list)))
10483 mm (if minus (list 'not mm) mm)
10484 term rest)
10485 (push mm tagsmatcher))
10486 (push (if (> (length tagsmatcher) 1)
10487 (cons 'and tagsmatcher)
10488 (car tagsmatcher))
10489 orlist)
10490 (setq tagsmatcher nil))
10491 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10492 (setq tagsmatcher
10493 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10494 ;; Make the todo matcher
10495 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10496 (setq todomatcher t)
10497 (setq orterms (org-split-string todomatch "|") orlist nil)
10498 (while (setq term (pop orterms))
10499 (while (string-match re term)
10500 (setq minus (and (match-end 1)
10501 (equal (match-string 1 term) "-"))
10502 kwd (match-string 2 term)
10503 re-p (equal (string-to-char kwd) ?{)
10504 term (substring term (match-end 0))
10505 mm (if re-p
10506 `(string-match ,(substring kwd 1 -1) todo)
10507 (list 'equal 'todo kwd))
10508 mm (if minus (list 'not mm) mm))
10509 (push mm todomatcher))
10510 (push (if (> (length todomatcher) 1)
10511 (cons 'and todomatcher)
10512 (car todomatcher))
10513 orlist)
10514 (setq todomatcher nil))
10515 (setq todomatcher (if (> (length orlist) 1)
10516 (cons 'or orlist) (car orlist))))
10518 ;; Return the string and lisp forms of the matcher
10519 (setq matcher (if todomatcher
10520 (list 'and tagsmatcher todomatcher)
10521 tagsmatcher))
10522 (cons match0 matcher)))
10524 (defun org-op-to-function (op &optional stringp)
10525 "Turn an operator into the appropriate function."
10526 (setq op
10527 (cond
10528 ((equal op "<" ) '(< string< org-time<))
10529 ((equal op ">" ) '(> org-string> org-time>))
10530 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10531 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10532 ((member op '("=" "==")) '(= string= org-time=))
10533 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10534 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10536 (defun org<> (a b) (not (= a b)))
10537 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10538 (defun org-string>= (a b) (not (string< a b)))
10539 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10540 (defun org-string<> (a b) (not (string= a b)))
10541 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10542 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10543 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10544 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10545 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10546 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10547 (defun org-2ft (s)
10548 "Convert S to a floating point time.
10549 If S is already a number, just return it. If it is a string, parse
10550 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10551 (cond
10552 ((numberp s) s)
10553 ((stringp s)
10554 (condition-case nil
10555 (float-time (apply 'encode-time (org-parse-time-string s)))
10556 (error 0.)))
10557 (t 0.)))
10559 (defun org-time-today ()
10560 "Time in seconds today at 0:00.
10561 Returns the float number of seconds since the beginning of the
10562 epoch to the beginning of today (00:00)."
10563 (float-time (apply 'encode-time
10564 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10566 (defun org-matcher-time (s)
10567 "Interpret a time comparison value."
10568 (save-match-data
10569 (cond
10570 ((string= s "<now>") (float-time))
10571 ((string= s "<today>") (org-time-today))
10572 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10573 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10574 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10575 (+ (org-time-today)
10576 (* (string-to-number (match-string 1 s))
10577 (cdr (assoc (match-string 2 s)
10578 '(("d" . 86400.0) ("w" . 604800.0)
10579 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10580 (t (org-2ft s)))))
10582 (defun org-match-any-p (re list)
10583 "Does re match any element of list?"
10584 (setq list (mapcar (lambda (x) (string-match re x)) list))
10585 (delq nil list))
10587 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10588 (defvar org-tags-overlay (org-make-overlay 1 1))
10589 (org-detach-overlay org-tags-overlay)
10591 (defun org-get-local-tags-at (&optional pos)
10592 "Get a list of tags defined in the current headline."
10593 (org-get-tags-at pos 'local))
10595 (defun org-get-local-tags ()
10596 "Get a list of tags defined in the current headline."
10597 (org-get-tags-at nil 'local))
10599 (defun org-get-tags-at (&optional pos local)
10600 "Get a list of all headline tags applicable at POS.
10601 POS defaults to point. If tags are inherited, the list contains
10602 the targets in the same sequence as the headlines appear, i.e.
10603 the tags of the current headline come last.
10604 When LOCAL is non-nil, only return tags from the current headline,
10605 ignore inherited ones."
10606 (interactive)
10607 (if (and org-trust-scanner-tags
10608 (or (not pos) (equal pos (point)))
10609 (not local))
10610 org-scanner-tags
10611 (let (tags ltags lastpos parent)
10612 (save-excursion
10613 (save-restriction
10614 (widen)
10615 (goto-char (or pos (point)))
10616 (save-match-data
10617 (catch 'done
10618 (condition-case nil
10619 (progn
10620 (org-back-to-heading t)
10621 (while (not (equal lastpos (point)))
10622 (setq lastpos (point))
10623 (when (looking-at
10624 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10625 (setq ltags (org-split-string
10626 (org-match-string-no-properties 1) ":"))
10627 (when parent
10628 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10629 (setq tags (append
10630 (if parent
10631 (org-remove-uniherited-tags ltags)
10632 ltags)
10633 tags)))
10634 (or org-use-tag-inheritance (throw 'done t))
10635 (if local (throw 'done t))
10636 (or (org-up-heading-safe) (error nil))
10637 (setq parent t)))
10638 (error nil)))))
10639 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10641 (defun org-add-prop-inherited (s)
10642 (add-text-properties 0 (length s) '(inherited t) s)
10645 (defun org-toggle-tag (tag &optional onoff)
10646 "Toggle the tag TAG for the current line.
10647 If ONOFF is `on' or `off', don't toggle but set to this state."
10648 (let (res current)
10649 (save-excursion
10650 (org-back-to-heading t)
10651 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10652 (point-at-eol) t)
10653 (progn
10654 (setq current (match-string 1))
10655 (replace-match ""))
10656 (setq current ""))
10657 (setq current (nreverse (org-split-string current ":")))
10658 (cond
10659 ((eq onoff 'on)
10660 (setq res t)
10661 (or (member tag current) (push tag current)))
10662 ((eq onoff 'off)
10663 (or (not (member tag current)) (setq current (delete tag current))))
10664 (t (if (member tag current)
10665 (setq current (delete tag current))
10666 (setq res t)
10667 (push tag current))))
10668 (end-of-line 1)
10669 (if current
10670 (progn
10671 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10672 (org-set-tags nil t))
10673 (delete-horizontal-space))
10674 (run-hooks 'org-after-tags-change-hook))
10675 res))
10677 (defun org-align-tags-here (to-col)
10678 ;; Assumes that this is a headline
10679 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10680 (beginning-of-line 1)
10681 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10682 (< pos (match-beginning 2)))
10683 (progn
10684 (setq tags-l (- (match-end 2) (match-beginning 2)))
10685 (goto-char (match-beginning 1))
10686 (insert " ")
10687 (delete-region (point) (1+ (match-beginning 2)))
10688 (setq ncol (max (1+ (current-column))
10689 (1+ col)
10690 (if (> to-col 0)
10691 to-col
10692 (- (abs to-col) tags-l))))
10693 (setq p (point))
10694 (insert (make-string (- ncol (current-column)) ?\ ))
10695 (setq ncol (current-column))
10696 (when indent-tabs-mode (tabify p (point-at-eol)))
10697 (org-move-to-column (min ncol col) t))
10698 (goto-char pos))))
10700 (defun org-set-tags-command (&optional arg just-align)
10701 "Call the set-tags command for the current entry."
10702 (interactive "P")
10703 (if (org-on-heading-p)
10704 (org-set-tags arg just-align)
10705 (save-excursion
10706 (org-back-to-heading t)
10707 (org-set-tags arg just-align))))
10709 (defun org-set-tags (&optional arg just-align)
10710 "Set the tags for the current headline.
10711 With prefix ARG, realign all tags in headings in the current buffer."
10712 (interactive "P")
10713 (let* ((re (concat "^" outline-regexp))
10714 (current (org-get-tags-string))
10715 (col (current-column))
10716 (org-setting-tags t)
10717 table current-tags inherited-tags ; computed below when needed
10718 tags p0 c0 c1 rpl)
10719 (if arg
10720 (save-excursion
10721 (goto-char (point-min))
10722 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10723 (while (re-search-forward re nil t)
10724 (org-set-tags nil t)
10725 (end-of-line 1)))
10726 (message "All tags realigned to column %d" org-tags-column))
10727 (if just-align
10728 (setq tags current)
10729 ;; Get a new set of tags from the user
10730 (save-excursion
10731 (setq table (append org-tag-persistent-alist
10732 (or org-tag-alist (org-get-buffer-tags)))
10733 org-last-tags-completion-table table
10734 current-tags (org-split-string current ":")
10735 inherited-tags (nreverse
10736 (nthcdr (length current-tags)
10737 (nreverse (org-get-tags-at))))
10738 tags
10739 (if (or (eq t org-use-fast-tag-selection)
10740 (and org-use-fast-tag-selection
10741 (delq nil (mapcar 'cdr table))))
10742 (org-fast-tag-selection
10743 current-tags inherited-tags table
10744 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10745 (let ((org-add-colon-after-tag-completion t))
10746 (org-trim
10747 (org-without-partial-completion
10748 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10749 nil nil current 'org-tags-history)))))))
10750 (while (string-match "[-+&]+" tags)
10751 ;; No boolean logic, just a list
10752 (setq tags (replace-match ":" t t tags))))
10754 (if (string-match "\\`[\t ]*\\'" tags)
10755 (setq tags "")
10756 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10757 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10759 ;; Insert new tags at the correct column
10760 (beginning-of-line 1)
10761 (cond
10762 ((and (equal current "") (equal tags "")))
10763 ((re-search-forward
10764 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10765 (point-at-eol) t)
10766 (if (equal tags "")
10767 (setq rpl "")
10768 (goto-char (match-beginning 0))
10769 (setq c0 (current-column) p0 (point)
10770 c1 (max (1+ c0) (if (> org-tags-column 0)
10771 org-tags-column
10772 (- (- org-tags-column) (length tags))))
10773 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10774 (replace-match rpl t t)
10775 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10776 tags)
10777 (t (error "Tags alignment failed")))
10778 (org-move-to-column col)
10779 (unless just-align
10780 (run-hooks 'org-after-tags-change-hook)))))
10782 (defun org-change-tag-in-region (beg end tag off)
10783 "Add or remove TAG for each entry in the region.
10784 This works in the agenda, and also in an org-mode buffer."
10785 (interactive
10786 (list (region-beginning) (region-end)
10787 (let ((org-last-tags-completion-table
10788 (if (org-mode-p)
10789 (org-get-buffer-tags)
10790 (org-global-tags-completion-table))))
10791 (org-ido-completing-read
10792 "Tag: " 'org-tags-completion-function nil nil nil
10793 'org-tags-history))
10794 (progn
10795 (message "[s]et or [r]emove? ")
10796 (equal (read-char-exclusive) ?r))))
10797 (if (fboundp 'deactivate-mark) (deactivate-mark))
10798 (let ((agendap (equal major-mode 'org-agenda-mode))
10799 l1 l2 m buf pos newhead (cnt 0))
10800 (goto-char end)
10801 (setq l2 (1- (org-current-line)))
10802 (goto-char beg)
10803 (setq l1 (org-current-line))
10804 (loop for l from l1 to l2 do
10805 (goto-line l)
10806 (setq m (get-text-property (point) 'org-hd-marker))
10807 (when (or (and (org-mode-p) (org-on-heading-p))
10808 (and agendap m))
10809 (setq buf (if agendap (marker-buffer m) (current-buffer))
10810 pos (if agendap m (point)))
10811 (with-current-buffer buf
10812 (save-excursion
10813 (save-restriction
10814 (goto-char pos)
10815 (setq cnt (1+ cnt))
10816 (org-toggle-tag tag (if off 'off 'on))
10817 (setq newhead (org-get-heading)))))
10818 (and agendap (org-agenda-change-all-lines newhead m))))
10819 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10821 (defun org-tags-completion-function (string predicate &optional flag)
10822 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10823 (confirm (lambda (x) (stringp (car x)))))
10824 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10825 (setq s1 (match-string 1 string)
10826 s2 (match-string 2 string))
10827 (setq s1 "" s2 string))
10828 (cond
10829 ((eq flag nil)
10830 ;; try completion
10831 (setq rtn (try-completion s2 ctable confirm))
10832 (if (stringp rtn)
10833 (setq rtn
10834 (concat s1 s2 (substring rtn (length s2))
10835 (if (and org-add-colon-after-tag-completion
10836 (assoc rtn ctable))
10837 ":" ""))))
10838 rtn)
10839 ((eq flag t)
10840 ;; all-completions
10841 (all-completions s2 ctable confirm)
10843 ((eq flag 'lambda)
10844 ;; exact match?
10845 (assoc s2 ctable)))
10848 (defun org-fast-tag-insert (kwd tags face &optional end)
10849 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10850 (insert (format "%-12s" (concat kwd ":"))
10851 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10852 (or end "")))
10854 (defun org-fast-tag-show-exit (flag)
10855 (save-excursion
10856 (goto-line 3)
10857 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10858 (replace-match ""))
10859 (when flag
10860 (end-of-line 1)
10861 (org-move-to-column (- (window-width) 19) t)
10862 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10864 (defun org-set-current-tags-overlay (current prefix)
10865 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10866 (if (featurep 'xemacs)
10867 (org-overlay-display org-tags-overlay (concat prefix s)
10868 'secondary-selection)
10869 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10870 (org-overlay-display org-tags-overlay (concat prefix s)))))
10872 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10873 "Fast tag selection with single keys.
10874 CURRENT is the current list of tags in the headline, INHERITED is the
10875 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10876 possibly with grouping information. TODO-TABLE is a similar table with
10877 TODO keywords, should these have keys assigned to them.
10878 If the keys are nil, a-z are automatically assigned.
10879 Returns the new tags string, or nil to not change the current settings."
10880 (let* ((fulltable (append table todo-table))
10881 (maxlen (apply 'max (mapcar
10882 (lambda (x)
10883 (if (stringp (car x)) (string-width (car x)) 0))
10884 fulltable)))
10885 (buf (current-buffer))
10886 (expert (eq org-fast-tag-selection-single-key 'expert))
10887 (buffer-tags nil)
10888 (fwidth (+ maxlen 3 1 3))
10889 (ncol (/ (- (window-width) 4) fwidth))
10890 (i-face 'org-done)
10891 (c-face 'org-todo)
10892 tg cnt e c char c1 c2 ntable tbl rtn
10893 ov-start ov-end ov-prefix
10894 (exit-after-next org-fast-tag-selection-single-key)
10895 (done-keywords org-done-keywords)
10896 groups ingroup)
10897 (save-excursion
10898 (beginning-of-line 1)
10899 (if (looking-at
10900 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10901 (setq ov-start (match-beginning 1)
10902 ov-end (match-end 1)
10903 ov-prefix "")
10904 (setq ov-start (1- (point-at-eol))
10905 ov-end (1+ ov-start))
10906 (skip-chars-forward "^\n\r")
10907 (setq ov-prefix
10908 (concat
10909 (buffer-substring (1- (point)) (point))
10910 (if (> (current-column) org-tags-column)
10912 (make-string (- org-tags-column (current-column)) ?\ ))))))
10913 (org-move-overlay org-tags-overlay ov-start ov-end)
10914 (save-window-excursion
10915 (if expert
10916 (set-buffer (get-buffer-create " *Org tags*"))
10917 (delete-other-windows)
10918 (split-window-vertically)
10919 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10920 (erase-buffer)
10921 (org-set-local 'org-done-keywords done-keywords)
10922 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10923 (org-fast-tag-insert "Current" current c-face "\n\n")
10924 (org-fast-tag-show-exit exit-after-next)
10925 (org-set-current-tags-overlay current ov-prefix)
10926 (setq tbl fulltable char ?a cnt 0)
10927 (while (setq e (pop tbl))
10928 (cond
10929 ((equal e '(:startgroup))
10930 (push '() groups) (setq ingroup t)
10931 (when (not (= cnt 0))
10932 (setq cnt 0)
10933 (insert "\n"))
10934 (insert "{ "))
10935 ((equal e '(:endgroup))
10936 (setq ingroup nil cnt 0)
10937 (insert "}\n"))
10938 ((equal e '(:newline))
10939 (when (not (= cnt 0))
10940 (setq cnt 0)
10941 (insert "\n")
10942 (setq e (car tbl))
10943 (while (equal (car tbl) '(:newline))
10944 (insert "\n")
10945 (setq tbl (cdr tbl)))))
10947 (setq tg (car e) c2 nil)
10948 (if (cdr e)
10949 (setq c (cdr e))
10950 ;; automatically assign a character.
10951 (setq c1 (string-to-char
10952 (downcase (substring
10953 tg (if (= (string-to-char tg) ?@) 1 0)))))
10954 (if (or (rassoc c1 ntable) (rassoc c1 table))
10955 (while (or (rassoc char ntable) (rassoc char table))
10956 (setq char (1+ char)))
10957 (setq c2 c1))
10958 (setq c (or c2 char)))
10959 (if ingroup (push tg (car groups)))
10960 (setq tg (org-add-props tg nil 'face
10961 (cond
10962 ((not (assoc tg table))
10963 (org-get-todo-face tg))
10964 ((member tg current) c-face)
10965 ((member tg inherited) i-face)
10966 (t nil))))
10967 (if (and (= cnt 0) (not ingroup)) (insert " "))
10968 (insert "[" c "] " tg (make-string
10969 (- fwidth 4 (length tg)) ?\ ))
10970 (push (cons tg c) ntable)
10971 (when (= (setq cnt (1+ cnt)) ncol)
10972 (insert "\n")
10973 (if ingroup (insert " "))
10974 (setq cnt 0)))))
10975 (setq ntable (nreverse ntable))
10976 (insert "\n")
10977 (goto-char (point-min))
10978 (if (not expert) (org-fit-window-to-buffer))
10979 (setq rtn
10980 (catch 'exit
10981 (while t
10982 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10983 (if groups " [!] no groups" " [!]groups")
10984 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10985 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10986 (cond
10987 ((= c ?\r) (throw 'exit t))
10988 ((= c ?!)
10989 (setq groups (not groups))
10990 (goto-char (point-min))
10991 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10992 ((= c ?\C-c)
10993 (if (not expert)
10994 (org-fast-tag-show-exit
10995 (setq exit-after-next (not exit-after-next)))
10996 (setq expert nil)
10997 (delete-other-windows)
10998 (split-window-vertically)
10999 (org-switch-to-buffer-other-window " *Org tags*")
11000 (org-fit-window-to-buffer)))
11001 ((or (= c ?\C-g)
11002 (and (= c ?q) (not (rassoc c ntable))))
11003 (org-detach-overlay org-tags-overlay)
11004 (setq quit-flag t))
11005 ((= c ?\ )
11006 (setq current nil)
11007 (if exit-after-next (setq exit-after-next 'now)))
11008 ((= c ?\t)
11009 (condition-case nil
11010 (setq tg (org-ido-completing-read
11011 "Tag: "
11012 (or buffer-tags
11013 (with-current-buffer buf
11014 (org-get-buffer-tags)))))
11015 (quit (setq tg "")))
11016 (when (string-match "\\S-" tg)
11017 (add-to-list 'buffer-tags (list tg))
11018 (if (member tg current)
11019 (setq current (delete tg current))
11020 (push tg current)))
11021 (if exit-after-next (setq exit-after-next 'now)))
11022 ((setq e (rassoc c todo-table) tg (car e))
11023 (with-current-buffer buf
11024 (save-excursion (org-todo tg)))
11025 (if exit-after-next (setq exit-after-next 'now)))
11026 ((setq e (rassoc c ntable) tg (car e))
11027 (if (member tg current)
11028 (setq current (delete tg current))
11029 (loop for g in groups do
11030 (if (member tg g)
11031 (mapc (lambda (x)
11032 (setq current (delete x current)))
11033 g)))
11034 (push tg current))
11035 (if exit-after-next (setq exit-after-next 'now))))
11037 ;; Create a sorted list
11038 (setq current
11039 (sort current
11040 (lambda (a b)
11041 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11042 (if (eq exit-after-next 'now) (throw 'exit t))
11043 (goto-char (point-min))
11044 (beginning-of-line 2)
11045 (delete-region (point) (point-at-eol))
11046 (org-fast-tag-insert "Current" current c-face)
11047 (org-set-current-tags-overlay current ov-prefix)
11048 (while (re-search-forward
11049 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11050 (setq tg (match-string 1))
11051 (add-text-properties
11052 (match-beginning 1) (match-end 1)
11053 (list 'face
11054 (cond
11055 ((member tg current) c-face)
11056 ((member tg inherited) i-face)
11057 (t (get-text-property (match-beginning 1) 'face))))))
11058 (goto-char (point-min)))))
11059 (org-detach-overlay org-tags-overlay)
11060 (if rtn
11061 (mapconcat 'identity current ":")
11062 nil))))
11064 (defun org-get-tags-string ()
11065 "Get the TAGS string in the current headline."
11066 (unless (org-on-heading-p t)
11067 (error "Not on a heading"))
11068 (save-excursion
11069 (beginning-of-line 1)
11070 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11071 (org-match-string-no-properties 1)
11072 "")))
11074 (defun org-get-tags ()
11075 "Get the list of tags specified in the current headline."
11076 (org-split-string (org-get-tags-string) ":"))
11078 (defun org-get-buffer-tags ()
11079 "Get a table of all tags used in the buffer, for completion."
11080 (let (tags)
11081 (save-excursion
11082 (goto-char (point-min))
11083 (while (re-search-forward
11084 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11085 (when (equal (char-after (point-at-bol 0)) ?*)
11086 (mapc (lambda (x) (add-to-list 'tags x))
11087 (org-split-string (org-match-string-no-properties 1) ":")))))
11088 (mapcar 'list tags)))
11090 ;;;; The mapping API
11092 ;;;###autoload
11093 (defun org-map-entries (func &optional match scope &rest skip)
11094 "Call FUNC at each headline selected by MATCH in SCOPE.
11096 FUNC is a function or a lisp form. The function will be called without
11097 arguments, with the cursor positioned at the beginning of the headline.
11098 The return values of all calls to the function will be collected and
11099 returned as a list.
11101 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11102 does not need to preserve point. After evaluaton, the cursor will be
11103 moved to the end of the line (presumably of the headline of the
11104 processed entry) and search continues from there. Under some
11105 circumstances, this may not produce the wanted results. For example,
11106 if you have removed (e.g. archived) the current (sub)tree it could
11107 mean that the next entry will be skipped entirely. In such cases, you
11108 can specify the position from where search should continue by making
11109 FUNC set the variable `org-map-continue-from' to the desired buffer
11110 position.
11112 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11113 Only headlines that are matched by this query will be considered during
11114 the iteration. When MATCH is nil or t, all headlines will be
11115 visited by the iteration.
11117 SCOPE determines the scope of this command. It can be any of:
11119 nil The current buffer, respecting the restriction if any
11120 tree The subtree started with the entry at point
11121 file The current buffer, without restriction
11122 file-with-archives
11123 The current buffer, and any archives associated with it
11124 agenda All agenda files
11125 agenda-with-archives
11126 All agenda files with any archive files associated with them
11127 \(file1 file2 ...)
11128 If this is a list, all files in the list will be scanned
11130 The remaining args are treated as settings for the skipping facilities of
11131 the scanner. The following items can be given here:
11133 archive skip trees with the archive tag.
11134 comment skip trees with the COMMENT keyword
11135 function or Emacs Lisp form:
11136 will be used as value for `org-agenda-skip-function', so whenever
11137 the the function returns t, FUNC will not be called for that
11138 entry and search will continue from the point where the
11139 function leaves it.
11141 If your function needs to retrieve the tags including inherited tags
11142 at the *current* entry, you can use the value of the variable
11143 `org-scanner-tags' which will be much faster than getting the value
11144 with `org-get-tags-at'. If your function gets properties with
11145 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11146 to t around the call to `org-entry-properties' to get the same speedup.
11147 Note that if your function moves around to retrieve tags and properties at
11148 a *different* entry, you cannot use these techniques."
11149 (let* ((org-agenda-archives-mode nil) ; just to make sure
11150 (org-agenda-skip-archived-trees (memq 'archive skip))
11151 (org-agenda-skip-comment-trees (memq 'comment skip))
11152 (org-agenda-skip-function
11153 (car (org-delete-all '(comment archive) skip)))
11154 (org-tags-match-list-sublevels t)
11155 matcher file res
11156 org-todo-keywords-for-agenda
11157 org-done-keywords-for-agenda
11158 org-todo-keyword-alist-for-agenda
11159 org-tag-alist-for-agenda)
11161 (cond
11162 ((eq match t) (setq matcher t))
11163 ((eq match nil) (setq matcher t))
11164 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11166 (save-excursion
11167 (save-restriction
11168 (when (eq scope 'tree)
11169 (org-back-to-heading t)
11170 (org-narrow-to-subtree)
11171 (setq scope nil))
11173 (if (not scope)
11174 (progn
11175 (org-prepare-agenda-buffers
11176 (list (buffer-file-name (current-buffer))))
11177 (setq res (org-scan-tags func matcher)))
11178 ;; Get the right scope
11179 (cond
11180 ((and scope (listp scope) (symbolp (car scope)))
11181 (setq scope (eval scope)))
11182 ((eq scope 'agenda)
11183 (setq scope (org-agenda-files t)))
11184 ((eq scope 'agenda-with-archives)
11185 (setq scope (org-agenda-files t))
11186 (setq scope (org-add-archive-files scope)))
11187 ((eq scope 'file)
11188 (setq scope (list (buffer-file-name))))
11189 ((eq scope 'file-with-archives)
11190 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11191 (org-prepare-agenda-buffers scope)
11192 (while (setq file (pop scope))
11193 (with-current-buffer (org-find-base-buffer-visiting file)
11194 (save-excursion
11195 (save-restriction
11196 (widen)
11197 (goto-char (point-min))
11198 (setq res (append res (org-scan-tags func matcher))))))))))
11199 res))
11201 ;;;; Properties
11203 ;;; Setting and retrieving properties
11205 (defconst org-special-properties
11206 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11207 "TIMESTAMP" "TIMESTAMP_IA")
11208 "The special properties valid in Org-mode.
11210 These are properties that are not defined in the property drawer,
11211 but in some other way.")
11213 (defconst org-default-properties
11214 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11215 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11216 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11217 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11218 "ORDERED" "NOBLOCKING" "COOKIE_DATA")
11219 "Some properties that are used by Org-mode for various purposes.
11220 Being in this list makes sure that they are offered for completion.")
11222 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11223 "Regular expression matching the first line of a property drawer.")
11225 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11226 "Regular expression matching the first line of a property drawer.")
11228 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11229 "Regular expression matching the first line of a property drawer.")
11231 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11232 "Regular expression matching the first line of a property drawer.")
11234 (defconst org-property-drawer-re
11235 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11236 org-property-end-re "\\)\n?")
11237 "Matches an entire property drawer.")
11239 (defconst org-clock-drawer-re
11240 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11241 org-property-end-re "\\)\n?")
11242 "Matches an entire clock drawer.")
11244 (defun org-property-action ()
11245 "Do an action on properties."
11246 (interactive)
11247 (let (c)
11248 (org-at-property-p)
11249 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11250 (setq c (read-char-exclusive))
11251 (cond
11252 ((equal c ?s)
11253 (call-interactively 'org-set-property))
11254 ((equal c ?d)
11255 (call-interactively 'org-delete-property))
11256 ((equal c ?D)
11257 (call-interactively 'org-delete-property-globally))
11258 ((equal c ?c)
11259 (call-interactively 'org-compute-property-at-point))
11260 (t (error "No such property action %c" c)))))
11262 (defun org-at-property-p ()
11263 "Is the cursor in a property line?"
11264 ;; FIXME: Does not check if we are actually in the drawer.
11265 ;; FIXME: also returns true on any drawers.....
11266 ;; This is used by C-c C-c for property action.
11267 (save-excursion
11268 (beginning-of-line 1)
11269 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11271 (defun org-get-property-block (&optional beg end force)
11272 "Return the (beg . end) range of the body of the property drawer.
11273 BEG and END can be beginning and end of subtree, if not given
11274 they will be found.
11275 If the drawer does not exist and FORCE is non-nil, create the drawer."
11276 (catch 'exit
11277 (save-excursion
11278 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11279 (end (or end (progn (outline-next-heading) (point)))))
11280 (goto-char beg)
11281 (if (re-search-forward org-property-start-re end t)
11282 (setq beg (1+ (match-end 0)))
11283 (if force
11284 (save-excursion
11285 (org-insert-property-drawer)
11286 (setq end (progn (outline-next-heading) (point))))
11287 (throw 'exit nil))
11288 (goto-char beg)
11289 (if (re-search-forward org-property-start-re end t)
11290 (setq beg (1+ (match-end 0)))))
11291 (if (re-search-forward org-property-end-re end t)
11292 (setq end (match-beginning 0))
11293 (or force (throw 'exit nil))
11294 (goto-char beg)
11295 (setq end beg)
11296 (org-indent-line-function)
11297 (insert ":END:\n"))
11298 (cons beg end)))))
11300 (defun org-entry-properties (&optional pom which)
11301 "Get all properties of the entry at point-or-marker POM.
11302 This includes the TODO keyword, the tags, time strings for deadline,
11303 scheduled, and clocking, and any additional properties defined in the
11304 entry. The return value is an alist, keys may occur multiple times
11305 if the property key was used several times.
11306 POM may also be nil, in which case the current entry is used.
11307 If WHICH is nil or `all', get all properties. If WHICH is
11308 `special' or `standard', only get that subclass."
11309 (setq which (or which 'all))
11310 (org-with-point-at pom
11311 (let ((clockstr (substring org-clock-string 0 -1))
11312 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11313 beg end range props sum-props key value string clocksum)
11314 (save-excursion
11315 (when (condition-case nil
11316 (and (org-mode-p) (org-back-to-heading t))
11317 (error nil))
11318 (setq beg (point))
11319 (setq sum-props (get-text-property (point) 'org-summaries))
11320 (setq clocksum (get-text-property (point) :org-clock-minutes))
11321 (outline-next-heading)
11322 (setq end (point))
11323 (when (memq which '(all special))
11324 ;; Get the special properties, like TODO and tags
11325 (goto-char beg)
11326 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11327 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11328 (when (looking-at org-priority-regexp)
11329 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11330 (when (and (setq value (org-get-tags-string))
11331 (string-match "\\S-" value))
11332 (push (cons "TAGS" value) props))
11333 (when (setq value (org-get-tags-at))
11334 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11335 props))
11336 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11337 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11338 string (if (equal key clockstr)
11339 (org-no-properties
11340 (org-trim
11341 (buffer-substring
11342 (match-beginning 3) (goto-char (point-at-eol)))))
11343 (substring (org-match-string-no-properties 3) 1 -1)))
11344 (unless key
11345 (if (= (char-after (match-beginning 3)) ?\[)
11346 (setq key "TIMESTAMP_IA")
11347 (setq key "TIMESTAMP")))
11348 (when (or (equal key clockstr) (not (assoc key props)))
11349 (push (cons key string) props)))
11353 (when (memq which '(all standard))
11354 ;; Get the standard properties, like :PROP: ...
11355 (setq range (org-get-property-block beg end))
11356 (when range
11357 (goto-char (car range))
11358 (while (re-search-forward
11359 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11360 (cdr range) t)
11361 (setq key (org-match-string-no-properties 1)
11362 value (org-trim (or (org-match-string-no-properties 2) "")))
11363 (unless (member key excluded)
11364 (push (cons key (or value "")) props)))))
11365 (if clocksum
11366 (push (cons "CLOCKSUM"
11367 (org-columns-number-to-string (/ (float clocksum) 60.)
11368 'add_times))
11369 props))
11370 (unless (assoc "CATEGORY" props)
11371 (setq value (or (org-get-category)
11372 (progn (org-refresh-category-properties)
11373 (org-get-category))))
11374 (push (cons "CATEGORY" value) props))
11375 (append sum-props (nreverse props)))))))
11377 (defun org-entry-get (pom property &optional inherit)
11378 "Get value of PROPERTY for entry at point-or-marker POM.
11379 If INHERIT is non-nil and the entry does not have the property,
11380 then also check higher levels of the hierarchy.
11381 If INHERIT is the symbol `selective', use inheritance only if the setting
11382 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11383 If the property is present but empty, the return value is the empty string.
11384 If the property is not present at all, nil is returned."
11385 (org-with-point-at pom
11386 (if (and inherit (if (eq inherit 'selective)
11387 (org-property-inherit-p property)
11389 (org-entry-get-with-inheritance property)
11390 (if (member property org-special-properties)
11391 ;; We need a special property. Use brute force, get all properties.
11392 (cdr (assoc property (org-entry-properties nil 'special)))
11393 (let ((range (org-get-property-block)))
11394 (if (and range
11395 (goto-char (car range))
11396 (re-search-forward
11397 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11398 (cdr range) t))
11399 ;; Found the property, return it.
11400 (if (match-end 1)
11401 (org-match-string-no-properties 1)
11402 "")))))))
11404 (defun org-property-or-variable-value (var &optional inherit)
11405 "Check if there is a property fixing the value of VAR.
11406 If yes, return this value. If not, return the current value of the variable."
11407 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11408 (if (and prop (stringp prop) (string-match "\\S-" prop))
11409 (read prop)
11410 (symbol-value var))))
11412 (defun org-entry-delete (pom property)
11413 "Delete the property PROPERTY from entry at point-or-marker POM."
11414 (org-with-point-at pom
11415 (if (member property org-special-properties)
11416 nil ; cannot delete these properties.
11417 (let ((range (org-get-property-block)))
11418 (if (and range
11419 (goto-char (car range))
11420 (re-search-forward
11421 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11422 (cdr range) t))
11423 (progn
11424 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11426 nil)))))
11428 ;; Multi-values properties are properties that contain multiple values
11429 ;; These values are assumed to be single words, separated by whitespace.
11430 (defun org-entry-add-to-multivalued-property (pom property value)
11431 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11432 (let* ((old (org-entry-get pom property))
11433 (values (and old (org-split-string old "[ \t]"))))
11434 (setq value (org-entry-protect-space value))
11435 (unless (member value values)
11436 (setq values (cons value values))
11437 (org-entry-put pom property
11438 (mapconcat 'identity values " ")))))
11440 (defun org-entry-remove-from-multivalued-property (pom property value)
11441 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11442 (let* ((old (org-entry-get pom property))
11443 (values (and old (org-split-string old "[ \t]"))))
11444 (setq value (org-entry-protect-space value))
11445 (when (member value values)
11446 (setq values (delete value values))
11447 (org-entry-put pom property
11448 (mapconcat 'identity values " ")))))
11450 (defun org-entry-member-in-multivalued-property (pom property value)
11451 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11452 (let* ((old (org-entry-get pom property))
11453 (values (and old (org-split-string old "[ \t]"))))
11454 (setq value (org-entry-protect-space value))
11455 (member value values)))
11457 (defun org-entry-get-multivalued-property (pom property)
11458 "Return a list of values in a multivalued property."
11459 (let* ((value (org-entry-get pom property))
11460 (values (and value (org-split-string value "[ \t]"))))
11461 (mapcar 'org-entry-restore-space values)))
11463 (defun org-entry-put-multivalued-property (pom property &rest values)
11464 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11465 VALUES should be a list of strings. Spaces will be protected."
11466 (org-entry-put pom property
11467 (mapconcat 'org-entry-protect-space values " "))
11468 (let* ((value (org-entry-get pom property))
11469 (values (and value (org-split-string value "[ \t]"))))
11470 (mapcar 'org-entry-restore-space values)))
11472 (defun org-entry-protect-space (s)
11473 "Protect spaces and newline in string S."
11474 (while (string-match " " s)
11475 (setq s (replace-match "%20" t t s)))
11476 (while (string-match "\n" s)
11477 (setq s (replace-match "%0A" t t s)))
11480 (defun org-entry-restore-space (s)
11481 "Restore spaces and newline in string S."
11482 (while (string-match "%20" s)
11483 (setq s (replace-match " " t t s)))
11484 (while (string-match "%0A" s)
11485 (setq s (replace-match "\n" t t s)))
11488 (defvar org-entry-property-inherited-from (make-marker)
11489 "Marker pointing to the entry from where a property was inherited.
11490 Each call to `org-entry-get-with-inheritance' will set this marker to the
11491 location of the entry where the inheritance search matched. If there was
11492 no match, the marker will point nowhere.
11493 Note that also `org-entry-get' calls this function, if the INHERIT flag
11494 is set.")
11496 (defun org-entry-get-with-inheritance (property)
11497 "Get entry property, and search higher levels if not present."
11498 (move-marker org-entry-property-inherited-from nil)
11499 (let (tmp)
11500 (save-excursion
11501 (save-restriction
11502 (widen)
11503 (catch 'ex
11504 (while t
11505 (when (setq tmp (org-entry-get nil property))
11506 (org-back-to-heading t)
11507 (move-marker org-entry-property-inherited-from (point))
11508 (throw 'ex tmp))
11509 (or (org-up-heading-safe) (throw 'ex nil)))))
11510 (or tmp
11511 (cdr (assoc property org-file-properties))
11512 (cdr (assoc property org-global-properties))
11513 (cdr (assoc property org-global-properties-fixed))))))
11515 (defun org-entry-put (pom property value)
11516 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11517 (org-with-point-at pom
11518 (org-back-to-heading t)
11519 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11520 range)
11521 (cond
11522 ((equal property "TODO")
11523 (when (and (stringp value) (string-match "\\S-" value)
11524 (not (member value org-todo-keywords-1)))
11525 (error "\"%s\" is not a valid TODO state" value))
11526 (if (or (not value)
11527 (not (string-match "\\S-" value)))
11528 (setq value 'none))
11529 (org-todo value)
11530 (org-set-tags nil 'align))
11531 ((equal property "PRIORITY")
11532 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11533 (string-to-char value) ?\ ))
11534 (org-set-tags nil 'align))
11535 ((equal property "SCHEDULED")
11536 (if (re-search-forward org-scheduled-time-regexp end t)
11537 (cond
11538 ((eq value 'earlier) (org-timestamp-change -1 'day))
11539 ((eq value 'later) (org-timestamp-change 1 'day))
11540 (t (call-interactively 'org-schedule)))
11541 (call-interactively 'org-schedule)))
11542 ((equal property "DEADLINE")
11543 (if (re-search-forward org-deadline-time-regexp end t)
11544 (cond
11545 ((eq value 'earlier) (org-timestamp-change -1 'day))
11546 ((eq value 'later) (org-timestamp-change 1 'day))
11547 (t (call-interactively 'org-deadline)))
11548 (call-interactively 'org-deadline)))
11549 ((member property org-special-properties)
11550 (error "The %s property can not yet be set with `org-entry-put'"
11551 property))
11552 (t ; a non-special property
11553 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11554 (setq range (org-get-property-block beg end 'force))
11555 (goto-char (car range))
11556 (if (re-search-forward
11557 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11558 (progn
11559 (delete-region (match-beginning 1) (match-end 1))
11560 (goto-char (match-beginning 1)))
11561 (goto-char (cdr range))
11562 (insert "\n")
11563 (backward-char 1)
11564 (org-indent-line-function)
11565 (insert ":" property ":"))
11566 (and value (insert " " value))
11567 (org-indent-line-function)))))))
11569 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11570 "Get all property keys in the current buffer.
11571 With INCLUDE-SPECIALS, also list the special properties that reflect things
11572 like tags and TODO state.
11573 With INCLUDE-DEFAULTS, also include properties that has special meaning
11574 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11575 With INCLUDE-COLUMNS, also include property names given in COLUMN
11576 formats in the current buffer."
11577 (let (rtn range cfmt s p)
11578 (save-excursion
11579 (save-restriction
11580 (widen)
11581 (goto-char (point-min))
11582 (while (re-search-forward org-property-start-re nil t)
11583 (setq range (org-get-property-block))
11584 (goto-char (car range))
11585 (while (re-search-forward
11586 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11587 (cdr range) t)
11588 (add-to-list 'rtn (org-match-string-no-properties 1)))
11589 (outline-next-heading))))
11591 (when include-specials
11592 (setq rtn (append org-special-properties rtn)))
11594 (when include-defaults
11595 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11597 (when include-columns
11598 (save-excursion
11599 (save-restriction
11600 (widen)
11601 (goto-char (point-min))
11602 (while (re-search-forward
11603 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11604 nil t)
11605 (setq cfmt (match-string 2) s 0)
11606 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11607 cfmt s)
11608 (setq s (match-end 0)
11609 p (match-string 1 cfmt))
11610 (unless (or (equal p "ITEM")
11611 (member p org-special-properties))
11612 (add-to-list 'rtn (match-string 1 cfmt))))))))
11614 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11616 (defun org-property-values (key)
11617 "Return a list of all values of property KEY."
11618 (save-excursion
11619 (save-restriction
11620 (widen)
11621 (goto-char (point-min))
11622 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11623 values)
11624 (while (re-search-forward re nil t)
11625 (add-to-list 'values (org-trim (match-string 1))))
11626 (delete "" values)))))
11628 (defun org-insert-property-drawer ()
11629 "Insert a property drawer into the current entry."
11630 (interactive)
11631 (org-back-to-heading t)
11632 (looking-at outline-regexp)
11633 (let ((indent (- (match-end 0)(match-beginning 0)))
11634 (beg (point))
11635 (re (concat "^[ \t]*" org-keyword-time-regexp))
11636 end hiddenp)
11637 (outline-next-heading)
11638 (setq end (point))
11639 (goto-char beg)
11640 (while (re-search-forward re end t))
11641 (setq hiddenp (org-invisible-p))
11642 (end-of-line 1)
11643 (and (equal (char-after) ?\n) (forward-char 1))
11644 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11645 (if (member (match-string 1) '("CLOCK:" ":END:"))
11646 ;; just skip this line
11647 (beginning-of-line 2)
11648 ;; Drawer start, find the end
11649 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11650 (beginning-of-line 1)))
11651 (org-skip-over-state-notes)
11652 (skip-chars-backward " \t\n\r")
11653 (if (eq (char-before) ?*) (forward-char 1))
11654 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11655 (beginning-of-line 0)
11656 (org-indent-to-column indent)
11657 (beginning-of-line 2)
11658 (org-indent-to-column indent)
11659 (beginning-of-line 0)
11660 (if hiddenp
11661 (save-excursion
11662 (org-back-to-heading t)
11663 (hide-entry))
11664 (org-flag-drawer t))))
11666 (defun org-set-property (property value)
11667 "In the current entry, set PROPERTY to VALUE.
11668 When called interactively, this will prompt for a property name, offering
11669 completion on existing and default properties. And then it will prompt
11670 for a value, offering completion either on allowed values (via an inherited
11671 xxx_ALL property) or on existing values in other instances of this property
11672 in the current file."
11673 (interactive
11674 (let* ((completion-ignore-case t)
11675 (keys (org-buffer-property-keys nil t t))
11676 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11677 (prop (if (member prop0 keys)
11678 prop0
11679 (or (cdr (assoc (downcase prop0)
11680 (mapcar (lambda (x) (cons (downcase x) x))
11681 keys)))
11682 prop0)))
11683 (cur (org-entry-get nil prop))
11684 (allowed (org-property-get-allowed-values nil prop 'table))
11685 (existing (mapcar 'list (org-property-values prop)))
11686 (val (if allowed
11687 (org-completing-read "Value: " allowed nil 'req-match)
11688 (let (org-completion-use-ido)
11689 (org-completing-read
11690 (concat "Value" (if (and cur (string-match "\\S-" cur))
11691 (concat "[" cur "]") "")
11692 ": ")
11693 existing nil nil "" nil cur)))))
11694 (list prop (if (equal val "") cur val))))
11695 (unless (equal (org-entry-get nil property) value)
11696 (org-entry-put nil property value)))
11698 (defun org-delete-property (property)
11699 "In the current entry, delete PROPERTY."
11700 (interactive
11701 (let* ((completion-ignore-case t)
11702 (prop (org-ido-completing-read
11703 "Property: " (org-entry-properties nil 'standard))))
11704 (list prop)))
11705 (message "Property %s %s" property
11706 (if (org-entry-delete nil property)
11707 "deleted"
11708 "was not present in the entry")))
11710 (defun org-delete-property-globally (property)
11711 "Remove PROPERTY globally, from all entries."
11712 (interactive
11713 (let* ((completion-ignore-case t)
11714 (prop (org-ido-completing-read
11715 "Globally remove property: "
11716 (mapcar 'list (org-buffer-property-keys)))))
11717 (list prop)))
11718 (save-excursion
11719 (save-restriction
11720 (widen)
11721 (goto-char (point-min))
11722 (let ((cnt 0))
11723 (while (re-search-forward
11724 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11725 nil t)
11726 (setq cnt (1+ cnt))
11727 (replace-match ""))
11728 (message "Property \"%s\" removed from %d entries" property cnt)))))
11730 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11732 (defun org-compute-property-at-point ()
11733 "Compute the property at point.
11734 This looks for an enclosing column format, extracts the operator and
11735 then applies it to the property in the column format's scope."
11736 (interactive)
11737 (unless (org-at-property-p)
11738 (error "Not at a property"))
11739 (let ((prop (org-match-string-no-properties 2)))
11740 (org-columns-get-format-and-top-level)
11741 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11742 (error "No operator defined for property %s" prop))
11743 (org-columns-compute prop)))
11745 (defun org-property-get-allowed-values (pom property &optional table)
11746 "Get allowed values for the property PROPERTY.
11747 When TABLE is non-nil, return an alist that can directly be used for
11748 completion."
11749 (let (vals)
11750 (cond
11751 ((equal property "TODO")
11752 (setq vals (org-with-point-at pom
11753 (append org-todo-keywords-1 '("")))))
11754 ((equal property "PRIORITY")
11755 (let ((n org-lowest-priority))
11756 (while (>= n org-highest-priority)
11757 (push (char-to-string n) vals)
11758 (setq n (1- n)))))
11759 ((member property org-special-properties))
11761 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11763 (when (and vals (string-match "\\S-" vals))
11764 (setq vals (car (read-from-string (concat "(" vals ")"))))
11765 (setq vals (mapcar (lambda (x)
11766 (cond ((stringp x) x)
11767 ((numberp x) (number-to-string x))
11768 ((symbolp x) (symbol-name x))
11769 (t "???")))
11770 vals)))))
11771 (if table (mapcar 'list vals) vals)))
11773 (defun org-property-previous-allowed-value (&optional previous)
11774 "Switch to the next allowed value for this property."
11775 (interactive)
11776 (org-property-next-allowed-value t))
11778 (defun org-property-next-allowed-value (&optional previous)
11779 "Switch to the next allowed value for this property."
11780 (interactive)
11781 (unless (org-at-property-p)
11782 (error "Not at a property"))
11783 (let* ((key (match-string 2))
11784 (value (match-string 3))
11785 (allowed (or (org-property-get-allowed-values (point) key)
11786 (and (member value '("[ ]" "[-]" "[X]"))
11787 '("[ ]" "[X]"))))
11788 nval)
11789 (unless allowed
11790 (error "Allowed values for this property have not been defined"))
11791 (if previous (setq allowed (reverse allowed)))
11792 (if (member value allowed)
11793 (setq nval (car (cdr (member value allowed)))))
11794 (setq nval (or nval (car allowed)))
11795 (if (equal nval value)
11796 (error "Only one allowed value for this property"))
11797 (org-at-property-p)
11798 (replace-match (concat " :" key ": " nval) t t)
11799 (org-indent-line-function)
11800 (beginning-of-line 1)
11801 (skip-chars-forward " \t")))
11803 (defun org-find-entry-with-id (ident)
11804 "Locate the entry that contains the ID property with exact value IDENT.
11805 IDENT can be a string, a symbol or a number, this function will search for
11806 the string representation of it.
11807 Return the position where this entry starts, or nil if there is no such entry."
11808 (interactive "sID: ")
11809 (let ((id (cond
11810 ((stringp ident) ident)
11811 ((symbol-name ident) (symbol-name ident))
11812 ((numberp ident) (number-to-string ident))
11813 (t (error "IDENT %s must be a string, symbol or number" ident))))
11814 (case-fold-search nil))
11815 (save-excursion
11816 (save-restriction
11817 (widen)
11818 (goto-char (point-min))
11819 (when (re-search-forward
11820 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11821 nil t)
11822 (org-back-to-heading)
11823 (point))))))
11825 ;;;; Timestamps
11827 (defvar org-last-changed-timestamp nil)
11828 (defvar org-last-inserted-timestamp nil
11829 "The last time stamp inserted with `org-insert-time-stamp'.")
11830 (defvar org-time-was-given) ; dynamically scoped parameter
11831 (defvar org-end-time-was-given) ; dynamically scoped parameter
11832 (defvar org-ts-what) ; dynamically scoped parameter
11834 (defun org-time-stamp (arg &optional inactive)
11835 "Prompt for a date/time and insert a time stamp.
11836 If the user specifies a time like HH:MM, or if this command is called
11837 with a prefix argument, the time stamp will contain date and time.
11838 Otherwise, only the date will be included. All parts of a date not
11839 specified by the user will be filled in from the current date/time.
11840 So if you press just return without typing anything, the time stamp
11841 will represent the current date/time. If there is already a timestamp
11842 at the cursor, it will be modified."
11843 (interactive "P")
11844 (let* ((ts nil)
11845 (default-time
11846 ;; Default time is either today, or, when entering a range,
11847 ;; the range start.
11848 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11849 (save-excursion
11850 (re-search-backward
11851 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11852 (- (point) 20) t)))
11853 (apply 'encode-time (org-parse-time-string (match-string 1)))
11854 (current-time)))
11855 (default-input (and ts (org-get-compact-tod ts)))
11856 org-time-was-given org-end-time-was-given time)
11857 (cond
11858 ((and (org-at-timestamp-p t)
11859 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11860 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11861 (insert "--")
11862 (setq time (let ((this-command this-command))
11863 (org-read-date arg 'totime nil nil
11864 default-time default-input)))
11865 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11866 ((org-at-timestamp-p t)
11867 (setq time (let ((this-command this-command))
11868 (org-read-date arg 'totime nil nil default-time default-input)))
11869 (when (org-at-timestamp-p t) ; just to get the match data
11870 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11871 (replace-match "")
11872 (setq org-last-changed-timestamp
11873 (org-insert-time-stamp
11874 time (or org-time-was-given arg)
11875 inactive nil nil (list org-end-time-was-given))))
11876 (message "Timestamp updated"))
11878 (setq time (let ((this-command this-command))
11879 (org-read-date arg 'totime nil nil default-time default-input)))
11880 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11881 nil nil (list org-end-time-was-given))))))
11883 ;; FIXME: can we use this for something else, like computing time differences?
11884 (defun org-get-compact-tod (s)
11885 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11886 (let* ((t1 (match-string 1 s))
11887 (h1 (string-to-number (match-string 2 s)))
11888 (m1 (string-to-number (match-string 3 s)))
11889 (t2 (and (match-end 4) (match-string 5 s)))
11890 (h2 (and t2 (string-to-number (match-string 6 s))))
11891 (m2 (and t2 (string-to-number (match-string 7 s))))
11892 dh dm)
11893 (if (not t2)
11895 (setq dh (- h2 h1) dm (- m2 m1))
11896 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11897 (concat t1 "+" (number-to-string dh)
11898 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11900 (defun org-time-stamp-inactive (&optional arg)
11901 "Insert an inactive time stamp.
11902 An inactive time stamp is enclosed in square brackets instead of angle
11903 brackets. It is inactive in the sense that it does not trigger agenda entries,
11904 does not link to the calendar and cannot be changed with the S-cursor keys.
11905 So these are more for recording a certain time/date."
11906 (interactive "P")
11907 (org-time-stamp arg 'inactive))
11909 (defvar org-date-ovl (org-make-overlay 1 1))
11910 (org-overlay-put org-date-ovl 'face 'org-warning)
11911 (org-detach-overlay org-date-ovl)
11913 (defvar org-ans1) ; dynamically scoped parameter
11914 (defvar org-ans2) ; dynamically scoped parameter
11916 (defvar org-plain-time-of-day-regexp) ; defined below
11918 (defvar org-overriding-default-time nil) ; dynamically scoped
11919 (defvar org-read-date-overlay nil)
11920 (defvar org-dcst nil) ; dynamically scoped
11921 (defvar org-read-date-history nil)
11923 (defun org-read-date (&optional with-time to-time from-string prompt
11924 default-time default-input)
11925 "Read a date, possibly a time, and make things smooth for the user.
11926 The prompt will suggest to enter an ISO date, but you can also enter anything
11927 which will at least partially be understood by `parse-time-string'.
11928 Unrecognized parts of the date will default to the current day, month, year,
11929 hour and minute. If this command is called to replace a timestamp at point,
11930 of to enter the second timestamp of a range, the default time is taken from the
11931 existing stamp. For example,
11932 3-2-5 --> 2003-02-05
11933 feb 15 --> currentyear-02-15
11934 sep 12 9 --> 2009-09-12
11935 12:45 --> today 12:45
11936 22 sept 0:34 --> currentyear-09-22 0:34
11937 12 --> currentyear-currentmonth-12
11938 Fri --> nearest Friday (today or later)
11939 etc.
11941 Furthermore you can specify a relative date by giving, as the *first* thing
11942 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11943 change in days weeks, months, years.
11944 With a single plus or minus, the date is relative to today. With a double
11945 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11946 +4d --> four days from today
11947 +4 --> same as above
11948 +2w --> two weeks from today
11949 ++5 --> five days from default date
11951 The function understands only English month and weekday abbreviations,
11952 but this can be configured with the variables `parse-time-months' and
11953 `parse-time-weekdays'.
11955 While prompting, a calendar is popped up - you can also select the
11956 date with the mouse (button 1). The calendar shows a period of three
11957 months. To scroll it to other months, use the keys `>' and `<'.
11958 If you don't like the calendar, turn it off with
11959 \(setq org-read-date-popup-calendar nil)
11961 With optional argument TO-TIME, the date will immediately be converted
11962 to an internal time.
11963 With an optional argument WITH-TIME, the prompt will suggest to also
11964 insert a time. Note that when WITH-TIME is not set, you can still
11965 enter a time, and this function will inform the calling routine about
11966 this change. The calling routine may then choose to change the format
11967 used to insert the time stamp into the buffer to include the time.
11968 With optional argument FROM-STRING, read from this string instead from
11969 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11970 the time/date that is used for everything that is not specified by the
11971 user."
11972 (require 'parse-time)
11973 (let* ((org-time-stamp-rounding-minutes
11974 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11975 (org-dcst org-display-custom-times)
11976 (ct (org-current-time))
11977 (def (or org-overriding-default-time default-time ct))
11978 (defdecode (decode-time def))
11979 (dummy (progn
11980 (when (< (nth 2 defdecode) org-extend-today-until)
11981 (setcar (nthcdr 2 defdecode) -1)
11982 (setcar (nthcdr 1 defdecode) 59)
11983 (setq def (apply 'encode-time defdecode)
11984 defdecode (decode-time def)))))
11985 (calendar-move-hook nil)
11986 (calendar-view-diary-initially-flag nil)
11987 (view-diary-entries-initially nil)
11988 (calendar-view-holidays-initially-flag nil)
11989 (view-calendar-holidays-initially nil)
11990 (timestr (format-time-string
11991 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11992 (prompt (concat (if prompt (concat prompt " ") "")
11993 (format "Date+time [%s]: " timestr)))
11994 ans (org-ans0 "") org-ans1 org-ans2 final)
11996 (cond
11997 (from-string (setq ans from-string))
11998 (org-read-date-popup-calendar
11999 (save-excursion
12000 (save-window-excursion
12001 (calendar)
12002 (calendar-forward-day (- (time-to-days def)
12003 (calendar-absolute-from-gregorian
12004 (calendar-current-date))))
12005 (org-eval-in-calendar nil t)
12006 (let* ((old-map (current-local-map))
12007 (map (copy-keymap calendar-mode-map))
12008 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12009 (org-defkey map (kbd "RET") 'org-calendar-select)
12010 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12011 'org-calendar-select-mouse)
12012 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12013 'org-calendar-select-mouse)
12014 (org-defkey minibuffer-local-map [(meta shift left)]
12015 (lambda () (interactive)
12016 (org-eval-in-calendar '(calendar-backward-month 1))))
12017 (org-defkey minibuffer-local-map [(meta shift right)]
12018 (lambda () (interactive)
12019 (org-eval-in-calendar '(calendar-forward-month 1))))
12020 (org-defkey minibuffer-local-map [(meta shift up)]
12021 (lambda () (interactive)
12022 (org-eval-in-calendar '(calendar-backward-year 1))))
12023 (org-defkey minibuffer-local-map [(meta shift down)]
12024 (lambda () (interactive)
12025 (org-eval-in-calendar '(calendar-forward-year 1))))
12026 (org-defkey minibuffer-local-map [(shift up)]
12027 (lambda () (interactive)
12028 (org-eval-in-calendar '(calendar-backward-week 1))))
12029 (org-defkey minibuffer-local-map [(shift down)]
12030 (lambda () (interactive)
12031 (org-eval-in-calendar '(calendar-forward-week 1))))
12032 (org-defkey minibuffer-local-map [(shift left)]
12033 (lambda () (interactive)
12034 (org-eval-in-calendar '(calendar-backward-day 1))))
12035 (org-defkey minibuffer-local-map [(shift right)]
12036 (lambda () (interactive)
12037 (org-eval-in-calendar '(calendar-forward-day 1))))
12038 (org-defkey minibuffer-local-map ">"
12039 (lambda () (interactive)
12040 (org-eval-in-calendar '(scroll-calendar-left 1))))
12041 (org-defkey minibuffer-local-map "<"
12042 (lambda () (interactive)
12043 (org-eval-in-calendar '(scroll-calendar-right 1))))
12044 (run-hooks 'org-read-date-minibuffer-setup-hook)
12045 (unwind-protect
12046 (progn
12047 (use-local-map map)
12048 (add-hook 'post-command-hook 'org-read-date-display)
12049 (setq org-ans0 (read-string prompt default-input
12050 'org-read-date-history nil))
12051 ;; org-ans0: from prompt
12052 ;; org-ans1: from mouse click
12053 ;; org-ans2: from calendar motion
12054 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12055 (remove-hook 'post-command-hook 'org-read-date-display)
12056 (use-local-map old-map)
12057 (when org-read-date-overlay
12058 (org-delete-overlay org-read-date-overlay)
12059 (setq org-read-date-overlay nil)))))))
12061 (t ; Naked prompt only
12062 (unwind-protect
12063 (setq ans (read-string prompt default-input
12064 'org-read-date-history timestr))
12065 (when org-read-date-overlay
12066 (org-delete-overlay org-read-date-overlay)
12067 (setq org-read-date-overlay nil)))))
12069 (setq final (org-read-date-analyze ans def defdecode))
12071 (if to-time
12072 (apply 'encode-time final)
12073 (if (and (boundp 'org-time-was-given) org-time-was-given)
12074 (format "%04d-%02d-%02d %02d:%02d"
12075 (nth 5 final) (nth 4 final) (nth 3 final)
12076 (nth 2 final) (nth 1 final))
12077 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12078 (defvar def)
12079 (defvar defdecode)
12080 (defvar with-time)
12081 (defun org-read-date-display ()
12082 "Display the current date prompt interpretation in the minibuffer."
12083 (when org-read-date-display-live
12084 (when org-read-date-overlay
12085 (org-delete-overlay org-read-date-overlay))
12086 (let ((p (point)))
12087 (end-of-line 1)
12088 (while (not (equal (buffer-substring
12089 (max (point-min) (- (point) 4)) (point))
12090 " "))
12091 (insert " "))
12092 (goto-char p))
12093 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12094 " " (or org-ans1 org-ans2)))
12095 (org-end-time-was-given nil)
12096 (f (org-read-date-analyze ans def defdecode))
12097 (fmts (if org-dcst
12098 org-time-stamp-custom-formats
12099 org-time-stamp-formats))
12100 (fmt (if (or with-time
12101 (and (boundp 'org-time-was-given) org-time-was-given))
12102 (cdr fmts)
12103 (car fmts)))
12104 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12105 (when (and org-end-time-was-given
12106 (string-match org-plain-time-of-day-regexp txt))
12107 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12108 org-end-time-was-given
12109 (substring txt (match-end 0)))))
12110 (setq org-read-date-overlay
12111 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12112 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12114 (defun org-read-date-analyze (ans def defdecode)
12115 "Analyse the combined answer of the date prompt."
12116 ;; FIXME: cleanup and comment
12117 (let (delta deltan deltaw deltadef year month day
12118 hour minute second wday pm h2 m2 tl wday1
12119 iso-year iso-weekday iso-week iso-year iso-date)
12121 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12122 (setq ans "+0"))
12124 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12125 (setq ans (replace-match "" t t ans)
12126 deltan (car delta)
12127 deltaw (nth 1 delta)
12128 deltadef (nth 2 delta)))
12130 ;; Check if there is an iso week date in there
12131 ;; If yes, sore the info and postpone interpreting it until the rest
12132 ;; of the parsing is done
12133 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12134 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12135 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12136 iso-week (string-to-number (match-string 2 ans)))
12137 (setq ans (replace-match "" t t ans)))
12139 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12140 (when (string-match
12141 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12142 (setq year (if (match-end 2)
12143 (string-to-number (match-string 2 ans))
12144 (string-to-number (format-time-string "%Y")))
12145 month (string-to-number (match-string 3 ans))
12146 day (string-to-number (match-string 4 ans)))
12147 (if (< year 100) (setq year (+ 2000 year)))
12148 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12149 t nil ans)))
12150 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12151 ;; If there is a time with am/pm, and *no* time without it, we convert
12152 ;; so that matching will be successful.
12153 (loop for i from 1 to 2 do ; twice, for end time as well
12154 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12155 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12156 (setq hour (string-to-number (match-string 1 ans))
12157 minute (if (match-end 3)
12158 (string-to-number (match-string 3 ans))
12160 pm (equal ?p
12161 (string-to-char (downcase (match-string 4 ans)))))
12162 (if (and (= hour 12) (not pm))
12163 (setq hour 0)
12164 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12165 (setq ans (replace-match (format "%02d:%02d" hour minute)
12166 t t ans))))
12168 ;; Check if a time range is given as a duration
12169 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12170 (setq hour (string-to-number (match-string 1 ans))
12171 h2 (+ hour (string-to-number (match-string 3 ans)))
12172 minute (string-to-number (match-string 2 ans))
12173 m2 (+ minute (if (match-end 5) (string-to-number
12174 (match-string 5 ans))0)))
12175 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12176 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12177 t t ans)))
12179 ;; Check if there is a time range
12180 (when (boundp 'org-end-time-was-given)
12181 (setq org-time-was-given nil)
12182 (when (and (string-match org-plain-time-of-day-regexp ans)
12183 (match-end 8))
12184 (setq org-end-time-was-given (match-string 8 ans))
12185 (setq ans (concat (substring ans 0 (match-beginning 7))
12186 (substring ans (match-end 7))))))
12188 (setq tl (parse-time-string ans)
12189 day (or (nth 3 tl) (nth 3 defdecode))
12190 month (or (nth 4 tl)
12191 (if (and org-read-date-prefer-future
12192 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12193 (1+ (nth 4 defdecode))
12194 (nth 4 defdecode)))
12195 year (or (nth 5 tl)
12196 (if (and org-read-date-prefer-future
12197 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12198 (1+ (nth 5 defdecode))
12199 (nth 5 defdecode)))
12200 hour (or (nth 2 tl) (nth 2 defdecode))
12201 minute (or (nth 1 tl) (nth 1 defdecode))
12202 second (or (nth 0 tl) 0)
12203 wday (nth 6 tl))
12205 ;; Special date definitions below
12206 (cond
12207 (iso-week
12208 ;; There was an iso week
12209 (setq year (or iso-year year)
12210 day (or iso-weekday wday 1)
12211 wday nil ; to make sure that the trigger below does not match
12212 iso-date (calendar-gregorian-from-absolute
12213 (calendar-absolute-from-iso
12214 (list iso-week day year))))
12215 ; FIXME: Should we also push ISO weeks into the future?
12216 ; (when (and org-read-date-prefer-future
12217 ; (not iso-year)
12218 ; (< (calendar-absolute-from-gregorian iso-date)
12219 ; (time-to-days (current-time))))
12220 ; (setq year (1+ year)
12221 ; iso-date (calendar-gregorian-from-absolute
12222 ; (calendar-absolute-from-iso
12223 ; (list iso-week day year)))))
12224 (setq month (car iso-date)
12225 year (nth 2 iso-date)
12226 day (nth 1 iso-date)))
12227 (deltan
12228 (unless deltadef
12229 (let ((now (decode-time (current-time))))
12230 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12231 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12232 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12233 ((equal deltaw "m") (setq month (+ month deltan)))
12234 ((equal deltaw "y") (setq year (+ year deltan)))))
12235 ((and wday (not (nth 3 tl)))
12236 ;; Weekday was given, but no day, so pick that day in the week
12237 ;; on or after the derived date.
12238 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12239 (unless (equal wday wday1)
12240 (setq day (+ day (% (- wday wday1 -7) 7))))))
12241 (if (and (boundp 'org-time-was-given)
12242 (nth 2 tl))
12243 (setq org-time-was-given t))
12244 (if (< year 100) (setq year (+ 2000 year)))
12245 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12246 (list second minute hour day month year)))
12248 (defvar parse-time-weekdays)
12250 (defun org-read-date-get-relative (s today default)
12251 "Check string S for special relative date string.
12252 TODAY and DEFAULT are internal times, for today and for a default.
12253 Return shift list (N what def-flag)
12254 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12255 N is the number of WHATs to shift.
12256 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12257 the DEFAULT date rather than TODAY."
12258 (when (and
12259 (string-match
12260 (concat
12261 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12262 "\\([0-9]+\\)?"
12263 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12264 "\\([ \t]\\|$\\)") s)
12265 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12266 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12267 (string-to-char (substring (match-string 1 s) -1))
12268 ?+))
12269 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12270 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12271 (what (if (match-end 3) (match-string 3 s) "d"))
12272 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12273 (date (if rel default today))
12274 (wday (nth 6 (decode-time date)))
12275 delta)
12276 (if wday1
12277 (progn
12278 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12279 (if (= dir ?-) (setq delta (- delta 7)))
12280 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12281 (list delta "d" rel))
12282 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12284 (defun org-eval-in-calendar (form &optional keepdate)
12285 "Eval FORM in the calendar window and return to current window.
12286 Also, store the cursor date in variable org-ans2."
12287 (let ((sw (selected-window)))
12288 (select-window (get-buffer-window "*Calendar*"))
12289 (eval form)
12290 (when (and (not keepdate) (calendar-cursor-to-date))
12291 (let* ((date (calendar-cursor-to-date))
12292 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12293 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12294 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12295 (select-window sw)))
12297 (defun org-calendar-select ()
12298 "Return to `org-read-date' with the date currently selected.
12299 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12300 (interactive)
12301 (when (calendar-cursor-to-date)
12302 (let* ((date (calendar-cursor-to-date))
12303 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12304 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12305 (if (active-minibuffer-window) (exit-minibuffer))))
12307 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12308 "Insert a date stamp for the date given by the internal TIME.
12309 WITH-HM means, use the stamp format that includes the time of the day.
12310 INACTIVE means use square brackets instead of angular ones, so that the
12311 stamp will not contribute to the agenda.
12312 PRE and POST are optional strings to be inserted before and after the
12313 stamp.
12314 The command returns the inserted time stamp."
12315 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12316 stamp)
12317 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12318 (insert-before-markers (or pre ""))
12319 (insert-before-markers (setq stamp (format-time-string fmt time)))
12320 (when (listp extra)
12321 (setq extra (car extra))
12322 (if (and (stringp extra)
12323 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12324 (setq extra (format "-%02d:%02d"
12325 (string-to-number (match-string 1 extra))
12326 (string-to-number (match-string 2 extra))))
12327 (setq extra nil)))
12328 (when extra
12329 (backward-char 1)
12330 (insert-before-markers extra)
12331 (forward-char 1))
12332 (insert-before-markers (or post ""))
12333 (setq org-last-inserted-timestamp stamp)))
12335 (defun org-toggle-time-stamp-overlays ()
12336 "Toggle the use of custom time stamp formats."
12337 (interactive)
12338 (setq org-display-custom-times (not org-display-custom-times))
12339 (unless org-display-custom-times
12340 (let ((p (point-min)) (bmp (buffer-modified-p)))
12341 (while (setq p (next-single-property-change p 'display))
12342 (if (and (get-text-property p 'display)
12343 (eq (get-text-property p 'face) 'org-date))
12344 (remove-text-properties
12345 p (setq p (next-single-property-change p 'display))
12346 '(display t))))
12347 (set-buffer-modified-p bmp)))
12348 (if (featurep 'xemacs)
12349 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12350 (org-restart-font-lock)
12351 (setq org-table-may-need-update t)
12352 (if org-display-custom-times
12353 (message "Time stamps are overlayed with custom format")
12354 (message "Time stamp overlays removed")))
12356 (defun org-display-custom-time (beg end)
12357 "Overlay modified time stamp format over timestamp between BEG and END."
12358 (let* ((ts (buffer-substring beg end))
12359 t1 w1 with-hm tf time str w2 (off 0))
12360 (save-match-data
12361 (setq t1 (org-parse-time-string ts t))
12362 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12363 (setq off (- (match-end 0) (match-beginning 0)))))
12364 (setq end (- end off))
12365 (setq w1 (- end beg)
12366 with-hm (and (nth 1 t1) (nth 2 t1))
12367 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12368 time (org-fix-decoded-time t1)
12369 str (org-add-props
12370 (format-time-string
12371 (substring tf 1 -1) (apply 'encode-time time))
12372 nil 'mouse-face 'highlight)
12373 w2 (length str))
12374 (if (not (= w2 w1))
12375 (add-text-properties (1+ beg) (+ 2 beg)
12376 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12377 (if (featurep 'xemacs)
12378 (progn
12379 (put-text-property beg end 'invisible t)
12380 (put-text-property beg end 'end-glyph (make-glyph str)))
12381 (put-text-property beg end 'display str))))
12383 (defun org-translate-time (string)
12384 "Translate all timestamps in STRING to custom format.
12385 But do this only if the variable `org-display-custom-times' is set."
12386 (when org-display-custom-times
12387 (save-match-data
12388 (let* ((start 0)
12389 (re org-ts-regexp-both)
12390 t1 with-hm inactive tf time str beg end)
12391 (while (setq start (string-match re string start))
12392 (setq beg (match-beginning 0)
12393 end (match-end 0)
12394 t1 (save-match-data
12395 (org-parse-time-string (substring string beg end) t))
12396 with-hm (and (nth 1 t1) (nth 2 t1))
12397 inactive (equal (substring string beg (1+ beg)) "[")
12398 tf (funcall (if with-hm 'cdr 'car)
12399 org-time-stamp-custom-formats)
12400 time (org-fix-decoded-time t1)
12401 str (format-time-string
12402 (concat
12403 (if inactive "[" "<") (substring tf 1 -1)
12404 (if inactive "]" ">"))
12405 (apply 'encode-time time))
12406 string (replace-match str t t string)
12407 start (+ start (length str)))))))
12408 string)
12410 (defun org-fix-decoded-time (time)
12411 "Set 0 instead of nil for the first 6 elements of time.
12412 Don't touch the rest."
12413 (let ((n 0))
12414 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12416 (defun org-days-to-time (timestamp-string)
12417 "Difference between TIMESTAMP-STRING and now in days."
12418 (- (time-to-days (org-time-string-to-time timestamp-string))
12419 (time-to-days (current-time))))
12421 (defun org-deadline-close (timestamp-string &optional ndays)
12422 "Is the time in TIMESTAMP-STRING close to the current date?"
12423 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12424 (and (< (org-days-to-time timestamp-string) ndays)
12425 (not (org-entry-is-done-p))))
12427 (defun org-get-wdays (ts)
12428 "Get the deadline lead time appropriate for timestring TS."
12429 (cond
12430 ((<= org-deadline-warning-days 0)
12431 ;; 0 or negative, enforce this value no matter what
12432 (- org-deadline-warning-days))
12433 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12434 ;; lead time is specified.
12435 (floor (* (string-to-number (match-string 1 ts))
12436 (cdr (assoc (match-string 2 ts)
12437 '(("d" . 1) ("w" . 7)
12438 ("m" . 30.4) ("y" . 365.25)))))))
12439 ;; go for the default.
12440 (t org-deadline-warning-days)))
12442 (defun org-calendar-select-mouse (ev)
12443 "Return to `org-read-date' with the date currently selected.
12444 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12445 (interactive "e")
12446 (mouse-set-point ev)
12447 (when (calendar-cursor-to-date)
12448 (let* ((date (calendar-cursor-to-date))
12449 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12450 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12451 (if (active-minibuffer-window) (exit-minibuffer))))
12453 (defun org-check-deadlines (ndays)
12454 "Check if there are any deadlines due or past due.
12455 A deadline is considered due if it happens within `org-deadline-warning-days'
12456 days from today's date. If the deadline appears in an entry marked DONE,
12457 it is not shown. The prefix arg NDAYS can be used to test that many
12458 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12459 (interactive "P")
12460 (let* ((org-warn-days
12461 (cond
12462 ((equal ndays '(4)) 100000)
12463 (ndays (prefix-numeric-value ndays))
12464 (t (abs org-deadline-warning-days))))
12465 (case-fold-search nil)
12466 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12467 (callback
12468 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12470 (message "%d deadlines past-due or due within %d days"
12471 (org-occur regexp nil callback)
12472 org-warn-days)))
12474 (defun org-check-before-date (date)
12475 "Check if there are deadlines or scheduled entries before DATE."
12476 (interactive (list (org-read-date)))
12477 (let ((case-fold-search nil)
12478 (regexp (concat "\\<\\(" org-deadline-string
12479 "\\|" org-scheduled-string
12480 "\\) *<\\([^>]+\\)>"))
12481 (callback
12482 (lambda () (time-less-p
12483 (org-time-string-to-time (match-string 2))
12484 (org-time-string-to-time date)))))
12485 (message "%d entries before %s"
12486 (org-occur regexp nil callback) date)))
12488 (defun org-check-after-date (date)
12489 "Check if there are deadlines or scheduled entries after DATE."
12490 (interactive (list (org-read-date)))
12491 (let ((case-fold-search nil)
12492 (regexp (concat "\\<\\(" org-deadline-string
12493 "\\|" org-scheduled-string
12494 "\\) *<\\([^>]+\\)>"))
12495 (callback
12496 (lambda () (not
12497 (time-less-p
12498 (org-time-string-to-time (match-string 2))
12499 (org-time-string-to-time date))))))
12500 (message "%d entries after %s"
12501 (org-occur regexp nil callback) date)))
12503 (defun org-evaluate-time-range (&optional to-buffer)
12504 "Evaluate a time range by computing the difference between start and end.
12505 Normally the result is just printed in the echo area, but with prefix arg
12506 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12507 If the time range is actually in a table, the result is inserted into the
12508 next column.
12509 For time difference computation, a year is assumed to be exactly 365
12510 days in order to avoid rounding problems."
12511 (interactive "P")
12513 (org-clock-update-time-maybe)
12514 (save-excursion
12515 (unless (org-at-date-range-p t)
12516 (goto-char (point-at-bol))
12517 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12518 (if (not (org-at-date-range-p t))
12519 (error "Not at a time-stamp range, and none found in current line")))
12520 (let* ((ts1 (match-string 1))
12521 (ts2 (match-string 2))
12522 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12523 (match-end (match-end 0))
12524 (time1 (org-time-string-to-time ts1))
12525 (time2 (org-time-string-to-time ts2))
12526 (t1 (time-to-seconds time1))
12527 (t2 (time-to-seconds time2))
12528 (diff (abs (- t2 t1)))
12529 (negative (< (- t2 t1) 0))
12530 ;; (ys (floor (* 365 24 60 60)))
12531 (ds (* 24 60 60))
12532 (hs (* 60 60))
12533 (fy "%dy %dd %02d:%02d")
12534 (fy1 "%dy %dd")
12535 (fd "%dd %02d:%02d")
12536 (fd1 "%dd")
12537 (fh "%02d:%02d")
12538 y d h m align)
12539 (if havetime
12540 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12542 d (floor (/ diff ds)) diff (mod diff ds)
12543 h (floor (/ diff hs)) diff (mod diff hs)
12544 m (floor (/ diff 60)))
12545 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12547 d (floor (+ (/ diff ds) 0.5))
12548 h 0 m 0))
12549 (if (not to-buffer)
12550 (message "%s" (org-make-tdiff-string y d h m))
12551 (if (org-at-table-p)
12552 (progn
12553 (goto-char match-end)
12554 (setq align t)
12555 (and (looking-at " *|") (goto-char (match-end 0))))
12556 (goto-char match-end))
12557 (if (looking-at
12558 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12559 (replace-match ""))
12560 (if negative (insert " -"))
12561 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12562 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12563 (insert " " (format fh h m))))
12564 (if align (org-table-align))
12565 (message "Time difference inserted")))))
12567 (defun org-make-tdiff-string (y d h m)
12568 (let ((fmt "")
12569 (l nil))
12570 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12571 l (push y l)))
12572 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12573 l (push d l)))
12574 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12575 l (push h l)))
12576 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12577 l (push m l)))
12578 (apply 'format fmt (nreverse l))))
12580 (defun org-time-string-to-time (s)
12581 (apply 'encode-time (org-parse-time-string s)))
12583 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12584 "Convert a time stamp to an absolute day number.
12585 If there is a specifyer for a cyclic time stamp, get the closest date to
12586 DAYNR.
12587 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12588 (cond
12589 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12590 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12591 daynr
12592 (+ daynr 1000)))
12593 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12594 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12595 (time-to-days (current-time))) (match-string 0 s)
12596 prefer show-all))
12597 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12599 (defun org-days-to-iso-week (days)
12600 "Return the iso week number."
12601 (require 'cal-iso)
12602 (car (calendar-iso-from-absolute days)))
12604 (defun org-small-year-to-year (year)
12605 "Convert 2-digit years into 4-digit years.
12606 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12607 The year 2000 cannot be abbreviated. Any year larger than 99
12608 is returned unchanged."
12609 (if (< year 38)
12610 (setq year (+ 2000 year))
12611 (if (< year 100)
12612 (setq year (+ 1900 year))))
12613 year)
12615 (defun org-time-from-absolute (d)
12616 "Return the time corresponding to date D.
12617 D may be an absolute day number, or a calendar-type list (month day year)."
12618 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12619 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12621 (defun org-calendar-holiday ()
12622 "List of holidays, for Diary display in Org-mode."
12623 (require 'holidays)
12624 (let ((hl (funcall
12625 (if (fboundp 'calendar-check-holidays)
12626 'calendar-check-holidays 'check-calendar-holidays) date)))
12627 (if hl (mapconcat 'identity hl "; "))))
12629 (defun org-diary-sexp-entry (sexp entry date)
12630 "Process a SEXP diary ENTRY for DATE."
12631 (require 'diary-lib)
12632 (let ((result (if calendar-debug-sexp
12633 (let ((stack-trace-on-error t))
12634 (eval (car (read-from-string sexp))))
12635 (condition-case nil
12636 (eval (car (read-from-string sexp)))
12637 (error
12638 (beep)
12639 (message "Bad sexp at line %d in %s: %s"
12640 (org-current-line)
12641 (buffer-file-name) sexp)
12642 (sleep-for 2))))))
12643 (cond ((stringp result) result)
12644 ((and (consp result)
12645 (stringp (cdr result))) (cdr result))
12646 (result entry)
12647 (t nil))))
12649 (defun org-diary-to-ical-string (frombuf)
12650 "Get iCalendar entries from diary entries in buffer FROMBUF.
12651 This uses the icalendar.el library."
12652 (let* ((tmpdir (if (featurep 'xemacs)
12653 (temp-directory)
12654 temporary-file-directory))
12655 (tmpfile (make-temp-name
12656 (expand-file-name "orgics" tmpdir)))
12657 buf rtn b e)
12658 (save-excursion
12659 (set-buffer frombuf)
12660 (icalendar-export-region (point-min) (point-max) tmpfile)
12661 (setq buf (find-buffer-visiting tmpfile))
12662 (set-buffer buf)
12663 (goto-char (point-min))
12664 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12665 (setq b (match-beginning 0)))
12666 (goto-char (point-max))
12667 (if (re-search-backward "^END:VEVENT" nil t)
12668 (setq e (match-end 0)))
12669 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12670 (kill-buffer buf)
12671 (delete-file tmpfile)
12672 rtn))
12674 (defun org-closest-date (start current change prefer show-all)
12675 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12676 When PREFER is `past' return a date that is either CURRENT or past.
12677 When PREFER is `future', return a date that is either CURRENT or future.
12678 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12679 ;; Make the proper lists from the dates
12680 (catch 'exit
12681 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12682 dn dw sday cday n1 n2 n0
12683 d m y y1 y2 date1 date2 nmonths nm ny m2)
12685 (setq start (org-date-to-gregorian start)
12686 current (org-date-to-gregorian
12687 (if show-all
12688 current
12689 (time-to-days (current-time))))
12690 sday (calendar-absolute-from-gregorian start)
12691 cday (calendar-absolute-from-gregorian current))
12693 (if (<= cday sday) (throw 'exit sday))
12695 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12696 (setq dn (string-to-number (match-string 1 change))
12697 dw (cdr (assoc (match-string 2 change) a1)))
12698 (error "Invalid change specifyer: %s" change))
12699 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12700 (cond
12701 ((eq dw 'day)
12702 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12703 n2 (+ n1 dn)))
12704 ((eq dw 'year)
12705 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12706 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12707 (setq date1 (list m d y1)
12708 n1 (calendar-absolute-from-gregorian date1)
12709 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12710 n2 (calendar-absolute-from-gregorian date2)))
12711 ((eq dw 'month)
12712 ;; approx number of month between the two dates
12713 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12714 ;; How often does dn fit in there?
12715 (setq d (nth 1 start) m (car start) y (nth 2 start)
12716 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12717 m (+ m nm)
12718 ny (floor (/ m 12))
12719 y (+ y ny)
12720 m (- m (* ny 12)))
12721 (while (> m 12) (setq m (- m 12) y (1+ y)))
12722 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12723 (setq m2 (+ m dn) y2 y)
12724 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12725 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12726 (while (<= n2 cday)
12727 (setq n1 n2 m m2 y y2)
12728 (setq m2 (+ m dn) y2 y)
12729 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12730 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12731 ;; Make sure n1 is the earlier date
12732 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12733 (if show-all
12734 (cond
12735 ((eq prefer 'past) n1)
12736 ((eq prefer 'future) (if (= cday n1) n1 n2))
12737 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12738 (cond
12739 ((eq prefer 'past) n1)
12740 ((eq prefer 'future) (if (= cday n1) n1 n2))
12741 (t (if (= cday n1) n1 n2)))))))
12743 (defun org-date-to-gregorian (date)
12744 "Turn any specification of DATE into a gregorian date for the calendar."
12745 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12746 ((and (listp date) (= (length date) 3)) date)
12747 ((stringp date)
12748 (setq date (org-parse-time-string date))
12749 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12750 ((listp date)
12751 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12753 (defun org-parse-time-string (s &optional nodefault)
12754 "Parse the standard Org-mode time string.
12755 This should be a lot faster than the normal `parse-time-string'.
12756 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12757 hour and minute fields will be nil if not given."
12758 (if (string-match org-ts-regexp0 s)
12759 (list 0
12760 (if (or (match-beginning 8) (not nodefault))
12761 (string-to-number (or (match-string 8 s) "0")))
12762 (if (or (match-beginning 7) (not nodefault))
12763 (string-to-number (or (match-string 7 s) "0")))
12764 (string-to-number (match-string 4 s))
12765 (string-to-number (match-string 3 s))
12766 (string-to-number (match-string 2 s))
12767 nil nil nil)
12768 (make-list 9 0)))
12770 (defun org-timestamp-up (&optional arg)
12771 "Increase the date item at the cursor by one.
12772 If the cursor is on the year, change the year. If it is on the month or
12773 the day, change that.
12774 With prefix ARG, change by that many units."
12775 (interactive "p")
12776 (org-timestamp-change (prefix-numeric-value arg)))
12778 (defun org-timestamp-down (&optional arg)
12779 "Decrease the date item at the cursor by one.
12780 If the cursor is on the year, change the year. If it is on the month or
12781 the day, change that.
12782 With prefix ARG, change by that many units."
12783 (interactive "p")
12784 (org-timestamp-change (- (prefix-numeric-value arg))))
12786 (defun org-timestamp-up-day (&optional arg)
12787 "Increase the date in the time stamp by one day.
12788 With prefix ARG, change that many days."
12789 (interactive "p")
12790 (if (and (not (org-at-timestamp-p t))
12791 (org-on-heading-p))
12792 (org-todo 'up)
12793 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12795 (defun org-timestamp-down-day (&optional arg)
12796 "Decrease the date in the time stamp by one day.
12797 With prefix ARG, change that many days."
12798 (interactive "p")
12799 (if (and (not (org-at-timestamp-p t))
12800 (org-on-heading-p))
12801 (org-todo 'down)
12802 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12804 (defun org-at-timestamp-p (&optional inactive-ok)
12805 "Determine if the cursor is in or at a timestamp."
12806 (interactive)
12807 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12808 (pos (point))
12809 (ans (or (looking-at tsr)
12810 (save-excursion
12811 (skip-chars-backward "^[<\n\r\t")
12812 (if (> (point) (point-min)) (backward-char 1))
12813 (and (looking-at tsr)
12814 (> (- (match-end 0) pos) -1))))))
12815 (and ans
12816 (boundp 'org-ts-what)
12817 (setq org-ts-what
12818 (cond
12819 ((= pos (match-beginning 0)) 'bracket)
12820 ((= pos (1- (match-end 0))) 'bracket)
12821 ((org-pos-in-match-range pos 2) 'year)
12822 ((org-pos-in-match-range pos 3) 'month)
12823 ((org-pos-in-match-range pos 7) 'hour)
12824 ((org-pos-in-match-range pos 8) 'minute)
12825 ((or (org-pos-in-match-range pos 4)
12826 (org-pos-in-match-range pos 5)) 'day)
12827 ((and (> pos (or (match-end 8) (match-end 5)))
12828 (< pos (match-end 0)))
12829 (- pos (or (match-end 8) (match-end 5))))
12830 (t 'day))))
12831 ans))
12833 (defun org-toggle-timestamp-type ()
12834 "Toggle the type (<active> or [inactive]) of a time stamp."
12835 (interactive)
12836 (when (org-at-timestamp-p t)
12837 (let ((beg (match-beginning 0)) (end (match-end 0))
12838 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12839 (save-excursion
12840 (goto-char beg)
12841 (while (re-search-forward "[][<>]" end t)
12842 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12843 t t)))
12844 (message "Timestamp is now %sactive"
12845 (if (equal (char-after beg) ?<) "" "in")))))
12847 (defun org-timestamp-change (n &optional what)
12848 "Change the date in the time stamp at point.
12849 The date will be changed by N times WHAT. WHAT can be `day', `month',
12850 `year', `minute', `second'. If WHAT is not given, the cursor position
12851 in the timestamp determines what will be changed."
12852 (let ((pos (point))
12853 with-hm inactive
12854 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12855 org-ts-what
12856 extra rem
12857 ts time time0)
12858 (if (not (org-at-timestamp-p t))
12859 (error "Not at a timestamp"))
12860 (if (and (not what) (eq org-ts-what 'bracket))
12861 (org-toggle-timestamp-type)
12862 (if (and (not what) (not (eq org-ts-what 'day))
12863 org-display-custom-times
12864 (get-text-property (point) 'display)
12865 (not (get-text-property (1- (point)) 'display)))
12866 (setq org-ts-what 'day))
12867 (setq org-ts-what (or what org-ts-what)
12868 inactive (= (char-after (match-beginning 0)) ?\[)
12869 ts (match-string 0))
12870 (replace-match "")
12871 (if (string-match
12872 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12874 (setq extra (match-string 1 ts)))
12875 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12876 (setq with-hm t))
12877 (setq time0 (org-parse-time-string ts))
12878 (when (and (eq org-ts-what 'minute)
12879 (eq current-prefix-arg nil))
12880 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12881 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12882 (setcar (cdr time0) (+ (nth 1 time0)
12883 (if (> n 0) (- rem) (- dm rem))))))
12884 (setq time
12885 (encode-time (or (car time0) 0)
12886 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12887 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12888 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12889 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12890 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12891 (nthcdr 6 time0)))
12892 (when (and (member org-ts-what '(hour minute))
12893 extra
12894 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
12895 (setq extra (org-modify-ts-extra
12896 extra
12897 (if (eq org-ts-what 'hour) 2 5)
12898 n dm)))
12899 (when (integerp org-ts-what)
12900 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12901 (if (eq what 'calendar)
12902 (let ((cal-date (org-get-date-from-calendar)))
12903 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12904 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12905 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12906 (setcar time0 (or (car time0) 0))
12907 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12908 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12909 (setq time (apply 'encode-time time0))))
12910 (setq org-last-changed-timestamp
12911 (org-insert-time-stamp time with-hm inactive nil nil extra))
12912 (org-clock-update-time-maybe)
12913 (goto-char pos)
12914 ;; Try to recenter the calendar window, if any
12915 (if (and org-calendar-follow-timestamp-change
12916 (get-buffer-window "*Calendar*" t)
12917 (memq org-ts-what '(day month year)))
12918 (org-recenter-calendar (time-to-days time))))))
12920 (defun org-modify-ts-extra (s pos n dm)
12921 "Change the different parts of the lead-time and repeat fields in timestamp."
12922 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12923 ng h m new rem)
12924 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12925 (cond
12926 ((or (org-pos-in-match-range pos 2)
12927 (org-pos-in-match-range pos 3))
12928 (setq m (string-to-number (match-string 3 s))
12929 h (string-to-number (match-string 2 s)))
12930 (if (org-pos-in-match-range pos 2)
12931 (setq h (+ h n))
12932 (setq n (* dm (org-no-warnings (signum n))))
12933 (when (not (= 0 (setq rem (% m dm))))
12934 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12935 (setq m (+ m n)))
12936 (if (< m 0) (setq m (+ m 60) h (1- h)))
12937 (if (> m 59) (setq m (- m 60) h (1+ h)))
12938 (setq h (min 24 (max 0 h)))
12939 (setq ng 1 new (format "-%02d:%02d" h m)))
12940 ((org-pos-in-match-range pos 6)
12941 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12942 ((org-pos-in-match-range pos 5)
12943 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12945 ((org-pos-in-match-range pos 9)
12946 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12947 ((org-pos-in-match-range pos 8)
12948 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12950 (when ng
12951 (setq s (concat
12952 (substring s 0 (match-beginning ng))
12954 (substring s (match-end ng))))))
12957 (defun org-recenter-calendar (date)
12958 "If the calendar is visible, recenter it to DATE."
12959 (let* ((win (selected-window))
12960 (cwin (get-buffer-window "*Calendar*" t))
12961 (calendar-move-hook nil))
12962 (when cwin
12963 (select-window cwin)
12964 (calendar-goto-date (if (listp date) date
12965 (calendar-gregorian-from-absolute date)))
12966 (select-window win))))
12968 (defun org-goto-calendar (&optional arg)
12969 "Go to the Emacs calendar at the current date.
12970 If there is a time stamp in the current line, go to that date.
12971 A prefix ARG can be used to force the current date."
12972 (interactive "P")
12973 (let ((tsr org-ts-regexp) diff
12974 (calendar-move-hook nil)
12975 (calendar-view-holidays-initially-flag nil)
12976 (view-calendar-holidays-initially nil)
12977 (calendar-view-diary-initially-flag nil)
12978 (view-diary-entries-initially nil))
12979 (if (or (org-at-timestamp-p)
12980 (save-excursion
12981 (beginning-of-line 1)
12982 (looking-at (concat ".*" tsr))))
12983 (let ((d1 (time-to-days (current-time)))
12984 (d2 (time-to-days
12985 (org-time-string-to-time (match-string 1)))))
12986 (setq diff (- d2 d1))))
12987 (calendar)
12988 (calendar-goto-today)
12989 (if (and diff (not arg)) (calendar-forward-day diff))))
12991 (defun org-get-date-from-calendar ()
12992 "Return a list (month day year) of date at point in calendar."
12993 (with-current-buffer "*Calendar*"
12994 (save-match-data
12995 (calendar-cursor-to-date))))
12997 (defun org-date-from-calendar ()
12998 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12999 If there is already a time stamp at the cursor position, update it."
13000 (interactive)
13001 (if (org-at-timestamp-p t)
13002 (org-timestamp-change 0 'calendar)
13003 (let ((cal-date (org-get-date-from-calendar)))
13004 (org-insert-time-stamp
13005 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13007 (defun org-minutes-to-hh:mm-string (m)
13008 "Compute H:MM from a number of minutes."
13009 (let ((h (/ m 60)))
13010 (setq m (- m (* 60 h)))
13011 (format org-time-clocksum-format h m)))
13013 (defun org-hh:mm-string-to-minutes (s)
13014 "Convert a string H:MM to a number of minutes."
13015 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13016 (+ (* (string-to-number (match-string 1 s)) 60)
13017 (string-to-number (match-string 2 s)))
13020 ;;;; Files
13022 (defun org-save-all-org-buffers ()
13023 "Save all Org-mode buffers without user confirmation."
13024 (interactive)
13025 (message "Saving all Org-mode buffers...")
13026 (save-some-buffers t 'org-mode-p)
13027 (when (featurep 'org-id) (org-id-locations-save))
13028 (message "Saving all Org-mode buffers... done"))
13030 (defun org-revert-all-org-buffers ()
13031 "Revert all Org-mode buffers.
13032 Prompt for confirmation when there are unsaved changes.
13033 Be sure you know what you are doing before letting this function
13034 overwrite your changes.
13036 This function is useful in a setup where one tracks org files
13037 with a version control system, to revert on one machine after pulling
13038 changes from another. I believe the procedure must be like this:
13040 1. M-x org-save-all-org-buffers
13041 2. Pull changes from the other machine, resolve conflicts
13042 3. M-x org-revert-all-org-buffers"
13043 (interactive)
13044 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13045 (error "Abort"))
13046 (save-excursion
13047 (save-window-excursion
13048 (mapc
13049 (lambda (b)
13050 (when (and (with-current-buffer b (org-mode-p))
13051 (with-current-buffer b buffer-file-name))
13052 (switch-to-buffer b)
13053 (revert-buffer t 'no-confirm)))
13054 (buffer-list))
13055 (when (and (featurep 'org-id) org-id-track-globally)
13056 (org-id-locations-load)))))
13058 ;;;; Agenda files
13060 ;;;###autoload
13061 (defun org-iswitchb (&optional arg)
13062 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13063 With a prefix argument, restrict available to files.
13064 With two prefix arguments, restrict available buffers to agenda files.
13066 Due to some yet unresolved reason, the global function
13067 `iswitchb-mode' needs to be active for this function to work."
13068 (interactive "P")
13069 (require 'iswitchb)
13070 (let ((enabled iswitchb-mode) blist)
13071 (or enabled (iswitchb-mode 1))
13072 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13073 ((equal arg '(16)) (org-buffer-list 'agenda))
13074 (t (org-buffer-list))))
13075 (unwind-protect
13076 (let ((iswitchb-make-buflist-hook
13077 (lambda ()
13078 (setq iswitchb-temp-buflist
13079 (mapcar 'buffer-name blist)))))
13080 (switch-to-buffer
13081 (iswitchb-read-buffer
13082 "Switch-to: " nil t))
13083 (or enabled (iswitchb-mode -1))))))
13085 ;;;###autoload
13086 (defun org-ido-switchb (&optional arg)
13087 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13088 With a prefix argument, restrict available to files.
13089 With two prefix arguments, restrict available buffers to agenda files."
13090 (interactive "P")
13091 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13092 ((equal arg '(16)) (org-buffer-list 'agenda))
13093 (t (org-buffer-list)))))
13094 (switch-to-buffer
13095 (org-ido-completing-read "Org buffer: "
13096 (mapcar 'list (mapcar 'buffer-name blist))
13097 nil t))))
13099 (defun org-buffer-list (&optional predicate exclude-tmp)
13100 "Return a list of Org buffers.
13101 PREDICATE can be `export', `files' or `agenda'.
13103 export restrict the list to Export buffers.
13104 files restrict the list to buffers visiting Org files.
13105 agenda restrict the list to buffers visiting agenda files.
13107 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13108 (let* ((bfn nil)
13109 (agenda-files (and (eq predicate 'agenda)
13110 (mapcar 'file-truename (org-agenda-files t))))
13111 (filter
13112 (cond
13113 ((eq predicate 'files)
13114 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13115 ((eq predicate 'export)
13116 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13117 ((eq predicate 'agenda)
13118 (lambda (b)
13119 (with-current-buffer b
13120 (and (eq major-mode 'org-mode)
13121 (setq bfn (buffer-file-name b))
13122 (member (file-truename bfn) agenda-files)))))
13123 (t (lambda (b) (with-current-buffer b
13124 (or (eq major-mode 'org-mode)
13125 (string-match "\*Org .*Export"
13126 (buffer-name b)))))))))
13127 (delq nil
13128 (mapcar
13129 (lambda(b)
13130 (if (and (funcall filter b)
13131 (or (not exclude-tmp)
13132 (not (string-match "tmp" (buffer-name b)))))
13134 nil))
13135 (buffer-list)))))
13137 (defun org-agenda-files (&optional unrestricted archives)
13138 "Get the list of agenda files.
13139 Optional UNRESTRICTED means return the full list even if a restriction
13140 is currently in place.
13141 When ARCHIVES is t, include all archive files hat are really being
13142 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13143 `org-agenda-archives-mode' is t."
13144 (let ((files
13145 (cond
13146 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13147 ((stringp org-agenda-files) (org-read-agenda-file-list))
13148 ((listp org-agenda-files) org-agenda-files)
13149 (t (error "Invalid value of `org-agenda-files'")))))
13150 (setq files (apply 'append
13151 (mapcar (lambda (f)
13152 (if (file-directory-p f)
13153 (directory-files
13154 f t org-agenda-file-regexp)
13155 (list f)))
13156 files)))
13157 (when org-agenda-skip-unavailable-files
13158 (setq files (delq nil
13159 (mapcar (function
13160 (lambda (file)
13161 (and (file-readable-p file) file)))
13162 files))))
13163 (when (or (eq archives t)
13164 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13165 (setq files (org-add-archive-files files)))
13166 files))
13168 (defun org-edit-agenda-file-list ()
13169 "Edit the list of agenda files.
13170 Depending on setup, this either uses customize to edit the variable
13171 `org-agenda-files', or it visits the file that is holding the list. In the
13172 latter case, the buffer is set up in a way that saving it automatically kills
13173 the buffer and restores the previous window configuration."
13174 (interactive)
13175 (if (stringp org-agenda-files)
13176 (let ((cw (current-window-configuration)))
13177 (find-file org-agenda-files)
13178 (org-set-local 'org-window-configuration cw)
13179 (org-add-hook 'after-save-hook
13180 (lambda ()
13181 (set-window-configuration
13182 (prog1 org-window-configuration
13183 (kill-buffer (current-buffer))))
13184 (org-install-agenda-files-menu)
13185 (message "New agenda file list installed"))
13186 nil 'local)
13187 (message "%s" (substitute-command-keys
13188 "Edit list and finish with \\[save-buffer]")))
13189 (customize-variable 'org-agenda-files)))
13191 (defun org-store-new-agenda-file-list (list)
13192 "Set new value for the agenda file list and save it correctly."
13193 (if (stringp org-agenda-files)
13194 (let ((f org-agenda-files) b)
13195 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13196 (with-temp-file f
13197 (insert (mapconcat 'identity list "\n") "\n")))
13198 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13199 (setq org-agenda-files list)
13200 (customize-save-variable 'org-agenda-files org-agenda-files))))
13202 (defun org-read-agenda-file-list ()
13203 "Read the list of agenda files from a file."
13204 (when (file-directory-p org-agenda-files)
13205 (error "`org-agenda-files' cannot be a single directory"))
13206 (when (stringp org-agenda-files)
13207 (with-temp-buffer
13208 (insert-file-contents org-agenda-files)
13209 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13212 ;;;###autoload
13213 (defun org-cycle-agenda-files ()
13214 "Cycle through the files in `org-agenda-files'.
13215 If the current buffer visits an agenda file, find the next one in the list.
13216 If the current buffer does not, find the first agenda file."
13217 (interactive)
13218 (let* ((fs (org-agenda-files t))
13219 (files (append fs (list (car fs))))
13220 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13221 file)
13222 (unless files (error "No agenda files"))
13223 (catch 'exit
13224 (while (setq file (pop files))
13225 (if (equal (file-truename file) tcf)
13226 (when (car files)
13227 (find-file (car files))
13228 (throw 'exit t))))
13229 (find-file (car fs)))
13230 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13232 (defun org-agenda-file-to-front (&optional to-end)
13233 "Move/add the current file to the top of the agenda file list.
13234 If the file is not present in the list, it is added to the front. If it is
13235 present, it is moved there. With optional argument TO-END, add/move to the
13236 end of the list."
13237 (interactive "P")
13238 (let ((org-agenda-skip-unavailable-files nil)
13239 (file-alist (mapcar (lambda (x)
13240 (cons (file-truename x) x))
13241 (org-agenda-files t)))
13242 (ctf (file-truename buffer-file-name))
13243 x had)
13244 (setq x (assoc ctf file-alist) had x)
13246 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13247 (if to-end
13248 (setq file-alist (append (delq x file-alist) (list x)))
13249 (setq file-alist (cons x (delq x file-alist))))
13250 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13251 (org-install-agenda-files-menu)
13252 (message "File %s to %s of agenda file list"
13253 (if had "moved" "added") (if to-end "end" "front"))))
13255 (defun org-remove-file (&optional file)
13256 "Remove current file from the list of files in variable `org-agenda-files'.
13257 These are the files which are being checked for agenda entries.
13258 Optional argument FILE means, use this file instead of the current."
13259 (interactive)
13260 (let* ((org-agenda-skip-unavailable-files nil)
13261 (file (or file buffer-file-name))
13262 (true-file (file-truename file))
13263 (afile (abbreviate-file-name file))
13264 (files (delq nil (mapcar
13265 (lambda (x)
13266 (if (equal true-file
13267 (file-truename x))
13268 nil x))
13269 (org-agenda-files t)))))
13270 (if (not (= (length files) (length (org-agenda-files t))))
13271 (progn
13272 (org-store-new-agenda-file-list files)
13273 (org-install-agenda-files-menu)
13274 (message "Removed file: %s" afile))
13275 (message "File was not in list: %s (not removed)" afile))))
13277 (defun org-file-menu-entry (file)
13278 (vector file (list 'find-file file) t))
13280 (defun org-check-agenda-file (file)
13281 "Make sure FILE exists. If not, ask user what to do."
13282 (when (not (file-exists-p file))
13283 (message "non-existent file %s. [R]emove from list or [A]bort?"
13284 (abbreviate-file-name file))
13285 (let ((r (downcase (read-char-exclusive))))
13286 (cond
13287 ((equal r ?r)
13288 (org-remove-file file)
13289 (throw 'nextfile t))
13290 (t (error "Abort"))))))
13292 (defun org-get-agenda-file-buffer (file)
13293 "Get a buffer visiting FILE. If the buffer needs to be created, add
13294 it to the list of buffers which might be released later."
13295 (let ((buf (org-find-base-buffer-visiting file)))
13296 (if buf
13297 buf ; just return it
13298 ;; Make a new buffer and remember it
13299 (setq buf (find-file-noselect file))
13300 (if buf (push buf org-agenda-new-buffers))
13301 buf)))
13303 (defun org-release-buffers (blist)
13304 "Release all buffers in list, asking the user for confirmation when needed.
13305 When a buffer is unmodified, it is just killed. When modified, it is saved
13306 \(if the user agrees) and then killed."
13307 (let (buf file)
13308 (while (setq buf (pop blist))
13309 (setq file (buffer-file-name buf))
13310 (when (and (buffer-modified-p buf)
13311 file
13312 (y-or-n-p (format "Save file %s? " file)))
13313 (with-current-buffer buf (save-buffer)))
13314 (kill-buffer buf))))
13316 (defun org-prepare-agenda-buffers (files)
13317 "Create buffers for all agenda files, protect archived trees and comments."
13318 (interactive)
13319 (let ((pa '(:org-archived t))
13320 (pc '(:org-comment t))
13321 (pall '(:org-archived t :org-comment t))
13322 (inhibit-read-only t)
13323 (rea (concat ":" org-archive-tag ":"))
13324 bmp file re)
13325 (save-excursion
13326 (save-restriction
13327 (while (setq file (pop files))
13328 (catch 'nextfile
13329 (if (bufferp file)
13330 (set-buffer file)
13331 (org-check-agenda-file file)
13332 (set-buffer (org-get-agenda-file-buffer file)))
13333 (widen)
13334 (setq bmp (buffer-modified-p))
13335 (org-refresh-category-properties)
13336 (setq org-todo-keywords-for-agenda
13337 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13338 (setq org-done-keywords-for-agenda
13339 (append org-done-keywords-for-agenda org-done-keywords))
13340 (setq org-todo-keyword-alist-for-agenda
13341 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13342 (setq org-tag-alist-for-agenda
13343 (append org-tag-alist-for-agenda org-tag-alist))
13345 (save-excursion
13346 (remove-text-properties (point-min) (point-max) pall)
13347 (when org-agenda-skip-archived-trees
13348 (goto-char (point-min))
13349 (while (re-search-forward rea nil t)
13350 (if (org-on-heading-p t)
13351 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13352 (goto-char (point-min))
13353 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13354 (while (re-search-forward re nil t)
13355 (add-text-properties
13356 (match-beginning 0) (org-end-of-subtree t) pc)))
13357 (set-buffer-modified-p bmp)))))
13358 (setq org-todo-keyword-alist-for-agenda
13359 (org-uniquify org-todo-keyword-alist-for-agenda)
13360 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13362 ;;;; Embedded LaTeX
13364 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13365 "Keymap for the minor `org-cdlatex-mode'.")
13367 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13368 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13369 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13370 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13371 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13373 (defvar org-cdlatex-texmathp-advice-is-done nil
13374 "Flag remembering if we have applied the advice to texmathp already.")
13376 (define-minor-mode org-cdlatex-mode
13377 "Toggle the minor `org-cdlatex-mode'.
13378 This mode supports entering LaTeX environment and math in LaTeX fragments
13379 in Org-mode.
13380 \\{org-cdlatex-mode-map}"
13381 nil " OCDL" nil
13382 (when org-cdlatex-mode (require 'cdlatex))
13383 (unless org-cdlatex-texmathp-advice-is-done
13384 (setq org-cdlatex-texmathp-advice-is-done t)
13385 (defadvice texmathp (around org-math-always-on activate)
13386 "Always return t in org-mode buffers.
13387 This is because we want to insert math symbols without dollars even outside
13388 the LaTeX math segments. If Orgmode thinks that point is actually inside
13389 an embedded LaTeX fragment, let texmathp do its job.
13390 \\[org-cdlatex-mode-map]"
13391 (interactive)
13392 (let (p)
13393 (cond
13394 ((not (org-mode-p)) ad-do-it)
13395 ((eq this-command 'cdlatex-math-symbol)
13396 (setq ad-return-value t
13397 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13399 (let ((p (org-inside-LaTeX-fragment-p)))
13400 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13401 (setq ad-return-value t
13402 texmathp-why '("Org-mode embedded math" . 0))
13403 (if p ad-do-it)))))))))
13405 (defun turn-on-org-cdlatex ()
13406 "Unconditionally turn on `org-cdlatex-mode'."
13407 (org-cdlatex-mode 1))
13409 (defun org-inside-LaTeX-fragment-p ()
13410 "Test if point is inside a LaTeX fragment.
13411 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13412 sequence appearing also before point.
13413 Even though the matchers for math are configurable, this function assumes
13414 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13415 delimiters are skipped when they have been removed by customization.
13416 The return value is nil, or a cons cell with the delimiter and
13417 and the position of this delimiter.
13419 This function does a reasonably good job, but can locally be fooled by
13420 for example currency specifications. For example it will assume being in
13421 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13422 fragments that are properly closed, but during editing, we have to live
13423 with the uncertainty caused by missing closing delimiters. This function
13424 looks only before point, not after."
13425 (catch 'exit
13426 (let ((pos (point))
13427 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13428 (lim (progn
13429 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13430 (point)))
13431 dd-on str (start 0) m re)
13432 (goto-char pos)
13433 (when dodollar
13434 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13435 re (nth 1 (assoc "$" org-latex-regexps)))
13436 (while (string-match re str start)
13437 (cond
13438 ((= (match-end 0) (length str))
13439 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13440 ((= (match-end 0) (- (length str) 5))
13441 (throw 'exit nil))
13442 (t (setq start (match-end 0))))))
13443 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13444 (goto-char pos)
13445 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13446 (and (match-beginning 2) (throw 'exit nil))
13447 ;; count $$
13448 (while (re-search-backward "\\$\\$" lim t)
13449 (setq dd-on (not dd-on)))
13450 (goto-char pos)
13451 (if dd-on (cons "$$" m))))))
13454 (defun org-try-cdlatex-tab ()
13455 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13456 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13457 - inside a LaTeX fragment, or
13458 - after the first word in a line, where an abbreviation expansion could
13459 insert a LaTeX environment."
13460 (when org-cdlatex-mode
13461 (cond
13462 ((save-excursion
13463 (skip-chars-backward "a-zA-Z0-9*")
13464 (skip-chars-backward " \t")
13465 (bolp))
13466 (cdlatex-tab) t)
13467 ((org-inside-LaTeX-fragment-p)
13468 (cdlatex-tab) t)
13469 (t nil))))
13471 (defun org-cdlatex-underscore-caret (&optional arg)
13472 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13473 Revert to the normal definition outside of these fragments."
13474 (interactive "P")
13475 (if (org-inside-LaTeX-fragment-p)
13476 (call-interactively 'cdlatex-sub-superscript)
13477 (let (org-cdlatex-mode)
13478 (call-interactively (key-binding (vector last-input-event))))))
13480 (defun org-cdlatex-math-modify (&optional arg)
13481 "Execute `cdlatex-math-modify' in LaTeX fragments.
13482 Revert to the normal definition outside of these fragments."
13483 (interactive "P")
13484 (if (org-inside-LaTeX-fragment-p)
13485 (call-interactively 'cdlatex-math-modify)
13486 (let (org-cdlatex-mode)
13487 (call-interactively (key-binding (vector last-input-event))))))
13489 (defvar org-latex-fragment-image-overlays nil
13490 "List of overlays carrying the images of latex fragments.")
13491 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13493 (defun org-remove-latex-fragment-image-overlays ()
13494 "Remove all overlays with LaTeX fragment images in current buffer."
13495 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13496 (setq org-latex-fragment-image-overlays nil))
13498 (defun org-preview-latex-fragment (&optional subtree)
13499 "Preview the LaTeX fragment at point, or all locally or globally.
13500 If the cursor is in a LaTeX fragment, create the image and overlay
13501 it over the source code. If there is no fragment at point, display
13502 all fragments in the current text, from one headline to the next. With
13503 prefix SUBTREE, display all fragments in the current subtree. With a
13504 double prefix `C-u C-u', or when the cursor is before the first headline,
13505 display all fragments in the buffer.
13506 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13507 (interactive "P")
13508 (org-remove-latex-fragment-image-overlays)
13509 (save-excursion
13510 (save-restriction
13511 (let (beg end at msg)
13512 (cond
13513 ((or (equal subtree '(16))
13514 (not (save-excursion
13515 (re-search-backward (concat "^" outline-regexp) nil t))))
13516 (setq beg (point-min) end (point-max)
13517 msg "Creating images for buffer...%s"))
13518 ((equal subtree '(4))
13519 (org-back-to-heading)
13520 (setq beg (point) end (org-end-of-subtree t)
13521 msg "Creating images for subtree...%s"))
13523 (if (setq at (org-inside-LaTeX-fragment-p))
13524 (goto-char (max (point-min) (- (cdr at) 2)))
13525 (org-back-to-heading))
13526 (setq beg (point) end (progn (outline-next-heading) (point))
13527 msg (if at "Creating image...%s"
13528 "Creating images for entry...%s"))))
13529 (message msg "")
13530 (narrow-to-region beg end)
13531 (goto-char beg)
13532 (org-format-latex
13533 (concat "ltxpng/" (file-name-sans-extension
13534 (file-name-nondirectory
13535 buffer-file-name)))
13536 default-directory 'overlays msg at 'forbuffer)
13537 (message msg "done. Use `C-c C-c' to remove images.")))))
13539 (defvar org-latex-regexps
13540 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13541 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13542 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13543 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13544 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13545 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13546 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13547 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13548 "Regular expressions for matching embedded LaTeX.")
13550 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13551 "Replace LaTeX fragments with links to an image, and produce images."
13552 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13553 (let* ((prefixnodir (file-name-nondirectory prefix))
13554 (absprefix (expand-file-name prefix dir))
13555 (todir (file-name-directory absprefix))
13556 (opt org-format-latex-options)
13557 (matchers (plist-get opt :matchers))
13558 (re-list org-latex-regexps)
13559 (cnt 0) txt link beg end re e checkdir
13560 executables-checked
13561 m n block linkfile movefile ov)
13562 ;; Check if there are old images files with this prefix, and remove them
13563 (when (file-directory-p todir)
13564 (mapc 'delete-file
13565 (directory-files
13566 todir 'full
13567 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13568 ;; Check the different regular expressions
13569 (while (setq e (pop re-list))
13570 (setq m (car e) re (nth 1 e) n (nth 2 e)
13571 block (if (nth 3 e) "\n\n" ""))
13572 (when (member m matchers)
13573 (goto-char (point-min))
13574 (while (re-search-forward re nil t)
13575 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13576 (not (get-text-property (match-beginning n)
13577 'org-protected)))
13578 (setq txt (match-string n)
13579 beg (match-beginning n) end (match-end n)
13580 cnt (1+ cnt)
13581 linkfile (format "%s_%04d.png" prefix cnt)
13582 movefile (format "%s_%04d.png" absprefix cnt)
13583 link (concat block "[[file:" linkfile "]]" block))
13584 (if msg (message msg cnt))
13585 (goto-char beg)
13586 (unless checkdir ; make sure the directory exists
13587 (setq checkdir t)
13588 (or (file-directory-p todir) (make-directory todir)))
13590 (unless executables-checked
13591 (org-check-external-command
13592 "latex" "needed to convert LaTeX fragments to images")
13593 (org-check-external-command
13594 "dvipng" "needed to convert LaTeX fragments to images")
13595 (setq executables-checked t))
13597 (org-create-formula-image
13598 txt movefile opt forbuffer)
13599 (if overlays
13600 (progn
13601 (setq ov (org-make-overlay beg end))
13602 (if (featurep 'xemacs)
13603 (progn
13604 (org-overlay-put ov 'invisible t)
13605 (org-overlay-put
13606 ov 'end-glyph
13607 (make-glyph (vector 'png :file movefile))))
13608 (org-overlay-put
13609 ov 'display
13610 (list 'image :type 'png :file movefile :ascent 'center)))
13611 (push ov org-latex-fragment-image-overlays)
13612 (goto-char end))
13613 (delete-region beg end)
13614 (insert link))))))))
13616 ;; This function borrows from Ganesh Swami's latex2png.el
13617 (defun org-create-formula-image (string tofile options buffer)
13618 (let* ((tmpdir (if (featurep 'xemacs)
13619 (temp-directory)
13620 temporary-file-directory))
13621 (texfilebase (make-temp-name
13622 (expand-file-name "orgtex" tmpdir)))
13623 (texfile (concat texfilebase ".tex"))
13624 (dvifile (concat texfilebase ".dvi"))
13625 (pngfile (concat texfilebase ".png"))
13626 (fnh (if (featurep 'xemacs)
13627 (font-height (get-face-font 'default))
13628 (face-attribute 'default :height nil)))
13629 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13630 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13631 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13632 "Black"))
13633 (bg (or (plist-get options (if buffer :background :html-background))
13634 "Transparent")))
13635 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13636 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13637 (with-temp-file texfile
13638 (insert org-format-latex-header
13639 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13640 (let ((dir default-directory))
13641 (condition-case nil
13642 (progn
13643 (cd tmpdir)
13644 (call-process "latex" nil nil nil texfile))
13645 (error nil))
13646 (cd dir))
13647 (if (not (file-exists-p dvifile))
13648 (progn (message "Failed to create dvi file from %s" texfile) nil)
13649 (condition-case nil
13650 (call-process "dvipng" nil nil nil
13651 "-E" "-fg" fg "-bg" bg
13652 "-D" dpi
13653 ;;"-x" scale "-y" scale
13654 "-T" "tight"
13655 "-o" pngfile
13656 dvifile)
13657 (error nil))
13658 (if (not (file-exists-p pngfile))
13659 (progn (message "Failed to create png file from %s" texfile) nil)
13660 ;; Use the requested file name and clean up
13661 (copy-file pngfile tofile 'replace)
13662 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13663 (delete-file (concat texfilebase e)))
13664 pngfile))))
13666 (defun org-dvipng-color (attr)
13667 "Return an rgb color specification for dvipng."
13668 (apply 'format "rgb %s %s %s"
13669 (mapcar 'org-normalize-color
13670 (color-values (face-attribute 'default attr nil)))))
13672 (defun org-normalize-color (value)
13673 "Return string to be used as color value for an RGB component."
13674 (format "%g" (/ value 65535.0)))
13676 ;;;; Key bindings
13678 ;; Make `C-c C-x' a prefix key
13679 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13681 ;; TAB key with modifiers
13682 (org-defkey org-mode-map "\C-i" 'org-cycle)
13683 (org-defkey org-mode-map [(tab)] 'org-cycle)
13684 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13685 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13686 (org-defkey org-mode-map "\M-\t" 'org-complete)
13687 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13688 ;; The following line is necessary under Suse GNU/Linux
13689 (unless (featurep 'xemacs)
13690 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13691 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13692 (define-key org-mode-map [backtab] 'org-shifttab)
13694 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13695 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13696 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13698 ;; Cursor keys with modifiers
13699 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13700 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13701 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13702 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13704 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13705 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13706 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13707 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13709 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13710 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13711 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13712 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13714 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13715 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13717 ;;; Extra keys for tty access.
13718 ;; We only set them when really needed because otherwise the
13719 ;; menus don't show the simple keys
13721 (when (or org-use-extra-keys
13722 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13723 (not window-system))
13724 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13725 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13726 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13727 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13728 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13729 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13730 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13731 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13732 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13733 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13734 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13735 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13736 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13737 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13738 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13739 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13740 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13741 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13742 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13743 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13744 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13745 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13747 ;; All the other keys
13749 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13750 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13751 (if (boundp 'narrow-map)
13752 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13753 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13754 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13755 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13756 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13757 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13758 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13759 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13760 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13761 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13762 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13763 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13764 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13765 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13766 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13767 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13768 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13769 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13770 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13771 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13772 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13773 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13774 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13775 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13776 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13777 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13778 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13779 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13780 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13781 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13782 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13783 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13784 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13785 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13786 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13787 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13788 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13789 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13790 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13791 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13792 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13793 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13794 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13795 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13796 (org-defkey org-mode-map "\C-c^" 'org-sort)
13797 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13798 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13799 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13800 (org-defkey org-mode-map "\C-m" 'org-return)
13801 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13802 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13803 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13804 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13805 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13806 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13807 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13808 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13809 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13810 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13811 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13812 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13813 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13814 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13815 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13816 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13817 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13819 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13820 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13821 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13822 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13824 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13825 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13826 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13827 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13828 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13829 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13830 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13831 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13832 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13833 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13834 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13835 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13836 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13838 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13839 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13840 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13841 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13843 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13845 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
13847 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
13848 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
13850 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
13853 (when (featurep 'xemacs)
13854 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13857 (defvar org-self-insert-command-undo-counter 0)
13859 (defvar org-table-auto-blank-field) ; defined in org-table.el
13860 (defun org-self-insert-command (N)
13861 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13862 If the cursor is in a table looking at whitespace, the whitespace is
13863 overwritten, and the table is not marked as requiring realignment."
13864 (interactive "p")
13865 (if (and
13866 (org-table-p)
13867 (progn
13868 ;; check if we blank the field, and if that triggers align
13869 (and (featurep 'org-table) org-table-auto-blank-field
13870 (member last-command
13871 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13872 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13873 ;; got extra space, this field does not determine column width
13874 (let (org-table-may-need-update) (org-table-blank-field))
13875 ;; no extra space, this field may determine column width
13876 (org-table-blank-field)))
13878 (eq N 1)
13879 (looking-at "[^|\n]* |"))
13880 (let (org-table-may-need-update)
13881 (goto-char (1- (match-end 0)))
13882 (delete-backward-char 1)
13883 (goto-char (match-beginning 0))
13884 (self-insert-command N))
13885 (setq org-table-may-need-update t)
13886 (self-insert-command N)
13887 (org-fix-tags-on-the-fly)
13888 (if org-self-insert-cluster-for-undo
13889 (if (not (eq last-command 'org-self-insert-command))
13890 (setq org-self-insert-command-undo-counter 1)
13891 (if (>= org-self-insert-command-undo-counter 20)
13892 (setq org-self-insert-command-undo-counter 1)
13893 (and (> org-self-insert-command-undo-counter 0)
13894 buffer-undo-list
13895 (not (cadr buffer-undo-list)) ; remove nil entry
13896 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13897 (setq org-self-insert-command-undo-counter
13898 (1+ org-self-insert-command-undo-counter)))))))
13900 (defun org-fix-tags-on-the-fly ()
13901 (when (and (equal (char-after (point-at-bol)) ?*)
13902 (org-on-heading-p))
13903 (org-align-tags-here org-tags-column)))
13905 (defun org-delete-backward-char (N)
13906 "Like `delete-backward-char', insert whitespace at field end in tables.
13907 When deleting backwards, in tables this function will insert whitespace in
13908 front of the next \"|\" separator, to keep the table aligned. The table will
13909 still be marked for re-alignment if the field did fill the entire column,
13910 because, in this case the deletion might narrow the column."
13911 (interactive "p")
13912 (if (and (org-table-p)
13913 (eq N 1)
13914 (string-match "|" (buffer-substring (point-at-bol) (point)))
13915 (looking-at ".*?|"))
13916 (let ((pos (point))
13917 (noalign (looking-at "[^|\n\r]* |"))
13918 (c org-table-may-need-update))
13919 (backward-delete-char N)
13920 (skip-chars-forward "^|")
13921 (insert " ")
13922 (goto-char (1- pos))
13923 ;; noalign: if there were two spaces at the end, this field
13924 ;; does not determine the width of the column.
13925 (if noalign (setq org-table-may-need-update c)))
13926 (backward-delete-char N)
13927 (org-fix-tags-on-the-fly)))
13929 (defun org-delete-char (N)
13930 "Like `delete-char', but insert whitespace at field end in tables.
13931 When deleting characters, in tables this function will insert whitespace in
13932 front of the next \"|\" separator, to keep the table aligned. The table will
13933 still be marked for re-alignment if the field did fill the entire column,
13934 because, in this case the deletion might narrow the column."
13935 (interactive "p")
13936 (if (and (org-table-p)
13937 (not (bolp))
13938 (not (= (char-after) ?|))
13939 (eq N 1))
13940 (if (looking-at ".*?|")
13941 (let ((pos (point))
13942 (noalign (looking-at "[^|\n\r]* |"))
13943 (c org-table-may-need-update))
13944 (replace-match (concat
13945 (substring (match-string 0) 1 -1)
13946 " |"))
13947 (goto-char pos)
13948 ;; noalign: if there were two spaces at the end, this field
13949 ;; does not determine the width of the column.
13950 (if noalign (setq org-table-may-need-update c)))
13951 (delete-char N))
13952 (delete-char N)
13953 (org-fix-tags-on-the-fly)))
13955 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13956 (put 'org-self-insert-command 'delete-selection t)
13957 (put 'orgtbl-self-insert-command 'delete-selection t)
13958 (put 'org-delete-char 'delete-selection 'supersede)
13959 (put 'org-delete-backward-char 'delete-selection 'supersede)
13960 (put 'org-yank 'delete-selection 'yank)
13962 ;; Make `flyspell-mode' delay after some commands
13963 (put 'org-self-insert-command 'flyspell-delayed t)
13964 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13965 (put 'org-delete-char 'flyspell-delayed t)
13966 (put 'org-delete-backward-char 'flyspell-delayed t)
13968 ;; Make pabbrev-mode expand after org-mode commands
13969 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13970 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13972 ;; How to do this: Measure non-white length of current string
13973 ;; If equal to column width, we should realign.
13975 (defun org-remap (map &rest commands)
13976 "In MAP, remap the functions given in COMMANDS.
13977 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13978 (let (new old)
13979 (while commands
13980 (setq old (pop commands) new (pop commands))
13981 (if (fboundp 'command-remapping)
13982 (org-defkey map (vector 'remap old) new)
13983 (substitute-key-definition old new map global-map)))))
13985 (when (eq org-enable-table-editor 'optimized)
13986 ;; If the user wants maximum table support, we need to hijack
13987 ;; some standard editing functions
13988 (org-remap org-mode-map
13989 'self-insert-command 'org-self-insert-command
13990 'delete-char 'org-delete-char
13991 'delete-backward-char 'org-delete-backward-char)
13992 (org-defkey org-mode-map "|" 'org-force-self-insert))
13994 (defvar org-ctrl-c-ctrl-c-hook nil
13995 "Hook for functions attaching themselves to `C-c C-c'.
13996 This can be used to add additional functionality to the C-c C-c key which
13997 executes context-dependent commands.
13998 Each function will be called with no arguments. The function must check
13999 if the context is appropriate for it to act. If yes, it should do its
14000 thing and then return a non-nil value. If the context is wrong,
14001 just do nothing and return nil.")
14003 (defvar org-tab-first-hook nil
14004 "Hook for functions to attach themselves to TAB.
14005 See `org-ctrl-c-ctrl-c-hook' for more information.
14006 This hook runs as the first action when TAB is pressed, even before
14007 `org-cycle' messes around with the `outline-regexp' to cater for
14008 inline tasks and plain list item folding.
14009 If any function in this hook returns t, not other actions like table
14010 field motion visibility cycling will be done.")
14012 (defvar org-tab-after-check-for-table-hook nil
14013 "Hook for functions to attach themselves to TAB.
14014 See `org-ctrl-c-ctrl-c-hook' for more information.
14015 This hook runs after it has been established that the cursor is not in a
14016 table, but before checking if the cursor is in a headline or if global cycling
14017 should be done.
14018 If any function in this hook returns t, not other actions like visibility
14019 cycling will be done.")
14021 (defvar org-tab-after-check-for-cycling-hook nil
14022 "Hook for functions to attach themselves to TAB.
14023 See `org-ctrl-c-ctrl-c-hook' for more information.
14024 This hook runs after it has been established that not table field motion and
14025 not visibility should be done because of current context. This is probably
14026 the place where a package like yasnippets can hook in.")
14028 (defvar org-metaleft-hook nil
14029 "Hook for functions attaching themselves to `M-left'.
14030 See `org-ctrl-c-ctrl-c-hook' for more information.")
14031 (defvar org-metaright-hook nil
14032 "Hook for functions attaching themselves to `M-right'.
14033 See `org-ctrl-c-ctrl-c-hook' for more information.")
14034 (defvar org-metaup-hook nil
14035 "Hook for functions attaching themselves to `M-up'.
14036 See `org-ctrl-c-ctrl-c-hook' for more information.")
14037 (defvar org-metadown-hook nil
14038 "Hook for functions attaching themselves to `M-down'.
14039 See `org-ctrl-c-ctrl-c-hook' for more information.")
14040 (defvar org-shiftmetaleft-hook nil
14041 "Hook for functions attaching themselves to `M-S-left'.
14042 See `org-ctrl-c-ctrl-c-hook' for more information.")
14043 (defvar org-shiftmetaright-hook nil
14044 "Hook for functions attaching themselves to `M-S-right'.
14045 See `org-ctrl-c-ctrl-c-hook' for more information.")
14046 (defvar org-shiftmetaup-hook nil
14047 "Hook for functions attaching themselves to `M-S-up'.
14048 See `org-ctrl-c-ctrl-c-hook' for more information.")
14049 (defvar org-shiftmetadown-hook nil
14050 "Hook for functions attaching themselves to `M-S-down'.
14051 See `org-ctrl-c-ctrl-c-hook' for more information.")
14052 (defvar org-metareturn-hook nil
14053 "Hook for functions attaching themselves to `M-RET'.
14054 See `org-ctrl-c-ctrl-c-hook' for more information.")
14056 (defun org-modifier-cursor-error ()
14057 "Throw an error, a modified cursor command was applied in wrong context."
14058 (error "This command is active in special context like tables, headlines or items"))
14060 (defun org-shiftselect-error ()
14061 "Throw an error because Shift-Cursor command was applied in wrong context."
14062 (if (and (boundp 'shift-select-mode) shift-select-mode)
14063 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14064 (error "This command works only in special context like headlines or timestamps.")))
14066 (defun org-call-for-shift-select (cmd)
14067 (let ((this-command-keys-shift-translated t))
14068 (call-interactively cmd)))
14070 (defun org-shifttab (&optional arg)
14071 "Global visibility cycling or move to previous table field.
14072 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14073 on context.
14074 See the individual commands for more information."
14075 (interactive "P")
14076 (cond
14077 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14078 ((integerp arg)
14079 (message "Content view to level: %d" arg)
14080 (org-content (prefix-numeric-value arg))
14081 (setq org-cycle-global-status 'overview))
14082 (t (call-interactively 'org-global-cycle))))
14084 (defun org-shiftmetaleft ()
14085 "Promote subtree or delete table column.
14086 Calls `org-promote-subtree', `org-outdent-item',
14087 or `org-table-delete-column', depending on context.
14088 See the individual commands for more information."
14089 (interactive)
14090 (cond
14091 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14092 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14093 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14094 ((org-at-item-p) (call-interactively 'org-outdent-item))
14095 (t (org-modifier-cursor-error))))
14097 (defun org-shiftmetaright ()
14098 "Demote subtree or insert table column.
14099 Calls `org-demote-subtree', `org-indent-item',
14100 or `org-table-insert-column', depending on context.
14101 See the individual commands for more information."
14102 (interactive)
14103 (cond
14104 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14105 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14106 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14107 ((org-at-item-p) (call-interactively 'org-indent-item))
14108 (t (org-modifier-cursor-error))))
14110 (defun org-shiftmetaup (&optional arg)
14111 "Move subtree up or kill table row.
14112 Calls `org-move-subtree-up' or `org-table-kill-row' or
14113 `org-move-item-up' depending on context. See the individual commands
14114 for more information."
14115 (interactive "P")
14116 (cond
14117 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14118 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14119 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14120 ((org-at-item-p) (call-interactively 'org-move-item-up))
14121 (t (org-modifier-cursor-error))))
14123 (defun org-shiftmetadown (&optional arg)
14124 "Move subtree down or insert table row.
14125 Calls `org-move-subtree-down' or `org-table-insert-row' or
14126 `org-move-item-down', depending on context. See the individual
14127 commands for more information."
14128 (interactive "P")
14129 (cond
14130 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14131 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14132 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14133 ((org-at-item-p) (call-interactively 'org-move-item-down))
14134 (t (org-modifier-cursor-error))))
14136 (defun org-metaleft (&optional arg)
14137 "Promote heading or move table column to left.
14138 Calls `org-do-promote' or `org-table-move-column', depending on context.
14139 With no specific context, calls the Emacs default `backward-word'.
14140 See the individual commands for more information."
14141 (interactive "P")
14142 (cond
14143 ((run-hook-with-args-until-success 'org-metaleft-hook))
14144 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14145 ((or (org-on-heading-p)
14146 (and (org-region-active-p)
14147 (save-excursion
14148 (goto-char (region-beginning))
14149 (org-on-heading-p))))
14150 (call-interactively 'org-do-promote))
14151 ((or (org-at-item-p)
14152 (and (org-region-active-p)
14153 (save-excursion
14154 (goto-char (region-beginning))
14155 (org-at-item-p))))
14156 (call-interactively 'org-outdent-item))
14157 (t (call-interactively 'backward-word))))
14159 (defun org-metaright (&optional arg)
14160 "Demote subtree or move table column to right.
14161 Calls `org-do-demote' or `org-table-move-column', depending on context.
14162 With no specific context, calls the Emacs default `forward-word'.
14163 See the individual commands for more information."
14164 (interactive "P")
14165 (cond
14166 ((run-hook-with-args-until-success 'org-metaright-hook))
14167 ((org-at-table-p) (call-interactively 'org-table-move-column))
14168 ((or (org-on-heading-p)
14169 (and (org-region-active-p)
14170 (save-excursion
14171 (goto-char (region-beginning))
14172 (org-on-heading-p))))
14173 (call-interactively 'org-do-demote))
14174 ((or (org-at-item-p)
14175 (and (org-region-active-p)
14176 (save-excursion
14177 (goto-char (region-beginning))
14178 (org-at-item-p))))
14179 (call-interactively 'org-indent-item))
14180 (t (call-interactively 'forward-word))))
14182 (defun org-metaup (&optional arg)
14183 "Move subtree up or move table row up.
14184 Calls `org-move-subtree-up' or `org-table-move-row' or
14185 `org-move-item-up', depending on context. See the individual commands
14186 for more information."
14187 (interactive "P")
14188 (cond
14189 ((run-hook-with-args-until-success 'org-metaup-hook))
14190 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14191 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14192 ((org-at-item-p) (call-interactively 'org-move-item-up))
14193 (t (transpose-lines 1) (beginning-of-line -1))))
14195 (defun org-metadown (&optional arg)
14196 "Move subtree down or move table row down.
14197 Calls `org-move-subtree-down' or `org-table-move-row' or
14198 `org-move-item-down', depending on context. See the individual
14199 commands for more information."
14200 (interactive "P")
14201 (cond
14202 ((run-hook-with-args-until-success 'org-metadown-hook))
14203 ((org-at-table-p) (call-interactively 'org-table-move-row))
14204 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14205 ((org-at-item-p) (call-interactively 'org-move-item-down))
14206 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14208 (defun org-shiftup (&optional arg)
14209 "Increase item in timestamp or increase priority of current headline.
14210 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14211 depending on context. See the individual commands for more information."
14212 (interactive "P")
14213 (cond
14214 ((and org-support-shift-select (org-region-active-p))
14215 (org-call-for-shift-select 'previous-line))
14216 ((org-at-timestamp-p t)
14217 (call-interactively (if org-edit-timestamp-down-means-later
14218 'org-timestamp-down 'org-timestamp-up)))
14219 ((and (not (eq org-support-shift-select 'always))
14220 (org-on-heading-p))
14221 (call-interactively 'org-priority-up))
14222 ((and (not org-support-shift-select) (org-at-item-p))
14223 (call-interactively 'org-previous-item))
14224 ((org-clocktable-try-shift 'up arg))
14225 (org-support-shift-select
14226 (org-call-for-shift-select 'previous-line))
14227 (t (org-shiftselect-error))))
14229 (defun org-shiftdown (&optional arg)
14230 "Decrease item in timestamp or decrease priority of current headline.
14231 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14232 depending on context. See the individual commands for more information."
14233 (interactive "P")
14234 (cond
14235 ((and org-support-shift-select (org-region-active-p))
14236 (org-call-for-shift-select 'next-line))
14237 ((org-at-timestamp-p t)
14238 (call-interactively (if org-edit-timestamp-down-means-later
14239 'org-timestamp-up 'org-timestamp-down)))
14240 ((and (not (eq org-support-shift-select 'always))
14241 (org-on-heading-p))
14242 (call-interactively 'org-priority-down))
14243 ((and (not org-support-shift-select) (org-at-item-p))
14244 (call-interactively 'org-next-item))
14245 ((org-clocktable-try-shift 'down arg))
14246 (org-support-shift-select
14247 (org-call-for-shift-select 'next-line))
14248 (t (org-shiftselect-error))))
14250 (defun org-shiftright (&optional arg)
14251 "Cycle the thing at point or in the current line, depending on context.
14252 Depending on context, this does one of the following:
14254 - switch a timestamp at point one day into the future
14255 - on a headline, switch to the next TODO keyword.
14256 - on an item, switch entire list to the next bullet type
14257 - on a property line, switch to the next allowed value
14258 - on a clocktable definition line, move time block into the future"
14259 (interactive "P")
14260 (cond
14261 ((and org-support-shift-select (org-region-active-p))
14262 (org-call-for-shift-select 'forward-char))
14263 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14264 ((and (not (eq org-support-shift-select 'always))
14265 (org-on-heading-p))
14266 (org-call-with-arg 'org-todo 'right))
14267 ((or (and org-support-shift-select
14268 (not (eq org-support-shift-select 'always))
14269 (org-at-item-bullet-p))
14270 (and (not org-support-shift-select) (org-at-item-p)))
14271 (org-call-with-arg 'org-cycle-list-bullet nil))
14272 ((and (not (eq org-support-shift-select 'always))
14273 (org-at-property-p))
14274 (call-interactively 'org-property-next-allowed-value))
14275 ((org-clocktable-try-shift 'right arg))
14276 (org-support-shift-select
14277 (org-call-for-shift-select 'forward-char))
14278 (t (org-shiftselect-error))))
14280 (defun org-shiftleft (&optional arg)
14281 "Cycle the thing at point or in the current line, depending on context.
14282 Depending on context, this does one of the following:
14284 - switch a timestamp at point one day into the past
14285 - on a headline, switch to the previous TODO keyword.
14286 - on an item, switch entire list to the previous bullet type
14287 - on a property line, switch to the previous allowed value
14288 - on a clocktable definition line, move time block into the past"
14289 (interactive "P")
14290 (cond
14291 ((and org-support-shift-select (org-region-active-p))
14292 (org-call-for-shift-select 'backward-char))
14293 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14294 ((and (not (eq org-support-shift-select 'always))
14295 (org-on-heading-p))
14296 (org-call-with-arg 'org-todo 'left))
14297 ((or (and org-support-shift-select
14298 (not (eq org-support-shift-select 'always))
14299 (org-at-item-bullet-p))
14300 (and (not org-support-shift-select) (org-at-item-p)))
14301 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14302 ((and (not (eq org-support-shift-select 'always))
14303 (org-at-property-p))
14304 (call-interactively 'org-property-previous-allowed-value))
14305 ((org-clocktable-try-shift 'left arg))
14306 (org-support-shift-select
14307 (org-call-for-shift-select 'backward-char))
14308 (t (org-shiftselect-error))))
14310 (defun org-shiftcontrolright ()
14311 "Switch to next TODO set."
14312 (interactive)
14313 (cond
14314 ((and org-support-shift-select (org-region-active-p))
14315 (org-call-for-shift-select 'forward-word))
14316 ((and (not (eq org-support-shift-select 'always))
14317 (org-on-heading-p))
14318 (org-call-with-arg 'org-todo 'nextset))
14319 (org-support-shift-select
14320 (org-call-for-shift-select 'forward-word))
14321 (t (org-shiftselect-error))))
14323 (defun org-shiftcontrolleft ()
14324 "Switch to previous TODO set."
14325 (interactive)
14326 (cond
14327 ((and org-support-shift-select (org-region-active-p))
14328 (org-call-for-shift-select 'backward-word))
14329 ((and (not (eq org-support-shift-select 'always))
14330 (org-on-heading-p))
14331 (org-call-with-arg 'org-todo 'previousset))
14332 (org-support-shift-select
14333 (org-call-for-shift-select 'backward-word))
14334 (t (org-shiftselect-error))))
14336 (defun org-ctrl-c-ret ()
14337 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14338 (interactive)
14339 (cond
14340 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14341 (t (call-interactively 'org-insert-heading))))
14343 (defun org-copy-special ()
14344 "Copy region in table or copy current subtree.
14345 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14346 See the individual commands for more information."
14347 (interactive)
14348 (call-interactively
14349 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14351 (defun org-cut-special ()
14352 "Cut region in table or cut current subtree.
14353 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14354 See the individual commands for more information."
14355 (interactive)
14356 (call-interactively
14357 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14359 (defun org-paste-special (arg)
14360 "Paste rectangular region into table, or past subtree relative to level.
14361 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14362 See the individual commands for more information."
14363 (interactive "P")
14364 (if (org-at-table-p)
14365 (org-table-paste-rectangle)
14366 (org-paste-subtree arg)))
14368 (defun org-edit-special ()
14369 "Call a special editor for the stuff at point.
14370 When at a table, call the formula editor with `org-table-edit-formulas'.
14371 When at the first line of an src example, call `org-edit-src-code'.
14372 When in an #+include line, visit the include file. Otherwise call
14373 `ffap' to visit the file at point."
14374 (interactive)
14375 (cond
14376 ((org-at-table-p)
14377 (call-interactively 'org-table-edit-formulas))
14378 ((save-excursion
14379 (beginning-of-line 1)
14380 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14381 (find-file (org-trim (match-string 1))))
14382 ((org-edit-src-code))
14383 ((org-edit-fixed-width-region))
14384 (t (call-interactively 'ffap))))
14387 (defun org-ctrl-c-ctrl-c (&optional arg)
14388 "Set tags in headline, or update according to changed information at point.
14390 This command does many different things, depending on context:
14392 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14393 this is what we do.
14395 - If the cursor is in a headline, prompt for tags and insert them
14396 into the current line, aligned to `org-tags-column'. When called
14397 with prefix arg, realign all tags in the current buffer.
14399 - If the cursor is in one of the special #+KEYWORD lines, this
14400 triggers scanning the buffer for these lines and updating the
14401 information.
14403 - If the cursor is inside a table, realign the table. This command
14404 works even if the automatic table editor has been turned off.
14406 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14407 the entire table.
14409 - If the cursor is at a footnote reference or definition, jump to
14410 the corresponding definition or references, respectively.
14412 - If the cursor is a the beginning of a dynamic block, update it.
14414 - If the cursor is inside a table created by the table.el package,
14415 activate that table.
14417 - If the current buffer is a remember buffer, close note and file
14418 it. A prefix argument of 1 files to the default location
14419 without further interaction. A prefix argument of 2 files to
14420 the currently clocking task.
14422 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14423 links in this buffer.
14425 - If the cursor is on a numbered item in a plain list, renumber the
14426 ordered list.
14428 - If the cursor is on a checkbox, toggle it."
14429 (interactive "P")
14430 (let ((org-enable-table-editor t))
14431 (cond
14432 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14433 org-occur-highlights
14434 org-latex-fragment-image-overlays)
14435 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14436 (org-remove-occur-highlights)
14437 (org-remove-latex-fragment-image-overlays)
14438 (message "Temporary highlights/overlays removed from current buffer"))
14439 ((and (local-variable-p 'org-finish-function (current-buffer))
14440 (fboundp org-finish-function))
14441 (funcall org-finish-function))
14442 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14443 ((org-at-property-p)
14444 (call-interactively 'org-property-action))
14445 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14446 ((org-on-heading-p) (call-interactively 'org-set-tags))
14447 ((org-at-table.el-p)
14448 (require 'table)
14449 (beginning-of-line 1)
14450 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14451 (call-interactively 'table-recognize-table))
14452 ((org-at-table-p)
14453 (org-table-maybe-eval-formula)
14454 (if arg
14455 (call-interactively 'org-table-recalculate)
14456 (org-table-maybe-recalculate-line))
14457 (call-interactively 'org-table-align))
14458 ((or (org-footnote-at-reference-p)
14459 (org-footnote-at-definition-p))
14460 (call-interactively 'org-footnote-action))
14461 ((org-at-item-checkbox-p)
14462 (call-interactively 'org-toggle-checkbox))
14463 ((org-at-item-p)
14464 (if arg
14465 (call-interactively 'org-toggle-checkbox)
14466 (call-interactively 'org-maybe-renumber-ordered-list)))
14467 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14468 ;; Dynamic block
14469 (beginning-of-line 1)
14470 (save-excursion (org-update-dblock)))
14471 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14472 (cond
14473 ((equal (match-string 1) "TBLFM")
14474 ;; Recalculate the table before this line
14475 (save-excursion
14476 (beginning-of-line 1)
14477 (skip-chars-backward " \r\n\t")
14478 (if (org-at-table-p)
14479 (org-call-with-arg 'org-table-recalculate t))))
14481 ; (org-set-regexps-and-options)
14482 ; (org-restart-font-lock)
14483 (let ((org-inhibit-startup t)) (org-mode-restart))
14484 (message "Local setup has been refreshed"))))
14485 (t (error "C-c C-c can do nothing useful at this location.")))))
14487 (defun org-mode-restart ()
14488 "Restart Org-mode, to scan again for special lines.
14489 Also updates the keyword regular expressions."
14490 (interactive)
14491 (org-mode)
14492 (message "Org-mode restarted"))
14494 (defun org-kill-note-or-show-branches ()
14495 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14496 (interactive)
14497 (if (not org-finish-function)
14498 (call-interactively 'show-branches)
14499 (let ((org-note-abort t))
14500 (funcall org-finish-function))))
14502 (defun org-return (&optional indent)
14503 "Goto next table row or insert a newline.
14504 Calls `org-table-next-row' or `newline', depending on context.
14505 See the individual commands for more information."
14506 (interactive)
14507 (cond
14508 ((bobp) (if indent (newline-and-indent) (newline)))
14509 ((org-at-table-p)
14510 (org-table-justify-field-maybe)
14511 (call-interactively 'org-table-next-row))
14512 ((and org-return-follows-link
14513 (eq (get-text-property (point) 'face) 'org-link))
14514 (call-interactively 'org-open-at-point))
14515 ((and (org-at-heading-p)
14516 (looking-at
14517 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14518 (org-show-entry)
14519 (end-of-line 1)
14520 (newline))
14521 (t (if indent (newline-and-indent) (newline)))))
14523 (defun org-return-indent ()
14524 "Goto next table row or insert a newline and indent.
14525 Calls `org-table-next-row' or `newline-and-indent', depending on
14526 context. See the individual commands for more information."
14527 (interactive)
14528 (org-return t))
14530 (defun org-ctrl-c-star ()
14531 "Compute table, or change heading status of lines.
14532 Calls `org-table-recalculate' or `org-toggle-heading',
14533 depending on context."
14534 (interactive)
14535 (cond
14536 ((org-at-table-p)
14537 (call-interactively 'org-table-recalculate))
14539 ;; Convert all lines in region to list items
14540 (call-interactively 'org-toggle-heading))))
14542 (defun org-ctrl-c-minus ()
14543 "Insert separator line in table or modify bullet status of line.
14544 Also turns a plain line or a region of lines into list items.
14545 Calls `org-table-insert-hline', `org-toggle-item', or
14546 `org-cycle-list-bullet', depending on context."
14547 (interactive)
14548 (cond
14549 ((org-at-table-p)
14550 (call-interactively 'org-table-insert-hline))
14551 ((org-region-active-p)
14552 (call-interactively 'org-toggle-item))
14553 ((org-in-item-p)
14554 (call-interactively 'org-cycle-list-bullet))
14556 (call-interactively 'org-toggle-item))))
14558 (defun org-toggle-item ()
14559 "Convert headings or normal lines to items, items to normal lines.
14560 If there is no active region, only the current line is considered.
14562 If the first line in the region is a headline, convert all headlines to items.
14564 If the first line in the region is an item, convert all items to normal lines.
14566 If the first line is normal text, add an item bullet to each line."
14567 (interactive)
14568 (let (l2 l beg end)
14569 (if (org-region-active-p)
14570 (setq beg (region-beginning) end (region-end))
14571 (setq beg (point-at-bol)
14572 end (min (1+ (point-at-eol)) (point-max))))
14573 (save-excursion
14574 (goto-char end)
14575 (setq l2 (org-current-line))
14576 (goto-char beg)
14577 (beginning-of-line 1)
14578 (setq l (1- (org-current-line)))
14579 (if (org-at-item-p)
14580 ;; We already have items, de-itemize
14581 (while (< (setq l (1+ l)) l2)
14582 (when (org-at-item-p)
14583 (goto-char (match-beginning 2))
14584 (delete-region (match-beginning 2) (match-end 2))
14585 (and (looking-at "[ \t]+") (replace-match "")))
14586 (beginning-of-line 2))
14587 (if (org-on-heading-p)
14588 ;; Headings, convert to items
14589 (while (< (setq l (1+ l)) l2)
14590 (if (looking-at org-outline-regexp)
14591 (replace-match "- " t t))
14592 (beginning-of-line 2))
14593 ;; normal lines, turn them into items
14594 (while (< (setq l (1+ l)) l2)
14595 (unless (org-at-item-p)
14596 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14597 (replace-match "\\1- \\2")))
14598 (beginning-of-line 2)))))))
14600 (defun org-toggle-heading (&optional nstars)
14601 "Convert headings to normal text, or items or text to headings.
14602 If there is no active region, only the current line is considered.
14604 If the first line is a heading, remove the stars from all headlines
14605 in the region.
14607 If the first line is a plain list item, turn all plain list items into
14608 headings.
14610 If the first line is a normal line, turn each and every line in the region
14611 into a heading.
14613 When converting a line into a heading, the number of stars is chosen
14614 such that the lines become children of the current entry. However, when
14615 a prefix argument is given, its value determines the number of stars to add."
14616 (interactive "P")
14617 (let (l2 l itemp beg end)
14618 (if (org-region-active-p)
14619 (setq beg (region-beginning) end (region-end))
14620 (setq beg (point-at-bol)
14621 end (min (1+ (point-at-eol)) (point-max))))
14622 (save-excursion
14623 (goto-char end)
14624 (setq l2 (org-current-line))
14625 (goto-char beg)
14626 (beginning-of-line 1)
14627 (setq l (1- (org-current-line)))
14628 (if (org-on-heading-p)
14629 ;; We already have headlines, de-star them
14630 (while (< (setq l (1+ l)) l2)
14631 (when (org-on-heading-p t)
14632 (and (looking-at outline-regexp) (replace-match "")))
14633 (beginning-of-line 2))
14634 (setq itemp (org-at-item-p))
14635 (let* ((stars
14636 (if nstars
14637 (make-string (prefix-numeric-value current-prefix-arg)
14639 (save-excursion
14640 (re-search-backward org-complex-heading-regexp nil t)
14641 (or (match-string 1) ""))))
14642 (add-stars (cond (nstars "")
14643 ((equal stars "") "*")
14644 (org-odd-levels-only "**")
14645 (t "*")))
14646 (rpl (concat stars add-stars " ")))
14647 (while (< (setq l (1+ l)) l2)
14648 (if itemp
14649 (and (org-at-item-p) (replace-match rpl t t))
14650 (unless (org-on-heading-p)
14651 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14652 (replace-match (concat rpl (match-string 2))))))
14653 (beginning-of-line 2)))))))
14655 (defun org-meta-return (&optional arg)
14656 "Insert a new heading or wrap a region in a table.
14657 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14658 See the individual commands for more information."
14659 (interactive "P")
14660 (cond
14661 ((run-hook-with-args-until-success 'org-metareturn-hook))
14662 ((org-at-table-p)
14663 (call-interactively 'org-table-wrap-region))
14664 (t (call-interactively 'org-insert-heading))))
14666 ;;; Menu entries
14668 ;; Define the Org-mode menus
14669 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14670 '("Tbl"
14671 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14672 ["Next Field" org-cycle (org-at-table-p)]
14673 ["Previous Field" org-shifttab (org-at-table-p)]
14674 ["Next Row" org-return (org-at-table-p)]
14675 "--"
14676 ["Blank Field" org-table-blank-field (org-at-table-p)]
14677 ["Edit Field" org-table-edit-field (org-at-table-p)]
14678 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14679 "--"
14680 ("Column"
14681 ["Move Column Left" org-metaleft (org-at-table-p)]
14682 ["Move Column Right" org-metaright (org-at-table-p)]
14683 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14684 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14685 ("Row"
14686 ["Move Row Up" org-metaup (org-at-table-p)]
14687 ["Move Row Down" org-metadown (org-at-table-p)]
14688 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14689 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14690 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14691 "--"
14692 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14693 ("Rectangle"
14694 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14695 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14696 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14697 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14698 "--"
14699 ("Calculate"
14700 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14701 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14702 ["Edit Formulas" org-edit-special (org-at-table-p)]
14703 "--"
14704 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14705 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14706 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14707 "--"
14708 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14709 "--"
14710 ["Sum Column/Rectangle" org-table-sum
14711 (or (org-at-table-p) (org-region-active-p))]
14712 ["Which Column?" org-table-current-column (org-at-table-p)])
14713 ["Debug Formulas"
14714 org-table-toggle-formula-debugger
14715 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14716 ["Show Col/Row Numbers"
14717 org-table-toggle-coordinate-overlays
14718 :style toggle
14719 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14720 "--"
14721 ["Create" org-table-create (and (not (org-at-table-p))
14722 org-enable-table-editor)]
14723 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14724 ["Import from File" org-table-import (not (org-at-table-p))]
14725 ["Export to File" org-table-export (org-at-table-p)]
14726 "--"
14727 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14729 (easy-menu-define org-org-menu org-mode-map "Org menu"
14730 '("Org"
14731 ("Show/Hide"
14732 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14733 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14734 ["Sparse Tree..." org-sparse-tree t]
14735 ["Reveal Context" org-reveal t]
14736 ["Show All" show-all t]
14737 "--"
14738 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14739 "--"
14740 ["New Heading" org-insert-heading t]
14741 ("Navigate Headings"
14742 ["Up" outline-up-heading t]
14743 ["Next" outline-next-visible-heading t]
14744 ["Previous" outline-previous-visible-heading t]
14745 ["Next Same Level" outline-forward-same-level t]
14746 ["Previous Same Level" outline-backward-same-level t]
14747 "--"
14748 ["Jump" org-goto t])
14749 ("Edit Structure"
14750 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14751 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14752 "--"
14753 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14754 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14755 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14756 "--"
14757 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14758 "--"
14759 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14760 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14761 ["Demote Heading" org-metaright (not (org-at-table-p))]
14762 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14763 "--"
14764 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14765 "--"
14766 ["Convert to odd levels" org-convert-to-odd-levels t]
14767 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14768 ("Editing"
14769 ["Emphasis..." org-emphasize t]
14770 ["Edit Source Example" org-edit-special t]
14771 "--"
14772 ["Footnote new/jump" org-footnote-action t]
14773 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14774 ("Archive"
14775 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14776 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14777 ; :active t :keys "C-u C-c C-x C-a"]
14778 ["Sparse trees open ARCHIVE trees"
14779 (setq org-sparse-tree-open-archived-trees
14780 (not org-sparse-tree-open-archived-trees))
14781 :style toggle :selected org-sparse-tree-open-archived-trees]
14782 ["Cycling opens ARCHIVE trees"
14783 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14784 :style toggle :selected org-cycle-open-archived-trees]
14785 "--"
14786 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14787 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14788 ; ["Check and Move Children" (org-archive-subtree '(4))
14789 ; :active t :keys "C-u C-c C-x C-s"]
14791 "--"
14792 ("Hyperlinks"
14793 ["Store Link (Global)" org-store-link t]
14794 ["Insert Link" org-insert-link t]
14795 ["Follow Link" org-open-at-point t]
14796 "--"
14797 ["Next link" org-next-link t]
14798 ["Previous link" org-previous-link t]
14799 "--"
14800 ["Descriptive Links"
14801 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14802 :style radio
14803 :selected (member '(org-link) buffer-invisibility-spec)]
14804 ["Literal Links"
14805 (progn
14806 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14807 :style radio
14808 :selected (not (member '(org-link) buffer-invisibility-spec))])
14809 "--"
14810 ("TODO Lists"
14811 ["TODO/DONE/-" org-todo t]
14812 ("Select keyword"
14813 ["Next keyword" org-shiftright (org-on-heading-p)]
14814 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14815 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14816 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14817 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14818 ["Show TODO Tree" org-show-todo-tree t]
14819 ["Global TODO list" org-todo-list t]
14820 "--"
14821 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14822 :selected org-enforce-todo-dependencies :style toggle :active t]
14823 "Settings for tree at point"
14824 ["Do Children sequentially" org-toggle-ordered-property :style radio
14825 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14826 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14827 ["Do Children parallel" org-toggle-ordered-property :style radio
14828 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14829 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14830 "--"
14831 ["Set Priority" org-priority t]
14832 ["Priority Up" org-shiftup t]
14833 ["Priority Down" org-shiftdown t]
14834 "--"
14835 ["Get news from all feeds" org-feed-update-all t]
14836 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
14837 ["Customize feeds" (customize-variable 'org-feed-alist) t])
14838 ("TAGS and Properties"
14839 ["Set Tags" org-set-tags-command t]
14840 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14841 "--"
14842 ["Set property" org-set-property t]
14843 ["Column view of properties" org-columns t]
14844 ["Insert Column View DBlock" org-insert-columns-dblock t])
14845 ("Dates and Scheduling"
14846 ["Timestamp" org-time-stamp t]
14847 ["Timestamp (inactive)" org-time-stamp-inactive t]
14848 ("Change Date"
14849 ["1 Day Later" org-shiftright t]
14850 ["1 Day Earlier" org-shiftleft t]
14851 ["1 ... Later" org-shiftup t]
14852 ["1 ... Earlier" org-shiftdown t])
14853 ["Compute Time Range" org-evaluate-time-range t]
14854 ["Schedule Item" org-schedule t]
14855 ["Deadline" org-deadline t]
14856 "--"
14857 ["Custom time format" org-toggle-time-stamp-overlays
14858 :style radio :selected org-display-custom-times]
14859 "--"
14860 ["Goto Calendar" org-goto-calendar t]
14861 ["Date from Calendar" org-date-from-calendar t]
14862 "--"
14863 ["Start/Restart Timer" org-timer-start t]
14864 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14865 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14866 ["Insert Timer String" org-timer t]
14867 ["Insert Timer Item" org-timer-item t])
14868 ("Logging work"
14869 ["Clock in" org-clock-in t]
14870 ["Clock out" org-clock-out t]
14871 ["Clock cancel" org-clock-cancel t]
14872 ["Goto running clock" org-clock-goto t]
14873 ["Display times" org-clock-display t]
14874 ["Create clock table" org-clock-report t]
14875 "--"
14876 ["Record DONE time"
14877 (progn (setq org-log-done (not org-log-done))
14878 (message "Switching to %s will %s record a timestamp"
14879 (car org-done-keywords)
14880 (if org-log-done "automatically" "not")))
14881 :style toggle :selected org-log-done])
14882 "--"
14883 ["Agenda Command..." org-agenda t]
14884 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14885 ("File List for Agenda")
14886 ("Special views current file"
14887 ["TODO Tree" org-show-todo-tree t]
14888 ["Check Deadlines" org-check-deadlines t]
14889 ["Timeline" org-timeline t]
14890 ["Tags/Property tree" org-match-sparse-tree t])
14891 "--"
14892 ["Export/Publish..." org-export t]
14893 ("LaTeX"
14894 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14895 :selected org-cdlatex-mode]
14896 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14897 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14898 ["Modify math symbol" org-cdlatex-math-modify
14899 (org-inside-LaTeX-fragment-p)]
14900 ["Insert citation" org-reftex-citation t]
14901 "--"
14902 ["Export LaTeX fragments as images"
14903 (if (featurep 'org-exp)
14904 (setq org-export-with-LaTeX-fragments
14905 (not org-export-with-LaTeX-fragments))
14906 (require 'org-exp))
14907 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14908 org-export-with-LaTeX-fragments)])
14909 "--"
14910 ("Documentation"
14911 ["Show Version" org-version t]
14912 ["Info Documentation" org-info t])
14913 ("Customize"
14914 ["Browse Org Group" org-customize t]
14915 "--"
14916 ["Expand This Menu" org-create-customize-menu
14917 (fboundp 'customize-menu-create)])
14918 "--"
14919 ("Refresh/Reload"
14920 ["Refresh setup current buffer" org-mode-restart t]
14921 ["Reload Org (after update)" org-reload t]
14922 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14925 (defun org-info (&optional node)
14926 "Read documentation for Org-mode in the info system.
14927 With optional NODE, go directly to that node."
14928 (interactive)
14929 (info (format "(org)%s" (or node ""))))
14931 (defun org-install-agenda-files-menu ()
14932 (let ((bl (buffer-list)))
14933 (save-excursion
14934 (while bl
14935 (set-buffer (pop bl))
14936 (if (org-mode-p) (setq bl nil)))
14937 (when (org-mode-p)
14938 (easy-menu-change
14939 '("Org") "File List for Agenda"
14940 (append
14941 (list
14942 ["Edit File List" (org-edit-agenda-file-list) t]
14943 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14944 ["Remove Current File from List" org-remove-file t]
14945 ["Cycle through agenda files" org-cycle-agenda-files t]
14946 ["Occur in all agenda files" org-occur-in-agenda-files t]
14947 "--")
14948 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14950 ;;;; Documentation
14952 ;;;###autoload
14953 (defun org-require-autoloaded-modules ()
14954 (interactive)
14955 (mapc 'require
14956 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
14957 org-docbook org-exp org-html org-icalendar
14958 org-id org-latex
14959 org-publish org-remember org-table
14960 org-timer org-xoxo)))
14962 ;;;###autoload
14963 (defun org-reload (&optional uncompiled)
14964 "Reload all org lisp files.
14965 With prefix arg UNCOMPILED, load the uncompiled versions."
14966 (interactive "P")
14967 (require 'find-func)
14968 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
14969 (dir-org (file-name-directory (org-find-library-name "org")))
14970 (dir-org-contrib (ignore-errors
14971 (file-name-directory
14972 (org-find-library-name "org-contribdir"))))
14973 (files
14974 (append (directory-files dir-org t file-re)
14975 (and dir-org-contrib
14976 (directory-files dir-org-contrib t file-re))))
14977 (remove-re (concat (if (featurep 'xemacs)
14978 "org-colview" "org-colview-xemacs")
14979 "\\'")))
14980 (setq files (mapcar 'file-name-sans-extension files))
14981 (setq files (mapcar
14982 (lambda (x) (if (string-match remove-re x) nil x))
14983 files))
14984 (setq files (delq nil files))
14985 (mapc
14986 (lambda (f)
14987 (when (featurep (intern (file-name-nondirectory f)))
14988 (if (and (not uncompiled)
14989 (file-exists-p (concat f ".elc")))
14990 (load (concat f ".elc") nil nil t)
14991 (load (concat f ".el") nil nil t))))
14992 files))
14993 (org-version))
14995 ;;;###autoload
14996 (defun org-customize ()
14997 "Call the customize function with org as argument."
14998 (interactive)
14999 (org-load-modules-maybe)
15000 (org-require-autoloaded-modules)
15001 (customize-browse 'org))
15003 (defun org-create-customize-menu ()
15004 "Create a full customization menu for Org-mode, insert it into the menu."
15005 (interactive)
15006 (org-load-modules-maybe)
15007 (org-require-autoloaded-modules)
15008 (if (fboundp 'customize-menu-create)
15009 (progn
15010 (easy-menu-change
15011 '("Org") "Customize"
15012 `(["Browse Org group" org-customize t]
15013 "--"
15014 ,(customize-menu-create 'org)
15015 ["Set" Custom-set t]
15016 ["Save" Custom-save t]
15017 ["Reset to Current" Custom-reset-current t]
15018 ["Reset to Saved" Custom-reset-saved t]
15019 ["Reset to Standard Settings" Custom-reset-standard t]))
15020 (message "\"Org\"-menu now contains full customization menu"))
15021 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15023 ;;;; Miscellaneous stuff
15025 ;;; Generally useful functions
15027 (defun org-find-text-property-in-string (prop s)
15028 "Return the first non-nil value of property PROP in string S."
15029 (or (get-text-property 0 prop s)
15030 (get-text-property (or (next-single-property-change 0 prop s) 0)
15031 prop s)))
15033 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15034 "Display the given MESSAGE as a warning."
15035 (if (fboundp 'display-warning)
15036 (display-warning 'org message
15037 (if (featurep 'xemacs)
15038 'warning
15039 :warning))
15040 (let ((buf (get-buffer-create "*Org warnings*")))
15041 (with-current-buffer buf
15042 (goto-char (point-max))
15043 (insert "Warning (Org): " message)
15044 (unless (bolp)
15045 (newline)))
15046 (display-buffer buf)
15047 (sit-for 0))))
15049 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15050 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15051 (if (and marker (marker-buffer marker)
15052 (buffer-live-p (marker-buffer marker)))
15053 (progn
15054 (switch-to-buffer (marker-buffer marker))
15055 (if (or (> marker (point-max)) (< marker (point-min)))
15056 (widen))
15057 (goto-char marker)
15058 (org-show-context 'org-goto))
15059 (if bookmark
15060 (bookmark-jump bookmark)
15061 (error "Cannot find location"))))
15063 (defun org-quote-csv-field (s)
15064 "Quote field for inclusion in CSV material."
15065 (if (string-match "[\",]" s)
15066 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15069 (defun org-plist-delete (plist property)
15070 "Delete PROPERTY from PLIST.
15071 This is in contrast to merely setting it to 0."
15072 (let (p)
15073 (while plist
15074 (if (not (eq property (car plist)))
15075 (setq p (plist-put p (car plist) (nth 1 plist))))
15076 (setq plist (cddr plist)))
15079 (defun org-force-self-insert (N)
15080 "Needed to enforce self-insert under remapping."
15081 (interactive "p")
15082 (self-insert-command N))
15084 (defun org-string-width (s)
15085 "Compute width of string, ignoring invisible characters.
15086 This ignores character with invisibility property `org-link', and also
15087 characters with property `org-cwidth', because these will become invisible
15088 upon the next fontification round."
15089 (let (b l)
15090 (when (or (eq t buffer-invisibility-spec)
15091 (assq 'org-link buffer-invisibility-spec))
15092 (while (setq b (text-property-any 0 (length s)
15093 'invisible 'org-link s))
15094 (setq s (concat (substring s 0 b)
15095 (substring s (or (next-single-property-change
15096 b 'invisible s) (length s)))))))
15097 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15098 (setq s (concat (substring s 0 b)
15099 (substring s (or (next-single-property-change
15100 b 'org-cwidth s) (length s))))))
15101 (setq l (string-width s) b -1)
15102 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15103 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15106 (defun org-get-indentation (&optional line)
15107 "Get the indentation of the current line, interpreting tabs.
15108 When LINE is given, assume it represents a line and compute its indentation."
15109 (if line
15110 (if (string-match "^ *" (org-remove-tabs line))
15111 (match-end 0))
15112 (save-excursion
15113 (beginning-of-line 1)
15114 (skip-chars-forward " \t")
15115 (current-column))))
15117 (defun org-remove-tabs (s &optional width)
15118 "Replace tabulators in S with spaces.
15119 Assumes that s is a single line, starting in column 0."
15120 (setq width (or width tab-width))
15121 (while (string-match "\t" s)
15122 (setq s (replace-match
15123 (make-string
15124 (- (* width (/ (+ (match-beginning 0) width) width))
15125 (match-beginning 0)) ?\ )
15126 t t s)))
15129 (defun org-fix-indentation (line ind)
15130 "Fix indentation in LINE.
15131 IND is a cons cell with target and minimum indentation.
15132 If the current indentation in LINE is smaller than the minimum,
15133 leave it alone. If it is larger than ind, set it to the target."
15134 (let* ((l (org-remove-tabs line))
15135 (i (org-get-indentation l))
15136 (i1 (car ind)) (i2 (cdr ind)))
15137 (if (>= i i2) (setq l (substring line i2)))
15138 (if (> i1 0)
15139 (concat (make-string i1 ?\ ) l)
15140 l)))
15142 (defun org-base-buffer (buffer)
15143 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15144 (if (not buffer)
15145 buffer
15146 (or (buffer-base-buffer buffer)
15147 buffer)))
15149 (defun org-trim (s)
15150 "Remove whitespace at beginning and end of string."
15151 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15152 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15155 (defun org-wrap (string &optional width lines)
15156 "Wrap string to either a number of lines, or a width in characters.
15157 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15158 that costs. If there is a word longer than WIDTH, the text is actually
15159 wrapped to the length of that word.
15160 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15161 many lines, whatever width that takes.
15162 The return value is a list of lines, without newlines at the end."
15163 (let* ((words (org-split-string string "[ \t\n]+"))
15164 (maxword (apply 'max (mapcar 'org-string-width words)))
15165 w ll)
15166 (cond (width
15167 (org-do-wrap words (max maxword width)))
15168 (lines
15169 (setq w maxword)
15170 (setq ll (org-do-wrap words maxword))
15171 (if (<= (length ll) lines)
15173 (setq ll words)
15174 (while (> (length ll) lines)
15175 (setq w (1+ w))
15176 (setq ll (org-do-wrap words w)))
15177 ll))
15178 (t (error "Cannot wrap this")))))
15180 (defun org-do-wrap (words width)
15181 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15182 (let (lines line)
15183 (while words
15184 (setq line (pop words))
15185 (while (and words (< (+ (length line) (length (car words))) width))
15186 (setq line (concat line " " (pop words))))
15187 (setq lines (push line lines)))
15188 (nreverse lines)))
15190 (defun org-split-string (string &optional separators)
15191 "Splits STRING into substrings at SEPARATORS.
15192 No empty strings are returned if there are matches at the beginning
15193 and end of string."
15194 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15195 (start 0)
15196 notfirst
15197 (list nil))
15198 (while (and (string-match rexp string
15199 (if (and notfirst
15200 (= start (match-beginning 0))
15201 (< start (length string)))
15202 (1+ start) start))
15203 (< (match-beginning 0) (length string)))
15204 (setq notfirst t)
15205 (or (eq (match-beginning 0) 0)
15206 (and (eq (match-beginning 0) (match-end 0))
15207 (eq (match-beginning 0) start))
15208 (setq list
15209 (cons (substring string start (match-beginning 0))
15210 list)))
15211 (setq start (match-end 0)))
15212 (or (eq start (length string))
15213 (setq list
15214 (cons (substring string start)
15215 list)))
15216 (nreverse list)))
15218 (defun org-uuidgen-p (s)
15219 "Is S an ID created by UUIDGEN?"
15220 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15222 (defun org-context ()
15223 "Return a list of contexts of the current cursor position.
15224 If several contexts apply, all are returned.
15225 Each context entry is a list with a symbol naming the context, and
15226 two positions indicating start and end of the context. Possible
15227 contexts are:
15229 :headline anywhere in a headline
15230 :headline-stars on the leading stars in a headline
15231 :todo-keyword on a TODO keyword (including DONE) in a headline
15232 :tags on the TAGS in a headline
15233 :priority on the priority cookie in a headline
15234 :item on the first line of a plain list item
15235 :item-bullet on the bullet/number of a plain list item
15236 :checkbox on the checkbox in a plain list item
15237 :table in an org-mode table
15238 :table-special on a special filed in a table
15239 :table-table in a table.el table
15240 :link on a hyperlink
15241 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15242 :target on a <<target>>
15243 :radio-target on a <<<radio-target>>>
15244 :latex-fragment on a LaTeX fragment
15245 :latex-preview on a LaTeX fragment with overlayed preview image
15247 This function expects the position to be visible because it uses font-lock
15248 faces as a help to recognize the following contexts: :table-special, :link,
15249 and :keyword."
15250 (let* ((f (get-text-property (point) 'face))
15251 (faces (if (listp f) f (list f)))
15252 (p (point)) clist o)
15253 ;; First the large context
15254 (cond
15255 ((org-on-heading-p t)
15256 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15257 (when (progn
15258 (beginning-of-line 1)
15259 (looking-at org-todo-line-tags-regexp))
15260 (push (org-point-in-group p 1 :headline-stars) clist)
15261 (push (org-point-in-group p 2 :todo-keyword) clist)
15262 (push (org-point-in-group p 4 :tags) clist))
15263 (goto-char p)
15264 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15265 (if (looking-at "\\[#[A-Z0-9]\\]")
15266 (push (org-point-in-group p 0 :priority) clist)))
15268 ((org-at-item-p)
15269 (push (org-point-in-group p 2 :item-bullet) clist)
15270 (push (list :item (point-at-bol)
15271 (save-excursion (org-end-of-item) (point)))
15272 clist)
15273 (and (org-at-item-checkbox-p)
15274 (push (org-point-in-group p 0 :checkbox) clist)))
15276 ((org-at-table-p)
15277 (push (list :table (org-table-begin) (org-table-end)) clist)
15278 (if (memq 'org-formula faces)
15279 (push (list :table-special
15280 (previous-single-property-change p 'face)
15281 (next-single-property-change p 'face)) clist)))
15282 ((org-at-table-p 'any)
15283 (push (list :table-table) clist)))
15284 (goto-char p)
15286 ;; Now the small context
15287 (cond
15288 ((org-at-timestamp-p)
15289 (push (org-point-in-group p 0 :timestamp) clist))
15290 ((memq 'org-link faces)
15291 (push (list :link
15292 (previous-single-property-change p 'face)
15293 (next-single-property-change p 'face)) clist))
15294 ((memq 'org-special-keyword faces)
15295 (push (list :keyword
15296 (previous-single-property-change p 'face)
15297 (next-single-property-change p 'face)) clist))
15298 ((org-on-target-p)
15299 (push (org-point-in-group p 0 :target) clist)
15300 (goto-char (1- (match-beginning 0)))
15301 (if (looking-at org-radio-target-regexp)
15302 (push (org-point-in-group p 0 :radio-target) clist))
15303 (goto-char p))
15304 ((setq o (car (delq nil
15305 (mapcar
15306 (lambda (x)
15307 (if (memq x org-latex-fragment-image-overlays) x))
15308 (org-overlays-at (point))))))
15309 (push (list :latex-fragment
15310 (org-overlay-start o) (org-overlay-end o)) clist)
15311 (push (list :latex-preview
15312 (org-overlay-start o) (org-overlay-end o)) clist))
15313 ((org-inside-LaTeX-fragment-p)
15314 ;; FIXME: positions wrong.
15315 (push (list :latex-fragment (point) (point)) clist)))
15317 (setq clist (nreverse (delq nil clist)))
15318 clist))
15320 ;; FIXME: Compare with at-regexp-p Do we need both?
15321 (defun org-in-regexp (re &optional nlines visually)
15322 "Check if point is inside a match of regexp.
15323 Normally only the current line is checked, but you can include NLINES extra
15324 lines both before and after point into the search.
15325 If VISUALLY is set, require that the cursor is not after the match but
15326 really on, so that the block visually is on the match."
15327 (catch 'exit
15328 (let ((pos (point))
15329 (eol (point-at-eol (+ 1 (or nlines 0))))
15330 (inc (if visually 1 0)))
15331 (save-excursion
15332 (beginning-of-line (- 1 (or nlines 0)))
15333 (while (re-search-forward re eol t)
15334 (if (and (<= (match-beginning 0) pos)
15335 (>= (+ inc (match-end 0)) pos))
15336 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15338 (defun org-at-regexp-p (regexp)
15339 "Is point inside a match of REGEXP in the current line?"
15340 (catch 'exit
15341 (save-excursion
15342 (let ((pos (point)) (end (point-at-eol)))
15343 (beginning-of-line 1)
15344 (while (re-search-forward regexp end t)
15345 (if (and (<= (match-beginning 0) pos)
15346 (>= (match-end 0) pos))
15347 (throw 'exit t)))
15348 nil))))
15350 (defun org-occur-in-agenda-files (regexp &optional nlines)
15351 "Call `multi-occur' with buffers for all agenda files."
15352 (interactive "sOrg-files matching: \np")
15353 (let* ((files (org-agenda-files))
15354 (tnames (mapcar 'file-truename files))
15355 (extra org-agenda-text-search-extra-files)
15357 (when (eq (car extra) 'agenda-archives)
15358 (setq extra (cdr extra))
15359 (setq files (org-add-archive-files files)))
15360 (while (setq f (pop extra))
15361 (unless (member (file-truename f) tnames)
15362 (add-to-list 'files f 'append)
15363 (add-to-list 'tnames (file-truename f) 'append)))
15364 (multi-occur
15365 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15366 regexp)))
15368 (if (boundp 'occur-mode-find-occurrence-hook)
15369 ;; Emacs 23
15370 (add-hook 'occur-mode-find-occurrence-hook
15371 (lambda ()
15372 (when (org-mode-p)
15373 (org-reveal))))
15374 ;; Emacs 22
15375 (defadvice occur-mode-goto-occurrence
15376 (after org-occur-reveal activate)
15377 (and (org-mode-p) (org-reveal)))
15378 (defadvice occur-mode-goto-occurrence-other-window
15379 (after org-occur-reveal activate)
15380 (and (org-mode-p) (org-reveal)))
15381 (defadvice occur-mode-display-occurrence
15382 (after org-occur-reveal activate)
15383 (when (org-mode-p)
15384 (let ((pos (occur-mode-find-occurrence)))
15385 (with-current-buffer (marker-buffer pos)
15386 (save-excursion
15387 (goto-char pos)
15388 (org-reveal)))))))
15390 (defun org-uniquify (list)
15391 "Remove duplicate elements from LIST."
15392 (let (res)
15393 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15394 res))
15396 (defun org-delete-all (elts list)
15397 "Remove all elements in ELTS from LIST."
15398 (while elts
15399 (setq list (delete (pop elts) list)))
15400 list)
15402 (defun org-back-over-empty-lines ()
15403 "Move backwards over whitespace, to the beginning of the first empty line.
15404 Returns the number of empty lines passed."
15405 (let ((pos (point)))
15406 (skip-chars-backward " \t\n\r")
15407 (beginning-of-line 2)
15408 (goto-char (min (point) pos))
15409 (count-lines (point) pos)))
15411 (defun org-skip-whitespace ()
15412 (skip-chars-forward " \t\n\r"))
15414 (defun org-point-in-group (point group &optional context)
15415 "Check if POINT is in match-group GROUP.
15416 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15417 match. If the match group does ot exist or point is not inside it,
15418 return nil."
15419 (and (match-beginning group)
15420 (>= point (match-beginning group))
15421 (<= point (match-end group))
15422 (if context
15423 (list context (match-beginning group) (match-end group))
15424 t)))
15426 (defun org-switch-to-buffer-other-window (&rest args)
15427 "Switch to buffer in a second window on the current frame.
15428 In particular, do not allow pop-up frames."
15429 (let (pop-up-frames special-display-buffer-names special-display-regexps
15430 special-display-function)
15431 (apply 'switch-to-buffer-other-window args)))
15433 (defun org-combine-plists (&rest plists)
15434 "Create a single property list from all plists in PLISTS.
15435 The process starts by copying the first list, and then setting properties
15436 from the other lists. Settings in the last list are the most significant
15437 ones and overrule settings in the other lists."
15438 (let ((rtn (copy-sequence (pop plists)))
15439 p v ls)
15440 (while plists
15441 (setq ls (pop plists))
15442 (while ls
15443 (setq p (pop ls) v (pop ls))
15444 (setq rtn (plist-put rtn p v))))
15445 rtn))
15447 (defun org-move-line-down (arg)
15448 "Move the current line down. With prefix argument, move it past ARG lines."
15449 (interactive "p")
15450 (let ((col (current-column))
15451 beg end pos)
15452 (beginning-of-line 1) (setq beg (point))
15453 (beginning-of-line 2) (setq end (point))
15454 (beginning-of-line (+ 1 arg))
15455 (setq pos (move-marker (make-marker) (point)))
15456 (insert (delete-and-extract-region beg end))
15457 (goto-char pos)
15458 (org-move-to-column col)))
15460 (defun org-move-line-up (arg)
15461 "Move the current line up. With prefix argument, move it past ARG lines."
15462 (interactive "p")
15463 (let ((col (current-column))
15464 beg end pos)
15465 (beginning-of-line 1) (setq beg (point))
15466 (beginning-of-line 2) (setq end (point))
15467 (beginning-of-line (- arg))
15468 (setq pos (move-marker (make-marker) (point)))
15469 (insert (delete-and-extract-region beg end))
15470 (goto-char pos)
15471 (org-move-to-column col)))
15473 (defun org-replace-escapes (string table)
15474 "Replace %-escapes in STRING with values in TABLE.
15475 TABLE is an association list with keys like \"%a\" and string values.
15476 The sequences in STRING may contain normal field width and padding information,
15477 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15478 so values can contain further %-escapes if they are define later in TABLE."
15479 (let ((case-fold-search nil)
15480 e re rpl)
15481 (while (setq e (pop table))
15482 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15483 (while (string-match re string)
15484 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15485 (cdr e)))
15486 (setq string (replace-match rpl t t string))))
15487 string))
15490 (defun org-sublist (list start end)
15491 "Return a section of LIST, from START to END.
15492 Counting starts at 1."
15493 (let (rtn (c start))
15494 (setq list (nthcdr (1- start) list))
15495 (while (and list (<= c end))
15496 (push (pop list) rtn)
15497 (setq c (1+ c)))
15498 (nreverse rtn)))
15500 (defun org-find-base-buffer-visiting (file)
15501 "Like `find-buffer-visiting' but always return the base buffer and
15502 not an indirect buffer."
15503 (let ((buf (or (get-file-buffer file)
15504 (find-buffer-visiting file))))
15505 (if buf
15506 (or (buffer-base-buffer buf) buf)
15507 nil)))
15509 (defun org-image-file-name-regexp (&optional extensions)
15510 "Return regexp matching the file names of images.
15511 If EXTENSIONS is given, only match these."
15512 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15513 (image-file-name-regexp)
15514 (let ((image-file-name-extensions
15515 (or extensions
15516 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15517 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15518 (concat "\\."
15519 (regexp-opt (nconc (mapcar 'upcase
15520 image-file-name-extensions)
15521 image-file-name-extensions)
15523 "\\'"))))
15525 (defun org-file-image-p (file &optional extensions)
15526 "Return non-nil if FILE is an image."
15527 (save-match-data
15528 (string-match (org-image-file-name-regexp extensions) file)))
15530 (defun org-get-cursor-date ()
15531 "Return the date at cursor in as a time.
15532 This works in the calendar and in the agenda, anywhere else it just
15533 returns the current time."
15534 (let (date day defd)
15535 (cond
15536 ((eq major-mode 'calendar-mode)
15537 (setq date (calendar-cursor-to-date)
15538 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15539 ((eq major-mode 'org-agenda-mode)
15540 (setq day (get-text-property (point) 'day))
15541 (if day
15542 (setq date (calendar-gregorian-from-absolute day)
15543 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15544 (nth 2 date))))))
15545 (or defd (current-time))))
15547 (defvar org-agenda-action-marker (make-marker)
15548 "Marker pointing to the entry for the next agenda action.")
15550 (defun org-mark-entry-for-agenda-action ()
15551 "Mark the current entry as target of an agenda action.
15552 Agenda actions are actions executed from the agenda with the key `k',
15553 which make use of the date at the cursor."
15554 (interactive)
15555 (move-marker org-agenda-action-marker
15556 (save-excursion (org-back-to-heading t) (point))
15557 (current-buffer))
15558 (message
15559 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15561 ;;; Paragraph filling stuff.
15562 ;; We want this to be just right, so use the full arsenal.
15564 (defun org-indent-line-function ()
15565 "Indent line like previous, but further if previous was headline or item."
15566 (interactive)
15567 (let* ((pos (point))
15568 (itemp (org-at-item-p))
15569 (org-drawer-regexp (or org-drawer-regexp "\000"))
15570 column bpos bcol tpos tcol bullet btype bullet-type)
15571 ;; Find the previous relevant line
15572 (beginning-of-line 1)
15573 (cond
15574 ((looking-at "#") (setq column 0))
15575 ((looking-at "\\*+ ") (setq column 0))
15576 ((and (looking-at "[ \t]*:END:")
15577 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15578 (save-excursion
15579 (goto-char (1- (match-beginning 1)))
15580 (setq column (current-column))))
15582 (beginning-of-line 0)
15583 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15584 (not (looking-at "[ \t]*:END:"))
15585 (not (looking-at org-drawer-regexp)))
15586 (beginning-of-line 0))
15587 (cond
15588 ((looking-at "\\*+[ \t]+")
15589 (if (not org-adapt-indentation)
15590 (setq column 0)
15591 (goto-char (match-end 0))
15592 (setq column (current-column))))
15593 ((looking-at org-drawer-regexp)
15594 (goto-char (1- (match-beginning 1)))
15595 (setq column (current-column)))
15596 ((looking-at "\\([ \t]*\\):END:")
15597 (goto-char (match-end 1))
15598 (setq column (current-column)))
15599 ((org-in-item-p)
15600 (org-beginning-of-item)
15601 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15602 (setq bpos (match-beginning 1) tpos (match-end 0)
15603 bcol (progn (goto-char bpos) (current-column))
15604 tcol (progn (goto-char tpos) (current-column))
15605 bullet (match-string 1)
15606 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15607 (if (> tcol (+ bcol org-description-max-indent))
15608 (setq tcol (+ bcol 5)))
15609 (if (not itemp)
15610 (setq column tcol)
15611 (goto-char pos)
15612 (beginning-of-line 1)
15613 (if (looking-at "\\S-")
15614 (progn
15615 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15616 (setq bullet (match-string 1)
15617 btype (if (string-match "[0-9]" bullet) "n" bullet))
15618 (setq column (if (equal btype bullet-type) bcol tcol)))
15619 (setq column (org-get-indentation)))))
15620 (t (setq column (org-get-indentation))))))
15621 (goto-char pos)
15622 (if (<= (current-column) (current-indentation))
15623 (org-indent-line-to column)
15624 (save-excursion (org-indent-line-to column)))
15625 (setq column (current-column))
15626 (beginning-of-line 1)
15627 (if (looking-at
15628 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15629 (replace-match (concat "\\1" (format org-property-format
15630 (match-string 2) (match-string 3)))
15631 t nil))
15632 (org-move-to-column column)))
15634 (defun org-set-autofill-regexps ()
15635 (interactive)
15636 ;; In the paragraph separator we include headlines, because filling
15637 ;; text in a line directly attached to a headline would otherwise
15638 ;; fill the headline as well.
15639 (org-set-local 'comment-start-skip "^#+[ \t]*")
15640 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15641 ;; The paragraph starter includes hand-formatted lists.
15642 (org-set-local 'paragraph-start
15643 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15644 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15645 ;; But only if the user has not turned off tables or fixed-width regions
15646 (org-set-local
15647 'auto-fill-inhibit-regexp
15648 (concat "\\*+ \\|#\\+"
15649 "\\|[ \t]*" org-keyword-time-regexp
15650 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15651 (concat
15652 "\\|[ \t]*["
15653 (if org-enable-table-editor "|" "")
15654 (if org-enable-fixed-width-editor ":" "")
15655 "]"))))
15656 ;; We use our own fill-paragraph function, to make sure that tables
15657 ;; and fixed-width regions are not wrapped. That function will pass
15658 ;; through to `fill-paragraph' when appropriate.
15659 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15660 ; Adaptive filling: To get full control, first make sure that
15661 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15662 (org-set-local 'adaptive-fill-regexp "\000")
15663 (org-set-local 'adaptive-fill-function
15664 'org-adaptive-fill-function)
15665 (org-set-local
15666 'align-mode-rules-list
15667 '((org-in-buffer-settings
15668 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15669 (modes . '(org-mode))))))
15671 (defun org-fill-paragraph (&optional justify)
15672 "Re-align a table, pass through to fill-paragraph if no table."
15673 (let ((table-p (org-at-table-p))
15674 (table.el-p (org-at-table.el-p)))
15675 (cond ((and (equal (char-after (point-at-bol)) ?*)
15676 (save-excursion (goto-char (point-at-bol))
15677 (looking-at outline-regexp)))
15678 t) ; skip headlines
15679 (table.el-p t) ; skip table.el tables
15680 (table-p (org-table-align) t) ; align org-mode tables
15681 (t nil)))) ; call paragraph-fill
15683 ;; For reference, this is the default value of adaptive-fill-regexp
15684 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15686 (defun org-adaptive-fill-function ()
15687 "Return a fill prefix for org-mode files.
15688 In particular, this makes sure hanging paragraphs for hand-formatted lists
15689 work correctly."
15690 (cond ((looking-at "#[ \t]+")
15691 (match-string 0))
15692 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15693 (save-excursion
15694 (if (> (match-end 1) (+ (match-beginning 1)
15695 org-description-max-indent))
15696 (goto-char (+ (match-beginning 1) 5))
15697 (goto-char (match-end 0)))
15698 (make-string (current-column) ?\ )))
15699 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15700 (save-excursion
15701 (goto-char (match-end 0))
15702 (make-string (current-column) ?\ )))
15703 (t nil)))
15705 ;;; Other stuff.
15707 (defun org-toggle-fixed-width-section (arg)
15708 "Toggle the fixed-width export.
15709 If there is no active region, the QUOTE keyword at the current headline is
15710 inserted or removed. When present, it causes the text between this headline
15711 and the next to be exported as fixed-width text, and unmodified.
15712 If there is an active region, this command adds or removes a colon as the
15713 first character of this line. If the first character of a line is a colon,
15714 this line is also exported in fixed-width font."
15715 (interactive "P")
15716 (let* ((cc 0)
15717 (regionp (org-region-active-p))
15718 (beg (if regionp (region-beginning) (point)))
15719 (end (if regionp (region-end)))
15720 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15721 (case-fold-search nil)
15722 (re "[ \t]*\\(: \\)")
15723 off)
15724 (if regionp
15725 (save-excursion
15726 (goto-char beg)
15727 (setq cc (current-column))
15728 (beginning-of-line 1)
15729 (setq off (looking-at re))
15730 (while (> nlines 0)
15731 (setq nlines (1- nlines))
15732 (beginning-of-line 1)
15733 (cond
15734 (arg
15735 (org-move-to-column cc t)
15736 (insert ": \n")
15737 (forward-line -1))
15738 ((and off (looking-at re))
15739 (replace-match "" t t nil 1))
15740 ((not off) (org-move-to-column cc t) (insert ": ")))
15741 (forward-line 1)))
15742 (save-excursion
15743 (org-back-to-heading)
15744 (if (looking-at (concat outline-regexp
15745 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15746 (replace-match "" t t nil 1)
15747 (if (looking-at outline-regexp)
15748 (progn
15749 (goto-char (match-end 0))
15750 (insert org-quote-string " "))))))))
15752 (defun org-reftex-citation ()
15753 "Use reftex-citation to insert a citation into the buffer.
15754 This looks for a line like
15756 #+BIBLIOGRAPHY: foo plain option:-d
15758 and derives from it that foo.bib is the bbliography file relevant
15759 for this document. It then installs the necessary environment for RefTeX
15760 to work in this buffer and calls `reftex-citation' to insert a citation
15761 into the buffer.
15763 Export of such citations to both LaTeX and HTML is handled by the contributed
15764 package org-exp-bibtex by Taru Karttunen."
15765 (interactive)
15766 (let ((reftex-docstruct-symbol 'rds)
15767 (reftex-cite-format "\\cite{%l}")
15768 rds bib)
15769 (save-excursion
15770 (save-restriction
15771 (widen)
15772 (let ((case-fold-search t)
15773 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15774 (if (not (save-excursion
15775 (or (re-search-forward re nil t)
15776 (re-search-backward re nil t))))
15777 (error "No bibliography defined in file")
15778 (setq bib (concat (match-string 1) ".bib")
15779 rds (list (list 'bib bib)))))))
15780 (call-interactively 'reftex-citation)))
15782 ;;;; Functions extending outline functionality
15784 (defun org-beginning-of-line (&optional arg)
15785 "Go to the beginning of the current line. If that is invisible, continue
15786 to a visible line beginning. This makes the function of C-a more intuitive.
15787 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15788 first attempt, and only move to after the tags when the cursor is already
15789 beyond the end of the headline."
15790 (interactive "P")
15791 (let ((pos (point))
15792 (special (if (consp org-special-ctrl-a/e)
15793 (car org-special-ctrl-a/e)
15794 org-special-ctrl-a/e))
15795 refpos)
15796 (beginning-of-line 1)
15797 (if (and arg (fboundp 'move-beginning-of-line))
15798 (call-interactively 'move-beginning-of-line)
15799 (if (bobp)
15801 (backward-char 1)
15802 (if (org-invisible-p)
15803 (while (and (not (bobp)) (org-invisible-p))
15804 (backward-char 1)
15805 (beginning-of-line 1))
15806 (forward-char 1))))
15807 (when special
15808 (cond
15809 ((and (looking-at org-complex-heading-regexp)
15810 (= (char-after (match-end 1)) ?\ ))
15811 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15812 (point-at-eol)))
15813 (goto-char
15814 (if (eq special t)
15815 (cond ((> pos refpos) refpos)
15816 ((= pos (point)) refpos)
15817 (t (point)))
15818 (cond ((> pos (point)) (point))
15819 ((not (eq last-command this-command)) (point))
15820 (t refpos)))))
15821 ((org-at-item-p)
15822 (goto-char
15823 (if (eq special t)
15824 (cond ((> pos (match-end 4)) (match-end 4))
15825 ((= pos (point)) (match-end 4))
15826 (t (point)))
15827 (cond ((> pos (point)) (point))
15828 ((not (eq last-command this-command)) (point))
15829 (t (match-end 4))))))))
15830 (org-no-warnings
15831 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15833 (defun org-end-of-line (&optional arg)
15834 "Go to the end of the line.
15835 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15836 first attempt, and only move to after the tags when the cursor is already
15837 beyond the end of the headline."
15838 (interactive "P")
15839 (let ((special (if (consp org-special-ctrl-a/e)
15840 (cdr org-special-ctrl-a/e)
15841 org-special-ctrl-a/e)))
15842 (if (or (not special)
15843 (not (org-on-heading-p))
15844 arg)
15845 (call-interactively (if (fboundp 'move-end-of-line)
15846 'move-end-of-line
15847 'end-of-line))
15848 (let ((pos (point)))
15849 (beginning-of-line 1)
15850 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15851 (if (eq special t)
15852 (if (or (< pos (match-beginning 1))
15853 (= pos (match-end 0)))
15854 (goto-char (match-beginning 1))
15855 (goto-char (match-end 0)))
15856 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15857 (goto-char (match-end 0))
15858 (goto-char (match-beginning 1))))
15859 (call-interactively (if (fboundp 'move-end-of-line)
15860 'move-end-of-line
15861 'end-of-line)))))
15862 (org-no-warnings
15863 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15865 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15866 (define-key org-mode-map "\C-e" 'org-end-of-line)
15868 (defun org-backward-sentence (&optional arg)
15869 "Go to beginning of sentence, or beginning of table field.
15870 This will call `backward-sentence' or `org-table-beginning-of-field',
15871 depending on context."
15872 (interactive "P")
15873 (cond
15874 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
15875 (t (call-interactively 'backward-sentence))))
15877 (defun org-forward-sentence (&optional arg)
15878 "Go to end of sentence, or end of table field.
15879 This will call `forward-sentence' or `org-table-end-of-field',
15880 depending on context."
15881 (interactive "P")
15882 (cond
15883 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
15884 (t (call-interactively 'forward-sentence))))
15886 (define-key org-mode-map "\M-a" 'org-backward-sentence)
15887 (define-key org-mode-map "\M-e" 'org-forward-sentence)
15889 (defun org-kill-line (&optional arg)
15890 "Kill line, to tags or end of line."
15891 (interactive "P")
15892 (cond
15893 ((or (not org-special-ctrl-k)
15894 (bolp)
15895 (not (org-on-heading-p)))
15896 (call-interactively 'kill-line))
15897 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15898 (kill-region (point) (match-beginning 1))
15899 (org-set-tags nil t))
15900 (t (kill-region (point) (point-at-eol)))))
15902 (define-key org-mode-map "\C-k" 'org-kill-line)
15904 (defun org-yank (&optional arg)
15905 "Yank. If the kill is a subtree, treat it specially.
15906 This command will look at the current kill and check if is a single
15907 subtree, or a series of subtrees[1]. If it passes the test, and if the
15908 cursor is at the beginning of a line or after the stars of a currently
15909 empty headline, then the yank is handled specially. How exactly depends
15910 on the value of the following variables, both set by default.
15912 org-yank-folded-subtrees
15913 When set, the subtree(s) will be folded after insertion, but only
15914 if doing so would now swallow text after the yanked text.
15916 org-yank-adjusted-subtrees
15917 When set, the subtree will be promoted or demoted in order to
15918 fit into the local outline tree structure, which means that the level
15919 will be adjusted so that it becomes the smaller one of the two
15920 *visible* surrounding headings.
15922 Any prefix to this command will cause `yank' to be called directly with
15923 no special treatment. In particular, a simple `C-u' prefix will just
15924 plainly yank the text as it is.
15926 \[1] Basically, the test checks if the first non-white line is a heading
15927 and if there are no other headings with fewer stars."
15928 (interactive "P")
15929 (setq this-command 'yank)
15930 (if arg
15931 (call-interactively 'yank)
15932 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15933 (and (org-kill-is-subtree-p)
15934 (or (bolp)
15935 (and (looking-at "[ \t]*$")
15936 (string-match
15937 "\\`\\*+\\'"
15938 (buffer-substring (point-at-bol) (point)))))))
15939 swallowp)
15940 (cond
15941 ((and subtreep org-yank-folded-subtrees)
15942 (let ((beg (point))
15943 end)
15944 (if (and subtreep org-yank-adjusted-subtrees)
15945 (org-paste-subtree nil nil 'for-yank)
15946 (call-interactively 'yank))
15947 (setq end (point))
15948 (goto-char beg)
15949 (when (and (bolp) subtreep
15950 (not (setq swallowp
15951 (org-yank-folding-would-swallow-text beg end))))
15952 (or (looking-at outline-regexp)
15953 (re-search-forward (concat "^" outline-regexp) end t))
15954 (while (and (< (point) end) (looking-at outline-regexp))
15955 (hide-subtree)
15956 (org-cycle-show-empty-lines 'folded)
15957 (condition-case nil
15958 (outline-forward-same-level 1)
15959 (error (goto-char end)))))
15960 (when swallowp
15961 (message
15962 "Yanked text not folded because that would swallow text"))
15963 (goto-char end)
15964 (skip-chars-forward " \t\n\r")
15965 (beginning-of-line 1)
15966 (push-mark beg 'nomsg)))
15967 ((and subtreep org-yank-adjusted-subtrees)
15968 (let ((beg (point-at-bol)))
15969 (org-paste-subtree nil nil 'for-yank)
15970 (push-mark beg 'nomsg)))
15972 (call-interactively 'yank))))))
15974 (defun org-yank-folding-would-swallow-text (beg end)
15975 "Would hide-subtree at BEG swallow any text after END?"
15976 (let (level)
15977 (save-excursion
15978 (goto-char beg)
15979 (when (or (looking-at outline-regexp)
15980 (re-search-forward (concat "^" outline-regexp) end t))
15981 (setq level (org-outline-level)))
15982 (goto-char end)
15983 (skip-chars-forward " \t\r\n\v\f")
15984 (if (or (eobp)
15985 (and (bolp) (looking-at org-outline-regexp)
15986 (<= (org-outline-level) level)))
15987 nil ; Nothing would be swallowed
15988 t)))) ; something would swallow
15990 (define-key org-mode-map "\C-y" 'org-yank)
15992 (defun org-invisible-p ()
15993 "Check if point is at a character currently not visible."
15994 ;; Early versions of noutline don't have `outline-invisible-p'.
15995 (if (fboundp 'outline-invisible-p)
15996 (outline-invisible-p)
15997 (get-char-property (point) 'invisible)))
15999 (defun org-invisible-p2 ()
16000 "Check if point is at a character currently not visible."
16001 (save-excursion
16002 (if (and (eolp) (not (bobp))) (backward-char 1))
16003 ;; Early versions of noutline don't have `outline-invisible-p'.
16004 (if (fboundp 'outline-invisible-p)
16005 (outline-invisible-p)
16006 (get-char-property (point) 'invisible))))
16008 (defun org-back-to-heading (&optional invisible-ok)
16009 "Call `outline-back-to-heading', but provide a better error message."
16010 (condition-case nil
16011 (outline-back-to-heading invisible-ok)
16012 (error (error "Before first headline at position %d in buffer %s"
16013 (point) (current-buffer)))))
16015 (defun org-before-first-heading-p ()
16016 "Before first heading?"
16017 (save-excursion
16018 (null (re-search-backward "^\\*+ " nil t))))
16020 (defalias 'org-on-heading-p 'outline-on-heading-p)
16021 (defalias 'org-at-heading-p 'outline-on-heading-p)
16022 (defun org-at-heading-or-item-p ()
16023 (or (org-on-heading-p) (org-at-item-p)))
16025 (defun org-on-target-p ()
16026 (or (org-in-regexp org-radio-target-regexp)
16027 (org-in-regexp org-target-regexp)))
16029 (defun org-up-heading-all (arg)
16030 "Move to the heading line of which the present line is a subheading.
16031 This function considers both visible and invisible heading lines.
16032 With argument, move up ARG levels."
16033 (if (fboundp 'outline-up-heading-all)
16034 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16035 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16037 (defun org-up-heading-safe ()
16038 "Move to the heading line of which the present line is a subheading.
16039 This version will not throw an error. It will return the level of the
16040 headline found, or nil if no higher level is found.
16042 Also, this function will be a lot faster than `outline-up-heading',
16043 because it relies on stars being the outline starters. This can really
16044 make a significant difference in outlines with very many siblings."
16045 (let (start-level re)
16046 (org-back-to-heading t)
16047 (setq start-level (funcall outline-level))
16048 (if (equal start-level 1)
16050 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16051 (if (re-search-backward re nil t)
16052 (funcall outline-level)))))
16054 (defun org-first-sibling-p ()
16055 "Is this heading the first child of its parents?"
16056 (interactive)
16057 (let ((re (concat "^" outline-regexp))
16058 level l)
16059 (unless (org-at-heading-p t)
16060 (error "Not at a heading"))
16061 (setq level (funcall outline-level))
16062 (save-excursion
16063 (if (not (re-search-backward re nil t))
16065 (setq l (funcall outline-level))
16066 (< l level)))))
16068 (defun org-goto-sibling (&optional previous)
16069 "Goto the next sibling, even if it is invisible.
16070 When PREVIOUS is set, go to the previous sibling instead. Returns t
16071 when a sibling was found. When none is found, return nil and don't
16072 move point."
16073 (let ((fun (if previous 're-search-backward 're-search-forward))
16074 (pos (point))
16075 (re (concat "^" outline-regexp))
16076 level l)
16077 (when (condition-case nil (org-back-to-heading t) (error nil))
16078 (setq level (funcall outline-level))
16079 (catch 'exit
16080 (or previous (forward-char 1))
16081 (while (funcall fun re nil t)
16082 (setq l (funcall outline-level))
16083 (when (< l level) (goto-char pos) (throw 'exit nil))
16084 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16085 (goto-char pos)
16086 nil))))
16088 (defun org-show-siblings ()
16089 "Show all siblings of the current headline."
16090 (save-excursion
16091 (while (org-goto-sibling) (org-flag-heading nil)))
16092 (save-excursion
16093 (while (org-goto-sibling 'previous)
16094 (org-flag-heading nil))))
16096 (defun org-show-hidden-entry ()
16097 "Show an entry where even the heading is hidden."
16098 (save-excursion
16099 (org-show-entry)))
16101 (defun org-flag-heading (flag &optional entry)
16102 "Flag the current heading. FLAG non-nil means make invisible.
16103 When ENTRY is non-nil, show the entire entry."
16104 (save-excursion
16105 (org-back-to-heading t)
16106 ;; Check if we should show the entire entry
16107 (if entry
16108 (progn
16109 (org-show-entry)
16110 (save-excursion
16111 (and (outline-next-heading)
16112 (org-flag-heading nil))))
16113 (outline-flag-region (max (point-min) (1- (point)))
16114 (save-excursion (outline-end-of-heading) (point))
16115 flag))))
16117 (defun org-forward-same-level (arg)
16118 "Move forward to the ARG'th subheading at same level as this one.
16119 Stop at the first and last subheadings of a superior heading.
16120 This is like outline-forward-same-level, but invisible headings are ok."
16121 (interactive "p")
16122 (org-back-to-heading t)
16123 (while (> arg 0)
16124 (let ((point-to-move-to (save-excursion
16125 (org-get-next-sibling))))
16126 (if point-to-move-to
16127 (progn
16128 (goto-char point-to-move-to)
16129 (setq arg (1- arg)))
16130 (progn
16131 (setq arg 0)
16132 (error "No following same-level heading"))))))
16134 (defun org-get-next-sibling ()
16135 "Move to next heading of the same level, and return point.
16136 If there is no such heading, return nil.
16137 This is like outline-next-sibling, but invisible headings are ok."
16138 (let ((level (funcall outline-level)))
16139 (outline-next-heading)
16140 (while (and (not (eobp)) (> (funcall outline-level) level))
16141 (outline-next-heading))
16142 (if (or (eobp) (< (funcall outline-level) level))
16144 (point))))
16146 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16147 ;; This contains an exact copy of the original function, but it uses
16148 ;; `org-back-to-heading', to make it work also in invisible
16149 ;; trees. And is uses an invisible-OK argument.
16150 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16151 ;; Furthermore, when used inside Org, finding the end of a large subtree
16152 ;; with many children and grandchildren etc, this can be much faster
16153 ;; than the outline version.
16154 (org-back-to-heading invisible-OK)
16155 (let ((first t)
16156 (level (funcall outline-level)))
16157 (if (and (org-mode-p) (< level 1000))
16158 ;; A true heading (not a plain list item), in Org-mode
16159 ;; This means we can easily find the end by looking
16160 ;; only for the right number of stars. Using a regexp to do
16161 ;; this is so much faster than using a Lisp loop.
16162 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16163 (forward-char 1)
16164 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16165 ;; something else, do it the slow way
16166 (while (and (not (eobp))
16167 (or first (> (funcall outline-level) level)))
16168 (setq first nil)
16169 (outline-next-heading)))
16170 (unless to-heading
16171 (if (memq (preceding-char) '(?\n ?\^M))
16172 (progn
16173 ;; Go to end of line before heading
16174 (forward-char -1)
16175 (if (memq (preceding-char) '(?\n ?\^M))
16176 ;; leave blank line before heading
16177 (forward-char -1))))))
16178 (point))
16180 (defun org-show-subtree ()
16181 "Show everything after this heading at deeper levels."
16182 (outline-flag-region
16183 (point)
16184 (save-excursion
16185 (outline-end-of-subtree) (outline-next-heading) (point))
16186 nil))
16188 (defun org-show-entry ()
16189 "Show the body directly following this heading.
16190 Show the heading too, if it is currently invisible."
16191 (interactive)
16192 (save-excursion
16193 (condition-case nil
16194 (progn
16195 (org-back-to-heading t)
16196 (outline-flag-region
16197 (max (point-min) (1- (point)))
16198 (save-excursion
16199 (if (re-search-forward
16200 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16201 (match-beginning 1)
16202 (point-max)))
16203 nil))
16204 (error nil))))
16206 (defun org-make-options-regexp (kwds &optional extra)
16207 "Make a regular expression for keyword lines."
16208 (concat
16210 "#?[ \t]*\\+\\("
16211 (mapconcat 'regexp-quote kwds "\\|")
16212 (if extra (concat "\\|" extra))
16213 "\\):[ \t]*"
16214 "\\(.+\\)"))
16216 ;; Make isearch reveal the necessary context
16217 (defun org-isearch-end ()
16218 "Reveal context after isearch exits."
16219 (when isearch-success ; only if search was successful
16220 (if (featurep 'xemacs)
16221 ;; Under XEmacs, the hook is run in the correct place,
16222 ;; we directly show the context.
16223 (org-show-context 'isearch)
16224 ;; In Emacs the hook runs *before* restoring the overlays.
16225 ;; So we have to use a one-time post-command-hook to do this.
16226 ;; (Emacs 22 has a special variable, see function `org-mode')
16227 (unless (and (boundp 'isearch-mode-end-hook-quit)
16228 isearch-mode-end-hook-quit)
16229 ;; Only when the isearch was not quitted.
16230 (org-add-hook 'post-command-hook 'org-isearch-post-command
16231 'append 'local)))))
16233 (defun org-isearch-post-command ()
16234 "Remove self from hook, and show context."
16235 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16236 (org-show-context 'isearch))
16239 ;;;; Integration with and fixes for other packages
16241 ;;; Imenu support
16243 (defvar org-imenu-markers nil
16244 "All markers currently used by Imenu.")
16245 (make-variable-buffer-local 'org-imenu-markers)
16247 (defun org-imenu-new-marker (&optional pos)
16248 "Return a new marker for use by Imenu, and remember the marker."
16249 (let ((m (make-marker)))
16250 (move-marker m (or pos (point)))
16251 (push m org-imenu-markers)
16254 (defun org-imenu-get-tree ()
16255 "Produce the index for Imenu."
16256 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16257 (setq org-imenu-markers nil)
16258 (let* ((n org-imenu-depth)
16259 (re (concat "^" outline-regexp))
16260 (subs (make-vector (1+ n) nil))
16261 (last-level 0)
16262 m level head)
16263 (save-excursion
16264 (save-restriction
16265 (widen)
16266 (goto-char (point-max))
16267 (while (re-search-backward re nil t)
16268 (setq level (org-reduced-level (funcall outline-level)))
16269 (when (<= level n)
16270 (looking-at org-complex-heading-regexp)
16271 (setq head (org-link-display-format
16272 (org-match-string-no-properties 4))
16273 m (org-imenu-new-marker))
16274 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16275 (if (>= level last-level)
16276 (push (cons head m) (aref subs level))
16277 (push (cons head (aref subs (1+ level))) (aref subs level))
16278 (loop for i from (1+ level) to n do (aset subs i nil)))
16279 (setq last-level level)))))
16280 (aref subs 1)))
16282 (eval-after-load "imenu"
16283 '(progn
16284 (add-hook 'imenu-after-jump-hook
16285 (lambda ()
16286 (if (eq major-mode 'org-mode)
16287 (org-show-context 'org-goto))))))
16289 (defun org-link-display-format (link)
16290 "Replace a link with either the description, or the link target
16291 if no description is present"
16292 (save-match-data
16293 (if (string-match org-bracket-link-analytic-regexp link)
16294 (replace-match (or (match-string 5 link)
16295 (concat (match-string 1 link)
16296 (match-string 3 link)))
16297 nil nil link)
16298 link)))
16300 ;; Speedbar support
16302 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16303 "Overlay marking the agenda restriction line in speedbar.")
16304 (org-overlay-put org-speedbar-restriction-lock-overlay
16305 'face 'org-agenda-restriction-lock)
16306 (org-overlay-put org-speedbar-restriction-lock-overlay
16307 'help-echo "Agendas are currently limited to this item.")
16308 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16310 (defun org-speedbar-set-agenda-restriction ()
16311 "Restrict future agenda commands to the location at point in speedbar.
16312 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16313 (interactive)
16314 (require 'org-agenda)
16315 (let (p m tp np dir txt)
16316 (cond
16317 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16318 'org-imenu t))
16319 (setq m (get-text-property p 'org-imenu-marker))
16320 (save-excursion
16321 (save-restriction
16322 (set-buffer (marker-buffer m))
16323 (goto-char m)
16324 (org-agenda-set-restriction-lock 'subtree))))
16325 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16326 'speedbar-function 'speedbar-find-file))
16327 (setq tp (previous-single-property-change
16328 (1+ p) 'speedbar-function)
16329 np (next-single-property-change
16330 tp 'speedbar-function)
16331 dir (speedbar-line-directory)
16332 txt (buffer-substring-no-properties (or tp (point-min))
16333 (or np (point-max))))
16334 (save-excursion
16335 (save-restriction
16336 (set-buffer (find-file-noselect
16337 (let ((default-directory dir))
16338 (expand-file-name txt))))
16339 (unless (org-mode-p)
16340 (error "Cannot restrict to non-Org-mode file"))
16341 (org-agenda-set-restriction-lock 'file))))
16342 (t (error "Don't know how to restrict Org-mode's agenda")))
16343 (org-move-overlay org-speedbar-restriction-lock-overlay
16344 (point-at-bol) (point-at-eol))
16345 (setq current-prefix-arg nil)
16346 (org-agenda-maybe-redo)))
16348 (eval-after-load "speedbar"
16349 '(progn
16350 (speedbar-add-supported-extension ".org")
16351 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16352 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16353 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16354 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16355 (add-hook 'speedbar-visiting-tag-hook
16356 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16359 ;;; Fixes and Hacks for problems with other packages
16361 ;; Make flyspell not check words in links, to not mess up our keymap
16362 (defun org-mode-flyspell-verify ()
16363 "Don't let flyspell put overlays at active buttons."
16364 (not (get-text-property (point) 'keymap)))
16366 ;; Make `bookmark-jump' show the jump location if it was hidden.
16367 (eval-after-load "bookmark"
16368 '(if (boundp 'bookmark-after-jump-hook)
16369 ;; We can use the hook
16370 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16371 ;; Hook not available, use advice
16372 (defadvice bookmark-jump (after org-make-visible activate)
16373 "Make the position visible."
16374 (org-bookmark-jump-unhide))))
16376 ;; Make sure saveplace show the location if it was hidden
16377 (eval-after-load "saveplace"
16378 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16379 "Make the position visible."
16380 (org-bookmark-jump-unhide)))
16382 (defun org-bookmark-jump-unhide ()
16383 "Unhide the current position, to show the bookmark location."
16384 (and (org-mode-p)
16385 (or (org-invisible-p)
16386 (save-excursion (goto-char (max (point-min) (1- (point))))
16387 (org-invisible-p)))
16388 (org-show-context 'bookmark-jump)))
16390 ;; Make session.el ignore our circular variable
16391 (eval-after-load "session"
16392 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16394 ;;;; Experimental code
16396 (defun org-closed-in-range ()
16397 "Sparse tree of items closed in a certain time range.
16398 Still experimental, may disappear in the future."
16399 (interactive)
16400 ;; Get the time interval from the user.
16401 (let* ((time1 (time-to-seconds
16402 (org-read-date nil 'to-time nil "Starting date: ")))
16403 (time2 (time-to-seconds
16404 (org-read-date nil 'to-time nil "End date:")))
16405 ;; callback function
16406 (callback (lambda ()
16407 (let ((time
16408 (time-to-seconds
16409 (apply 'encode-time
16410 (org-parse-time-string
16411 (match-string 1))))))
16412 ;; check if time in interval
16413 (and (>= time time1) (<= time time2))))))
16414 ;; make tree, check each match with the callback
16415 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16417 ;;;; Finish up
16419 (provide 'org)
16421 (run-hooks 'org-load-hook)
16423 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16425 ;;; org.el ends here