Fix critical bug in ID search.
[org-mode.git] / lisp / org.el
blob07d790f7410a4e752988c5119cc68e9268f3ade2
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.27trans
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-src)
92 (require 'org-footnote)
94 ;;;; Customization variables
96 ;;; Version
98 (defconst org-version "6.27trans"
99 "The version number of the file org.el.")
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let ((version (format "Org-mode version %s" org-version)))
106 (message version)
107 (if here
108 (insert version))))
110 ;;; Compatibility constants
112 ;;; The custom variables
114 (defgroup org nil
115 "Outline-based notes management and organizer."
116 :tag "Org"
117 :group 'outlines
118 :group 'hypermedia
119 :group 'calendar)
121 (defcustom org-load-hook nil
122 "Hook that is run after org.el has been loaded."
123 :group 'org
124 :type 'hook)
126 (defvar org-modules) ; defined below
127 (defvar org-modules-loaded nil
128 "Have the modules been loaded already?")
130 (defun org-load-modules-maybe (&optional force)
131 "Load all extensions listed in `org-modules'."
132 (when (or force (not org-modules-loaded))
133 (mapc (lambda (ext)
134 (condition-case nil (require ext)
135 (error (message "Problems while trying to load feature `%s'" ext))))
136 org-modules)
137 (setq org-modules-loaded t)))
139 (defun org-set-modules (var value)
140 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
141 (set var value)
142 (when (featurep 'org)
143 (org-load-modules-maybe 'force)))
145 (when (org-bound-and-true-p org-modules)
146 (let ((a (member 'org-infojs org-modules)))
147 (and a (setcar a 'org-jsinfo))))
149 (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)
150 "Modules that should always be loaded together with org.el.
151 If a description starts with <C>, the file is not part of Emacs
152 and loading it will require that you have downloaded and properly installed
153 the org-mode distribution.
155 You can also use this system to load external packages (i.e. neither Org
156 core modules, not modules from the CONTRIB directory). Just add symbols
157 to the end of the list. If the package is called org-xyz.el, then you need
158 to add the symbol `xyz', and the package must have a call to
160 (provide 'org-xyz)"
161 :group 'org
162 :set 'org-set-modules
163 :type
164 '(set :greedy t
165 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
166 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
167 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
168 (const :tag " id: Global IDs for identifying entries" org-id)
169 (const :tag " info: Links to Info nodes" org-info)
170 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
171 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
172 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
173 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
174 (const :tag " mew Links to Mew folders/messages" org-mew)
175 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
176 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
177 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
178 (const :tag " vm: Links to VM folders/messages" org-vm)
179 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
180 (const :tag " w3m: Special cut/paste from w3m to Org." org-w3m)
181 (const :tag " mouse: Additional mouse support" org-mouse)
183 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
184 (const :tag "C annotation-helper: Call Remember directly from Browser (OBSOLETE, use org-protocol)" org-annotation-helper)
185 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
186 (const :tag "C browser-url: Store link, directly from Browser (OBSOLETE, use org-protocol)" org-browser-url)
187 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
188 (const :tag "C collector: Collect properties into tables" org-collector)
189 (const :tag "C depend: TODO dependencies for Org-mode (PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
190 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
191 (const :tag "C eval: Include command output as text" org-eval)
192 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
193 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
194 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
195 (const :tag "C interactive-query: Interactive modification of tags query (PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
196 (const :tag "C jira Add a jira:ticket protocol to Org" org-jira)
197 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
198 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
199 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
200 (const :tag "C mtags: Support for muse-like tags" org-mtags)
201 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
202 (const :tag "C R: Computation using the R language" org-R)
203 (const :tag "C registry: A registry for Org links" org-registry)
204 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
205 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
206 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
207 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
208 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
209 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
211 (defcustom org-support-shift-select nil
212 "Non-nil means, make shift-cursor commands select text when possible.
214 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
215 selecting a region, or enlarge thusly regions started in this way.
216 In Org-mode, in special contexts, these same keys are used for other
217 purposes, important enough to compete with shift selection. Org tries
218 to balance these needs by supporting `shift-select-mode' outside these
219 special contexts, under control of this variable.
221 The default of this variable is nil, to avoid confusing behavior. Shifted
222 cursor keys will then execute Org commands in the following contexts:
223 - on a headline, changing TODO state (left/right) and priority (up/down)
224 - on a time stamp, changing the time
225 - in a plain list item, changing the bullet type
226 - in a property definition line, switching between allowed values
227 - in the BEGIN line of a clock table (changing the time block).
228 Outside these contexts, the commands will throw an error.
230 When this variable is t and the cursor is not in a special context,
231 Org-mode will support shift-selection for making and enlarging regions.
232 To make this more effective, the bullet cycling will no longer happen
233 anywhere in an item line, but only if the cursor is exactly on the bullet.
235 If you set this variable to the symbol `always', then the keys
236 will not be special in headlines, property lines, and item lines, to make
237 shift selection work there as well. If this is what you want, you can
238 use the following alternative commands: `C-c C-t' and `C-c ,' to
239 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
240 TODO sets, `C-c -' to cycle item bullet types, and properties can be
241 edited by hand or in column view.
243 However, when the cursor is on a timestamp, shift-cursor commands
244 will still edit the time stamp - this is just too good to give up.
246 XEmacs user should have this variable set to nil, because shift-select-mode
247 is Emacs 23 only."
248 :group 'org
249 :type '(choice
250 (const :tag "Never" nil)
251 (const :tag "When outside special context" t)
252 (const :tag "Everywhere except timestamps" always)))
254 (defgroup org-startup nil
255 "Options concerning startup of Org-mode."
256 :tag "Org Startup"
257 :group 'org)
259 (defcustom org-startup-folded t
260 "Non-nil means, entering Org-mode will switch to OVERVIEW.
261 This can also be configured on a per-file basis by adding one of
262 the following lines anywhere in the buffer:
264 #+STARTUP: fold
265 #+STARTUP: nofold
266 #+STARTUP: content"
267 :group 'org-startup
268 :type '(choice
269 (const :tag "nofold: show all" nil)
270 (const :tag "fold: overview" t)
271 (const :tag "content: all headlines" content)))
273 (defcustom org-startup-truncated t
274 "Non-nil means, entering Org-mode will set `truncate-lines'.
275 This is useful since some lines containing links can be very long and
276 uninteresting. Also tables look terrible when wrapped."
277 :group 'org-startup
278 :type 'boolean)
280 (defcustom org-startup-align-all-tables nil
281 "Non-nil means, align all tables when visiting a file.
282 This is useful when the column width in tables is forced with <N> cookies
283 in table fields. Such tables will look correct only after the first re-align.
284 This can also be configured on a per-file basis by adding one of
285 the following lines anywhere in the buffer:
286 #+STARTUP: align
287 #+STARTUP: noalign"
288 :group 'org-startup
289 :type 'boolean)
291 (defcustom org-insert-mode-line-in-empty-file nil
292 "Non-nil means insert the first line setting Org-mode in empty files.
293 When the function `org-mode' is called interactively in an empty file, this
294 normally means that the file name does not automatically trigger Org-mode.
295 To ensure that the file will always be in Org-mode in the future, a
296 line enforcing Org-mode will be inserted into the buffer, if this option
297 has been set."
298 :group 'org-startup
299 :type 'boolean)
301 (defcustom org-replace-disputed-keys nil
302 "Non-nil means use alternative key bindings for some keys.
303 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
304 These keys are also used by other packages like shift-selection-mode'
305 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
306 If you want to use Org-mode together with one of these other modes,
307 or more generally if you would like to move some Org-mode commands to
308 other keys, set this variable and configure the keys with the variable
309 `org-disputed-keys'.
311 This option is only relevant at load-time of Org-mode, and must be set
312 *before* org.el is loaded. Changing it requires a restart of Emacs to
313 become effective."
314 :group 'org-startup
315 :type 'boolean)
317 (defcustom org-use-extra-keys nil
318 "Non-nil means use extra key sequence definitions for certain
319 commands. This happens automatically if you run XEmacs or if
320 window-system is nil. This variable lets you do the same
321 manually. You must set it before loading org.
323 Example: on Carbon Emacs 22 running graphically, with an external
324 keyboard on a Powerbook, the default way of setting M-left might
325 not work for either Alt or ESC. Setting this variable will make
326 it work for ESC."
327 :group 'org-startup
328 :type 'boolean)
330 (if (fboundp 'defvaralias)
331 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
333 (defcustom org-disputed-keys
334 '(([(shift up)] . [(meta p)])
335 ([(shift down)] . [(meta n)])
336 ([(shift left)] . [(meta -)])
337 ([(shift right)] . [(meta +)])
338 ([(control shift right)] . [(meta shift +)])
339 ([(control shift left)] . [(meta shift -)]))
340 "Keys for which Org-mode and other modes compete.
341 This is an alist, cars are the default keys, second element specifies
342 the alternative to use when `org-replace-disputed-keys' is t.
344 Keys can be specified in any syntax supported by `define-key'.
345 The value of this option takes effect only at Org-mode's startup,
346 therefore you'll have to restart Emacs to apply it after changing."
347 :group 'org-startup
348 :type 'alist)
350 (defun org-key (key)
351 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
352 Or return the original if not disputed."
353 (if org-replace-disputed-keys
354 (let* ((nkey (key-description key))
355 (x (org-find-if (lambda (x)
356 (equal (key-description (car x)) nkey))
357 org-disputed-keys)))
358 (if x (cdr x) key))
359 key))
361 (defun org-find-if (predicate seq)
362 (catch 'exit
363 (while seq
364 (if (funcall predicate (car seq))
365 (throw 'exit (car seq))
366 (pop seq)))))
368 (defun org-defkey (keymap key def)
369 "Define a key, possibly translated, as returned by `org-key'."
370 (define-key keymap (org-key key) def))
372 (defcustom org-ellipsis nil
373 "The ellipsis to use in the Org-mode outline.
374 When nil, just use the standard three dots. When a string, use that instead,
375 When a face, use the standard 3 dots, but with the specified face.
376 The change affects only Org-mode (which will then use its own display table).
377 Changing this requires executing `M-x org-mode' in a buffer to become
378 effective."
379 :group 'org-startup
380 :type '(choice (const :tag "Default" nil)
381 (face :tag "Face" :value org-warning)
382 (string :tag "String" :value "...#")))
384 (defvar org-display-table nil
385 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
387 (defgroup org-keywords nil
388 "Keywords in Org-mode."
389 :tag "Org Keywords"
390 :group 'org)
392 (defcustom org-deadline-string "DEADLINE:"
393 "String to mark deadline entries.
394 A deadline is this string, followed by a time stamp. Should be a word,
395 terminated by a colon. You can insert a schedule keyword and
396 a timestamp with \\[org-deadline].
397 Changes become only effective after restarting Emacs."
398 :group 'org-keywords
399 :type 'string)
401 (defcustom org-scheduled-string "SCHEDULED:"
402 "String to mark scheduled TODO entries.
403 A schedule is this string, followed by a time stamp. Should be a word,
404 terminated by a colon. You can insert a schedule keyword and
405 a timestamp with \\[org-schedule].
406 Changes become only effective after restarting Emacs."
407 :group 'org-keywords
408 :type 'string)
410 (defcustom org-closed-string "CLOSED:"
411 "String used as the prefix for timestamps logging closing a TODO entry."
412 :group 'org-keywords
413 :type 'string)
415 (defcustom org-clock-string "CLOCK:"
416 "String used as prefix for timestamps clocking work hours on an item."
417 :group 'org-keywords
418 :type 'string)
420 (defcustom org-comment-string "COMMENT"
421 "Entries starting with this keyword will never be exported.
422 An entry can be toggled between COMMENT and normal with
423 \\[org-toggle-comment].
424 Changes become only effective after restarting Emacs."
425 :group 'org-keywords
426 :type 'string)
428 (defcustom org-quote-string "QUOTE"
429 "Entries starting with this keyword will be exported in fixed-width font.
430 Quoting applies only to the text in the entry following the headline, and does
431 not extend beyond the next headline, even if that is lower level.
432 An entry can be toggled between QUOTE and normal with
433 \\[org-toggle-fixed-width-section]."
434 :group 'org-keywords
435 :type 'string)
437 (defconst org-repeat-re
438 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
439 "Regular expression for specifying repeated events.
440 After a match, group 1 contains the repeat expression.")
442 (defgroup org-structure nil
443 "Options concerning the general structure of Org-mode files."
444 :tag "Org Structure"
445 :group 'org)
447 (defgroup org-reveal-location nil
448 "Options about how to make context of a location visible."
449 :tag "Org Reveal Location"
450 :group 'org-structure)
452 (defconst org-context-choice
453 '(choice
454 (const :tag "Always" t)
455 (const :tag "Never" nil)
456 (repeat :greedy t :tag "Individual contexts"
457 (cons
458 (choice :tag "Context"
459 (const agenda)
460 (const org-goto)
461 (const occur-tree)
462 (const tags-tree)
463 (const link-search)
464 (const mark-goto)
465 (const bookmark-jump)
466 (const isearch)
467 (const default))
468 (boolean))))
469 "Contexts for the reveal options.")
471 (defcustom org-show-hierarchy-above '((default . t))
472 "Non-nil means, show full hierarchy when revealing a location.
473 Org-mode often shows locations in an org-mode file which might have
474 been invisible before. When this is set, the hierarchy of headings
475 above the exposed location is shown.
476 Turning this off for example for sparse trees makes them very compact.
477 Instead of t, this can also be an alist specifying this option for different
478 contexts. Valid contexts are
479 agenda when exposing an entry from the agenda
480 org-goto when using the command `org-goto' on key C-c C-j
481 occur-tree when using the command `org-occur' on key C-c /
482 tags-tree when constructing a sparse tree based on tags matches
483 link-search when exposing search matches associated with a link
484 mark-goto when exposing the jump goal of a mark
485 bookmark-jump when exposing a bookmark location
486 isearch when exiting from an incremental search
487 default default for all contexts not set explicitly"
488 :group 'org-reveal-location
489 :type org-context-choice)
491 (defcustom org-show-following-heading '((default . nil))
492 "Non-nil means, show following heading when revealing a location.
493 Org-mode often shows locations in an org-mode file which might have
494 been invisible before. When this is set, the heading following the
495 match is shown.
496 Turning this off for example for sparse trees makes them very compact,
497 but makes it harder to edit the location of the match. In such a case,
498 use the command \\[org-reveal] to show more context.
499 Instead of t, this can also be an alist specifying this option for different
500 contexts. See `org-show-hierarchy-above' for valid contexts."
501 :group 'org-reveal-location
502 :type org-context-choice)
504 (defcustom org-show-siblings '((default . nil) (isearch t))
505 "Non-nil means, show all sibling heading when revealing a location.
506 Org-mode often shows locations in an org-mode file which might have
507 been invisible before. When this is set, the sibling of the current entry
508 heading are all made visible. If `org-show-hierarchy-above' is t,
509 the same happens on each level of the hierarchy above the current entry.
511 By default this is on for the isearch context, off for all other contexts.
512 Turning this off for example for sparse trees makes them very compact,
513 but makes it harder to edit the location of the match. In such a case,
514 use the command \\[org-reveal] to show more context.
515 Instead of t, this can also be an alist specifying this option for different
516 contexts. See `org-show-hierarchy-above' for valid contexts."
517 :group 'org-reveal-location
518 :type org-context-choice)
520 (defcustom org-show-entry-below '((default . nil))
521 "Non-nil means, show the entry below a headline when revealing a location.
522 Org-mode often shows locations in an org-mode file which might have
523 been invisible before. When this is set, the text below the headline that is
524 exposed is also shown.
526 By default this is off for all contexts.
527 Instead of t, this can also be an alist specifying this option for different
528 contexts. See `org-show-hierarchy-above' for valid contexts."
529 :group 'org-reveal-location
530 :type org-context-choice)
532 (defcustom org-indirect-buffer-display 'other-window
533 "How should indirect tree buffers be displayed?
534 This applies to indirect buffers created with the commands
535 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
536 Valid values are:
537 current-window Display in the current window
538 other-window Just display in another window.
539 dedicated-frame Create one new frame, and re-use it each time.
540 new-frame Make a new frame each time. Note that in this case
541 previously-made indirect buffers are kept, and you need to
542 kill these buffers yourself."
543 :group 'org-structure
544 :group 'org-agenda-windows
545 :type '(choice
546 (const :tag "In current window" current-window)
547 (const :tag "In current frame, other window" other-window)
548 (const :tag "Each time a new frame" new-frame)
549 (const :tag "One dedicated frame" dedicated-frame)))
551 (defgroup org-cycle nil
552 "Options concerning visibility cycling in Org-mode."
553 :tag "Org Cycle"
554 :group 'org-structure)
556 (defcustom org-cycle-max-level nil
557 "Maximum level which should still be subject to visibility cycling.
558 Levels higher than this will, for cycling, be treated as text, not a headline.
559 When `org-odd-levels-only' is set, a value of N in this variable actually
560 means 2N-1 stars as the limiting headline.
561 When nil, cycle all levels.
562 Note that the limiting level of cycling is also influenced by
563 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
564 `org-inlinetask-min-level' is, cycling will be limited to levels one less
565 than its value."
566 :group 'org-cycle
567 :type '(choice
568 (const :tag "No limit" nil)
569 (integer :tag "Maximum level")))
571 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
572 "Names of drawers. Drawers are not opened by cycling on the headline above.
573 Drawers only open with a TAB on the drawer line itself. A drawer looks like
574 this:
575 :DRAWERNAME:
576 .....
577 :END:
578 The drawer \"PROPERTIES\" is special for capturing properties through
579 the property API.
581 Drawers can be defined on the per-file basis with a line like:
583 #+DRAWERS: HIDDEN STATE PROPERTIES"
584 :group 'org-structure
585 :group 'org-cycle
586 :type '(repeat (string :tag "Drawer Name")))
588 (defcustom org-hide-block-startup nil
589 "Non-nil means, , entering Org-mode will fold all blocks.
590 This can also be set in on a per-file basis with
592 #+STARTUP: hideblocks
593 #+STARTUP: showblocks"
594 :group 'org-startup
595 :group 'org-cycle
596 :type 'boolean)
598 (defcustom org-cycle-global-at-bob nil
599 "Cycle globally if cursor is at beginning of buffer and not at a headline.
600 This makes it possible to do global cycling without having to use S-TAB or
601 C-u TAB. For this special case to work, the first line of the buffer
602 must not be a headline - it may be empty or some other text. When used in
603 this way, `org-cycle-hook' is disables temporarily, to make sure the
604 cursor stays at the beginning of the buffer.
605 When this option is nil, don't do anything special at the beginning
606 of the buffer."
607 :group 'org-cycle
608 :type 'boolean)
610 (defcustom org-cycle-emulate-tab t
611 "Where should `org-cycle' emulate TAB.
612 nil Never
613 white Only in completely white lines
614 whitestart Only at the beginning of lines, before the first non-white char
615 t Everywhere except in headlines
616 exc-hl-bol Everywhere except at the start of a headline
617 If TAB is used in a place where it does not emulate TAB, the current subtree
618 visibility is cycled."
619 :group 'org-cycle
620 :type '(choice (const :tag "Never" nil)
621 (const :tag "Only in completely white lines" white)
622 (const :tag "Before first char in a line" whitestart)
623 (const :tag "Everywhere except in headlines" t)
624 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
627 (defcustom org-cycle-separator-lines 2
628 "Number of empty lines needed to keep an empty line between collapsed trees.
629 If you leave an empty line between the end of a subtree and the following
630 headline, this empty line is hidden when the subtree is folded.
631 Org-mode will leave (exactly) one empty line visible if the number of
632 empty lines is equal or larger to the number given in this variable.
633 So the default 2 means, at least 2 empty lines after the end of a subtree
634 are needed to produce free space between a collapsed subtree and the
635 following headline.
637 Special case: when 0, never leave empty lines in collapsed view."
638 :group 'org-cycle
639 :type 'integer)
640 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
642 (defcustom org-pre-cycle-hook nil
643 "Hook that is run before visibility cycling is happening.
644 The function(s) in this hook must accept a single argument which indicates
645 the new state that will be set right after running this hook. The
646 argument is a symbol. Before a global state change, it can have the values
647 `overview', `content', or `all'. Before a local state change, it can have
648 the values `folded', `children', or `subtree'."
649 :group 'org-cycle
650 :type 'hook)
652 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
653 org-cycle-hide-drawers
654 org-cycle-show-empty-lines
655 org-optimize-window-after-visibility-change)
656 "Hook that is run after `org-cycle' has changed the buffer visibility.
657 The function(s) in this hook must accept a single argument which indicates
658 the new state that was set by the most recent `org-cycle' command. The
659 argument is a symbol. After a global state change, it can have the values
660 `overview', `content', or `all'. After a local state change, it can have
661 the values `folded', `children', or `subtree'."
662 :group 'org-cycle
663 :type 'hook)
665 (defgroup org-edit-structure nil
666 "Options concerning structure editing in Org-mode."
667 :tag "Org Edit Structure"
668 :group 'org-structure)
670 (defcustom org-odd-levels-only nil
671 "Non-nil means, skip even levels and only use odd levels for the outline.
672 This has the effect that two stars are being added/taken away in
673 promotion/demotion commands. It also influences how levels are
674 handled by the exporters.
675 Changing it requires restart of `font-lock-mode' to become effective
676 for fontification also in regions already fontified.
677 You may also set this on a per-file basis by adding one of the following
678 lines to the buffer:
680 #+STARTUP: odd
681 #+STARTUP: oddeven"
682 :group 'org-edit-structure
683 :group 'org-font-lock
684 :type 'boolean)
686 (defcustom org-adapt-indentation t
687 "Non-nil means, adapt indentation when promoting and demoting.
688 When this is set and the *entire* text in an entry is indented, the
689 indentation is increased by one space in a demotion command, and
690 decreased by one in a promotion command. If any line in the entry
691 body starts at column 0, indentation is not changed at all.
693 This variable also influences how property drawers and planning
694 information is inserted. When t, these lines drawers will be inserted
695 indented. When nil, they will not be indented."
696 :group 'org-edit-structure
697 :type 'boolean)
699 (defcustom org-special-ctrl-a/e nil
700 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
702 When t, `C-a' will bring back the cursor to the beginning of the
703 headline text, i.e. after the stars and after a possible TODO keyword.
704 In an item, this will be the position after the bullet.
705 When the cursor is already at that position, another `C-a' will bring
706 it to the beginning of the line.
708 `C-e' will jump to the end of the headline, ignoring the presence of tags
709 in the headline. A second `C-e' will then jump to the true end of the
710 line, after any tags.
712 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
713 and only a directly following, identical keypress will bring the cursor
714 to the special positions.
716 This may also be a cons cell where the behavior for `C-a' and `C-e' is
717 set separately."
718 :group 'org-edit-structure
719 :type '(choice
720 (const :tag "off" nil)
721 (const :tag "after stars/bullet and before tags first" t)
722 (const :tag "true line boundary first" reversed)
723 (cons :tag "Set C-a and C-e separately"
724 (choice :tag "Special C-a"
725 (const :tag "off" nil)
726 (const :tag "after stars/bullet first" t)
727 (const :tag "before stars/bullet first" reversed))
728 (choice :tag "Special C-e"
729 (const :tag "off" nil)
730 (const :tag "before tags first" t)
731 (const :tag "after tags first" reversed)))))
732 (if (fboundp 'defvaralias)
733 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
735 (defcustom org-special-ctrl-k nil
736 "Non-nil means `C-k' will behave specially in headlines.
737 When nil, `C-k' will call the default `kill-line' command.
738 When t, the following will happen while the cursor is in the headline:
740 - When the cursor is at the beginning of a headline, kill the entire
741 line and possible the folded subtree below the line.
742 - When in the middle of the headline text, kill the headline up to the tags.
743 - When after the headline text, kill the tags."
744 :group 'org-edit-structure
745 :type 'boolean)
747 (defcustom org-yank-folded-subtrees t
748 "Non-nil means, when yanking subtrees, fold them.
749 If the kill is a single subtree, or a sequence of subtrees, i.e. if
750 it starts with a heading and all other headings in it are either children
751 or siblings, then fold all the subtrees. However, do this only if no
752 text after the yank would be swallowed into a folded tree by this action."
753 :group 'org-edit-structure
754 :type 'boolean)
756 (defcustom org-yank-adjusted-subtrees nil
757 "Non-nil means, when yanking subtrees, adjust the level.
758 With this setting, `org-paste-subtree' is used to insert the subtree, see
759 this function for details."
760 :group 'org-edit-structure
761 :type 'boolean)
763 (defcustom org-M-RET-may-split-line '((default . t))
764 "Non-nil means, M-RET will split the line at the cursor position.
765 When nil, it will go to the end of the line before making a
766 new line.
767 You may also set this option in a different way for different
768 contexts. Valid contexts are:
770 headline when creating a new headline
771 item when creating a new item
772 table in a table field
773 default the value to be used for all contexts not explicitly
774 customized"
775 :group 'org-structure
776 :group 'org-table
777 :type '(choice
778 (const :tag "Always" t)
779 (const :tag "Never" nil)
780 (repeat :greedy t :tag "Individual contexts"
781 (cons
782 (choice :tag "Context"
783 (const headline)
784 (const item)
785 (const table)
786 (const default))
787 (boolean)))))
790 (defcustom org-insert-heading-respect-content nil
791 "Non-nil means, insert new headings after the current subtree.
792 When nil, the new heading is created directly after the current line.
793 The commands \\[org-insert-heading-respect-content] and
794 \\[org-insert-todo-heading-respect-content] turn this variable on
795 for the duration of the command."
796 :group 'org-structure
797 :type 'boolean)
799 (defcustom org-blank-before-new-entry '((heading . auto)
800 (plain-list-item . auto))
801 "Should `org-insert-heading' leave a blank line before new heading/item?
802 The value is an alist, with `heading' and `plain-list-item' as car,
803 and a boolean flag as cdr. For plain lists, if the variable
804 `org-empty-line-terminates-plain-lists' is set, the setting here
805 is ignored and no empty line is inserted, to keep the list in tact."
806 :group 'org-edit-structure
807 :type '(list
808 (cons (const heading)
809 (choice (const :tag "Never" nil)
810 (const :tag "Always" t)
811 (const :tag "Auto" auto)))
812 (cons (const plain-list-item)
813 (choice (const :tag "Never" nil)
814 (const :tag "Always" t)
815 (const :tag "Auto" auto)))))
817 (defcustom org-insert-heading-hook nil
818 "Hook being run after inserting a new heading."
819 :group 'org-edit-structure
820 :type 'hook)
822 (defcustom org-enable-fixed-width-editor t
823 "Non-nil means, lines starting with \":\" are treated as fixed-width.
824 This currently only means, they are never auto-wrapped.
825 When nil, such lines will be treated like ordinary lines.
826 See also the QUOTE keyword."
827 :group 'org-edit-structure
828 :type 'boolean)
831 (defcustom org-goto-auto-isearch t
832 "Non-nil means, typing characters in org-goto starts incremental search."
833 :group 'org-edit-structure
834 :type 'boolean)
836 (defgroup org-sparse-trees nil
837 "Options concerning sparse trees in Org-mode."
838 :tag "Org Sparse Trees"
839 :group 'org-structure)
841 (defcustom org-highlight-sparse-tree-matches t
842 "Non-nil means, highlight all matches that define a sparse tree.
843 The highlights will automatically disappear the next time the buffer is
844 changed by an edit command."
845 :group 'org-sparse-trees
846 :type 'boolean)
848 (defcustom org-remove-highlights-with-change t
849 "Non-nil means, any change to the buffer will remove temporary highlights.
850 Such highlights are created by `org-occur' and `org-clock-display'.
851 When nil, `C-c C-c needs to be used to get rid of the highlights.
852 The highlights created by `org-preview-latex-fragment' always need
853 `C-c C-c' to be removed."
854 :group 'org-sparse-trees
855 :group 'org-time
856 :type 'boolean)
859 (defcustom org-occur-hook '(org-first-headline-recenter)
860 "Hook that is run after `org-occur' has constructed a sparse tree.
861 This can be used to recenter the window to show as much of the structure
862 as possible."
863 :group 'org-sparse-trees
864 :type 'hook)
866 (defgroup org-imenu-and-speedbar nil
867 "Options concerning imenu and speedbar in Org-mode."
868 :tag "Org Imenu and Speedbar"
869 :group 'org-structure)
871 (defcustom org-imenu-depth 2
872 "The maximum level for Imenu access to Org-mode headlines.
873 This also applied for speedbar access."
874 :group 'org-imenu-and-speedbar
875 :type 'integer)
877 (defgroup org-table nil
878 "Options concerning tables in Org-mode."
879 :tag "Org Table"
880 :group 'org)
882 (defcustom org-enable-table-editor 'optimized
883 "Non-nil means, lines starting with \"|\" are handled by the table editor.
884 When nil, such lines will be treated like ordinary lines.
886 When equal to the symbol `optimized', the table editor will be optimized to
887 do the following:
888 - Automatic overwrite mode in front of whitespace in table fields.
889 This makes the structure of the table stay in tact as long as the edited
890 field does not exceed the column width.
891 - Minimize the number of realigns. Normally, the table is aligned each time
892 TAB or RET are pressed to move to another field. With optimization this
893 happens only if changes to a field might have changed the column width.
894 Optimization requires replacing the functions `self-insert-command',
895 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
896 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
897 very good at guessing when a re-align will be necessary, but you can always
898 force one with \\[org-ctrl-c-ctrl-c].
900 If you would like to use the optimized version in Org-mode, but the
901 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
903 This variable can be used to turn on and off the table editor during a session,
904 but in order to toggle optimization, a restart is required.
906 See also the variable `org-table-auto-blank-field'."
907 :group 'org-table
908 :type '(choice
909 (const :tag "off" nil)
910 (const :tag "on" t)
911 (const :tag "on, optimized" optimized)))
913 (defcustom org-self-insert-cluster-for-undo t
914 "Non-nil means cluster self-insert commands for undo when possible.
915 If this is set, then, like in the Emacs command loop, 20 consequtive
916 characters will be undone together.
917 This is configurable, because there is some impact on typing performance."
918 :group 'org-table
919 :type 'boolean)
921 (defcustom org-table-tab-recognizes-table.el t
922 "Non-nil means, TAB will automatically notice a table.el table.
923 When it sees such a table, it moves point into it and - if necessary -
924 calls `table-recognize-table'."
925 :group 'org-table-editing
926 :type 'boolean)
928 (defgroup org-link nil
929 "Options concerning links in Org-mode."
930 :tag "Org Link"
931 :group 'org)
933 (defvar org-link-abbrev-alist-local nil
934 "Buffer-local version of `org-link-abbrev-alist', which see.
935 The value of this is taken from the #+LINK lines.")
936 (make-variable-buffer-local 'org-link-abbrev-alist-local)
938 (defcustom org-link-abbrev-alist nil
939 "Alist of link abbreviations.
940 The car of each element is a string, to be replaced at the start of a link.
941 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
942 links in Org-mode buffers can have an optional tag after a double colon, e.g.
944 [[linkkey:tag][description]]
946 The 'linkkey' must be a word word, starting with a letter, followed
947 by letters, numbers, '-' or '_'.
949 If REPLACE is a string, the tag will simply be appended to create the link.
950 If the string contains \"%s\", the tag will be inserted there. Alternatively,
951 the placeholder \"%h\" will cause a url-encoded version of the tag to
952 be inserted at that point (see the function `url-hexify-string').
954 REPLACE may also be a function that will be called with the tag as the
955 only argument to create the link, which should be returned as a string.
957 See the manual for examples."
958 :group 'org-link
959 :type '(repeat
960 (cons
961 (string :tag "Protocol")
962 (choice
963 (string :tag "Format")
964 (function)))))
966 (defcustom org-descriptive-links t
967 "Non-nil means, hide link part and only show description of bracket links.
968 Bracket links are like [[link][description]]. This variable sets the initial
969 state in new org-mode buffers. The setting can then be toggled on a
970 per-buffer basis from the Org->Hyperlinks menu."
971 :group 'org-link
972 :type 'boolean)
974 (defcustom org-link-file-path-type 'adaptive
975 "How the path name in file links should be stored.
976 Valid values are:
978 relative Relative to the current directory, i.e. the directory of the file
979 into which the link is being inserted.
980 absolute Absolute path, if possible with ~ for home directory.
981 noabbrev Absolute path, no abbreviation of home directory.
982 adaptive Use relative path for files in the current directory and sub-
983 directories of it. For other files, use an absolute path."
984 :group 'org-link
985 :type '(choice
986 (const relative)
987 (const absolute)
988 (const noabbrev)
989 (const adaptive)))
991 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
992 "Types of links that should be activated in Org-mode files.
993 This is a list of symbols, each leading to the activation of a certain link
994 type. In principle, it does not hurt to turn on most link types - there may
995 be a small gain when turning off unused link types. The types are:
997 bracket The recommended [[link][description]] or [[link]] links with hiding.
998 angular Links in angular brackets that may contain whitespace like
999 <bbdb:Carsten Dominik>.
1000 plain Plain links in normal text, no whitespace, like http://google.com.
1001 radio Text that is matched by a radio target, see manual for details.
1002 tag Tag settings in a headline (link to tag search).
1003 date Time stamps (link to calendar).
1004 footnote Footnote labels.
1006 Changing this variable requires a restart of Emacs to become effective."
1007 :group 'org-link
1008 :type '(set :greedy t
1009 (const :tag "Double bracket links (new style)" bracket)
1010 (const :tag "Angular bracket links (old style)" angular)
1011 (const :tag "Plain text links" plain)
1012 (const :tag "Radio target matches" radio)
1013 (const :tag "Tags" tag)
1014 (const :tag "Timestamps" date)
1015 (const :tag "Footnotes" footnote)))
1017 (defcustom org-make-link-description-function nil
1018 "Function to use to generate link descriptions from links. If
1019 nil the link location will be used. This function must take two
1020 parameters; the first is the link and the second the description
1021 org-insert-link has generated, and should return the description
1022 to use."
1023 :group 'org-link
1024 :type 'function)
1026 (defgroup org-link-store nil
1027 "Options concerning storing links in Org-mode."
1028 :tag "Org Store Link"
1029 :group 'org-link)
1031 (defcustom org-email-link-description-format "Email %c: %.30s"
1032 "Format of the description part of a link to an email or usenet message.
1033 The following %-escapes will be replaced by corresponding information:
1035 %F full \"From\" field
1036 %f name, taken from \"From\" field, address if no name
1037 %T full \"To\" field
1038 %t first name in \"To\" field, address if no name
1039 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1040 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1041 %s subject
1042 %m message-id.
1044 You may use normal field width specification between the % and the letter.
1045 This is for example useful to limit the length of the subject.
1047 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1048 :group 'org-link-store
1049 :type 'string)
1051 (defcustom org-from-is-user-regexp
1052 (let (r1 r2)
1053 (when (and user-mail-address (not (string= user-mail-address "")))
1054 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1055 (when (and user-full-name (not (string= user-full-name "")))
1056 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1057 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1058 "Regexp matched against the \"From:\" header of an email or usenet message.
1059 It should match if the message is from the user him/herself."
1060 :group 'org-link-store
1061 :type 'regexp)
1063 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1064 "Non-nil means, storing a link to an Org file will use entry IDs.
1066 Note that before this variable is even considered, org-id must be loaded,
1067 to please customize `org-modules' and turn it on.
1069 The variable can have the following values:
1071 t Create an ID if needed to make a link to the current entry.
1073 create-if-interactive
1074 If `org-store-link' is called directly (interactively, as a user
1075 command), do create an ID to support the link. But when doing the
1076 job for remember, only use the ID if it already exists. The
1077 purpose of this setting is to avoid proliferation of unwanted
1078 IDs, just because you happen to be in an Org file when you
1079 call `org-remember' that automatically and preemptively
1080 creates a link. If you do want to get an ID link in a remember
1081 template to an entry not having an ID, create it first by
1082 explicitly creating a link to it, using `C-c C-l' first.
1084 use-existing
1085 Use existing ID, do not create one.
1087 nil Never use an ID to make a link, instead link using a text search for
1088 the headline text."
1089 :group 'org-link-store
1090 :type '(choice
1091 (const :tag "Create ID to make link" t)
1092 (const :tag "Create if storing link interactively"
1093 create-if-interactive)
1094 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1095 create-if-interactive-and-no-custom-id)
1096 (const :tag "Only use existing" use-existing)
1097 (const :tag "Do not use ID to create link" nil)))
1099 (defcustom org-context-in-file-links t
1100 "Non-nil means, file links from `org-store-link' contain context.
1101 A search string will be added to the file name with :: as separator and
1102 used to find the context when the link is activated by the command
1103 `org-open-at-point'.
1104 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1105 negates this setting for the duration of the command."
1106 :group 'org-link-store
1107 :type 'boolean)
1109 (defcustom org-keep-stored-link-after-insertion nil
1110 "Non-nil means, keep link in list for entire session.
1112 The command `org-store-link' adds a link pointing to the current
1113 location to an internal list. These links accumulate during a session.
1114 The command `org-insert-link' can be used to insert links into any
1115 Org-mode file (offering completion for all stored links). When this
1116 option is nil, every link which has been inserted once using \\[org-insert-link]
1117 will be removed from the list, to make completing the unused links
1118 more efficient."
1119 :group 'org-link-store
1120 :type 'boolean)
1122 (defgroup org-link-follow nil
1123 "Options concerning following links in Org-mode."
1124 :tag "Org Follow Link"
1125 :group 'org-link)
1127 (defcustom org-link-translation-function nil
1128 "Function to translate links with different syntax to Org syntax.
1129 This can be used to translate links created for example by the Planner
1130 or emacs-wiki packages to Org syntax.
1131 The function must accept two parameters, a TYPE containing the link
1132 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1133 which is everything after the link protocol. It should return a cons
1134 with possibly modified values of type and path.
1135 Org contains a function for this, so if you set this variable to
1136 `org-translate-link-from-planner', you should be able follow many
1137 links created by planner."
1138 :group 'org-link-follow
1139 :type 'function)
1141 (defcustom org-follow-link-hook nil
1142 "Hook that is run after a link has been followed."
1143 :group 'org-link-follow
1144 :type 'hook)
1146 (defcustom org-tab-follows-link nil
1147 "Non-nil means, on links TAB will follow the link.
1148 Needs to be set before org.el is loaded.
1149 This really should not be used, it does not make sense, and the
1150 implementation is bad."
1151 :group 'org-link-follow
1152 :type 'boolean)
1154 (defcustom org-return-follows-link nil
1155 "Non-nil means, on links RET will follow the link.
1156 Needs to be set before org.el is loaded."
1157 :group 'org-link-follow
1158 :type 'boolean)
1160 (defcustom org-mouse-1-follows-link
1161 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1162 "Non-nil means, mouse-1 on a link will follow the link.
1163 A longer mouse click will still set point. Does not work on XEmacs.
1164 Needs to be set before org.el is loaded."
1165 :group 'org-link-follow
1166 :type 'boolean)
1168 (defcustom org-mark-ring-length 4
1169 "Number of different positions to be recorded in the ring
1170 Changing this requires a restart of Emacs to work correctly."
1171 :group 'org-link-follow
1172 :type 'integer)
1174 (defcustom org-link-frame-setup
1175 '((vm . vm-visit-folder-other-frame)
1176 (gnus . gnus-other-frame)
1177 (file . find-file-other-window))
1178 "Setup the frame configuration for following links.
1179 When following a link with Emacs, it may often be useful to display
1180 this link in another window or frame. This variable can be used to
1181 set this up for the different types of links.
1182 For VM, use any of
1183 `vm-visit-folder'
1184 `vm-visit-folder-other-frame'
1185 For Gnus, use any of
1186 `gnus'
1187 `gnus-other-frame'
1188 `org-gnus-no-new-news'
1189 For FILE, use any of
1190 `find-file'
1191 `find-file-other-window'
1192 `find-file-other-frame'
1193 For the calendar, use the variable `calendar-setup'.
1194 For BBDB, it is currently only possible to display the matches in
1195 another window."
1196 :group 'org-link-follow
1197 :type '(list
1198 (cons (const vm)
1199 (choice
1200 (const vm-visit-folder)
1201 (const vm-visit-folder-other-window)
1202 (const vm-visit-folder-other-frame)))
1203 (cons (const gnus)
1204 (choice
1205 (const gnus)
1206 (const gnus-other-frame)
1207 (const org-gnus-no-new-news)))
1208 (cons (const file)
1209 (choice
1210 (const find-file)
1211 (const find-file-other-window)
1212 (const find-file-other-frame)))))
1214 (defcustom org-display-internal-link-with-indirect-buffer nil
1215 "Non-nil means, use indirect buffer to display infile links.
1216 Activating internal links (from one location in a file to another location
1217 in the same file) normally just jumps to the location. When the link is
1218 activated with a C-u prefix (or with mouse-3), the link is displayed in
1219 another window. When this option is set, the other window actually displays
1220 an indirect buffer clone of the current buffer, to avoid any visibility
1221 changes to the current buffer."
1222 :group 'org-link-follow
1223 :type 'boolean)
1225 (defcustom org-open-non-existing-files nil
1226 "Non-nil means, `org-open-file' will open non-existing files.
1227 When nil, an error will be generated.
1228 This variable applies only to external applications because they
1229 might choke on non-existing files. If the link is to a file that
1230 will be openend in Emacs, the variable is ignored."
1231 :group 'org-link-follow
1232 :type 'boolean)
1234 (defcustom org-open-directory-means-index-dot-org nil
1235 "Non-nil means, a link to a directory really means to index.org.
1236 When nil, following a directory link will run dired or open a finder/explorer
1237 window on that directory."
1238 :group 'org-link-follow
1239 :type 'boolean)
1241 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1242 "Function and arguments to call for following mailto links.
1243 This is a list with the first element being a lisp function, and the
1244 remaining elements being arguments to the function. In string arguments,
1245 %a will be replaced by the address, and %s will be replaced by the subject
1246 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1247 :group 'org-link-follow
1248 :type '(choice
1249 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1250 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1251 (const :tag "message-mail" (message-mail "%a" "%s"))
1252 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1254 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1255 "Non-nil means, ask for confirmation before executing shell links.
1256 Shell links can be dangerous: just think about a link
1258 [[shell:rm -rf ~/*][Google Search]]
1260 This link would show up in your Org-mode document as \"Google Search\",
1261 but really it would remove your entire home directory.
1262 Therefore we advise against setting this variable to nil.
1263 Just change it to `y-or-n-p' if you want to confirm with a
1264 single keystroke rather than having to type \"yes\"."
1265 :group 'org-link-follow
1266 :type '(choice
1267 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1268 (const :tag "with y-or-n (faster)" y-or-n-p)
1269 (const :tag "no confirmation (dangerous)" nil)))
1271 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1272 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1273 Elisp links can be dangerous: just think about a link
1275 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1277 This link would show up in your Org-mode document as \"Google Search\",
1278 but really it would remove your entire home directory.
1279 Therefore we advise against setting this variable to nil.
1280 Just change it to `y-or-n-p' if you want to confirm with a
1281 single keystroke rather than having to type \"yes\"."
1282 :group 'org-link-follow
1283 :type '(choice
1284 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1285 (const :tag "with y-or-n (faster)" y-or-n-p)
1286 (const :tag "no confirmation (dangerous)" nil)))
1288 (defconst org-file-apps-defaults-gnu
1289 '((remote . emacs)
1290 (system . mailcap)
1291 (t . mailcap))
1292 "Default file applications on a UNIX or GNU/Linux system.
1293 See `org-file-apps'.")
1295 (defconst org-file-apps-defaults-macosx
1296 '((remote . emacs)
1297 (t . "open %s")
1298 (system . "open %s")
1299 ("ps.gz" . "gv %s")
1300 ("eps.gz" . "gv %s")
1301 ("dvi" . "xdvi %s")
1302 ("fig" . "xfig %s"))
1303 "Default file applications on a MacOS X system.
1304 The system \"open\" is known as a default, but we use X11 applications
1305 for some files for which the OS does not have a good default.
1306 See `org-file-apps'.")
1308 (defconst org-file-apps-defaults-windowsnt
1309 (list
1310 '(remote . emacs)
1311 (cons t
1312 (list (if (featurep 'xemacs)
1313 'mswindows-shell-execute
1314 'w32-shell-execute)
1315 "open" 'file))
1316 (cons 'system
1317 (list (if (featurep 'xemacs)
1318 'mswindows-shell-execute
1319 'w32-shell-execute)
1320 "open" 'file)))
1321 "Default file applications on a Windows NT system.
1322 The system \"open\" is used for most files.
1323 See `org-file-apps'.")
1325 (defcustom org-file-apps
1327 (auto-mode . emacs)
1328 ("\\.x?html?\\'" . default)
1329 ("\\.pdf\\'" . default)
1331 "External applications for opening `file:path' items in a document.
1332 Org-mode uses system defaults for different file types, but
1333 you can use this variable to set the application for a given file
1334 extension. The entries in this list are cons cells where the car identifies
1335 files and the cdr the corresponding command. Possible values for the
1336 file identifier are
1337 \"regex\" Regular expression matched against the file name. For backward
1338 compatibility, this can also be a string with only alphanumeric
1339 characters, which is then interpreted as an extension.
1340 `directory' Matches a directory
1341 `remote' Matches a remote file, accessible through tramp or efs.
1342 Remote files most likely should be visited through Emacs
1343 because external applications cannot handle such paths.
1344 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1345 so all files Emacs knows how to handle. Using this with
1346 command `emacs' will open most files in Emacs. Beware that this
1347 will also open html files inside Emacs, unless you add
1348 (\"html\" . default) to the list as well.
1349 t Default for files not matched by any of the other options.
1350 `system' The system command to open files, like `open' on Windows
1351 and Mac OS X, and mailcap under GNU/Linux. This is the command
1352 that will be selected if you call `C-c C-o' with a double
1353 `C-u C-u' prefix.
1355 Possible values for the command are:
1356 `emacs' The file will be visited by the current Emacs process.
1357 `default' Use the default application for this file type, which is the
1358 association for t in the list, most likely in the system-specific
1359 part.
1360 This can be used to overrule an unwanted setting in the
1361 system-specific variable.
1362 `system' Use the system command for opening files, like \"open\".
1363 This command is specified by the entry whose car is `system'.
1364 Most likely, the system-specific version of this variable
1365 does define this command, but you can overrule/replace it
1366 here.
1367 string A command to be executed by a shell; %s will be replaced
1368 by the path to the file.
1369 sexp A Lisp form which will be evaluated. The file path will
1370 be available in the Lisp variable `file'.
1371 For more examples, see the system specific constants
1372 `org-file-apps-defaults-macosx'
1373 `org-file-apps-defaults-windowsnt'
1374 `org-file-apps-defaults-gnu'."
1375 :group 'org-link-follow
1376 :type '(repeat
1377 (cons (choice :value ""
1378 (string :tag "Extension")
1379 (const :tag "System command to open files" system)
1380 (const :tag "Default for unrecognized files" t)
1381 (const :tag "Remote file" remote)
1382 (const :tag "Links to a directory" directory)
1383 (const :tag "Any files that have Emacs modes"
1384 auto-mode))
1385 (choice :value ""
1386 (const :tag "Visit with Emacs" emacs)
1387 (const :tag "Use default" default)
1388 (const :tag "Use the system command" system)
1389 (string :tag "Command")
1390 (sexp :tag "Lisp form")))))
1392 (defgroup org-refile nil
1393 "Options concerning refiling entries in Org-mode."
1394 :tag "Org Refile"
1395 :group 'org)
1397 (defcustom org-directory "~/org"
1398 "Directory with org files.
1399 This is just a default location to look for Org files. There is no need
1400 at all to put your files into this directory. It is only used in the
1401 following situations:
1403 1. When a remember template specifies a target file that is not an
1404 absolute path. The path will then be interpreted relative to
1405 `org-directory'
1406 2. When a remember note is filed away in an interactive way (when exiting the
1407 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1408 with `org-directory' as the default path."
1409 :group 'org-refile
1410 :group 'org-remember
1411 :type 'directory)
1413 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1414 "Default target for storing notes.
1415 Used by the hooks for remember.el. This can be a string, or nil to mean
1416 the value of `remember-data-file'.
1417 You can set this on a per-template basis with the variable
1418 `org-remember-templates'."
1419 :group 'org-refile
1420 :group 'org-remember
1421 :type '(choice
1422 (const :tag "Default from remember-data-file" nil)
1423 file))
1425 (defcustom org-goto-interface 'outline
1426 "The default interface to be used for `org-goto'.
1427 Allowed values are:
1428 outline The interface shows an outline of the relevant file
1429 and the correct heading is found by moving through
1430 the outline or by searching with incremental search.
1431 outline-path-completion Headlines in the current buffer are offered via
1432 completion. This is the interface also used by
1433 the refile command."
1434 :group 'org-refile
1435 :type '(choice
1436 (const :tag "Outline" outline)
1437 (const :tag "Outline-path-completion" outline-path-completion)))
1439 (defcustom org-goto-max-level 5
1440 "Maximum level to be considered when running org-goto with refile interface."
1441 :group 'org-refile
1442 :type 'integer)
1444 (defcustom org-reverse-note-order nil
1445 "Non-nil means, store new notes at the beginning of a file or entry.
1446 When nil, new notes will be filed to the end of a file or entry.
1447 This can also be a list with cons cells of regular expressions that
1448 are matched against file names, and values."
1449 :group 'org-remember
1450 :group 'org-refile
1451 :type '(choice
1452 (const :tag "Reverse always" t)
1453 (const :tag "Reverse never" nil)
1454 (repeat :tag "By file name regexp"
1455 (cons regexp boolean))))
1457 (defcustom org-refile-targets nil
1458 "Targets for refiling entries with \\[org-refile].
1459 This is list of cons cells. Each cell contains:
1460 - a specification of the files to be considered, either a list of files,
1461 or a symbol whose function or variable value will be used to retrieve
1462 a file name or a list of file names. If you use `org-agenda-files' for
1463 that, all agenda files will be scanned for targets. Nil means, consider
1464 headings in the current buffer.
1465 - A specification of how to find candidate refile targets. This may be
1466 any of:
1467 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1468 This tag has to be present in all target headlines, inheritance will
1469 not be considered.
1470 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1471 todo keyword.
1472 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1473 headlines that are refiling targets.
1474 - a cons cell (:level . N). Any headline of level N is considered a target.
1475 Note that, when `org-odd-levels-only' is set, level corresponds to
1476 order in hierarchy, not to the number of stars.
1477 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1478 Note that, when `org-odd-levels-only' is set, level corresponds to
1479 order in hierarchy, not to the number of stars.
1481 You can set the variable `org-refile-target-verify-function' to a function
1482 to verify each headline found by the simple critery above.
1484 When this variable is nil, all top-level headlines in the current buffer
1485 are used, equivalent to the value `((nil . (:level . 1))'."
1486 :group 'org-refile
1487 :type '(repeat
1488 (cons
1489 (choice :value org-agenda-files
1490 (const :tag "All agenda files" org-agenda-files)
1491 (const :tag "Current buffer" nil)
1492 (function) (variable) (file))
1493 (choice :tag "Identify target headline by"
1494 (cons :tag "Specific tag" (const :value :tag) (string))
1495 (cons :tag "TODO keyword" (const :value :todo) (string))
1496 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1497 (cons :tag "Level number" (const :value :level) (integer))
1498 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1500 (defcustom org-refile-target-verify-function nil
1501 "Function to verify if the headline at point should be a refile target.
1502 The function will be called without arguments, with point at the
1503 beginning of the headline. It should return t and leave point
1504 where it is if the headline is a valid target for refiling.
1506 If the target should not be selected, the function must return nil.
1507 In addition to this, it may move point to a place from where the search
1508 should be continued. For example, the function may decide that the entire
1509 subtree of the current entry should be excluded and move point to the end
1510 of the subtree."
1511 :group 'org-refile
1512 :type 'function)
1514 (defcustom org-refile-use-outline-path nil
1515 "Non-nil means, provide refile targets as paths.
1516 So a level 3 headline will be available as level1/level2/level3.
1518 When the value is `file', also include the file name (without directory)
1519 into the path. In this case, you can also stop the completion after
1520 the file name, to get entries inserted as top level in the file.
1522 When `full-file-path', include the full file path."
1523 :group 'org-refile
1524 :type '(choice
1525 (const :tag "Not" nil)
1526 (const :tag "Yes" t)
1527 (const :tag "Start with file name" file)
1528 (const :tag "Start with full file path" full-file-path)))
1530 (defcustom org-outline-path-complete-in-steps t
1531 "Non-nil means, complete the outline path in hierarchical steps.
1532 When Org-mode uses the refile interface to select an outline path
1533 \(see variable `org-refile-use-outline-path'), the completion of
1534 the path can be done is a single go, or if can be done in steps down
1535 the headline hierarchy. Going in steps is probably the best if you
1536 do not use a special completion package like `ido' or `icicles'.
1537 However, when using these packages, going in one step can be very
1538 fast, while still showing the whole path to the entry."
1539 :group 'org-refile
1540 :type 'boolean)
1542 (defcustom org-refile-allow-creating-parent-nodes nil
1543 "Non-nil means, allow to create new nodes as refile targets.
1544 New nodes are then created by adding \"/new node name\" to the completion
1545 of an existing node. When the value of this variable is `confirm',
1546 new node creation must be confirmed by the user (recommended)
1547 When nil, the completion must match an existing entry.
1549 Note that, if the new heading is not seen by the criteria
1550 listed in `org-refile-targets', multiple instances of the same
1551 heading would be created by trying again to file under the new
1552 heading."
1553 :group 'org-refile
1554 :type '(choice
1555 (const :tag "Never" nil)
1556 (const :tag "Always" t)
1557 (const :tag "Prompt for confirmation" confirm)))
1559 (defgroup org-todo nil
1560 "Options concerning TODO items in Org-mode."
1561 :tag "Org TODO"
1562 :group 'org)
1564 (defgroup org-progress nil
1565 "Options concerning Progress logging in Org-mode."
1566 :tag "Org Progress"
1567 :group 'org-time)
1569 (defvar org-todo-interpretation-widgets
1571 (:tag "Sequence (cycling hits every state)" sequence)
1572 (:tag "Type (cycling directly to DONE)" type))
1573 "The available interpretation symbols for customizing
1574 `org-todo-keywords'.
1575 Interested libraries should add to this list.")
1577 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1578 "List of TODO entry keyword sequences and their interpretation.
1579 \\<org-mode-map>This is a list of sequences.
1581 Each sequence starts with a symbol, either `sequence' or `type',
1582 indicating if the keywords should be interpreted as a sequence of
1583 action steps, or as different types of TODO items. The first
1584 keywords are states requiring action - these states will select a headline
1585 for inclusion into the global TODO list Org-mode produces. If one of
1586 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1587 signify that no further action is necessary. If \"|\" is not found,
1588 the last keyword is treated as the only DONE state of the sequence.
1590 The command \\[org-todo] cycles an entry through these states, and one
1591 additional state where no keyword is present. For details about this
1592 cycling, see the manual.
1594 TODO keywords and interpretation can also be set on a per-file basis with
1595 the special #+SEQ_TODO and #+TYP_TODO lines.
1597 Each keyword can optionally specify a character for fast state selection
1598 \(in combination with the variable `org-use-fast-todo-selection')
1599 and specifiers for state change logging, using the same syntax
1600 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1601 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1602 indicates to record a time stamp each time this state is selected.
1604 Each keyword may also specify if a timestamp or a note should be
1605 recorded when entering or leaving the state, by adding additional
1606 characters in the parenthesis after the keyword. This looks like this:
1607 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1608 record only the time of the state change. With X and Y being either
1609 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1610 Y when leaving the state if and only if the *target* state does not
1611 define X. You may omit any of the fast-selection key or X or /Y,
1612 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1614 For backward compatibility, this variable may also be just a list
1615 of keywords - in this case the interpretation (sequence or type) will be
1616 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1617 :group 'org-todo
1618 :group 'org-keywords
1619 :type '(choice
1620 (repeat :tag "Old syntax, just keywords"
1621 (string :tag "Keyword"))
1622 (repeat :tag "New syntax"
1623 (cons
1624 (choice
1625 :tag "Interpretation"
1626 ;;Quick and dirty way to see
1627 ;;`org-todo-interpretations'. This takes the
1628 ;;place of item arguments
1629 :convert-widget
1630 (lambda (widget)
1631 (widget-put widget
1632 :args (mapcar
1633 #'(lambda (x)
1634 (widget-convert
1635 (cons 'const x)))
1636 org-todo-interpretation-widgets))
1637 widget))
1638 (repeat
1639 (string :tag "Keyword"))))))
1641 (defvar org-todo-keywords-1 nil
1642 "All TODO and DONE keywords active in a buffer.")
1643 (make-variable-buffer-local 'org-todo-keywords-1)
1644 (defvar org-todo-keywords-for-agenda nil)
1645 (defvar org-done-keywords-for-agenda nil)
1646 (defvar org-todo-keyword-alist-for-agenda nil)
1647 (defvar org-tag-alist-for-agenda nil)
1648 (defvar org-agenda-contributing-files nil)
1649 (defvar org-not-done-keywords nil)
1650 (make-variable-buffer-local 'org-not-done-keywords)
1651 (defvar org-done-keywords nil)
1652 (make-variable-buffer-local 'org-done-keywords)
1653 (defvar org-todo-heads nil)
1654 (make-variable-buffer-local 'org-todo-heads)
1655 (defvar org-todo-sets nil)
1656 (make-variable-buffer-local 'org-todo-sets)
1657 (defvar org-todo-log-states nil)
1658 (make-variable-buffer-local 'org-todo-log-states)
1659 (defvar org-todo-kwd-alist nil)
1660 (make-variable-buffer-local 'org-todo-kwd-alist)
1661 (defvar org-todo-key-alist nil)
1662 (make-variable-buffer-local 'org-todo-key-alist)
1663 (defvar org-todo-key-trigger nil)
1664 (make-variable-buffer-local 'org-todo-key-trigger)
1666 (defcustom org-todo-interpretation 'sequence
1667 "Controls how TODO keywords are interpreted.
1668 This variable is in principle obsolete and is only used for
1669 backward compatibility, if the interpretation of todo keywords is
1670 not given already in `org-todo-keywords'. See that variable for
1671 more information."
1672 :group 'org-todo
1673 :group 'org-keywords
1674 :type '(choice (const sequence)
1675 (const type)))
1677 (defcustom org-use-fast-todo-selection t
1678 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1679 This variable describes if and under what circumstances the cycling
1680 mechanism for TODO keywords will be replaced by a single-key, direct
1681 selection scheme.
1683 When nil, fast selection is never used.
1685 When the symbol `prefix', it will be used when `org-todo' is called with
1686 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1687 in an agenda buffer.
1689 When t, fast selection is used by default. In this case, the prefix
1690 argument forces cycling instead.
1692 In all cases, the special interface is only used if access keys have actually
1693 been assigned by the user, i.e. if keywords in the configuration are followed
1694 by a letter in parenthesis, like TODO(t)."
1695 :group 'org-todo
1696 :type '(choice
1697 (const :tag "Never" nil)
1698 (const :tag "By default" t)
1699 (const :tag "Only with C-u C-c C-t" prefix)))
1701 (defcustom org-provide-todo-statistics t
1702 "Non-nil means, update todo statistics after insert and toggle.
1703 When this is set, todo statistics is updated in the parent of the current
1704 entry each time a todo state is changed."
1705 :group 'org-todo
1706 :type 'boolean)
1708 (defcustom org-hierarchical-todo-statistics t
1709 "Non-nil means, TODO statistics covers just direct children.
1710 When nil, all entries in the subtree are considered.
1711 This has only an effect if `org-provide-todo-statistics' is set."
1712 :group 'org-todo
1713 :type 'boolean)
1715 (defcustom org-after-todo-state-change-hook nil
1716 "Hook which is run after the state of a TODO item was changed.
1717 The new state (a string with a TODO keyword, or nil) is available in the
1718 Lisp variable `state'."
1719 :group 'org-todo
1720 :type 'hook)
1722 (defvar org-blocker-hook nil
1723 "Hook for functions that are allowed to block a state change.
1725 Each function gets as its single argument a property list, see
1726 `org-trigger-hook' for more information about this list.
1728 If any of the functions in this hook returns nil, the state change
1729 is blocked.")
1731 (defvar org-trigger-hook nil
1732 "Hook for functions that are triggered by a state change.
1734 Each function gets as its single argument a property list with at least
1735 the following elements:
1737 (:type type-of-change :position pos-at-entry-start
1738 :from old-state :to new-state)
1740 Depending on the type, more properties may be present.
1742 This mechanism is currently implemented for:
1744 TODO state changes
1745 ------------------
1746 :type todo-state-change
1747 :from previous state (keyword as a string), or nil, or a symbol
1748 'todo' or 'done', to indicate the general type of state.
1749 :to new state, like in :from")
1751 (defcustom org-enforce-todo-dependencies nil
1752 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1753 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1754 be blocked if any prior sibling is not yet done.
1755 Finally, if the parent is blocked because of ordered siblings of its own,
1756 the child will also be blocked.
1757 This variable needs to be set before org.el is loaded, and you need to
1758 restart Emacs after a change to make the change effective. The only way
1759 to change is while Emacs is running is through the customize interface."
1760 :set (lambda (var val)
1761 (set var val)
1762 (if val
1763 (add-hook 'org-blocker-hook
1764 'org-block-todo-from-children-or-siblings-or-parent)
1765 (remove-hook 'org-blocker-hook
1766 'org-block-todo-from-children-or-siblings-or-parent)))
1767 :group 'org-todo
1768 :type 'boolean)
1770 (defcustom org-enforce-todo-checkbox-dependencies nil
1771 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1772 When this is nil, checkboxes have no influence on switching TODO states.
1773 When non-nil, you first need to check off all check boxes before the TODO
1774 entry can be switched to DONE.
1775 This variable needs to be set before org.el is loaded, and you need to
1776 restart Emacs after a change to make the change effective. The only way
1777 to change is while Emacs is running is through the customize interface."
1778 :set (lambda (var val)
1779 (set var val)
1780 (if val
1781 (add-hook 'org-blocker-hook
1782 'org-block-todo-from-checkboxes)
1783 (remove-hook 'org-blocker-hook
1784 'org-block-todo-from-checkboxes)))
1785 :group 'org-todo
1786 :type 'boolean)
1788 (defcustom org-treat-insert-todo-heading-as-state-change nil
1789 "Non-nil means, inserting a TODO heading is treated as state change.
1790 So when the command \\[org-insert-todo-heading] is used, state change
1791 logging will apply if appropriate. When nil, the new TODO item will
1792 be inserted directly, and no logging will take place."
1793 :group 'org-todo
1794 :type 'boolean)
1796 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1797 "Non-nil means, switching TODO states with S-cursor counts as state change.
1798 This is the default behavior. However, setting this to nil allows a
1799 convenient way to select a TODO state and bypass any logging associated
1800 with that."
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.
1913 You can set the property LOG_INTO_DRAWER to overrule this setting for
1914 a subtree."
1915 :group 'org-todo
1916 :group 'org-progress
1917 :type '(choice
1918 (const :tag "Not into a drawer" nil)
1919 (const :tag "LOGBOOK" t)
1920 (string :tag "Other")))
1922 (if (fboundp 'defvaralias)
1923 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1925 (defun org-log-into-drawer ()
1926 "Return the value of `org-log-into-drawer', but let properties overrule.
1927 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
1928 used instead of the default value."
1929 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
1930 (cond
1931 ((or (not p) (equal p "nil")) org-log-into-drawer)
1932 ((equal p "t") "LOGBOOK")
1933 (t p))))
1935 (defcustom org-log-state-notes-insert-after-drawers nil
1936 "Non-nil means, insert state change notes after any drawers in entry.
1937 Only the drawers that *immediately* follow the headline and the
1938 deadline/scheduled line are skipped.
1939 When nil, insert notes right after the heading and perhaps the line
1940 with deadline/scheduling if present.
1942 This variable will have no effect if `org-log-into-drawer' is
1943 set."
1944 :group 'org-todo
1945 :group 'org-progress
1946 :type 'boolean)
1948 (defcustom org-log-states-order-reversed t
1949 "Non-nil means, the latest state change note will be directly after heading.
1950 When nil, the notes will be orderer according to time."
1951 :group 'org-todo
1952 :group 'org-progress
1953 :type 'boolean)
1955 (defcustom org-log-repeat 'time
1956 "Non-nil means, record moving through the DONE state when triggering repeat.
1957 An auto-repeating tasks is immediately switched back to TODO when marked
1958 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1959 the TODO keyword definition, or recording a closing note by setting
1960 `org-log-done', there will be no record of the task moving through DONE.
1961 This variable forces taking a note anyway. Possible values are:
1963 nil Don't force a record
1964 time Record a time stamp
1965 note Record a note
1967 This option can also be set with on a per-file-basis with
1969 #+STARTUP: logrepeat
1970 #+STARTUP: lognoterepeat
1971 #+STARTUP: nologrepeat
1973 You can have local logging settings for a subtree by setting the LOGGING
1974 property to one or more of these keywords."
1975 :group 'org-todo
1976 :group 'org-progress
1977 :type '(choice
1978 (const :tag "Don't force a record" nil)
1979 (const :tag "Force recording the DONE state" time)
1980 (const :tag "Force recording a note with the DONE state" note)))
1983 (defgroup org-priorities nil
1984 "Priorities in Org-mode."
1985 :tag "Org Priorities"
1986 :group 'org-todo)
1988 (defcustom org-enable-priority-commands t
1989 "Non-nil means, priority commands are active.
1990 When nil, these commands will be disabled, so that you never accidentally
1991 set a priority."
1992 :group 'org-priorities
1993 :type 'boolean)
1995 (defcustom org-highest-priority ?A
1996 "The highest priority of TODO items. A character like ?A, ?B etc.
1997 Must have a smaller ASCII number than `org-lowest-priority'."
1998 :group 'org-priorities
1999 :type 'character)
2001 (defcustom org-lowest-priority ?C
2002 "The lowest priority of TODO items. A character like ?A, ?B etc.
2003 Must have a larger ASCII number than `org-highest-priority'."
2004 :group 'org-priorities
2005 :type 'character)
2007 (defcustom org-default-priority ?B
2008 "The default priority of TODO items.
2009 This is the priority an item get if no explicit priority is given."
2010 :group 'org-priorities
2011 :type 'character)
2013 (defcustom org-priority-start-cycle-with-default t
2014 "Non-nil means, start with default priority when starting to cycle.
2015 When this is nil, the first step in the cycle will be (depending on the
2016 command used) one higher or lower that the default priority."
2017 :group 'org-priorities
2018 :type 'boolean)
2020 (defgroup org-time nil
2021 "Options concerning time stamps and deadlines in Org-mode."
2022 :tag "Org Time"
2023 :group 'org)
2025 (defcustom org-insert-labeled-timestamps-at-point nil
2026 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2027 When nil, these labeled time stamps are forces into the second line of an
2028 entry, just after the headline. When scheduling from the global TODO list,
2029 the time stamp will always be forced into the second line."
2030 :group 'org-time
2031 :type 'boolean)
2033 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2034 "Formats for `format-time-string' which are used for time stamps.
2035 It is not recommended to change this constant.")
2037 (defcustom org-time-stamp-rounding-minutes '(0 5)
2038 "Number of minutes to round time stamps to.
2039 These are two values, the first applies when first creating a time stamp.
2040 The second applies when changing it with the commands `S-up' and `S-down'.
2041 When changing the time stamp, this means that it will change in steps
2042 of N minutes, as given by the second value.
2044 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2045 numbers should be factors of 60, so for example 5, 10, 15.
2047 When this is larger than 1, you can still force an exact time-stamp by using
2048 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2049 and by using a prefix arg to `S-up/down' to specify the exact number
2050 of minutes to shift."
2051 :group 'org-time
2052 :get '(lambda (var) ; Make sure all entries have 5 elements
2053 (if (integerp (default-value var))
2054 (list (default-value var) 5)
2055 (default-value var)))
2056 :type '(list
2057 (integer :tag "when inserting times")
2058 (integer :tag "when modifying times")))
2060 ;; Normalize old customizations of this variable.
2061 (when (integerp org-time-stamp-rounding-minutes)
2062 (setq org-time-stamp-rounding-minutes
2063 (list org-time-stamp-rounding-minutes
2064 org-time-stamp-rounding-minutes)))
2066 (defcustom org-display-custom-times nil
2067 "Non-nil means, overlay custom formats over all time stamps.
2068 The formats are defined through the variable `org-time-stamp-custom-formats'.
2069 To turn this on on a per-file basis, insert anywhere in the file:
2070 #+STARTUP: customtime"
2071 :group 'org-time
2072 :set 'set-default
2073 :type 'sexp)
2074 (make-variable-buffer-local 'org-display-custom-times)
2076 (defcustom org-time-stamp-custom-formats
2077 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2078 "Custom formats for time stamps. See `format-time-string' for the syntax.
2079 These are overlayed over the default ISO format if the variable
2080 `org-display-custom-times' is set. Time like %H:%M should be at the
2081 end of the second format. The custom formats are also honored by export
2082 commands, if custom time display is turned on at the time of export."
2083 :group 'org-time
2084 :type 'sexp)
2086 (defun org-time-stamp-format (&optional long inactive)
2087 "Get the right format for a time string."
2088 (let ((f (if long (cdr org-time-stamp-formats)
2089 (car org-time-stamp-formats))))
2090 (if inactive
2091 (concat "[" (substring f 1 -1) "]")
2092 f)))
2094 (defcustom org-time-clocksum-format "%d:%02d"
2095 "The format string used when creating CLOCKSUM lines, or when
2096 org-mode generates a time duration."
2097 :group 'org-time
2098 :type 'string)
2100 (defcustom org-deadline-warning-days 14
2101 "No. of days before expiration during which a deadline becomes active.
2102 This variable governs the display in sparse trees and in the agenda.
2103 When 0 or negative, it means use this number (the absolute value of it)
2104 even if a deadline has a different individual lead time specified.
2106 Custom commands can set this variable in the options section."
2107 :group 'org-time
2108 :group 'org-agenda-daily/weekly
2109 :type 'integer)
2111 (defcustom org-read-date-prefer-future t
2112 "Non-nil means, assume future for incomplete date input from user.
2113 This affects the following situations:
2114 1. The user gives a day, but no month.
2115 For example, if today is the 15th, and you enter \"3\", Org-mode will
2116 read this as the third of *next* month. However, if you enter \"17\",
2117 it will be considered as *this* month.
2118 2. The user gives a month but not a year.
2119 For example, if it is april and you enter \"feb 2\", this will be read
2120 as feb 2, *next* year. \"May 5\", however, will be this year.
2122 Currently this does not work for ISO week specifications.
2124 When this option is nil, the current month and year will always be used
2125 as defaults."
2126 :group 'org-time
2127 :type 'boolean)
2129 (defcustom org-read-date-display-live t
2130 "Non-nil means, display current interpretation of date prompt live.
2131 This display will be in an overlay, in the minibuffer."
2132 :group 'org-time
2133 :type 'boolean)
2135 (defcustom org-read-date-popup-calendar t
2136 "Non-nil means, pop up a calendar when prompting for a date.
2137 In the calendar, the date can be selected with mouse-1. However, the
2138 minibuffer will also be active, and you can simply enter the date as well.
2139 When nil, only the minibuffer will be available."
2140 :group 'org-time
2141 :type 'boolean)
2142 (if (fboundp 'defvaralias)
2143 (defvaralias 'org-popup-calendar-for-date-prompt
2144 'org-read-date-popup-calendar))
2146 (defcustom org-read-date-minibuffer-setup-hook nil
2147 "Hook to be used to set up keys for the date/time interface.
2148 Add key definitions to `minibuffer-local-map', which will be a temporary
2149 copy."
2150 :group 'org-time
2151 :type 'hook)
2153 (defcustom org-extend-today-until 0
2154 "The hour when your day really ends. Must be an integer.
2155 This has influence for the following applications:
2156 - When switching the agenda to \"today\". It it is still earlier than
2157 the time given here, the day recognized as TODAY is actually yesterday.
2158 - When a date is read from the user and it is still before the time given
2159 here, the current date and time will be assumed to be yesterday, 23:59.
2160 Also, timestamps inserted in remember templates follow this rule.
2162 IMPORTANT: This is a feature whose implementation is and likely will
2163 remain incomplete. Really, it is only here because past midnight seems to
2164 be the favorite working time of John Wiegley :-)"
2165 :group 'org-time
2166 :type 'integer)
2168 (defcustom org-edit-timestamp-down-means-later nil
2169 "Non-nil means, S-down will increase the time in a time stamp.
2170 When nil, S-up will increase."
2171 :group 'org-time
2172 :type 'boolean)
2174 (defcustom org-calendar-follow-timestamp-change t
2175 "Non-nil means, make the calendar window follow timestamp changes.
2176 When a timestamp is modified and the calendar window is visible, it will be
2177 moved to the new date."
2178 :group 'org-time
2179 :type 'boolean)
2181 (defgroup org-tags nil
2182 "Options concerning tags in Org-mode."
2183 :tag "Org Tags"
2184 :group 'org)
2186 (defcustom org-tag-alist nil
2187 "List of tags allowed in Org-mode files.
2188 When this list is nil, Org-mode will base TAG input on what is already in the
2189 buffer.
2190 The value of this variable is an alist, the car of each entry must be a
2191 keyword as a string, the cdr may be a character that is used to select
2192 that tag through the fast-tag-selection interface.
2193 See the manual for details."
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 (defcustom org-tag-persistent-alist nil
2204 "List of tags that will always appear in all Org-mode files.
2205 This is in addition to any in buffer settings or customizations
2206 of `org-tag-alist'.
2207 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2208 The value of this variable is an alist, the car of each entry must be a
2209 keyword as a string, the cdr may be a character that is used to select
2210 that tag through the fast-tag-selection interface.
2211 See the manual for details.
2212 To disable these tags on a per-file basis, insert anywhere in the file:
2213 #+STARTUP: noptag"
2214 :group 'org-tags
2215 :type '(repeat
2216 (choice
2217 (cons (string :tag "Tag name")
2218 (character :tag "Access char"))
2219 (const :tag "Start radio group" (:startgroup))
2220 (const :tag "End radio group" (:endgroup))
2221 (const :tag "New line" (:newline)))))
2223 (defvar org-file-tags nil
2224 "List of tags that can be inherited by all entries in the file.
2225 The tags will be inherited if the variable `org-use-tag-inheritance'
2226 says they should be.
2227 This variable is populated from #+TAG lines.")
2229 (defcustom org-use-fast-tag-selection 'auto
2230 "Non-nil means, use fast tag selection scheme.
2231 This is a special interface to select and deselect tags with single keys.
2232 When nil, fast selection is never used.
2233 When the symbol `auto', fast selection is used if and only if selection
2234 characters for tags have been configured, either through the variable
2235 `org-tag-alist' or through a #+TAGS line in the buffer.
2236 When t, fast selection is always used and selection keys are assigned
2237 automatically if necessary."
2238 :group 'org-tags
2239 :type '(choice
2240 (const :tag "Always" t)
2241 (const :tag "Never" nil)
2242 (const :tag "When selection characters are configured" 'auto)))
2244 (defcustom org-fast-tag-selection-single-key nil
2245 "Non-nil means, fast tag selection exits after first change.
2246 When nil, you have to press RET to exit it.
2247 During fast tag selection, you can toggle this flag with `C-c'.
2248 This variable can also have the value `expert'. In this case, the window
2249 displaying the tags menu is not even shown, until you press C-c again."
2250 :group 'org-tags
2251 :type '(choice
2252 (const :tag "No" nil)
2253 (const :tag "Yes" t)
2254 (const :tag "Expert" expert)))
2256 (defvar org-fast-tag-selection-include-todo nil
2257 "Non-nil means, fast tags selection interface will also offer TODO states.
2258 This is an undocumented feature, you should not rely on it.")
2260 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2261 "The column to which tags should be indented in a headline.
2262 If this number is positive, it specifies the column. If it is negative,
2263 it means that the tags should be flushright to that column. For example,
2264 -80 works well for a normal 80 character screen."
2265 :group 'org-tags
2266 :type 'integer)
2268 (defcustom org-auto-align-tags t
2269 "Non-nil means, realign tags after pro/demotion of TODO state change.
2270 These operations change the length of a headline and therefore shift
2271 the tags around. With this options turned on, after each such operation
2272 the tags are again aligned to `org-tags-column'."
2273 :group 'org-tags
2274 :type 'boolean)
2276 (defcustom org-use-tag-inheritance t
2277 "Non-nil means, tags in levels apply also for sublevels.
2278 When nil, only the tags directly given in a specific line apply there.
2279 This may also be a list of tags that should be inherited, or a regexp that
2280 matches tags that should be inherited. Additional control is possible
2281 with the variable `org-tags-exclude-from-inheritance' which gives an
2282 explicit list of tags to be excluded from inheritance., even if the value of
2283 `org-use-tag-inheritance' would select it for inheritance.
2285 If this option is t, a match early-on in a tree can lead to a large
2286 number of matches in the subtree when constructing the agenda or creating
2287 a sparse tree. If you only want to see the first match in a tree during
2288 a search, check out the variable `org-tags-match-list-sublevels'."
2289 :group 'org-tags
2290 :type '(choice
2291 (const :tag "Not" nil)
2292 (const :tag "Always" t)
2293 (repeat :tag "Specific tags" (string :tag "Tag"))
2294 (regexp :tag "Tags matched by regexp")))
2296 (defcustom org-tags-exclude-from-inheritance nil
2297 "List of tags that should never be inherited.
2298 This is a way to exclude a few tags from inheritance. For way to do
2299 the opposite, to actively allow inheritance for selected tags,
2300 see the variable `org-use-tag-inheritance'."
2301 :group 'org-tags
2302 :type '(repeat (string :tag "Tag")))
2304 (defun org-tag-inherit-p (tag)
2305 "Check if TAG is one that should be inherited."
2306 (cond
2307 ((member tag org-tags-exclude-from-inheritance) nil)
2308 ((eq org-use-tag-inheritance t) t)
2309 ((not org-use-tag-inheritance) nil)
2310 ((stringp org-use-tag-inheritance)
2311 (string-match org-use-tag-inheritance tag))
2312 ((listp org-use-tag-inheritance)
2313 (member tag org-use-tag-inheritance))
2314 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2316 (defcustom org-tags-match-list-sublevels t
2317 "Non-nil means list also sublevels of headlines matching a search.
2318 This variable applies to tags/property searches, and also to stuck
2319 projects because this search is based on a tags match as well.
2321 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2322 the sublevels of a headline matching a tag search often also match
2323 the same search. Listing all of them can create very long lists.
2324 Setting this variable to nil causes subtrees of a match to be skipped.
2326 As a special case, if the tag search is restricted to TODO items, the
2327 value of this variable is ignored and sublevels are always checked, to
2328 make sure all corresponding TODO items find their way into the list.
2330 This variable is semi-obsolete and probably should always be true. It
2331 is better to limit inheritance to certain tags using the variables
2332 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2333 :group 'org-tags
2334 :type '(choice
2335 (const :tag "No, don't list them" nil)
2336 (const :tag "Yes, do list them" t)
2337 (const :tag "List them, indented with leading dots" indented)))
2339 (defvar org-tags-history nil
2340 "History of minibuffer reads for tags.")
2341 (defvar org-last-tags-completion-table nil
2342 "The last used completion table for tags.")
2343 (defvar org-after-tags-change-hook nil
2344 "Hook that is run after the tags in a line have changed.")
2346 (defgroup org-properties nil
2347 "Options concerning properties in Org-mode."
2348 :tag "Org Properties"
2349 :group 'org)
2351 (defcustom org-property-format "%-10s %s"
2352 "How property key/value pairs should be formatted by `indent-line'.
2353 When `indent-line' hits a property definition, it will format the line
2354 according to this format, mainly to make sure that the values are
2355 lined-up with respect to each other."
2356 :group 'org-properties
2357 :type 'string)
2359 (defcustom org-use-property-inheritance nil
2360 "Non-nil means, properties apply also for sublevels.
2362 This setting is chiefly used during property searches. Turning it on can
2363 cause significant overhead when doing a search, which is why it is not
2364 on by default.
2366 When nil, only the properties directly given in the current entry count.
2367 When t, every property is inherited. The value may also be a list of
2368 properties that should have inheritance, or a regular expression matching
2369 properties that should be inherited.
2371 However, note that some special properties use inheritance under special
2372 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2373 and the properties ending in \"_ALL\" when they are used as descriptor
2374 for valid values of a property.
2376 Note for programmers:
2377 When querying an entry with `org-entry-get', you can control if inheritance
2378 should be used. By default, `org-entry-get' looks only at the local
2379 properties. You can request inheritance by setting the inherit argument
2380 to t (to force inheritance) or to `selective' (to respect the setting
2381 in this variable)."
2382 :group 'org-properties
2383 :type '(choice
2384 (const :tag "Not" nil)
2385 (const :tag "Always" t)
2386 (repeat :tag "Specific properties" (string :tag "Property"))
2387 (regexp :tag "Properties matched by regexp")))
2389 (defun org-property-inherit-p (property)
2390 "Check if PROPERTY is one that should be inherited."
2391 (cond
2392 ((eq org-use-property-inheritance t) t)
2393 ((not org-use-property-inheritance) nil)
2394 ((stringp org-use-property-inheritance)
2395 (string-match org-use-property-inheritance property))
2396 ((listp org-use-property-inheritance)
2397 (member property org-use-property-inheritance))
2398 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2400 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2401 "The default column format, if no other format has been defined.
2402 This variable can be set on the per-file basis by inserting a line
2404 #+COLUMNS: %25ITEM ....."
2405 :group 'org-properties
2406 :type 'string)
2408 (defcustom org-columns-ellipses ".."
2409 "The ellipses to be used when a field in column view is truncated.
2410 When this is the empty string, as many characters as possible are shown,
2411 but then there will be no visual indication that the field has been truncated.
2412 When this is a string of length N, the last N characters of a truncated
2413 field are replaced by this string. If the column is narrower than the
2414 ellipses string, only part of the ellipses string will be shown."
2415 :group 'org-properties
2416 :type 'string)
2418 (defcustom org-columns-modify-value-for-display-function nil
2419 "Function that modifies values for display in column view.
2420 For example, it can be used to cut out a certain part from a time stamp.
2421 The function must take 2 arguments:
2423 column-title The title of the column (*not* the property name)
2424 value The value that should be modified.
2426 The function should return the value that should be displayed,
2427 or nil if the normal value should be used."
2428 :group 'org-properties
2429 :type 'function)
2431 (defcustom org-effort-property "Effort"
2432 "The property that is being used to keep track of effort estimates.
2433 Effort estimates given in this property need to have the format H:MM."
2434 :group 'org-properties
2435 :group 'org-progress
2436 :type '(string :tag "Property"))
2438 (defconst org-global-properties-fixed
2439 '(("VISIBILITY_ALL" . "folded children content all")
2440 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2441 "List of property/value pairs that can be inherited by any entry.
2443 These are fixed values, for the preset properties. The user variable
2444 that can be used to add to this list is `org-global-properties'.
2446 The entries in this list are cons cells where the car is a property
2447 name and cdr is a string with the value. If the value represents
2448 multiple items like an \"_ALL\" property, separate the items by
2449 spaces.")
2451 (defcustom org-global-properties nil
2452 "List of property/value pairs that can be inherited by any entry.
2454 This list will be combined with the constant `org-global-properties-fixed'.
2456 The entries in this list are cons cells where the car is a property
2457 name and cdr is a string with the value.
2459 You can set buffer-local values for the same purpose in the variable
2460 `org-file-properties' this by adding lines like
2462 #+PROPERTY: NAME VALUE"
2463 :group 'org-properties
2464 :type '(repeat
2465 (cons (string :tag "Property")
2466 (string :tag "Value"))))
2468 (defvar org-file-properties nil
2469 "List of property/value pairs that can be inherited by any entry.
2470 Valid for the current buffer.
2471 This variable is populated from #+PROPERTY lines.")
2472 (make-variable-buffer-local 'org-file-properties)
2474 (defgroup org-agenda nil
2475 "Options concerning agenda views in Org-mode."
2476 :tag "Org Agenda"
2477 :group 'org)
2479 (defvar org-category nil
2480 "Variable used by org files to set a category for agenda display.
2481 Such files should use a file variable to set it, for example
2483 # -*- mode: org; org-category: \"ELisp\"
2485 or contain a special line
2487 #+CATEGORY: ELisp
2489 If the file does not specify a category, then file's base name
2490 is used instead.")
2491 (make-variable-buffer-local 'org-category)
2492 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2494 (defcustom org-agenda-files nil
2495 "The files to be used for agenda display.
2496 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2497 \\[org-remove-file]. You can also use customize to edit the list.
2499 If an entry is a directory, all files in that directory that are matched by
2500 `org-agenda-file-regexp' will be part of the file list.
2502 If the value of the variable is not a list but a single file name, then
2503 the list of agenda files is actually stored and maintained in that file, one
2504 agenda file per line."
2505 :group 'org-agenda
2506 :type '(choice
2507 (repeat :tag "List of files and directories" file)
2508 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2510 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2511 "Regular expression to match files for `org-agenda-files'.
2512 If any element in the list in that variable contains a directory instead
2513 of a normal file, all files in that directory that are matched by this
2514 regular expression will be included."
2515 :group 'org-agenda
2516 :type 'regexp)
2518 (defcustom org-agenda-text-search-extra-files nil
2519 "List of extra files to be searched by text search commands.
2520 These files will be search in addition to the agenda files by the
2521 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2522 Note that these files will only be searched for text search commands,
2523 not for the other agenda views like todo lists, tag searches or the weekly
2524 agenda. This variable is intended to list notes and possibly archive files
2525 that should also be searched by these two commands.
2526 In fact, if the first element in the list is the symbol `agenda-archives',
2527 than all archive files of all agenda files will be added to the search
2528 scope."
2529 :group 'org-agenda
2530 :type '(set :greedy t
2531 (const :tag "Agenda Archives" agenda-archives)
2532 (repeat :inline t (file))))
2534 (if (fboundp 'defvaralias)
2535 (defvaralias 'org-agenda-multi-occur-extra-files
2536 'org-agenda-text-search-extra-files))
2538 (defcustom org-agenda-skip-unavailable-files nil
2539 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2540 A nil value means to remove them, after a query, from the list."
2541 :group 'org-agenda
2542 :type 'boolean)
2544 (defcustom org-calendar-to-agenda-key [?c]
2545 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2546 The command `org-calendar-goto-agenda' will be bound to this key. The
2547 default is the character `c' because then `c' can be used to switch back and
2548 forth between agenda and calendar."
2549 :group 'org-agenda
2550 :type 'sexp)
2552 (defcustom org-calendar-agenda-action-key [?k]
2553 "The key to be installed in `calendar-mode-map' for agenda-action.
2554 The command `org-agenda-action' will be bound to this key. The
2555 default is the character `k' because we use the same key in the agenda."
2556 :group 'org-agenda
2557 :type 'sexp)
2559 (eval-after-load "calendar"
2560 '(progn
2561 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2562 'org-calendar-goto-agenda)
2563 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2564 'org-agenda-action)))
2566 (defgroup org-latex nil
2567 "Options for embedding LaTeX code into Org-mode."
2568 :tag "Org LaTeX"
2569 :group 'org)
2571 (defcustom org-format-latex-options
2572 '(:foreground default :background default :scale 1.0
2573 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2574 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2575 "Options for creating images from LaTeX fragments.
2576 This is a property list with the following properties:
2577 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2578 `default' means use the foreground of the default face.
2579 :background the background color, or \"Transparent\".
2580 `default' means use the background of the default face.
2581 :scale a scaling factor for the size of the images.
2582 :html-foreground, :html-background, :html-scale
2583 the same numbers for HTML export.
2584 :matchers a list indicating which matchers should be used to
2585 find LaTeX fragments. Valid members of this list are:
2586 \"begin\" find environments
2587 \"$1\" find single characters surrounded by $.$
2588 \"$\" find math expressions surrounded by $...$
2589 \"$$\" find math expressions surrounded by $$....$$
2590 \"\\(\" find math expressions surrounded by \\(...\\)
2591 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2592 :group 'org-latex
2593 :type 'plist)
2595 (defcustom org-format-latex-header "\\documentclass{article}
2596 \\usepackage{fullpage} % do not remove
2597 \\usepackage{amssymb}
2598 \\usepackage[usenames]{color}
2599 \\usepackage{amsmath}
2600 \\usepackage{latexsym}
2601 \\usepackage[mathscr]{eucal}
2602 \\pagestyle{empty} % do not remove"
2603 "The document header used for processing LaTeX fragments."
2604 :group 'org-latex
2605 :type 'string)
2608 (defgroup org-font-lock nil
2609 "Font-lock settings for highlighting in Org-mode."
2610 :tag "Org Font Lock"
2611 :group 'org)
2613 (defcustom org-level-color-stars-only nil
2614 "Non-nil means fontify only the stars in each headline.
2615 When nil, the entire headline is fontified.
2616 Changing it requires restart of `font-lock-mode' to become effective
2617 also in regions already fontified."
2618 :group 'org-font-lock
2619 :type 'boolean)
2621 (defcustom org-hide-leading-stars nil
2622 "Non-nil means, hide the first N-1 stars in a headline.
2623 This works by using the face `org-hide' for these stars. This
2624 face is white for a light background, and black for a dark
2625 background. You may have to customize the face `org-hide' to
2626 make this work.
2627 Changing it requires restart of `font-lock-mode' to become effective
2628 also in regions already fontified.
2629 You may also set this on a per-file basis by adding one of the following
2630 lines to the buffer:
2632 #+STARTUP: hidestars
2633 #+STARTUP: showstars"
2634 :group 'org-font-lock
2635 :type 'boolean)
2637 (defcustom org-fontify-done-headline nil
2638 "Non-nil means, change the face of a headline if it is marked DONE.
2639 Normally, only the TODO/DONE keyword indicates the state of a headline.
2640 When this is non-nil, the headline after the keyword is set to the
2641 `org-headline-done' as an additional indication."
2642 :group 'org-font-lock
2643 :type 'boolean)
2645 (defcustom org-fontify-emphasized-text t
2646 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2647 Changing this variable requires a restart of Emacs to take effect."
2648 :group 'org-font-lock
2649 :type 'boolean)
2651 (defcustom org-highlight-latex-fragments-and-specials nil
2652 "Non-nil means, fontify what is treated specially by the exporters."
2653 :group 'org-font-lock
2654 :type 'boolean)
2656 (defcustom org-hide-emphasis-markers nil
2657 "Non-nil mean font-lock should hide the emphasis marker characters."
2658 :group 'org-font-lock
2659 :type 'boolean)
2661 (defvar org-emph-re nil
2662 "Regular expression for matching emphasis.")
2663 (defvar org-verbatim-re nil
2664 "Regular expression for matching verbatim text.")
2665 (defvar org-emphasis-regexp-components) ; defined just below
2666 (defvar org-emphasis-alist) ; defined just below
2667 (defun org-set-emph-re (var val)
2668 "Set variable and compute the emphasis regular expression."
2669 (set var val)
2670 (when (and (boundp 'org-emphasis-alist)
2671 (boundp 'org-emphasis-regexp-components)
2672 org-emphasis-alist org-emphasis-regexp-components)
2673 (let* ((e org-emphasis-regexp-components)
2674 (pre (car e))
2675 (post (nth 1 e))
2676 (border (nth 2 e))
2677 (body (nth 3 e))
2678 (nl (nth 4 e))
2679 (body1 (concat body "*?"))
2680 (markers (mapconcat 'car org-emphasis-alist ""))
2681 (vmarkers (mapconcat
2682 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2683 org-emphasis-alist "")))
2684 ;; make sure special characters appear at the right position in the class
2685 (if (string-match "\\^" markers)
2686 (setq markers (concat (replace-match "" t t markers) "^")))
2687 (if (string-match "-" markers)
2688 (setq markers (concat (replace-match "" t t markers) "-")))
2689 (if (string-match "\\^" vmarkers)
2690 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2691 (if (string-match "-" vmarkers)
2692 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2693 (if (> nl 0)
2694 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2695 (int-to-string nl) "\\}")))
2696 ;; Make the regexp
2697 (setq org-emph-re
2698 (concat "\\([" pre "]\\|^\\)"
2699 "\\("
2700 "\\([" markers "]\\)"
2701 "\\("
2702 "[^" border "]\\|"
2703 "[^" border "]"
2704 body1
2705 "[^" border "]"
2706 "\\)"
2707 "\\3\\)"
2708 "\\([" post "]\\|$\\)"))
2709 (setq org-verbatim-re
2710 (concat "\\([" pre "]\\|^\\)"
2711 "\\("
2712 "\\([" vmarkers "]\\)"
2713 "\\("
2714 "[^" border "]\\|"
2715 "[^" border "]"
2716 body1
2717 "[^" border "]"
2718 "\\)"
2719 "\\3\\)"
2720 "\\([" post "]\\|$\\)")))))
2722 (defcustom org-emphasis-regexp-components
2723 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2724 "Components used to build the regular expression for emphasis.
2725 This is a list with 6 entries. Terminology: In an emphasis string
2726 like \" *strong word* \", we call the initial space PREMATCH, the final
2727 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2728 and \"trong wor\" is the body. The different components in this variable
2729 specify what is allowed/forbidden in each part:
2731 pre Chars allowed as prematch. Beginning of line will be allowed too.
2732 post Chars allowed as postmatch. End of line will be allowed too.
2733 border The chars *forbidden* as border characters.
2734 body-regexp A regexp like \".\" to match a body character. Don't use
2735 non-shy groups here, and don't allow newline here.
2736 newline The maximum number of newlines allowed in an emphasis exp.
2738 Use customize to modify this, or restart Emacs after changing it."
2739 :group 'org-font-lock
2740 :set 'org-set-emph-re
2741 :type '(list
2742 (sexp :tag "Allowed chars in pre ")
2743 (sexp :tag "Allowed chars in post ")
2744 (sexp :tag "Forbidden chars in border ")
2745 (sexp :tag "Regexp for body ")
2746 (integer :tag "number of newlines allowed")
2747 (option (boolean :tag "Please ignore this button"))))
2749 (defcustom org-emphasis-alist
2750 `(("*" bold "<b>" "</b>")
2751 ("/" italic "<i>" "</i>")
2752 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2753 ("=" org-code "<code>" "</code>" verbatim)
2754 ("~" org-verbatim "<code>" "</code>" verbatim)
2755 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2756 "<del>" "</del>")
2758 "Special syntax for emphasized text.
2759 Text starting and ending with a special character will be emphasized, for
2760 example *bold*, _underlined_ and /italic/. This variable sets the marker
2761 characters, the face to be used by font-lock for highlighting in Org-mode
2762 Emacs buffers, and the HTML tags to be used for this.
2763 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2764 Use customize to modify this, or restart Emacs after changing it."
2765 :group 'org-font-lock
2766 :set 'org-set-emph-re
2767 :type '(repeat
2768 (list
2769 (string :tag "Marker character")
2770 (choice
2771 (face :tag "Font-lock-face")
2772 (plist :tag "Face property list"))
2773 (string :tag "HTML start tag")
2774 (string :tag "HTML end tag")
2775 (option (const verbatim)))))
2777 (defvar org-protecting-blocks
2778 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2779 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2780 This is needed for font-lock setup.")
2782 ;;; Miscellaneous options
2784 (defgroup org-completion nil
2785 "Completion in Org-mode."
2786 :tag "Org Completion"
2787 :group 'org)
2789 (defcustom org-completion-use-ido nil
2790 "Non-nil means, use ido completion wherever possible.
2791 Note that `ido-mode' must be active for this variable to be relevant.
2792 If you decide to turn this variable on, you might well want to turn off
2793 `org-outline-path-complete-in-steps'."
2794 :group 'org-completion
2795 :type 'boolean)
2797 (defcustom org-completion-fallback-command 'hippie-expand
2798 "The expansion command called by \\[org-complete] in normal context.
2799 Normal means, no org-mode-specific context."
2800 :group 'org-completion
2801 :type 'function)
2803 ;;; Functions and variables from ther packages
2804 ;; Declared here to avoid compiler warnings
2806 ;; XEmacs only
2807 (defvar outline-mode-menu-heading)
2808 (defvar outline-mode-menu-show)
2809 (defvar outline-mode-menu-hide)
2810 (defvar zmacs-regions) ; XEmacs regions
2812 ;; Emacs only
2813 (defvar mark-active)
2815 ;; Various packages
2816 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2817 (declare-function calendar-forward-day "cal-move" (arg))
2818 (declare-function calendar-goto-date "cal-move" (date))
2819 (declare-function calendar-goto-today "cal-move" ())
2820 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2821 (defvar calc-embedded-close-formula)
2822 (defvar calc-embedded-open-formula)
2823 (declare-function cdlatex-tab "ext:cdlatex" ())
2824 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2825 (defvar font-lock-unfontify-region-function)
2826 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2827 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2828 (defvar iswitchb-temp-buflist)
2829 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2830 (defvar org-agenda-tags-todo-honor-ignore-options)
2831 (declare-function org-agenda-skip "org-agenda" ())
2832 (declare-function org-format-agenda-item "org-agenda"
2833 (extra txt &optional category tags dotime noprefix remove-re))
2834 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2835 (declare-function org-agenda-change-all-lines "org-agenda"
2836 (newhead hdmarker &optional fixface just-this))
2837 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2838 (declare-function org-agenda-maybe-redo "org-agenda" ())
2839 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2840 (beg end))
2841 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2842 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2843 "org-agenda" (&optional end))
2845 (declare-function parse-time-string "parse-time" (string))
2846 (declare-function remember "remember" (&optional initial))
2847 (declare-function remember-buffer-desc "remember" ())
2848 (declare-function remember-finalize "remember" ())
2849 (defvar remember-save-after-remembering)
2850 (defvar remember-data-file)
2851 (defvar remember-register)
2852 (defvar remember-buffer)
2853 (defvar remember-handler-functions)
2854 (defvar remember-annotation-functions)
2855 (defvar texmathp-why)
2856 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2857 (declare-function table--at-cell-p "table" (position &optional object at-column))
2859 (defvar w3m-current-url)
2860 (defvar w3m-current-title)
2862 (defvar org-latex-regexps)
2864 ;;; Autoload and prepare some org modules
2866 ;; Some table stuff that needs to be defined here, because it is used
2867 ;; by the functions setting up org-mode or checking for table context.
2869 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2870 "Detects an org-type or table-type table.")
2871 (defconst org-table-line-regexp "^[ \t]*|"
2872 "Detects an org-type table line.")
2873 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2874 "Detects an org-type table line.")
2875 (defconst org-table-hline-regexp "^[ \t]*|-"
2876 "Detects an org-type table hline.")
2877 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2878 "Detects a table-type table hline.")
2879 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2880 "Searching from within a table (any type) this finds the first line
2881 outside the table.")
2883 ;; Autoload the functions in org-table.el that are needed by functions here.
2885 (eval-and-compile
2886 (org-autoload "org-table"
2887 '(org-table-align org-table-begin org-table-blank-field
2888 org-table-convert org-table-convert-region org-table-copy-down
2889 org-table-copy-region org-table-create
2890 org-table-create-or-convert-from-region
2891 org-table-create-with-table.el org-table-current-dline
2892 org-table-cut-region org-table-delete-column org-table-edit-field
2893 org-table-edit-formulas org-table-end org-table-eval-formula
2894 org-table-export org-table-field-info
2895 org-table-get-stored-formulas org-table-goto-column
2896 org-table-hline-and-move org-table-import org-table-insert-column
2897 org-table-insert-hline org-table-insert-row org-table-iterate
2898 org-table-justify-field-maybe org-table-kill-row
2899 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2900 org-table-move-column org-table-move-column-left
2901 org-table-move-column-right org-table-move-row
2902 org-table-move-row-down org-table-move-row-up
2903 org-table-next-field org-table-next-row org-table-paste-rectangle
2904 org-table-previous-field org-table-recalculate
2905 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2906 org-table-toggle-coordinate-overlays
2907 org-table-toggle-formula-debugger org-table-wrap-region
2908 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2910 (defun org-at-table-p (&optional table-type)
2911 "Return t if the cursor is inside an org-type table.
2912 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2913 (if org-enable-table-editor
2914 (save-excursion
2915 (beginning-of-line 1)
2916 (looking-at (if table-type org-table-any-line-regexp
2917 org-table-line-regexp)))
2918 nil))
2919 (defsubst org-table-p () (org-at-table-p))
2921 (defun org-at-table.el-p ()
2922 "Return t if and only if we are at a table.el table."
2923 (and (org-at-table-p 'any)
2924 (save-excursion
2925 (goto-char (org-table-begin 'any))
2926 (looking-at org-table1-hline-regexp))))
2927 (defun org-table-recognize-table.el ()
2928 "If there is a table.el table nearby, recognize it and move into it."
2929 (if org-table-tab-recognizes-table.el
2930 (if (org-at-table.el-p)
2931 (progn
2932 (beginning-of-line 1)
2933 (if (looking-at org-table-dataline-regexp)
2935 (if (looking-at org-table1-hline-regexp)
2936 (progn
2937 (beginning-of-line 2)
2938 (if (looking-at org-table-any-border-regexp)
2939 (beginning-of-line -1)))))
2940 (if (re-search-forward "|" (org-table-end t) t)
2941 (progn
2942 (require 'table)
2943 (if (table--at-cell-p (point))
2945 (message "recognizing table.el table...")
2946 (table-recognize-table)
2947 (message "recognizing table.el table...done")))
2948 (error "This should not happen..."))
2950 nil)
2951 nil))
2953 (defun org-at-table-hline-p ()
2954 "Return t if the cursor is inside a hline in a table."
2955 (if org-enable-table-editor
2956 (save-excursion
2957 (beginning-of-line 1)
2958 (looking-at org-table-hline-regexp))
2959 nil))
2961 (defvar org-table-clean-did-remove-column nil)
2963 (defun org-table-map-tables (function)
2964 "Apply FUNCTION to the start of all tables in the buffer."
2965 (save-excursion
2966 (save-restriction
2967 (widen)
2968 (goto-char (point-min))
2969 (while (re-search-forward org-table-any-line-regexp nil t)
2970 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2971 (beginning-of-line 1)
2972 (if (looking-at org-table-line-regexp)
2973 (save-excursion (funcall function)))
2974 (re-search-forward org-table-any-border-regexp nil 1))))
2975 (message "Mapping tables: done"))
2977 ;; Declare and autoload functions from org-exp.el & Co
2979 (declare-function org-default-export-plist "org-exp")
2980 (declare-function org-infile-export-plist "org-exp")
2981 (declare-function org-get-current-options "org-exp")
2982 (eval-and-compile
2983 (org-autoload "org-exp"
2984 '(org-export org-export-visible
2985 org-insert-export-options-template
2986 org-table-clean-before-export))
2987 (org-autoload "org-ascii"
2988 '(org-export-as-ascii org-export-ascii-preprocess
2989 org-export-as-ascii-to-buffer org-replace-region-by-ascii
2990 org-export-region-as-ascii))
2991 (org-autoload "org-html"
2992 '(org-export-as-html-and-open
2993 org-export-as-html-batch org-export-as-html-to-buffer
2994 org-replace-region-by-html org-export-region-as-html
2995 org-export-as-html))
2996 (org-autoload "org-icalendar"
2997 '(org-export-icalendar-this-file
2998 org-export-icalendar-all-agenda-files
2999 org-export-icalendar-combine-agenda-files))
3000 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3002 ;; Declare and autoload functions from org-agenda.el
3004 (eval-and-compile
3005 (org-autoload "org-agenda"
3006 '(org-agenda org-agenda-list org-search-view
3007 org-todo-list org-tags-view org-agenda-list-stuck-projects
3008 org-diary org-agenda-to-appt
3009 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3011 ;; Autoload org-remember
3013 (eval-and-compile
3014 (org-autoload "org-remember"
3015 '(org-remember-insinuate org-remember-annotation
3016 org-remember-apply-template org-remember org-remember-handler)))
3018 ;; Autoload org-clock.el
3021 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3022 (beg end))
3023 (declare-function org-clock-update-mode-line "org-clock" ())
3024 (defvar org-clock-start-time)
3025 (defvar org-clock-marker (make-marker)
3026 "Marker recording the last clock-in.")
3027 (defun org-clock-is-active ()
3028 "Return non-nil if clock is currently running.
3029 The return value is actually the clock marker."
3030 (marker-buffer org-clock-marker))
3032 (eval-and-compile
3033 (org-autoload
3034 "org-clock"
3035 '(org-clock-in org-clock-out org-clock-cancel
3036 org-clock-goto org-clock-sum org-clock-display
3037 org-clock-remove-overlays org-clock-report
3038 org-clocktable-shift org-dblock-write:clocktable
3039 org-get-clocktable)))
3041 (defun org-clock-update-time-maybe ()
3042 "If this is a CLOCK line, update it and return t.
3043 Otherwise, return nil."
3044 (interactive)
3045 (save-excursion
3046 (beginning-of-line 1)
3047 (skip-chars-forward " \t")
3048 (when (looking-at org-clock-string)
3049 (let ((re (concat "[ \t]*" org-clock-string
3050 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3051 "\\([ \t]*=>.*\\)?\\)?"))
3052 ts te h m s neg)
3053 (cond
3054 ((not (looking-at re))
3055 nil)
3056 ((not (match-end 2))
3057 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3058 (> org-clock-marker (point))
3059 (<= org-clock-marker (point-at-eol)))
3060 ;; The clock is running here
3061 (setq org-clock-start-time
3062 (apply 'encode-time
3063 (org-parse-time-string (match-string 1))))
3064 (org-clock-update-mode-line)))
3066 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3067 (end-of-line 1)
3068 (setq ts (match-string 1)
3069 te (match-string 3))
3070 (setq s (- (time-to-seconds
3071 (apply 'encode-time (org-parse-time-string te)))
3072 (time-to-seconds
3073 (apply 'encode-time (org-parse-time-string ts))))
3074 neg (< s 0)
3075 s (abs s)
3076 h (floor (/ s 3600))
3077 s (- s (* 3600 h))
3078 m (floor (/ s 60))
3079 s (- s (* 60 s)))
3080 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3081 t))))))
3083 (defun org-check-running-clock ()
3084 "Check if the current buffer contains the running clock.
3085 If yes, offer to stop it and to save the buffer with the changes."
3086 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3087 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3088 (buffer-name))))
3089 (org-clock-out)
3090 (when (y-or-n-p "Save changed buffer?")
3091 (save-buffer))))
3093 (defun org-clocktable-try-shift (dir n)
3094 "Check if this line starts a clock table, if yes, shift the time block."
3095 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3096 (org-clocktable-shift dir n)))
3098 ;; Autoload org-timer.el
3100 (eval-and-compile
3101 (org-autoload
3102 "org-timer"
3103 '(org-timer-start org-timer org-timer-item
3104 org-timer-change-times-in-region)))
3106 ;; Autoload org-feed.el
3108 (eval-and-compile
3109 (org-autoload
3110 "org-feed"
3111 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3114 ;; Autoload archiving code
3115 ;; The stuff that is needed for cycling and tags has to be defined here.
3117 (defgroup org-archive nil
3118 "Options concerning archiving in Org-mode."
3119 :tag "Org Archive"
3120 :group 'org-structure)
3122 (defcustom org-archive-location "%s_archive::"
3123 "The location where subtrees should be archived.
3125 The value of this variable is a string, consisting of two parts,
3126 separated by a double-colon. The first part is a filename and
3127 the second part is a headline.
3129 When the filename is omitted, archiving happens in the same file.
3130 %s in the filename will be replaced by the current file
3131 name (without the directory part). Archiving to a different file
3132 is useful to keep archived entries from contributing to the
3133 Org-mode Agenda.
3135 The archived entries will be filed as subtrees of the specified
3136 headline. When the headline is omitted, the subtrees are simply
3137 filed away at the end of the file, as top-level entries. Also in
3138 the heading you can use %s to represent the file name, this can be
3139 useful when using the same archive for a number of different files.
3141 Here are a few examples:
3142 \"%s_archive::\"
3143 If the current file is Projects.org, archive in file
3144 Projects.org_archive, as top-level trees. This is the default.
3146 \"::* Archived Tasks\"
3147 Archive in the current file, under the top-level headline
3148 \"* Archived Tasks\".
3150 \"~/org/archive.org::\"
3151 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3153 \"~/org/archive.org::From %s\"
3154 Archive in file ~/org/archive.org (absolute path), und headlines
3155 \"From FILENAME\" where file name is the current file name.
3157 \"basement::** Finished Tasks\"
3158 Archive in file ./basement (relative path), as level 3 trees
3159 below the level 2 heading \"** Finished Tasks\".
3161 You may set this option on a per-file basis by adding to the buffer a
3162 line like
3164 #+ARCHIVE: basement::** Finished Tasks
3166 You may also define it locally for a subtree by setting an ARCHIVE property
3167 in the entry. If such a property is found in an entry, or anywhere up
3168 the hierarchy, it will be used."
3169 :group 'org-archive
3170 :type 'string)
3172 (defcustom org-archive-tag "ARCHIVE"
3173 "The tag that marks a subtree as archived.
3174 An archived subtree does not open during visibility cycling, and does
3175 not contribute to the agenda listings.
3176 After changing this, font-lock must be restarted in the relevant buffers to
3177 get the proper fontification."
3178 :group 'org-archive
3179 :group 'org-keywords
3180 :type 'string)
3182 (defcustom org-agenda-skip-archived-trees t
3183 "Non-nil means, the agenda will skip any items located in archived trees.
3184 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3185 variable is no longer recommended, you should leave it at the value t.
3186 Instead, use the key `v' to cycle the archives-mode in the agenda."
3187 :group 'org-archive
3188 :group 'org-agenda-skip
3189 :type 'boolean)
3191 (defcustom org-columns-skip-arrchived-trees t
3192 "Non-nil means, irgnore archived trees when creating column view."
3193 :group 'org-archive
3194 :group 'org-properties
3195 :type 'boolean)
3197 (defcustom org-cycle-open-archived-trees nil
3198 "Non-nil means, `org-cycle' will open archived trees.
3199 An archived tree is a tree marked with the tag ARCHIVE.
3200 When nil, archived trees will stay folded. You can still open them with
3201 normal outline commands like `show-all', but not with the cycling commands."
3202 :group 'org-archive
3203 :group 'org-cycle
3204 :type 'boolean)
3206 (defcustom org-sparse-tree-open-archived-trees nil
3207 "Non-nil means sparse tree construction shows matches in archived trees.
3208 When nil, matches in these trees are highlighted, but the trees are kept in
3209 collapsed state."
3210 :group 'org-archive
3211 :group 'org-sparse-trees
3212 :type 'boolean)
3214 (defun org-cycle-hide-archived-subtrees (state)
3215 "Re-hide all archived subtrees after a visibility state change."
3216 (when (and (not org-cycle-open-archived-trees)
3217 (not (memq state '(overview folded))))
3218 (save-excursion
3219 (let* ((globalp (memq state '(contents all)))
3220 (beg (if globalp (point-min) (point)))
3221 (end (if globalp (point-max) (org-end-of-subtree t))))
3222 (org-hide-archived-subtrees beg end)
3223 (goto-char beg)
3224 (if (looking-at (concat ".*:" org-archive-tag ":"))
3225 (message "%s" (substitute-command-keys
3226 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3228 (defun org-force-cycle-archived ()
3229 "Cycle subtree even if it is archived."
3230 (interactive)
3231 (setq this-command 'org-cycle)
3232 (let ((org-cycle-open-archived-trees t))
3233 (call-interactively 'org-cycle)))
3235 (defun org-hide-archived-subtrees (beg end)
3236 "Re-hide all archived subtrees after a visibility state change."
3237 (save-excursion
3238 (let* ((re (concat ":" org-archive-tag ":")))
3239 (goto-char beg)
3240 (while (re-search-forward re end t)
3241 (and (org-on-heading-p) (hide-subtree))
3242 (org-end-of-subtree t)))))
3244 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3246 (eval-and-compile
3247 (org-autoload "org-archive"
3248 '(org-add-archive-files org-archive-subtree
3249 org-archive-to-archive-sibling org-toggle-archive-tag)))
3251 ;; Autoload Column View Code
3253 (declare-function org-columns-number-to-string "org-colview")
3254 (declare-function org-columns-get-format-and-top-level "org-colview")
3255 (declare-function org-columns-compute "org-colview")
3257 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3258 '(org-columns-number-to-string org-columns-get-format-and-top-level
3259 org-columns-compute org-agenda-columns org-columns-remove-overlays
3260 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3262 ;; Autoload ID code
3264 (declare-function org-id-store-link "org-id")
3265 (declare-function org-id-locations-load "org-id")
3266 (declare-function org-id-locations-save "org-id")
3267 (defvar org-id-track-globally)
3268 (org-autoload "org-id"
3269 '(org-id-get-create org-id-new org-id-copy org-id-get
3270 org-id-get-with-outline-path-completion
3271 org-id-get-with-outline-drilling
3272 org-id-goto org-id-find org-id-store-link))
3274 ;; Autoload Plotting Code
3276 (org-autoload "org-plot"
3277 '(org-plot/gnuplot))
3279 ;;; Variables for pre-computed regular expressions, all buffer local
3281 (defvar org-drawer-regexp nil
3282 "Matches first line of a hidden block.")
3283 (make-variable-buffer-local 'org-drawer-regexp)
3284 (defvar org-todo-regexp nil
3285 "Matches any of the TODO state keywords.")
3286 (make-variable-buffer-local 'org-todo-regexp)
3287 (defvar org-not-done-regexp nil
3288 "Matches any of the TODO state keywords except the last one.")
3289 (make-variable-buffer-local 'org-not-done-regexp)
3290 (defvar org-not-done-heading-regexp nil
3291 "Matches a TODO headline that is not done.")
3292 (make-variable-buffer-local 'org-not-done-regexp)
3293 (defvar org-todo-line-regexp nil
3294 "Matches a headline and puts TODO state into group 2 if present.")
3295 (make-variable-buffer-local 'org-todo-line-regexp)
3296 (defvar org-complex-heading-regexp nil
3297 "Matches a headline and puts everything into groups:
3298 group 1: the stars
3299 group 2: The todo keyword, maybe
3300 group 3: Priority cookie
3301 group 4: True headline
3302 group 5: Tags")
3303 (make-variable-buffer-local 'org-complex-heading-regexp)
3304 (defvar org-todo-line-tags-regexp nil
3305 "Matches a headline and puts TODO state into group 2 if present.
3306 Also put tags into group 4 if tags are present.")
3307 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3308 (defvar org-nl-done-regexp nil
3309 "Matches newline followed by a headline with the DONE keyword.")
3310 (make-variable-buffer-local 'org-nl-done-regexp)
3311 (defvar org-looking-at-done-regexp nil
3312 "Matches the DONE keyword a point.")
3313 (make-variable-buffer-local 'org-looking-at-done-regexp)
3314 (defvar org-ds-keyword-length 12
3315 "Maximum length of the Deadline and SCHEDULED keywords.")
3316 (make-variable-buffer-local 'org-ds-keyword-length)
3317 (defvar org-deadline-regexp nil
3318 "Matches the DEADLINE keyword.")
3319 (make-variable-buffer-local 'org-deadline-regexp)
3320 (defvar org-deadline-time-regexp nil
3321 "Matches the DEADLINE keyword together with a time stamp.")
3322 (make-variable-buffer-local 'org-deadline-time-regexp)
3323 (defvar org-deadline-line-regexp nil
3324 "Matches the DEADLINE keyword and the rest of the line.")
3325 (make-variable-buffer-local 'org-deadline-line-regexp)
3326 (defvar org-scheduled-regexp nil
3327 "Matches the SCHEDULED keyword.")
3328 (make-variable-buffer-local 'org-scheduled-regexp)
3329 (defvar org-scheduled-time-regexp nil
3330 "Matches the SCHEDULED keyword together with a time stamp.")
3331 (make-variable-buffer-local 'org-scheduled-time-regexp)
3332 (defvar org-closed-time-regexp nil
3333 "Matches the CLOSED keyword together with a time stamp.")
3334 (make-variable-buffer-local 'org-closed-time-regexp)
3336 (defvar org-keyword-time-regexp nil
3337 "Matches any of the 4 keywords, together with the time stamp.")
3338 (make-variable-buffer-local 'org-keyword-time-regexp)
3339 (defvar org-keyword-time-not-clock-regexp nil
3340 "Matches any of the 3 keywords, together with the time stamp.")
3341 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3342 (defvar org-maybe-keyword-time-regexp nil
3343 "Matches a timestamp, possibly preceeded by a keyword.")
3344 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3345 (defvar org-planning-or-clock-line-re nil
3346 "Matches a line with planning or clock info.")
3347 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3349 (defconst org-plain-time-of-day-regexp
3350 (concat
3351 "\\(\\<[012]?[0-9]"
3352 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3353 "\\(--?"
3354 "\\(\\<[012]?[0-9]"
3355 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3356 "\\)?")
3357 "Regular expression to match a plain time or time range.
3358 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3359 groups carry important information:
3360 0 the full match
3361 1 the first time, range or not
3362 8 the second time, if it is a range.")
3364 (defconst org-plain-time-extension-regexp
3365 (concat
3366 "\\(\\<[012]?[0-9]"
3367 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3368 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3369 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3370 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3371 groups carry important information:
3372 0 the full match
3373 7 hours of duration
3374 9 minutes of duration")
3376 (defconst org-stamp-time-of-day-regexp
3377 (concat
3378 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3379 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3380 "\\(--?"
3381 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3382 "Regular expression to match a timestamp time or time range.
3383 After a match, the following groups carry important information:
3384 0 the full match
3385 1 date plus weekday, for backreferencing to make sure both times on same day
3386 2 the first time, range or not
3387 4 the second time, if it is a range.")
3389 (defconst org-startup-options
3390 '(("fold" org-startup-folded t)
3391 ("overview" org-startup-folded t)
3392 ("nofold" org-startup-folded nil)
3393 ("showall" org-startup-folded nil)
3394 ("content" org-startup-folded content)
3395 ("hidestars" org-hide-leading-stars t)
3396 ("showstars" org-hide-leading-stars nil)
3397 ("odd" org-odd-levels-only t)
3398 ("oddeven" org-odd-levels-only nil)
3399 ("align" org-startup-align-all-tables t)
3400 ("noalign" org-startup-align-all-tables nil)
3401 ("customtime" org-display-custom-times t)
3402 ("logdone" org-log-done time)
3403 ("lognotedone" org-log-done note)
3404 ("nologdone" org-log-done nil)
3405 ("lognoteclock-out" org-log-note-clock-out t)
3406 ("nolognoteclock-out" org-log-note-clock-out nil)
3407 ("logrepeat" org-log-repeat state)
3408 ("lognoterepeat" org-log-repeat note)
3409 ("nologrepeat" org-log-repeat nil)
3410 ("fninline" org-footnote-define-inline t)
3411 ("nofninline" org-footnote-define-inline nil)
3412 ("fnlocal" org-footnote-section nil)
3413 ("fnauto" org-footnote-auto-label t)
3414 ("fnprompt" org-footnote-auto-label nil)
3415 ("fnconfirm" org-footnote-auto-label confirm)
3416 ("fnplain" org-footnote-auto-label plain)
3417 ("constcgs" constants-unit-system cgs)
3418 ("constSI" constants-unit-system SI)
3419 ("noptag" org-tag-persistent-alist nil)
3420 ("hideblocks" org-hide-block-startup t)
3421 ("nohideblocks" org-hide-block-startup nil))
3422 "Variable associated with STARTUP options for org-mode.
3423 Each element is a list of three items: The startup options as written
3424 in the #+STARTUP line, the corresponding variable, and the value to
3425 set this variable to if the option is found. An optional forth element PUSH
3426 means to push this value onto the list in the variable.")
3428 (defun org-set-regexps-and-options ()
3429 "Precompute regular expressions for current buffer."
3430 (when (org-mode-p)
3431 (org-set-local 'org-todo-kwd-alist nil)
3432 (org-set-local 'org-todo-key-alist nil)
3433 (org-set-local 'org-todo-key-trigger nil)
3434 (org-set-local 'org-todo-keywords-1 nil)
3435 (org-set-local 'org-done-keywords nil)
3436 (org-set-local 'org-todo-heads nil)
3437 (org-set-local 'org-todo-sets nil)
3438 (org-set-local 'org-todo-log-states nil)
3439 (org-set-local 'org-file-properties nil)
3440 (org-set-local 'org-file-tags nil)
3441 (let ((re (org-make-options-regexp
3442 '("CATEGORY" "TODO" "COLUMNS"
3443 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3444 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3445 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3446 (splitre "[ \t]+")
3447 kwds kws0 kwsa key log value cat arch tags const links hw dws
3448 tail sep kws1 prio props ftags drawers
3449 ext-setup-or-nil setup-contents (start 0))
3450 (save-excursion
3451 (save-restriction
3452 (widen)
3453 (goto-char (point-min))
3454 (while (or (and ext-setup-or-nil
3455 (string-match re ext-setup-or-nil start)
3456 (setq start (match-end 0)))
3457 (and (setq ext-setup-or-nil nil start 0)
3458 (re-search-forward re nil t)))
3459 (setq key (upcase (match-string 1 ext-setup-or-nil))
3460 value (org-match-string-no-properties 2 ext-setup-or-nil))
3461 (cond
3462 ((equal key "CATEGORY")
3463 (if (string-match "[ \t]+$" value)
3464 (setq value (replace-match "" t t value)))
3465 (setq cat value))
3466 ((member key '("SEQ_TODO" "TODO"))
3467 (push (cons 'sequence (org-split-string value splitre)) kwds))
3468 ((equal key "TYP_TODO")
3469 (push (cons 'type (org-split-string value splitre)) kwds))
3470 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3471 ;; general TODO-like setup
3472 (push (cons (intern (downcase (match-string 1 key)))
3473 (org-split-string value splitre)) kwds))
3474 ((equal key "TAGS")
3475 (setq tags (append tags (if tags '("\\n") nil)
3476 (org-split-string value splitre))))
3477 ((equal key "COLUMNS")
3478 (org-set-local 'org-columns-default-format value))
3479 ((equal key "LINK")
3480 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3481 (push (cons (match-string 1 value)
3482 (org-trim (match-string 2 value)))
3483 links)))
3484 ((equal key "PRIORITIES")
3485 (setq prio (org-split-string value " +")))
3486 ((equal key "PROPERTY")
3487 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3488 (push (cons (match-string 1 value) (match-string 2 value))
3489 props)))
3490 ((equal key "FILETAGS")
3491 (when (string-match "\\S-" value)
3492 (setq ftags
3493 (append
3494 ftags
3495 (apply 'append
3496 (mapcar (lambda (x) (org-split-string x ":"))
3497 (org-split-string value)))))))
3498 ((equal key "DRAWERS")
3499 (setq drawers (org-split-string value splitre)))
3500 ((equal key "CONSTANTS")
3501 (setq const (append const (org-split-string value splitre))))
3502 ((equal key "STARTUP")
3503 (let ((opts (org-split-string value splitre))
3504 l var val)
3505 (while (setq l (pop opts))
3506 (when (setq l (assoc l org-startup-options))
3507 (setq var (nth 1 l) val (nth 2 l))
3508 (if (not (nth 3 l))
3509 (set (make-local-variable var) val)
3510 (if (not (listp (symbol-value var)))
3511 (set (make-local-variable var) nil))
3512 (set (make-local-variable var) (symbol-value var))
3513 (add-to-list var val))))))
3514 ((equal key "ARCHIVE")
3515 (string-match " *$" value)
3516 (setq arch (replace-match "" t t value))
3517 (remove-text-properties 0 (length arch)
3518 '(face t fontified t) arch))
3519 ((equal key "SETUPFILE")
3520 (setq setup-contents (org-file-contents
3521 (expand-file-name
3522 (org-remove-double-quotes value))
3523 'noerror))
3524 (if (not ext-setup-or-nil)
3525 (setq ext-setup-or-nil setup-contents start 0)
3526 (setq ext-setup-or-nil
3527 (concat (substring ext-setup-or-nil 0 start)
3528 "\n" setup-contents "\n"
3529 (substring ext-setup-or-nil start)))))
3530 ))))
3531 (when cat
3532 (org-set-local 'org-category (intern cat))
3533 (push (cons "CATEGORY" cat) props))
3534 (when prio
3535 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3536 (setq prio (mapcar 'string-to-char prio))
3537 (org-set-local 'org-highest-priority (nth 0 prio))
3538 (org-set-local 'org-lowest-priority (nth 1 prio))
3539 (org-set-local 'org-default-priority (nth 2 prio)))
3540 (and props (org-set-local 'org-file-properties (nreverse props)))
3541 (and ftags (org-set-local 'org-file-tags
3542 (mapcar 'org-add-prop-inherited ftags)))
3543 (and drawers (org-set-local 'org-drawers drawers))
3544 (and arch (org-set-local 'org-archive-location arch))
3545 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3546 ;; Process the TODO keywords
3547 (unless kwds
3548 ;; Use the global values as if they had been given locally.
3549 (setq kwds (default-value 'org-todo-keywords))
3550 (if (stringp (car kwds))
3551 (setq kwds (list (cons org-todo-interpretation
3552 (default-value 'org-todo-keywords)))))
3553 (setq kwds (reverse kwds)))
3554 (setq kwds (nreverse kwds))
3555 (let (inter kws kw)
3556 (while (setq kws (pop kwds))
3557 (let ((kws (or
3558 (run-hook-with-args-until-success
3559 'org-todo-setup-filter-hook kws)
3560 kws)))
3561 (setq inter (pop kws) sep (member "|" kws)
3562 kws0 (delete "|" (copy-sequence kws))
3563 kwsa nil
3564 kws1 (mapcar
3565 (lambda (x)
3566 ;; 1 2
3567 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3568 (progn
3569 (setq kw (match-string 1 x)
3570 key (and (match-end 2) (match-string 2 x))
3571 log (org-extract-log-state-settings x))
3572 (push (cons kw (and key (string-to-char key))) kwsa)
3573 (and log (push log org-todo-log-states))
3575 (error "Invalid TODO keyword %s" x)))
3576 kws0)
3577 kwsa (if kwsa (append '((:startgroup))
3578 (nreverse kwsa)
3579 '((:endgroup))))
3580 hw (car kws1)
3581 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3582 tail (list inter hw (car dws) (org-last dws))))
3583 (add-to-list 'org-todo-heads hw 'append)
3584 (push kws1 org-todo-sets)
3585 (setq org-done-keywords (append org-done-keywords dws nil))
3586 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3587 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3588 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3589 (setq org-todo-sets (nreverse org-todo-sets)
3590 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3591 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3592 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3593 ;; Process the constants
3594 (when const
3595 (let (e cst)
3596 (while (setq e (pop const))
3597 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3598 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3599 (setq org-table-formula-constants-local cst)))
3601 ;; Process the tags.
3602 (when tags
3603 (let (e tgs)
3604 (while (setq e (pop tags))
3605 (cond
3606 ((equal e "{") (push '(:startgroup) tgs))
3607 ((equal e "}") (push '(:endgroup) tgs))
3608 ((equal e "\\n") (push '(:newline) tgs))
3609 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3610 (push (cons (match-string 1 e)
3611 (string-to-char (match-string 2 e)))
3612 tgs))
3613 (t (push (list e) tgs))))
3614 (org-set-local 'org-tag-alist nil)
3615 (while (setq e (pop tgs))
3616 (or (and (stringp (car e))
3617 (assoc (car e) org-tag-alist))
3618 (push e org-tag-alist)))))
3620 ;; Compute the regular expressions and other local variables
3621 (if (not org-done-keywords)
3622 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3623 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3624 (length org-scheduled-string)
3625 (length org-clock-string)
3626 (length org-closed-string)))
3627 org-drawer-regexp
3628 (concat "^[ \t]*:\\("
3629 (mapconcat 'regexp-quote org-drawers "\\|")
3630 "\\):[ \t]*$")
3631 org-not-done-keywords
3632 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3633 org-todo-regexp
3634 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3635 "\\|") "\\)\\>")
3636 org-not-done-regexp
3637 (concat "\\<\\("
3638 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3639 "\\)\\>")
3640 org-not-done-heading-regexp
3641 (concat "^\\(\\*+\\)[ \t]+\\("
3642 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3643 "\\)\\>")
3644 org-todo-line-regexp
3645 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3646 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3647 "\\)\\>\\)?[ \t]*\\(.*\\)")
3648 org-complex-heading-regexp
3649 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3650 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3651 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3652 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3653 org-nl-done-regexp
3654 (concat "\n\\*+[ \t]+"
3655 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3656 "\\)" "\\>")
3657 org-todo-line-tags-regexp
3658 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3659 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3660 (org-re
3661 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3662 org-looking-at-done-regexp
3663 (concat "^" "\\(?:"
3664 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3665 "\\>")
3666 org-deadline-regexp (concat "\\<" org-deadline-string)
3667 org-deadline-time-regexp
3668 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3669 org-deadline-line-regexp
3670 (concat "\\<\\(" org-deadline-string "\\).*")
3671 org-scheduled-regexp
3672 (concat "\\<" org-scheduled-string)
3673 org-scheduled-time-regexp
3674 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3675 org-closed-time-regexp
3676 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3677 org-keyword-time-regexp
3678 (concat "\\<\\(" org-scheduled-string
3679 "\\|" org-deadline-string
3680 "\\|" org-closed-string
3681 "\\|" org-clock-string "\\)"
3682 " *[[<]\\([^]>]+\\)[]>]")
3683 org-keyword-time-not-clock-regexp
3684 (concat "\\<\\(" org-scheduled-string
3685 "\\|" org-deadline-string
3686 "\\|" org-closed-string
3687 "\\)"
3688 " *[[<]\\([^]>]+\\)[]>]")
3689 org-maybe-keyword-time-regexp
3690 (concat "\\(\\<\\(" org-scheduled-string
3691 "\\|" org-deadline-string
3692 "\\|" org-closed-string
3693 "\\|" org-clock-string "\\)\\)?"
3694 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3695 org-planning-or-clock-line-re
3696 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3697 "\\|" org-deadline-string
3698 "\\|" org-closed-string "\\|" org-clock-string
3699 "\\)\\>\\)")
3701 (org-compute-latex-and-specials-regexp)
3702 (org-set-font-lock-defaults))))
3704 (defun org-file-contents (file &optional noerror)
3705 "Return the contents of FILE, as a string."
3706 (if (or (not file)
3707 (not (file-readable-p file)))
3708 (if noerror
3709 (progn
3710 (message "Cannot read file %s" file)
3711 (ding) (sit-for 2)
3713 (error "Cannot read file %s" file))
3714 (with-temp-buffer
3715 (insert-file-contents file)
3716 (buffer-string))))
3718 (defun org-extract-log-state-settings (x)
3719 "Extract the log state setting from a TODO keyword string.
3720 This will extract info from a string like \"WAIT(w@/!)\"."
3721 (let (kw key log1 log2)
3722 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3723 (setq kw (match-string 1 x)
3724 key (and (match-end 2) (match-string 2 x))
3725 log1 (and (match-end 3) (match-string 3 x))
3726 log2 (and (match-end 4) (match-string 4 x)))
3727 (and (or log1 log2)
3728 (list kw
3729 (and log1 (if (equal log1 "!") 'time 'note))
3730 (and log2 (if (equal log2 "!") 'time 'note)))))))
3732 (defun org-remove-keyword-keys (list)
3733 "Remove a pair of parenthesis at the end of each string in LIST."
3734 (mapcar (lambda (x)
3735 (if (string-match "(.*)$" x)
3736 (substring x 0 (match-beginning 0))
3738 list))
3740 ;; FIXME: this could be done much better, using second characters etc.
3741 (defun org-assign-fast-keys (alist)
3742 "Assign fast keys to a keyword-key alist.
3743 Respect keys that are already there."
3744 (let (new e k c c1 c2 (char ?a))
3745 (while (setq e (pop alist))
3746 (cond
3747 ((equal e '(:startgroup)) (push e new))
3748 ((equal e '(:endgroup)) (push e new))
3749 ((equal e '(:newline)) (push e new))
3751 (setq k (car e) c2 nil)
3752 (if (cdr e)
3753 (setq c (cdr e))
3754 ;; automatically assign a character.
3755 (setq c1 (string-to-char
3756 (downcase (substring
3757 k (if (= (string-to-char k) ?@) 1 0)))))
3758 (if (or (rassoc c1 new) (rassoc c1 alist))
3759 (while (or (rassoc char new) (rassoc char alist))
3760 (setq char (1+ char)))
3761 (setq c2 c1))
3762 (setq c (or c2 char)))
3763 (push (cons k c) new))))
3764 (nreverse new)))
3766 ;;; Some variables used in various places
3768 (defvar org-window-configuration nil
3769 "Used in various places to store a window configuration.")
3770 (defvar org-finish-function nil
3771 "Function to be called when `C-c C-c' is used.
3772 This is for getting out of special buffers like remember.")
3775 ;; FIXME: Occasionally check by commenting these, to make sure
3776 ;; no other functions uses these, forgetting to let-bind them.
3777 (defvar entry)
3778 (defvar last-state)
3779 (defvar date)
3781 ;; Defined somewhere in this file, but used before definition.
3782 (defvar org-html-entities)
3783 (defvar org-struct-menu)
3784 (defvar org-org-menu)
3785 (defvar org-tbl-menu)
3786 (defvar org-agenda-keymap)
3788 ;;;; Define the Org-mode
3790 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3791 (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."))
3794 ;; We use a before-change function to check if a table might need
3795 ;; an update.
3796 (defvar org-table-may-need-update t
3797 "Indicates that a table might need an update.
3798 This variable is set by `org-before-change-function'.
3799 `org-table-align' sets it back to nil.")
3800 (defun org-before-change-function (beg end)
3801 "Every change indicates that a table might need an update."
3802 (setq org-table-may-need-update t))
3803 (defvar org-mode-map)
3804 (defvar org-mode-hook nil
3805 "Mode hook for Org-mode, run after the mode was turned on.")
3806 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3807 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3808 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3809 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
3810 (defvar org-table-buffer-is-an nil)
3811 (defconst org-outline-regexp "\\*+ ")
3813 ;;;###autoload
3814 (define-derived-mode org-mode outline-mode "Org"
3815 "Outline-based notes management and organizer, alias
3816 \"Carsten's outline-mode for keeping track of everything.\"
3818 Org-mode develops organizational tasks around a NOTES file which
3819 contains information about projects as plain text. Org-mode is
3820 implemented on top of outline-mode, which is ideal to keep the content
3821 of large files well structured. It supports ToDo items, deadlines and
3822 time stamps, which magically appear in the diary listing of the Emacs
3823 calendar. Tables are easily created with a built-in table editor.
3824 Plain text URL-like links connect to websites, emails (VM), Usenet
3825 messages (Gnus), BBDB entries, and any files related to the project.
3826 For printing and sharing of notes, an Org-mode file (or a part of it)
3827 can be exported as a structured ASCII or HTML file.
3829 The following commands are available:
3831 \\{org-mode-map}"
3833 ;; Get rid of Outline menus, they are not needed
3834 ;; Need to do this here because define-derived-mode sets up
3835 ;; the keymap so late. Still, it is a waste to call this each time
3836 ;; we switch another buffer into org-mode.
3837 (if (featurep 'xemacs)
3838 (when (boundp 'outline-mode-menu-heading)
3839 ;; Assume this is Greg's port, it used easymenu
3840 (easy-menu-remove outline-mode-menu-heading)
3841 (easy-menu-remove outline-mode-menu-show)
3842 (easy-menu-remove outline-mode-menu-hide))
3843 (define-key org-mode-map [menu-bar headings] 'undefined)
3844 (define-key org-mode-map [menu-bar hide] 'undefined)
3845 (define-key org-mode-map [menu-bar show] 'undefined))
3847 (org-load-modules-maybe)
3848 (easy-menu-add org-org-menu)
3849 (easy-menu-add org-tbl-menu)
3850 (org-install-agenda-files-menu)
3851 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3852 (org-add-to-invisibility-spec '(org-cwidth))
3853 (org-add-to-invisibility-spec '(org-hide-block . t))
3854 (when (featurep 'xemacs)
3855 (org-set-local 'line-move-ignore-invisible t))
3856 (org-set-local 'outline-regexp org-outline-regexp)
3857 (org-set-local 'outline-level 'org-outline-level)
3858 (when (and org-ellipsis
3859 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3860 (fboundp 'make-glyph-code))
3861 (unless org-display-table
3862 (setq org-display-table (make-display-table)))
3863 (set-display-table-slot
3864 org-display-table 4
3865 (vconcat (mapcar
3866 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3867 org-ellipsis)))
3868 (if (stringp org-ellipsis) org-ellipsis "..."))))
3869 (setq buffer-display-table org-display-table))
3870 (org-set-regexps-and-options)
3871 (when (and org-tag-faces (not org-tags-special-faces-re))
3872 ;; tag faces set outside customize.... force initialization.
3873 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3874 ;; Calc embedded
3875 (org-set-local 'calc-embedded-open-mode "# ")
3876 (modify-syntax-entry ?# "<")
3877 (modify-syntax-entry ?@ "w")
3878 (if org-startup-truncated (setq truncate-lines t))
3879 (org-set-local 'font-lock-unfontify-region-function
3880 'org-unfontify-region)
3881 ;; Activate before-change-function
3882 (org-set-local 'org-table-may-need-update t)
3883 (org-add-hook 'before-change-functions 'org-before-change-function nil
3884 'local)
3885 ;; Check for running clock before killing a buffer
3886 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3887 ;; Paragraphs and auto-filling
3888 (org-set-autofill-regexps)
3889 (setq indent-line-function 'org-indent-line-function)
3890 (org-update-radio-target-regexp)
3891 ;; Make sure dependence stuff works reliably, even for users who set it
3892 ;; too late :-(
3893 (if org-enforce-todo-dependencies
3894 (add-hook 'org-blocker-hook
3895 'org-block-todo-from-children-or-siblings-or-parent)
3896 (remove-hook 'org-blocker-hook
3897 'org-block-todo-from-children-or-siblings-or-parent))
3898 (if org-enforce-todo-checkbox-dependencies
3899 (add-hook 'org-blocker-hook
3900 'org-block-todo-from-checkboxes)
3901 (remove-hook 'org-blocker-hook
3902 'org-block-todo-from-checkboxes))
3904 ;; Comment characters
3905 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3906 (org-set-local 'comment-padding " ")
3908 ;; Align options lines
3909 (org-set-local
3910 'align-mode-rules-list
3911 '((org-in-buffer-settings
3912 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3913 (modes . '(org-mode)))))
3915 ;; Imenu
3916 (org-set-local 'imenu-create-index-function
3917 'org-imenu-get-tree)
3919 ;; Make isearch reveal context
3920 (if (or (featurep 'xemacs)
3921 (not (boundp 'outline-isearch-open-invisible-function)))
3922 ;; Emacs 21 and XEmacs make use of the hook
3923 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3924 ;; Emacs 22 deals with this through a special variable
3925 (org-set-local 'outline-isearch-open-invisible-function
3926 (lambda (&rest ignore) (org-show-context 'isearch))))
3928 ;; If empty file that did not turn on org-mode automatically, make it to.
3929 (if (and org-insert-mode-line-in-empty-file
3930 (interactive-p)
3931 (= (point-min) (point-max)))
3932 (insert "# -*- mode: org -*-\n\n"))
3934 (unless org-inhibit-startup
3935 (when org-startup-align-all-tables
3936 (let ((bmp (buffer-modified-p)))
3937 (org-table-map-tables 'org-table-align)
3938 (set-buffer-modified-p bmp)))
3939 (org-set-startup-visibility)))
3941 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3943 (defun org-current-time ()
3944 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3945 (if (> (car org-time-stamp-rounding-minutes) 1)
3946 (let ((r (car org-time-stamp-rounding-minutes))
3947 (time (decode-time)))
3948 (apply 'encode-time
3949 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3950 (nthcdr 2 time))))
3951 (current-time)))
3953 ;;;; Font-Lock stuff, including the activators
3955 (defvar org-mouse-map (make-sparse-keymap))
3956 (org-defkey org-mouse-map
3957 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3958 (org-defkey org-mouse-map
3959 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3960 (when org-mouse-1-follows-link
3961 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3962 (when org-tab-follows-link
3963 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3964 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3966 (require 'font-lock)
3968 (defconst org-non-link-chars "]\t\n\r<>")
3969 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3970 "shell" "elisp"))
3971 (defvar org-link-types-re nil
3972 "Matches a link that has a url-like prefix like \"http:\"")
3973 (defvar org-link-re-with-space nil
3974 "Matches a link with spaces, optional angular brackets around it.")
3975 (defvar org-link-re-with-space2 nil
3976 "Matches a link with spaces, optional angular brackets around it.")
3977 (defvar org-link-re-with-space3 nil
3978 "Matches a link with spaces, only for internal part in bracket links.")
3979 (defvar org-angle-link-re nil
3980 "Matches link with angular brackets, spaces are allowed.")
3981 (defvar org-plain-link-re nil
3982 "Matches plain link, without spaces.")
3983 (defvar org-bracket-link-regexp nil
3984 "Matches a link in double brackets.")
3985 (defvar org-bracket-link-analytic-regexp nil
3986 "Regular expression used to analyze links.
3987 Here is what the match groups contain after a match:
3988 1: http:
3989 2: http
3990 3: path
3991 4: [desc]
3992 5: desc")
3993 (defvar org-bracket-link-analytic-regexp++ nil
3994 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3995 (defvar org-any-link-re nil
3996 "Regular expression matching any link.")
3998 (defun org-make-link-regexps ()
3999 "Update the link regular expressions.
4000 This should be called after the variable `org-link-types' has changed."
4001 (setq org-link-types-re
4002 (concat
4003 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4004 org-link-re-with-space
4005 (concat
4006 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4007 "\\([^" org-non-link-chars " ]"
4008 "[^" org-non-link-chars "]*"
4009 "[^" org-non-link-chars " ]\\)>?")
4010 org-link-re-with-space2
4011 (concat
4012 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4013 "\\([^" org-non-link-chars " ]"
4014 "[^\t\n\r]*"
4015 "[^" org-non-link-chars " ]\\)>?")
4016 org-link-re-with-space3
4017 (concat
4018 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4019 "\\([^" org-non-link-chars " ]"
4020 "[^\t\n\r]*\\)")
4021 org-angle-link-re
4022 (concat
4023 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4024 "\\([^" org-non-link-chars " ]"
4025 "[^" org-non-link-chars "]*"
4026 "\\)>")
4027 org-plain-link-re
4028 (concat
4029 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4030 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4031 org-bracket-link-regexp
4032 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4033 org-bracket-link-analytic-regexp
4034 (concat
4035 "\\[\\["
4036 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4037 "\\([^]]+\\)"
4038 "\\]"
4039 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4040 "\\]")
4041 org-bracket-link-analytic-regexp++
4042 (concat
4043 "\\[\\["
4044 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4045 "\\([^]]+\\)"
4046 "\\]"
4047 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4048 "\\]")
4049 org-any-link-re
4050 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4051 org-angle-link-re "\\)\\|\\("
4052 org-plain-link-re "\\)")))
4054 (org-make-link-regexps)
4056 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4057 "Regular expression for fast time stamp matching.")
4058 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4059 "Regular expression for fast time stamp matching.")
4060 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4061 "Regular expression matching time strings for analysis.
4062 This one does not require the space after the date, so it can be used
4063 on a string that terminates immediately after the date.")
4064 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4065 "Regular expression matching time strings for analysis.")
4066 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4067 "Regular expression matching time stamps, with groups.")
4068 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4069 "Regular expression matching time stamps (also [..]), with groups.")
4070 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4071 "Regular expression matching a time stamp range.")
4072 (defconst org-tr-regexp-both
4073 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4074 "Regular expression matching a time stamp range.")
4075 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4076 org-ts-regexp "\\)?")
4077 "Regular expression matching a time stamp or time stamp range.")
4078 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4079 org-ts-regexp-both "\\)?")
4080 "Regular expression matching a time stamp or time stamp range.
4081 The time stamps may be either active or inactive.")
4083 (defvar org-emph-face nil)
4085 (defun org-do-emphasis-faces (limit)
4086 "Run through the buffer and add overlays to links."
4087 (let (rtn a)
4088 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4089 (if (not (= (char-after (match-beginning 3))
4090 (char-after (match-beginning 4))))
4091 (progn
4092 (setq rtn t)
4093 (setq a (assoc (match-string 3) org-emphasis-alist))
4094 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4095 'face
4096 (nth 1 a))
4097 (and (nth 4 a)
4098 (org-remove-flyspell-overlays-in
4099 (match-beginning 0) (match-end 0)))
4100 (add-text-properties (match-beginning 2) (match-end 2)
4101 '(font-lock-multiline t))
4102 (when org-hide-emphasis-markers
4103 (add-text-properties (match-end 4) (match-beginning 5)
4104 '(invisible org-link))
4105 (add-text-properties (match-beginning 3) (match-end 3)
4106 '(invisible org-link)))))
4107 (backward-char 1))
4108 rtn))
4110 (defun org-emphasize (&optional char)
4111 "Insert or change an emphasis, i.e. a font like bold or italic.
4112 If there is an active region, change that region to a new emphasis.
4113 If there is no region, just insert the marker characters and position
4114 the cursor between them.
4115 CHAR should be either the marker character, or the first character of the
4116 HTML tag associated with that emphasis. If CHAR is a space, the means
4117 to remove the emphasis of the selected region.
4118 If char is not given (for example in an interactive call) it
4119 will be prompted for."
4120 (interactive)
4121 (let ((eal org-emphasis-alist) e det
4122 (erc org-emphasis-regexp-components)
4123 (prompt "")
4124 (string "") beg end move tag c s)
4125 (if (org-region-active-p)
4126 (setq beg (region-beginning) end (region-end)
4127 string (buffer-substring beg end))
4128 (setq move t))
4130 (while (setq e (pop eal))
4131 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4132 c (aref tag 0))
4133 (push (cons c (string-to-char (car e))) det)
4134 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4135 (substring tag 1)))))
4136 (setq det (nreverse det))
4137 (unless char
4138 (message "%s" (concat "Emphasis marker or tag:" prompt))
4139 (setq char (read-char-exclusive)))
4140 (setq char (or (cdr (assoc char det)) char))
4141 (if (equal char ?\ )
4142 (setq s "" move nil)
4143 (unless (assoc (char-to-string char) org-emphasis-alist)
4144 (error "No such emphasis marker: \"%c\"" char))
4145 (setq s (char-to-string char)))
4146 (while (and (> (length string) 1)
4147 (equal (substring string 0 1) (substring string -1))
4148 (assoc (substring string 0 1) org-emphasis-alist))
4149 (setq string (substring string 1 -1)))
4150 (setq string (concat s string s))
4151 (if beg (delete-region beg end))
4152 (unless (or (bolp)
4153 (string-match (concat "[" (nth 0 erc) "\n]")
4154 (char-to-string (char-before (point)))))
4155 (insert " "))
4156 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4157 (char-to-string (char-after (point))))
4158 (insert " ") (backward-char 1))
4159 (insert string)
4160 (and move (backward-char 1))))
4162 (defconst org-nonsticky-props
4163 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4165 (defsubst org-rear-nonsticky-at (pos)
4166 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4168 (defun org-activate-plain-links (limit)
4169 "Run through the buffer and add overlays to links."
4170 (catch 'exit
4171 (let (f)
4172 (while (re-search-forward org-plain-link-re limit t)
4173 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4174 (setq f (get-text-property (match-beginning 0) 'face))
4175 (if (or (eq f 'org-tag)
4176 (and (listp f) (memq 'org-tag f)))
4178 (add-text-properties (match-beginning 0) (match-end 0)
4179 (list 'mouse-face 'highlight
4180 'keymap org-mouse-map))
4181 (org-rear-nonsticky-at (match-end 0))
4182 (throw 'exit t))))))
4184 (defun org-activate-code (limit)
4185 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4186 (progn
4187 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4188 (remove-text-properties (match-beginning 0) (match-end 0)
4189 '(display t invisible t intangible t))
4190 t)))
4192 (defun org-fontify-meta-lines-and-blocks (limit)
4193 "Fontify #+ lines and blocks, in the correct ways."
4194 (let ((case-fold-search t))
4195 (if (re-search-forward
4196 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4197 limit t)
4198 (let ((beg (match-beginning 0))
4199 (beg1 (line-beginning-position 2))
4200 (dc1 (downcase (match-string 2)))
4201 (dc3 (downcase (match-string 3)))
4202 end end1 quoting)
4203 (cond
4204 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4205 ;; a single line of backend-specific content
4206 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4207 (remove-text-properties (match-beginning 0) (match-end 0)
4208 '(display t invisible t intangible t))
4209 (add-text-properties (match-beginning 1) (match-end 3)
4210 '(font-lock-fontified t face org-meta-line))
4211 (add-text-properties (match-beginning 6) (match-end 6)
4212 '(font-lock-fontified t face org-block))
4214 ((and (match-end 4) (equal dc3 "begin"))
4215 ;; Truely a block
4216 (setq quoting (member (downcase (match-string 5))
4217 org-protecting-blocks))
4218 (when (re-search-forward
4219 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4220 nil t) ;; on purpose, we look further than LIMIT
4221 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4222 (when quoting
4223 (remove-text-properties beg end
4224 '(display t invisible t intangible t)))
4225 (add-text-properties
4226 beg end
4227 '(font-lock-fontified t font-lock-multiline t))
4228 (add-text-properties beg beg1 '(face org-meta-line))
4229 (add-text-properties end1 end '(face org-meta-line))
4230 (when quoting
4231 (add-text-properties beg1 end1 '(face org-block)))
4233 ((not (member (char-after beg) '(?\ ?\t)))
4234 ;; just any other in-buffer setting, but not indented
4235 (add-text-properties
4236 beg (match-end 0)
4237 '(font-lock-fontified t face org-meta-line))
4239 ((or (member dc1 '("caption:" "label:" "orgtbl:" "tblfm:"))
4240 (and (match-end 4) (equal dc3 "attr")))
4241 (add-text-properties
4242 beg (match-end 0)
4243 '(font-lock-fontified t face org-meta-line))
4245 (t nil))))))
4247 (defun org-activate-angle-links (limit)
4248 "Run through the buffer and add overlays to links."
4249 (if (re-search-forward org-angle-link-re limit t)
4250 (progn
4251 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4252 (add-text-properties (match-beginning 0) (match-end 0)
4253 (list 'mouse-face 'highlight
4254 'keymap org-mouse-map))
4255 (org-rear-nonsticky-at (match-end 0))
4256 t)))
4258 (defun org-activate-footnote-links (limit)
4259 "Run through the buffer and add overlays to links."
4260 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4261 limit t)
4262 (progn
4263 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4264 (add-text-properties (match-beginning 2) (match-end 2)
4265 (list 'mouse-face 'highlight
4266 'keymap org-mouse-map
4267 'help-echo
4268 (if (= (point-at-bol) (match-beginning 2))
4269 "Footnote definition"
4270 "Footnote reference")
4272 (org-rear-nonsticky-at (match-end 2))
4273 t)))
4275 (defun org-activate-bracket-links (limit)
4276 "Run through the buffer and add overlays to bracketed links."
4277 (if (re-search-forward org-bracket-link-regexp limit t)
4278 (let* ((help (concat "LINK: "
4279 (org-match-string-no-properties 1)))
4280 ;; FIXME: above we should remove the escapes.
4281 ;; but that requires another match, protecting match data,
4282 ;; a lot of overhead for font-lock.
4283 (ip (org-maybe-intangible
4284 (list 'invisible 'org-link
4285 'keymap org-mouse-map 'mouse-face 'highlight
4286 'font-lock-multiline t 'help-echo help)))
4287 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4288 'font-lock-multiline t 'help-echo help)))
4289 ;; We need to remove the invisible property here. Table narrowing
4290 ;; may have made some of this invisible.
4291 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4292 (remove-text-properties (match-beginning 0) (match-end 0)
4293 '(invisible nil))
4294 (if (match-end 3)
4295 (progn
4296 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4297 (org-rear-nonsticky-at (match-beginning 3))
4298 (add-text-properties (match-beginning 3) (match-end 3) vp)
4299 (org-rear-nonsticky-at (match-end 3))
4300 (add-text-properties (match-end 3) (match-end 0) ip)
4301 (org-rear-nonsticky-at (match-end 0)))
4302 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4303 (org-rear-nonsticky-at (match-beginning 1))
4304 (add-text-properties (match-beginning 1) (match-end 1) vp)
4305 (org-rear-nonsticky-at (match-end 1))
4306 (add-text-properties (match-end 1) (match-end 0) ip)
4307 (org-rear-nonsticky-at (match-end 0)))
4308 t)))
4310 (defun org-activate-dates (limit)
4311 "Run through the buffer and add overlays to dates."
4312 (if (re-search-forward org-tsr-regexp-both limit t)
4313 (progn
4314 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4315 (add-text-properties (match-beginning 0) (match-end 0)
4316 (list 'mouse-face 'highlight
4317 'keymap org-mouse-map))
4318 (org-rear-nonsticky-at (match-end 0))
4319 (when org-display-custom-times
4320 (if (match-end 3)
4321 (org-display-custom-time (match-beginning 3) (match-end 3)))
4322 (org-display-custom-time (match-beginning 1) (match-end 1)))
4323 t)))
4325 (defvar org-target-link-regexp nil
4326 "Regular expression matching radio targets in plain text.")
4327 (make-variable-buffer-local 'org-target-link-regexp)
4328 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4329 "Regular expression matching a link target.")
4330 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4331 "Regular expression matching a radio target.")
4332 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4333 "Regular expression matching any target.")
4335 (defun org-activate-target-links (limit)
4336 "Run through the buffer and add overlays to target matches."
4337 (when org-target-link-regexp
4338 (let ((case-fold-search t))
4339 (if (re-search-forward org-target-link-regexp limit t)
4340 (progn
4341 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4342 (add-text-properties (match-beginning 0) (match-end 0)
4343 (list 'mouse-face 'highlight
4344 'keymap org-mouse-map
4345 'help-echo "Radio target link"
4346 'org-linked-text t))
4347 (org-rear-nonsticky-at (match-end 0))
4348 t)))))
4350 (defun org-update-radio-target-regexp ()
4351 "Find all radio targets in this file and update the regular expression."
4352 (interactive)
4353 (when (memq 'radio org-activate-links)
4354 (setq org-target-link-regexp
4355 (org-make-target-link-regexp (org-all-targets 'radio)))
4356 (org-restart-font-lock)))
4358 (defun org-hide-wide-columns (limit)
4359 (let (s e)
4360 (setq s (text-property-any (point) (or limit (point-max))
4361 'org-cwidth t))
4362 (when s
4363 (setq e (next-single-property-change s 'org-cwidth))
4364 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4365 (goto-char e)
4366 t)))
4368 (defvar org-latex-and-specials-regexp nil
4369 "Regular expression for highlighting export special stuff.")
4370 (defvar org-match-substring-regexp)
4371 (defvar org-match-substring-with-braces-regexp)
4372 (defvar org-export-html-special-string-regexps)
4374 (defun org-compute-latex-and-specials-regexp ()
4375 "Compute regular expression for stuff treated specially by exporters."
4376 (if (not org-highlight-latex-fragments-and-specials)
4377 (org-set-local 'org-latex-and-specials-regexp nil)
4378 (require 'org-exp)
4379 (let*
4380 ((matchers (plist-get org-format-latex-options :matchers))
4381 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4382 org-latex-regexps)))
4383 (options (org-combine-plists (org-default-export-plist)
4384 (org-infile-export-plist)))
4385 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4386 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4387 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4388 (org-export-html-expand (plist-get options :expand-quoted-html))
4389 (org-export-with-special-strings (plist-get options :special-strings))
4390 (re-sub
4391 (cond
4392 ((equal org-export-with-sub-superscripts '{})
4393 (list org-match-substring-with-braces-regexp))
4394 (org-export-with-sub-superscripts
4395 (list org-match-substring-regexp))
4396 (t nil)))
4397 (re-latex
4398 (if org-export-with-LaTeX-fragments
4399 (mapcar (lambda (x) (nth 1 x)) latexs)))
4400 (re-macros
4401 (if org-export-with-TeX-macros
4402 (list (concat "\\\\"
4403 (regexp-opt
4404 (append (mapcar 'car org-html-entities)
4405 (if (boundp 'org-latex-entities)
4406 (mapcar (lambda (x)
4407 (or (car-safe x) x))
4408 org-latex-entities)
4409 nil))
4410 'words))) ; FIXME
4412 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4413 (re-special (if org-export-with-special-strings
4414 (mapcar (lambda (x) (car x))
4415 org-export-html-special-string-regexps)))
4416 (re-rest
4417 (delq nil
4418 (list
4419 (if org-export-html-expand "@<[^>\n]+>")
4420 ))))
4421 (org-set-local
4422 'org-latex-and-specials-regexp
4423 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4424 re-rest) "\\|")))))
4426 (defun org-do-latex-and-special-faces (limit)
4427 "Run through the buffer and add overlays to links."
4428 (when org-latex-and-specials-regexp
4429 (let (rtn d)
4430 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4431 limit t))
4432 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4433 'face))
4434 '(org-code org-verbatim underline)))
4435 (progn
4436 (setq rtn t
4437 d (cond ((member (char-after (1+ (match-beginning 0)))
4438 '(?_ ?^)) 1)
4439 (t 0)))
4440 (font-lock-prepend-text-property
4441 (+ d (match-beginning 0)) (match-end 0)
4442 'face 'org-latex-and-export-specials)
4443 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4444 '(font-lock-multiline t)))))
4445 rtn)))
4447 (defun org-restart-font-lock ()
4448 "Restart font-lock-mode, to force refontification."
4449 (when (and (boundp 'font-lock-mode) font-lock-mode)
4450 (font-lock-mode -1)
4451 (font-lock-mode 1)))
4453 (defun org-all-targets (&optional radio)
4454 "Return a list of all targets in this file.
4455 With optional argument RADIO, only find radio targets."
4456 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4457 rtn)
4458 (save-excursion
4459 (goto-char (point-min))
4460 (while (re-search-forward re nil t)
4461 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4462 rtn)))
4464 (defun org-make-target-link-regexp (targets)
4465 "Make regular expression matching all strings in TARGETS.
4466 The regular expression finds the targets also if there is a line break
4467 between words."
4468 (and targets
4469 (concat
4470 "\\<\\("
4471 (mapconcat
4472 (lambda (x)
4473 (while (string-match " +" x)
4474 (setq x (replace-match "\\s-+" t t x)))
4476 targets
4477 "\\|")
4478 "\\)\\>")))
4480 (defun org-activate-tags (limit)
4481 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4482 (progn
4483 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4484 (add-text-properties (match-beginning 1) (match-end 1)
4485 (list 'mouse-face 'highlight
4486 'keymap org-mouse-map))
4487 (org-rear-nonsticky-at (match-end 1))
4488 t)))
4490 (defun org-outline-level ()
4491 (save-excursion
4492 (looking-at outline-regexp)
4493 (if (match-beginning 1)
4494 (+ (org-get-string-indentation (match-string 1)) 1000)
4495 (1- (- (match-end 0) (match-beginning 0))))))
4497 (defvar org-font-lock-keywords nil)
4499 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4500 "Regular expression matching a property line.")
4502 (defvar org-font-lock-hook nil
4503 "Functions to be called for special font lock stuff.")
4505 (defun org-font-lock-hook (limit)
4506 (run-hook-with-args 'org-font-lock-hook limit))
4508 (defun org-set-font-lock-defaults ()
4509 (let* ((em org-fontify-emphasized-text)
4510 (lk org-activate-links)
4511 (org-font-lock-extra-keywords
4512 (list
4513 ;; Call the hook
4514 '(org-font-lock-hook)
4515 ;; Headlines
4516 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4517 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4518 ;; Table lines
4519 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4520 (1 'org-table t))
4521 ;; Table internals
4522 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4523 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4524 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4525 ;; Drawers
4526 (list org-drawer-regexp '(0 'org-special-keyword t))
4527 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4528 ;; Properties
4529 (list org-property-re
4530 '(1 'org-special-keyword t)
4531 '(3 'org-property-value t))
4532 (if org-format-transports-properties-p
4533 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4534 ;; Links
4535 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4536 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4537 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4538 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4539 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4540 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4541 (if (memq 'footnote lk) '(org-activate-footnote-links
4542 (2 'org-footnote t)))
4543 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4544 '(org-hide-wide-columns (0 nil append))
4545 ;; TODO lines
4546 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4547 '(1 (org-get-todo-face 1) t))
4548 ;; DONE
4549 (if org-fontify-done-headline
4550 (list (concat "^[*]+ +\\<\\("
4551 (mapconcat 'regexp-quote org-done-keywords "\\|")
4552 "\\)\\(.*\\)")
4553 '(2 'org-headline-done t))
4554 nil)
4555 ;; Priorities
4556 '(org-font-lock-add-priority-faces)
4557 ;; Tags
4558 '(org-font-lock-add-tag-faces)
4559 ;; Special keywords
4560 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4561 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4562 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4563 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4564 ;; Emphasis
4565 (if em
4566 (if (featurep 'xemacs)
4567 '(org-do-emphasis-faces (0 nil append))
4568 '(org-do-emphasis-faces)))
4569 ;; Checkboxes
4570 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4571 2 'org-checkbox prepend)
4572 (if org-provide-checkbox-statistics
4573 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4574 (0 (org-get-checkbox-statistics-face) t)))
4575 ;; Description list items
4576 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4577 2 'bold prepend)
4578 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4579 '(1 'org-archived prepend))
4580 ;; Specials
4581 '(org-do-latex-and-special-faces)
4582 ;; Code
4583 '(org-activate-code (1 'org-code t))
4584 ;; COMMENT
4585 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4586 "\\|" org-quote-string "\\)\\>")
4587 '(1 'org-special-keyword t))
4588 '("^#.*" (0 'font-lock-comment-face t))
4589 ;; Blocks and meta lines
4590 '(org-fontify-meta-lines-and-blocks)
4592 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4593 ;; Now set the full font-lock-keywords
4594 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4595 (org-set-local 'font-lock-defaults
4596 '(org-font-lock-keywords t nil nil backward-paragraph))
4597 (kill-local-variable 'font-lock-keywords) nil))
4599 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4600 "Fontify string S like in Org-mode"
4601 (with-temp-buffer
4602 (insert s)
4603 (let ((org-odd-levels-only odd-levels))
4604 (org-mode)
4605 (font-lock-fontify-buffer)
4606 (buffer-string))))
4608 (defvar org-m nil)
4609 (defvar org-l nil)
4610 (defvar org-f nil)
4611 (defun org-get-level-face (n)
4612 "Get the right face for match N in font-lock matching of headlines."
4613 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4614 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4615 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4616 (cond
4617 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4618 ((eq n 2) org-f)
4619 (t (if org-level-color-stars-only nil org-f))))
4621 (defun org-get-todo-face (kwd)
4622 "Get the right face for a TODO keyword KWD.
4623 If KWD is a number, get the corresponding match group."
4624 (if (numberp kwd) (setq kwd (match-string kwd)))
4625 (or (cdr (assoc kwd org-todo-keyword-faces))
4626 (and (member kwd org-done-keywords) 'org-done)
4627 'org-todo))
4629 (defun org-font-lock-add-tag-faces (limit)
4630 "Add the special tag faces."
4631 (when (and org-tag-faces org-tags-special-faces-re)
4632 (while (re-search-forward org-tags-special-faces-re limit t)
4633 (add-text-properties (match-beginning 1) (match-end 1)
4634 (list 'face (org-get-tag-face 1)
4635 'font-lock-fontified t))
4636 (backward-char 1))))
4638 (defun org-font-lock-add-priority-faces (limit)
4639 "Add the special priority faces."
4640 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4641 (add-text-properties
4642 (match-beginning 0) (match-end 0)
4643 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4644 org-priority-faces))
4645 'org-special-keyword)
4646 'font-lock-fontified t))))
4648 (defun org-get-tag-face (kwd)
4649 "Get the right face for a TODO keyword KWD.
4650 If KWD is a number, get the corresponding match group."
4651 (if (numberp kwd) (setq kwd (match-string kwd)))
4652 (or (cdr (assoc kwd org-tag-faces))
4653 'org-tag))
4655 (defun org-unfontify-region (beg end &optional maybe_loudly)
4656 "Remove fontification and activation overlays from links."
4657 (font-lock-default-unfontify-region beg end)
4658 (let* ((buffer-undo-list t)
4659 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4660 (inhibit-modification-hooks t)
4661 deactivate-mark buffer-file-name buffer-file-truename)
4662 (remove-text-properties beg end
4663 '(mouse-face t keymap t org-linked-text t
4664 invisible t intangible t
4665 org-no-flyspell t))))
4667 ;;;; Visibility cycling, including org-goto and indirect buffer
4669 ;;; Cycling
4671 (defvar org-cycle-global-status nil)
4672 (make-variable-buffer-local 'org-cycle-global-status)
4673 (defvar org-cycle-subtree-status nil)
4674 (make-variable-buffer-local 'org-cycle-subtree-status)
4676 ;;;###autoload
4678 (defvar org-inlinetask-min-level)
4680 (defun org-cycle (&optional arg)
4681 "TAB-action and visibility cycling for Org-mode.
4683 This is the command invoked in Org-moe by the TAB key. It's main purpose
4684 is outine visibility cycling, but it also invokes other actions
4685 in special contexts.
4687 - When this function is called with a prefix argument, rotate the entire
4688 buffer through 3 states (global cycling)
4689 1. OVERVIEW: Show only top-level headlines.
4690 2. CONTENTS: Show all headlines of all levels, but no body text.
4691 3. SHOW ALL: Show everything.
4692 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4693 determined by the variable `org-startup-folded', and by any VISIBILITY
4694 properties in the buffer.
4695 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4696 including any drawers.
4698 - When inside a table, re-align the table and move to the next field.
4700 - When point is at the beginning of a headline, rotate the subtree started
4701 by this line through 3 different states (local cycling)
4702 1. FOLDED: Only the main headline is shown.
4703 2. CHILDREN: The main headline and the direct children are shown.
4704 From this state, you can move to one of the children
4705 and zoom in further.
4706 3. SUBTREE: Show the entire subtree, including body text.
4708 - When there is a numeric prefix, go up to a heading with level ARG, do
4709 a `show-subtree' and return to the previous cursor position. If ARG
4710 is negative, go up that many levels.
4712 - When point is not at the beginning of a headline, execute the global
4713 binding for TAB, which is re-indenting the line. See the option
4714 `org-cycle-emulate-tab' for details.
4716 - Special case: if point is at the beginning of the buffer and there is
4717 no headline in line 1, this function will act as if called with prefix arg.
4718 But only if also the variable `org-cycle-global-at-bob' is t."
4719 (interactive "P")
4720 (org-load-modules-maybe)
4721 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4722 (let* ((limit-level
4723 (or org-cycle-max-level
4724 (and (boundp 'org-inlinetask-min-level)
4725 org-inlinetask-min-level
4726 (1- org-inlinetask-min-level))))
4727 (nstars (and limit-level
4728 (if org-odd-levels-only
4729 (and limit-level (1- (* limit-level 2)))
4730 limit-level)))
4731 (outline-regexp
4732 (cond
4733 ((not (org-mode-p)) outline-regexp)
4734 (org-cycle-include-plain-lists
4735 (concat "\\(?:\\*"
4736 (if nstars (format "\\{1,%d\\}" nstars) "+")
4737 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4738 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4739 (bob-special (and org-cycle-global-at-bob (bobp)
4740 (not (looking-at outline-regexp))))
4741 (org-cycle-hook
4742 (if bob-special
4743 (delq 'org-optimize-window-after-visibility-change
4744 (copy-sequence org-cycle-hook))
4745 org-cycle-hook))
4746 (pos (point)))
4748 (if (or bob-special (equal arg '(4)))
4749 ;; special case: use global cycling
4750 (setq arg t))
4752 (cond
4754 ((equal arg '(16))
4755 (org-set-startup-visibility)
4756 (message "Startup visibility, plus VISIBILITY properties"))
4758 ((equal arg '(64))
4759 (show-all)
4760 (message "Entire buffer visible, including drawers"))
4762 ((org-at-table-p 'any)
4763 ;; Enter the table or move to the next field in the table
4764 (or (org-table-recognize-table.el)
4765 (progn
4766 (if arg (org-table-edit-field t)
4767 (org-table-justify-field-maybe)
4768 (call-interactively 'org-table-next-field)))))
4770 ((run-hook-with-args-until-success
4771 'org-tab-after-check-for-table-hook))
4773 ((eq arg t) ;; Global cycling
4774 (org-cycle-internal-global))
4776 ((and org-drawers org-drawer-regexp
4777 (save-excursion
4778 (beginning-of-line 1)
4779 (looking-at org-drawer-regexp)))
4780 ;; Toggle block visibility
4781 (org-flag-drawer
4782 (not (get-char-property (match-end 0) 'invisible))))
4784 ((integerp arg)
4785 ;; Show-subtree, ARG levels up from here.
4786 (save-excursion
4787 (org-back-to-heading)
4788 (outline-up-heading (if (< arg 0) (- arg)
4789 (- (funcall outline-level) arg)))
4790 (org-show-subtree)))
4792 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4793 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4795 (org-cycle-internal-local))
4797 ;; TAB emulation and template completion
4798 (buffer-read-only (org-back-to-heading))
4800 ((run-hook-with-args-until-success
4801 'org-tab-after-check-for-cycling-hook))
4803 ((org-try-structure-completion))
4805 ((org-try-cdlatex-tab))
4807 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4808 (or (not (bolp))
4809 (not (looking-at outline-regexp))))
4810 (call-interactively (global-key-binding "\t")))
4812 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4813 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4814 (or (and (eq org-cycle-emulate-tab 'white)
4815 (= (match-end 0) (point-at-eol)))
4816 (and (eq org-cycle-emulate-tab 'whitestart)
4817 (>= (match-end 0) pos))))
4819 (eq org-cycle-emulate-tab t))
4820 (call-interactively (global-key-binding "\t")))
4822 (t (save-excursion
4823 (org-back-to-heading)
4824 (org-cycle)))))))
4826 (defun org-cycle-internal-global ()
4827 "Do the global cycling action."
4828 (cond
4829 ((and (eq last-command this-command)
4830 (eq org-cycle-global-status 'overview))
4831 ;; We just created the overview - now do table of contents
4832 ;; This can be slow in very large buffers, so indicate action
4833 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4834 (message "CONTENTS...")
4835 (org-content)
4836 (message "CONTENTS...done")
4837 (setq org-cycle-global-status 'contents)
4838 (run-hook-with-args 'org-cycle-hook 'contents))
4840 ((and (eq last-command this-command)
4841 (eq org-cycle-global-status 'contents))
4842 ;; We just showed the table of contents - now show everything
4843 (run-hook-with-args 'org-pre-cycle-hook 'all)
4844 (show-all)
4845 (message "SHOW ALL")
4846 (setq org-cycle-global-status 'all)
4847 (run-hook-with-args 'org-cycle-hook 'all))
4850 ;; Default action: go to overview
4851 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4852 (org-overview)
4853 (message "OVERVIEW")
4854 (setq org-cycle-global-status 'overview)
4855 (run-hook-with-args 'org-cycle-hook 'overview))))
4857 (defun org-cycle-internal-local ()
4858 "Do the local cycling action."
4859 (org-back-to-heading)
4860 (let ((goal-column 0) eoh eol eos)
4861 ;; First, some boundaries
4862 (save-excursion
4863 (org-back-to-heading)
4864 (save-excursion
4865 (beginning-of-line 2)
4866 (while (and (not (eobp)) ;; this is like `next-line'
4867 (get-char-property (1- (point)) 'invisible))
4868 (beginning-of-line 2)) (setq eol (point)))
4869 (outline-end-of-heading) (setq eoh (point))
4870 (org-end-of-subtree t)
4871 (unless (eobp)
4872 (skip-chars-forward " \t\n")
4873 (beginning-of-line 1) ; in case this is an item
4875 (setq eos (1- (point))))
4876 ;; Find out what to do next and set `this-command'
4877 (cond
4878 ((= eos eoh)
4879 ;; Nothing is hidden behind this heading
4880 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4881 (message "EMPTY ENTRY")
4882 (setq org-cycle-subtree-status nil)
4883 (save-excursion
4884 (goto-char eos)
4885 (outline-next-heading)
4886 (if (org-invisible-p) (org-flag-heading nil))))
4887 ((or (>= eol eos)
4888 (not (string-match "\\S-" (buffer-substring eol eos))))
4889 ;; Entire subtree is hidden in one line: open it
4890 (run-hook-with-args 'org-pre-cycle-hook 'children)
4891 (org-show-entry)
4892 (show-children)
4893 (message "CHILDREN")
4894 (save-excursion
4895 (goto-char eos)
4896 (outline-next-heading)
4897 (if (org-invisible-p) (org-flag-heading nil)))
4898 (setq org-cycle-subtree-status 'children)
4899 (run-hook-with-args 'org-cycle-hook 'children))
4900 ((and (eq last-command this-command)
4901 (eq org-cycle-subtree-status 'children))
4902 ;; We just showed the children, now show everything.
4903 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
4904 (org-show-subtree)
4905 (message "SUBTREE")
4906 (setq org-cycle-subtree-status 'subtree)
4907 (run-hook-with-args 'org-cycle-hook 'subtree))
4909 ;; Default action: hide the subtree.
4910 (run-hook-with-args 'org-pre-cycle-hook 'folded)
4911 (hide-subtree)
4912 (message "FOLDED")
4913 (setq org-cycle-subtree-status 'folded)
4914 (run-hook-with-args 'org-cycle-hook 'folded)))))
4916 ;;;###autoload
4917 (defun org-global-cycle (&optional arg)
4918 "Cycle the global visibility. For details see `org-cycle'.
4919 With C-u prefix arg, switch to startup visibility.
4920 With a numeric prefix, show all headlines up to that level."
4921 (interactive "P")
4922 (let ((org-cycle-include-plain-lists
4923 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4924 (cond
4925 ((integerp arg)
4926 (show-all)
4927 (hide-sublevels arg)
4928 (setq org-cycle-global-status 'contents))
4929 ((equal arg '(4))
4930 (org-set-startup-visibility)
4931 (message "Startup visibility, plus VISIBILITY properties."))
4933 (org-cycle '(4))))))
4935 (defun org-set-startup-visibility ()
4936 "Set the visibility required by startup options and properties."
4937 (cond
4938 ((eq org-startup-folded t)
4939 (org-cycle '(4)))
4940 ((eq org-startup-folded 'content)
4941 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4942 (org-cycle '(4)) (org-cycle '(4)))))
4943 (if org-hide-block-startup (org-hide-block-all))
4944 (org-set-visibility-according-to-property 'no-cleanup)
4945 (org-cycle-hide-archived-subtrees 'all)
4946 (org-cycle-hide-drawers 'all)
4947 (org-cycle-show-empty-lines 'all))
4949 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4950 "Switch subtree visibilities according to :VISIBILITY: property."
4951 (interactive)
4952 (let (org-show-entry-below state)
4953 (save-excursion
4954 (goto-char (point-min))
4955 (while (re-search-forward
4956 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4957 nil t)
4958 (setq state (match-string 1))
4959 (save-excursion
4960 (org-back-to-heading t)
4961 (hide-subtree)
4962 (org-reveal)
4963 (cond
4964 ((equal state '("fold" "folded"))
4965 (hide-subtree))
4966 ((equal state "children")
4967 (org-show-hidden-entry)
4968 (show-children))
4969 ((equal state "content")
4970 (save-excursion
4971 (save-restriction
4972 (org-narrow-to-subtree)
4973 (org-content))))
4974 ((member state '("all" "showall"))
4975 (show-subtree)))))
4976 (unless no-cleanup
4977 (org-cycle-hide-archived-subtrees 'all)
4978 (org-cycle-hide-drawers 'all)
4979 (org-cycle-show-empty-lines 'all)))))
4981 (defun org-overview ()
4982 "Switch to overview mode, showing only top-level headlines.
4983 Really, this shows all headlines with level equal or greater than the level
4984 of the first headline in the buffer. This is important, because if the
4985 first headline is not level one, then (hide-sublevels 1) gives confusing
4986 results."
4987 (interactive)
4988 (let ((level (save-excursion
4989 (goto-char (point-min))
4990 (if (re-search-forward (concat "^" outline-regexp) nil t)
4991 (progn
4992 (goto-char (match-beginning 0))
4993 (funcall outline-level))))))
4994 (and level (hide-sublevels level))))
4996 (defun org-content (&optional arg)
4997 "Show all headlines in the buffer, like a table of contents.
4998 With numerical argument N, show content up to level N."
4999 (interactive "P")
5000 (save-excursion
5001 ;; Visit all headings and show their offspring
5002 (and (integerp arg) (org-overview))
5003 (goto-char (point-max))
5004 (catch 'exit
5005 (while (and (progn (condition-case nil
5006 (outline-previous-visible-heading 1)
5007 (error (goto-char (point-min))))
5009 (looking-at outline-regexp))
5010 (if (integerp arg)
5011 (show-children (1- arg))
5012 (show-branches))
5013 (if (bobp) (throw 'exit nil))))))
5016 (defun org-optimize-window-after-visibility-change (state)
5017 "Adjust the window after a change in outline visibility.
5018 This function is the default value of the hook `org-cycle-hook'."
5019 (when (get-buffer-window (current-buffer))
5020 (cond
5021 ((eq state 'content) nil)
5022 ((eq state 'all) nil)
5023 ((eq state 'folded) nil)
5024 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5025 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5027 (defun org-compact-display-after-subtree-move ()
5028 "Show a compacter version of the tree of the entry's parent."
5029 (save-excursion
5030 (if (org-up-heading-safe)
5031 (progn
5032 (hide-subtree)
5033 (show-entry)
5034 (show-children)
5035 (org-cycle-show-empty-lines 'children)
5036 (org-cycle-hide-drawers 'children))
5037 (org-overview))))
5039 (defun org-cycle-show-empty-lines (state)
5040 "Show empty lines above all visible headlines.
5041 The region to be covered depends on STATE when called through
5042 `org-cycle-hook'. Lisp program can use t for STATE to get the
5043 entire buffer covered. Note that an empty line is only shown if there
5044 are at least `org-cycle-separator-lines' empty lines before the headline."
5045 (when (> org-cycle-separator-lines 0)
5046 (save-excursion
5047 (let* ((n org-cycle-separator-lines)
5048 (re (cond
5049 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5050 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5051 (t (let ((ns (number-to-string (- n 2))))
5052 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5053 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5054 beg end)
5055 (cond
5056 ((memq state '(overview contents t))
5057 (setq beg (point-min) end (point-max)))
5058 ((memq state '(children folded))
5059 (setq beg (point) end (progn (org-end-of-subtree t t)
5060 (beginning-of-line 2)
5061 (point)))))
5062 (when beg
5063 (goto-char beg)
5064 (while (re-search-forward re end t)
5065 (if (not (get-char-property (match-end 1) 'invisible))
5066 (outline-flag-region
5067 (match-beginning 1) (match-end 1) nil)))))))
5068 ;; Never hide empty lines at the end of the file.
5069 (save-excursion
5070 (goto-char (point-max))
5071 (outline-previous-heading)
5072 (outline-end-of-heading)
5073 (if (and (looking-at "[ \t\n]+")
5074 (= (match-end 0) (point-max)))
5075 (outline-flag-region (point) (match-end 0) nil))))
5077 (defun org-show-empty-lines-in-parent ()
5078 "Move to the parent and re-show empty lines before visible headlines."
5079 (save-excursion
5080 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5081 (org-cycle-show-empty-lines context))))
5083 (defun org-cycle-hide-drawers (state)
5084 "Re-hide all drawers after a visibility state change."
5085 (when (and (org-mode-p)
5086 (not (memq state '(overview folded))))
5087 (save-excursion
5088 (let* ((globalp (memq state '(contents all)))
5089 (beg (if globalp (point-min) (point)))
5090 (end (if globalp (point-max) (org-end-of-subtree t))))
5091 (goto-char beg)
5092 (while (re-search-forward org-drawer-regexp end t)
5093 (org-flag-drawer t))))))
5095 (defun org-flag-drawer (flag)
5096 (save-excursion
5097 (beginning-of-line 1)
5098 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5099 (let ((b (match-end 0))
5100 (outline-regexp org-outline-regexp))
5101 (if (re-search-forward
5102 "^[ \t]*:END:"
5103 (save-excursion (outline-next-heading) (point)) t)
5104 (outline-flag-region b (point-at-eol) flag)
5105 (error ":END: line missing"))))))
5107 (defun org-subtree-end-visible-p ()
5108 "Is the end of the current subtree visible?"
5109 (pos-visible-in-window-p
5110 (save-excursion (org-end-of-subtree t) (point))))
5112 (defun org-first-headline-recenter (&optional N)
5113 "Move cursor to the first headline and recenter the headline.
5114 Optional argument N means, put the headline into the Nth line of the window."
5115 (goto-char (point-min))
5116 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5117 (beginning-of-line)
5118 (recenter (prefix-numeric-value N))))
5120 ;;; Folding of blocks
5122 (defconst org-block-regexp
5124 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5125 "Regular expression for hiding blocks.")
5127 (defvar org-hide-block-overlays nil
5128 "Overays hiding blocks.")
5129 (make-variable-buffer-local 'org-hide-block-overlays)
5131 (defun org-block-map (function &optional start end)
5132 "Call func at the head of all source blocks in the current
5133 buffer. Optional arguments START and END can be used to limit
5134 the range."
5135 (let ((start (or start (point-min)))
5136 (end (or end (point-max))))
5137 (save-excursion
5138 (goto-char start)
5139 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5140 (save-excursion
5141 (save-match-data
5142 (goto-char (match-beginning 0))
5143 (funcall function)))))))
5145 (defun org-hide-block-toggle-all ()
5146 "Toggle the visibility of all blocks in the current buffer."
5147 (org-block-map #'org-hide-block-toggle))
5149 (defun org-hide-block-all ()
5150 "Fold all blocks in the current buffer."
5151 (interactive)
5152 (org-show-block-all)
5153 (org-block-map #'org-hide-block-toggle-maybe))
5155 (defun org-show-block-all ()
5156 "Unfold all blocks in the current buffer."
5157 (mapc 'org-delete-overlay org-hide-block-overlays)
5158 (setq org-hide-block-overlays nil))
5160 (defun org-hide-block-toggle-maybe ()
5161 "Toggle visibility of block at point."
5162 (interactive)
5163 (let ((case-fold-search t))
5164 (if (save-excursion
5165 (beginning-of-line 1)
5166 (looking-at org-block-regexp))
5167 (progn (org-hide-block-toggle)
5168 t) ;; to signal that we took action
5169 nil))) ;; to signal that we did not
5171 (defun org-hide-block-toggle (&optional force)
5172 "Toggle the visibility of the current block."
5173 (interactive)
5174 (save-excursion
5175 (beginning-of-line)
5176 (if (re-search-forward org-block-regexp nil t)
5177 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5178 (end (match-end 0))
5179 ov) ;; end of entire body
5180 (if (memq t (mapcar (lambda (overlay)
5181 (eq (org-overlay-get overlay 'invisible)
5182 'org-hide-block))
5183 (org-overlays-at start)))
5184 (if (or (not force) (eq force 'off))
5185 (mapc (lambda (ov)
5186 (when (member ov org-hide-block-overlays)
5187 (setq org-hide-block-overlays
5188 (delq ov org-hide-block-overlays)))
5189 (when (eq (org-overlay-get ov 'invisible)
5190 'org-hide-block)
5191 (org-delete-overlay ov)))
5192 (org-overlays-at start)))
5193 (setq ov (make-overlay start end))
5194 (org-overlay-put ov 'invisible 'org-hide-block)
5195 (push ov org-hide-block-overlays)))
5196 (error "Not looking at a source block"))))
5198 ;; org-tab-after-check-for-cycling-hook
5199 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5200 ;; Remove overlays when changing major mode
5201 (add-hook 'org-mode-hook
5202 (lambda () (org-add-hook 'change-major-mode-hook
5203 'org-show-block-all 'append 'local)))
5205 ;;; Org-goto
5207 (defvar org-goto-window-configuration nil)
5208 (defvar org-goto-marker nil)
5209 (defvar org-goto-map
5210 (let ((map (make-sparse-keymap)))
5211 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5212 (while (setq cmd (pop cmds))
5213 (substitute-key-definition cmd cmd map global-map)))
5214 (suppress-keymap map)
5215 (org-defkey map "\C-m" 'org-goto-ret)
5216 (org-defkey map [(return)] 'org-goto-ret)
5217 (org-defkey map [(left)] 'org-goto-left)
5218 (org-defkey map [(right)] 'org-goto-right)
5219 (org-defkey map [(control ?g)] 'org-goto-quit)
5220 (org-defkey map "\C-i" 'org-cycle)
5221 (org-defkey map [(tab)] 'org-cycle)
5222 (org-defkey map [(down)] 'outline-next-visible-heading)
5223 (org-defkey map [(up)] 'outline-previous-visible-heading)
5224 (if org-goto-auto-isearch
5225 (if (fboundp 'define-key-after)
5226 (define-key-after map [t] 'org-goto-local-auto-isearch)
5227 nil)
5228 (org-defkey map "q" 'org-goto-quit)
5229 (org-defkey map "n" 'outline-next-visible-heading)
5230 (org-defkey map "p" 'outline-previous-visible-heading)
5231 (org-defkey map "f" 'outline-forward-same-level)
5232 (org-defkey map "b" 'outline-backward-same-level)
5233 (org-defkey map "u" 'outline-up-heading))
5234 (org-defkey map "/" 'org-occur)
5235 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5236 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5237 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5238 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5239 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5240 map))
5242 (defconst org-goto-help
5243 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5244 RET=jump to location [Q]uit and return to previous location
5245 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5247 (defvar org-goto-start-pos) ; dynamically scoped parameter
5249 ;; FIXME: Docstring doe not mention both interfaces
5250 (defun org-goto (&optional alternative-interface)
5251 "Look up a different location in the current file, keeping current visibility.
5253 When you want look-up or go to a different location in a document, the
5254 fastest way is often to fold the entire buffer and then dive into the tree.
5255 This method has the disadvantage, that the previous location will be folded,
5256 which may not be what you want.
5258 This command works around this by showing a copy of the current buffer
5259 in an indirect buffer, in overview mode. You can dive into the tree in
5260 that copy, use org-occur and incremental search to find a location.
5261 When pressing RET or `Q', the command returns to the original buffer in
5262 which the visibility is still unchanged. After RET is will also jump to
5263 the location selected in the indirect buffer and expose the
5264 the headline hierarchy above."
5265 (interactive "P")
5266 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5267 (org-refile-use-outline-path t)
5268 (org-refile-target-verify-function nil)
5269 (interface
5270 (if (not alternative-interface)
5271 org-goto-interface
5272 (if (eq org-goto-interface 'outline)
5273 'outline-path-completion
5274 'outline)))
5275 (org-goto-start-pos (point))
5276 (selected-point
5277 (if (eq interface 'outline)
5278 (car (org-get-location (current-buffer) org-goto-help))
5279 (nth 3 (org-refile-get-location "Goto: ")))))
5280 (if selected-point
5281 (progn
5282 (org-mark-ring-push org-goto-start-pos)
5283 (goto-char selected-point)
5284 (if (or (org-invisible-p) (org-invisible-p2))
5285 (org-show-context 'org-goto)))
5286 (message "Quit"))))
5288 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5289 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5290 (defvar org-goto-local-auto-isearch-map) ; defined below
5292 (defun org-get-location (buf help)
5293 "Let the user select a location in the Org-mode buffer BUF.
5294 This function uses a recursive edit. It returns the selected position
5295 or nil."
5296 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5297 (isearch-hide-immediately nil)
5298 (isearch-search-fun-function
5299 (lambda () 'org-goto-local-search-headings))
5300 (org-goto-selected-point org-goto-exit-command))
5301 (save-excursion
5302 (save-window-excursion
5303 (delete-other-windows)
5304 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5305 (switch-to-buffer
5306 (condition-case nil
5307 (make-indirect-buffer (current-buffer) "*org-goto*")
5308 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5309 (with-output-to-temp-buffer "*Help*"
5310 (princ help))
5311 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5312 (setq buffer-read-only nil)
5313 (let ((org-startup-truncated t)
5314 (org-startup-folded nil)
5315 (org-startup-align-all-tables nil))
5316 (org-mode)
5317 (org-overview))
5318 (setq buffer-read-only t)
5319 (if (and (boundp 'org-goto-start-pos)
5320 (integer-or-marker-p org-goto-start-pos))
5321 (let ((org-show-hierarchy-above t)
5322 (org-show-siblings t)
5323 (org-show-following-heading t))
5324 (goto-char org-goto-start-pos)
5325 (and (org-invisible-p) (org-show-context)))
5326 (goto-char (point-min)))
5327 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5328 (message "Select location and press RET")
5329 (use-local-map org-goto-map)
5330 (recursive-edit)
5332 (kill-buffer "*org-goto*")
5333 (cons org-goto-selected-point org-goto-exit-command)))
5335 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5336 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5337 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5338 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5340 (defun org-goto-local-search-headings (string bound noerror)
5341 "Search and make sure that any matches are in headlines."
5342 (catch 'return
5343 (while (if isearch-forward
5344 (search-forward string bound noerror)
5345 (search-backward string bound noerror))
5346 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5347 (and (member :headline context)
5348 (not (member :tags context))))
5349 (throw 'return (point))))))
5351 (defun org-goto-local-auto-isearch ()
5352 "Start isearch."
5353 (interactive)
5354 (goto-char (point-min))
5355 (let ((keys (this-command-keys)))
5356 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5357 (isearch-mode t)
5358 (isearch-process-search-char (string-to-char keys)))))
5360 (defun org-goto-ret (&optional arg)
5361 "Finish `org-goto' by going to the new location."
5362 (interactive "P")
5363 (setq org-goto-selected-point (point)
5364 org-goto-exit-command 'return)
5365 (throw 'exit nil))
5367 (defun org-goto-left ()
5368 "Finish `org-goto' by going to the new location."
5369 (interactive)
5370 (if (org-on-heading-p)
5371 (progn
5372 (beginning-of-line 1)
5373 (setq org-goto-selected-point (point)
5374 org-goto-exit-command 'left)
5375 (throw 'exit nil))
5376 (error "Not on a heading")))
5378 (defun org-goto-right ()
5379 "Finish `org-goto' by going to the new location."
5380 (interactive)
5381 (if (org-on-heading-p)
5382 (progn
5383 (setq org-goto-selected-point (point)
5384 org-goto-exit-command 'right)
5385 (throw 'exit nil))
5386 (error "Not on a heading")))
5388 (defun org-goto-quit ()
5389 "Finish `org-goto' without cursor motion."
5390 (interactive)
5391 (setq org-goto-selected-point nil)
5392 (setq org-goto-exit-command 'quit)
5393 (throw 'exit nil))
5395 ;;; Indirect buffer display of subtrees
5397 (defvar org-indirect-dedicated-frame nil
5398 "This is the frame being used for indirect tree display.")
5399 (defvar org-last-indirect-buffer nil)
5401 (defun org-tree-to-indirect-buffer (&optional arg)
5402 "Create indirect buffer and narrow it to current subtree.
5403 With numerical prefix ARG, go up to this level and then take that tree.
5404 If ARG is negative, go up that many levels.
5405 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5406 indirect buffer previously made with this command, to avoid proliferation of
5407 indirect buffers. However, when you call the command with a `C-u' prefix, or
5408 when `org-indirect-buffer-display' is `new-frame', the last buffer
5409 is kept so that you can work with several indirect buffers at the same time.
5410 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5411 requests that a new frame be made for the new buffer, so that the dedicated
5412 frame is not changed."
5413 (interactive "P")
5414 (let ((cbuf (current-buffer))
5415 (cwin (selected-window))
5416 (pos (point))
5417 beg end level heading ibuf)
5418 (save-excursion
5419 (org-back-to-heading t)
5420 (when (numberp arg)
5421 (setq level (org-outline-level))
5422 (if (< arg 0) (setq arg (+ level arg)))
5423 (while (> (setq level (org-outline-level)) arg)
5424 (outline-up-heading 1 t)))
5425 (setq beg (point)
5426 heading (org-get-heading))
5427 (org-end-of-subtree t) (setq end (point)))
5428 (if (and (buffer-live-p org-last-indirect-buffer)
5429 (not (eq org-indirect-buffer-display 'new-frame))
5430 (not arg))
5431 (kill-buffer org-last-indirect-buffer))
5432 (setq ibuf (org-get-indirect-buffer cbuf)
5433 org-last-indirect-buffer ibuf)
5434 (cond
5435 ((or (eq org-indirect-buffer-display 'new-frame)
5436 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5437 (select-frame (make-frame))
5438 (delete-other-windows)
5439 (switch-to-buffer ibuf)
5440 (org-set-frame-title heading))
5441 ((eq org-indirect-buffer-display 'dedicated-frame)
5442 (raise-frame
5443 (select-frame (or (and org-indirect-dedicated-frame
5444 (frame-live-p org-indirect-dedicated-frame)
5445 org-indirect-dedicated-frame)
5446 (setq org-indirect-dedicated-frame (make-frame)))))
5447 (delete-other-windows)
5448 (switch-to-buffer ibuf)
5449 (org-set-frame-title (concat "Indirect: " heading)))
5450 ((eq org-indirect-buffer-display 'current-window)
5451 (switch-to-buffer ibuf))
5452 ((eq org-indirect-buffer-display 'other-window)
5453 (pop-to-buffer ibuf))
5454 (t (error "Invalid value.")))
5455 (if (featurep 'xemacs)
5456 (save-excursion (org-mode) (turn-on-font-lock)))
5457 (narrow-to-region beg end)
5458 (show-all)
5459 (goto-char pos)
5460 (and (window-live-p cwin) (select-window cwin))))
5462 (defun org-get-indirect-buffer (&optional buffer)
5463 (setq buffer (or buffer (current-buffer)))
5464 (let ((n 1) (base (buffer-name buffer)) bname)
5465 (while (buffer-live-p
5466 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5467 (setq n (1+ n)))
5468 (condition-case nil
5469 (make-indirect-buffer buffer bname 'clone)
5470 (error (make-indirect-buffer buffer bname)))))
5472 (defun org-set-frame-title (title)
5473 "Set the title of the current frame to the string TITLE."
5474 ;; FIXME: how to name a single frame in XEmacs???
5475 (unless (featurep 'xemacs)
5476 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5478 ;;;; Structure editing
5480 ;;; Inserting headlines
5482 (defun org-previous-line-empty-p ()
5483 (save-excursion
5484 (and (not (bobp))
5485 (or (beginning-of-line 0) t)
5486 (save-match-data
5487 (looking-at "[ \t]*$")))))
5489 (defun org-insert-heading (&optional force-heading)
5490 "Insert a new heading or item with same depth at point.
5491 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5492 If point is at the beginning of a headline, insert a sibling before the
5493 current headline. If point is not at the beginning, do not split the line,
5494 but create the new headline after the current line."
5495 (interactive "P")
5496 (if (= (buffer-size) 0)
5497 (insert "\n* ")
5498 (when (or force-heading (not (org-insert-item)))
5499 (let* ((empty-line-p nil)
5500 (head (save-excursion
5501 (condition-case nil
5502 (progn
5503 (org-back-to-heading)
5504 (setq empty-line-p (org-previous-line-empty-p))
5505 (match-string 0))
5506 (error "*"))))
5507 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5508 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5509 pos hide-previous previous-pos)
5510 (cond
5511 ((and (org-on-heading-p) (bolp)
5512 (or (bobp)
5513 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5514 ;; insert before the current line
5515 (open-line (if blank 2 1)))
5516 ((and (bolp)
5517 (or (bobp)
5518 (save-excursion
5519 (backward-char 1) (not (org-invisible-p)))))
5520 ;; insert right here
5521 nil)
5523 ;; somewhere in the line
5524 (save-excursion
5525 (setq previous-pos (point-at-bol))
5526 (end-of-line)
5527 (setq hide-previous (org-invisible-p)))
5528 (and org-insert-heading-respect-content (org-show-subtree))
5529 (let ((split
5530 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5531 (save-excursion
5532 (let ((p (point)))
5533 (goto-char (point-at-bol))
5534 (and (looking-at org-complex-heading-regexp)
5535 (> p (match-beginning 4)))))))
5536 tags pos)
5537 (cond
5538 (org-insert-heading-respect-content
5539 (org-end-of-subtree nil t)
5540 (or (bolp) (newline))
5541 (or (org-previous-line-empty-p)
5542 (and blank (newline)))
5543 (open-line 1))
5544 ((org-on-heading-p)
5545 (when hide-previous
5546 (show-children)
5547 (org-show-entry))
5548 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5549 (setq tags (and (match-end 2) (match-string 2)))
5550 (and (match-end 1)
5551 (delete-region (match-beginning 1) (match-end 1)))
5552 (setq pos (point-at-bol))
5553 (or split (end-of-line 1))
5554 (delete-horizontal-space)
5555 (newline (if blank 2 1))
5556 (when tags
5557 (save-excursion
5558 (goto-char pos)
5559 (end-of-line 1)
5560 (insert " " tags)
5561 (org-set-tags nil 'align))))
5563 (or split (end-of-line 1))
5564 (newline (if blank 2 1)))))))
5565 (insert head) (just-one-space)
5566 (setq pos (point))
5567 (end-of-line 1)
5568 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5569 (when (and org-insert-heading-respect-content hide-previous)
5570 (save-excursion
5571 (goto-char previous-pos)
5572 (hide-subtree)))
5573 (run-hooks 'org-insert-heading-hook)))))
5575 (defun org-get-heading (&optional no-tags)
5576 "Return the heading of the current entry, without the stars."
5577 (save-excursion
5578 (org-back-to-heading t)
5579 (if (looking-at
5580 (if no-tags
5581 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5582 "\\*+[ \t]+\\([^\r\n]*\\)"))
5583 (match-string 1) "")))
5585 (defun org-heading-components ()
5586 "Return the components of the current heading.
5587 This is a list with the following elements:
5588 - the level as an integer
5589 - the reduced level, different if `org-odd-levels-only' is set.
5590 - the TODO keyword, or nil
5591 - the priority character, like ?A, or nil if no priority is given
5592 - the headline text itself, or the tags string if no headline text
5593 - the tags string, or nil."
5594 (save-excursion
5595 (org-back-to-heading t)
5596 (if (looking-at org-complex-heading-regexp)
5597 (list (length (match-string 1))
5598 (org-reduced-level (length (match-string 1)))
5599 (org-match-string-no-properties 2)
5600 (and (match-end 3) (aref (match-string 3) 2))
5601 (org-match-string-no-properties 4)
5602 (org-match-string-no-properties 5)))))
5604 (defun org-get-entry ()
5605 "Get the entry text, after heading, entire subtree."
5606 (save-excursion
5607 (org-back-to-heading t)
5608 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5610 (defun org-insert-heading-after-current ()
5611 "Insert a new heading with same level as current, after current subtree."
5612 (interactive)
5613 (org-back-to-heading)
5614 (org-insert-heading)
5615 (org-move-subtree-down)
5616 (end-of-line 1))
5618 (defun org-insert-heading-respect-content ()
5619 (interactive)
5620 (let ((org-insert-heading-respect-content t))
5621 (org-insert-heading t)))
5623 (defun org-insert-todo-heading-respect-content (&optional force-state)
5624 (interactive "P")
5625 (let ((org-insert-heading-respect-content t))
5626 (org-insert-todo-heading force-state t)))
5628 (defun org-insert-todo-heading (arg &optional force-heading)
5629 "Insert a new heading with the same level and TODO state as current heading.
5630 If the heading has no TODO state, or if the state is DONE, use the first
5631 state (TODO by default). Also with prefix arg, force first state."
5632 (interactive "P")
5633 (when (or force-heading (not (org-insert-item 'checkbox)))
5634 (org-insert-heading force-heading)
5635 (save-excursion
5636 (org-back-to-heading)
5637 (outline-previous-heading)
5638 (looking-at org-todo-line-regexp))
5639 (let*
5640 ((new-mark-x
5641 (if (or arg
5642 (not (match-beginning 2))
5643 (member (match-string 2) org-done-keywords))
5644 (car org-todo-keywords-1)
5645 (match-string 2)))
5646 (new-mark
5648 (run-hook-with-args-until-success
5649 'org-todo-get-default-hook new-mark-x nil)
5650 new-mark-x)))
5651 (beginning-of-line 1)
5652 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5653 (if org-treat-insert-todo-heading-as-state-change
5654 (org-todo new-mark)
5655 (insert new-mark " "))))
5656 (when org-provide-todo-statistics
5657 (org-update-parent-todo-statistics))))
5659 (defun org-insert-subheading (arg)
5660 "Insert a new subheading and demote it.
5661 Works for outline headings and for plain lists alike."
5662 (interactive "P")
5663 (org-insert-heading arg)
5664 (cond
5665 ((org-on-heading-p) (org-do-demote))
5666 ((org-at-item-p) (org-indent-item 1))))
5668 (defun org-insert-todo-subheading (arg)
5669 "Insert a new subheading with TODO keyword or checkbox and demote it.
5670 Works for outline headings and for plain lists alike."
5671 (interactive "P")
5672 (org-insert-todo-heading arg)
5673 (cond
5674 ((org-on-heading-p) (org-do-demote))
5675 ((org-at-item-p) (org-indent-item 1))))
5677 ;;; Promotion and Demotion
5679 (defun org-promote-subtree ()
5680 "Promote the entire subtree.
5681 See also `org-promote'."
5682 (interactive)
5683 (save-excursion
5684 (org-map-tree 'org-promote))
5685 (org-fix-position-after-promote))
5687 (defun org-demote-subtree ()
5688 "Demote the entire subtree. See `org-demote'.
5689 See also `org-promote'."
5690 (interactive)
5691 (save-excursion
5692 (org-map-tree 'org-demote))
5693 (org-fix-position-after-promote))
5696 (defun org-do-promote ()
5697 "Promote the current heading higher up the tree.
5698 If the region is active in `transient-mark-mode', promote all headings
5699 in the region."
5700 (interactive)
5701 (save-excursion
5702 (if (org-region-active-p)
5703 (org-map-region 'org-promote (region-beginning) (region-end))
5704 (org-promote)))
5705 (org-fix-position-after-promote))
5707 (defun org-do-demote ()
5708 "Demote the current heading lower down the tree.
5709 If the region is active in `transient-mark-mode', demote all headings
5710 in the region."
5711 (interactive)
5712 (save-excursion
5713 (if (org-region-active-p)
5714 (org-map-region 'org-demote (region-beginning) (region-end))
5715 (org-demote)))
5716 (org-fix-position-after-promote))
5718 (defun org-fix-position-after-promote ()
5719 "Make sure that after pro/demotion cursor position is right."
5720 (let ((pos (point)))
5721 (when (save-excursion
5722 (beginning-of-line 1)
5723 (looking-at org-todo-line-regexp)
5724 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5725 (cond ((eobp) (insert " "))
5726 ((eolp) (insert " "))
5727 ((equal (char-after) ?\ ) (forward-char 1))))))
5729 (defun org-reduced-level (l)
5730 "Compute the effective level of a heading.
5731 This takes into account the setting of `org-odd-levels-only'."
5732 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5734 (defun org-get-valid-level (level &optional change)
5735 "Rectify a level change under the influence of `org-odd-levels-only'
5736 LEVEL is a current level, CHANGE is by how much the level should be
5737 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5738 even level numbers will become the next higher odd number."
5739 (if org-odd-levels-only
5740 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5741 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5742 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5743 (max 1 (+ level (or change 0)))))
5745 (if (boundp 'define-obsolete-function-alias)
5746 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5747 (define-obsolete-function-alias 'org-get-legal-level
5748 'org-get-valid-level)
5749 (define-obsolete-function-alias 'org-get-legal-level
5750 'org-get-valid-level "23.1")))
5752 (defun org-promote ()
5753 "Promote the current heading higher up the tree.
5754 If the region is active in `transient-mark-mode', promote all headings
5755 in the region."
5756 (org-back-to-heading t)
5757 (let* ((level (save-match-data (funcall outline-level)))
5758 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5759 (diff (abs (- level (length up-head) -1))))
5760 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5761 (replace-match up-head nil t)
5762 ;; Fixup tag positioning
5763 (and org-auto-align-tags (org-set-tags nil t))
5764 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5766 (defun org-demote ()
5767 "Demote the current heading lower down the tree.
5768 If the region is active in `transient-mark-mode', demote all headings
5769 in the region."
5770 (org-back-to-heading t)
5771 (let* ((level (save-match-data (funcall outline-level)))
5772 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5773 (diff (abs (- level (length down-head) -1))))
5774 (replace-match down-head nil t)
5775 ;; Fixup tag positioning
5776 (and org-auto-align-tags (org-set-tags nil t))
5777 (if org-adapt-indentation (org-fixup-indentation diff))))
5779 (defun org-map-tree (fun)
5780 "Call FUN for every heading underneath the current one."
5781 (org-back-to-heading)
5782 (let ((level (funcall outline-level)))
5783 (save-excursion
5784 (funcall fun)
5785 (while (and (progn
5786 (outline-next-heading)
5787 (> (funcall outline-level) level))
5788 (not (eobp)))
5789 (funcall fun)))))
5791 (defun org-map-region (fun beg end)
5792 "Call FUN for every heading between BEG and END."
5793 (let ((org-ignore-region t))
5794 (save-excursion
5795 (setq end (copy-marker end))
5796 (goto-char beg)
5797 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5798 (< (point) end))
5799 (funcall fun))
5800 (while (and (progn
5801 (outline-next-heading)
5802 (< (point) end))
5803 (not (eobp)))
5804 (funcall fun)))))
5806 (defun org-fixup-indentation (diff)
5807 "Change the indentation in the current entry by DIFF
5808 However, if any line in the current entry has no indentation, or if it
5809 would end up with no indentation after the change, nothing at all is done."
5810 (save-excursion
5811 (let ((end (save-excursion (outline-next-heading)
5812 (point-marker)))
5813 (prohibit (if (> diff 0)
5814 "^\\S-"
5815 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5816 col)
5817 (unless (save-excursion (end-of-line 1)
5818 (re-search-forward prohibit end t))
5819 (while (and (< (point) end)
5820 (re-search-forward "^[ \t]+" end t))
5821 (goto-char (match-end 0))
5822 (setq col (current-column))
5823 (if (< diff 0) (replace-match ""))
5824 (org-indent-to-column (+ diff col))))
5825 (move-marker end nil))))
5827 (defun org-convert-to-odd-levels ()
5828 "Convert an org-mode file with all levels allowed to one with odd levels.
5829 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5830 level 5 etc."
5831 (interactive)
5832 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5833 (let ((org-odd-levels-only nil) n)
5834 (save-excursion
5835 (goto-char (point-min))
5836 (while (re-search-forward "^\\*\\*+ " nil t)
5837 (setq n (- (length (match-string 0)) 2))
5838 (while (>= (setq n (1- n)) 0)
5839 (org-demote))
5840 (end-of-line 1))))))
5843 (defun org-convert-to-oddeven-levels ()
5844 "Convert an org-mode file with only odd levels to one with odd and even levels.
5845 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5846 section with an even level, conversion would destroy the structure of the file. An error
5847 is signaled in this case."
5848 (interactive)
5849 (goto-char (point-min))
5850 ;; First check if there are no even levels
5851 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5852 (org-show-context t)
5853 (error "Not all levels are odd in this file. Conversion not possible."))
5854 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5855 (let ((org-odd-levels-only nil) n)
5856 (save-excursion
5857 (goto-char (point-min))
5858 (while (re-search-forward "^\\*\\*+ " nil t)
5859 (setq n (/ (1- (length (match-string 0))) 2))
5860 (while (>= (setq n (1- n)) 0)
5861 (org-promote))
5862 (end-of-line 1))))))
5864 (defun org-tr-level (n)
5865 "Make N odd if required."
5866 (if org-odd-levels-only (1+ (/ n 2)) n))
5868 ;;; Vertical tree motion, cutting and pasting of subtrees
5870 (defun org-move-subtree-up (&optional arg)
5871 "Move the current subtree up past ARG headlines of the same level."
5872 (interactive "p")
5873 (org-move-subtree-down (- (prefix-numeric-value arg))))
5875 (defun org-move-subtree-down (&optional arg)
5876 "Move the current subtree down past ARG headlines of the same level."
5877 (interactive "p")
5878 (setq arg (prefix-numeric-value arg))
5879 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5880 'outline-get-last-sibling))
5881 (ins-point (make-marker))
5882 (cnt (abs arg))
5883 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5884 ;; Select the tree
5885 (org-back-to-heading)
5886 (setq beg0 (point))
5887 (save-excursion
5888 (setq ne-beg (org-back-over-empty-lines))
5889 (setq beg (point)))
5890 (save-match-data
5891 (save-excursion (outline-end-of-heading)
5892 (setq folded (org-invisible-p)))
5893 (outline-end-of-subtree))
5894 (outline-next-heading)
5895 (setq ne-end (org-back-over-empty-lines))
5896 (setq end (point))
5897 (goto-char beg0)
5898 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5899 ;; include less whitespace
5900 (save-excursion
5901 (goto-char beg)
5902 (forward-line (- ne-beg ne-end))
5903 (setq beg (point))))
5904 ;; Find insertion point, with error handling
5905 (while (> cnt 0)
5906 (or (and (funcall movfunc) (looking-at outline-regexp))
5907 (progn (goto-char beg0)
5908 (error "Cannot move past superior level or buffer limit")))
5909 (setq cnt (1- cnt)))
5910 (if (> arg 0)
5911 ;; Moving forward - still need to move over subtree
5912 (progn (org-end-of-subtree t t)
5913 (save-excursion
5914 (org-back-over-empty-lines)
5915 (or (bolp) (newline)))))
5916 (setq ne-ins (org-back-over-empty-lines))
5917 (move-marker ins-point (point))
5918 (setq txt (buffer-substring beg end))
5919 (org-save-markers-in-region beg end)
5920 (delete-region beg end)
5921 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5922 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5923 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5924 (let ((bbb (point)))
5925 (insert-before-markers txt)
5926 (org-reinstall-markers-in-region bbb)
5927 (move-marker ins-point bbb))
5928 (or (bolp) (insert "\n"))
5929 (setq ins-end (point))
5930 (goto-char ins-point)
5931 (org-skip-whitespace)
5932 (when (and (< arg 0)
5933 (org-first-sibling-p)
5934 (> ne-ins ne-beg))
5935 ;; Move whitespace back to beginning
5936 (save-excursion
5937 (goto-char ins-end)
5938 (let ((kill-whole-line t))
5939 (kill-line (- ne-ins ne-beg)) (point)))
5940 (insert (make-string (- ne-ins ne-beg) ?\n)))
5941 (move-marker ins-point nil)
5942 (org-compact-display-after-subtree-move)
5943 (org-show-empty-lines-in-parent)
5944 (unless folded
5945 (org-show-entry)
5946 (show-children)
5947 (org-cycle-hide-drawers 'children))))
5949 (defvar org-subtree-clip ""
5950 "Clipboard for cut and paste of subtrees.
5951 This is actually only a copy of the kill, because we use the normal kill
5952 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5954 (defvar org-subtree-clip-folded nil
5955 "Was the last copied subtree folded?
5956 This is used to fold the tree back after pasting.")
5958 (defun org-cut-subtree (&optional n)
5959 "Cut the current subtree into the clipboard.
5960 With prefix arg N, cut this many sequential subtrees.
5961 This is a short-hand for marking the subtree and then cutting it."
5962 (interactive "p")
5963 (org-copy-subtree n 'cut))
5965 (defun org-copy-subtree (&optional n cut force-store-markers)
5966 "Cut the current subtree into the clipboard.
5967 With prefix arg N, cut this many sequential subtrees.
5968 This is a short-hand for marking the subtree and then copying it.
5969 If CUT is non-nil, actually cut the subtree.
5970 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5971 of some markers in the region, even if CUT is non-nil. This is
5972 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5973 (interactive "p")
5974 (let (beg end folded (beg0 (point)))
5975 (if (interactive-p)
5976 (org-back-to-heading nil) ; take what looks like a subtree
5977 (org-back-to-heading t)) ; take what is really there
5978 (org-back-over-empty-lines)
5979 (setq beg (point))
5980 (skip-chars-forward " \t\r\n")
5981 (save-match-data
5982 (save-excursion (outline-end-of-heading)
5983 (setq folded (org-invisible-p)))
5984 (condition-case nil
5985 (outline-forward-same-level (1- n))
5986 (error nil))
5987 (org-end-of-subtree t t))
5988 (org-back-over-empty-lines)
5989 (setq end (point))
5990 (goto-char beg0)
5991 (when (> end beg)
5992 (setq org-subtree-clip-folded folded)
5993 (when (or cut force-store-markers)
5994 (org-save-markers-in-region beg end))
5995 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5996 (setq org-subtree-clip (current-kill 0))
5997 (message "%s: Subtree(s) with %d characters"
5998 (if cut "Cut" "Copied")
5999 (length org-subtree-clip)))))
6001 (defun org-paste-subtree (&optional level tree for-yank)
6002 "Paste the clipboard as a subtree, with modification of headline level.
6003 The entire subtree is promoted or demoted in order to match a new headline
6004 level.
6006 If the cursor is at the beginning of a headline, the same level as
6007 that headline is used to paste the tree
6009 If not, the new level is derived from the *visible* headings
6010 before and after the insertion point, and taken to be the inferior headline
6011 level of the two. So if the previous visible heading is level 3 and the
6012 next is level 4 (or vice versa), level 4 will be used for insertion.
6013 This makes sure that the subtree remains an independent subtree and does
6014 not swallow low level entries.
6016 You can also force a different level, either by using a numeric prefix
6017 argument, or by inserting the heading marker by hand. For example, if the
6018 cursor is after \"*****\", then the tree will be shifted to level 5.
6020 If optional TREE is given, use this text instead of the kill ring.
6022 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6023 move back over whitespace before inserting, and move point to the end of
6024 the inserted text when done."
6025 (interactive "P")
6026 (unless (org-kill-is-subtree-p tree)
6027 (error "%s"
6028 (substitute-command-keys
6029 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6030 (let* ((visp (not (org-invisible-p)))
6031 (txt (or tree (and kill-ring (current-kill 0))))
6032 (^re (concat "^\\(" outline-regexp "\\)"))
6033 (re (concat "\\(" outline-regexp "\\)"))
6034 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6036 (old-level (if (string-match ^re txt)
6037 (- (match-end 0) (match-beginning 0) 1)
6038 -1))
6039 (force-level (cond (level (prefix-numeric-value level))
6040 ((and (looking-at "[ \t]*$")
6041 (string-match
6042 ^re_ (buffer-substring
6043 (point-at-bol) (point))))
6044 (- (match-end 1) (match-beginning 1)))
6045 ((and (bolp)
6046 (looking-at org-outline-regexp))
6047 (- (match-end 0) (point) 1))
6048 (t nil)))
6049 (previous-level (save-excursion
6050 (condition-case nil
6051 (progn
6052 (outline-previous-visible-heading 1)
6053 (if (looking-at re)
6054 (- (match-end 0) (match-beginning 0) 1)
6056 (error 1))))
6057 (next-level (save-excursion
6058 (condition-case nil
6059 (progn
6060 (or (looking-at outline-regexp)
6061 (outline-next-visible-heading 1))
6062 (if (looking-at re)
6063 (- (match-end 0) (match-beginning 0) 1)
6065 (error 1))))
6066 (new-level (or force-level (max previous-level next-level)))
6067 (shift (if (or (= old-level -1)
6068 (= new-level -1)
6069 (= old-level new-level))
6071 (- new-level old-level)))
6072 (delta (if (> shift 0) -1 1))
6073 (func (if (> shift 0) 'org-demote 'org-promote))
6074 (org-odd-levels-only nil)
6075 beg end newend)
6076 ;; Remove the forced level indicator
6077 (if force-level
6078 (delete-region (point-at-bol) (point)))
6079 ;; Paste
6080 (beginning-of-line 1)
6081 (unless for-yank (org-back-over-empty-lines))
6082 (setq beg (point))
6083 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6084 (insert-before-markers txt)
6085 (unless (string-match "\n\\'" txt) (insert "\n"))
6086 (setq newend (point))
6087 (org-reinstall-markers-in-region beg)
6088 (setq end (point))
6089 (goto-char beg)
6090 (skip-chars-forward " \t\n\r")
6091 (setq beg (point))
6092 (if (and (org-invisible-p) visp)
6093 (save-excursion (outline-show-heading)))
6094 ;; Shift if necessary
6095 (unless (= shift 0)
6096 (save-restriction
6097 (narrow-to-region beg end)
6098 (while (not (= shift 0))
6099 (org-map-region func (point-min) (point-max))
6100 (setq shift (+ delta shift)))
6101 (goto-char (point-min))
6102 (setq newend (point-max))))
6103 (when (or (interactive-p) for-yank)
6104 (message "Clipboard pasted as level %d subtree" new-level))
6105 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6106 kill-ring
6107 (eq org-subtree-clip (current-kill 0))
6108 org-subtree-clip-folded)
6109 ;; The tree was folded before it was killed/copied
6110 (hide-subtree))
6111 (and for-yank (goto-char newend))))
6113 (defun org-kill-is-subtree-p (&optional txt)
6114 "Check if the current kill is an outline subtree, or a set of trees.
6115 Returns nil if kill does not start with a headline, or if the first
6116 headline level is not the largest headline level in the tree.
6117 So this will actually accept several entries of equal levels as well,
6118 which is OK for `org-paste-subtree'.
6119 If optional TXT is given, check this string instead of the current kill."
6120 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6121 (start-level (and kill
6122 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6123 org-outline-regexp "\\)")
6124 kill)
6125 (- (match-end 2) (match-beginning 2) 1)))
6126 (re (concat "^" org-outline-regexp))
6127 (start (1+ (or (match-beginning 2) -1))))
6128 (if (not start-level)
6129 (progn
6130 nil) ;; does not even start with a heading
6131 (catch 'exit
6132 (while (setq start (string-match re kill (1+ start)))
6133 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6134 (throw 'exit nil)))
6135 t))))
6137 (defvar org-markers-to-move nil
6138 "Markers that should be moved with a cut-and-paste operation.
6139 Those markers are stored together with their positions relative to
6140 the start of the region.")
6142 (defun org-save-markers-in-region (beg end)
6143 "Check markers in region.
6144 If these markers are between BEG and END, record their position relative
6145 to BEG, so that after moving the block of text, we can put the markers back
6146 into place.
6147 This function gets called just before an entry or tree gets cut from the
6148 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6149 called immediately, to move the markers with the entries."
6150 (setq org-markers-to-move nil)
6151 (when (featurep 'org-clock)
6152 (org-clock-save-markers-for-cut-and-paste beg end))
6153 (when (featurep 'org-agenda)
6154 (org-agenda-save-markers-for-cut-and-paste beg end)))
6156 (defun org-check-and-save-marker (marker beg end)
6157 "Check if MARKER is between BEG and END.
6158 If yes, remember the marker and the distance to BEG."
6159 (when (and (marker-buffer marker)
6160 (equal (marker-buffer marker) (current-buffer)))
6161 (if (and (>= marker beg) (< marker end))
6162 (push (cons marker (- marker beg)) org-markers-to-move))))
6164 (defun org-reinstall-markers-in-region (beg)
6165 "Move all remembered markers to their position relative to BEG."
6166 (mapc (lambda (x)
6167 (move-marker (car x) (+ beg (cdr x))))
6168 org-markers-to-move)
6169 (setq org-markers-to-move nil))
6171 (defun org-narrow-to-subtree ()
6172 "Narrow buffer to the current subtree."
6173 (interactive)
6174 (save-excursion
6175 (save-match-data
6176 (narrow-to-region
6177 (progn (org-back-to-heading) (point))
6178 (progn (org-end-of-subtree t) (point))))))
6180 (defun org-clone-subtree-with-time-shift (n &optional shift)
6181 "Clone the task (subtree) at point N times.
6182 The clones will be inserted as siblings.
6184 In interactive use, the user will be prompted for the number of clones
6185 to be produced, and for a time SHIFT, which may be a repeater as used
6186 in time stamps, for example `+3d'.
6188 When a valid repeater is given and the entry contains any time stamps,
6189 the clones will become a sequence in time, with time stamps in the
6190 subtree shifted for each clone produced. If SHIFT is nil or the
6191 empty string, time stamps will be left alone.
6193 If the original subtree did contain time stamps with a repeater,
6194 the following will happen:
6195 - the repeater will be removed in each clone
6196 - an additional clone will be produced, with the current, unshifted
6197 date(s) in the entry.
6198 - the original entry will be placed *after* all the clones, with
6199 repeater intact.
6200 - the start days in the repeater in the original entry will be shifted
6201 to past the last clone.
6202 I this way you can spell out a number of instances of a repeating task,
6203 and still retain the repeater to cover future instances of the task."
6204 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6205 (let (beg end template task
6206 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6207 (if (not (and (integerp n) (> n 0)))
6208 (error "Invalid number of replications %s" n))
6209 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6210 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6211 shift)))
6212 (error "Invalid shift specification %s" shift))
6213 (when doshift
6214 (setq shift-n (string-to-number (match-string 1 shift))
6215 shift-what (cdr (assoc (match-string 2 shift)
6216 '(("d" . day) ("w" . week)
6217 ("m" . month) ("y" . year))))))
6218 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6219 (setq nmin 1 nmax n)
6220 (org-back-to-heading t)
6221 (setq beg (point))
6222 (org-end-of-subtree t t)
6223 (setq end (point))
6224 (setq template (buffer-substring beg end))
6225 (when (and doshift
6226 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6227 (delete-region beg end)
6228 (setq end beg)
6229 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6230 (goto-char end)
6231 (loop for n from nmin to nmax do
6232 (if (not doshift)
6233 (setq task template)
6234 (with-temp-buffer
6235 (insert template)
6236 (org-mode)
6237 (goto-char (point-min))
6238 (while (re-search-forward org-ts-regexp-both nil t)
6239 (org-timestamp-change (* n shift-n) shift-what))
6240 (unless (= n n-no-remove)
6241 (goto-char (point-min))
6242 (while (re-search-forward org-ts-regexp nil t)
6243 (save-excursion
6244 (goto-char (match-beginning 0))
6245 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6246 (delete-region (match-beginning 1) (match-end 1))))))
6247 (setq task (buffer-string))))
6248 (insert task))
6249 (goto-char beg)))
6251 ;;; Outline Sorting
6253 (defun org-sort (with-case)
6254 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6255 Optional argument WITH-CASE means sort case-sensitively.
6256 With a double prefix argument, also remove duplicate entries."
6257 (interactive "P")
6258 (if (org-at-table-p)
6259 (org-call-with-arg 'org-table-sort-lines with-case)
6260 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6262 (defun org-sort-remove-invisible (s)
6263 (remove-text-properties 0 (length s) org-rm-props s)
6264 (while (string-match org-bracket-link-regexp s)
6265 (setq s (replace-match (if (match-end 2)
6266 (match-string 3 s)
6267 (match-string 1 s)) t t s)))
6270 (defvar org-priority-regexp) ; defined later in the file
6272 (defvar org-after-sorting-entries-or-items-hook nil
6273 "Hook that is run after a bunch of entries or items have been sorted.
6274 When children are sorted, the cursor is in the parent line when this
6275 hook gets called. When a region or a plain list is sorted, the cursor
6276 will be in the first entry of the sorted region/list.")
6278 (defun org-sort-entries-or-items
6279 (&optional with-case sorting-type getkey-func compare-func property)
6280 "Sort entries on a certain level of an outline tree, or plain list items.
6281 If there is an active region, the entries in the region are sorted.
6282 Else, if the cursor is before the first entry, sort the top-level items.
6283 Else, the children of the entry at point are sorted.
6284 If the cursor is at the first item in a plain list, the list items will be
6285 sorted.
6287 Sorting can be alphabetically, numerically, by date/time as given by
6288 a time stamp, by a property or by priority.
6290 The command prompts for the sorting type unless it has been given to the
6291 function through the SORTING-TYPE argument, which needs to a character,
6292 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6293 precise meaning of each character:
6295 n Numerically, by converting the beginning of the entry/item to a number.
6296 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6297 t By date/time, either the first active time stamp in the entry, or, if
6298 none exist, by the first inactive one.
6299 In items, only the first line will be chekced.
6300 s By the scheduled date/time.
6301 d By deadline date/time.
6302 c By creation time, which is assumed to be the first inactive time stamp
6303 at the beginning of a line.
6304 p By priority according to the cookie.
6305 r By the value of a property.
6307 Capital letters will reverse the sort order.
6309 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6310 called with point at the beginning of the record. It must return either
6311 a string or a number that should serve as the sorting key for that record.
6313 Comparing entries ignores case by default. However, with an optional argument
6314 WITH-CASE, the sorting considers case as well."
6315 (interactive "P")
6316 (let ((case-func (if with-case 'identity 'downcase))
6317 start beg end stars re re2
6318 txt what tmp plain-list-p)
6319 ;; Find beginning and end of region to sort
6320 (cond
6321 ((org-region-active-p)
6322 ;; we will sort the region
6323 (setq end (region-end)
6324 what "region")
6325 (goto-char (region-beginning))
6326 (if (not (org-on-heading-p)) (outline-next-heading))
6327 (setq start (point)))
6328 ((org-at-item-p)
6329 ;; we will sort this plain list
6330 (org-beginning-of-item-list) (setq start (point))
6331 (org-end-of-item-list) (setq end (point))
6332 (goto-char start)
6333 (setq plain-list-p t
6334 what "plain list"))
6335 ((or (org-on-heading-p)
6336 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6337 ;; we will sort the children of the current headline
6338 (org-back-to-heading)
6339 (setq start (point)
6340 end (progn (org-end-of-subtree t t)
6341 (org-back-over-empty-lines)
6342 (point))
6343 what "children")
6344 (goto-char start)
6345 (show-subtree)
6346 (outline-next-heading))
6348 ;; we will sort the top-level entries in this file
6349 (goto-char (point-min))
6350 (or (org-on-heading-p) (outline-next-heading))
6351 (setq start (point) end (point-max) what "top-level")
6352 (goto-char start)
6353 (show-all)))
6355 (setq beg (point))
6356 (if (>= beg end) (error "Nothing to sort"))
6358 (unless plain-list-p
6359 (looking-at "\\(\\*+\\)")
6360 (setq stars (match-string 1)
6361 re (concat "^" (regexp-quote stars) " +")
6362 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6363 txt (buffer-substring beg end))
6364 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6365 (if (and (not (equal stars "*")) (string-match re2 txt))
6366 (error "Region to sort contains a level above the first entry")))
6368 (unless sorting-type
6369 (message
6370 (if plain-list-p
6371 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6372 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6373 [t]ime [s]cheduled [d]eadline [c]reated
6374 A/N/T/S/D/C/P/O/F means reversed:")
6375 what)
6376 (setq sorting-type (read-char-exclusive))
6378 (and (= (downcase sorting-type) ?f)
6379 (setq getkey-func
6380 (org-ido-completing-read "Sort using function: "
6381 obarray 'fboundp t nil nil))
6382 (setq getkey-func (intern getkey-func)))
6384 (and (= (downcase sorting-type) ?r)
6385 (setq property
6386 (org-ido-completing-read "Property: "
6387 (mapcar 'list (org-buffer-property-keys t))
6388 nil t))))
6390 (message "Sorting entries...")
6392 (save-restriction
6393 (narrow-to-region start end)
6395 (let ((dcst (downcase sorting-type))
6396 (case-fold-search nil)
6397 (now (current-time)))
6398 (sort-subr
6399 (/= dcst sorting-type)
6400 ;; This function moves to the beginning character of the "record" to
6401 ;; be sorted.
6402 (if plain-list-p
6403 (lambda nil
6404 (if (org-at-item-p) t (goto-char (point-max))))
6405 (lambda nil
6406 (if (re-search-forward re nil t)
6407 (goto-char (match-beginning 0))
6408 (goto-char (point-max)))))
6409 ;; This function moves to the last character of the "record" being
6410 ;; sorted.
6411 (if plain-list-p
6412 'org-end-of-item
6413 (lambda nil
6414 (save-match-data
6415 (condition-case nil
6416 (outline-forward-same-level 1)
6417 (error
6418 (goto-char (point-max)))))))
6420 ;; This function returns the value that gets sorted against.
6421 (if plain-list-p
6422 (lambda nil
6423 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6424 (cond
6425 ((= dcst ?n)
6426 (string-to-number (buffer-substring (match-end 0)
6427 (point-at-eol))))
6428 ((= dcst ?a)
6429 (buffer-substring (match-end 0) (point-at-eol)))
6430 ((= dcst ?t)
6431 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6432 (re-search-forward org-ts-regexp-both
6433 (point-at-eol) t))
6434 (org-time-string-to-seconds (match-string 0))
6435 (time-to-seconds now)))
6436 ((= dcst ?f)
6437 (if getkey-func
6438 (progn
6439 (setq tmp (funcall getkey-func))
6440 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6441 tmp)
6442 (error "Invalid key function `%s'" getkey-func)))
6443 (t (error "Invalid sorting type `%c'" sorting-type)))))
6444 (lambda nil
6445 (cond
6446 ((= dcst ?n)
6447 (if (looking-at org-complex-heading-regexp)
6448 (string-to-number (match-string 4))
6449 nil))
6450 ((= dcst ?a)
6451 (if (looking-at org-complex-heading-regexp)
6452 (funcall case-func (match-string 4))
6453 nil))
6454 ((= dcst ?t)
6455 (let ((end (save-excursion (outline-next-heading) (point))))
6456 (if (or (re-search-forward org-ts-regexp end t)
6457 (re-search-forward org-ts-regexp-both end t))
6458 (org-time-string-to-seconds (match-string 0))
6459 (time-to-seconds now))))
6460 ((= dcst ?c)
6461 (let ((end (save-excursion (outline-next-heading) (point))))
6462 (if (re-search-forward
6463 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6464 end t)
6465 (org-time-string-to-seconds (match-string 0))
6466 (time-to-seconds now))))
6467 ((= dcst ?s)
6468 (let ((end (save-excursion (outline-next-heading) (point))))
6469 (if (re-search-forward org-scheduled-time-regexp end t)
6470 (org-time-string-to-seconds (match-string 1))
6471 (time-to-seconds now))))
6472 ((= dcst ?d)
6473 (let ((end (save-excursion (outline-next-heading) (point))))
6474 (if (re-search-forward org-deadline-time-regexp end t)
6475 (org-time-string-to-seconds (match-string 1))
6476 (time-to-seconds now))))
6477 ((= dcst ?p)
6478 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6479 (string-to-char (match-string 2))
6480 org-default-priority))
6481 ((= dcst ?r)
6482 (or (org-entry-get nil property) ""))
6483 ((= dcst ?o)
6484 (if (looking-at org-complex-heading-regexp)
6485 (- 9999 (length (member (match-string 2)
6486 org-todo-keywords-1)))))
6487 ((= dcst ?f)
6488 (if getkey-func
6489 (progn
6490 (setq tmp (funcall getkey-func))
6491 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6492 tmp)
6493 (error "Invalid key function `%s'" getkey-func)))
6494 (t (error "Invalid sorting type `%c'" sorting-type)))))
6496 (cond
6497 ((= dcst ?a) 'string<)
6498 ((= dcst ?f) compare-func)
6499 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6500 (t nil)))))
6501 (run-hooks 'org-after-sorting-entries-or-items-hook)
6502 (message "Sorting entries...done")))
6504 (defun org-do-sort (table what &optional with-case sorting-type)
6505 "Sort TABLE of WHAT according to SORTING-TYPE.
6506 The user will be prompted for the SORTING-TYPE if the call to this
6507 function does not specify it. WHAT is only for the prompt, to indicate
6508 what is being sorted. The sorting key will be extracted from
6509 the car of the elements of the table.
6510 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6511 (unless sorting-type
6512 (message
6513 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6514 what)
6515 (setq sorting-type (read-char-exclusive)))
6516 (let ((dcst (downcase sorting-type))
6517 extractfun comparefun)
6518 ;; Define the appropriate functions
6519 (cond
6520 ((= dcst ?n)
6521 (setq extractfun 'string-to-number
6522 comparefun (if (= dcst sorting-type) '< '>)))
6523 ((= dcst ?a)
6524 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6525 (lambda(x) (downcase (org-sort-remove-invisible x))))
6526 comparefun (if (= dcst sorting-type)
6527 'string<
6528 (lambda (a b) (and (not (string< a b))
6529 (not (string= a b)))))))
6530 ((= dcst ?t)
6531 (setq extractfun
6532 (lambda (x)
6533 (if (or (string-match org-ts-regexp x)
6534 (string-match org-ts-regexp-both x))
6535 (time-to-seconds
6536 (org-time-string-to-time (match-string 0 x)))
6538 comparefun (if (= dcst sorting-type) '< '>)))
6539 (t (error "Invalid sorting type `%c'" sorting-type)))
6541 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6542 table)
6543 (lambda (a b) (funcall comparefun (car a) (car b))))))
6546 ;;; The orgstruct minor mode
6548 ;; Define a minor mode which can be used in other modes in order to
6549 ;; integrate the org-mode structure editing commands.
6551 ;; This is really a hack, because the org-mode structure commands use
6552 ;; keys which normally belong to the major mode. Here is how it
6553 ;; works: The minor mode defines all the keys necessary to operate the
6554 ;; structure commands, but wraps the commands into a function which
6555 ;; tests if the cursor is currently at a headline or a plain list
6556 ;; item. If that is the case, the structure command is used,
6557 ;; temporarily setting many Org-mode variables like regular
6558 ;; expressions for filling etc. However, when any of those keys is
6559 ;; used at a different location, function uses `key-binding' to look
6560 ;; up if the key has an associated command in another currently active
6561 ;; keymap (minor modes, major mode, global), and executes that
6562 ;; command. There might be problems if any of the keys is otherwise
6563 ;; used as a prefix key.
6565 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6566 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6567 ;; addresses this by checking explicitly for both bindings.
6569 (defvar orgstruct-mode-map (make-sparse-keymap)
6570 "Keymap for the minor `orgstruct-mode'.")
6572 (defvar org-local-vars nil
6573 "List of local variables, for use by `orgstruct-mode'")
6575 ;;;###autoload
6576 (define-minor-mode orgstruct-mode
6577 "Toggle the minor more `orgstruct-mode'.
6578 This mode is for using Org-mode structure commands in other modes.
6579 The following key behave as if Org-mode was active, if the cursor
6580 is on a headline, or on a plain list item (both in the definition
6581 of Org-mode).
6583 M-up Move entry/item up
6584 M-down Move entry/item down
6585 M-left Promote
6586 M-right Demote
6587 M-S-up Move entry/item up
6588 M-S-down Move entry/item down
6589 M-S-left Promote subtree
6590 M-S-right Demote subtree
6591 M-q Fill paragraph and items like in Org-mode
6592 C-c ^ Sort entries
6593 C-c - Cycle list bullet
6594 TAB Cycle item visibility
6595 M-RET Insert new heading/item
6596 S-M-RET Insert new TODO heading / Checkbox item
6597 C-c C-c Set tags / toggle checkbox"
6598 nil " OrgStruct" nil
6599 (org-load-modules-maybe)
6600 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6602 ;;;###autoload
6603 (defun turn-on-orgstruct ()
6604 "Unconditionally turn on `orgstruct-mode'."
6605 (orgstruct-mode 1))
6607 (defun orgstruct++-mode (&optional arg)
6608 "Toggle `orgstruct-mode', the enhanced version of it.
6609 In addition to setting orgstruct-mode, this also exports all indentation and
6610 autofilling variables from org-mode into the buffer. It will also
6611 recognize item context in multiline items.
6612 Note that turning off orgstruct-mode will *not* remove the
6613 indentation/paragraph settings. This can only be done by refreshing the
6614 major mode, for example with \[normal-mode]."
6615 (interactive "P")
6616 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6617 (if (< arg 1)
6618 (orgstruct-mode -1)
6619 (orgstruct-mode 1)
6620 (let (var val)
6621 (mapc
6622 (lambda (x)
6623 (when (string-match
6624 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6625 (symbol-name (car x)))
6626 (setq var (car x) val (nth 1 x))
6627 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6628 org-local-vars)
6629 (org-set-local 'orgstruct-is-++ t))))
6631 (defvar orgstruct-is-++ nil
6632 "Is orgstruct-mode in ++ version in the current-buffer?")
6633 (make-variable-buffer-local 'orgstruct-is-++)
6635 ;;;###autoload
6636 (defun turn-on-orgstruct++ ()
6637 "Unconditionally turn on `orgstruct++-mode'."
6638 (orgstruct++-mode 1))
6640 (defun orgstruct-error ()
6641 "Error when there is no default binding for a structure key."
6642 (interactive)
6643 (error "This key has no function outside structure elements"))
6645 (defun orgstruct-setup ()
6646 "Setup orgstruct keymaps."
6647 (let ((nfunc 0)
6648 (bindings
6649 (list
6650 '([(meta up)] org-metaup)
6651 '([(meta down)] org-metadown)
6652 '([(meta left)] org-metaleft)
6653 '([(meta right)] org-metaright)
6654 '([(meta shift up)] org-shiftmetaup)
6655 '([(meta shift down)] org-shiftmetadown)
6656 '([(meta shift left)] org-shiftmetaleft)
6657 '([(meta shift right)] org-shiftmetaright)
6658 '([?\e (up)] org-metaup)
6659 '([?\e (down)] org-metadown)
6660 '([?\e (left)] org-metaleft)
6661 '([?\e (right)] org-metaright)
6662 '([?\e (shift up)] org-shiftmetaup)
6663 '([?\e (shift down)] org-shiftmetadown)
6664 '([?\e (shift left)] org-shiftmetaleft)
6665 '([?\e (shift right)] org-shiftmetaright)
6666 '([(shift up)] org-shiftup)
6667 '([(shift down)] org-shiftdown)
6668 '([(shift left)] org-shiftleft)
6669 '([(shift right)] org-shiftright)
6670 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6671 '("\M-q" fill-paragraph)
6672 '("\C-c^" org-sort)
6673 '("\C-c-" org-cycle-list-bullet)))
6674 elt key fun cmd)
6675 (while (setq elt (pop bindings))
6676 (setq nfunc (1+ nfunc))
6677 (setq key (org-key (car elt))
6678 fun (nth 1 elt)
6679 cmd (orgstruct-make-binding fun nfunc key))
6680 (org-defkey orgstruct-mode-map key cmd))
6682 ;; Special treatment needed for TAB and RET
6683 (org-defkey orgstruct-mode-map [(tab)]
6684 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6685 (org-defkey orgstruct-mode-map "\C-i"
6686 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6688 (org-defkey orgstruct-mode-map "\M-\C-m"
6689 (orgstruct-make-binding 'org-insert-heading 105
6690 "\M-\C-m" [(meta return)]))
6691 (org-defkey orgstruct-mode-map [(meta return)]
6692 (orgstruct-make-binding 'org-insert-heading 106
6693 [(meta return)] "\M-\C-m"))
6695 (org-defkey orgstruct-mode-map [(shift meta return)]
6696 (orgstruct-make-binding 'org-insert-todo-heading 107
6697 [(meta return)] "\M-\C-m"))
6699 (org-defkey orgstruct-mode-map "\e\C-m"
6700 (orgstruct-make-binding 'org-insert-heading 108
6701 "\e\C-m" [?\e (return)]))
6702 (org-defkey orgstruct-mode-map [?\e (return)]
6703 (orgstruct-make-binding 'org-insert-heading 109
6704 [?\e (return)] "\e\C-m"))
6705 (org-defkey orgstruct-mode-map [?\e (shift return)]
6706 (orgstruct-make-binding 'org-insert-todo-heading 110
6707 [?\e (return)] "\e\C-m"))
6709 (unless org-local-vars
6710 (setq org-local-vars (org-get-local-variables)))
6714 (defun orgstruct-make-binding (fun n &rest keys)
6715 "Create a function for binding in the structure minor mode.
6716 FUN is the command to call inside a table. N is used to create a unique
6717 command name. KEYS are keys that should be checked in for a command
6718 to execute outside of tables."
6719 (eval
6720 (list 'defun
6721 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6722 '(arg)
6723 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6724 "Outside of structure, run the binding of `"
6725 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6726 "'.")
6727 '(interactive "p")
6728 (list 'if
6729 `(org-context-p 'headline 'item
6730 (and orgstruct-is-++
6731 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6732 'item-body))
6733 (list 'org-run-like-in-org-mode (list 'quote fun))
6734 (list 'let '(orgstruct-mode)
6735 (list 'call-interactively
6736 (append '(or)
6737 (mapcar (lambda (k)
6738 (list 'key-binding k))
6739 keys)
6740 '('orgstruct-error))))))))
6742 (defun org-context-p (&rest contexts)
6743 "Check if local context is any of CONTEXTS.
6744 Possible values in the list of contexts are `table', `headline', and `item'."
6745 (let ((pos (point)))
6746 (goto-char (point-at-bol))
6747 (prog1 (or (and (memq 'table contexts)
6748 (looking-at "[ \t]*|"))
6749 (and (memq 'headline contexts)
6750 ;;????????? (looking-at "\\*+"))
6751 (looking-at outline-regexp))
6752 (and (memq 'item contexts)
6753 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6754 (and (memq 'item-body contexts)
6755 (org-in-item-p)))
6756 (goto-char pos))))
6758 (defun org-get-local-variables ()
6759 "Return a list of all local variables in an org-mode buffer."
6760 (let (varlist)
6761 (with-current-buffer (get-buffer-create "*Org tmp*")
6762 (erase-buffer)
6763 (org-mode)
6764 (setq varlist (buffer-local-variables)))
6765 (kill-buffer "*Org tmp*")
6766 (delq nil
6767 (mapcar
6768 (lambda (x)
6769 (setq x
6770 (if (symbolp x)
6771 (list x)
6772 (list (car x) (list 'quote (cdr x)))))
6773 (if (string-match
6774 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6775 (symbol-name (car x)))
6776 x nil))
6777 varlist))))
6779 ;;;###autoload
6780 (defun org-run-like-in-org-mode (cmd)
6781 "Run a command, pretending that the current buffer is in Org-mode.
6782 This will temporarily bind local variables that are typically bound in
6783 Org-mode to the values they have in Org-mode, and then interactively
6784 call CMD."
6785 (org-load-modules-maybe)
6786 (unless org-local-vars
6787 (setq org-local-vars (org-get-local-variables)))
6788 (eval (list 'let org-local-vars
6789 (list 'call-interactively (list 'quote cmd)))))
6791 ;;;; Archiving
6793 (defun org-get-category (&optional pos)
6794 "Get the category applying to position POS."
6795 (get-text-property (or pos (point)) 'org-category))
6797 (defun org-refresh-category-properties ()
6798 "Refresh category text properties in the buffer."
6799 (let ((def-cat (cond
6800 ((null org-category)
6801 (if buffer-file-name
6802 (file-name-sans-extension
6803 (file-name-nondirectory buffer-file-name))
6804 "???"))
6805 ((symbolp org-category) (symbol-name org-category))
6806 (t org-category)))
6807 beg end cat pos optionp)
6808 (org-unmodified
6809 (save-excursion
6810 (save-restriction
6811 (widen)
6812 (goto-char (point-min))
6813 (put-text-property (point) (point-max) 'org-category def-cat)
6814 (while (re-search-forward
6815 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6816 (setq pos (match-end 0)
6817 optionp (equal (char-after (match-beginning 0)) ?#)
6818 cat (org-trim (match-string 2)))
6819 (if optionp
6820 (setq beg (point-at-bol) end (point-max))
6821 (org-back-to-heading t)
6822 (setq beg (point) end (org-end-of-subtree t t)))
6823 (put-text-property beg end 'org-category cat)
6824 (goto-char pos)))))))
6827 ;;;; Link Stuff
6829 ;;; Link abbreviations
6831 (defun org-link-expand-abbrev (link)
6832 "Apply replacements as defined in `org-link-abbrev-alist."
6833 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6834 (let* ((key (match-string 1 link))
6835 (as (or (assoc key org-link-abbrev-alist-local)
6836 (assoc key org-link-abbrev-alist)))
6837 (tag (and (match-end 2) (match-string 3 link)))
6838 rpl)
6839 (if (not as)
6840 link
6841 (setq rpl (cdr as))
6842 (cond
6843 ((symbolp rpl) (funcall rpl tag))
6844 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6845 ((string-match "%h" rpl)
6846 (replace-match (url-hexify-string (or tag "")) t t rpl))
6847 (t (concat rpl tag)))))
6848 link))
6850 ;;; Storing and inserting links
6852 (defvar org-insert-link-history nil
6853 "Minibuffer history for links inserted with `org-insert-link'.")
6855 (defvar org-stored-links nil
6856 "Contains the links stored with `org-store-link'.")
6858 (defvar org-store-link-plist nil
6859 "Plist with info about the most recently link created with `org-store-link'.")
6861 (defvar org-link-protocols nil
6862 "Link protocols added to Org-mode using `org-add-link-type'.")
6864 (defvar org-store-link-functions nil
6865 "List of functions that are called to create and store a link.
6866 Each function will be called in turn until one returns a non-nil
6867 value. Each function should check if it is responsible for creating
6868 this link (for example by looking at the major mode).
6869 If not, it must exit and return nil.
6870 If yes, it should return a non-nil value after a calling
6871 `org-store-link-props' with a list of properties and values.
6872 Special properties are:
6874 :type The link prefix. like \"http\". This must be given.
6875 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6876 This is obligatory as well.
6877 :description Optional default description for the second pair
6878 of brackets in an Org-mode link. The user can still change
6879 this when inserting this link into an Org-mode buffer.
6881 In addition to these, any additional properties can be specified
6882 and then used in remember templates.")
6884 (defun org-add-link-type (type &optional follow export)
6885 "Add TYPE to the list of `org-link-types'.
6886 Re-compute all regular expressions depending on `org-link-types'
6888 FOLLOW and EXPORT are two functions.
6890 FOLLOW should take the link path as the single argument and do whatever
6891 is necessary to follow the link, for example find a file or display
6892 a mail message.
6894 EXPORT should format the link path for export to one of the export formats.
6895 It should be a function accepting three arguments:
6897 path the path of the link, the text after the prefix (like \"http:\")
6898 desc the description of the link, if any, nil if there was no description
6899 format the export format, a symbol like `html' or `latex'.
6901 The function may use the FORMAT information to return different values
6902 depending on the format. The return value will be put literally into
6903 the exported file.
6904 Org-mode has a built-in default for exporting links. If you are happy with
6905 this default, there is no need to define an export function for the link
6906 type. For a simple example of an export function, see `org-bbdb.el'."
6907 (add-to-list 'org-link-types type t)
6908 (org-make-link-regexps)
6909 (if (assoc type org-link-protocols)
6910 (setcdr (assoc type org-link-protocols) (list follow export))
6911 (push (list type follow export) org-link-protocols)))
6913 ;;;###autoload
6914 (defun org-store-link (arg)
6915 "\\<org-mode-map>Store an org-link to the current location.
6916 This link is added to `org-stored-links' and can later be inserted
6917 into an org-buffer with \\[org-insert-link].
6919 For some link types, a prefix arg is interpreted:
6920 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6921 For file links, arg negates `org-context-in-file-links'."
6922 (interactive "P")
6923 (org-load-modules-maybe)
6924 (setq org-store-link-plist nil) ; reset
6925 (let (link cpltxt desc description search txt custom-id)
6926 (cond
6928 ((run-hook-with-args-until-success 'org-store-link-functions)
6929 (setq link (plist-get org-store-link-plist :link)
6930 desc (or (plist-get org-store-link-plist :description) link)))
6932 ((equal (buffer-name) "*Org Edit Src Example*")
6933 (let (label gc)
6934 (while (or (not label)
6935 (save-excursion
6936 (save-restriction
6937 (widen)
6938 (goto-char (point-min))
6939 (re-search-forward
6940 (regexp-quote (format org-coderef-label-format label))
6941 nil t))))
6942 (when label (message "Label exists already") (sit-for 2))
6943 (setq label (read-string "Code line label: " label)))
6944 (end-of-line 1)
6945 (setq link (format org-coderef-label-format label))
6946 (setq gc (- 79 (length link)))
6947 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6948 (insert link)
6949 (setq link (concat "(" label ")") desc nil)))
6951 ((eq major-mode 'calendar-mode)
6952 (let ((cd (calendar-cursor-to-date)))
6953 (setq link
6954 (format-time-string
6955 (car org-time-stamp-formats)
6956 (apply 'encode-time
6957 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6958 nil nil nil))))
6959 (org-store-link-props :type "calendar" :date cd)))
6961 ((eq major-mode 'w3-mode)
6962 (setq cpltxt (if (and (buffer-name)
6963 (not (string-match "Untitled" (buffer-name))))
6964 (buffer-name)
6965 (url-view-url t))
6966 link (org-make-link (url-view-url t)))
6967 (org-store-link-props :type "w3" :url (url-view-url t)))
6969 ((eq major-mode 'w3m-mode)
6970 (setq cpltxt (or w3m-current-title w3m-current-url)
6971 link (org-make-link w3m-current-url))
6972 (org-store-link-props :type "w3m" :url (url-view-url t)))
6974 ((setq search (run-hook-with-args-until-success
6975 'org-create-file-search-functions))
6976 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6977 "::" search))
6978 (setq cpltxt (or description link)))
6980 ((eq major-mode 'image-mode)
6981 (setq cpltxt (concat "file:"
6982 (abbreviate-file-name buffer-file-name))
6983 link (org-make-link cpltxt))
6984 (org-store-link-props :type "image" :file buffer-file-name))
6986 ((eq major-mode 'dired-mode)
6987 ;; link to the file in the current line
6988 (setq cpltxt (concat "file:"
6989 (abbreviate-file-name
6990 (expand-file-name
6991 (dired-get-filename nil t))))
6992 link (org-make-link cpltxt)))
6994 ((and buffer-file-name (org-mode-p))
6995 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
6996 (cond
6997 ((org-in-regexp "<<\\(.*?\\)>>")
6998 (setq cpltxt
6999 (concat "file:"
7000 (abbreviate-file-name buffer-file-name)
7001 "::" (match-string 1))
7002 link (org-make-link cpltxt)))
7003 ((and (featurep 'org-id)
7004 (or (eq org-link-to-org-use-id t)
7005 (and (eq org-link-to-org-use-id 'create-if-interactive)
7006 (interactive-p))
7007 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7008 (interactive-p)
7009 (not custom-id))
7010 (and org-link-to-org-use-id
7011 (condition-case nil
7012 (org-entry-get nil "ID")
7013 (error nil)))))
7014 ;; We can make a link using the ID.
7015 (setq link (condition-case nil
7016 (prog1 (org-id-store-link)
7017 (setq desc (plist-get org-store-link-plist
7018 :description)))
7019 (error
7020 ;; probably before first headline, link to file only
7021 (concat "file:"
7022 (abbreviate-file-name buffer-file-name))))))
7024 ;; Just link to current headline
7025 (setq cpltxt (concat "file:"
7026 (abbreviate-file-name buffer-file-name)))
7027 ;; Add a context search string
7028 (when (org-xor org-context-in-file-links arg)
7029 (setq txt (cond
7030 ((org-on-heading-p) nil)
7031 ((org-region-active-p)
7032 (buffer-substring (region-beginning) (region-end)))
7033 (t nil)))
7034 (when (or (null txt) (string-match "\\S-" txt))
7035 (setq cpltxt
7036 (concat cpltxt "::"
7037 (condition-case nil
7038 (org-make-org-heading-search-string txt)
7039 (error "")))
7040 desc "NONE")))
7041 (if (string-match "::\\'" cpltxt)
7042 (setq cpltxt (substring cpltxt 0 -2)))
7043 (setq link (org-make-link cpltxt)))))
7045 ((buffer-file-name (buffer-base-buffer))
7046 ;; Just link to this file here.
7047 (setq cpltxt (concat "file:"
7048 (abbreviate-file-name
7049 (buffer-file-name (buffer-base-buffer)))))
7050 ;; Add a context string
7051 (when (org-xor org-context-in-file-links arg)
7052 (setq txt (if (org-region-active-p)
7053 (buffer-substring (region-beginning) (region-end))
7054 (buffer-substring (point-at-bol) (point-at-eol))))
7055 ;; Only use search option if there is some text.
7056 (when (string-match "\\S-" txt)
7057 (setq cpltxt
7058 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7059 desc "NONE")))
7060 (setq link (org-make-link cpltxt)))
7062 ((interactive-p)
7063 (error "Cannot link to a buffer which is not visiting a file"))
7065 (t (setq link nil)))
7067 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7068 (setq link (or link cpltxt)
7069 desc (or desc cpltxt))
7070 (if (equal desc "NONE") (setq desc nil))
7072 (if (and (interactive-p) link)
7073 (progn
7074 (setq org-stored-links
7075 (cons (list link desc) org-stored-links))
7076 (message "Stored: %s" (or desc link))
7077 (when custom-id
7078 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7079 "::#" custom-id))
7080 (setq org-stored-links
7081 (cons (list link desc) org-stored-links))))
7082 (and link (org-make-link-string link desc)))))
7084 (defun org-store-link-props (&rest plist)
7085 "Store link properties, extract names and addresses."
7086 (let (x adr)
7087 (when (setq x (plist-get plist :from))
7088 (setq adr (mail-extract-address-components x))
7089 (setq plist (plist-put plist :fromname (car adr)))
7090 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7091 (when (setq x (plist-get plist :to))
7092 (setq adr (mail-extract-address-components x))
7093 (setq plist (plist-put plist :toname (car adr)))
7094 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7095 (let ((from (plist-get plist :from))
7096 (to (plist-get plist :to)))
7097 (when (and from to org-from-is-user-regexp)
7098 (setq plist
7099 (plist-put plist :fromto
7100 (if (string-match org-from-is-user-regexp from)
7101 (concat "to %t")
7102 (concat "from %f"))))))
7103 (setq org-store-link-plist plist))
7105 (defun org-add-link-props (&rest plist)
7106 "Add these properties to the link property list."
7107 (let (key value)
7108 (while plist
7109 (setq key (pop plist) value (pop plist))
7110 (setq org-store-link-plist
7111 (plist-put org-store-link-plist key value)))))
7113 (defun org-email-link-description (&optional fmt)
7114 "Return the description part of an email link.
7115 This takes information from `org-store-link-plist' and formats it
7116 according to FMT (default from `org-email-link-description-format')."
7117 (setq fmt (or fmt org-email-link-description-format))
7118 (let* ((p org-store-link-plist)
7119 (to (plist-get p :toaddress))
7120 (from (plist-get p :fromaddress))
7121 (table
7122 (list
7123 (cons "%c" (plist-get p :fromto))
7124 (cons "%F" (plist-get p :from))
7125 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7126 (cons "%T" (plist-get p :to))
7127 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7128 (cons "%s" (plist-get p :subject))
7129 (cons "%m" (plist-get p :message-id)))))
7130 (when (string-match "%c" fmt)
7131 ;; Check if the user wrote this message
7132 (if (and org-from-is-user-regexp from to
7133 (save-match-data (string-match org-from-is-user-regexp from)))
7134 (setq fmt (replace-match "to %t" t t fmt))
7135 (setq fmt (replace-match "from %f" t t fmt))))
7136 (org-replace-escapes fmt table)))
7138 (defun org-make-org-heading-search-string (&optional string heading)
7139 "Make search string for STRING or current headline."
7140 (interactive)
7141 (let ((s (or string (org-get-heading))))
7142 (unless (and string (not heading))
7143 ;; We are using a headline, clean up garbage in there.
7144 (if (string-match org-todo-regexp s)
7145 (setq s (replace-match "" t t s)))
7146 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7147 (setq s (replace-match "" t t s)))
7148 (setq s (org-trim s))
7149 (if (string-match (concat "^\\(" org-quote-string "\\|"
7150 org-comment-string "\\)") s)
7151 (setq s (replace-match "" t t s)))
7152 (while (string-match org-ts-regexp s)
7153 (setq s (replace-match "" t t s))))
7154 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7155 (setq s (replace-match " " t t s)))
7156 (or string (setq s (concat "*" s))) ; Add * for headlines
7157 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7159 (defun org-make-link (&rest strings)
7160 "Concatenate STRINGS."
7161 (apply 'concat strings))
7163 (defun org-make-link-string (link &optional description)
7164 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7165 (unless (string-match "\\S-" link)
7166 (error "Empty link"))
7167 (when (stringp description)
7168 ;; Remove brackets from the description, they are fatal.
7169 (while (string-match "\\[" description)
7170 (setq description (replace-match "{" t t description)))
7171 (while (string-match "\\]" description)
7172 (setq description (replace-match "}" t t description))))
7173 (when (equal (org-link-escape link) description)
7174 ;; No description needed, it is identical
7175 (setq description nil))
7176 (when (and (not description)
7177 (not (equal link (org-link-escape link))))
7178 (setq description (org-extract-attributes link)))
7179 (concat "[[" (org-link-escape link) "]"
7180 (if description (concat "[" description "]") "")
7181 "]"))
7183 (defconst org-link-escape-chars
7184 '((?\ . "%20")
7185 (?\[ . "%5B")
7186 (?\] . "%5D")
7187 (?\340 . "%E0") ; `a
7188 (?\342 . "%E2") ; ^a
7189 (?\347 . "%E7") ; ,c
7190 (?\350 . "%E8") ; `e
7191 (?\351 . "%E9") ; 'e
7192 (?\352 . "%EA") ; ^e
7193 (?\356 . "%EE") ; ^i
7194 (?\364 . "%F4") ; ^o
7195 (?\371 . "%F9") ; `u
7196 (?\373 . "%FB") ; ^u
7197 (?\; . "%3B")
7198 (?? . "%3F")
7199 (?= . "%3D")
7200 (?+ . "%2B")
7202 "Association list of escapes for some characters problematic in links.
7203 This is the list that is used for internal purposes.")
7205 (defvar org-url-encoding-use-url-hexify nil)
7207 (defconst org-link-escape-chars-browser
7208 '((?\ . "%20")) ; 32 for the SPC char
7209 "Association list of escapes for some characters problematic in links.
7210 This is the list that is used before handing over to the browser.")
7212 (defun org-link-escape (text &optional table)
7213 "Escape characters in TEXT that are problematic for links."
7214 (if org-url-encoding-use-url-hexify
7215 (url-hexify-string text)
7216 (setq table (or table org-link-escape-chars))
7217 (when text
7218 (let ((re (mapconcat (lambda (x) (regexp-quote
7219 (char-to-string (car x))))
7220 table "\\|")))
7221 (while (string-match re text)
7222 (setq text
7223 (replace-match
7224 (cdr (assoc (string-to-char (match-string 0 text))
7225 table))
7226 t t text)))
7227 text))))
7229 (defun org-link-unescape (text &optional table)
7230 "Reverse the action of `org-link-escape'."
7231 (if org-url-encoding-use-url-hexify
7232 (url-unhex-string text)
7233 (setq table (or table org-link-escape-chars))
7234 (when text
7235 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7236 table "\\|")))
7237 (while (string-match re text)
7238 (setq text
7239 (replace-match
7240 (char-to-string (car (rassoc (match-string 0 text) table)))
7241 t t text)))
7242 text))))
7244 (defun org-xor (a b)
7245 "Exclusive or."
7246 (if a (not b) b))
7248 (defun org-fixup-message-id-for-http (s)
7249 "Replace special characters in a message id, so it can be used in an http query."
7250 (while (string-match "<" s)
7251 (setq s (replace-match "%3C" t t s)))
7252 (while (string-match ">" s)
7253 (setq s (replace-match "%3E" t t s)))
7254 (while (string-match "@" s)
7255 (setq s (replace-match "%40" t t s)))
7258 ;;;###autoload
7259 (defun org-insert-link-global ()
7260 "Insert a link like Org-mode does.
7261 This command can be called in any mode to insert a link in Org-mode syntax."
7262 (interactive)
7263 (org-load-modules-maybe)
7264 (org-run-like-in-org-mode 'org-insert-link))
7266 (defun org-insert-link (&optional complete-file link-location)
7267 "Insert a link. At the prompt, enter the link.
7269 Completion can be used to insert any of the link protocol prefixes like
7270 http or ftp in use.
7272 The history can be used to select a link previously stored with
7273 `org-store-link'. When the empty string is entered (i.e. if you just
7274 press RET at the prompt), the link defaults to the most recently
7275 stored link. As SPC triggers completion in the minibuffer, you need to
7276 use M-SPC or C-q SPC to force the insertion of a space character.
7278 You will also be prompted for a description, and if one is given, it will
7279 be displayed in the buffer instead of the link.
7281 If there is already a link at point, this command will allow you to edit link
7282 and description parts.
7284 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7285 be selected using completion. The path to the file will be relative to the
7286 current directory if the file is in the current directory or a subdirectory.
7287 Otherwise, the link will be the absolute path as completed in the minibuffer
7288 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7289 option `org-link-file-path-type'.
7291 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7292 the current directory or below.
7294 With three \\[universal-argument] prefixes, negate the meaning of
7295 `org-keep-stored-link-after-insertion'.
7297 If `org-make-link-description-function' is non-nil, this function will be
7298 called with the link target, and the result will be the default
7299 link description.
7301 If the LINK-LOCATION parameter is non-nil, this value will be
7302 used as the link location instead of reading one interactively."
7303 (interactive "P")
7304 (let* ((wcf (current-window-configuration))
7305 (region (if (org-region-active-p)
7306 (buffer-substring (region-beginning) (region-end))))
7307 (remove (and region (list (region-beginning) (region-end))))
7308 (desc region)
7309 tmphist ; byte-compile incorrectly complains about this
7310 (link link-location)
7311 entry file all-prefixes)
7312 (cond
7313 (link-location) ; specified by arg, just use it.
7314 ((org-in-regexp org-bracket-link-regexp 1)
7315 ;; We do have a link at point, and we are going to edit it.
7316 (setq remove (list (match-beginning 0) (match-end 0)))
7317 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7318 (setq link (read-string "Link: "
7319 (org-link-unescape
7320 (org-match-string-no-properties 1)))))
7321 ((or (org-in-regexp org-angle-link-re)
7322 (org-in-regexp org-plain-link-re))
7323 ;; Convert to bracket link
7324 (setq remove (list (match-beginning 0) (match-end 0))
7325 link (read-string "Link: "
7326 (org-remove-angle-brackets (match-string 0)))))
7327 ((member complete-file '((4) (16)))
7328 ;; Completing read for file names.
7329 (setq link (org-file-complete-link complete-file)))
7331 ;; Read link, with completion for stored links.
7332 (with-output-to-temp-buffer "*Org Links*"
7333 (princ "Insert a link.
7334 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7335 (when org-stored-links
7336 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7337 (princ (mapconcat
7338 (lambda (x)
7339 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7340 (reverse org-stored-links) "\n"))))
7341 (let ((cw (selected-window)))
7342 (select-window (get-buffer-window "*Org Links*"))
7343 (setq truncate-lines t)
7344 (unless (pos-visible-in-window-p (point-max))
7345 (org-fit-window-to-buffer))
7346 (and (window-live-p cw) (select-window cw)))
7347 ;; Fake a link history, containing the stored links.
7348 (setq tmphist (append (mapcar 'car org-stored-links)
7349 org-insert-link-history))
7350 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7351 (mapcar 'car org-link-abbrev-alist)
7352 org-link-types))
7353 (unwind-protect
7354 (progn
7355 (setq link
7356 (let ((org-completion-use-ido nil))
7357 (org-completing-read
7358 "Link: "
7359 (mapcar (lambda (x) (list (concat x ":")))
7360 all-prefixes)
7361 nil nil nil
7362 'tmphist
7363 (or (car (car org-stored-links))))))
7364 (if (or (member link all-prefixes)
7365 (and (equal ":" (substring link -1))
7366 (member (substring link 0 -1) all-prefixes)
7367 (setq link (substring link 0 -1))))
7368 (setq link (org-link-try-special-completion link))))
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-link-try-special-completion (type)
7431 "If there is completion support for link type TAPE, offer it."
7432 (let ((fun (intern (concat "org-" type "-complete-link"))))
7433 (if (functionp fun)
7434 (funcall fun)
7435 (read-string "Link (no completion support): " (concat type ":")))))
7437 (defun org-file-complete-link (&optional arg)
7438 "Create a file link using completion."
7439 (let (file link)
7440 (setq file (read-file-name "File: "))
7441 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7442 (pwd1 (file-name-as-directory (abbreviate-file-name
7443 (expand-file-name ".")))))
7444 (cond
7445 ((equal arg '(16))
7446 (setq link (org-make-link
7447 "file:"
7448 (abbreviate-file-name (expand-file-name file)))))
7449 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7450 (setq link (org-make-link "file:" (match-string 1 file))))
7451 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7452 (expand-file-name file))
7453 (setq link (org-make-link
7454 "file:" (match-string 1 (expand-file-name file)))))
7455 (t (setq link (org-make-link "file:" file)))))
7456 link))
7458 (defun org-completing-read (&rest args)
7459 "Completing-read with SPACE being a normal character."
7460 (let ((minibuffer-local-completion-map
7461 (copy-keymap minibuffer-local-completion-map)))
7462 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7463 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7464 (apply 'org-ido-completing-read args)))
7466 (defun org-completing-read-no-ido (&rest args)
7467 (let (org-completion-use-ido)
7468 (apply 'org-completing-read args)))
7470 (defun org-ido-completing-read (&rest args)
7471 "Completing-read using `ido-mode' speedups if available"
7472 (if (and org-completion-use-ido
7473 (fboundp 'ido-completing-read)
7474 (boundp 'ido-mode) ido-mode
7475 (listp (second args)))
7476 (let ((ido-enter-matching-directory nil))
7477 (apply 'ido-completing-read (concat (car args))
7478 (mapcar (lambda (x) (car x)) (nth 1 args))
7479 (cddr args)))
7480 (apply 'completing-read args)))
7482 (defun org-extract-attributes (s)
7483 "Extract the attributes cookie from a string and set as text property."
7484 (let (a attr (start 0) key value)
7485 (save-match-data
7486 (when (string-match "{{\\([^}]+\\)}}$" s)
7487 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7488 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7489 (setq key (match-string 1 a) value (match-string 2 a)
7490 start (match-end 0)
7491 attr (plist-put attr (intern key) value))))
7492 (org-add-props s nil 'org-attr attr))
7495 (defun org-extract-attributes-from-string (tag)
7496 (let (key value attr)
7497 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7498 (setq key (match-string 1 tag) value (match-string 2 tag)
7499 tag (replace-match "" t t tag)
7500 attr (plist-put attr (intern key) value)))
7501 (cons tag attr)))
7503 (defun org-attributes-to-string (plist)
7504 "Format a property list into an HTML attribute list."
7505 (let ((s "") key value)
7506 (while plist
7507 (setq key (pop plist) value (pop plist))
7508 (and value
7509 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7512 ;;; Opening/following a link
7514 (defvar org-link-search-failed nil)
7516 (defun org-next-link ()
7517 "Move forward to the next link.
7518 If the link is in hidden text, expose it."
7519 (interactive)
7520 (when (and org-link-search-failed (eq this-command last-command))
7521 (goto-char (point-min))
7522 (message "Link search wrapped back to beginning of buffer"))
7523 (setq org-link-search-failed nil)
7524 (let* ((pos (point))
7525 (ct (org-context))
7526 (a (assoc :link ct)))
7527 (if a (goto-char (nth 2 a)))
7528 (if (re-search-forward org-any-link-re nil t)
7529 (progn
7530 (goto-char (match-beginning 0))
7531 (if (org-invisible-p) (org-show-context)))
7532 (goto-char pos)
7533 (setq org-link-search-failed t)
7534 (error "No further link found"))))
7536 (defun org-previous-link ()
7537 "Move backward to the previous link.
7538 If the link is in hidden text, expose it."
7539 (interactive)
7540 (when (and org-link-search-failed (eq this-command last-command))
7541 (goto-char (point-max))
7542 (message "Link search wrapped back to end of buffer"))
7543 (setq org-link-search-failed nil)
7544 (let* ((pos (point))
7545 (ct (org-context))
7546 (a (assoc :link ct)))
7547 (if a (goto-char (nth 1 a)))
7548 (if (re-search-backward org-any-link-re nil t)
7549 (progn
7550 (goto-char (match-beginning 0))
7551 (if (org-invisible-p) (org-show-context)))
7552 (goto-char pos)
7553 (setq org-link-search-failed t)
7554 (error "No further link found"))))
7556 (defun org-translate-link (s)
7557 "Translate a link string if a translation function has been defined."
7558 (if (and org-link-translation-function
7559 (fboundp org-link-translation-function)
7560 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7561 (progn
7562 (setq s (funcall org-link-translation-function
7563 (match-string 1) (match-string 2)))
7564 (concat (car s) ":" (cdr s)))
7567 (defun org-translate-link-from-planner (type path)
7568 "Translate a link from Emacs Planner syntax so that Org can follow it.
7569 This is still an experimental function, your mileage may vary."
7570 (cond
7571 ((member type '("http" "https" "news" "ftp"))
7572 ;; standard Internet links are the same.
7573 nil)
7574 ((and (equal type "irc") (string-match "^//" path))
7575 ;; Planner has two / at the beginning of an irc link, we have 1.
7576 ;; We should have zero, actually....
7577 (setq path (substring path 1)))
7578 ((and (equal type "lisp") (string-match "^/" path))
7579 ;; Planner has a slash, we do not.
7580 (setq type "elisp" path (substring path 1)))
7581 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7582 ;; A typical message link. Planner has the id after the fina slash,
7583 ;; we separate it with a hash mark
7584 (setq path (concat (match-string 1 path) "#"
7585 (org-remove-angle-brackets (match-string 2 path)))))
7587 (cons type path))
7589 (defun org-find-file-at-mouse (ev)
7590 "Open file link or URL at mouse."
7591 (interactive "e")
7592 (mouse-set-point ev)
7593 (org-open-at-point 'in-emacs))
7595 (defun org-open-at-mouse (ev)
7596 "Open file link or URL at mouse."
7597 (interactive "e")
7598 (mouse-set-point ev)
7599 (if (eq major-mode 'org-agenda-mode)
7600 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7601 (org-open-at-point))
7603 (defvar org-window-config-before-follow-link nil
7604 "The window configuration before following a link.
7605 This is saved in case the need arises to restore it.")
7607 (defvar org-open-link-marker (make-marker)
7608 "Marker pointing to the location where `org-open-at-point; was called.")
7610 ;;;###autoload
7611 (defun org-open-at-point-global ()
7612 "Follow a link like Org-mode does.
7613 This command can be called in any mode to follow a link that has
7614 Org-mode syntax."
7615 (interactive)
7616 (org-run-like-in-org-mode 'org-open-at-point))
7618 ;;;###autoload
7619 (defun org-open-link-from-string (s &optional arg)
7620 "Open a link in the string S, as if it was in Org-mode."
7621 (interactive "sLink: \nP")
7622 (let ((reference-buffer (current-buffer)))
7623 (with-temp-buffer
7624 (let ((org-inhibit-startup t))
7625 (org-mode)
7626 (insert s)
7627 (goto-char (point-min))
7628 (org-open-at-point arg reference-buffer)))))
7630 (defun org-open-at-point (&optional in-emacs reference-buffer)
7631 "Open link at or after point.
7632 If there is no link at point, this function will search forward up to
7633 the end of the current line.
7634 Normally, files will be opened by an appropriate application. If the
7635 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7636 With a double prefix argument, try to open outside of Emacs, in the
7637 application the system uses for this file type."
7638 (interactive "P")
7639 (org-load-modules-maybe)
7640 (move-marker org-open-link-marker (point))
7641 (setq org-window-config-before-follow-link (current-window-configuration))
7642 (org-remove-occur-highlights nil nil t)
7643 (cond
7644 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7645 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7646 (org-footnote-action))
7648 (let (type path link line search (pos (point)))
7649 (catch 'match
7650 (save-excursion
7651 (skip-chars-forward "^]\n\r")
7652 (when (org-in-regexp org-bracket-link-regexp)
7653 (setq link (org-extract-attributes
7654 (org-link-unescape (org-match-string-no-properties 1))))
7655 (while (string-match " *\n *" link)
7656 (setq link (replace-match " " t t link)))
7657 (setq link (org-link-expand-abbrev link))
7658 (cond
7659 ((or (file-name-absolute-p link)
7660 (string-match "^\\.\\.?/" link))
7661 (setq type "file" path link))
7662 ((string-match org-link-re-with-space3 link)
7663 (setq type (match-string 1 link) path (match-string 2 link)))
7664 (t (setq type "thisfile" path link)))
7665 (throw 'match t)))
7667 (when (get-text-property (point) 'org-linked-text)
7668 (setq type "thisfile"
7669 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7670 (1+ (point)) (point))
7671 path (buffer-substring
7672 (previous-single-property-change pos 'org-linked-text)
7673 (next-single-property-change pos 'org-linked-text)))
7674 (throw 'match t))
7676 (save-excursion
7677 (when (or (org-in-regexp org-angle-link-re)
7678 (org-in-regexp org-plain-link-re))
7679 (setq type (match-string 1) path (match-string 2))
7680 (throw 'match t)))
7681 (save-excursion
7682 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7683 (setq type "tags"
7684 path (match-string 1))
7685 (while (string-match ":" path)
7686 (setq path (replace-match "+" t t path)))
7687 (throw 'match t)))
7688 (when (org-in-regexp "<\\([^><\n]+\\)>")
7689 (setq type "tree-match"
7690 path (match-string 1))
7691 (throw 'match t)))
7692 (unless path
7693 (error "No link found"))
7695 ;; switch back to reference buffer
7696 ;; needed when if called in a temporary buffer through
7697 ;; org-open-link-from-string
7698 (and reference-buffer (switch-to-buffer reference-buffer))
7700 ;; Remove any trailing spaces in path
7701 (if (string-match " +\\'" path)
7702 (setq path (replace-match "" t t path)))
7703 (if (and org-link-translation-function
7704 (fboundp org-link-translation-function))
7705 ;; Check if we need to translate the link
7706 (let ((tmp (funcall org-link-translation-function type path)))
7707 (setq type (car tmp) path (cdr tmp))))
7709 (cond
7711 ((assoc type org-link-protocols)
7712 (funcall (nth 1 (assoc type org-link-protocols)) path))
7714 ((equal type "mailto")
7715 (let ((cmd (car org-link-mailto-program))
7716 (args (cdr org-link-mailto-program)) args1
7717 (address path) (subject "") a)
7718 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7719 (setq address (match-string 1 path)
7720 subject (org-link-escape (match-string 2 path))))
7721 (while args
7722 (cond
7723 ((not (stringp (car args))) (push (pop args) args1))
7724 (t (setq a (pop args))
7725 (if (string-match "%a" a)
7726 (setq a (replace-match address t t a)))
7727 (if (string-match "%s" a)
7728 (setq a (replace-match subject t t a)))
7729 (push a args1))))
7730 (apply cmd (nreverse args1))))
7732 ((member type '("http" "https" "ftp" "news"))
7733 (browse-url (concat type ":" (org-link-escape
7734 path org-link-escape-chars-browser))))
7736 ((member type '("message"))
7737 (browse-url (concat type ":" path)))
7739 ((string= type "tags")
7740 (org-tags-view in-emacs path))
7741 ((string= type "thisfile")
7742 (if in-emacs
7743 (switch-to-buffer-other-window
7744 (org-get-buffer-for-internal-link (current-buffer)))
7745 (org-mark-ring-push))
7746 (let ((cmd `(org-link-search
7747 ,path
7748 ,(cond ((equal in-emacs '(4)) 'occur)
7749 ((equal in-emacs '(16)) 'org-occur)
7750 (t nil))
7751 ,pos)))
7752 (condition-case nil (eval cmd)
7753 (error (progn (widen) (eval cmd))))))
7755 ((string= type "tree-match")
7756 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7758 ((string= type "file")
7759 (if (string-match "::\\([0-9]+\\)\\'" path)
7760 (setq line (string-to-number (match-string 1 path))
7761 path (substring path 0 (match-beginning 0)))
7762 (if (string-match "::\\(.+\\)\\'" path)
7763 (setq search (match-string 1 path)
7764 path (substring path 0 (match-beginning 0)))))
7765 (if (string-match "[*?{]" (file-name-nondirectory path))
7766 (dired path)
7767 (org-open-file path in-emacs line search)))
7769 ((string= type "news")
7770 (require 'org-gnus)
7771 (org-gnus-follow-link path))
7773 ((string= type "shell")
7774 (let ((cmd path))
7775 (if (or (not org-confirm-shell-link-function)
7776 (funcall org-confirm-shell-link-function
7777 (format "Execute \"%s\" in shell? "
7778 (org-add-props cmd nil
7779 'face 'org-warning))))
7780 (progn
7781 (message "Executing %s" cmd)
7782 (shell-command cmd))
7783 (error "Abort"))))
7785 ((string= type "elisp")
7786 (let ((cmd path))
7787 (if (or (not org-confirm-elisp-link-function)
7788 (funcall org-confirm-elisp-link-function
7789 (format "Execute \"%s\" as elisp? "
7790 (org-add-props cmd nil
7791 'face 'org-warning))))
7792 (message "%s => %s" cmd
7793 (if (equal (string-to-char cmd) ?\()
7794 (eval (read cmd))
7795 (call-interactively (read cmd))))
7796 (error "Abort"))))
7799 (browse-url-at-point))))))
7800 (move-marker org-open-link-marker nil)
7801 (run-hook-with-args 'org-follow-link-hook))
7803 ;;;; Time estimates
7805 (defun org-get-effort (&optional pom)
7806 "Get the effort estimate for the current entry."
7807 (org-entry-get pom org-effort-property))
7809 ;;; File search
7811 (defvar org-create-file-search-functions nil
7812 "List of functions to construct the right search string for a file link.
7813 These functions are called in turn with point at the location to
7814 which the link should point.
7816 A function in the hook should first test if it would like to
7817 handle this file type, for example by checking the major-mode or
7818 the file extension. If it decides not to handle this file, it
7819 should just return nil to give other functions a chance. If it
7820 does handle the file, it must return the search string to be used
7821 when following the link. The search string will be part of the
7822 file link, given after a double colon, and `org-open-at-point'
7823 will automatically search for it. If special measures must be
7824 taken to make the search successful, another function should be
7825 added to the companion hook `org-execute-file-search-functions',
7826 which see.
7828 A function in this hook may also use `setq' to set the variable
7829 `description' to provide a suggestion for the descriptive text to
7830 be used for this link when it gets inserted into an Org-mode
7831 buffer with \\[org-insert-link].")
7833 (defvar org-execute-file-search-functions nil
7834 "List of functions to execute a file search triggered by a link.
7836 Functions added to this hook must accept a single argument, the
7837 search string that was part of the file link, the part after the
7838 double colon. The function must first check if it would like to
7839 handle this search, for example by checking the major-mode or the
7840 file extension. If it decides not to handle this search, it
7841 should just return nil to give other functions a chance. If it
7842 does handle the search, it must return a non-nil value to keep
7843 other functions from trying.
7845 Each function can access the current prefix argument through the
7846 variable `current-prefix-argument'. Note that a single prefix is
7847 used to force opening a link in Emacs, so it may be good to only
7848 use a numeric or double prefix to guide the search function.
7850 In case this is needed, a function in this hook can also restore
7851 the window configuration before `org-open-at-point' was called using:
7853 (set-window-configuration org-window-config-before-follow-link)")
7855 (defun org-link-search (s &optional type avoid-pos)
7856 "Search for a link search option.
7857 If S is surrounded by forward slashes, it is interpreted as a
7858 regular expression. In org-mode files, this will create an `org-occur'
7859 sparse tree. In ordinary files, `occur' will be used to list matches.
7860 If the current buffer is in `dired-mode', grep will be used to search
7861 in all files. If AVOID-POS is given, ignore matches near that position."
7862 (let ((case-fold-search t)
7863 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7864 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7865 (append '(("") (" ") ("\t") ("\n"))
7866 org-emphasis-alist)
7867 "\\|") "\\)"))
7868 (pos (point))
7869 (pre nil) (post nil)
7870 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7871 (cond
7872 ;; First check if there are any special
7873 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7874 ;; Now try the builtin stuff
7875 ((and (equal (string-to-char s0) ?#)
7876 (> (length s0) 1)
7877 (save-excursion
7878 (goto-char (point-min))
7879 (and
7880 (re-search-forward
7881 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
7882 (setq type 'dedicated
7883 pos (match-beginning 0))))
7884 ;; There is an exact target for this
7885 (goto-char pos)
7886 (org-back-to-heading t)))
7887 ((save-excursion
7888 (goto-char (point-min))
7889 (and
7890 (re-search-forward
7891 (concat "<<" (regexp-quote s0) ">>") nil t)
7892 (setq type 'dedicated
7893 pos (match-beginning 0))))
7894 ;; There is an exact target for this
7895 (goto-char pos))
7896 ((and (string-match "^(\\(.*\\))$" s0)
7897 (save-excursion
7898 (goto-char (point-min))
7899 (and
7900 (re-search-forward
7901 (concat "[^[]" (regexp-quote
7902 (format org-coderef-label-format
7903 (match-string 1 s0))))
7904 nil t)
7905 (setq type 'dedicated
7906 pos (1+ (match-beginning 0))))))
7907 ;; There is a coderef target for this
7908 (goto-char pos))
7909 ((string-match "^/\\(.*\\)/$" s)
7910 ;; A regular expression
7911 (cond
7912 ((org-mode-p)
7913 (org-occur (match-string 1 s)))
7914 ;;((eq major-mode 'dired-mode)
7915 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7916 (t (org-do-occur (match-string 1 s)))))
7918 ;; A normal search strings
7919 (when (equal (string-to-char s) ?*)
7920 ;; Anchor on headlines, post may include tags.
7921 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7922 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7923 s (substring s 1)))
7924 (remove-text-properties
7925 0 (length s)
7926 '(face nil mouse-face nil keymap nil fontified nil) s)
7927 ;; Make a series of regular expressions to find a match
7928 (setq words (org-split-string s "[ \n\r\t]+")
7930 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7931 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7932 "\\)" markers)
7933 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7934 re2a (concat "[ \t\r\n]" re2a_)
7935 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7936 re4 (concat "[^a-zA-Z_]" re4_)
7938 re1 (concat pre re2 post)
7939 re3 (concat pre (if pre re4_ re4) post)
7940 re5 (concat pre ".*" re4)
7941 re2 (concat pre re2)
7942 re2a (concat pre (if pre re2a_ re2a))
7943 re4 (concat pre (if pre re4_ re4))
7944 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7945 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7946 re5 "\\)"
7948 (cond
7949 ((eq type 'org-occur) (org-occur reall))
7950 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7951 (t (goto-char (point-min))
7952 (setq type 'fuzzy)
7953 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7954 (org-search-not-self 1 re1 nil t)
7955 (org-search-not-self 1 re2 nil t)
7956 (org-search-not-self 1 re2a nil t)
7957 (org-search-not-self 1 re3 nil t)
7958 (org-search-not-self 1 re4 nil t)
7959 (org-search-not-self 1 re5 nil t)
7961 (goto-char (match-beginning 1))
7962 (goto-char pos)
7963 (error "No match")))))
7965 ;; Normal string-search
7966 (goto-char (point-min))
7967 (if (search-forward s nil t)
7968 (goto-char (match-beginning 0))
7969 (error "No match"))))
7970 (and (org-mode-p) (org-show-context 'link-search))
7971 type))
7973 (defun org-search-not-self (group &rest args)
7974 "Execute `re-search-forward', but only accept matches that do not
7975 enclose the position of `org-open-link-marker'."
7976 (let ((m org-open-link-marker))
7977 (catch 'exit
7978 (while (apply 're-search-forward args)
7979 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7980 (goto-char (match-end group))
7981 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7982 (> (match-beginning 0) (marker-position m))
7983 (< (match-end 0) (marker-position m)))
7984 (save-match-data
7985 (or (not (org-in-regexp
7986 org-bracket-link-analytic-regexp 1))
7987 (not (match-end 4)) ; no description
7988 (and (<= (match-beginning 4) (point))
7989 (>= (match-end 4) (point))))))
7990 (throw 'exit (point))))))))
7992 (defun org-get-buffer-for-internal-link (buffer)
7993 "Return a buffer to be used for displaying the link target of internal links."
7994 (cond
7995 ((not org-display-internal-link-with-indirect-buffer)
7996 buffer)
7997 ((string-match "(Clone)$" (buffer-name buffer))
7998 (message "Buffer is already a clone, not making another one")
7999 ;; we also do not modify visibility in this case
8000 buffer)
8001 (t ; make a new indirect buffer for displaying the link
8002 (let* ((bn (buffer-name buffer))
8003 (ibn (concat bn "(Clone)"))
8004 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8005 (with-current-buffer ib (org-overview))
8006 ib))))
8008 (defun org-do-occur (regexp &optional cleanup)
8009 "Call the Emacs command `occur'.
8010 If CLEANUP is non-nil, remove the printout of the regular expression
8011 in the *Occur* buffer. This is useful if the regex is long and not useful
8012 to read."
8013 (occur regexp)
8014 (when cleanup
8015 (let ((cwin (selected-window)) win beg end)
8016 (when (setq win (get-buffer-window "*Occur*"))
8017 (select-window win))
8018 (goto-char (point-min))
8019 (when (re-search-forward "match[a-z]+" nil t)
8020 (setq beg (match-end 0))
8021 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8022 (setq end (1- (match-beginning 0)))))
8023 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8024 (goto-char (point-min))
8025 (select-window cwin))))
8027 ;;; The mark ring for links jumps
8029 (defvar org-mark-ring nil
8030 "Mark ring for positions before jumps in Org-mode.")
8031 (defvar org-mark-ring-last-goto nil
8032 "Last position in the mark ring used to go back.")
8033 ;; Fill and close the ring
8034 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8035 (loop for i from 1 to org-mark-ring-length do
8036 (push (make-marker) org-mark-ring))
8037 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8038 org-mark-ring)
8040 (defun org-mark-ring-push (&optional pos buffer)
8041 "Put the current position or POS into the mark ring and rotate it."
8042 (interactive)
8043 (setq pos (or pos (point)))
8044 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8045 (move-marker (car org-mark-ring)
8046 (or pos (point))
8047 (or buffer (current-buffer)))
8048 (message "%s"
8049 (substitute-command-keys
8050 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8052 (defun org-mark-ring-goto (&optional n)
8053 "Jump to the previous position in the mark ring.
8054 With prefix arg N, jump back that many stored positions. When
8055 called several times in succession, walk through the entire ring.
8056 Org-mode commands jumping to a different position in the current file,
8057 or to another Org-mode file, automatically push the old position
8058 onto the ring."
8059 (interactive "p")
8060 (let (p m)
8061 (if (eq last-command this-command)
8062 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8063 (setq p org-mark-ring))
8064 (setq org-mark-ring-last-goto p)
8065 (setq m (car p))
8066 (switch-to-buffer (marker-buffer m))
8067 (goto-char m)
8068 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8070 (defun org-remove-angle-brackets (s)
8071 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8072 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8074 (defun org-add-angle-brackets (s)
8075 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8076 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8078 (defun org-remove-double-quotes (s)
8079 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8080 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8083 ;;; Following specific links
8085 (defun org-follow-timestamp-link ()
8086 (cond
8087 ((org-at-date-range-p t)
8088 (let ((org-agenda-start-on-weekday)
8089 (t1 (match-string 1))
8090 (t2 (match-string 2)))
8091 (setq t1 (time-to-days (org-time-string-to-time t1))
8092 t2 (time-to-days (org-time-string-to-time t2)))
8093 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8094 ((org-at-timestamp-p t)
8095 (org-agenda-list nil (time-to-days (org-time-string-to-time
8096 (substring (match-string 1) 0 10)))
8098 (t (error "This should not happen"))))
8101 ;;; Following file links
8102 (defvar org-wait nil)
8103 (defun org-open-file (path &optional in-emacs line search)
8104 "Open the file at PATH.
8105 First, this expands any special file name abbreviations. Then the
8106 configuration variable `org-file-apps' is checked if it contains an
8107 entry for this file type, and if yes, the corresponding command is launched.
8109 If no application is found, Emacs simply visits the file.
8111 With optional prefix argument IN-EMACS, Emacs will visit the file.
8112 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8113 and o use an external application to visit the file.
8115 Optional LINE specifies a line to go to, optional SEARCH a string to
8116 search for. If LINE or SEARCH is given, the file will always be
8117 opened in Emacs.
8118 If the file does not exist, an error is thrown."
8119 (setq in-emacs (or in-emacs line search))
8120 (let* ((file (if (equal path "")
8121 buffer-file-name
8122 (substitute-in-file-name (expand-file-name path))))
8123 (apps (append org-file-apps (org-default-apps)))
8124 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8125 (dirp (if remp nil (file-directory-p file)))
8126 (file (if (and dirp org-open-directory-means-index-dot-org)
8127 (concat (file-name-as-directory file) "index.org")
8128 file))
8129 (a-m-a-p (assq 'auto-mode apps))
8130 (dfile (downcase file))
8131 (old-buffer (current-buffer))
8132 (old-pos (point))
8133 (old-mode major-mode)
8134 ext cmd)
8135 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8136 (setq ext (match-string 1 dfile))
8137 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8138 (setq ext (match-string 1 dfile))))
8139 (cond
8140 ((equal in-emacs '(16))
8141 (setq cmd (cdr (assoc 'system apps))))
8142 (in-emacs (setq cmd 'emacs))
8144 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8145 (and dirp (cdr (assoc 'directory apps)))
8146 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8147 'string-match)
8148 (cdr (assoc ext apps))
8149 (cdr (assoc t apps))))))
8150 (when (eq cmd 'system)
8151 (setq cmd (cdr (assoc 'system apps))))
8152 (when (eq cmd 'default)
8153 (setq cmd (cdr (assoc t apps))))
8154 (when (eq cmd 'mailcap)
8155 (require 'mailcap)
8156 (mailcap-parse-mailcaps)
8157 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8158 (command (mailcap-mime-info mime-type)))
8159 (if (stringp command)
8160 (setq cmd command)
8161 (setq cmd 'emacs))))
8162 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8163 (not (file-exists-p file))
8164 (not org-open-non-existing-files))
8165 (error "No such file: %s" file))
8166 (cond
8167 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8168 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8169 (while (string-match "['\"]%s['\"]" cmd)
8170 (setq cmd (replace-match "%s" t t cmd)))
8171 (while (string-match "%s" cmd)
8172 (setq cmd (replace-match
8173 (save-match-data
8174 (shell-quote-argument
8175 (convert-standard-filename file)))
8176 t t cmd)))
8177 (save-window-excursion
8178 (start-process-shell-command cmd nil cmd)
8179 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8181 ((or (stringp cmd)
8182 (eq cmd 'emacs))
8183 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8184 (widen)
8185 (if line (goto-line line)
8186 (if search (org-link-search search))))
8187 ((consp cmd)
8188 (let ((file (convert-standard-filename file)))
8189 (eval cmd)))
8190 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8191 (and (org-mode-p) (eq old-mode 'org-mode)
8192 (or (not (equal old-buffer (current-buffer)))
8193 (not (equal old-pos (point))))
8194 (org-mark-ring-push old-pos old-buffer))))
8196 (defun org-default-apps ()
8197 "Return the default applications for this operating system."
8198 (cond
8199 ((eq system-type 'darwin)
8200 org-file-apps-defaults-macosx)
8201 ((eq system-type 'windows-nt)
8202 org-file-apps-defaults-windowsnt)
8203 (t org-file-apps-defaults-gnu)))
8205 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8206 "Convert extensions to regular expressions in the cars of LIST.
8207 Also, weed out any non-string entries, because the return value is used
8208 only for regexp matching.
8209 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8210 point to the symbol `emacs', indicating that the file should
8211 be opened in Emacs."
8212 (append
8213 (delq nil
8214 (mapcar (lambda (x)
8215 (if (not (stringp (car x)))
8217 (if (string-match "\\W" (car x))
8219 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8220 list))
8221 (if add-auto-mode
8222 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8224 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8225 (defun org-file-remote-p (file)
8226 "Test whether FILE specifies a location on a remote system.
8227 Return non-nil if the location is indeed remote.
8229 For example, the filename \"/user@host:/foo\" specifies a location
8230 on the system \"/user@host:\"."
8231 (cond ((fboundp 'file-remote-p)
8232 (file-remote-p file))
8233 ((fboundp 'tramp-handle-file-remote-p)
8234 (tramp-handle-file-remote-p file))
8235 ((and (boundp 'ange-ftp-name-format)
8236 (string-match (car ange-ftp-name-format) file))
8238 (t nil)))
8241 ;;;; Refiling
8243 (defun org-get-org-file ()
8244 "Read a filename, with default directory `org-directory'."
8245 (let ((default (or org-default-notes-file remember-data-file)))
8246 (read-file-name (format "File name [%s]: " default)
8247 (file-name-as-directory org-directory)
8248 default)))
8250 (defun org-notes-order-reversed-p ()
8251 "Check if the current file should receive notes in reversed order."
8252 (cond
8253 ((not org-reverse-note-order) nil)
8254 ((eq t org-reverse-note-order) t)
8255 ((not (listp org-reverse-note-order)) nil)
8256 (t (catch 'exit
8257 (let ((all org-reverse-note-order)
8258 entry)
8259 (while (setq entry (pop all))
8260 (if (string-match (car entry) buffer-file-name)
8261 (throw 'exit (cdr entry))))
8262 nil)))))
8264 (defvar org-refile-target-table nil
8265 "The list of refile targets, created by `org-refile'.")
8267 (defvar org-agenda-new-buffers nil
8268 "Buffers created to visit agenda files.")
8270 (defun org-get-refile-targets (&optional default-buffer)
8271 "Produce a table with refile targets."
8272 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8273 targets txt re files f desc descre fast-path-p level pos0)
8274 (message "Getting targets...")
8275 (with-current-buffer (or default-buffer (current-buffer))
8276 (while (setq entry (pop entries))
8277 (setq files (car entry) desc (cdr entry))
8278 (setq fast-path-p nil)
8279 (cond
8280 ((null files) (setq files (list (current-buffer))))
8281 ((eq files 'org-agenda-files)
8282 (setq files (org-agenda-files 'unrestricted)))
8283 ((and (symbolp files) (fboundp files))
8284 (setq files (funcall files)))
8285 ((and (symbolp files) (boundp files))
8286 (setq files (symbol-value files))))
8287 (if (stringp files) (setq files (list files)))
8288 (cond
8289 ((eq (car desc) :tag)
8290 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8291 ((eq (car desc) :todo)
8292 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8293 ((eq (car desc) :regexp)
8294 (setq descre (cdr desc)))
8295 ((eq (car desc) :level)
8296 (setq descre (concat "^\\*\\{" (number-to-string
8297 (if org-odd-levels-only
8298 (1- (* 2 (cdr desc)))
8299 (cdr desc)))
8300 "\\}[ \t]")))
8301 ((eq (car desc) :maxlevel)
8302 (setq fast-path-p t)
8303 (setq descre (concat "^\\*\\{1," (number-to-string
8304 (if org-odd-levels-only
8305 (1- (* 2 (cdr desc)))
8306 (cdr desc)))
8307 "\\}[ \t]")))
8308 (t (error "Bad refiling target description %s" desc)))
8309 (while (setq f (pop files))
8310 (save-excursion
8311 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8312 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8313 (setq f (expand-file-name f))
8314 (if (eq org-refile-use-outline-path 'file)
8315 (push (list (file-name-nondirectory f) f nil nil) targets))
8316 (save-excursion
8317 (save-restriction
8318 (widen)
8319 (goto-char (point-min))
8320 (while (re-search-forward descre nil t)
8321 (goto-char (setq pos0 (point-at-bol)))
8322 (catch 'next
8323 (when org-refile-target-verify-function
8324 (save-match-data
8325 (or (funcall org-refile-target-verify-function)
8326 (throw 'next t))))
8327 (when (looking-at org-complex-heading-regexp)
8328 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8329 txt (org-link-display-format (match-string 4))
8330 re (concat "^" (regexp-quote
8331 (buffer-substring (match-beginning 1)
8332 (match-end 4)))))
8333 (if (match-end 5) (setq re (concat re "[ \t]+"
8334 (regexp-quote
8335 (match-string 5)))))
8336 (setq re (concat re "[ \t]*$"))
8337 (when org-refile-use-outline-path
8338 (setq txt (mapconcat 'org-protect-slash
8339 (append
8340 (if (eq org-refile-use-outline-path 'file)
8341 (list (file-name-nondirectory
8342 (buffer-file-name (buffer-base-buffer))))
8343 (if (eq org-refile-use-outline-path 'full-file-path)
8344 (list (buffer-file-name (buffer-base-buffer)))))
8345 (org-get-outline-path fast-path-p level txt)
8346 (list txt))
8347 "/")))
8348 (push (list txt f re (point)) targets)))
8349 (when (= (point) pos0)
8350 ;; verification function has not moved point
8351 (goto-char (point-at-eol))))))))))
8352 (message "Getting targets...done")
8353 (nreverse targets)))
8355 (defun org-protect-slash (s)
8356 (while (string-match "/" s)
8357 (setq s (replace-match "\\" t t s)))
8360 (defvar org-olpa (make-vector 20 nil))
8362 (defun org-get-outline-path (&optional fastp level heading)
8363 "Return the outline path to the current entry, as a list."
8364 (if fastp
8365 (progn
8366 (if (> level 19)
8367 (error "Outline path failure, more than 19 levels."))
8368 (loop for i from level upto 19 do
8369 (aset org-olpa i nil))
8370 (prog1
8371 (delq nil (append org-olpa nil))
8372 (aset org-olpa level heading)))
8373 (let (rtn)
8374 (save-excursion
8375 (while (org-up-heading-safe)
8376 (when (looking-at org-complex-heading-regexp)
8377 (push (org-match-string-no-properties 4) rtn)))
8378 rtn))))
8380 (defvar org-refile-history nil
8381 "History for refiling operations.")
8383 (defvar org-after-refile-insert-hook nil
8384 "Hook run after `org-refile' has inserted its stuff at the new location.
8385 Note that this is still *before* the stuff will be removed from
8386 the *old* location.")
8388 (defun org-refile (&optional goto default-buffer)
8389 "Move the entry at point to another heading.
8390 The list of target headings is compiled using the information in
8391 `org-refile-targets', which see. This list is created before each use
8392 and will therefore always be up-to-date.
8394 At the target location, the entry is filed as a subitem of the target heading.
8395 Depending on `org-reverse-note-order', the new subitem will either be the
8396 first or the last subitem.
8398 If there is an active region, all entries in that region will be moved.
8399 However, the region must fulfil the requirement that the first heading
8400 is the first one sets the top-level of the moved text - at most siblings
8401 below it are allowed.
8403 With prefix arg GOTO, the command will only visit the target location,
8404 not actually move anything.
8405 With a double prefix `C-u C-u', go to the location where the last refiling
8406 operation has put the subtree.
8408 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8409 (interactive "P")
8410 (let* ((cbuf (current-buffer))
8411 (regionp (org-region-active-p))
8412 (region-start (and regionp (region-beginning)))
8413 (region-end (and regionp (region-end)))
8414 (region-length (and regionp (- region-end region-start)))
8415 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8416 pos it nbuf file re level reversed)
8417 (when regionp (goto-char region-start)
8418 (unless (org-kill-is-subtree-p
8419 (buffer-substring region-start region-end))
8420 (error "The region is not a (sequence of) subtree(s)")))
8421 (if (equal goto '(16))
8422 (org-refile-goto-last-stored)
8423 (when (setq it (org-refile-get-location
8424 (if goto "Goto: " "Refile to: ") default-buffer
8425 org-refile-allow-creating-parent-nodes))
8426 (setq file (nth 1 it)
8427 re (nth 2 it)
8428 pos (nth 3 it))
8429 (if (and (not goto)
8431 (equal (buffer-file-name) file)
8432 (if regionp
8433 (and (>= pos region-start)
8434 (<= pos region-end))
8435 (and (>= pos (point))
8436 (< pos (save-excursion
8437 (org-end-of-subtree t t))))))
8438 (error "Cannot refile to position inside the tree or region"))
8440 (setq nbuf (or (find-buffer-visiting file)
8441 (find-file-noselect file)))
8442 (if goto
8443 (progn
8444 (switch-to-buffer nbuf)
8445 (goto-char pos)
8446 (org-show-context 'org-goto))
8447 (if regionp
8448 (progn
8449 (kill-new (buffer-substring region-start region-end))
8450 (org-save-markers-in-region region-start region-end))
8451 (org-copy-subtree 1 nil t))
8452 (save-excursion
8453 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8454 (find-file-noselect file))))
8455 (setq reversed (org-notes-order-reversed-p))
8456 (save-excursion
8457 (save-restriction
8458 (widen)
8459 (if pos
8460 (progn
8461 (goto-char pos)
8462 (looking-at outline-regexp)
8463 (setq level (org-get-valid-level (funcall outline-level) 1))
8464 (goto-char
8465 (if reversed
8466 (or (outline-next-heading) (point-max))
8467 (or (save-excursion (outline-get-next-sibling))
8468 (org-end-of-subtree t t)
8469 (point-max)))))
8470 (setq level 1)
8471 (if (not reversed)
8472 (goto-char (point-max))
8473 (goto-char (point-min))
8474 (or (outline-next-heading) (goto-char (point-max)))))
8475 (if (not (bolp)) (newline))
8476 (bookmark-set "org-refile-last-stored")
8477 (org-paste-subtree level)
8478 (if (fboundp 'deactivate-mark) (deactivate-mark))
8479 (run-hooks 'org-after-refile-insert-hook))))
8480 (if regionp
8481 (delete-region (point) (+ (point) region-length))
8482 (org-cut-subtree))
8483 (setq org-markers-to-move nil)
8484 (message "Refiled to \"%s\"" (car it))))))
8485 (org-reveal))
8487 (defun org-refile-goto-last-stored ()
8488 "Go to the location where the last refile was stored."
8489 (interactive)
8490 (bookmark-jump "org-refile-last-stored")
8491 (message "This is the location of the last refile"))
8493 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8494 "Prompt the user for a refile location, using PROMPT."
8495 (let ((org-refile-targets org-refile-targets)
8496 (org-refile-use-outline-path org-refile-use-outline-path))
8497 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8498 (unless org-refile-target-table
8499 (error "No refile targets"))
8500 (let* ((cbuf (current-buffer))
8501 (partial-completion-mode nil)
8502 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8503 (cfunc (if (and org-refile-use-outline-path
8504 org-outline-path-complete-in-steps)
8505 'org-olpath-completing-read
8506 'org-ido-completing-read))
8507 (extra (if org-refile-use-outline-path "/" ""))
8508 (filename (and cfn (expand-file-name cfn)))
8509 (tbl (mapcar
8510 (lambda (x)
8511 (if (and (not (member org-refile-use-outline-path
8512 '(file full-file-path)))
8513 (not (equal filename (nth 1 x))))
8514 (cons (concat (car x) extra " ("
8515 (file-name-nondirectory (nth 1 x)) ")")
8516 (cdr x))
8517 (cons (concat (car x) extra) (cdr x))))
8518 org-refile-target-table))
8519 (completion-ignore-case t)
8520 pa answ parent-target child parent)
8521 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8522 nil 'org-refile-history))
8523 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8524 (if pa
8526 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8527 (setq parent (match-string 1 answ)
8528 child (match-string 2 answ))
8529 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8530 (when (and parent-target
8531 (or (eq new-nodes t)
8532 (and (eq new-nodes 'confirm)
8533 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8534 (org-refile-new-child parent-target child))))))
8536 (defun org-refile-new-child (parent-target child)
8537 "Use refile target PARENT-TARGET to add new CHILD below it."
8538 (unless parent-target
8539 (error "Cannot find parent for new node"))
8540 (let ((file (nth 1 parent-target))
8541 (pos (nth 3 parent-target))
8542 level)
8543 (with-current-buffer (or (find-buffer-visiting file)
8544 (find-file-noselect file))
8545 (save-excursion
8546 (save-restriction
8547 (widen)
8548 (if pos
8549 (goto-char pos)
8550 (goto-char (point-max))
8551 (if (not (bolp)) (newline)))
8552 (when (looking-at outline-regexp)
8553 (setq level (funcall outline-level))
8554 (org-end-of-subtree t t))
8555 (org-back-over-empty-lines)
8556 (insert "\n" (make-string
8557 (if pos (org-get-valid-level level 1) 1) ?*)
8558 " " child "\n")
8559 (beginning-of-line 0)
8560 (list (concat (car parent-target) "/" child) file "" (point)))))))
8562 (defun org-olpath-completing-read (prompt collection &rest args)
8563 "Read an outline path like a file name."
8564 (let ((thetable collection)
8565 (org-completion-use-ido nil)) ; does not work with ido.
8566 (apply
8567 'org-ido-completing-read prompt
8568 (lambda (string predicate &optional flag)
8569 (let (rtn r f (l (length string)))
8570 (cond
8571 ((eq flag nil)
8572 ;; try completion
8573 (try-completion string thetable))
8574 ((eq flag t)
8575 ;; all-completions
8576 (setq rtn (all-completions string thetable predicate))
8577 (mapcar
8578 (lambda (x)
8579 (setq r (substring x l))
8580 (if (string-match " ([^)]*)$" x)
8581 (setq f (match-string 0 x))
8582 (setq f ""))
8583 (if (string-match "/" r)
8584 (concat string (substring r 0 (match-end 0)) f)
8586 rtn))
8587 ((eq flag 'lambda)
8588 ;; exact match?
8589 (assoc string thetable)))
8591 args)))
8593 ;;;; Dynamic blocks
8595 (defun org-find-dblock (name)
8596 "Find the first dynamic block with name NAME in the buffer.
8597 If not found, stay at current position and return nil."
8598 (let (pos)
8599 (save-excursion
8600 (goto-char (point-min))
8601 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8602 nil t)
8603 (match-beginning 0))))
8604 (if pos (goto-char pos))
8605 pos))
8607 (defconst org-dblock-start-re
8608 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8609 "Matches the startline of a dynamic block, with parameters.")
8611 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8612 "Matches the end of a dynamic block.")
8614 (defun org-create-dblock (plist)
8615 "Create a dynamic block section, with parameters taken from PLIST.
8616 PLIST must contain a :name entry which is used as name of the block."
8617 (unless (bolp) (newline))
8618 (let ((name (plist-get plist :name)))
8619 (insert "#+BEGIN: " name)
8620 (while plist
8621 (if (eq (car plist) :name)
8622 (setq plist (cddr plist))
8623 (insert " " (prin1-to-string (pop plist)))))
8624 (insert "\n\n#+END:\n")
8625 (beginning-of-line -2)))
8627 (defun org-prepare-dblock ()
8628 "Prepare dynamic block for refresh.
8629 This empties the block, puts the cursor at the insert position and returns
8630 the property list including an extra property :name with the block name."
8631 (unless (looking-at org-dblock-start-re)
8632 (error "Not at a dynamic block"))
8633 (let* ((begdel (1+ (match-end 0)))
8634 (name (org-no-properties (match-string 1)))
8635 (params (append (list :name name)
8636 (read (concat "(" (match-string 3) ")")))))
8637 (unless (re-search-forward org-dblock-end-re nil t)
8638 (error "Dynamic block not terminated"))
8639 (setq params
8640 (append params
8641 (list :content (buffer-substring
8642 begdel (match-beginning 0)))))
8643 (delete-region begdel (match-beginning 0))
8644 (goto-char begdel)
8645 (open-line 1)
8646 params))
8648 (defun org-map-dblocks (&optional command)
8649 "Apply COMMAND to all dynamic blocks in the current buffer.
8650 If COMMAND is not given, use `org-update-dblock'."
8651 (let ((cmd (or command 'org-update-dblock))
8652 pos)
8653 (save-excursion
8654 (goto-char (point-min))
8655 (while (re-search-forward org-dblock-start-re nil t)
8656 (goto-char (setq pos (match-beginning 0)))
8657 (condition-case nil
8658 (funcall cmd)
8659 (error (message "Error during update of dynamic block")))
8660 (goto-char pos)
8661 (unless (re-search-forward org-dblock-end-re nil t)
8662 (error "Dynamic block not terminated"))))))
8664 (defun org-dblock-update (&optional arg)
8665 "User command for updating dynamic blocks.
8666 Update the dynamic block at point. With prefix ARG, update all dynamic
8667 blocks in the buffer."
8668 (interactive "P")
8669 (if arg
8670 (org-update-all-dblocks)
8671 (or (looking-at org-dblock-start-re)
8672 (org-beginning-of-dblock))
8673 (org-update-dblock)))
8675 (defun org-update-dblock ()
8676 "Update the dynamic block at point
8677 This means to empty the block, parse for parameters and then call
8678 the correct writing function."
8679 (save-window-excursion
8680 (let* ((pos (point))
8681 (line (org-current-line))
8682 (params (org-prepare-dblock))
8683 (name (plist-get params :name))
8684 (cmd (intern (concat "org-dblock-write:" name))))
8685 (message "Updating dynamic block `%s' at line %d..." name line)
8686 (funcall cmd params)
8687 (message "Updating dynamic block `%s' at line %d...done" name line)
8688 (goto-char pos))))
8690 (defun org-beginning-of-dblock ()
8691 "Find the beginning of the dynamic block at point.
8692 Error if there is no such block at point."
8693 (let ((pos (point))
8694 beg)
8695 (end-of-line 1)
8696 (if (and (re-search-backward org-dblock-start-re nil t)
8697 (setq beg (match-beginning 0))
8698 (re-search-forward org-dblock-end-re nil t)
8699 (> (match-end 0) pos))
8700 (goto-char beg)
8701 (goto-char pos)
8702 (error "Not in a dynamic block"))))
8704 (defun org-update-all-dblocks ()
8705 "Update all dynamic blocks in the buffer.
8706 This function can be used in a hook."
8707 (when (org-mode-p)
8708 (org-map-dblocks 'org-update-dblock)))
8711 ;;;; Completion
8713 (defconst org-additional-option-like-keywords
8714 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8715 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8716 "LATEX_HEADER:"
8717 "BEGIN_EXAMPLE" "END_EXAMPLE"
8718 "BEGIN_QUOTE" "END_QUOTE"
8719 "BEGIN_VERSE" "END_VERSE"
8720 "BEGIN_CENTER" "END_CENTER"
8721 "BEGIN_SRC" "END_SRC"
8722 "CATEGORY" "COLUMNS"
8723 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8725 (defcustom org-structure-template-alist
8727 ("s" "#+begin_src ?\n\n#+end_src"
8728 "<src lang=\"?\">\n\n</src>")
8729 ("e" "#+begin_example\n?\n#+end_example"
8730 "<example>\n?\n</example>")
8731 ("q" "#+begin_quote\n?\n#+end_quote"
8732 "<quote>\n?\n</quote>")
8733 ("v" "#+begin_verse\n?\n#+end_verse"
8734 "<verse>\n?\n/verse>")
8735 ("c" "#+begin_center\n?\n#+end_center"
8736 "<center>\n?\n/center>")
8737 ("l" "#+begin_latex\n?\n#+end_latex"
8738 "<literal style=\"latex\">\n?\n</literal>")
8739 ("L" "#+latex: "
8740 "<literal style=\"latex\">?</literal>")
8741 ("h" "#+begin_html\n?\n#+end_html"
8742 "<literal style=\"html\">\n?\n</literal>")
8743 ("H" "#+html: "
8744 "<literal style=\"html\">?</literal>")
8745 ("a" "#+begin_ascii\n?\n#+end_ascii")
8746 ("A" "#+ascii: ")
8747 ("i" "#+include %file ?"
8748 "<include file=%file markup=\"?\">")
8750 "Structure completion elements.
8751 This is a list of abbreviation keys and values. The value gets inserted
8752 it you type @samp{.} followed by the key and then the completion key,
8753 usually `M-TAB'. %file will be replaced by a file name after prompting
8754 for the file using completion.
8755 There are two templates for each key, the first uses the original Org syntax,
8756 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8757 the default when the /org-mtags.el/ module has been loaded. See also the
8758 variable `org-mtags-prefer-muse-templates'.
8759 This is an experimental feature, it is undecided if it is going to stay in."
8760 :group 'org-completion
8761 :type '(repeat
8762 (string :tag "Key")
8763 (string :tag "Template")
8764 (string :tag "Muse Template")))
8766 (defun org-try-structure-completion ()
8767 "Try to complete a structure template before point.
8768 This looks for strings like \"<e\" on an otherwise empty line and
8769 expands them."
8770 (let ((l (buffer-substring (point-at-bol) (point)))
8772 (when (and (looking-at "[ \t]*$")
8773 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8774 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8775 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8776 (match-beginning 1)) a)
8777 t)))
8779 (defun org-complete-expand-structure-template (start cell)
8780 "Expand a structure template."
8781 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8782 (rpl (nth (if musep 2 1) cell))
8783 (ind ""))
8784 (delete-region start (point))
8785 (when (string-match "\\`#\\+" rpl)
8786 (cond
8787 ((bolp))
8788 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8789 (setq ind (buffer-substring (point-at-bol) (point))))
8790 (t (newline))))
8791 (setq start (point))
8792 (if (string-match "%file" rpl)
8793 (setq rpl (replace-match
8794 (concat
8795 "\""
8796 (save-match-data
8797 (abbreviate-file-name (read-file-name "Include file: ")))
8798 "\"")
8799 t t rpl)))
8800 (setq rpl (mapconcat 'identity (split-string rpl "\n")
8801 (concat "\n" ind)))
8802 (insert rpl)
8803 (if (re-search-backward "\\?" start t) (delete-char 1))))
8806 (defun org-complete (&optional arg)
8807 "Perform completion on word at point.
8808 At the beginning of a headline, this completes TODO keywords as given in
8809 `org-todo-keywords'.
8810 If the current word is preceded by a backslash, completes the TeX symbols
8811 that are supported for HTML support.
8812 If the current word is preceded by \"#+\", completes special words for
8813 setting file options.
8814 In the line after \"#+STARTUP:, complete valid keywords.\"
8815 At all other locations, this simply calls the value of
8816 `org-completion-fallback-command'."
8817 (interactive "P")
8818 (org-without-partial-completion
8819 (catch 'exit
8820 (let* ((a nil)
8821 (end (point))
8822 (beg1 (save-excursion
8823 (skip-chars-backward (org-re "[:alnum:]_@"))
8824 (point)))
8825 (beg (save-excursion
8826 (skip-chars-backward "a-zA-Z0-9_:$")
8827 (point)))
8828 (confirm (lambda (x) (stringp (car x))))
8829 (searchhead (equal (char-before beg) ?*))
8830 (struct
8831 (when (and (member (char-before beg1) '(?. ?<))
8832 (setq a (assoc (buffer-substring beg1 (point))
8833 org-structure-template-alist)))
8834 (org-complete-expand-structure-template (1- beg1) a)
8835 (throw 'exit t)))
8836 (tag (and (equal (char-before beg1) ?:)
8837 (equal (char-after (point-at-bol)) ?*)))
8838 (prop (and (equal (char-before beg1) ?:)
8839 (not (equal (char-after (point-at-bol)) ?*))))
8840 (texp (equal (char-before beg) ?\\))
8841 (link (equal (char-before beg) ?\[))
8842 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8843 beg)
8844 "#+"))
8845 (startup (string-match "^#\\+STARTUP:.*"
8846 (buffer-substring (point-at-bol) (point))))
8847 (completion-ignore-case opt)
8848 (type nil)
8849 (tbl nil)
8850 (table (cond
8851 (opt
8852 (setq type :opt)
8853 (require 'org-exp)
8854 (append
8855 (mapcar
8856 (lambda (x)
8857 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8858 (cons (match-string 2 x) (match-string 1 x)))
8859 (org-split-string (org-get-current-options) "\n"))
8860 (mapcar 'list org-additional-option-like-keywords)))
8861 (startup
8862 (setq type :startup)
8863 org-startup-options)
8864 (link (append org-link-abbrev-alist-local
8865 org-link-abbrev-alist))
8866 (texp
8867 (setq type :tex)
8868 org-html-entities)
8869 ((string-match "\\`\\*+[ \t]+\\'"
8870 (buffer-substring (point-at-bol) beg))
8871 (setq type :todo)
8872 (mapcar 'list org-todo-keywords-1))
8873 (searchhead
8874 (setq type :searchhead)
8875 (save-excursion
8876 (goto-char (point-min))
8877 (while (re-search-forward org-todo-line-regexp nil t)
8878 (push (list
8879 (org-make-org-heading-search-string
8880 (match-string 3) t))
8881 tbl)))
8882 tbl)
8883 (tag (setq type :tag beg beg1)
8884 (or org-tag-alist (org-get-buffer-tags)))
8885 (prop (setq type :prop beg beg1)
8886 (mapcar 'list (org-buffer-property-keys nil t t)))
8887 (t (progn
8888 (call-interactively org-completion-fallback-command)
8889 (throw 'exit nil)))))
8890 (pattern (buffer-substring-no-properties beg end))
8891 (completion (try-completion pattern table confirm)))
8892 (cond ((eq completion t)
8893 (if (not (assoc (upcase pattern) table))
8894 (message "Already complete")
8895 (if (and (equal type :opt)
8896 (not (member (car (assoc (upcase pattern) table))
8897 org-additional-option-like-keywords)))
8898 (insert (substring (cdr (assoc (upcase pattern) table))
8899 (length pattern)))
8900 (if (memq type '(:tag :prop)) (insert ":")))))
8901 ((null completion)
8902 (message "Can't find completion for \"%s\"" pattern)
8903 (ding))
8904 ((not (string= pattern completion))
8905 (delete-region beg end)
8906 (if (string-match " +$" completion)
8907 (setq completion (replace-match "" t t completion)))
8908 (insert completion)
8909 (if (get-buffer-window "*Completions*")
8910 (delete-window (get-buffer-window "*Completions*")))
8911 (if (assoc completion table)
8912 (if (eq type :todo) (insert " ")
8913 (if (memq type '(:tag :prop)) (insert ":"))))
8914 (if (and (equal type :opt) (assoc completion table))
8915 (message "%s" (substitute-command-keys
8916 "Press \\[org-complete] again to insert example settings"))))
8918 (message "Making completion list...")
8919 (let ((list (sort (all-completions pattern table confirm)
8920 'string<)))
8921 (with-output-to-temp-buffer "*Completions*"
8922 (condition-case nil
8923 ;; Protection needed for XEmacs and emacs 21
8924 (display-completion-list list pattern)
8925 (error (display-completion-list list)))))
8926 (message "Making completion list...%s" "done")))))))
8928 ;;;; TODO, DEADLINE, Comments
8930 (defun org-toggle-comment ()
8931 "Change the COMMENT state of an entry."
8932 (interactive)
8933 (save-excursion
8934 (org-back-to-heading)
8935 (let (case-fold-search)
8936 (if (looking-at (concat outline-regexp
8937 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8938 (replace-match "" t t nil 1)
8939 (if (looking-at outline-regexp)
8940 (progn
8941 (goto-char (match-end 0))
8942 (insert org-comment-string " ")))))))
8944 (defvar org-last-todo-state-is-todo nil
8945 "This is non-nil when the last TODO state change led to a TODO state.
8946 If the last change removed the TODO tag or switched to DONE, then
8947 this is nil.")
8949 (defvar org-setting-tags nil) ; dynamically skipped
8951 (defun org-parse-local-options (string var)
8952 "Parse STRING for startup setting relevant for variable VAR."
8953 (let ((rtn (symbol-value var))
8954 e opts)
8955 (save-match-data
8956 (if (or (not string) (not (string-match "\\S-" string)))
8958 (setq opts (delq nil (mapcar (lambda (x)
8959 (setq e (assoc x org-startup-options))
8960 (if (eq (nth 1 e) var) e nil))
8961 (org-split-string string "[ \t]+"))))
8962 (if (not opts)
8964 (setq rtn nil)
8965 (while (setq e (pop opts))
8966 (if (not (nth 3 e))
8967 (setq rtn (nth 2 e))
8968 (if (not (listp rtn)) (setq rtn nil))
8969 (push (nth 2 e) rtn)))
8970 rtn)))))
8972 (defvar org-todo-setup-filter-hook nil
8973 "Hook for functions that pre-filter todo specs.
8975 Each function takes a todo spec and returns either `nil' or the spec
8976 transformed into canonical form." )
8978 (defvar org-todo-get-default-hook nil
8979 "Hook for functions that get a default item for todo.
8981 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8982 `nil' or a string to be used for the todo mark." )
8984 (defvar org-agenda-headline-snapshot-before-repeat)
8986 (defun org-todo (&optional arg)
8987 "Change the TODO state of an item.
8988 The state of an item is given by a keyword at the start of the heading,
8989 like
8990 *** TODO Write paper
8991 *** DONE Call mom
8993 The different keywords are specified in the variable `org-todo-keywords'.
8994 By default the available states are \"TODO\" and \"DONE\".
8995 So for this example: when the item starts with TODO, it is changed to DONE.
8996 When it starts with DONE, the DONE is removed. And when neither TODO nor
8997 DONE are present, add TODO at the beginning of the heading.
8999 With C-u prefix arg, use completion to determine the new state.
9000 With numeric prefix arg, switch to that state.
9001 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9002 With a tripple C-u prefix, circumvent any state blocking.
9004 For calling through lisp, arg is also interpreted in the following way:
9005 'none -> empty state
9006 \"\"(empty string) -> switch to empty state
9007 'done -> switch to DONE
9008 'nextset -> switch to the next set of keywords
9009 'previousset -> switch to the previous set of keywords
9010 \"WAITING\" -> switch to the specified keyword, but only if it
9011 really is a member of `org-todo-keywords'."
9012 (interactive "P")
9013 (if (equal arg '(16)) (setq arg 'nextset))
9014 (let ((org-blocker-hook org-blocker-hook)
9015 (case-fold-search nil))
9016 (when (equal arg '(64))
9017 (setq arg nil org-blocker-hook nil))
9018 (when (and org-blocker-hook
9019 (or org-inhibit-blocking
9020 (org-entry-get nil "NOBLOCKING")))
9021 (setq org-blocker-hook nil))
9022 (save-excursion
9023 (catch 'exit
9024 (org-back-to-heading)
9025 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9026 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9027 (looking-at " *"))
9028 (let* ((match-data (match-data))
9029 (startpos (point-at-bol))
9030 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9031 (org-log-done org-log-done)
9032 (org-log-repeat org-log-repeat)
9033 (org-todo-log-states org-todo-log-states)
9034 (this (match-string 1))
9035 (hl-pos (match-beginning 0))
9036 (head (org-get-todo-sequence-head this))
9037 (ass (assoc head org-todo-kwd-alist))
9038 (interpret (nth 1 ass))
9039 (done-word (nth 3 ass))
9040 (final-done-word (nth 4 ass))
9041 (last-state (or this ""))
9042 (completion-ignore-case t)
9043 (member (member this org-todo-keywords-1))
9044 (tail (cdr member))
9045 (state (cond
9046 ((and org-todo-key-trigger
9047 (or (and (equal arg '(4))
9048 (eq org-use-fast-todo-selection 'prefix))
9049 (and (not arg) org-use-fast-todo-selection
9050 (not (eq org-use-fast-todo-selection
9051 'prefix)))))
9052 ;; Use fast selection
9053 (org-fast-todo-selection))
9054 ((and (equal arg '(4))
9055 (or (not org-use-fast-todo-selection)
9056 (not org-todo-key-trigger)))
9057 ;; Read a state with completion
9058 (org-ido-completing-read
9059 "State: " (mapcar (lambda(x) (list x))
9060 org-todo-keywords-1)
9061 nil t))
9062 ((eq arg 'right)
9063 (if this
9064 (if tail (car tail) nil)
9065 (car org-todo-keywords-1)))
9066 ((eq arg 'left)
9067 (if (equal member org-todo-keywords-1)
9069 (if this
9070 (nth (- (length org-todo-keywords-1)
9071 (length tail) 2)
9072 org-todo-keywords-1)
9073 (org-last org-todo-keywords-1))))
9074 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9075 (setq arg nil))) ; hack to fall back to cycling
9076 (arg
9077 ;; user or caller requests a specific state
9078 (cond
9079 ((equal arg "") nil)
9080 ((eq arg 'none) nil)
9081 ((eq arg 'done) (or done-word (car org-done-keywords)))
9082 ((eq arg 'nextset)
9083 (or (car (cdr (member head org-todo-heads)))
9084 (car org-todo-heads)))
9085 ((eq arg 'previousset)
9086 (let ((org-todo-heads (reverse org-todo-heads)))
9087 (or (car (cdr (member head org-todo-heads)))
9088 (car org-todo-heads))))
9089 ((car (member arg org-todo-keywords-1)))
9090 ((nth (1- (prefix-numeric-value arg))
9091 org-todo-keywords-1))))
9092 ((null member) (or head (car org-todo-keywords-1)))
9093 ((equal this final-done-word) nil) ;; -> make empty
9094 ((null tail) nil) ;; -> first entry
9095 ((memq interpret '(type priority))
9096 (if (eq this-command last-command)
9097 (car tail)
9098 (if (> (length tail) 0)
9099 (or done-word (car org-done-keywords))
9100 nil)))
9102 (car tail))))
9103 (state (or
9104 (run-hook-with-args-until-success
9105 'org-todo-get-default-hook state last-state)
9106 state))
9107 (next (if state (concat " " state " ") " "))
9108 (change-plist (list :type 'todo-state-change :from this :to state
9109 :position startpos))
9110 dolog now-done-p)
9111 (when org-blocker-hook
9112 (setq org-last-todo-state-is-todo
9113 (not (member this org-done-keywords)))
9114 (unless (save-excursion
9115 (save-match-data
9116 (run-hook-with-args-until-failure
9117 'org-blocker-hook change-plist)))
9118 (if (interactive-p)
9119 (error "TODO state change from %s to %s blocked" this state)
9120 ;; fail silently
9121 (message "TODO state change from %s to %s blocked" this state)
9122 (throw 'exit nil))))
9123 (store-match-data match-data)
9124 (replace-match next t t)
9125 (unless (pos-visible-in-window-p hl-pos)
9126 (message "TODO state changed to %s" (org-trim next)))
9127 (unless head
9128 (setq head (org-get-todo-sequence-head state)
9129 ass (assoc head org-todo-kwd-alist)
9130 interpret (nth 1 ass)
9131 done-word (nth 3 ass)
9132 final-done-word (nth 4 ass)))
9133 (when (memq arg '(nextset previousset))
9134 (message "Keyword-Set %d/%d: %s"
9135 (- (length org-todo-sets) -1
9136 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9137 (length org-todo-sets)
9138 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9139 (setq org-last-todo-state-is-todo
9140 (not (member state org-done-keywords)))
9141 (setq now-done-p (and (member state org-done-keywords)
9142 (not (member this org-done-keywords))))
9143 (and logging (org-local-logging logging))
9144 (when (and (or org-todo-log-states org-log-done)
9145 (not org-inhibit-logging)
9146 (not (memq arg '(nextset previousset))))
9147 ;; we need to look at recording a time and note
9148 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9149 (nth 2 (assoc this org-todo-log-states))))
9150 (when (and state
9151 (member state org-not-done-keywords)
9152 (not (member this org-not-done-keywords)))
9153 ;; This is now a todo state and was not one before
9154 ;; If there was a CLOSED time stamp, get rid of it.
9155 (org-add-planning-info nil nil 'closed))
9156 (when (and now-done-p org-log-done)
9157 ;; It is now done, and it was not done before
9158 (org-add-planning-info 'closed (org-current-time))
9159 (if (and (not dolog) (eq 'note org-log-done))
9160 (org-add-log-setup 'done state this 'findpos 'note)))
9161 (when (and state dolog)
9162 ;; This is a non-nil state, and we need to log it
9163 (org-add-log-setup 'state state this 'findpos dolog)))
9164 ;; Fixup tag positioning
9165 (org-todo-trigger-tag-changes state)
9166 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9167 (when org-provide-todo-statistics
9168 (org-update-parent-todo-statistics))
9169 (run-hooks 'org-after-todo-state-change-hook)
9170 (if (and arg (not (member state org-done-keywords)))
9171 (setq head (org-get-todo-sequence-head state)))
9172 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9173 ;; Do we need to trigger a repeat?
9174 (when now-done-p
9175 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9176 ;; This is for the agenda, take a snapshot of the headline.
9177 (save-match-data
9178 (setq org-agenda-headline-snapshot-before-repeat
9179 (org-get-heading))))
9180 (org-auto-repeat-maybe state))
9181 ;; Fixup cursor location if close to the keyword
9182 (if (and (outline-on-heading-p)
9183 (not (bolp))
9184 (save-excursion (beginning-of-line 1)
9185 (looking-at org-todo-line-regexp))
9186 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9187 (progn
9188 (goto-char (or (match-end 2) (match-end 1)))
9189 (and (looking-at " ") (just-one-space))))
9190 (when org-trigger-hook
9191 (save-excursion
9192 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9194 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9195 "Block turning an entry into a TODO, using the hierarchy.
9196 This checks whether the current task should be blocked from state
9197 changes. Such blocking occurs when:
9199 1. The task has children which are not all in a completed state.
9201 2. A task has a parent with the property :ORDERED:, and there
9202 are siblings prior to the current task with incomplete
9203 status.
9205 3. The parent of the task is blocked because it has siblings that should
9206 be done first, or is child of a block grandparent TODO entry."
9208 (catch 'dont-block
9209 ;; If this is not a todo state change, or if this entry is already DONE,
9210 ;; do not block
9211 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9212 (member (plist-get change-plist :from)
9213 (cons 'done org-done-keywords))
9214 (member (plist-get change-plist :to)
9215 (cons 'todo org-not-done-keywords)))
9216 (throw 'dont-block t))
9217 ;; If this task has children, and any are undone, it's blocked
9218 (save-excursion
9219 (org-back-to-heading t)
9220 (let ((this-level (funcall outline-level)))
9221 (outline-next-heading)
9222 (let ((child-level (funcall outline-level)))
9223 (while (and (not (eobp))
9224 (> child-level this-level))
9225 ;; this todo has children, check whether they are all
9226 ;; completed
9227 (if (and (not (org-entry-is-done-p))
9228 (org-entry-is-todo-p))
9229 (throw 'dont-block nil))
9230 (outline-next-heading)
9231 (setq child-level (funcall outline-level))))))
9232 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9233 ;; any previous siblings are undone, it's blocked
9234 (save-excursion
9235 (org-back-to-heading t)
9236 (let* ((pos (point))
9237 (parent-pos (and (org-up-heading-safe) (point))))
9238 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9239 (when (and (org-entry-get (point) "ORDERED")
9240 (forward-line 1)
9241 (re-search-forward org-not-done-heading-regexp pos t))
9242 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9243 ;; Search further up the hierarchy, to see if an anchestor is blocked
9244 (while t
9245 (goto-char parent-pos)
9246 (if (not (looking-at org-not-done-heading-regexp))
9247 (throw 'dont-block t)) ; do not block, parent is not a TODO
9248 (setq pos (point))
9249 (setq parent-pos (and (org-up-heading-safe) (point)))
9250 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9251 (when (and (org-entry-get (point) "ORDERED")
9252 (forward-line 1)
9253 (re-search-forward org-not-done-heading-regexp pos t))
9254 (throw 'dont-block nil))))))) ; block, older sibling not done.
9256 (defcustom org-track-ordered-property-with-tag nil
9257 "Should the ORDERED property also be shown as a tag?
9258 The ORDERED property decides if an entry should require subtasks to be
9259 completed in sequence. Since a property is not very visible, setting
9260 this option means that toggling the ORDERED property with the command
9261 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9262 not relevant for the behavior, but it makes things more visible.
9264 Note that toggling the tag with tags commands will not change the property
9265 and therefore not influence behavior!
9267 This can be t, meaning the tag ORDERED should be used, It can also be a
9268 string to select a different tag for this task."
9269 :group 'org-todo
9270 :type '(choice
9271 (const :tag "No tracking" nil)
9272 (const :tag "Track with ORDERED tag" t)
9273 (string :tag "Use other tag")))
9275 (defun org-toggle-ordered-property ()
9276 "Toggle the ORDERED property of the current entry.
9277 For better visibility, you can track the value of this property with a tag.
9278 See variable `org-track-ordered-property-with-tag'."
9279 (interactive)
9280 (let* ((t1 org-track-ordered-property-with-tag)
9281 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9282 (save-excursion
9283 (org-back-to-heading)
9284 (if (org-entry-get nil "ORDERED")
9285 (progn
9286 (org-delete-property "ORDERED")
9287 (and tag (org-toggle-tag tag 'off))
9288 (message "Subtasks can be completed in arbitrary order"))
9289 (org-entry-put nil "ORDERED" "t")
9290 (and tag (org-toggle-tag tag 'on))
9291 (message "Subtasks must be completed in sequence")))))
9293 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9294 (defun org-block-todo-from-checkboxes (change-plist)
9295 "Block turning an entry into a TODO, using checkboxes.
9296 This checks whether the current task should be blocked from state
9297 changes because there are uncheckd boxes in this entry."
9298 (catch 'dont-block
9299 ;; If this is not a todo state change, or if this entry is already DONE,
9300 ;; do not block
9301 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9302 (member (plist-get change-plist :from)
9303 (cons 'done org-done-keywords))
9304 (member (plist-get change-plist :to)
9305 (cons 'todo org-not-done-keywords)))
9306 (throw 'dont-block t))
9307 ;; If this task has checkboxes that are not checked, it's blocked
9308 (save-excursion
9309 (org-back-to-heading t)
9310 (let ((beg (point)) end)
9311 (outline-next-heading)
9312 (setq end (point))
9313 (goto-char beg)
9314 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9315 end t)
9316 (progn
9317 (if (boundp 'org-blocked-by-checkboxes)
9318 (setq org-blocked-by-checkboxes t))
9319 (throw 'dont-block nil)))))
9320 t)) ; do not block
9322 (defvar org-entry-property-inherited-from) ;; defined below
9323 (defun org-update-parent-todo-statistics ()
9324 "Update any statistics cookie in the parent of the current headline.
9325 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9326 the entire subtree and this will travel up the hierarchy and update
9327 statistics everywhere."
9328 (interactive)
9329 (let* ((lim 0) prop
9330 (recursive (or (not org-hierarchical-todo-statistics)
9331 (string-match
9332 "\\<recursive\\>"
9333 (or (setq prop (org-entry-get
9334 nil "COOKIE_DATA" 'inherit)) ""))))
9335 (lim (or (and prop (marker-position
9336 org-entry-property-inherited-from))
9337 lim))
9338 (first t)
9339 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9340 level ltoggle l1
9341 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9342 (catch 'exit
9343 (save-excursion
9344 (beginning-of-line 1)
9345 (if (org-at-heading-p)
9346 (setq ltoggle (funcall outline-level))
9347 (error "This should not happen"))
9348 (while (and (setq level (org-up-heading-safe))
9349 (or recursive first)
9350 (>= (point) lim))
9351 (setq first nil)
9352 (unless (and level
9353 (not (string-match
9354 "\\<checkbox\\>"
9355 (downcase
9356 (or (org-entry-get
9357 nil "COOKIE_DATA")
9358 "")))))
9359 (throw 'exit nil))
9360 (while (re-search-forward box-re (point-at-eol) t)
9361 (setq cnt-all 0 cnt-done 0 cookie-present t)
9362 (setq is-percent (match-end 2))
9363 (save-match-data
9364 (unless (outline-next-heading) (throw 'exit nil))
9365 (while (and (looking-at org-complex-heading-regexp)
9366 (> (setq l1 (length (match-string 1))) level))
9367 (setq kwd (and (or recursive (= l1 ltoggle))
9368 (match-string 2)))
9369 (and kwd (setq cnt-all (1+ cnt-all)))
9370 (and (member kwd org-done-keywords)
9371 (setq cnt-done (1+ cnt-done)))
9372 (outline-next-heading)))
9373 (replace-match
9374 (if is-percent
9375 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9376 (format "[%d/%d]" cnt-done cnt-all)))))
9377 (when cookie-present
9378 (run-hook-with-args 'org-after-todo-statistics-hook
9379 cnt-done (- cnt-all cnt-done)))))
9380 (run-hooks 'org-todo-statistics-hook)))
9382 (defvar org-after-todo-statistics-hook nil
9383 "Hook that is called after a TODO statistics cookie has been updated.
9384 Each function is called with two arguments: the number of not-done entries
9385 and the number of done entries.
9387 For example, the following function, when added to this hook, will switch
9388 an entry to DONE when all children are done, and back to TODO when new
9389 entries are set to a TODO status. Note that this hook is only called
9390 when there is a statistics cookie in the headline!
9392 (defun org-summary-todo (n-done n-not-done)
9393 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9394 (let (org-log-done org-log-states) ; turn off logging
9395 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9398 (defvar org-todo-statistics-hook nil
9399 "Hook that is run whenever Org thinks TODO statistics should be updated.
9400 This hook runs even if there is no statisics cookie present, in which case
9401 `org-after-todo-statistics-hook' would not run.")
9403 (defun org-todo-trigger-tag-changes (state)
9404 "Apply the changes defined in `org-todo-state-tags-triggers'."
9405 (let ((l org-todo-state-tags-triggers)
9406 changes)
9407 (when (or (not state) (equal state ""))
9408 (setq changes (append changes (cdr (assoc "" l)))))
9409 (when (and (stringp state) (> (length state) 0))
9410 (setq changes (append changes (cdr (assoc state l)))))
9411 (when (member state org-not-done-keywords)
9412 (setq changes (append changes (cdr (assoc 'todo l)))))
9413 (when (member state org-done-keywords)
9414 (setq changes (append changes (cdr (assoc 'done l)))))
9415 (dolist (c changes)
9416 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9418 (defun org-local-logging (value)
9419 "Get logging settings from a property VALUE."
9420 (let* (words w a)
9421 ;; directly set the variables, they are already local.
9422 (setq org-log-done nil
9423 org-log-repeat nil
9424 org-todo-log-states nil)
9425 (setq words (org-split-string value))
9426 (while (setq w (pop words))
9427 (cond
9428 ((setq a (assoc w org-startup-options))
9429 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9430 (set (nth 1 a) (nth 2 a))))
9431 ((setq a (org-extract-log-state-settings w))
9432 (and (member (car a) org-todo-keywords-1)
9433 (push a org-todo-log-states)))))))
9435 (defun org-get-todo-sequence-head (kwd)
9436 "Return the head of the TODO sequence to which KWD belongs.
9437 If KWD is not set, check if there is a text property remembering the
9438 right sequence."
9439 (let (p)
9440 (cond
9441 ((not kwd)
9442 (or (get-text-property (point-at-bol) 'org-todo-head)
9443 (progn
9444 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9445 nil (point-at-eol)))
9446 (get-text-property p 'org-todo-head))))
9447 ((not (member kwd org-todo-keywords-1))
9448 (car org-todo-keywords-1))
9449 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9451 (defun org-fast-todo-selection ()
9452 "Fast TODO keyword selection with single keys.
9453 Returns the new TODO keyword, or nil if no state change should occur."
9454 (let* ((fulltable org-todo-key-alist)
9455 (done-keywords org-done-keywords) ;; needed for the faces.
9456 (maxlen (apply 'max (mapcar
9457 (lambda (x)
9458 (if (stringp (car x)) (string-width (car x)) 0))
9459 fulltable)))
9460 (expert nil)
9461 (fwidth (+ maxlen 3 1 3))
9462 (ncol (/ (- (window-width) 4) fwidth))
9463 tg cnt e c tbl
9464 groups ingroup)
9465 (save-excursion
9466 (save-window-excursion
9467 (if expert
9468 (set-buffer (get-buffer-create " *Org todo*"))
9469 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9470 (erase-buffer)
9471 (org-set-local 'org-done-keywords done-keywords)
9472 (setq tbl fulltable cnt 0)
9473 (while (setq e (pop tbl))
9474 (cond
9475 ((equal e '(:startgroup))
9476 (push '() groups) (setq ingroup t)
9477 (when (not (= cnt 0))
9478 (setq cnt 0)
9479 (insert "\n"))
9480 (insert "{ "))
9481 ((equal e '(:endgroup))
9482 (setq ingroup nil cnt 0)
9483 (insert "}\n"))
9484 ((equal e '(:newline))
9485 (when (not (= cnt 0))
9486 (setq cnt 0)
9487 (insert "\n")
9488 (setq e (car tbl))
9489 (while (equal (car tbl) '(:newline))
9490 (insert "\n")
9491 (setq tbl (cdr tbl)))))
9493 (setq tg (car e) c (cdr e))
9494 (if ingroup (push tg (car groups)))
9495 (setq tg (org-add-props tg nil 'face
9496 (org-get-todo-face tg)))
9497 (if (and (= cnt 0) (not ingroup)) (insert " "))
9498 (insert "[" c "] " tg (make-string
9499 (- fwidth 4 (length tg)) ?\ ))
9500 (when (= (setq cnt (1+ cnt)) ncol)
9501 (insert "\n")
9502 (if ingroup (insert " "))
9503 (setq cnt 0)))))
9504 (insert "\n")
9505 (goto-char (point-min))
9506 (if (not expert) (org-fit-window-to-buffer))
9507 (message "[a-z..]:Set [SPC]:clear")
9508 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9509 (cond
9510 ((or (= c ?\C-g)
9511 (and (= c ?q) (not (rassoc c fulltable))))
9512 (setq quit-flag t))
9513 ((= c ?\ ) nil)
9514 ((setq e (rassoc c fulltable) tg (car e))
9516 (t (setq quit-flag t)))))))
9518 (defun org-entry-is-todo-p ()
9519 (member (org-get-todo-state) org-not-done-keywords))
9521 (defun org-entry-is-done-p ()
9522 (member (org-get-todo-state) org-done-keywords))
9524 (defun org-get-todo-state ()
9525 (save-excursion
9526 (org-back-to-heading t)
9527 (and (looking-at org-todo-line-regexp)
9528 (match-end 2)
9529 (match-string 2))))
9531 (defun org-at-date-range-p (&optional inactive-ok)
9532 "Is the cursor inside a date range?"
9533 (interactive)
9534 (save-excursion
9535 (catch 'exit
9536 (let ((pos (point)))
9537 (skip-chars-backward "^[<\r\n")
9538 (skip-chars-backward "<[")
9539 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9540 (>= (match-end 0) pos)
9541 (throw 'exit t))
9542 (skip-chars-backward "^<[\r\n")
9543 (skip-chars-backward "<[")
9544 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9545 (>= (match-end 0) pos)
9546 (throw 'exit t)))
9547 nil)))
9549 (defun org-get-repeat ()
9550 "Check if there is a deadline/schedule with repeater in this entry."
9551 (save-match-data
9552 (save-excursion
9553 (org-back-to-heading t)
9554 (if (re-search-forward
9555 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9556 (match-string 1)))))
9558 (defvar org-last-changed-timestamp)
9559 (defvar org-last-inserted-timestamp)
9560 (defvar org-log-post-message)
9561 (defvar org-log-note-purpose)
9562 (defvar org-log-note-how)
9563 (defvar org-log-note-extra)
9564 (defun org-auto-repeat-maybe (done-word)
9565 "Check if the current headline contains a repeated deadline/schedule.
9566 If yes, set TODO state back to what it was and change the base date
9567 of repeating deadline/scheduled time stamps to new date.
9568 This function is run automatically after each state change to a DONE state."
9569 ;; last-state is dynamically scoped into this function
9570 (let* ((repeat (org-get-repeat))
9571 (aa (assoc last-state org-todo-kwd-alist))
9572 (interpret (nth 1 aa))
9573 (head (nth 2 aa))
9574 (whata '(("d" . day) ("m" . month) ("y" . year)))
9575 (msg "Entry repeats: ")
9576 (org-log-done nil)
9577 (org-todo-log-states nil)
9578 (nshiftmax 10) (nshift 0)
9579 re type n what ts time)
9580 (when repeat
9581 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9582 (org-todo (if (eq interpret 'type) last-state head))
9583 (org-entry-put nil "LAST_REPEAT" (format-time-string
9584 (org-time-stamp-format t t)))
9585 (when org-log-repeat
9586 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9587 (memq 'org-add-log-note post-command-hook))
9588 ;; OK, we are already setup for some record
9589 (if (eq org-log-repeat 'note)
9590 ;; make sure we take a note, not only a time stamp
9591 (setq org-log-note-how 'note))
9592 ;; Set up for taking a record
9593 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9594 last-state
9595 'findpos org-log-repeat)))
9596 (org-back-to-heading t)
9597 (org-add-planning-info nil nil 'closed)
9598 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9599 org-deadline-time-regexp "\\)\\|\\("
9600 org-ts-regexp "\\)"))
9601 (while (re-search-forward
9602 re (save-excursion (outline-next-heading) (point)) t)
9603 (setq type (if (match-end 1) org-scheduled-string
9604 (if (match-end 3) org-deadline-string "Plain:"))
9605 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9606 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9607 (setq n (string-to-number (match-string 2 ts))
9608 what (match-string 3 ts))
9609 (if (equal what "w") (setq n (* n 7) what "d"))
9610 ;; Preparation, see if we need to modify the start date for the change
9611 (when (match-end 1)
9612 (setq time (save-match-data (org-time-string-to-time ts)))
9613 (cond
9614 ((equal (match-string 1 ts) ".")
9615 ;; Shift starting date to today
9616 (org-timestamp-change
9617 (- (time-to-days (current-time)) (time-to-days time))
9618 'day))
9619 ((equal (match-string 1 ts) "+")
9620 (while (or (= nshift 0)
9621 (<= (time-to-days time) (time-to-days (current-time))))
9622 (when (= (incf nshift) nshiftmax)
9623 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9624 (error "Abort")))
9625 (org-timestamp-change n (cdr (assoc what whata)))
9626 (org-at-timestamp-p t)
9627 (setq ts (match-string 1))
9628 (setq time (save-match-data (org-time-string-to-time ts))))
9629 (org-timestamp-change (- n) (cdr (assoc what whata)))
9630 ;; rematch, so that we have everything in place for the real shift
9631 (org-at-timestamp-p t)
9632 (setq ts (match-string 1))
9633 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9634 (org-timestamp-change n (cdr (assoc what whata)))
9635 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9636 (setq org-log-post-message msg)
9637 (message "%s" msg))))
9639 (defun org-show-todo-tree (arg)
9640 "Make a compact tree which shows all headlines marked with TODO.
9641 The tree will show the lines where the regexp matches, and all higher
9642 headlines above the match.
9643 With a \\[universal-argument] prefix, prompt for a regexp to match.
9644 With a numeric prefix N, construct a sparse tree for the Nth element
9645 of `org-todo-keywords-1'."
9646 (interactive "P")
9647 (let ((case-fold-search nil)
9648 (kwd-re
9649 (cond ((null arg) org-not-done-regexp)
9650 ((equal arg '(4))
9651 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9652 (mapcar 'list org-todo-keywords-1))))
9653 (concat "\\("
9654 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9655 "\\)\\>")))
9656 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9657 (regexp-quote (nth (1- (prefix-numeric-value arg))
9658 org-todo-keywords-1)))
9659 (t (error "Invalid prefix argument: %s" arg)))))
9660 (message "%d TODO entries found"
9661 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9663 (defun org-deadline (&optional remove time)
9664 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9665 With argument REMOVE, remove any deadline from the item.
9666 When TIME is set, it should be an internal time specification, and the
9667 scheduling will use the corresponding date."
9668 (interactive "P")
9669 (if remove
9670 (progn
9671 (org-remove-timestamp-with-keyword org-deadline-string)
9672 (message "Item no longer has a deadline."))
9673 (if (org-get-repeat)
9674 (error "Cannot change deadline on task with repeater, please do that by hand")
9675 (org-add-planning-info 'deadline time 'closed)
9676 (message "Deadline on %s" org-last-inserted-timestamp))))
9678 (defun org-schedule (&optional remove time)
9679 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9680 With argument REMOVE, remove any scheduling date from the item.
9681 When TIME is set, it should be an internal time specification, and the
9682 scheduling will use the corresponding date."
9683 (interactive "P")
9684 (if remove
9685 (progn
9686 (org-remove-timestamp-with-keyword org-scheduled-string)
9687 (message "Item is no longer scheduled."))
9688 (if (org-get-repeat)
9689 (error "Cannot reschedule task with repeater, please do that by hand")
9690 (org-add-planning-info 'scheduled time 'closed)
9691 (message "Scheduled to %s" org-last-inserted-timestamp))))
9693 (defun org-get-scheduled-time (pom &optional inherit)
9694 "Get the scheduled time as a time tuple, of a format suitable
9695 for calling org-schedule with, or if there is no scheduling,
9696 returns nil."
9697 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9698 (when time
9699 (apply 'encode-time (org-parse-time-string time)))))
9701 (defun org-get-deadline-time (pom &optional inherit)
9702 "Get the deadine as a time tuple, of a format suitable for
9703 calling org-deadlin with, or if there is no scheduling, returns
9704 nil."
9705 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9706 (when time
9707 (apply 'encode-time (org-parse-time-string time)))))
9709 (defun org-remove-timestamp-with-keyword (keyword)
9710 "Remove all time stamps with KEYWORD in the current entry."
9711 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9712 beg)
9713 (save-excursion
9714 (org-back-to-heading t)
9715 (setq beg (point))
9716 (org-end-of-subtree t t)
9717 (while (re-search-backward re beg t)
9718 (replace-match "")
9719 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9720 (equal (char-before) ?\ ))
9721 (backward-delete-char 1)
9722 (if (string-match "^[ \t]*$" (buffer-substring
9723 (point-at-bol) (point-at-eol)))
9724 (delete-region (point-at-bol)
9725 (min (point-max) (1+ (point-at-eol))))))))))
9727 (defun org-add-planning-info (what &optional time &rest remove)
9728 "Insert new timestamp with keyword in the line directly after the headline.
9729 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9730 If non is given, the user is prompted for a date.
9731 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9732 be removed."
9733 (interactive)
9734 (let (org-time-was-given org-end-time-was-given ts
9735 end default-time default-input)
9737 (catch 'exit
9738 (when (and (not time) (memq what '(scheduled deadline)))
9739 ;; Try to get a default date/time from existing timestamp
9740 (save-excursion
9741 (org-back-to-heading t)
9742 (setq end (save-excursion (outline-next-heading) (point)))
9743 (when (re-search-forward (if (eq what 'scheduled)
9744 org-scheduled-time-regexp
9745 org-deadline-time-regexp)
9746 end t)
9747 (setq ts (match-string 1)
9748 default-time
9749 (apply 'encode-time (org-parse-time-string ts))
9750 default-input (and ts (org-get-compact-tod ts))))))
9751 (when what
9752 ;; If necessary, get the time from the user
9753 (setq time (or time (org-read-date nil 'to-time nil nil
9754 default-time default-input))))
9756 (when (and org-insert-labeled-timestamps-at-point
9757 (member what '(scheduled deadline)))
9758 (insert
9759 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9760 (org-insert-time-stamp time org-time-was-given
9761 nil nil nil (list org-end-time-was-given))
9762 (setq what nil))
9763 (save-excursion
9764 (save-restriction
9765 (let (col list elt ts buffer-invisibility-spec)
9766 (org-back-to-heading t)
9767 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9768 (goto-char (match-end 1))
9769 (setq col (current-column))
9770 (goto-char (match-end 0))
9771 (if (eobp) (insert "\n") (forward-char 1))
9772 (when (and (not what)
9773 (not (looking-at
9774 (concat "[ \t]*"
9775 org-keyword-time-not-clock-regexp))))
9776 ;; Nothing to add, nothing to remove...... :-)
9777 (throw 'exit nil))
9778 (if (and (not (looking-at outline-regexp))
9779 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9780 "[^\r\n]*"))
9781 (not (equal (match-string 1) org-clock-string)))
9782 (narrow-to-region (match-beginning 0) (match-end 0))
9783 (insert-before-markers "\n")
9784 (backward-char 1)
9785 (narrow-to-region (point) (point))
9786 (and org-adapt-indentation (org-indent-to-column col)))
9787 ;; Check if we have to remove something.
9788 (setq list (cons what remove))
9789 (while list
9790 (setq elt (pop list))
9791 (goto-char (point-min))
9792 (when (or (and (eq elt 'scheduled)
9793 (re-search-forward org-scheduled-time-regexp nil t))
9794 (and (eq elt 'deadline)
9795 (re-search-forward org-deadline-time-regexp nil t))
9796 (and (eq elt 'closed)
9797 (re-search-forward org-closed-time-regexp nil t)))
9798 (replace-match "")
9799 (if (looking-at "--+<[^>]+>") (replace-match ""))
9800 (if (looking-at " +") (replace-match ""))))
9801 (goto-char (point-max))
9802 (when what
9803 (insert
9804 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9805 (cond ((eq what 'scheduled) org-scheduled-string)
9806 ((eq what 'deadline) org-deadline-string)
9807 ((eq what 'closed) org-closed-string))
9808 " ")
9809 (setq ts (org-insert-time-stamp
9810 time
9811 (or org-time-was-given
9812 (and (eq what 'closed) org-log-done-with-time))
9813 (eq what 'closed)
9814 nil nil (list org-end-time-was-given)))
9815 (end-of-line 1))
9816 (goto-char (point-min))
9817 (widen)
9818 (if (and (looking-at "[ \t]+\n")
9819 (equal (char-before) ?\n))
9820 (delete-region (1- (point)) (point-at-eol)))
9821 ts))))))
9823 (defvar org-log-note-marker (make-marker))
9824 (defvar org-log-note-purpose nil)
9825 (defvar org-log-note-state nil)
9826 (defvar org-log-note-previous-state nil)
9827 (defvar org-log-note-how nil)
9828 (defvar org-log-note-extra nil)
9829 (defvar org-log-note-window-configuration nil)
9830 (defvar org-log-note-return-to (make-marker))
9831 (defvar org-log-post-message nil
9832 "Message to be displayed after a log note has been stored.
9833 The auto-repeater uses this.")
9835 (defun org-add-note ()
9836 "Add a note to the current entry.
9837 This is done in the same way as adding a state change note."
9838 (interactive)
9839 (org-add-log-setup 'note nil nil 'findpos nil))
9841 (defvar org-property-end-re)
9842 (defun org-add-log-setup (&optional purpose state prev-state
9843 findpos how &optional extra)
9844 "Set up the post command hook to take a note.
9845 If this is about to TODO state change, the new state is expected in STATE.
9846 When FINDPOS is non-nil, find the correct position for the note in
9847 the current entry. If not, assume that it can be inserted at point.
9848 HOW is an indicator what kind of note should be created.
9849 EXTRA is additional text that will be inserted into the notes buffer."
9850 (let* ((org-log-into-drawer (org-log-into-drawer))
9851 (drawer (cond ((stringp org-log-into-drawer)
9852 org-log-into-drawer)
9853 (org-log-into-drawer "LOGBOOK")
9854 (t nil))))
9855 (save-restriction
9856 (save-excursion
9857 (when findpos
9858 (org-back-to-heading t)
9859 (narrow-to-region (point) (save-excursion
9860 (outline-next-heading) (point)))
9861 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9862 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9863 "[^\r\n]*\\)?"))
9864 (goto-char (match-end 0))
9865 (cond
9866 (drawer
9867 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9868 nil t)
9869 (progn
9870 (goto-char (match-end 0))
9871 (or org-log-states-order-reversed
9872 (and (re-search-forward org-property-end-re nil t)
9873 (goto-char (1- (match-beginning 0))))))
9874 (insert "\n:" drawer ":\n:END:")
9875 (beginning-of-line 0)
9876 (org-indent-line-function)
9877 (beginning-of-line 2)
9878 (org-indent-line-function)
9879 (end-of-line 0)))
9880 ((and org-log-state-notes-insert-after-drawers
9881 (save-excursion
9882 (forward-line) (looking-at org-drawer-regexp)))
9883 (forward-line)
9884 (while (looking-at org-drawer-regexp)
9885 (goto-char (match-end 0))
9886 (re-search-forward org-property-end-re (point-max) t)
9887 (forward-line))
9888 (forward-line -1)))
9889 (unless org-log-states-order-reversed
9890 (and (= (char-after) ?\n) (forward-char 1))
9891 (org-skip-over-state-notes)
9892 (skip-chars-backward " \t\n\r")))
9893 (move-marker org-log-note-marker (point))
9894 (setq org-log-note-purpose purpose
9895 org-log-note-state state
9896 org-log-note-previous-state prev-state
9897 org-log-note-how how
9898 org-log-note-extra extra)
9899 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9901 (defun org-skip-over-state-notes ()
9902 "Skip past the list of State notes in an entry."
9903 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9904 (while (looking-at "[ \t]*- State")
9905 (condition-case nil
9906 (org-next-item)
9907 (error (org-end-of-item)))))
9909 (defun org-add-log-note (&optional purpose)
9910 "Pop up a window for taking a note, and add this note later at point."
9911 (remove-hook 'post-command-hook 'org-add-log-note)
9912 (setq org-log-note-window-configuration (current-window-configuration))
9913 (delete-other-windows)
9914 (move-marker org-log-note-return-to (point))
9915 (switch-to-buffer (marker-buffer org-log-note-marker))
9916 (goto-char org-log-note-marker)
9917 (org-switch-to-buffer-other-window "*Org Note*")
9918 (erase-buffer)
9919 (if (memq org-log-note-how '(time state))
9920 (let (current-prefix-arg) (org-store-log-note))
9921 (let ((org-inhibit-startup t)) (org-mode))
9922 (insert (format "# Insert note for %s.
9923 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9924 (cond
9925 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9926 ((eq org-log-note-purpose 'done) "closed todo item")
9927 ((eq org-log-note-purpose 'state)
9928 (format "state change from \"%s\" to \"%s\""
9929 (or org-log-note-previous-state "")
9930 (or org-log-note-state "")))
9931 ((eq org-log-note-purpose 'note)
9932 "this entry")
9933 (t (error "This should not happen")))))
9934 (if org-log-note-extra (insert org-log-note-extra))
9935 (org-set-local 'org-finish-function 'org-store-log-note)))
9937 (defvar org-note-abort nil) ; dynamically scoped
9938 (defun org-store-log-note ()
9939 "Finish taking a log note, and insert it to where it belongs."
9940 (let ((txt (buffer-string))
9941 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9942 lines ind)
9943 (kill-buffer (current-buffer))
9944 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9945 (setq txt (replace-match "" t t txt)))
9946 (if (string-match "\\s-+\\'" txt)
9947 (setq txt (replace-match "" t t txt)))
9948 (setq lines (org-split-string txt "\n"))
9949 (when (and note (string-match "\\S-" note))
9950 (setq note
9951 (org-replace-escapes
9952 note
9953 (list (cons "%u" (user-login-name))
9954 (cons "%U" user-full-name)
9955 (cons "%t" (format-time-string
9956 (org-time-stamp-format 'long 'inactive)
9957 (current-time)))
9958 (cons "%s" (if org-log-note-state
9959 (concat "\"" org-log-note-state "\"")
9960 ""))
9961 (cons "%S" (if org-log-note-previous-state
9962 (concat "\"" org-log-note-previous-state "\"")
9963 "\"\"")))))
9964 (if lines (setq note (concat note " \\\\")))
9965 (push note lines))
9966 (when (or current-prefix-arg org-note-abort)
9967 (when org-log-into-drawer
9968 (org-remove-empty-drawer-at
9969 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
9970 org-log-note-marker))
9971 (setq lines nil))
9972 (when lines
9973 (save-excursion
9974 (set-buffer (marker-buffer org-log-note-marker))
9975 (save-excursion
9976 (goto-char org-log-note-marker)
9977 (move-marker org-log-note-marker nil)
9978 (end-of-line 1)
9979 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9980 (insert "- " (pop lines))
9981 (org-indent-line-function)
9982 (beginning-of-line 1)
9983 (looking-at "[ \t]*")
9984 (setq ind (concat (match-string 0) " "))
9985 (end-of-line 1)
9986 (while lines (insert "\n" ind (pop lines)))
9987 (message "Note stored")
9988 (org-back-to-heading t)
9989 (org-cycle-hide-drawers 'children)))))
9990 (set-window-configuration org-log-note-window-configuration)
9991 (with-current-buffer (marker-buffer org-log-note-return-to)
9992 (goto-char org-log-note-return-to))
9993 (move-marker org-log-note-return-to nil)
9994 (and org-log-post-message (message "%s" org-log-post-message)))
9996 (defun org-remove-empty-drawer-at (drawer pos)
9997 "Remove an emptyr DARWER drawer at position POS.
9998 POS may also be a marker."
9999 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10000 (save-excursion
10001 (save-restriction
10002 (widen)
10003 (goto-char pos)
10004 (if (org-in-regexp
10005 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10006 (replace-match ""))))))
10008 (defun org-sparse-tree (&optional arg)
10009 "Create a sparse tree, prompt for the details.
10010 This command can create sparse trees. You first need to select the type
10011 of match used to create the tree:
10013 t Show entries with a specific TODO keyword.
10014 m Show entries selected by a tags/property match.
10015 p Enter a property name and its value (both with completion on existing
10016 names/values) and show entries with that property.
10017 r Show entries matching a regular expression.
10018 d Show deadlines due within `org-deadline-warning-days'.
10019 b Show deadlines and scheduled items before a date.
10020 a Show deadlines and scheduled items after a date."
10021 (interactive "P")
10022 (let (ans kwd value)
10023 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10024 (setq ans (read-char-exclusive))
10025 (cond
10026 ((equal ans ?d)
10027 (call-interactively 'org-check-deadlines))
10028 ((equal ans ?b)
10029 (call-interactively 'org-check-before-date))
10030 ((equal ans ?a)
10031 (call-interactively 'org-check-after-date))
10032 ((equal ans ?t)
10033 (org-show-todo-tree '(4)))
10034 ((member ans '(?T ?m))
10035 (call-interactively 'org-match-sparse-tree))
10036 ((member ans '(?p ?P))
10037 (setq kwd (org-ido-completing-read "Property: "
10038 (mapcar 'list (org-buffer-property-keys))))
10039 (setq value (org-ido-completing-read "Value: "
10040 (mapcar 'list (org-property-values kwd))))
10041 (unless (string-match "\\`{.*}\\'" value)
10042 (setq value (concat "\"" value "\"")))
10043 (org-match-sparse-tree arg (concat kwd "=" value)))
10044 ((member ans '(?r ?R ?/))
10045 (call-interactively 'org-occur))
10046 (t (error "No such sparse tree command \"%c\"" ans)))))
10048 (defvar org-occur-highlights nil
10049 "List of overlays used for occur matches.")
10050 (make-variable-buffer-local 'org-occur-highlights)
10051 (defvar org-occur-parameters nil
10052 "Parameters of the active org-occur calls.
10053 This is a list, each call to org-occur pushes as cons cell,
10054 containing the regular expression and the callback, onto the list.
10055 The list can contain several entries if `org-occur' has been called
10056 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10057 will only contain one set of parameters. When the highlights are
10058 removed (for example with `C-c C-c', or with the next edit (depending
10059 on `org-remove-highlights-with-change'), this variable is emptied
10060 as well.")
10061 (make-variable-buffer-local 'org-occur-parameters)
10063 (defun org-occur (regexp &optional keep-previous callback)
10064 "Make a compact tree which shows all matches of REGEXP.
10065 The tree will show the lines where the regexp matches, and all higher
10066 headlines above the match. It will also show the heading after the match,
10067 to make sure editing the matching entry is easy.
10068 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10069 call to `org-occur' will be kept, to allow stacking of calls to this
10070 command.
10071 If CALLBACK is non-nil, it is a function which is called to confirm
10072 that the match should indeed be shown."
10073 (interactive "sRegexp: \nP")
10074 (unless keep-previous
10075 (org-remove-occur-highlights nil nil t))
10076 (push (cons regexp callback) org-occur-parameters)
10077 (let ((cnt 0))
10078 (save-excursion
10079 (goto-char (point-min))
10080 (if (or (not keep-previous) ; do not want to keep
10081 (not org-occur-highlights)) ; no previous matches
10082 ;; hide everything
10083 (org-overview))
10084 (while (re-search-forward regexp nil t)
10085 (when (or (not callback)
10086 (save-match-data (funcall callback)))
10087 (setq cnt (1+ cnt))
10088 (when org-highlight-sparse-tree-matches
10089 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10090 (org-show-context 'occur-tree))))
10091 (when org-remove-highlights-with-change
10092 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10093 nil 'local))
10094 (unless org-sparse-tree-open-archived-trees
10095 (org-hide-archived-subtrees (point-min) (point-max)))
10096 (run-hooks 'org-occur-hook)
10097 (if (interactive-p)
10098 (message "%d match(es) for regexp %s" cnt regexp))
10099 cnt))
10101 (defun org-show-context (&optional key)
10102 "Make sure point and context and visible.
10103 How much context is shown depends upon the variables
10104 `org-show-hierarchy-above', `org-show-following-heading'. and
10105 `org-show-siblings'."
10106 (let ((heading-p (org-on-heading-p t))
10107 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10108 (following-p (org-get-alist-option org-show-following-heading key))
10109 (entry-p (org-get-alist-option org-show-entry-below key))
10110 (siblings-p (org-get-alist-option org-show-siblings key)))
10111 (catch 'exit
10112 ;; Show heading or entry text
10113 (if (and heading-p (not entry-p))
10114 (org-flag-heading nil) ; only show the heading
10115 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10116 (org-show-hidden-entry))) ; show entire entry
10117 (when following-p
10118 ;; Show next sibling, or heading below text
10119 (save-excursion
10120 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10121 (org-flag-heading nil))))
10122 (when siblings-p (org-show-siblings))
10123 (when hierarchy-p
10124 ;; show all higher headings, possibly with siblings
10125 (save-excursion
10126 (while (and (condition-case nil
10127 (progn (org-up-heading-all 1) t)
10128 (error nil))
10129 (not (bobp)))
10130 (org-flag-heading nil)
10131 (when siblings-p (org-show-siblings))))))))
10133 (defun org-reveal (&optional siblings)
10134 "Show current entry, hierarchy above it, and the following headline.
10135 This can be used to show a consistent set of context around locations
10136 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10137 not t for the search context.
10139 With optional argument SIBLINGS, on each level of the hierarchy all
10140 siblings are shown. This repairs the tree structure to what it would
10141 look like when opened with hierarchical calls to `org-cycle'."
10142 (interactive "P")
10143 (let ((org-show-hierarchy-above t)
10144 (org-show-following-heading t)
10145 (org-show-siblings (if siblings t org-show-siblings)))
10146 (org-show-context nil)))
10148 (defun org-highlight-new-match (beg end)
10149 "Highlight from BEG to END and mark the highlight is an occur headline."
10150 (let ((ov (org-make-overlay beg end)))
10151 (org-overlay-put ov 'face 'secondary-selection)
10152 (push ov org-occur-highlights)))
10154 (defun org-remove-occur-highlights (&optional beg end noremove)
10155 "Remove the occur highlights from the buffer.
10156 BEG and END are ignored. If NOREMOVE is nil, remove this function
10157 from the `before-change-functions' in the current buffer."
10158 (interactive)
10159 (unless org-inhibit-highlight-removal
10160 (mapc 'org-delete-overlay org-occur-highlights)
10161 (setq org-occur-highlights nil)
10162 (setq org-occur-parameters nil)
10163 (unless noremove
10164 (remove-hook 'before-change-functions
10165 'org-remove-occur-highlights 'local))))
10167 ;;;; Priorities
10169 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10170 "Regular expression matching the priority indicator.")
10172 (defvar org-remove-priority-next-time nil)
10174 (defun org-priority-up ()
10175 "Increase the priority of the current item."
10176 (interactive)
10177 (org-priority 'up))
10179 (defun org-priority-down ()
10180 "Decrease the priority of the current item."
10181 (interactive)
10182 (org-priority 'down))
10184 (defun org-priority (&optional action)
10185 "Change the priority of an item by ARG.
10186 ACTION can be `set', `up', `down', or a character."
10187 (interactive)
10188 (unless org-enable-priority-commands
10189 (error "Priority commands are disabled"))
10190 (setq action (or action 'set))
10191 (let (current new news have remove)
10192 (save-excursion
10193 (org-back-to-heading t)
10194 (if (looking-at org-priority-regexp)
10195 (setq current (string-to-char (match-string 2))
10196 have t)
10197 (setq current org-default-priority))
10198 (cond
10199 ((or (eq action 'set)
10200 (if (featurep 'xemacs) (characterp action) (integerp action)))
10201 (if (not (eq action 'set))
10202 (setq new action)
10203 (message "Priority %c-%c, SPC to remove: "
10204 org-highest-priority org-lowest-priority)
10205 (setq new (read-char-exclusive)))
10206 (if (and (= (upcase org-highest-priority) org-highest-priority)
10207 (= (upcase org-lowest-priority) org-lowest-priority))
10208 (setq new (upcase new)))
10209 (cond ((equal new ?\ ) (setq remove t))
10210 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10211 (error "Priority must be between `%c' and `%c'"
10212 org-highest-priority org-lowest-priority))))
10213 ((eq action 'up)
10214 (if (and (not have) (eq last-command this-command))
10215 (setq new org-lowest-priority)
10216 (setq new (if (and org-priority-start-cycle-with-default (not have))
10217 org-default-priority (1- current)))))
10218 ((eq action 'down)
10219 (if (and (not have) (eq last-command this-command))
10220 (setq new org-highest-priority)
10221 (setq new (if (and org-priority-start-cycle-with-default (not have))
10222 org-default-priority (1+ current)))))
10223 (t (error "Invalid action")))
10224 (if (or (< (upcase new) org-highest-priority)
10225 (> (upcase new) org-lowest-priority))
10226 (setq remove t))
10227 (setq news (format "%c" new))
10228 (if have
10229 (if remove
10230 (replace-match "" t t nil 1)
10231 (replace-match news t t nil 2))
10232 (if remove
10233 (error "No priority cookie found in line")
10234 (let ((case-fold-search nil))
10235 (looking-at org-todo-line-regexp))
10236 (if (match-end 2)
10237 (progn
10238 (goto-char (match-end 2))
10239 (insert " [#" news "]"))
10240 (goto-char (match-beginning 3))
10241 (insert "[#" news "] ")))))
10242 (org-preserve-lc (org-set-tags nil 'align))
10243 (if remove
10244 (message "Priority removed")
10245 (message "Priority of current item set to %s" news))))
10248 (defun org-get-priority (s)
10249 "Find priority cookie and return priority."
10250 (save-match-data
10251 (if (not (string-match org-priority-regexp s))
10252 (* 1000 (- org-lowest-priority org-default-priority))
10253 (* 1000 (- org-lowest-priority
10254 (string-to-char (match-string 2 s)))))))
10256 ;;;; Tags
10258 (defvar org-agenda-archives-mode)
10259 (defvar org-map-continue-from nil
10260 "Position from where mapping should continue.
10261 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10263 (defvar org-scanner-tags nil
10264 "The current tag list while the tags scanner is running.")
10265 (defvar org-trust-scanner-tags nil
10266 "Should `org-get-tags-at' use the tags fro the scanner.
10267 This is for internal dynamical scoping only.
10268 When this is non-nil, the function `org-get-tags-at' will return the value
10269 of `org-scanner-tags' instead of building the list by itself. This
10270 can lead to large speed-ups when the tags scanner is used in a file with
10271 many entries, and when the list of tags is retrieved, for example to
10272 obtain a list of properties. Building the tags list for each entry in such
10273 a file becomes an N^2 operation - but with this variable set, it scales
10274 as N.")
10276 (defun org-scan-tags (action matcher &optional todo-only)
10277 "Scan headline tags with inheritance and produce output ACTION.
10279 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10280 or `agenda' to produce an entry list for an agenda view. It can also be
10281 a Lisp form or a function that should be called at each matched headline, in
10282 this case the return value is a list of all return values from these calls.
10284 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10285 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10286 only lines with a TODO keyword are included in the output."
10287 (require 'org-agenda)
10288 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10289 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10290 (org-re
10291 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10292 (props (list 'face 'default
10293 'done-face 'org-agenda-done
10294 'undone-face 'default
10295 'mouse-face 'highlight
10296 'org-not-done-regexp org-not-done-regexp
10297 'org-todo-regexp org-todo-regexp
10298 'keymap org-agenda-keymap
10299 'help-echo
10300 (format "mouse-2 or RET jump to org file %s"
10301 (abbreviate-file-name
10302 (or (buffer-file-name (buffer-base-buffer))
10303 (buffer-name (buffer-base-buffer)))))))
10304 (case-fold-search nil)
10305 (org-map-continue-from nil)
10306 lspos tags tags-list
10307 (tags-alist (list (cons 0 org-file-tags)))
10308 (llast 0) rtn rtn1 level category i txt
10309 todo marker entry priority)
10310 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10311 (setq action (list 'lambda nil action)))
10312 (save-excursion
10313 (goto-char (point-min))
10314 (when (eq action 'sparse-tree)
10315 (org-overview)
10316 (org-remove-occur-highlights))
10317 (while (re-search-forward re nil t)
10318 (catch :skip
10319 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10320 tags (if (match-end 4) (org-match-string-no-properties 4)))
10321 (goto-char (setq lspos (match-beginning 0)))
10322 (setq level (org-reduced-level (funcall outline-level))
10323 category (org-get-category))
10324 (setq i llast llast level)
10325 ;; remove tag lists from same and sublevels
10326 (while (>= i level)
10327 (when (setq entry (assoc i tags-alist))
10328 (setq tags-alist (delete entry tags-alist)))
10329 (setq i (1- i)))
10330 ;; add the next tags
10331 (when tags
10332 (setq tags (org-split-string tags ":")
10333 tags-alist
10334 (cons (cons level tags) tags-alist)))
10335 ;; compile tags for current headline
10336 (setq tags-list
10337 (if org-use-tag-inheritance
10338 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10339 tags)
10340 org-scanner-tags tags-list)
10341 (when org-use-tag-inheritance
10342 (setcdr (car tags-alist)
10343 (mapcar (lambda (x)
10344 (setq x (copy-sequence x))
10345 (org-add-prop-inherited x))
10346 (cdar tags-alist))))
10347 (when (and tags org-use-tag-inheritance
10348 (or (not (eq t org-use-tag-inheritance))
10349 org-tags-exclude-from-inheritance))
10350 ;; selective inheritance, remove uninherited ones
10351 (setcdr (car tags-alist)
10352 (org-remove-uniherited-tags (cdar tags-alist))))
10353 (when (and (or (not todo-only)
10354 (and (member todo org-not-done-keywords)
10355 (or (not org-agenda-tags-todo-honor-ignore-options)
10356 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10357 (let ((case-fold-search t)) (eval matcher))
10359 (not (member org-archive-tag tags-list))
10360 ;; we have an archive tag, should we use this anyway?
10361 (or (not org-agenda-skip-archived-trees)
10362 (and (eq action 'agenda) org-agenda-archives-mode))))
10363 (unless (eq action 'sparse-tree) (org-agenda-skip))
10365 ;; select this headline
10367 (cond
10368 ((eq action 'sparse-tree)
10369 (and org-highlight-sparse-tree-matches
10370 (org-get-heading) (match-end 0)
10371 (org-highlight-new-match
10372 (match-beginning 0) (match-beginning 1)))
10373 (org-show-context 'tags-tree))
10374 ((eq action 'agenda)
10375 (setq txt (org-format-agenda-item
10377 (concat
10378 (if (eq org-tags-match-list-sublevels 'indented)
10379 (make-string (1- level) ?.) "")
10380 (org-get-heading))
10381 category
10382 tags-list
10384 priority (org-get-priority txt))
10385 (goto-char lspos)
10386 (setq marker (org-agenda-new-marker))
10387 (org-add-props txt props
10388 'org-marker marker 'org-hd-marker marker 'org-category category
10389 'todo-state todo
10390 'priority priority 'type "tagsmatch")
10391 (push txt rtn))
10392 ((functionp action)
10393 (setq org-map-continue-from nil)
10394 (save-excursion
10395 (setq rtn1 (funcall action))
10396 (push rtn1 rtn)))
10397 (t (error "Invalid action")))
10399 ;; if we are to skip sublevels, jump to end of subtree
10400 (unless org-tags-match-list-sublevels
10401 (org-end-of-subtree t)
10402 (backward-char 1))))
10403 ;; Get the correct position from where to continue
10404 (if org-map-continue-from
10405 (goto-char org-map-continue-from)
10406 (and (= (point) lspos) (end-of-line 1)))))
10407 (when (and (eq action 'sparse-tree)
10408 (not org-sparse-tree-open-archived-trees))
10409 (org-hide-archived-subtrees (point-min) (point-max)))
10410 (nreverse rtn)))
10412 (defun org-remove-uniherited-tags (tags)
10413 "Remove all tags that are not inherited from the list TAGS."
10414 (cond
10415 ((eq org-use-tag-inheritance t)
10416 (if org-tags-exclude-from-inheritance
10417 (org-delete-all org-tags-exclude-from-inheritance tags)
10418 tags))
10419 ((not org-use-tag-inheritance) nil)
10420 ((stringp org-use-tag-inheritance)
10421 (delq nil (mapcar
10422 (lambda (x)
10423 (if (and (string-match org-use-tag-inheritance x)
10424 (not (member x org-tags-exclude-from-inheritance)))
10425 x nil))
10426 tags)))
10427 ((listp org-use-tag-inheritance)
10428 (delq nil (mapcar
10429 (lambda (x)
10430 (if (member x org-use-tag-inheritance) x nil))
10431 tags)))))
10433 (defvar todo-only) ;; dynamically scoped
10435 (defun org-match-sparse-tree (&optional todo-only match)
10436 "Create a sparse tree according to tags string MATCH.
10437 MATCH can contain positive and negative selection of tags, like
10438 \"+WORK+URGENT-WITHBOSS\".
10439 If optional argument TODO-ONLY is non-nil, only select lines that are
10440 also TODO lines."
10441 (interactive "P")
10442 (org-prepare-agenda-buffers (list (current-buffer)))
10443 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10445 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10447 (defvar org-cached-props nil)
10448 (defun org-cached-entry-get (pom property)
10449 (if (or (eq t org-use-property-inheritance)
10450 (and (stringp org-use-property-inheritance)
10451 (string-match org-use-property-inheritance property))
10452 (and (listp org-use-property-inheritance)
10453 (member property org-use-property-inheritance)))
10454 ;; Caching is not possible, check it directly
10455 (org-entry-get pom property 'inherit)
10456 ;; Get all properties, so that we can do complicated checks easily
10457 (cdr (assoc property (or org-cached-props
10458 (setq org-cached-props
10459 (org-entry-properties pom)))))))
10461 (defun org-global-tags-completion-table (&optional files)
10462 "Return the list of all tags in all agenda buffer/files."
10463 (save-excursion
10464 (org-uniquify
10465 (delq nil
10466 (apply 'append
10467 (mapcar
10468 (lambda (file)
10469 (set-buffer (find-file-noselect file))
10470 (append (org-get-buffer-tags)
10471 (mapcar (lambda (x) (if (stringp (car-safe x))
10472 (list (car-safe x)) nil))
10473 org-tag-alist)))
10474 (if (and files (car files))
10475 files
10476 (org-agenda-files))))))))
10478 (defun org-make-tags-matcher (match)
10479 "Create the TAGS//TODO matcher form for the selection string MATCH."
10480 ;; todo-only is scoped dynamically into this function, and the function
10481 ;; may change it if the matcher asks for it.
10482 (unless match
10483 ;; Get a new match request, with completion
10484 (let ((org-last-tags-completion-table
10485 (org-global-tags-completion-table)))
10486 (setq match (org-completing-read-no-ido
10487 "Match: " 'org-tags-completion-function nil nil nil
10488 'org-tags-history))))
10490 ;; Parse the string and create a lisp form
10491 (let ((match0 match)
10492 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10493 minus tag mm
10494 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10495 orterms term orlist re-p str-p level-p level-op time-p
10496 prop-p pn pv po cat-p gv rest)
10497 (if (string-match "/+" match)
10498 ;; match contains also a todo-matching request
10499 (progn
10500 (setq tagsmatch (substring match 0 (match-beginning 0))
10501 todomatch (substring match (match-end 0)))
10502 (if (string-match "^!" todomatch)
10503 (setq todo-only t todomatch (substring todomatch 1)))
10504 (if (string-match "^\\s-*$" todomatch)
10505 (setq todomatch nil)))
10506 ;; only matching tags
10507 (setq tagsmatch match todomatch nil))
10509 ;; Make the tags matcher
10510 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10511 (setq tagsmatcher t)
10512 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10513 (while (setq term (pop orterms))
10514 (while (and (equal (substring term -1) "\\") orterms)
10515 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10516 (while (string-match re term)
10517 (setq rest (substring term (match-end 0))
10518 minus (and (match-end 1)
10519 (equal (match-string 1 term) "-"))
10520 tag (match-string 2 term)
10521 re-p (equal (string-to-char tag) ?{)
10522 level-p (match-end 4)
10523 prop-p (match-end 5)
10524 mm (cond
10525 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10526 (level-p
10527 (setq level-op (org-op-to-function (match-string 3 term)))
10528 `(,level-op level ,(string-to-number
10529 (match-string 4 term))))
10530 (prop-p
10531 (setq pn (match-string 5 term)
10532 po (match-string 6 term)
10533 pv (match-string 7 term)
10534 cat-p (equal pn "CATEGORY")
10535 re-p (equal (string-to-char pv) ?{)
10536 str-p (equal (string-to-char pv) ?\")
10537 time-p (save-match-data
10538 (string-match "^\"[[<].*[]>]\"$" pv))
10539 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10540 (if time-p (setq pv (org-matcher-time pv)))
10541 (setq po (org-op-to-function po (if time-p 'time str-p)))
10542 (cond
10543 ((equal pn "CATEGORY")
10544 (setq gv '(get-text-property (point) 'org-category)))
10545 ((equal pn "TODO")
10546 (setq gv 'todo))
10548 (setq gv `(org-cached-entry-get nil ,pn))))
10549 (if re-p
10550 (if (eq po 'org<>)
10551 `(not (string-match ,pv (or ,gv "")))
10552 `(string-match ,pv (or ,gv "")))
10553 (if str-p
10554 `(,po (or ,gv "") ,pv)
10555 `(,po (string-to-number (or ,gv ""))
10556 ,(string-to-number pv) ))))
10557 (t `(member ,tag tags-list)))
10558 mm (if minus (list 'not mm) mm)
10559 term rest)
10560 (push mm tagsmatcher))
10561 (push (if (> (length tagsmatcher) 1)
10562 (cons 'and tagsmatcher)
10563 (car tagsmatcher))
10564 orlist)
10565 (setq tagsmatcher nil))
10566 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10567 (setq tagsmatcher
10568 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10569 ;; Make the todo matcher
10570 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10571 (setq todomatcher t)
10572 (setq orterms (org-split-string todomatch "|") orlist nil)
10573 (while (setq term (pop orterms))
10574 (while (string-match re term)
10575 (setq minus (and (match-end 1)
10576 (equal (match-string 1 term) "-"))
10577 kwd (match-string 2 term)
10578 re-p (equal (string-to-char kwd) ?{)
10579 term (substring term (match-end 0))
10580 mm (if re-p
10581 `(string-match ,(substring kwd 1 -1) todo)
10582 (list 'equal 'todo kwd))
10583 mm (if minus (list 'not mm) mm))
10584 (push mm todomatcher))
10585 (push (if (> (length todomatcher) 1)
10586 (cons 'and todomatcher)
10587 (car todomatcher))
10588 orlist)
10589 (setq todomatcher nil))
10590 (setq todomatcher (if (> (length orlist) 1)
10591 (cons 'or orlist) (car orlist))))
10593 ;; Return the string and lisp forms of the matcher
10594 (setq matcher (if todomatcher
10595 (list 'and tagsmatcher todomatcher)
10596 tagsmatcher))
10597 (cons match0 matcher)))
10599 (defun org-op-to-function (op &optional stringp)
10600 "Turn an operator into the appropriate function."
10601 (setq op
10602 (cond
10603 ((equal op "<" ) '(< string< org-time<))
10604 ((equal op ">" ) '(> org-string> org-time>))
10605 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10606 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10607 ((member op '("=" "==")) '(= string= org-time=))
10608 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10609 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10611 (defun org<> (a b) (not (= a b)))
10612 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10613 (defun org-string>= (a b) (not (string< a b)))
10614 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10615 (defun org-string<> (a b) (not (string= a b)))
10616 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10617 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10618 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10619 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10620 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10621 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10622 (defun org-2ft (s)
10623 "Convert S to a floating point time.
10624 If S is already a number, just return it. If it is a string, parse
10625 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10626 (cond
10627 ((numberp s) s)
10628 ((stringp s)
10629 (condition-case nil
10630 (float-time (apply 'encode-time (org-parse-time-string s)))
10631 (error 0.)))
10632 (t 0.)))
10634 (defun org-time-today ()
10635 "Time in seconds today at 0:00.
10636 Returns the float number of seconds since the beginning of the
10637 epoch to the beginning of today (00:00)."
10638 (float-time (apply 'encode-time
10639 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10641 (defun org-matcher-time (s)
10642 "Interpret a time comparison value."
10643 (save-match-data
10644 (cond
10645 ((string= s "<now>") (float-time))
10646 ((string= s "<today>") (org-time-today))
10647 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10648 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10649 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10650 (+ (org-time-today)
10651 (* (string-to-number (match-string 1 s))
10652 (cdr (assoc (match-string 2 s)
10653 '(("d" . 86400.0) ("w" . 604800.0)
10654 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10655 (t (org-2ft s)))))
10657 (defun org-match-any-p (re list)
10658 "Does re match any element of list?"
10659 (setq list (mapcar (lambda (x) (string-match re x)) list))
10660 (delq nil list))
10662 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10663 (defvar org-tags-overlay (org-make-overlay 1 1))
10664 (org-detach-overlay org-tags-overlay)
10666 (defun org-get-local-tags-at (&optional pos)
10667 "Get a list of tags defined in the current headline."
10668 (org-get-tags-at pos 'local))
10670 (defun org-get-local-tags ()
10671 "Get a list of tags defined in the current headline."
10672 (org-get-tags-at nil 'local))
10674 (defun org-get-tags-at (&optional pos local)
10675 "Get a list of all headline tags applicable at POS.
10676 POS defaults to point. If tags are inherited, the list contains
10677 the targets in the same sequence as the headlines appear, i.e.
10678 the tags of the current headline come last.
10679 When LOCAL is non-nil, only return tags from the current headline,
10680 ignore inherited ones."
10681 (interactive)
10682 (if (and org-trust-scanner-tags
10683 (or (not pos) (equal pos (point)))
10684 (not local))
10685 org-scanner-tags
10686 (let (tags ltags lastpos parent)
10687 (save-excursion
10688 (save-restriction
10689 (widen)
10690 (goto-char (or pos (point)))
10691 (save-match-data
10692 (catch 'done
10693 (condition-case nil
10694 (progn
10695 (org-back-to-heading t)
10696 (while (not (equal lastpos (point)))
10697 (setq lastpos (point))
10698 (when (looking-at
10699 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10700 (setq ltags (org-split-string
10701 (org-match-string-no-properties 1) ":"))
10702 (when parent
10703 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10704 (setq tags (append
10705 (if parent
10706 (org-remove-uniherited-tags ltags)
10707 ltags)
10708 tags)))
10709 (or org-use-tag-inheritance (throw 'done t))
10710 (if local (throw 'done t))
10711 (or (org-up-heading-safe) (error nil))
10712 (setq parent t)))
10713 (error nil)))))
10714 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10716 (defun org-add-prop-inherited (s)
10717 (add-text-properties 0 (length s) '(inherited t) s)
10720 (defun org-toggle-tag (tag &optional onoff)
10721 "Toggle the tag TAG for the current line.
10722 If ONOFF is `on' or `off', don't toggle but set to this state."
10723 (let (res current)
10724 (save-excursion
10725 (org-back-to-heading t)
10726 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10727 (point-at-eol) t)
10728 (progn
10729 (setq current (match-string 1))
10730 (replace-match ""))
10731 (setq current ""))
10732 (setq current (nreverse (org-split-string current ":")))
10733 (cond
10734 ((eq onoff 'on)
10735 (setq res t)
10736 (or (member tag current) (push tag current)))
10737 ((eq onoff 'off)
10738 (or (not (member tag current)) (setq current (delete tag current))))
10739 (t (if (member tag current)
10740 (setq current (delete tag current))
10741 (setq res t)
10742 (push tag current))))
10743 (end-of-line 1)
10744 (if current
10745 (progn
10746 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10747 (org-set-tags nil t))
10748 (delete-horizontal-space))
10749 (run-hooks 'org-after-tags-change-hook))
10750 res))
10752 (defun org-align-tags-here (to-col)
10753 ;; Assumes that this is a headline
10754 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10755 (beginning-of-line 1)
10756 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10757 (< pos (match-beginning 2)))
10758 (progn
10759 (setq tags-l (- (match-end 2) (match-beginning 2)))
10760 (goto-char (match-beginning 1))
10761 (insert " ")
10762 (delete-region (point) (1+ (match-beginning 2)))
10763 (setq ncol (max (1+ (current-column))
10764 (1+ col)
10765 (if (> to-col 0)
10766 to-col
10767 (- (abs to-col) tags-l))))
10768 (setq p (point))
10769 (insert (make-string (- ncol (current-column)) ?\ ))
10770 (setq ncol (current-column))
10771 (when indent-tabs-mode (tabify p (point-at-eol)))
10772 (org-move-to-column (min ncol col) t))
10773 (goto-char pos))))
10775 (defun org-set-tags-command (&optional arg just-align)
10776 "Call the set-tags command for the current entry."
10777 (interactive "P")
10778 (if (org-on-heading-p)
10779 (org-set-tags arg just-align)
10780 (save-excursion
10781 (org-back-to-heading t)
10782 (org-set-tags arg just-align))))
10784 (defun org-set-tags (&optional arg just-align)
10785 "Set the tags for the current headline.
10786 With prefix ARG, realign all tags in headings in the current buffer."
10787 (interactive "P")
10788 (let* ((re (concat "^" outline-regexp))
10789 (current (org-get-tags-string))
10790 (col (current-column))
10791 (org-setting-tags t)
10792 table current-tags inherited-tags ; computed below when needed
10793 tags p0 c0 c1 rpl)
10794 (if arg
10795 (save-excursion
10796 (goto-char (point-min))
10797 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10798 (while (re-search-forward re nil t)
10799 (org-set-tags nil t)
10800 (end-of-line 1)))
10801 (message "All tags realigned to column %d" org-tags-column))
10802 (if just-align
10803 (setq tags current)
10804 ;; Get a new set of tags from the user
10805 (save-excursion
10806 (setq table (append org-tag-persistent-alist
10807 (or org-tag-alist (org-get-buffer-tags)))
10808 org-last-tags-completion-table table
10809 current-tags (org-split-string current ":")
10810 inherited-tags (nreverse
10811 (nthcdr (length current-tags)
10812 (nreverse (org-get-tags-at))))
10813 tags
10814 (if (or (eq t org-use-fast-tag-selection)
10815 (and org-use-fast-tag-selection
10816 (delq nil (mapcar 'cdr table))))
10817 (org-fast-tag-selection
10818 current-tags inherited-tags table
10819 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10820 (let ((org-add-colon-after-tag-completion t))
10821 (org-trim
10822 (org-without-partial-completion
10823 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10824 nil nil current 'org-tags-history)))))))
10825 (while (string-match "[-+&]+" tags)
10826 ;; No boolean logic, just a list
10827 (setq tags (replace-match ":" t t tags))))
10829 (if (string-match "\\`[\t ]*\\'" tags)
10830 (setq tags "")
10831 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10832 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10834 ;; Insert new tags at the correct column
10835 (beginning-of-line 1)
10836 (cond
10837 ((and (equal current "") (equal tags "")))
10838 ((re-search-forward
10839 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10840 (point-at-eol) t)
10841 (if (equal tags "")
10842 (setq rpl "")
10843 (goto-char (match-beginning 0))
10844 (setq c0 (current-column) p0 (point)
10845 c1 (max (1+ c0) (if (> org-tags-column 0)
10846 org-tags-column
10847 (- (- org-tags-column) (length tags))))
10848 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10849 (replace-match rpl t t)
10850 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10851 tags)
10852 (t (error "Tags alignment failed")))
10853 (org-move-to-column col)
10854 (unless just-align
10855 (run-hooks 'org-after-tags-change-hook)))))
10857 (defun org-change-tag-in-region (beg end tag off)
10858 "Add or remove TAG for each entry in the region.
10859 This works in the agenda, and also in an org-mode buffer."
10860 (interactive
10861 (list (region-beginning) (region-end)
10862 (let ((org-last-tags-completion-table
10863 (if (org-mode-p)
10864 (org-get-buffer-tags)
10865 (org-global-tags-completion-table))))
10866 (org-ido-completing-read
10867 "Tag: " 'org-tags-completion-function nil nil nil
10868 'org-tags-history))
10869 (progn
10870 (message "[s]et or [r]emove? ")
10871 (equal (read-char-exclusive) ?r))))
10872 (if (fboundp 'deactivate-mark) (deactivate-mark))
10873 (let ((agendap (equal major-mode 'org-agenda-mode))
10874 l1 l2 m buf pos newhead (cnt 0))
10875 (goto-char end)
10876 (setq l2 (1- (org-current-line)))
10877 (goto-char beg)
10878 (setq l1 (org-current-line))
10879 (loop for l from l1 to l2 do
10880 (goto-line l)
10881 (setq m (get-text-property (point) 'org-hd-marker))
10882 (when (or (and (org-mode-p) (org-on-heading-p))
10883 (and agendap m))
10884 (setq buf (if agendap (marker-buffer m) (current-buffer))
10885 pos (if agendap m (point)))
10886 (with-current-buffer buf
10887 (save-excursion
10888 (save-restriction
10889 (goto-char pos)
10890 (setq cnt (1+ cnt))
10891 (org-toggle-tag tag (if off 'off 'on))
10892 (setq newhead (org-get-heading)))))
10893 (and agendap (org-agenda-change-all-lines newhead m))))
10894 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10896 (defun org-tags-completion-function (string predicate &optional flag)
10897 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10898 (confirm (lambda (x) (stringp (car x)))))
10899 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10900 (setq s1 (match-string 1 string)
10901 s2 (match-string 2 string))
10902 (setq s1 "" s2 string))
10903 (cond
10904 ((eq flag nil)
10905 ;; try completion
10906 (setq rtn (try-completion s2 ctable confirm))
10907 (if (stringp rtn)
10908 (setq rtn
10909 (concat s1 s2 (substring rtn (length s2))
10910 (if (and org-add-colon-after-tag-completion
10911 (assoc rtn ctable))
10912 ":" ""))))
10913 rtn)
10914 ((eq flag t)
10915 ;; all-completions
10916 (all-completions s2 ctable confirm)
10918 ((eq flag 'lambda)
10919 ;; exact match?
10920 (assoc s2 ctable)))
10923 (defun org-fast-tag-insert (kwd tags face &optional end)
10924 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10925 (insert (format "%-12s" (concat kwd ":"))
10926 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10927 (or end "")))
10929 (defun org-fast-tag-show-exit (flag)
10930 (save-excursion
10931 (goto-line 3)
10932 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10933 (replace-match ""))
10934 (when flag
10935 (end-of-line 1)
10936 (org-move-to-column (- (window-width) 19) t)
10937 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10939 (defun org-set-current-tags-overlay (current prefix)
10940 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10941 (if (featurep 'xemacs)
10942 (org-overlay-display org-tags-overlay (concat prefix s)
10943 'secondary-selection)
10944 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10945 (org-overlay-display org-tags-overlay (concat prefix s)))))
10947 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10948 "Fast tag selection with single keys.
10949 CURRENT is the current list of tags in the headline, INHERITED is the
10950 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10951 possibly with grouping information. TODO-TABLE is a similar table with
10952 TODO keywords, should these have keys assigned to them.
10953 If the keys are nil, a-z are automatically assigned.
10954 Returns the new tags string, or nil to not change the current settings."
10955 (let* ((fulltable (append table todo-table))
10956 (maxlen (apply 'max (mapcar
10957 (lambda (x)
10958 (if (stringp (car x)) (string-width (car x)) 0))
10959 fulltable)))
10960 (buf (current-buffer))
10961 (expert (eq org-fast-tag-selection-single-key 'expert))
10962 (buffer-tags nil)
10963 (fwidth (+ maxlen 3 1 3))
10964 (ncol (/ (- (window-width) 4) fwidth))
10965 (i-face 'org-done)
10966 (c-face 'org-todo)
10967 tg cnt e c char c1 c2 ntable tbl rtn
10968 ov-start ov-end ov-prefix
10969 (exit-after-next org-fast-tag-selection-single-key)
10970 (done-keywords org-done-keywords)
10971 groups ingroup)
10972 (save-excursion
10973 (beginning-of-line 1)
10974 (if (looking-at
10975 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10976 (setq ov-start (match-beginning 1)
10977 ov-end (match-end 1)
10978 ov-prefix "")
10979 (setq ov-start (1- (point-at-eol))
10980 ov-end (1+ ov-start))
10981 (skip-chars-forward "^\n\r")
10982 (setq ov-prefix
10983 (concat
10984 (buffer-substring (1- (point)) (point))
10985 (if (> (current-column) org-tags-column)
10987 (make-string (- org-tags-column (current-column)) ?\ ))))))
10988 (org-move-overlay org-tags-overlay ov-start ov-end)
10989 (save-window-excursion
10990 (if expert
10991 (set-buffer (get-buffer-create " *Org tags*"))
10992 (delete-other-windows)
10993 (split-window-vertically)
10994 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10995 (erase-buffer)
10996 (org-set-local 'org-done-keywords done-keywords)
10997 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10998 (org-fast-tag-insert "Current" current c-face "\n\n")
10999 (org-fast-tag-show-exit exit-after-next)
11000 (org-set-current-tags-overlay current ov-prefix)
11001 (setq tbl fulltable char ?a cnt 0)
11002 (while (setq e (pop tbl))
11003 (cond
11004 ((equal e '(:startgroup))
11005 (push '() groups) (setq ingroup t)
11006 (when (not (= cnt 0))
11007 (setq cnt 0)
11008 (insert "\n"))
11009 (insert "{ "))
11010 ((equal e '(:endgroup))
11011 (setq ingroup nil cnt 0)
11012 (insert "}\n"))
11013 ((equal e '(:newline))
11014 (when (not (= cnt 0))
11015 (setq cnt 0)
11016 (insert "\n")
11017 (setq e (car tbl))
11018 (while (equal (car tbl) '(:newline))
11019 (insert "\n")
11020 (setq tbl (cdr tbl)))))
11022 (setq tg (car e) c2 nil)
11023 (if (cdr e)
11024 (setq c (cdr e))
11025 ;; automatically assign a character.
11026 (setq c1 (string-to-char
11027 (downcase (substring
11028 tg (if (= (string-to-char tg) ?@) 1 0)))))
11029 (if (or (rassoc c1 ntable) (rassoc c1 table))
11030 (while (or (rassoc char ntable) (rassoc char table))
11031 (setq char (1+ char)))
11032 (setq c2 c1))
11033 (setq c (or c2 char)))
11034 (if ingroup (push tg (car groups)))
11035 (setq tg (org-add-props tg nil 'face
11036 (cond
11037 ((not (assoc tg table))
11038 (org-get-todo-face tg))
11039 ((member tg current) c-face)
11040 ((member tg inherited) i-face)
11041 (t nil))))
11042 (if (and (= cnt 0) (not ingroup)) (insert " "))
11043 (insert "[" c "] " tg (make-string
11044 (- fwidth 4 (length tg)) ?\ ))
11045 (push (cons tg c) ntable)
11046 (when (= (setq cnt (1+ cnt)) ncol)
11047 (insert "\n")
11048 (if ingroup (insert " "))
11049 (setq cnt 0)))))
11050 (setq ntable (nreverse ntable))
11051 (insert "\n")
11052 (goto-char (point-min))
11053 (if (not expert) (org-fit-window-to-buffer))
11054 (setq rtn
11055 (catch 'exit
11056 (while t
11057 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11058 (if groups " [!] no groups" " [!]groups")
11059 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11060 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11061 (cond
11062 ((= c ?\r) (throw 'exit t))
11063 ((= c ?!)
11064 (setq groups (not groups))
11065 (goto-char (point-min))
11066 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11067 ((= c ?\C-c)
11068 (if (not expert)
11069 (org-fast-tag-show-exit
11070 (setq exit-after-next (not exit-after-next)))
11071 (setq expert nil)
11072 (delete-other-windows)
11073 (split-window-vertically)
11074 (org-switch-to-buffer-other-window " *Org tags*")
11075 (org-fit-window-to-buffer)))
11076 ((or (= c ?\C-g)
11077 (and (= c ?q) (not (rassoc c ntable))))
11078 (org-detach-overlay org-tags-overlay)
11079 (setq quit-flag t))
11080 ((= c ?\ )
11081 (setq current nil)
11082 (if exit-after-next (setq exit-after-next 'now)))
11083 ((= c ?\t)
11084 (condition-case nil
11085 (setq tg (org-ido-completing-read
11086 "Tag: "
11087 (or buffer-tags
11088 (with-current-buffer buf
11089 (org-get-buffer-tags)))))
11090 (quit (setq tg "")))
11091 (when (string-match "\\S-" tg)
11092 (add-to-list 'buffer-tags (list tg))
11093 (if (member tg current)
11094 (setq current (delete tg current))
11095 (push tg current)))
11096 (if exit-after-next (setq exit-after-next 'now)))
11097 ((setq e (rassoc c todo-table) tg (car e))
11098 (with-current-buffer buf
11099 (save-excursion (org-todo tg)))
11100 (if exit-after-next (setq exit-after-next 'now)))
11101 ((setq e (rassoc c ntable) tg (car e))
11102 (if (member tg current)
11103 (setq current (delete tg current))
11104 (loop for g in groups do
11105 (if (member tg g)
11106 (mapc (lambda (x)
11107 (setq current (delete x current)))
11108 g)))
11109 (push tg current))
11110 (if exit-after-next (setq exit-after-next 'now))))
11112 ;; Create a sorted list
11113 (setq current
11114 (sort current
11115 (lambda (a b)
11116 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11117 (if (eq exit-after-next 'now) (throw 'exit t))
11118 (goto-char (point-min))
11119 (beginning-of-line 2)
11120 (delete-region (point) (point-at-eol))
11121 (org-fast-tag-insert "Current" current c-face)
11122 (org-set-current-tags-overlay current ov-prefix)
11123 (while (re-search-forward
11124 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11125 (setq tg (match-string 1))
11126 (add-text-properties
11127 (match-beginning 1) (match-end 1)
11128 (list 'face
11129 (cond
11130 ((member tg current) c-face)
11131 ((member tg inherited) i-face)
11132 (t (get-text-property (match-beginning 1) 'face))))))
11133 (goto-char (point-min)))))
11134 (org-detach-overlay org-tags-overlay)
11135 (if rtn
11136 (mapconcat 'identity current ":")
11137 nil))))
11139 (defun org-get-tags-string ()
11140 "Get the TAGS string in the current headline."
11141 (unless (org-on-heading-p t)
11142 (error "Not on a heading"))
11143 (save-excursion
11144 (beginning-of-line 1)
11145 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11146 (org-match-string-no-properties 1)
11147 "")))
11149 (defun org-get-tags ()
11150 "Get the list of tags specified in the current headline."
11151 (org-split-string (org-get-tags-string) ":"))
11153 (defun org-get-buffer-tags ()
11154 "Get a table of all tags used in the buffer, for completion."
11155 (let (tags)
11156 (save-excursion
11157 (goto-char (point-min))
11158 (while (re-search-forward
11159 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11160 (when (equal (char-after (point-at-bol 0)) ?*)
11161 (mapc (lambda (x) (add-to-list 'tags x))
11162 (org-split-string (org-match-string-no-properties 1) ":")))))
11163 (mapcar 'list tags)))
11165 ;;;; The mapping API
11167 ;;;###autoload
11168 (defun org-map-entries (func &optional match scope &rest skip)
11169 "Call FUNC at each headline selected by MATCH in SCOPE.
11171 FUNC is a function or a lisp form. The function will be called without
11172 arguments, with the cursor positioned at the beginning of the headline.
11173 The return values of all calls to the function will be collected and
11174 returned as a list.
11176 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11177 does not need to preserve point. After evaluaton, the cursor will be
11178 moved to the end of the line (presumably of the headline of the
11179 processed entry) and search continues from there. Under some
11180 circumstances, this may not produce the wanted results. For example,
11181 if you have removed (e.g. archived) the current (sub)tree it could
11182 mean that the next entry will be skipped entirely. In such cases, you
11183 can specify the position from where search should continue by making
11184 FUNC set the variable `org-map-continue-from' to the desired buffer
11185 position.
11187 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11188 Only headlines that are matched by this query will be considered during
11189 the iteration. When MATCH is nil or t, all headlines will be
11190 visited by the iteration.
11192 SCOPE determines the scope of this command. It can be any of:
11194 nil The current buffer, respecting the restriction if any
11195 tree The subtree started with the entry at point
11196 file The current buffer, without restriction
11197 file-with-archives
11198 The current buffer, and any archives associated with it
11199 agenda All agenda files
11200 agenda-with-archives
11201 All agenda files with any archive files associated with them
11202 \(file1 file2 ...)
11203 If this is a list, all files in the list will be scanned
11205 The remaining args are treated as settings for the skipping facilities of
11206 the scanner. The following items can be given here:
11208 archive skip trees with the archive tag.
11209 comment skip trees with the COMMENT keyword
11210 function or Emacs Lisp form:
11211 will be used as value for `org-agenda-skip-function', so whenever
11212 the the function returns t, FUNC will not be called for that
11213 entry and search will continue from the point where the
11214 function leaves it.
11216 If your function needs to retrieve the tags including inherited tags
11217 at the *current* entry, you can use the value of the variable
11218 `org-scanner-tags' which will be much faster than getting the value
11219 with `org-get-tags-at'. If your function gets properties with
11220 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11221 to t around the call to `org-entry-properties' to get the same speedup.
11222 Note that if your function moves around to retrieve tags and properties at
11223 a *different* entry, you cannot use these techniques."
11224 (let* ((org-agenda-archives-mode nil) ; just to make sure
11225 (org-agenda-skip-archived-trees (memq 'archive skip))
11226 (org-agenda-skip-comment-trees (memq 'comment skip))
11227 (org-agenda-skip-function
11228 (car (org-delete-all '(comment archive) skip)))
11229 (org-tags-match-list-sublevels t)
11230 matcher file res
11231 org-todo-keywords-for-agenda
11232 org-done-keywords-for-agenda
11233 org-todo-keyword-alist-for-agenda
11234 org-tag-alist-for-agenda)
11236 (cond
11237 ((eq match t) (setq matcher t))
11238 ((eq match nil) (setq matcher t))
11239 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11241 (save-excursion
11242 (save-restriction
11243 (when (eq scope 'tree)
11244 (org-back-to-heading t)
11245 (org-narrow-to-subtree)
11246 (setq scope nil))
11248 (if (not scope)
11249 (progn
11250 (org-prepare-agenda-buffers
11251 (list (buffer-file-name (current-buffer))))
11252 (setq res (org-scan-tags func matcher)))
11253 ;; Get the right scope
11254 (cond
11255 ((and scope (listp scope) (symbolp (car scope)))
11256 (setq scope (eval scope)))
11257 ((eq scope 'agenda)
11258 (setq scope (org-agenda-files t)))
11259 ((eq scope 'agenda-with-archives)
11260 (setq scope (org-agenda-files t))
11261 (setq scope (org-add-archive-files scope)))
11262 ((eq scope 'file)
11263 (setq scope (list (buffer-file-name))))
11264 ((eq scope 'file-with-archives)
11265 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11266 (org-prepare-agenda-buffers scope)
11267 (while (setq file (pop scope))
11268 (with-current-buffer (org-find-base-buffer-visiting file)
11269 (save-excursion
11270 (save-restriction
11271 (widen)
11272 (goto-char (point-min))
11273 (setq res (append res (org-scan-tags func matcher))))))))))
11274 res))
11276 ;;;; Properties
11278 ;;; Setting and retrieving properties
11280 (defconst org-special-properties
11281 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11282 "TIMESTAMP" "TIMESTAMP_IA")
11283 "The special properties valid in Org-mode.
11285 These are properties that are not defined in the property drawer,
11286 but in some other way.")
11288 (defconst org-default-properties
11289 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11290 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11291 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11292 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11293 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11294 "CLOCK_MODELINE_TOTAL")
11295 "Some properties that are used by Org-mode for various purposes.
11296 Being in this list makes sure that they are offered for completion.")
11298 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11299 "Regular expression matching the first line of a property drawer.")
11301 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11302 "Regular expression matching the first line of a property drawer.")
11304 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11305 "Regular expression matching the first line of a property drawer.")
11307 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11308 "Regular expression matching the first line of a property drawer.")
11310 (defconst org-property-drawer-re
11311 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11312 org-property-end-re "\\)\n?")
11313 "Matches an entire property drawer.")
11315 (defconst org-clock-drawer-re
11316 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11317 org-property-end-re "\\)\n?")
11318 "Matches an entire clock drawer.")
11320 (defun org-property-action ()
11321 "Do an action on properties."
11322 (interactive)
11323 (let (c)
11324 (org-at-property-p)
11325 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11326 (setq c (read-char-exclusive))
11327 (cond
11328 ((equal c ?s)
11329 (call-interactively 'org-set-property))
11330 ((equal c ?d)
11331 (call-interactively 'org-delete-property))
11332 ((equal c ?D)
11333 (call-interactively 'org-delete-property-globally))
11334 ((equal c ?c)
11335 (call-interactively 'org-compute-property-at-point))
11336 (t (error "No such property action %c" c)))))
11338 (defun org-at-property-p ()
11339 "Is the cursor in a property line?"
11340 ;; FIXME: Does not check if we are actually in the drawer.
11341 ;; FIXME: also returns true on any drawers.....
11342 ;; This is used by C-c C-c for property action.
11343 (save-excursion
11344 (beginning-of-line 1)
11345 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11347 (defun org-get-property-block (&optional beg end force)
11348 "Return the (beg . end) range of the body of the property drawer.
11349 BEG and END can be beginning and end of subtree, if not given
11350 they will be found.
11351 If the drawer does not exist and FORCE is non-nil, create the drawer."
11352 (catch 'exit
11353 (save-excursion
11354 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11355 (end (or end (progn (outline-next-heading) (point)))))
11356 (goto-char beg)
11357 (if (re-search-forward org-property-start-re end t)
11358 (setq beg (1+ (match-end 0)))
11359 (if force
11360 (save-excursion
11361 (org-insert-property-drawer)
11362 (setq end (progn (outline-next-heading) (point))))
11363 (throw 'exit nil))
11364 (goto-char beg)
11365 (if (re-search-forward org-property-start-re end t)
11366 (setq beg (1+ (match-end 0)))))
11367 (if (re-search-forward org-property-end-re end t)
11368 (setq end (match-beginning 0))
11369 (or force (throw 'exit nil))
11370 (goto-char beg)
11371 (setq end beg)
11372 (org-indent-line-function)
11373 (insert ":END:\n"))
11374 (cons beg end)))))
11376 (defun org-entry-properties (&optional pom which)
11377 "Get all properties of the entry at point-or-marker POM.
11378 This includes the TODO keyword, the tags, time strings for deadline,
11379 scheduled, and clocking, and any additional properties defined in the
11380 entry. The return value is an alist, keys may occur multiple times
11381 if the property key was used several times.
11382 POM may also be nil, in which case the current entry is used.
11383 If WHICH is nil or `all', get all properties. If WHICH is
11384 `special' or `standard', only get that subclass."
11385 (setq which (or which 'all))
11386 (org-with-point-at pom
11387 (let ((clockstr (substring org-clock-string 0 -1))
11388 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11389 beg end range props sum-props key value string clocksum)
11390 (save-excursion
11391 (when (condition-case nil
11392 (and (org-mode-p) (org-back-to-heading t))
11393 (error nil))
11394 (setq beg (point))
11395 (setq sum-props (get-text-property (point) 'org-summaries))
11396 (setq clocksum (get-text-property (point) :org-clock-minutes))
11397 (outline-next-heading)
11398 (setq end (point))
11399 (when (memq which '(all special))
11400 ;; Get the special properties, like TODO and tags
11401 (goto-char beg)
11402 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11403 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11404 (when (looking-at org-priority-regexp)
11405 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11406 (when (and (setq value (org-get-tags-string))
11407 (string-match "\\S-" value))
11408 (push (cons "TAGS" value) props))
11409 (when (setq value (org-get-tags-at))
11410 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11411 props))
11412 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11413 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11414 string (if (equal key clockstr)
11415 (org-no-properties
11416 (org-trim
11417 (buffer-substring
11418 (match-beginning 3) (goto-char (point-at-eol)))))
11419 (substring (org-match-string-no-properties 3) 1 -1)))
11420 (unless key
11421 (if (= (char-after (match-beginning 3)) ?\[)
11422 (setq key "TIMESTAMP_IA")
11423 (setq key "TIMESTAMP")))
11424 (when (or (equal key clockstr) (not (assoc key props)))
11425 (push (cons key string) props)))
11429 (when (memq which '(all standard))
11430 ;; Get the standard properties, like :PROP: ...
11431 (setq range (org-get-property-block beg end))
11432 (when range
11433 (goto-char (car range))
11434 (while (re-search-forward
11435 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11436 (cdr range) t)
11437 (setq key (org-match-string-no-properties 1)
11438 value (org-trim (or (org-match-string-no-properties 2) "")))
11439 (unless (member key excluded)
11440 (push (cons key (or value "")) props)))))
11441 (if clocksum
11442 (push (cons "CLOCKSUM"
11443 (org-columns-number-to-string (/ (float clocksum) 60.)
11444 'add_times))
11445 props))
11446 (unless (assoc "CATEGORY" props)
11447 (setq value (or (org-get-category)
11448 (progn (org-refresh-category-properties)
11449 (org-get-category))))
11450 (push (cons "CATEGORY" value) props))
11451 (append sum-props (nreverse props)))))))
11453 (defun org-entry-get (pom property &optional inherit)
11454 "Get value of PROPERTY for entry at point-or-marker POM.
11455 If INHERIT is non-nil and the entry does not have the property,
11456 then also check higher levels of the hierarchy.
11457 If INHERIT is the symbol `selective', use inheritance only if the setting
11458 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11459 If the property is present but empty, the return value is the empty string.
11460 If the property is not present at all, nil is returned."
11461 (org-with-point-at pom
11462 (if (and inherit (if (eq inherit 'selective)
11463 (org-property-inherit-p property)
11465 (org-entry-get-with-inheritance property)
11466 (if (member property org-special-properties)
11467 ;; We need a special property. Use brute force, get all properties.
11468 (cdr (assoc property (org-entry-properties nil 'special)))
11469 (let ((range (org-get-property-block)))
11470 (if (and range
11471 (goto-char (car range))
11472 (re-search-forward
11473 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11474 (cdr range) t))
11475 ;; Found the property, return it.
11476 (if (match-end 1)
11477 (org-match-string-no-properties 1)
11478 "")))))))
11480 (defun org-property-or-variable-value (var &optional inherit)
11481 "Check if there is a property fixing the value of VAR.
11482 If yes, return this value. If not, return the current value of the variable."
11483 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11484 (if (and prop (stringp prop) (string-match "\\S-" prop))
11485 (read prop)
11486 (symbol-value var))))
11488 (defun org-entry-delete (pom property)
11489 "Delete the property PROPERTY from entry at point-or-marker POM."
11490 (org-with-point-at pom
11491 (if (member property org-special-properties)
11492 nil ; cannot delete these properties.
11493 (let ((range (org-get-property-block)))
11494 (if (and range
11495 (goto-char (car range))
11496 (re-search-forward
11497 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11498 (cdr range) t))
11499 (progn
11500 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11502 nil)))))
11504 ;; Multi-values properties are properties that contain multiple values
11505 ;; These values are assumed to be single words, separated by whitespace.
11506 (defun org-entry-add-to-multivalued-property (pom property value)
11507 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11508 (let* ((old (org-entry-get pom property))
11509 (values (and old (org-split-string old "[ \t]"))))
11510 (setq value (org-entry-protect-space value))
11511 (unless (member value values)
11512 (setq values (cons value values))
11513 (org-entry-put pom property
11514 (mapconcat 'identity values " ")))))
11516 (defun org-entry-remove-from-multivalued-property (pom property value)
11517 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11518 (let* ((old (org-entry-get pom property))
11519 (values (and old (org-split-string old "[ \t]"))))
11520 (setq value (org-entry-protect-space value))
11521 (when (member value values)
11522 (setq values (delete value values))
11523 (org-entry-put pom property
11524 (mapconcat 'identity values " ")))))
11526 (defun org-entry-member-in-multivalued-property (pom property value)
11527 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11528 (let* ((old (org-entry-get pom property))
11529 (values (and old (org-split-string old "[ \t]"))))
11530 (setq value (org-entry-protect-space value))
11531 (member value values)))
11533 (defun org-entry-get-multivalued-property (pom property)
11534 "Return a list of values in a multivalued property."
11535 (let* ((value (org-entry-get pom property))
11536 (values (and value (org-split-string value "[ \t]"))))
11537 (mapcar 'org-entry-restore-space values)))
11539 (defun org-entry-put-multivalued-property (pom property &rest values)
11540 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11541 VALUES should be a list of strings. Spaces will be protected."
11542 (org-entry-put pom property
11543 (mapconcat 'org-entry-protect-space values " "))
11544 (let* ((value (org-entry-get pom property))
11545 (values (and value (org-split-string value "[ \t]"))))
11546 (mapcar 'org-entry-restore-space values)))
11548 (defun org-entry-protect-space (s)
11549 "Protect spaces and newline in string S."
11550 (while (string-match " " s)
11551 (setq s (replace-match "%20" t t s)))
11552 (while (string-match "\n" s)
11553 (setq s (replace-match "%0A" t t s)))
11556 (defun org-entry-restore-space (s)
11557 "Restore spaces and newline in string S."
11558 (while (string-match "%20" s)
11559 (setq s (replace-match " " t t s)))
11560 (while (string-match "%0A" s)
11561 (setq s (replace-match "\n" t t s)))
11564 (defvar org-entry-property-inherited-from (make-marker)
11565 "Marker pointing to the entry from where a property was inherited.
11566 Each call to `org-entry-get-with-inheritance' will set this marker to the
11567 location of the entry where the inheritance search matched. If there was
11568 no match, the marker will point nowhere.
11569 Note that also `org-entry-get' calls this function, if the INHERIT flag
11570 is set.")
11572 (defun org-entry-get-with-inheritance (property)
11573 "Get entry property, and search higher levels if not present."
11574 (move-marker org-entry-property-inherited-from nil)
11575 (let (tmp)
11576 (save-excursion
11577 (save-restriction
11578 (widen)
11579 (catch 'ex
11580 (while t
11581 (when (setq tmp (org-entry-get nil property))
11582 (org-back-to-heading t)
11583 (move-marker org-entry-property-inherited-from (point))
11584 (throw 'ex tmp))
11585 (or (org-up-heading-safe) (throw 'ex nil)))))
11586 (or tmp
11587 (cdr (assoc property org-file-properties))
11588 (cdr (assoc property org-global-properties))
11589 (cdr (assoc property org-global-properties-fixed))))))
11591 (defun org-entry-put (pom property value)
11592 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11593 (org-with-point-at pom
11594 (org-back-to-heading t)
11595 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11596 range)
11597 (cond
11598 ((equal property "TODO")
11599 (when (and (stringp value) (string-match "\\S-" value)
11600 (not (member value org-todo-keywords-1)))
11601 (error "\"%s\" is not a valid TODO state" value))
11602 (if (or (not value)
11603 (not (string-match "\\S-" value)))
11604 (setq value 'none))
11605 (org-todo value)
11606 (org-set-tags nil 'align))
11607 ((equal property "PRIORITY")
11608 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11609 (string-to-char value) ?\ ))
11610 (org-set-tags nil 'align))
11611 ((equal property "SCHEDULED")
11612 (if (re-search-forward org-scheduled-time-regexp end t)
11613 (cond
11614 ((eq value 'earlier) (org-timestamp-change -1 'day))
11615 ((eq value 'later) (org-timestamp-change 1 'day))
11616 (t (call-interactively 'org-schedule)))
11617 (call-interactively 'org-schedule)))
11618 ((equal property "DEADLINE")
11619 (if (re-search-forward org-deadline-time-regexp end t)
11620 (cond
11621 ((eq value 'earlier) (org-timestamp-change -1 'day))
11622 ((eq value 'later) (org-timestamp-change 1 'day))
11623 (t (call-interactively 'org-deadline)))
11624 (call-interactively 'org-deadline)))
11625 ((member property org-special-properties)
11626 (error "The %s property can not yet be set with `org-entry-put'"
11627 property))
11628 (t ; a non-special property
11629 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11630 (setq range (org-get-property-block beg end 'force))
11631 (goto-char (car range))
11632 (if (re-search-forward
11633 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11634 (progn
11635 (delete-region (match-beginning 1) (match-end 1))
11636 (goto-char (match-beginning 1)))
11637 (goto-char (cdr range))
11638 (insert "\n")
11639 (backward-char 1)
11640 (org-indent-line-function)
11641 (insert ":" property ":"))
11642 (and value (insert " " value))
11643 (org-indent-line-function)))))))
11645 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11646 "Get all property keys in the current buffer.
11647 With INCLUDE-SPECIALS, also list the special properties that reflect things
11648 like tags and TODO state.
11649 With INCLUDE-DEFAULTS, also include properties that has special meaning
11650 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11651 With INCLUDE-COLUMNS, also include property names given in COLUMN
11652 formats in the current buffer."
11653 (let (rtn range cfmt s p)
11654 (save-excursion
11655 (save-restriction
11656 (widen)
11657 (goto-char (point-min))
11658 (while (re-search-forward org-property-start-re nil t)
11659 (setq range (org-get-property-block))
11660 (goto-char (car range))
11661 (while (re-search-forward
11662 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11663 (cdr range) t)
11664 (add-to-list 'rtn (org-match-string-no-properties 1)))
11665 (outline-next-heading))))
11667 (when include-specials
11668 (setq rtn (append org-special-properties rtn)))
11670 (when include-defaults
11671 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
11672 (add-to-list 'rtn org-effort-property))
11674 (when include-columns
11675 (save-excursion
11676 (save-restriction
11677 (widen)
11678 (goto-char (point-min))
11679 (while (re-search-forward
11680 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11681 nil t)
11682 (setq cfmt (match-string 2) s 0)
11683 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11684 cfmt s)
11685 (setq s (match-end 0)
11686 p (match-string 1 cfmt))
11687 (unless (or (equal p "ITEM")
11688 (member p org-special-properties))
11689 (add-to-list 'rtn (match-string 1 cfmt))))))))
11691 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11693 (defun org-property-values (key)
11694 "Return a list of all values of property KEY."
11695 (save-excursion
11696 (save-restriction
11697 (widen)
11698 (goto-char (point-min))
11699 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11700 values)
11701 (while (re-search-forward re nil t)
11702 (add-to-list 'values (org-trim (match-string 1))))
11703 (delete "" values)))))
11705 (defun org-insert-property-drawer ()
11706 "Insert a property drawer into the current entry."
11707 (interactive)
11708 (org-back-to-heading t)
11709 (looking-at outline-regexp)
11710 (let ((indent (if org-adapt-indentation
11711 (- (match-end 0)(match-beginning 0))
11713 (beg (point))
11714 (re (concat "^[ \t]*" org-keyword-time-regexp))
11715 end hiddenp)
11716 (outline-next-heading)
11717 (setq end (point))
11718 (goto-char beg)
11719 (while (re-search-forward re end t))
11720 (setq hiddenp (org-invisible-p))
11721 (end-of-line 1)
11722 (and (equal (char-after) ?\n) (forward-char 1))
11723 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11724 (if (member (match-string 1) '("CLOCK:" ":END:"))
11725 ;; just skip this line
11726 (beginning-of-line 2)
11727 ;; Drawer start, find the end
11728 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11729 (beginning-of-line 1)))
11730 (org-skip-over-state-notes)
11731 (skip-chars-backward " \t\n\r")
11732 (if (eq (char-before) ?*) (forward-char 1))
11733 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11734 (beginning-of-line 0)
11735 (org-indent-to-column indent)
11736 (beginning-of-line 2)
11737 (org-indent-to-column indent)
11738 (beginning-of-line 0)
11739 (if hiddenp
11740 (save-excursion
11741 (org-back-to-heading t)
11742 (hide-entry))
11743 (org-flag-drawer t))))
11745 (defun org-set-property (property value)
11746 "In the current entry, set PROPERTY to VALUE.
11747 When called interactively, this will prompt for a property name, offering
11748 completion on existing and default properties. And then it will prompt
11749 for a value, offering completion either on allowed values (via an inherited
11750 xxx_ALL property) or on existing values in other instances of this property
11751 in the current file."
11752 (interactive
11753 (let* ((completion-ignore-case t)
11754 (keys (org-buffer-property-keys nil t t))
11755 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11756 (prop (if (member prop0 keys)
11757 prop0
11758 (or (cdr (assoc (downcase prop0)
11759 (mapcar (lambda (x) (cons (downcase x) x))
11760 keys)))
11761 prop0)))
11762 (cur (org-entry-get nil prop))
11763 (allowed (org-property-get-allowed-values nil prop 'table))
11764 (existing (mapcar 'list (org-property-values prop)))
11765 (val (if allowed
11766 (org-completing-read "Value: " allowed nil 'req-match)
11767 (let (org-completion-use-ido)
11768 (org-completing-read
11769 (concat "Value" (if (and cur (string-match "\\S-" cur))
11770 (concat "[" cur "]") "")
11771 ": ")
11772 existing nil nil "" nil cur)))))
11773 (list prop (if (equal val "") cur val))))
11774 (unless (equal (org-entry-get nil property) value)
11775 (org-entry-put nil property value)))
11777 (defun org-delete-property (property)
11778 "In the current entry, delete PROPERTY."
11779 (interactive
11780 (let* ((completion-ignore-case t)
11781 (prop (org-ido-completing-read
11782 "Property: " (org-entry-properties nil 'standard))))
11783 (list prop)))
11784 (message "Property %s %s" property
11785 (if (org-entry-delete nil property)
11786 "deleted"
11787 "was not present in the entry")))
11789 (defun org-delete-property-globally (property)
11790 "Remove PROPERTY globally, from all entries."
11791 (interactive
11792 (let* ((completion-ignore-case t)
11793 (prop (org-ido-completing-read
11794 "Globally remove property: "
11795 (mapcar 'list (org-buffer-property-keys)))))
11796 (list prop)))
11797 (save-excursion
11798 (save-restriction
11799 (widen)
11800 (goto-char (point-min))
11801 (let ((cnt 0))
11802 (while (re-search-forward
11803 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11804 nil t)
11805 (setq cnt (1+ cnt))
11806 (replace-match ""))
11807 (message "Property \"%s\" removed from %d entries" property cnt)))))
11809 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11811 (defun org-compute-property-at-point ()
11812 "Compute the property at point.
11813 This looks for an enclosing column format, extracts the operator and
11814 then applies it to the property in the column format's scope."
11815 (interactive)
11816 (unless (org-at-property-p)
11817 (error "Not at a property"))
11818 (let ((prop (org-match-string-no-properties 2)))
11819 (org-columns-get-format-and-top-level)
11820 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11821 (error "No operator defined for property %s" prop))
11822 (org-columns-compute prop)))
11824 (defun org-property-get-allowed-values (pom property &optional table)
11825 "Get allowed values for the property PROPERTY.
11826 When TABLE is non-nil, return an alist that can directly be used for
11827 completion."
11828 (let (vals)
11829 (cond
11830 ((equal property "TODO")
11831 (setq vals (org-with-point-at pom
11832 (append org-todo-keywords-1 '("")))))
11833 ((equal property "PRIORITY")
11834 (let ((n org-lowest-priority))
11835 (while (>= n org-highest-priority)
11836 (push (char-to-string n) vals)
11837 (setq n (1- n)))))
11838 ((member property org-special-properties))
11840 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11842 (when (and vals (string-match "\\S-" vals))
11843 (setq vals (car (read-from-string (concat "(" vals ")"))))
11844 (setq vals (mapcar (lambda (x)
11845 (cond ((stringp x) x)
11846 ((numberp x) (number-to-string x))
11847 ((symbolp x) (symbol-name x))
11848 (t "???")))
11849 vals)))))
11850 (if table (mapcar 'list vals) vals)))
11852 (defun org-property-previous-allowed-value (&optional previous)
11853 "Switch to the next allowed value for this property."
11854 (interactive)
11855 (org-property-next-allowed-value t))
11857 (defun org-property-next-allowed-value (&optional previous)
11858 "Switch to the next allowed value for this property."
11859 (interactive)
11860 (unless (org-at-property-p)
11861 (error "Not at a property"))
11862 (let* ((key (match-string 2))
11863 (value (match-string 3))
11864 (allowed (or (org-property-get-allowed-values (point) key)
11865 (and (member value '("[ ]" "[-]" "[X]"))
11866 '("[ ]" "[X]"))))
11867 nval)
11868 (unless allowed
11869 (error "Allowed values for this property have not been defined"))
11870 (if previous (setq allowed (reverse allowed)))
11871 (if (member value allowed)
11872 (setq nval (car (cdr (member value allowed)))))
11873 (setq nval (or nval (car allowed)))
11874 (if (equal nval value)
11875 (error "Only one allowed value for this property"))
11876 (org-at-property-p)
11877 (replace-match (concat " :" key ": " nval) t t)
11878 (org-indent-line-function)
11879 (beginning-of-line 1)
11880 (skip-chars-forward " \t")))
11882 (defun org-find-entry-with-id (ident)
11883 "Locate the entry that contains the ID property with exact value IDENT.
11884 IDENT can be a string, a symbol or a number, this function will search for
11885 the string representation of it.
11886 Return the position where this entry starts, or nil if there is no such entry."
11887 (interactive "sID: ")
11888 (let ((id (cond
11889 ((stringp ident) ident)
11890 ((symbol-name ident) (symbol-name ident))
11891 ((numberp ident) (number-to-string ident))
11892 (t (error "IDENT %s must be a string, symbol or number" ident))))
11893 (case-fold-search nil))
11894 (save-excursion
11895 (save-restriction
11896 (widen)
11897 (goto-char (point-min))
11898 (when (re-search-forward
11899 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11900 nil t)
11901 (org-back-to-heading t)
11902 (point))))))
11904 ;;;; Timestamps
11906 (defvar org-last-changed-timestamp nil)
11907 (defvar org-last-inserted-timestamp nil
11908 "The last time stamp inserted with `org-insert-time-stamp'.")
11909 (defvar org-time-was-given) ; dynamically scoped parameter
11910 (defvar org-end-time-was-given) ; dynamically scoped parameter
11911 (defvar org-ts-what) ; dynamically scoped parameter
11913 (defun org-time-stamp (arg &optional inactive)
11914 "Prompt for a date/time and insert a time stamp.
11915 If the user specifies a time like HH:MM, or if this command is called
11916 with a prefix argument, the time stamp will contain date and time.
11917 Otherwise, only the date will be included. All parts of a date not
11918 specified by the user will be filled in from the current date/time.
11919 So if you press just return without typing anything, the time stamp
11920 will represent the current date/time. If there is already a timestamp
11921 at the cursor, it will be modified."
11922 (interactive "P")
11923 (let* ((ts nil)
11924 (default-time
11925 ;; Default time is either today, or, when entering a range,
11926 ;; the range start.
11927 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11928 (save-excursion
11929 (re-search-backward
11930 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11931 (- (point) 20) t)))
11932 (apply 'encode-time (org-parse-time-string (match-string 1)))
11933 (current-time)))
11934 (default-input (and ts (org-get-compact-tod ts)))
11935 org-time-was-given org-end-time-was-given time)
11936 (cond
11937 ((and (org-at-timestamp-p t)
11938 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11939 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11940 (insert "--")
11941 (setq time (let ((this-command this-command))
11942 (org-read-date arg 'totime nil nil
11943 default-time default-input)))
11944 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11945 ((org-at-timestamp-p t)
11946 (setq time (let ((this-command this-command))
11947 (org-read-date arg 'totime nil nil default-time default-input)))
11948 (when (org-at-timestamp-p t) ; just to get the match data
11949 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11950 (replace-match "")
11951 (setq org-last-changed-timestamp
11952 (org-insert-time-stamp
11953 time (or org-time-was-given arg)
11954 inactive nil nil (list org-end-time-was-given))))
11955 (message "Timestamp updated"))
11957 (setq time (let ((this-command this-command))
11958 (org-read-date arg 'totime nil nil default-time default-input)))
11959 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11960 nil nil (list org-end-time-was-given))))))
11962 ;; FIXME: can we use this for something else, like computing time differences?
11963 (defun org-get-compact-tod (s)
11964 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11965 (let* ((t1 (match-string 1 s))
11966 (h1 (string-to-number (match-string 2 s)))
11967 (m1 (string-to-number (match-string 3 s)))
11968 (t2 (and (match-end 4) (match-string 5 s)))
11969 (h2 (and t2 (string-to-number (match-string 6 s))))
11970 (m2 (and t2 (string-to-number (match-string 7 s))))
11971 dh dm)
11972 (if (not t2)
11974 (setq dh (- h2 h1) dm (- m2 m1))
11975 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11976 (concat t1 "+" (number-to-string dh)
11977 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11979 (defun org-time-stamp-inactive (&optional arg)
11980 "Insert an inactive time stamp.
11981 An inactive time stamp is enclosed in square brackets instead of angle
11982 brackets. It is inactive in the sense that it does not trigger agenda entries,
11983 does not link to the calendar and cannot be changed with the S-cursor keys.
11984 So these are more for recording a certain time/date."
11985 (interactive "P")
11986 (org-time-stamp arg 'inactive))
11988 (defvar org-date-ovl (org-make-overlay 1 1))
11989 (org-overlay-put org-date-ovl 'face 'org-warning)
11990 (org-detach-overlay org-date-ovl)
11992 (defvar org-ans1) ; dynamically scoped parameter
11993 (defvar org-ans2) ; dynamically scoped parameter
11995 (defvar org-plain-time-of-day-regexp) ; defined below
11997 (defvar org-overriding-default-time nil) ; dynamically scoped
11998 (defvar org-read-date-overlay nil)
11999 (defvar org-dcst nil) ; dynamically scoped
12000 (defvar org-read-date-history nil)
12002 (defun org-read-date (&optional with-time to-time from-string prompt
12003 default-time default-input)
12004 "Read a date, possibly a time, and make things smooth for the user.
12005 The prompt will suggest to enter an ISO date, but you can also enter anything
12006 which will at least partially be understood by `parse-time-string'.
12007 Unrecognized parts of the date will default to the current day, month, year,
12008 hour and minute. If this command is called to replace a timestamp at point,
12009 of to enter the second timestamp of a range, the default time is taken from the
12010 existing stamp. For example,
12011 3-2-5 --> 2003-02-05
12012 feb 15 --> currentyear-02-15
12013 sep 12 9 --> 2009-09-12
12014 12:45 --> today 12:45
12015 22 sept 0:34 --> currentyear-09-22 0:34
12016 12 --> currentyear-currentmonth-12
12017 Fri --> nearest Friday (today or later)
12018 etc.
12020 Furthermore you can specify a relative date by giving, as the *first* thing
12021 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12022 change in days weeks, months, years.
12023 With a single plus or minus, the date is relative to today. With a double
12024 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12025 +4d --> four days from today
12026 +4 --> same as above
12027 +2w --> two weeks from today
12028 ++5 --> five days from default date
12030 The function understands only English month and weekday abbreviations,
12031 but this can be configured with the variables `parse-time-months' and
12032 `parse-time-weekdays'.
12034 While prompting, a calendar is popped up - you can also select the
12035 date with the mouse (button 1). The calendar shows a period of three
12036 months. To scroll it to other months, use the keys `>' and `<'.
12037 If you don't like the calendar, turn it off with
12038 \(setq org-read-date-popup-calendar nil)
12040 With optional argument TO-TIME, the date will immediately be converted
12041 to an internal time.
12042 With an optional argument WITH-TIME, the prompt will suggest to also
12043 insert a time. Note that when WITH-TIME is not set, you can still
12044 enter a time, and this function will inform the calling routine about
12045 this change. The calling routine may then choose to change the format
12046 used to insert the time stamp into the buffer to include the time.
12047 With optional argument FROM-STRING, read from this string instead from
12048 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12049 the time/date that is used for everything that is not specified by the
12050 user."
12051 (require 'parse-time)
12052 (let* ((org-time-stamp-rounding-minutes
12053 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12054 (org-dcst org-display-custom-times)
12055 (ct (org-current-time))
12056 (def (or org-overriding-default-time default-time ct))
12057 (defdecode (decode-time def))
12058 (dummy (progn
12059 (when (< (nth 2 defdecode) org-extend-today-until)
12060 (setcar (nthcdr 2 defdecode) -1)
12061 (setcar (nthcdr 1 defdecode) 59)
12062 (setq def (apply 'encode-time defdecode)
12063 defdecode (decode-time def)))))
12064 (calendar-move-hook nil)
12065 (calendar-view-diary-initially-flag nil)
12066 (view-diary-entries-initially nil)
12067 (calendar-view-holidays-initially-flag nil)
12068 (view-calendar-holidays-initially nil)
12069 (timestr (format-time-string
12070 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12071 (prompt (concat (if prompt (concat prompt " ") "")
12072 (format "Date+time [%s]: " timestr)))
12073 ans (org-ans0 "") org-ans1 org-ans2 final)
12075 (cond
12076 (from-string (setq ans from-string))
12077 (org-read-date-popup-calendar
12078 (save-excursion
12079 (save-window-excursion
12080 (calendar)
12081 (calendar-forward-day (- (time-to-days def)
12082 (calendar-absolute-from-gregorian
12083 (calendar-current-date))))
12084 (org-eval-in-calendar nil t)
12085 (let* ((old-map (current-local-map))
12086 (map (copy-keymap calendar-mode-map))
12087 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12088 (org-defkey map (kbd "RET") 'org-calendar-select)
12089 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12090 'org-calendar-select-mouse)
12091 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12092 'org-calendar-select-mouse)
12093 (org-defkey minibuffer-local-map [(meta shift left)]
12094 (lambda () (interactive)
12095 (org-eval-in-calendar '(calendar-backward-month 1))))
12096 (org-defkey minibuffer-local-map [(meta shift right)]
12097 (lambda () (interactive)
12098 (org-eval-in-calendar '(calendar-forward-month 1))))
12099 (org-defkey minibuffer-local-map [(meta shift up)]
12100 (lambda () (interactive)
12101 (org-eval-in-calendar '(calendar-backward-year 1))))
12102 (org-defkey minibuffer-local-map [(meta shift down)]
12103 (lambda () (interactive)
12104 (org-eval-in-calendar '(calendar-forward-year 1))))
12105 (org-defkey minibuffer-local-map [?\e (shift left)]
12106 (lambda () (interactive)
12107 (org-eval-in-calendar '(calendar-backward-month 1))))
12108 (org-defkey minibuffer-local-map [?\e (shift right)]
12109 (lambda () (interactive)
12110 (org-eval-in-calendar '(calendar-forward-month 1))))
12111 (org-defkey minibuffer-local-map [?\e (shift up)]
12112 (lambda () (interactive)
12113 (org-eval-in-calendar '(calendar-backward-year 1))))
12114 (org-defkey minibuffer-local-map [?\e (shift down)]
12115 (lambda () (interactive)
12116 (org-eval-in-calendar '(calendar-forward-year 1))))
12117 (org-defkey minibuffer-local-map [(shift up)]
12118 (lambda () (interactive)
12119 (org-eval-in-calendar '(calendar-backward-week 1))))
12120 (org-defkey minibuffer-local-map [(shift down)]
12121 (lambda () (interactive)
12122 (org-eval-in-calendar '(calendar-forward-week 1))))
12123 (org-defkey minibuffer-local-map [(shift left)]
12124 (lambda () (interactive)
12125 (org-eval-in-calendar '(calendar-backward-day 1))))
12126 (org-defkey minibuffer-local-map [(shift right)]
12127 (lambda () (interactive)
12128 (org-eval-in-calendar '(calendar-forward-day 1))))
12129 (org-defkey minibuffer-local-map ">"
12130 (lambda () (interactive)
12131 (org-eval-in-calendar '(scroll-calendar-left 1))))
12132 (org-defkey minibuffer-local-map "<"
12133 (lambda () (interactive)
12134 (org-eval-in-calendar '(scroll-calendar-right 1))))
12135 (run-hooks 'org-read-date-minibuffer-setup-hook)
12136 (unwind-protect
12137 (progn
12138 (use-local-map map)
12139 (add-hook 'post-command-hook 'org-read-date-display)
12140 (setq org-ans0 (read-string prompt default-input
12141 'org-read-date-history nil))
12142 ;; org-ans0: from prompt
12143 ;; org-ans1: from mouse click
12144 ;; org-ans2: from calendar motion
12145 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12146 (remove-hook 'post-command-hook 'org-read-date-display)
12147 (use-local-map old-map)
12148 (when org-read-date-overlay
12149 (org-delete-overlay org-read-date-overlay)
12150 (setq org-read-date-overlay nil)))))))
12152 (t ; Naked prompt only
12153 (unwind-protect
12154 (setq ans (read-string prompt default-input
12155 'org-read-date-history timestr))
12156 (when org-read-date-overlay
12157 (org-delete-overlay org-read-date-overlay)
12158 (setq org-read-date-overlay nil)))))
12160 (setq final (org-read-date-analyze ans def defdecode))
12162 (if to-time
12163 (apply 'encode-time final)
12164 (if (and (boundp 'org-time-was-given) org-time-was-given)
12165 (format "%04d-%02d-%02d %02d:%02d"
12166 (nth 5 final) (nth 4 final) (nth 3 final)
12167 (nth 2 final) (nth 1 final))
12168 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12169 (defvar def)
12170 (defvar defdecode)
12171 (defvar with-time)
12172 (defun org-read-date-display ()
12173 "Display the current date prompt interpretation in the minibuffer."
12174 (when org-read-date-display-live
12175 (when org-read-date-overlay
12176 (org-delete-overlay org-read-date-overlay))
12177 (let ((p (point)))
12178 (end-of-line 1)
12179 (while (not (equal (buffer-substring
12180 (max (point-min) (- (point) 4)) (point))
12181 " "))
12182 (insert " "))
12183 (goto-char p))
12184 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12185 " " (or org-ans1 org-ans2)))
12186 (org-end-time-was-given nil)
12187 (f (org-read-date-analyze ans def defdecode))
12188 (fmts (if org-dcst
12189 org-time-stamp-custom-formats
12190 org-time-stamp-formats))
12191 (fmt (if (or with-time
12192 (and (boundp 'org-time-was-given) org-time-was-given))
12193 (cdr fmts)
12194 (car fmts)))
12195 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12196 (when (and org-end-time-was-given
12197 (string-match org-plain-time-of-day-regexp txt))
12198 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12199 org-end-time-was-given
12200 (substring txt (match-end 0)))))
12201 (setq org-read-date-overlay
12202 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12203 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12205 (defun org-read-date-analyze (ans def defdecode)
12206 "Analyse the combined answer of the date prompt."
12207 ;; FIXME: cleanup and comment
12208 (let (delta deltan deltaw deltadef year month day
12209 hour minute second wday pm h2 m2 tl wday1
12210 iso-year iso-weekday iso-week iso-year iso-date)
12212 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12213 (setq ans "+0"))
12215 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12216 (setq ans (replace-match "" t t ans)
12217 deltan (car delta)
12218 deltaw (nth 1 delta)
12219 deltadef (nth 2 delta)))
12221 ;; Check if there is an iso week date in there
12222 ;; If yes, sore the info and postpone interpreting it until the rest
12223 ;; of the parsing is done
12224 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12225 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12226 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12227 iso-week (string-to-number (match-string 2 ans)))
12228 (setq ans (replace-match "" t t ans)))
12230 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12231 (when (string-match
12232 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12233 (setq year (if (match-end 2)
12234 (string-to-number (match-string 2 ans))
12235 (string-to-number (format-time-string "%Y")))
12236 month (string-to-number (match-string 3 ans))
12237 day (string-to-number (match-string 4 ans)))
12238 (if (< year 100) (setq year (+ 2000 year)))
12239 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12240 t nil ans)))
12241 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12242 ;; If there is a time with am/pm, and *no* time without it, we convert
12243 ;; so that matching will be successful.
12244 (loop for i from 1 to 2 do ; twice, for end time as well
12245 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12246 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12247 (setq hour (string-to-number (match-string 1 ans))
12248 minute (if (match-end 3)
12249 (string-to-number (match-string 3 ans))
12251 pm (equal ?p
12252 (string-to-char (downcase (match-string 4 ans)))))
12253 (if (and (= hour 12) (not pm))
12254 (setq hour 0)
12255 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12256 (setq ans (replace-match (format "%02d:%02d" hour minute)
12257 t t ans))))
12259 ;; Check if a time range is given as a duration
12260 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12261 (setq hour (string-to-number (match-string 1 ans))
12262 h2 (+ hour (string-to-number (match-string 3 ans)))
12263 minute (string-to-number (match-string 2 ans))
12264 m2 (+ minute (if (match-end 5) (string-to-number
12265 (match-string 5 ans))0)))
12266 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12267 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12268 t t ans)))
12270 ;; Check if there is a time range
12271 (when (boundp 'org-end-time-was-given)
12272 (setq org-time-was-given nil)
12273 (when (and (string-match org-plain-time-of-day-regexp ans)
12274 (match-end 8))
12275 (setq org-end-time-was-given (match-string 8 ans))
12276 (setq ans (concat (substring ans 0 (match-beginning 7))
12277 (substring ans (match-end 7))))))
12279 (setq tl (parse-time-string ans)
12280 day (or (nth 3 tl) (nth 3 defdecode))
12281 month (or (nth 4 tl)
12282 (if (and org-read-date-prefer-future
12283 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12284 (1+ (nth 4 defdecode))
12285 (nth 4 defdecode)))
12286 year (or (nth 5 tl)
12287 (if (and org-read-date-prefer-future
12288 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12289 (1+ (nth 5 defdecode))
12290 (nth 5 defdecode)))
12291 hour (or (nth 2 tl) (nth 2 defdecode))
12292 minute (or (nth 1 tl) (nth 1 defdecode))
12293 second (or (nth 0 tl) 0)
12294 wday (nth 6 tl))
12296 ;; Special date definitions below
12297 (cond
12298 (iso-week
12299 ;; There was an iso week
12300 (setq year (or iso-year year)
12301 day (or iso-weekday wday 1)
12302 wday nil ; to make sure that the trigger below does not match
12303 iso-date (calendar-gregorian-from-absolute
12304 (calendar-absolute-from-iso
12305 (list iso-week day year))))
12306 ; FIXME: Should we also push ISO weeks into the future?
12307 ; (when (and org-read-date-prefer-future
12308 ; (not iso-year)
12309 ; (< (calendar-absolute-from-gregorian iso-date)
12310 ; (time-to-days (current-time))))
12311 ; (setq year (1+ year)
12312 ; iso-date (calendar-gregorian-from-absolute
12313 ; (calendar-absolute-from-iso
12314 ; (list iso-week day year)))))
12315 (setq month (car iso-date)
12316 year (nth 2 iso-date)
12317 day (nth 1 iso-date)))
12318 (deltan
12319 (unless deltadef
12320 (let ((now (decode-time (current-time))))
12321 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12322 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12323 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12324 ((equal deltaw "m") (setq month (+ month deltan)))
12325 ((equal deltaw "y") (setq year (+ year deltan)))))
12326 ((and wday (not (nth 3 tl)))
12327 ;; Weekday was given, but no day, so pick that day in the week
12328 ;; on or after the derived date.
12329 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12330 (unless (equal wday wday1)
12331 (setq day (+ day (% (- wday wday1 -7) 7))))))
12332 (if (and (boundp 'org-time-was-given)
12333 (nth 2 tl))
12334 (setq org-time-was-given t))
12335 (if (< year 100) (setq year (+ 2000 year)))
12336 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12337 (list second minute hour day month year)))
12339 (defvar parse-time-weekdays)
12341 (defun org-read-date-get-relative (s today default)
12342 "Check string S for special relative date string.
12343 TODAY and DEFAULT are internal times, for today and for a default.
12344 Return shift list (N what def-flag)
12345 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12346 N is the number of WHATs to shift.
12347 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12348 the DEFAULT date rather than TODAY."
12349 (when (and
12350 (string-match
12351 (concat
12352 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12353 "\\([0-9]+\\)?"
12354 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12355 "\\([ \t]\\|$\\)") s)
12356 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12357 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12358 (string-to-char (substring (match-string 1 s) -1))
12359 ?+))
12360 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12361 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12362 (what (if (match-end 3) (match-string 3 s) "d"))
12363 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12364 (date (if rel default today))
12365 (wday (nth 6 (decode-time date)))
12366 delta)
12367 (if wday1
12368 (progn
12369 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12370 (if (= dir ?-) (setq delta (- delta 7)))
12371 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12372 (list delta "d" rel))
12373 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12375 (defun org-eval-in-calendar (form &optional keepdate)
12376 "Eval FORM in the calendar window and return to current window.
12377 Also, store the cursor date in variable org-ans2."
12378 (let ((sw (selected-window)))
12379 (select-window (get-buffer-window "*Calendar*"))
12380 (eval form)
12381 (when (and (not keepdate) (calendar-cursor-to-date))
12382 (let* ((date (calendar-cursor-to-date))
12383 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12384 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12385 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12386 (select-window sw)))
12388 (defun org-calendar-select ()
12389 "Return to `org-read-date' with the date currently selected.
12390 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12391 (interactive)
12392 (when (calendar-cursor-to-date)
12393 (let* ((date (calendar-cursor-to-date))
12394 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12395 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12396 (if (active-minibuffer-window) (exit-minibuffer))))
12398 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12399 "Insert a date stamp for the date given by the internal TIME.
12400 WITH-HM means, use the stamp format that includes the time of the day.
12401 INACTIVE means use square brackets instead of angular ones, so that the
12402 stamp will not contribute to the agenda.
12403 PRE and POST are optional strings to be inserted before and after the
12404 stamp.
12405 The command returns the inserted time stamp."
12406 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12407 stamp)
12408 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12409 (insert-before-markers (or pre ""))
12410 (insert-before-markers (setq stamp (format-time-string fmt time)))
12411 (when (listp extra)
12412 (setq extra (car extra))
12413 (if (and (stringp extra)
12414 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12415 (setq extra (format "-%02d:%02d"
12416 (string-to-number (match-string 1 extra))
12417 (string-to-number (match-string 2 extra))))
12418 (setq extra nil)))
12419 (when extra
12420 (backward-char 1)
12421 (insert-before-markers extra)
12422 (forward-char 1))
12423 (insert-before-markers (or post ""))
12424 (setq org-last-inserted-timestamp stamp)))
12426 (defun org-toggle-time-stamp-overlays ()
12427 "Toggle the use of custom time stamp formats."
12428 (interactive)
12429 (setq org-display-custom-times (not org-display-custom-times))
12430 (unless org-display-custom-times
12431 (let ((p (point-min)) (bmp (buffer-modified-p)))
12432 (while (setq p (next-single-property-change p 'display))
12433 (if (and (get-text-property p 'display)
12434 (eq (get-text-property p 'face) 'org-date))
12435 (remove-text-properties
12436 p (setq p (next-single-property-change p 'display))
12437 '(display t))))
12438 (set-buffer-modified-p bmp)))
12439 (if (featurep 'xemacs)
12440 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12441 (org-restart-font-lock)
12442 (setq org-table-may-need-update t)
12443 (if org-display-custom-times
12444 (message "Time stamps are overlayed with custom format")
12445 (message "Time stamp overlays removed")))
12447 (defun org-display-custom-time (beg end)
12448 "Overlay modified time stamp format over timestamp between BEG and END."
12449 (let* ((ts (buffer-substring beg end))
12450 t1 w1 with-hm tf time str w2 (off 0))
12451 (save-match-data
12452 (setq t1 (org-parse-time-string ts t))
12453 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12454 (setq off (- (match-end 0) (match-beginning 0)))))
12455 (setq end (- end off))
12456 (setq w1 (- end beg)
12457 with-hm (and (nth 1 t1) (nth 2 t1))
12458 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12459 time (org-fix-decoded-time t1)
12460 str (org-add-props
12461 (format-time-string
12462 (substring tf 1 -1) (apply 'encode-time time))
12463 nil 'mouse-face 'highlight)
12464 w2 (length str))
12465 (if (not (= w2 w1))
12466 (add-text-properties (1+ beg) (+ 2 beg)
12467 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12468 (if (featurep 'xemacs)
12469 (progn
12470 (put-text-property beg end 'invisible t)
12471 (put-text-property beg end 'end-glyph (make-glyph str)))
12472 (put-text-property beg end 'display str))))
12474 (defun org-translate-time (string)
12475 "Translate all timestamps in STRING to custom format.
12476 But do this only if the variable `org-display-custom-times' is set."
12477 (when org-display-custom-times
12478 (save-match-data
12479 (let* ((start 0)
12480 (re org-ts-regexp-both)
12481 t1 with-hm inactive tf time str beg end)
12482 (while (setq start (string-match re string start))
12483 (setq beg (match-beginning 0)
12484 end (match-end 0)
12485 t1 (save-match-data
12486 (org-parse-time-string (substring string beg end) t))
12487 with-hm (and (nth 1 t1) (nth 2 t1))
12488 inactive (equal (substring string beg (1+ beg)) "[")
12489 tf (funcall (if with-hm 'cdr 'car)
12490 org-time-stamp-custom-formats)
12491 time (org-fix-decoded-time t1)
12492 str (format-time-string
12493 (concat
12494 (if inactive "[" "<") (substring tf 1 -1)
12495 (if inactive "]" ">"))
12496 (apply 'encode-time time))
12497 string (replace-match str t t string)
12498 start (+ start (length str)))))))
12499 string)
12501 (defun org-fix-decoded-time (time)
12502 "Set 0 instead of nil for the first 6 elements of time.
12503 Don't touch the rest."
12504 (let ((n 0))
12505 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12507 (defun org-days-to-time (timestamp-string)
12508 "Difference between TIMESTAMP-STRING and now in days."
12509 (- (time-to-days (org-time-string-to-time timestamp-string))
12510 (time-to-days (current-time))))
12512 (defun org-deadline-close (timestamp-string &optional ndays)
12513 "Is the time in TIMESTAMP-STRING close to the current date?"
12514 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12515 (and (< (org-days-to-time timestamp-string) ndays)
12516 (not (org-entry-is-done-p))))
12518 (defun org-get-wdays (ts)
12519 "Get the deadline lead time appropriate for timestring TS."
12520 (cond
12521 ((<= org-deadline-warning-days 0)
12522 ;; 0 or negative, enforce this value no matter what
12523 (- org-deadline-warning-days))
12524 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12525 ;; lead time is specified.
12526 (floor (* (string-to-number (match-string 1 ts))
12527 (cdr (assoc (match-string 2 ts)
12528 '(("d" . 1) ("w" . 7)
12529 ("m" . 30.4) ("y" . 365.25)))))))
12530 ;; go for the default.
12531 (t org-deadline-warning-days)))
12533 (defun org-calendar-select-mouse (ev)
12534 "Return to `org-read-date' with the date currently selected.
12535 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12536 (interactive "e")
12537 (mouse-set-point ev)
12538 (when (calendar-cursor-to-date)
12539 (let* ((date (calendar-cursor-to-date))
12540 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12541 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12542 (if (active-minibuffer-window) (exit-minibuffer))))
12544 (defun org-check-deadlines (ndays)
12545 "Check if there are any deadlines due or past due.
12546 A deadline is considered due if it happens within `org-deadline-warning-days'
12547 days from today's date. If the deadline appears in an entry marked DONE,
12548 it is not shown. The prefix arg NDAYS can be used to test that many
12549 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12550 (interactive "P")
12551 (let* ((org-warn-days
12552 (cond
12553 ((equal ndays '(4)) 100000)
12554 (ndays (prefix-numeric-value ndays))
12555 (t (abs org-deadline-warning-days))))
12556 (case-fold-search nil)
12557 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12558 (callback
12559 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12561 (message "%d deadlines past-due or due within %d days"
12562 (org-occur regexp nil callback)
12563 org-warn-days)))
12565 (defun org-check-before-date (date)
12566 "Check if there are deadlines or scheduled entries before DATE."
12567 (interactive (list (org-read-date)))
12568 (let ((case-fold-search nil)
12569 (regexp (concat "\\<\\(" org-deadline-string
12570 "\\|" org-scheduled-string
12571 "\\) *<\\([^>]+\\)>"))
12572 (callback
12573 (lambda () (time-less-p
12574 (org-time-string-to-time (match-string 2))
12575 (org-time-string-to-time date)))))
12576 (message "%d entries before %s"
12577 (org-occur regexp nil callback) date)))
12579 (defun org-check-after-date (date)
12580 "Check if there are deadlines or scheduled entries after DATE."
12581 (interactive (list (org-read-date)))
12582 (let ((case-fold-search nil)
12583 (regexp (concat "\\<\\(" org-deadline-string
12584 "\\|" org-scheduled-string
12585 "\\) *<\\([^>]+\\)>"))
12586 (callback
12587 (lambda () (not
12588 (time-less-p
12589 (org-time-string-to-time (match-string 2))
12590 (org-time-string-to-time date))))))
12591 (message "%d entries after %s"
12592 (org-occur regexp nil callback) date)))
12594 (defun org-evaluate-time-range (&optional to-buffer)
12595 "Evaluate a time range by computing the difference between start and end.
12596 Normally the result is just printed in the echo area, but with prefix arg
12597 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12598 If the time range is actually in a table, the result is inserted into the
12599 next column.
12600 For time difference computation, a year is assumed to be exactly 365
12601 days in order to avoid rounding problems."
12602 (interactive "P")
12604 (org-clock-update-time-maybe)
12605 (save-excursion
12606 (unless (org-at-date-range-p t)
12607 (goto-char (point-at-bol))
12608 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12609 (if (not (org-at-date-range-p t))
12610 (error "Not at a time-stamp range, and none found in current line")))
12611 (let* ((ts1 (match-string 1))
12612 (ts2 (match-string 2))
12613 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12614 (match-end (match-end 0))
12615 (time1 (org-time-string-to-time ts1))
12616 (time2 (org-time-string-to-time ts2))
12617 (t1 (time-to-seconds time1))
12618 (t2 (time-to-seconds time2))
12619 (diff (abs (- t2 t1)))
12620 (negative (< (- t2 t1) 0))
12621 ;; (ys (floor (* 365 24 60 60)))
12622 (ds (* 24 60 60))
12623 (hs (* 60 60))
12624 (fy "%dy %dd %02d:%02d")
12625 (fy1 "%dy %dd")
12626 (fd "%dd %02d:%02d")
12627 (fd1 "%dd")
12628 (fh "%02d:%02d")
12629 y d h m align)
12630 (if havetime
12631 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12633 d (floor (/ diff ds)) diff (mod diff ds)
12634 h (floor (/ diff hs)) diff (mod diff hs)
12635 m (floor (/ diff 60)))
12636 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12638 d (floor (+ (/ diff ds) 0.5))
12639 h 0 m 0))
12640 (if (not to-buffer)
12641 (message "%s" (org-make-tdiff-string y d h m))
12642 (if (org-at-table-p)
12643 (progn
12644 (goto-char match-end)
12645 (setq align t)
12646 (and (looking-at " *|") (goto-char (match-end 0))))
12647 (goto-char match-end))
12648 (if (looking-at
12649 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12650 (replace-match ""))
12651 (if negative (insert " -"))
12652 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12653 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12654 (insert " " (format fh h m))))
12655 (if align (org-table-align))
12656 (message "Time difference inserted")))))
12658 (defun org-make-tdiff-string (y d h m)
12659 (let ((fmt "")
12660 (l nil))
12661 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12662 l (push y l)))
12663 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12664 l (push d l)))
12665 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12666 l (push h l)))
12667 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12668 l (push m l)))
12669 (apply 'format fmt (nreverse l))))
12671 (defun org-time-string-to-time (s)
12672 (apply 'encode-time (org-parse-time-string s)))
12673 (defun org-time-string-to-seconds (s)
12674 (time-to-seconds (org-time-string-to-time s)))
12676 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12677 "Convert a time stamp to an absolute day number.
12678 If there is a specifyer for a cyclic time stamp, get the closest date to
12679 DAYNR.
12680 PREFER and SHOW-ALL are passed through to `org-closest-date'.
12681 the variable date is bound by the calendar when this is called."
12682 (cond
12683 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12684 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12685 daynr
12686 (+ daynr 1000)))
12687 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12688 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12689 (time-to-days (current-time))) (match-string 0 s)
12690 prefer show-all))
12691 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12693 (defun org-days-to-iso-week (days)
12694 "Return the iso week number."
12695 (require 'cal-iso)
12696 (car (calendar-iso-from-absolute days)))
12698 (defun org-small-year-to-year (year)
12699 "Convert 2-digit years into 4-digit years.
12700 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12701 The year 2000 cannot be abbreviated. Any year larger than 99
12702 is returned unchanged."
12703 (if (< year 38)
12704 (setq year (+ 2000 year))
12705 (if (< year 100)
12706 (setq year (+ 1900 year))))
12707 year)
12709 (defun org-time-from-absolute (d)
12710 "Return the time corresponding to date D.
12711 D may be an absolute day number, or a calendar-type list (month day year)."
12712 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12713 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12715 (defun org-calendar-holiday ()
12716 "List of holidays, for Diary display in Org-mode."
12717 (require 'holidays)
12718 (let ((hl (funcall
12719 (if (fboundp 'calendar-check-holidays)
12720 'calendar-check-holidays 'check-calendar-holidays) date)))
12721 (if hl (mapconcat 'identity hl "; "))))
12723 (defun org-diary-sexp-entry (sexp entry date)
12724 "Process a SEXP diary ENTRY for DATE."
12725 (require 'diary-lib)
12726 (let ((result (if calendar-debug-sexp
12727 (let ((stack-trace-on-error t))
12728 (eval (car (read-from-string sexp))))
12729 (condition-case nil
12730 (eval (car (read-from-string sexp)))
12731 (error
12732 (beep)
12733 (message "Bad sexp at line %d in %s: %s"
12734 (org-current-line)
12735 (buffer-file-name) sexp)
12736 (sleep-for 2))))))
12737 (cond ((stringp result) result)
12738 ((and (consp result)
12739 (stringp (cdr result))) (cdr result))
12740 (result entry)
12741 (t nil))))
12743 (defun org-diary-to-ical-string (frombuf)
12744 "Get iCalendar entries from diary entries in buffer FROMBUF.
12745 This uses the icalendar.el library."
12746 (let* ((tmpdir (if (featurep 'xemacs)
12747 (temp-directory)
12748 temporary-file-directory))
12749 (tmpfile (make-temp-name
12750 (expand-file-name "orgics" tmpdir)))
12751 buf rtn b e)
12752 (save-excursion
12753 (set-buffer frombuf)
12754 (icalendar-export-region (point-min) (point-max) tmpfile)
12755 (setq buf (find-buffer-visiting tmpfile))
12756 (set-buffer buf)
12757 (goto-char (point-min))
12758 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12759 (setq b (match-beginning 0)))
12760 (goto-char (point-max))
12761 (if (re-search-backward "^END:VEVENT" nil t)
12762 (setq e (match-end 0)))
12763 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12764 (kill-buffer buf)
12765 (delete-file tmpfile)
12766 rtn))
12768 (defun org-closest-date (start current change prefer show-all)
12769 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12770 When PREFER is `past' return a date that is either CURRENT or past.
12771 When PREFER is `future', return a date that is either CURRENT or future.
12772 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12773 ;; Make the proper lists from the dates
12774 (catch 'exit
12775 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12776 dn dw sday cday n1 n2 n0
12777 d m y y1 y2 date1 date2 nmonths nm ny m2)
12779 (setq start (org-date-to-gregorian start)
12780 current (org-date-to-gregorian
12781 (if show-all
12782 current
12783 (time-to-days (current-time))))
12784 sday (calendar-absolute-from-gregorian start)
12785 cday (calendar-absolute-from-gregorian current))
12787 (if (<= cday sday) (throw 'exit sday))
12789 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12790 (setq dn (string-to-number (match-string 1 change))
12791 dw (cdr (assoc (match-string 2 change) a1)))
12792 (error "Invalid change specifyer: %s" change))
12793 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12794 (cond
12795 ((eq dw 'day)
12796 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12797 n2 (+ n1 dn)))
12798 ((eq dw 'year)
12799 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12800 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12801 (setq date1 (list m d y1)
12802 n1 (calendar-absolute-from-gregorian date1)
12803 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12804 n2 (calendar-absolute-from-gregorian date2)))
12805 ((eq dw 'month)
12806 ;; approx number of month between the two dates
12807 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12808 ;; How often does dn fit in there?
12809 (setq d (nth 1 start) m (car start) y (nth 2 start)
12810 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12811 m (+ m nm)
12812 ny (floor (/ m 12))
12813 y (+ y ny)
12814 m (- m (* ny 12)))
12815 (while (> m 12) (setq m (- m 12) y (1+ y)))
12816 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12817 (setq m2 (+ m dn) y2 y)
12818 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12819 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12820 (while (<= n2 cday)
12821 (setq n1 n2 m m2 y y2)
12822 (setq m2 (+ m dn) y2 y)
12823 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12824 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12825 ;; Make sure n1 is the earlier date
12826 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12827 (if show-all
12828 (cond
12829 ((eq prefer 'past) n1)
12830 ((eq prefer 'future) (if (= cday n1) n1 n2))
12831 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12832 (cond
12833 ((eq prefer 'past) n1)
12834 ((eq prefer 'future) (if (= cday n1) n1 n2))
12835 (t (if (= cday n1) n1 n2)))))))
12837 (defun org-date-to-gregorian (date)
12838 "Turn any specification of DATE into a gregorian date for the calendar."
12839 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12840 ((and (listp date) (= (length date) 3)) date)
12841 ((stringp date)
12842 (setq date (org-parse-time-string date))
12843 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12844 ((listp date)
12845 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12847 (defun org-parse-time-string (s &optional nodefault)
12848 "Parse the standard Org-mode time string.
12849 This should be a lot faster than the normal `parse-time-string'.
12850 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12851 hour and minute fields will be nil if not given."
12852 (if (string-match org-ts-regexp0 s)
12853 (list 0
12854 (if (or (match-beginning 8) (not nodefault))
12855 (string-to-number (or (match-string 8 s) "0")))
12856 (if (or (match-beginning 7) (not nodefault))
12857 (string-to-number (or (match-string 7 s) "0")))
12858 (string-to-number (match-string 4 s))
12859 (string-to-number (match-string 3 s))
12860 (string-to-number (match-string 2 s))
12861 nil nil nil)
12862 (make-list 9 0)))
12864 (defun org-timestamp-up (&optional arg)
12865 "Increase the date item at the cursor by one.
12866 If the cursor is on the year, change the year. If it is on the month or
12867 the day, change that.
12868 With prefix ARG, change by that many units."
12869 (interactive "p")
12870 (org-timestamp-change (prefix-numeric-value arg)))
12872 (defun org-timestamp-down (&optional arg)
12873 "Decrease the date item at the cursor by one.
12874 If the cursor is on the year, change the year. If it is on the month or
12875 the day, change that.
12876 With prefix ARG, change by that many units."
12877 (interactive "p")
12878 (org-timestamp-change (- (prefix-numeric-value arg))))
12880 (defun org-timestamp-up-day (&optional arg)
12881 "Increase the date in the time stamp by one day.
12882 With prefix ARG, change that many days."
12883 (interactive "p")
12884 (if (and (not (org-at-timestamp-p t))
12885 (org-on-heading-p))
12886 (org-todo 'up)
12887 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12889 (defun org-timestamp-down-day (&optional arg)
12890 "Decrease the date in the time stamp by one day.
12891 With prefix ARG, change that many days."
12892 (interactive "p")
12893 (if (and (not (org-at-timestamp-p t))
12894 (org-on-heading-p))
12895 (org-todo 'down)
12896 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12898 (defun org-at-timestamp-p (&optional inactive-ok)
12899 "Determine if the cursor is in or at a timestamp."
12900 (interactive)
12901 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12902 (pos (point))
12903 (ans (or (looking-at tsr)
12904 (save-excursion
12905 (skip-chars-backward "^[<\n\r\t")
12906 (if (> (point) (point-min)) (backward-char 1))
12907 (and (looking-at tsr)
12908 (> (- (match-end 0) pos) -1))))))
12909 (and ans
12910 (boundp 'org-ts-what)
12911 (setq org-ts-what
12912 (cond
12913 ((= pos (match-beginning 0)) 'bracket)
12914 ((= pos (1- (match-end 0))) 'bracket)
12915 ((org-pos-in-match-range pos 2) 'year)
12916 ((org-pos-in-match-range pos 3) 'month)
12917 ((org-pos-in-match-range pos 7) 'hour)
12918 ((org-pos-in-match-range pos 8) 'minute)
12919 ((or (org-pos-in-match-range pos 4)
12920 (org-pos-in-match-range pos 5)) 'day)
12921 ((and (> pos (or (match-end 8) (match-end 5)))
12922 (< pos (match-end 0)))
12923 (- pos (or (match-end 8) (match-end 5))))
12924 (t 'day))))
12925 ans))
12927 (defun org-toggle-timestamp-type ()
12928 "Toggle the type (<active> or [inactive]) of a time stamp."
12929 (interactive)
12930 (when (org-at-timestamp-p t)
12931 (let ((beg (match-beginning 0)) (end (match-end 0))
12932 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12933 (save-excursion
12934 (goto-char beg)
12935 (while (re-search-forward "[][<>]" end t)
12936 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12937 t t)))
12938 (message "Timestamp is now %sactive"
12939 (if (equal (char-after beg) ?<) "" "in")))))
12941 (defun org-timestamp-change (n &optional what)
12942 "Change the date in the time stamp at point.
12943 The date will be changed by N times WHAT. WHAT can be `day', `month',
12944 `year', `minute', `second'. If WHAT is not given, the cursor position
12945 in the timestamp determines what will be changed."
12946 (let ((pos (point))
12947 with-hm inactive
12948 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12949 org-ts-what
12950 extra rem
12951 ts time time0)
12952 (if (not (org-at-timestamp-p t))
12953 (error "Not at a timestamp"))
12954 (if (and (not what) (eq org-ts-what 'bracket))
12955 (org-toggle-timestamp-type)
12956 (if (and (not what) (not (eq org-ts-what 'day))
12957 org-display-custom-times
12958 (get-text-property (point) 'display)
12959 (not (get-text-property (1- (point)) 'display)))
12960 (setq org-ts-what 'day))
12961 (setq org-ts-what (or what org-ts-what)
12962 inactive (= (char-after (match-beginning 0)) ?\[)
12963 ts (match-string 0))
12964 (replace-match "")
12965 (if (string-match
12966 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12968 (setq extra (match-string 1 ts)))
12969 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12970 (setq with-hm t))
12971 (setq time0 (org-parse-time-string ts))
12972 (when (and (eq org-ts-what 'minute)
12973 (eq current-prefix-arg nil))
12974 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12975 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12976 (setcar (cdr time0) (+ (nth 1 time0)
12977 (if (> n 0) (- rem) (- dm rem))))))
12978 (setq time
12979 (encode-time (or (car time0) 0)
12980 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12981 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12982 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12983 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12984 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12985 (nthcdr 6 time0)))
12986 (when (and (member org-ts-what '(hour minute))
12987 extra
12988 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
12989 (setq extra (org-modify-ts-extra
12990 extra
12991 (if (eq org-ts-what 'hour) 2 5)
12992 n dm)))
12993 (when (integerp org-ts-what)
12994 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12995 (if (eq what 'calendar)
12996 (let ((cal-date (org-get-date-from-calendar)))
12997 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12998 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12999 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13000 (setcar time0 (or (car time0) 0))
13001 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13002 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13003 (setq time (apply 'encode-time time0))))
13004 (setq org-last-changed-timestamp
13005 (org-insert-time-stamp time with-hm inactive nil nil extra))
13006 (org-clock-update-time-maybe)
13007 (goto-char pos)
13008 ;; Try to recenter the calendar window, if any
13009 (if (and org-calendar-follow-timestamp-change
13010 (get-buffer-window "*Calendar*" t)
13011 (memq org-ts-what '(day month year)))
13012 (org-recenter-calendar (time-to-days time))))))
13014 (defun org-modify-ts-extra (s pos n dm)
13015 "Change the different parts of the lead-time and repeat fields in timestamp."
13016 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13017 ng h m new rem)
13018 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13019 (cond
13020 ((or (org-pos-in-match-range pos 2)
13021 (org-pos-in-match-range pos 3))
13022 (setq m (string-to-number (match-string 3 s))
13023 h (string-to-number (match-string 2 s)))
13024 (if (org-pos-in-match-range pos 2)
13025 (setq h (+ h n))
13026 (setq n (* dm (org-no-warnings (signum n))))
13027 (when (not (= 0 (setq rem (% m dm))))
13028 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13029 (setq m (+ m n)))
13030 (if (< m 0) (setq m (+ m 60) h (1- h)))
13031 (if (> m 59) (setq m (- m 60) h (1+ h)))
13032 (setq h (min 24 (max 0 h)))
13033 (setq ng 1 new (format "-%02d:%02d" h m)))
13034 ((org-pos-in-match-range pos 6)
13035 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13036 ((org-pos-in-match-range pos 5)
13037 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13039 ((org-pos-in-match-range pos 9)
13040 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13041 ((org-pos-in-match-range pos 8)
13042 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13044 (when ng
13045 (setq s (concat
13046 (substring s 0 (match-beginning ng))
13048 (substring s (match-end ng))))))
13051 (defun org-recenter-calendar (date)
13052 "If the calendar is visible, recenter it to DATE."
13053 (let* ((win (selected-window))
13054 (cwin (get-buffer-window "*Calendar*" t))
13055 (calendar-move-hook nil))
13056 (when cwin
13057 (select-window cwin)
13058 (calendar-goto-date (if (listp date) date
13059 (calendar-gregorian-from-absolute date)))
13060 (select-window win))))
13062 (defun org-goto-calendar (&optional arg)
13063 "Go to the Emacs calendar at the current date.
13064 If there is a time stamp in the current line, go to that date.
13065 A prefix ARG can be used to force the current date."
13066 (interactive "P")
13067 (let ((tsr org-ts-regexp) diff
13068 (calendar-move-hook nil)
13069 (calendar-view-holidays-initially-flag nil)
13070 (view-calendar-holidays-initially nil)
13071 (calendar-view-diary-initially-flag nil)
13072 (view-diary-entries-initially nil))
13073 (if (or (org-at-timestamp-p)
13074 (save-excursion
13075 (beginning-of-line 1)
13076 (looking-at (concat ".*" tsr))))
13077 (let ((d1 (time-to-days (current-time)))
13078 (d2 (time-to-days
13079 (org-time-string-to-time (match-string 1)))))
13080 (setq diff (- d2 d1))))
13081 (calendar)
13082 (calendar-goto-today)
13083 (if (and diff (not arg)) (calendar-forward-day diff))))
13085 (defun org-get-date-from-calendar ()
13086 "Return a list (month day year) of date at point in calendar."
13087 (with-current-buffer "*Calendar*"
13088 (save-match-data
13089 (calendar-cursor-to-date))))
13091 (defun org-date-from-calendar ()
13092 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13093 If there is already a time stamp at the cursor position, update it."
13094 (interactive)
13095 (if (org-at-timestamp-p t)
13096 (org-timestamp-change 0 'calendar)
13097 (let ((cal-date (org-get-date-from-calendar)))
13098 (org-insert-time-stamp
13099 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13101 (defun org-minutes-to-hh:mm-string (m)
13102 "Compute H:MM from a number of minutes."
13103 (let ((h (/ m 60)))
13104 (setq m (- m (* 60 h)))
13105 (format org-time-clocksum-format h m)))
13107 (defun org-hh:mm-string-to-minutes (s)
13108 "Convert a string H:MM to a number of minutes.
13109 If the string is just a number, interprete it as minutes.
13110 In fact, the first hh:mm or number in the string will be taken,
13111 there can be extra stuff in the string.
13112 If no number is found, the return value is 0."
13113 (cond
13114 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13115 (+ (* (string-to-number (match-string 1 s)) 60)
13116 (string-to-number (match-string 2 s))))
13117 ((string-match "\\([0-9]+\\)" s)
13118 (string-to-number (match-string 1 s)))
13119 (t 0)))
13121 ;;;; Files
13123 (defun org-save-all-org-buffers ()
13124 "Save all Org-mode buffers without user confirmation."
13125 (interactive)
13126 (message "Saving all Org-mode buffers...")
13127 (save-some-buffers t 'org-mode-p)
13128 (when (featurep 'org-id) (org-id-locations-save))
13129 (message "Saving all Org-mode buffers... done"))
13131 (defun org-revert-all-org-buffers ()
13132 "Revert all Org-mode buffers.
13133 Prompt for confirmation when there are unsaved changes.
13134 Be sure you know what you are doing before letting this function
13135 overwrite your changes.
13137 This function is useful in a setup where one tracks org files
13138 with a version control system, to revert on one machine after pulling
13139 changes from another. I believe the procedure must be like this:
13141 1. M-x org-save-all-org-buffers
13142 2. Pull changes from the other machine, resolve conflicts
13143 3. M-x org-revert-all-org-buffers"
13144 (interactive)
13145 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13146 (error "Abort"))
13147 (save-excursion
13148 (save-window-excursion
13149 (mapc
13150 (lambda (b)
13151 (when (and (with-current-buffer b (org-mode-p))
13152 (with-current-buffer b buffer-file-name))
13153 (switch-to-buffer b)
13154 (revert-buffer t 'no-confirm)))
13155 (buffer-list))
13156 (when (and (featurep 'org-id) org-id-track-globally)
13157 (org-id-locations-load)))))
13159 ;;;; Agenda files
13161 ;;;###autoload
13162 (defun org-iswitchb (&optional arg)
13163 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13164 With a prefix argument, restrict available to files.
13165 With two prefix arguments, restrict available buffers to agenda files.
13167 Due to some yet unresolved reason, the global function
13168 `iswitchb-mode' needs to be active for this function to work."
13169 (interactive "P")
13170 (require 'iswitchb)
13171 (let ((enabled iswitchb-mode) blist)
13172 (or enabled (iswitchb-mode 1))
13173 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13174 ((equal arg '(16)) (org-buffer-list 'agenda))
13175 (t (org-buffer-list))))
13176 (unwind-protect
13177 (let ((iswitchb-make-buflist-hook
13178 (lambda ()
13179 (setq iswitchb-temp-buflist
13180 (mapcar 'buffer-name blist)))))
13181 (switch-to-buffer
13182 (iswitchb-read-buffer
13183 "Switch-to: " nil t))
13184 (or enabled (iswitchb-mode -1))))))
13186 ;;;###autoload
13187 (defun org-ido-switchb (&optional arg)
13188 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13189 With a prefix argument, restrict available to files.
13190 With two prefix arguments, restrict available buffers to agenda files."
13191 (interactive "P")
13192 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13193 ((equal arg '(16)) (org-buffer-list 'agenda))
13194 (t (org-buffer-list)))))
13195 (switch-to-buffer
13196 (org-ido-completing-read "Org buffer: "
13197 (mapcar 'list (mapcar 'buffer-name blist))
13198 nil t))))
13200 (defun org-buffer-list (&optional predicate exclude-tmp)
13201 "Return a list of Org buffers.
13202 PREDICATE can be `export', `files' or `agenda'.
13204 export restrict the list to Export buffers.
13205 files restrict the list to buffers visiting Org files.
13206 agenda restrict the list to buffers visiting agenda files.
13208 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13209 (let* ((bfn nil)
13210 (agenda-files (and (eq predicate 'agenda)
13211 (mapcar 'file-truename (org-agenda-files t))))
13212 (filter
13213 (cond
13214 ((eq predicate 'files)
13215 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13216 ((eq predicate 'export)
13217 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13218 ((eq predicate 'agenda)
13219 (lambda (b)
13220 (with-current-buffer b
13221 (and (eq major-mode 'org-mode)
13222 (setq bfn (buffer-file-name b))
13223 (member (file-truename bfn) agenda-files)))))
13224 (t (lambda (b) (with-current-buffer b
13225 (or (eq major-mode 'org-mode)
13226 (string-match "\*Org .*Export"
13227 (buffer-name b)))))))))
13228 (delq nil
13229 (mapcar
13230 (lambda(b)
13231 (if (and (funcall filter b)
13232 (or (not exclude-tmp)
13233 (not (string-match "tmp" (buffer-name b)))))
13235 nil))
13236 (buffer-list)))))
13238 (defun org-agenda-files (&optional unrestricted archives)
13239 "Get the list of agenda files.
13240 Optional UNRESTRICTED means return the full list even if a restriction
13241 is currently in place.
13242 When ARCHIVES is t, include all archive files hat are really being
13243 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13244 `org-agenda-archives-mode' is t."
13245 (let ((files
13246 (cond
13247 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13248 ((stringp org-agenda-files) (org-read-agenda-file-list))
13249 ((listp org-agenda-files) org-agenda-files)
13250 (t (error "Invalid value of `org-agenda-files'")))))
13251 (setq files (apply 'append
13252 (mapcar (lambda (f)
13253 (if (file-directory-p f)
13254 (directory-files
13255 f t org-agenda-file-regexp)
13256 (list f)))
13257 files)))
13258 (when org-agenda-skip-unavailable-files
13259 (setq files (delq nil
13260 (mapcar (function
13261 (lambda (file)
13262 (and (file-readable-p file) file)))
13263 files))))
13264 (when (or (eq archives t)
13265 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13266 (setq files (org-add-archive-files files)))
13267 files))
13269 (defun org-edit-agenda-file-list ()
13270 "Edit the list of agenda files.
13271 Depending on setup, this either uses customize to edit the variable
13272 `org-agenda-files', or it visits the file that is holding the list. In the
13273 latter case, the buffer is set up in a way that saving it automatically kills
13274 the buffer and restores the previous window configuration."
13275 (interactive)
13276 (if (stringp org-agenda-files)
13277 (let ((cw (current-window-configuration)))
13278 (find-file org-agenda-files)
13279 (org-set-local 'org-window-configuration cw)
13280 (org-add-hook 'after-save-hook
13281 (lambda ()
13282 (set-window-configuration
13283 (prog1 org-window-configuration
13284 (kill-buffer (current-buffer))))
13285 (org-install-agenda-files-menu)
13286 (message "New agenda file list installed"))
13287 nil 'local)
13288 (message "%s" (substitute-command-keys
13289 "Edit list and finish with \\[save-buffer]")))
13290 (customize-variable 'org-agenda-files)))
13292 (defun org-store-new-agenda-file-list (list)
13293 "Set new value for the agenda file list and save it correctly."
13294 (if (stringp org-agenda-files)
13295 (let ((f org-agenda-files) b)
13296 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13297 (with-temp-file f
13298 (insert (mapconcat 'identity list "\n") "\n")))
13299 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13300 (setq org-agenda-files list)
13301 (customize-save-variable 'org-agenda-files org-agenda-files))))
13303 (defun org-read-agenda-file-list ()
13304 "Read the list of agenda files from a file."
13305 (when (file-directory-p org-agenda-files)
13306 (error "`org-agenda-files' cannot be a single directory"))
13307 (when (stringp org-agenda-files)
13308 (with-temp-buffer
13309 (insert-file-contents org-agenda-files)
13310 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13313 ;;;###autoload
13314 (defun org-cycle-agenda-files ()
13315 "Cycle through the files in `org-agenda-files'.
13316 If the current buffer visits an agenda file, find the next one in the list.
13317 If the current buffer does not, find the first agenda file."
13318 (interactive)
13319 (let* ((fs (org-agenda-files t))
13320 (files (append fs (list (car fs))))
13321 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13322 file)
13323 (unless files (error "No agenda files"))
13324 (catch 'exit
13325 (while (setq file (pop files))
13326 (if (equal (file-truename file) tcf)
13327 (when (car files)
13328 (find-file (car files))
13329 (throw 'exit t))))
13330 (find-file (car fs)))
13331 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13333 (defun org-agenda-file-to-front (&optional to-end)
13334 "Move/add the current file to the top of the agenda file list.
13335 If the file is not present in the list, it is added to the front. If it is
13336 present, it is moved there. With optional argument TO-END, add/move to the
13337 end of the list."
13338 (interactive "P")
13339 (let ((org-agenda-skip-unavailable-files nil)
13340 (file-alist (mapcar (lambda (x)
13341 (cons (file-truename x) x))
13342 (org-agenda-files t)))
13343 (ctf (file-truename buffer-file-name))
13344 x had)
13345 (setq x (assoc ctf file-alist) had x)
13347 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13348 (if to-end
13349 (setq file-alist (append (delq x file-alist) (list x)))
13350 (setq file-alist (cons x (delq x file-alist))))
13351 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13352 (org-install-agenda-files-menu)
13353 (message "File %s to %s of agenda file list"
13354 (if had "moved" "added") (if to-end "end" "front"))))
13356 (defun org-remove-file (&optional file)
13357 "Remove current file from the list of files in variable `org-agenda-files'.
13358 These are the files which are being checked for agenda entries.
13359 Optional argument FILE means, use this file instead of the current."
13360 (interactive)
13361 (let* ((org-agenda-skip-unavailable-files nil)
13362 (file (or file buffer-file-name))
13363 (true-file (file-truename file))
13364 (afile (abbreviate-file-name file))
13365 (files (delq nil (mapcar
13366 (lambda (x)
13367 (if (equal true-file
13368 (file-truename x))
13369 nil x))
13370 (org-agenda-files t)))))
13371 (if (not (= (length files) (length (org-agenda-files t))))
13372 (progn
13373 (org-store-new-agenda-file-list files)
13374 (org-install-agenda-files-menu)
13375 (message "Removed file: %s" afile))
13376 (message "File was not in list: %s (not removed)" afile))))
13378 (defun org-file-menu-entry (file)
13379 (vector file (list 'find-file file) t))
13381 (defun org-check-agenda-file (file)
13382 "Make sure FILE exists. If not, ask user what to do."
13383 (when (not (file-exists-p file))
13384 (message "non-existent file %s. [R]emove from list or [A]bort?"
13385 (abbreviate-file-name file))
13386 (let ((r (downcase (read-char-exclusive))))
13387 (cond
13388 ((equal r ?r)
13389 (org-remove-file file)
13390 (throw 'nextfile t))
13391 (t (error "Abort"))))))
13393 (defun org-get-agenda-file-buffer (file)
13394 "Get a buffer visiting FILE. If the buffer needs to be created, add
13395 it to the list of buffers which might be released later."
13396 (let ((buf (org-find-base-buffer-visiting file)))
13397 (if buf
13398 buf ; just return it
13399 ;; Make a new buffer and remember it
13400 (setq buf (find-file-noselect file))
13401 (if buf (push buf org-agenda-new-buffers))
13402 buf)))
13404 (defun org-release-buffers (blist)
13405 "Release all buffers in list, asking the user for confirmation when needed.
13406 When a buffer is unmodified, it is just killed. When modified, it is saved
13407 \(if the user agrees) and then killed."
13408 (let (buf file)
13409 (while (setq buf (pop blist))
13410 (setq file (buffer-file-name buf))
13411 (when (and (buffer-modified-p buf)
13412 file
13413 (y-or-n-p (format "Save file %s? " file)))
13414 (with-current-buffer buf (save-buffer)))
13415 (kill-buffer buf))))
13417 (defun org-prepare-agenda-buffers (files)
13418 "Create buffers for all agenda files, protect archived trees and comments."
13419 (interactive)
13420 (let ((pa '(:org-archived t))
13421 (pc '(:org-comment t))
13422 (pall '(:org-archived t :org-comment t))
13423 (inhibit-read-only t)
13424 (rea (concat ":" org-archive-tag ":"))
13425 bmp file re)
13426 (save-excursion
13427 (save-restriction
13428 (while (setq file (pop files))
13429 (catch 'nextfile
13430 (if (bufferp file)
13431 (set-buffer file)
13432 (org-check-agenda-file file)
13433 (set-buffer (org-get-agenda-file-buffer file)))
13434 (widen)
13435 (setq bmp (buffer-modified-p))
13436 (org-refresh-category-properties)
13437 (setq org-todo-keywords-for-agenda
13438 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13439 (setq org-done-keywords-for-agenda
13440 (append org-done-keywords-for-agenda org-done-keywords))
13441 (setq org-todo-keyword-alist-for-agenda
13442 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13443 (setq org-tag-alist-for-agenda
13444 (append org-tag-alist-for-agenda org-tag-alist))
13446 (save-excursion
13447 (remove-text-properties (point-min) (point-max) pall)
13448 (when org-agenda-skip-archived-trees
13449 (goto-char (point-min))
13450 (while (re-search-forward rea nil t)
13451 (if (org-on-heading-p t)
13452 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13453 (goto-char (point-min))
13454 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13455 (while (re-search-forward re nil t)
13456 (add-text-properties
13457 (match-beginning 0) (org-end-of-subtree t) pc)))
13458 (set-buffer-modified-p bmp)))))
13459 (setq org-todo-keyword-alist-for-agenda
13460 (org-uniquify org-todo-keyword-alist-for-agenda)
13461 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13463 ;;;; Embedded LaTeX
13465 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13466 "Keymap for the minor `org-cdlatex-mode'.")
13468 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13469 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13470 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13471 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13472 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13474 (defvar org-cdlatex-texmathp-advice-is-done nil
13475 "Flag remembering if we have applied the advice to texmathp already.")
13477 (define-minor-mode org-cdlatex-mode
13478 "Toggle the minor `org-cdlatex-mode'.
13479 This mode supports entering LaTeX environment and math in LaTeX fragments
13480 in Org-mode.
13481 \\{org-cdlatex-mode-map}"
13482 nil " OCDL" nil
13483 (when org-cdlatex-mode (require 'cdlatex))
13484 (unless org-cdlatex-texmathp-advice-is-done
13485 (setq org-cdlatex-texmathp-advice-is-done t)
13486 (defadvice texmathp (around org-math-always-on activate)
13487 "Always return t in org-mode buffers.
13488 This is because we want to insert math symbols without dollars even outside
13489 the LaTeX math segments. If Orgmode thinks that point is actually inside
13490 an embedded LaTeX fragment, let texmathp do its job.
13491 \\[org-cdlatex-mode-map]"
13492 (interactive)
13493 (let (p)
13494 (cond
13495 ((not (org-mode-p)) ad-do-it)
13496 ((eq this-command 'cdlatex-math-symbol)
13497 (setq ad-return-value t
13498 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13500 (let ((p (org-inside-LaTeX-fragment-p)))
13501 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13502 (setq ad-return-value t
13503 texmathp-why '("Org-mode embedded math" . 0))
13504 (if p ad-do-it)))))))))
13506 (defun turn-on-org-cdlatex ()
13507 "Unconditionally turn on `org-cdlatex-mode'."
13508 (org-cdlatex-mode 1))
13510 (defun org-inside-LaTeX-fragment-p ()
13511 "Test if point is inside a LaTeX fragment.
13512 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13513 sequence appearing also before point.
13514 Even though the matchers for math are configurable, this function assumes
13515 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13516 delimiters are skipped when they have been removed by customization.
13517 The return value is nil, or a cons cell with the delimiter and
13518 and the position of this delimiter.
13520 This function does a reasonably good job, but can locally be fooled by
13521 for example currency specifications. For example it will assume being in
13522 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13523 fragments that are properly closed, but during editing, we have to live
13524 with the uncertainty caused by missing closing delimiters. This function
13525 looks only before point, not after."
13526 (catch 'exit
13527 (let ((pos (point))
13528 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13529 (lim (progn
13530 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13531 (point)))
13532 dd-on str (start 0) m re)
13533 (goto-char pos)
13534 (when dodollar
13535 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13536 re (nth 1 (assoc "$" org-latex-regexps)))
13537 (while (string-match re str start)
13538 (cond
13539 ((= (match-end 0) (length str))
13540 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13541 ((= (match-end 0) (- (length str) 5))
13542 (throw 'exit nil))
13543 (t (setq start (match-end 0))))))
13544 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13545 (goto-char pos)
13546 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13547 (and (match-beginning 2) (throw 'exit nil))
13548 ;; count $$
13549 (while (re-search-backward "\\$\\$" lim t)
13550 (setq dd-on (not dd-on)))
13551 (goto-char pos)
13552 (if dd-on (cons "$$" m))))))
13555 (defun org-try-cdlatex-tab ()
13556 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13557 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13558 - inside a LaTeX fragment, or
13559 - after the first word in a line, where an abbreviation expansion could
13560 insert a LaTeX environment."
13561 (when org-cdlatex-mode
13562 (cond
13563 ((save-excursion
13564 (skip-chars-backward "a-zA-Z0-9*")
13565 (skip-chars-backward " \t")
13566 (bolp))
13567 (cdlatex-tab) t)
13568 ((org-inside-LaTeX-fragment-p)
13569 (cdlatex-tab) t)
13570 (t nil))))
13572 (defun org-cdlatex-underscore-caret (&optional arg)
13573 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13574 Revert to the normal definition outside of these fragments."
13575 (interactive "P")
13576 (if (org-inside-LaTeX-fragment-p)
13577 (call-interactively 'cdlatex-sub-superscript)
13578 (let (org-cdlatex-mode)
13579 (call-interactively (key-binding (vector last-input-event))))))
13581 (defun org-cdlatex-math-modify (&optional arg)
13582 "Execute `cdlatex-math-modify' in LaTeX fragments.
13583 Revert to the normal definition outside of these fragments."
13584 (interactive "P")
13585 (if (org-inside-LaTeX-fragment-p)
13586 (call-interactively 'cdlatex-math-modify)
13587 (let (org-cdlatex-mode)
13588 (call-interactively (key-binding (vector last-input-event))))))
13590 (defvar org-latex-fragment-image-overlays nil
13591 "List of overlays carrying the images of latex fragments.")
13592 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13594 (defun org-remove-latex-fragment-image-overlays ()
13595 "Remove all overlays with LaTeX fragment images in current buffer."
13596 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13597 (setq org-latex-fragment-image-overlays nil))
13599 (defun org-preview-latex-fragment (&optional subtree)
13600 "Preview the LaTeX fragment at point, or all locally or globally.
13601 If the cursor is in a LaTeX fragment, create the image and overlay
13602 it over the source code. If there is no fragment at point, display
13603 all fragments in the current text, from one headline to the next. With
13604 prefix SUBTREE, display all fragments in the current subtree. With a
13605 double prefix `C-u C-u', or when the cursor is before the first headline,
13606 display all fragments in the buffer.
13607 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13608 (interactive "P")
13609 (org-remove-latex-fragment-image-overlays)
13610 (save-excursion
13611 (save-restriction
13612 (let (beg end at msg)
13613 (cond
13614 ((or (equal subtree '(16))
13615 (not (save-excursion
13616 (re-search-backward (concat "^" outline-regexp) nil t))))
13617 (setq beg (point-min) end (point-max)
13618 msg "Creating images for buffer...%s"))
13619 ((equal subtree '(4))
13620 (org-back-to-heading)
13621 (setq beg (point) end (org-end-of-subtree t)
13622 msg "Creating images for subtree...%s"))
13624 (if (setq at (org-inside-LaTeX-fragment-p))
13625 (goto-char (max (point-min) (- (cdr at) 2)))
13626 (org-back-to-heading))
13627 (setq beg (point) end (progn (outline-next-heading) (point))
13628 msg (if at "Creating image...%s"
13629 "Creating images for entry...%s"))))
13630 (message msg "")
13631 (narrow-to-region beg end)
13632 (goto-char beg)
13633 (org-format-latex
13634 (concat "ltxpng/" (file-name-sans-extension
13635 (file-name-nondirectory
13636 buffer-file-name)))
13637 default-directory 'overlays msg at 'forbuffer)
13638 (message msg "done. Use `C-c C-c' to remove images.")))))
13640 (defvar org-latex-regexps
13641 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13642 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13643 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13644 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13645 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13646 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13647 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13648 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13649 "Regular expressions for matching embedded LaTeX.")
13651 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13652 "Replace LaTeX fragments with links to an image, and produce images."
13653 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13654 (let* ((prefixnodir (file-name-nondirectory prefix))
13655 (absprefix (expand-file-name prefix dir))
13656 (todir (file-name-directory absprefix))
13657 (opt org-format-latex-options)
13658 (matchers (plist-get opt :matchers))
13659 (re-list org-latex-regexps)
13660 (cnt 0) txt link beg end re e checkdir
13661 executables-checked
13662 m n block linkfile movefile ov)
13663 ;; Check if there are old images files with this prefix, and remove them
13664 (when (file-directory-p todir)
13665 (mapc 'delete-file
13666 (directory-files
13667 todir 'full
13668 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13669 ;; Check the different regular expressions
13670 (while (setq e (pop re-list))
13671 (setq m (car e) re (nth 1 e) n (nth 2 e)
13672 block (if (nth 3 e) "\n\n" ""))
13673 (when (member m matchers)
13674 (goto-char (point-min))
13675 (while (re-search-forward re nil t)
13676 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13677 (not (get-text-property (match-beginning n)
13678 'org-protected)))
13679 (setq txt (match-string n)
13680 beg (match-beginning n) end (match-end n)
13681 cnt (1+ cnt)
13682 linkfile (format "%s_%04d.png" prefix cnt)
13683 movefile (format "%s_%04d.png" absprefix cnt)
13684 link (concat block "[[file:" linkfile "]]" block))
13685 (if msg (message msg cnt))
13686 (goto-char beg)
13687 (unless checkdir ; make sure the directory exists
13688 (setq checkdir t)
13689 (or (file-directory-p todir) (make-directory todir)))
13691 (unless executables-checked
13692 (org-check-external-command
13693 "latex" "needed to convert LaTeX fragments to images")
13694 (org-check-external-command
13695 "dvipng" "needed to convert LaTeX fragments to images")
13696 (setq executables-checked t))
13698 (org-create-formula-image
13699 txt movefile opt forbuffer)
13700 (if overlays
13701 (progn
13702 (setq ov (org-make-overlay beg end))
13703 (if (featurep 'xemacs)
13704 (progn
13705 (org-overlay-put ov 'invisible t)
13706 (org-overlay-put
13707 ov 'end-glyph
13708 (make-glyph (vector 'png :file movefile))))
13709 (org-overlay-put
13710 ov 'display
13711 (list 'image :type 'png :file movefile :ascent 'center)))
13712 (push ov org-latex-fragment-image-overlays)
13713 (goto-char end))
13714 (delete-region beg end)
13715 (insert link))))))))
13717 ;; This function borrows from Ganesh Swami's latex2png.el
13718 (defun org-create-formula-image (string tofile options buffer)
13719 (let* ((tmpdir (if (featurep 'xemacs)
13720 (temp-directory)
13721 temporary-file-directory))
13722 (texfilebase (make-temp-name
13723 (expand-file-name "orgtex" tmpdir)))
13724 (texfile (concat texfilebase ".tex"))
13725 (dvifile (concat texfilebase ".dvi"))
13726 (pngfile (concat texfilebase ".png"))
13727 (fnh (if (featurep 'xemacs)
13728 (font-height (get-face-font 'default))
13729 (face-attribute 'default :height nil)))
13730 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13731 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13732 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13733 "Black"))
13734 (bg (or (plist-get options (if buffer :background :html-background))
13735 "Transparent")))
13736 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13737 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13738 (with-temp-file texfile
13739 (insert org-format-latex-header
13740 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13741 (let ((dir default-directory))
13742 (condition-case nil
13743 (progn
13744 (cd tmpdir)
13745 (call-process "latex" nil nil nil texfile))
13746 (error nil))
13747 (cd dir))
13748 (if (not (file-exists-p dvifile))
13749 (progn (message "Failed to create dvi file from %s" texfile) nil)
13750 (condition-case nil
13751 (call-process "dvipng" nil nil nil
13752 "-E" "-fg" fg "-bg" bg
13753 "-D" dpi
13754 ;;"-x" scale "-y" scale
13755 "-T" "tight"
13756 "-o" pngfile
13757 dvifile)
13758 (error nil))
13759 (if (not (file-exists-p pngfile))
13760 (progn (message "Failed to create png file from %s" texfile) nil)
13761 ;; Use the requested file name and clean up
13762 (copy-file pngfile tofile 'replace)
13763 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13764 (delete-file (concat texfilebase e)))
13765 pngfile))))
13767 (defun org-dvipng-color (attr)
13768 "Return an rgb color specification for dvipng."
13769 (apply 'format "rgb %s %s %s"
13770 (mapcar 'org-normalize-color
13771 (color-values (face-attribute 'default attr nil)))))
13773 (defun org-normalize-color (value)
13774 "Return string to be used as color value for an RGB component."
13775 (format "%g" (/ value 65535.0)))
13777 ;;;; Key bindings
13779 ;; Make `C-c C-x' a prefix key
13780 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13782 ;; TAB key with modifiers
13783 (org-defkey org-mode-map "\C-i" 'org-cycle)
13784 (org-defkey org-mode-map [(tab)] 'org-cycle)
13785 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13786 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13787 (org-defkey org-mode-map "\M-\t" 'org-complete)
13788 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13789 ;; The following line is necessary under Suse GNU/Linux
13790 (unless (featurep 'xemacs)
13791 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13792 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13793 (define-key org-mode-map [backtab] 'org-shifttab)
13795 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13796 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13797 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13799 ;; Cursor keys with modifiers
13800 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13801 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13802 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13803 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13805 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13806 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13807 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13808 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13810 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13811 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13812 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13813 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13815 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13816 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13818 ;;; Extra keys for tty access.
13819 ;; We only set them when really needed because otherwise the
13820 ;; menus don't show the simple keys
13822 (when (or org-use-extra-keys
13823 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13824 (not window-system))
13825 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13826 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13827 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13828 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13829 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13830 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13831 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13832 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13833 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13834 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13835 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13836 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13837 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13838 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13839 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13840 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13841 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13842 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13843 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13844 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13845 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13846 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
13847 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
13848 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
13849 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
13850 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
13851 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
13852 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
13854 ;; All the other keys
13856 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13857 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13858 (if (boundp 'narrow-map)
13859 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13860 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13861 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13862 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13863 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13864 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13865 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13866 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13867 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13868 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13869 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13870 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13871 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13872 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13873 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13874 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13875 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13876 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13877 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13878 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13879 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13880 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13881 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13882 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13883 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13884 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13885 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13886 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13887 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13888 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13889 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13890 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13891 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13892 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13893 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13894 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13895 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13896 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13897 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13898 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13899 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13900 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13901 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13902 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13903 (org-defkey org-mode-map "\C-c^" 'org-sort)
13904 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13905 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13906 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13907 (org-defkey org-mode-map "\C-m" 'org-return)
13908 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13909 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13910 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13911 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13912 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13913 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13914 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13915 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13916 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13917 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13918 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13919 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13920 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13921 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13922 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13923 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13924 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13926 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13927 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13928 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13929 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13931 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13932 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13933 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13934 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13935 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13936 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13937 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13938 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13939 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13940 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13941 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13942 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13943 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13945 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13946 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13947 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13948 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13950 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13952 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
13954 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
13955 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
13957 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
13960 (when (featurep 'xemacs)
13961 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13964 (defvar org-self-insert-command-undo-counter 0)
13966 (defvar org-table-auto-blank-field) ; defined in org-table.el
13967 (defun org-self-insert-command (N)
13968 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13969 If the cursor is in a table looking at whitespace, the whitespace is
13970 overwritten, and the table is not marked as requiring realignment."
13971 (interactive "p")
13972 (if (and
13973 (org-table-p)
13974 (progn
13975 ;; check if we blank the field, and if that triggers align
13976 (and (featurep 'org-table) org-table-auto-blank-field
13977 (member last-command
13978 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13979 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13980 ;; got extra space, this field does not determine column width
13981 (let (org-table-may-need-update) (org-table-blank-field))
13982 ;; no extra space, this field may determine column width
13983 (org-table-blank-field)))
13985 (eq N 1)
13986 (looking-at "[^|\n]* |"))
13987 (let (org-table-may-need-update)
13988 (goto-char (1- (match-end 0)))
13989 (delete-backward-char 1)
13990 (goto-char (match-beginning 0))
13991 (self-insert-command N))
13992 (setq org-table-may-need-update t)
13993 (self-insert-command N)
13994 (org-fix-tags-on-the-fly)
13995 (if org-self-insert-cluster-for-undo
13996 (if (not (eq last-command 'org-self-insert-command))
13997 (setq org-self-insert-command-undo-counter 1)
13998 (if (>= org-self-insert-command-undo-counter 20)
13999 (setq org-self-insert-command-undo-counter 1)
14000 (and (> org-self-insert-command-undo-counter 0)
14001 buffer-undo-list
14002 (not (cadr buffer-undo-list)) ; remove nil entry
14003 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14004 (setq org-self-insert-command-undo-counter
14005 (1+ org-self-insert-command-undo-counter)))))))
14007 (defun org-fix-tags-on-the-fly ()
14008 (when (and (equal (char-after (point-at-bol)) ?*)
14009 (org-on-heading-p))
14010 (org-align-tags-here org-tags-column)))
14012 (defun org-delete-backward-char (N)
14013 "Like `delete-backward-char', insert whitespace at field end in tables.
14014 When deleting backwards, in tables this function will insert whitespace in
14015 front of the next \"|\" separator, to keep the table aligned. The table will
14016 still be marked for re-alignment if the field did fill the entire column,
14017 because, in this case the deletion might narrow the column."
14018 (interactive "p")
14019 (if (and (org-table-p)
14020 (eq N 1)
14021 (string-match "|" (buffer-substring (point-at-bol) (point)))
14022 (looking-at ".*?|"))
14023 (let ((pos (point))
14024 (noalign (looking-at "[^|\n\r]* |"))
14025 (c org-table-may-need-update))
14026 (backward-delete-char N)
14027 (skip-chars-forward "^|")
14028 (insert " ")
14029 (goto-char (1- pos))
14030 ;; noalign: if there were two spaces at the end, this field
14031 ;; does not determine the width of the column.
14032 (if noalign (setq org-table-may-need-update c)))
14033 (backward-delete-char N)
14034 (org-fix-tags-on-the-fly)))
14036 (defun org-delete-char (N)
14037 "Like `delete-char', but insert whitespace at field end in tables.
14038 When deleting characters, in tables this function will insert whitespace in
14039 front of the next \"|\" separator, to keep the table aligned. The table will
14040 still be marked for re-alignment if the field did fill the entire column,
14041 because, in this case the deletion might narrow the column."
14042 (interactive "p")
14043 (if (and (org-table-p)
14044 (not (bolp))
14045 (not (= (char-after) ?|))
14046 (eq N 1))
14047 (if (looking-at ".*?|")
14048 (let ((pos (point))
14049 (noalign (looking-at "[^|\n\r]* |"))
14050 (c org-table-may-need-update))
14051 (replace-match (concat
14052 (substring (match-string 0) 1 -1)
14053 " |"))
14054 (goto-char pos)
14055 ;; noalign: if there were two spaces at the end, this field
14056 ;; does not determine the width of the column.
14057 (if noalign (setq org-table-may-need-update c)))
14058 (delete-char N))
14059 (delete-char N)
14060 (org-fix-tags-on-the-fly)))
14062 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14063 (put 'org-self-insert-command 'delete-selection t)
14064 (put 'orgtbl-self-insert-command 'delete-selection t)
14065 (put 'org-delete-char 'delete-selection 'supersede)
14066 (put 'org-delete-backward-char 'delete-selection 'supersede)
14067 (put 'org-yank 'delete-selection 'yank)
14069 ;; Make `flyspell-mode' delay after some commands
14070 (put 'org-self-insert-command 'flyspell-delayed t)
14071 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14072 (put 'org-delete-char 'flyspell-delayed t)
14073 (put 'org-delete-backward-char 'flyspell-delayed t)
14075 ;; Make pabbrev-mode expand after org-mode commands
14076 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14077 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14079 ;; How to do this: Measure non-white length of current string
14080 ;; If equal to column width, we should realign.
14082 (defun org-remap (map &rest commands)
14083 "In MAP, remap the functions given in COMMANDS.
14084 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14085 (let (new old)
14086 (while commands
14087 (setq old (pop commands) new (pop commands))
14088 (if (fboundp 'command-remapping)
14089 (org-defkey map (vector 'remap old) new)
14090 (substitute-key-definition old new map global-map)))))
14092 (when (eq org-enable-table-editor 'optimized)
14093 ;; If the user wants maximum table support, we need to hijack
14094 ;; some standard editing functions
14095 (org-remap org-mode-map
14096 'self-insert-command 'org-self-insert-command
14097 'delete-char 'org-delete-char
14098 'delete-backward-char 'org-delete-backward-char)
14099 (org-defkey org-mode-map "|" 'org-force-self-insert))
14101 (defvar org-ctrl-c-ctrl-c-hook nil
14102 "Hook for functions attaching themselves to `C-c C-c'.
14103 This can be used to add additional functionality to the C-c C-c key which
14104 executes context-dependent commands.
14105 Each function will be called with no arguments. The function must check
14106 if the context is appropriate for it to act. If yes, it should do its
14107 thing and then return a non-nil value. If the context is wrong,
14108 just do nothing and return nil.")
14110 (defvar org-tab-first-hook nil
14111 "Hook for functions to attach themselves to TAB.
14112 See `org-ctrl-c-ctrl-c-hook' for more information.
14113 This hook runs as the first action when TAB is pressed, even before
14114 `org-cycle' messes around with the `outline-regexp' to cater for
14115 inline tasks and plain list item folding.
14116 If any function in this hook returns t, not other actions like table
14117 field motion visibility cycling will be done.")
14119 (defvar org-tab-after-check-for-table-hook nil
14120 "Hook for functions to attach themselves to TAB.
14121 See `org-ctrl-c-ctrl-c-hook' for more information.
14122 This hook runs after it has been established that the cursor is not in a
14123 table, but before checking if the cursor is in a headline or if global cycling
14124 should be done.
14125 If any function in this hook returns t, not other actions like visibility
14126 cycling will be done.")
14128 (defvar org-tab-after-check-for-cycling-hook nil
14129 "Hook for functions to attach themselves to TAB.
14130 See `org-ctrl-c-ctrl-c-hook' for more information.
14131 This hook runs after it has been established that not table field motion and
14132 not visibility should be done because of current context. This is probably
14133 the place where a package like yasnippets can hook in.")
14135 (defvar org-metaleft-hook nil
14136 "Hook for functions attaching themselves to `M-left'.
14137 See `org-ctrl-c-ctrl-c-hook' for more information.")
14138 (defvar org-metaright-hook nil
14139 "Hook for functions attaching themselves to `M-right'.
14140 See `org-ctrl-c-ctrl-c-hook' for more information.")
14141 (defvar org-metaup-hook nil
14142 "Hook for functions attaching themselves to `M-up'.
14143 See `org-ctrl-c-ctrl-c-hook' for more information.")
14144 (defvar org-metadown-hook nil
14145 "Hook for functions attaching themselves to `M-down'.
14146 See `org-ctrl-c-ctrl-c-hook' for more information.")
14147 (defvar org-shiftmetaleft-hook nil
14148 "Hook for functions attaching themselves to `M-S-left'.
14149 See `org-ctrl-c-ctrl-c-hook' for more information.")
14150 (defvar org-shiftmetaright-hook nil
14151 "Hook for functions attaching themselves to `M-S-right'.
14152 See `org-ctrl-c-ctrl-c-hook' for more information.")
14153 (defvar org-shiftmetaup-hook nil
14154 "Hook for functions attaching themselves to `M-S-up'.
14155 See `org-ctrl-c-ctrl-c-hook' for more information.")
14156 (defvar org-shiftmetadown-hook nil
14157 "Hook for functions attaching themselves to `M-S-down'.
14158 See `org-ctrl-c-ctrl-c-hook' for more information.")
14159 (defvar org-metareturn-hook nil
14160 "Hook for functions attaching themselves to `M-RET'.
14161 See `org-ctrl-c-ctrl-c-hook' for more information.")
14163 (defun org-modifier-cursor-error ()
14164 "Throw an error, a modified cursor command was applied in wrong context."
14165 (error "This command is active in special context like tables, headlines or items"))
14167 (defun org-shiftselect-error ()
14168 "Throw an error because Shift-Cursor command was applied in wrong context."
14169 (if (and (boundp 'shift-select-mode) shift-select-mode)
14170 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14171 (error "This command works only in special context like headlines or timestamps.")))
14173 (defun org-call-for-shift-select (cmd)
14174 (let ((this-command-keys-shift-translated t))
14175 (call-interactively cmd)))
14177 (defun org-shifttab (&optional arg)
14178 "Global visibility cycling or move to previous table field.
14179 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14180 on context.
14181 See the individual commands for more information."
14182 (interactive "P")
14183 (cond
14184 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14185 ((integerp arg)
14186 (message "Content view to level: %d" arg)
14187 (org-content (prefix-numeric-value arg))
14188 (setq org-cycle-global-status 'overview))
14189 (t (call-interactively 'org-global-cycle))))
14191 (defun org-shiftmetaleft ()
14192 "Promote subtree or delete table column.
14193 Calls `org-promote-subtree', `org-outdent-item',
14194 or `org-table-delete-column', depending on context.
14195 See the individual commands for more information."
14196 (interactive)
14197 (cond
14198 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14199 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14200 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14201 ((org-at-item-p) (call-interactively 'org-outdent-item))
14202 (t (org-modifier-cursor-error))))
14204 (defun org-shiftmetaright ()
14205 "Demote subtree or insert table column.
14206 Calls `org-demote-subtree', `org-indent-item',
14207 or `org-table-insert-column', depending on context.
14208 See the individual commands for more information."
14209 (interactive)
14210 (cond
14211 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14212 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14213 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14214 ((org-at-item-p) (call-interactively 'org-indent-item))
14215 (t (org-modifier-cursor-error))))
14217 (defun org-shiftmetaup (&optional arg)
14218 "Move subtree up or kill table row.
14219 Calls `org-move-subtree-up' or `org-table-kill-row' or
14220 `org-move-item-up' depending on context. See the individual commands
14221 for more information."
14222 (interactive "P")
14223 (cond
14224 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14225 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14226 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14227 ((org-at-item-p) (call-interactively 'org-move-item-up))
14228 (t (org-modifier-cursor-error))))
14230 (defun org-shiftmetadown (&optional arg)
14231 "Move subtree down or insert table row.
14232 Calls `org-move-subtree-down' or `org-table-insert-row' or
14233 `org-move-item-down', depending on context. See the individual
14234 commands for more information."
14235 (interactive "P")
14236 (cond
14237 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14238 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14239 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14240 ((org-at-item-p) (call-interactively 'org-move-item-down))
14241 (t (org-modifier-cursor-error))))
14243 (defun org-metaleft (&optional arg)
14244 "Promote heading or move table column to left.
14245 Calls `org-do-promote' or `org-table-move-column', depending on context.
14246 With no specific context, calls the Emacs default `backward-word'.
14247 See the individual commands for more information."
14248 (interactive "P")
14249 (cond
14250 ((run-hook-with-args-until-success 'org-metaleft-hook))
14251 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14252 ((or (org-on-heading-p)
14253 (and (org-region-active-p)
14254 (save-excursion
14255 (goto-char (region-beginning))
14256 (org-on-heading-p))))
14257 (call-interactively 'org-do-promote))
14258 ((or (org-at-item-p)
14259 (and (org-region-active-p)
14260 (save-excursion
14261 (goto-char (region-beginning))
14262 (org-at-item-p))))
14263 (call-interactively 'org-outdent-item))
14264 (t (call-interactively 'backward-word))))
14266 (defun org-metaright (&optional arg)
14267 "Demote subtree or move table column to right.
14268 Calls `org-do-demote' or `org-table-move-column', depending on context.
14269 With no specific context, calls the Emacs default `forward-word'.
14270 See the individual commands for more information."
14271 (interactive "P")
14272 (cond
14273 ((run-hook-with-args-until-success 'org-metaright-hook))
14274 ((org-at-table-p) (call-interactively 'org-table-move-column))
14275 ((or (org-on-heading-p)
14276 (and (org-region-active-p)
14277 (save-excursion
14278 (goto-char (region-beginning))
14279 (org-on-heading-p))))
14280 (call-interactively 'org-do-demote))
14281 ((or (org-at-item-p)
14282 (and (org-region-active-p)
14283 (save-excursion
14284 (goto-char (region-beginning))
14285 (org-at-item-p))))
14286 (call-interactively 'org-indent-item))
14287 (t (call-interactively 'forward-word))))
14289 (defun org-metaup (&optional arg)
14290 "Move subtree up or move table row up.
14291 Calls `org-move-subtree-up' or `org-table-move-row' or
14292 `org-move-item-up', depending on context. See the individual commands
14293 for more information."
14294 (interactive "P")
14295 (cond
14296 ((run-hook-with-args-until-success 'org-metaup-hook))
14297 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14298 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14299 ((org-at-item-p) (call-interactively 'org-move-item-up))
14300 (t (transpose-lines 1) (beginning-of-line -1))))
14302 (defun org-metadown (&optional arg)
14303 "Move subtree down or move table row down.
14304 Calls `org-move-subtree-down' or `org-table-move-row' or
14305 `org-move-item-down', depending on context. See the individual
14306 commands for more information."
14307 (interactive "P")
14308 (cond
14309 ((run-hook-with-args-until-success 'org-metadown-hook))
14310 ((org-at-table-p) (call-interactively 'org-table-move-row))
14311 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14312 ((org-at-item-p) (call-interactively 'org-move-item-down))
14313 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14315 (defun org-shiftup (&optional arg)
14316 "Increase item in timestamp or increase priority of current headline.
14317 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14318 depending on context. See the individual commands for more information."
14319 (interactive "P")
14320 (cond
14321 ((and org-support-shift-select (org-region-active-p))
14322 (org-call-for-shift-select 'previous-line))
14323 ((org-at-timestamp-p t)
14324 (call-interactively (if org-edit-timestamp-down-means-later
14325 'org-timestamp-down 'org-timestamp-up)))
14326 ((and (not (eq org-support-shift-select 'always))
14327 org-enable-priority-commands
14328 (org-on-heading-p))
14329 (call-interactively 'org-priority-up))
14330 ((and (not org-support-shift-select) (org-at-item-p))
14331 (call-interactively 'org-previous-item))
14332 ((org-clocktable-try-shift 'up arg))
14333 (org-support-shift-select
14334 (org-call-for-shift-select 'previous-line))
14335 (t (org-shiftselect-error))))
14337 (defun org-shiftdown (&optional arg)
14338 "Decrease item in timestamp or decrease priority of current headline.
14339 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14340 depending on context. See the individual commands for more information."
14341 (interactive "P")
14342 (cond
14343 ((and org-support-shift-select (org-region-active-p))
14344 (org-call-for-shift-select 'next-line))
14345 ((org-at-timestamp-p t)
14346 (call-interactively (if org-edit-timestamp-down-means-later
14347 'org-timestamp-up 'org-timestamp-down)))
14348 ((and (not (eq org-support-shift-select 'always))
14349 org-enable-priority-commands
14350 (org-on-heading-p))
14351 (call-interactively 'org-priority-down))
14352 ((and (not org-support-shift-select) (org-at-item-p))
14353 (call-interactively 'org-next-item))
14354 ((org-clocktable-try-shift 'down arg))
14355 (org-support-shift-select
14356 (org-call-for-shift-select 'next-line))
14357 (t (org-shiftselect-error))))
14359 (defun org-shiftright (&optional arg)
14360 "Cycle the thing at point or in the current line, depending on context.
14361 Depending on context, this does one of the following:
14363 - switch a timestamp at point one day into the future
14364 - on a headline, switch to the next TODO keyword.
14365 - on an item, switch entire list to the next bullet type
14366 - on a property line, switch to the next allowed value
14367 - on a clocktable definition line, move time block into the future"
14368 (interactive "P")
14369 (cond
14370 ((and org-support-shift-select (org-region-active-p))
14371 (org-call-for-shift-select 'forward-char))
14372 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14373 ((and (not (eq org-support-shift-select 'always))
14374 (org-on-heading-p))
14375 (let ((org-inhibit-logging
14376 (not org-treat-S-cursor-todo-selection-as-state-change))
14377 (org-inhibit-blocking
14378 (not org-treat-S-cursor-todo-selection-as-state-change)))
14379 (org-call-with-arg 'org-todo 'right)))
14380 ((or (and org-support-shift-select
14381 (not (eq org-support-shift-select 'always))
14382 (org-at-item-bullet-p))
14383 (and (not org-support-shift-select) (org-at-item-p)))
14384 (org-call-with-arg 'org-cycle-list-bullet nil))
14385 ((and (not (eq org-support-shift-select 'always))
14386 (org-at-property-p))
14387 (call-interactively 'org-property-next-allowed-value))
14388 ((org-clocktable-try-shift 'right arg))
14389 (org-support-shift-select
14390 (org-call-for-shift-select 'forward-char))
14391 (t (org-shiftselect-error))))
14393 (defun org-shiftleft (&optional arg)
14394 "Cycle the thing at point or in the current line, depending on context.
14395 Depending on context, this does one of the following:
14397 - switch a timestamp at point one day into the past
14398 - on a headline, switch to the previous TODO keyword.
14399 - on an item, switch entire list to the previous bullet type
14400 - on a property line, switch to the previous allowed value
14401 - on a clocktable definition line, move time block into the past"
14402 (interactive "P")
14403 (cond
14404 ((and org-support-shift-select (org-region-active-p))
14405 (org-call-for-shift-select 'backward-char))
14406 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14407 ((and (not (eq org-support-shift-select 'always))
14408 (org-on-heading-p))
14409 (let ((org-inhibit-logging
14410 (not org-treat-S-cursor-todo-selection-as-state-change))
14411 (org-inhibit-blocking
14412 (not org-treat-S-cursor-todo-selection-as-state-change)))
14413 (org-call-with-arg 'org-todo 'left)))
14414 ((or (and org-support-shift-select
14415 (not (eq org-support-shift-select 'always))
14416 (org-at-item-bullet-p))
14417 (and (not org-support-shift-select) (org-at-item-p)))
14418 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14419 ((and (not (eq org-support-shift-select 'always))
14420 (org-at-property-p))
14421 (call-interactively 'org-property-previous-allowed-value))
14422 ((org-clocktable-try-shift 'left arg))
14423 (org-support-shift-select
14424 (org-call-for-shift-select 'backward-char))
14425 (t (org-shiftselect-error))))
14427 (defun org-shiftcontrolright ()
14428 "Switch to next TODO set."
14429 (interactive)
14430 (cond
14431 ((and org-support-shift-select (org-region-active-p))
14432 (org-call-for-shift-select 'forward-word))
14433 ((and (not (eq org-support-shift-select 'always))
14434 (org-on-heading-p))
14435 (org-call-with-arg 'org-todo 'nextset))
14436 (org-support-shift-select
14437 (org-call-for-shift-select 'forward-word))
14438 (t (org-shiftselect-error))))
14440 (defun org-shiftcontrolleft ()
14441 "Switch to previous TODO set."
14442 (interactive)
14443 (cond
14444 ((and org-support-shift-select (org-region-active-p))
14445 (org-call-for-shift-select 'backward-word))
14446 ((and (not (eq org-support-shift-select 'always))
14447 (org-on-heading-p))
14448 (org-call-with-arg 'org-todo 'previousset))
14449 (org-support-shift-select
14450 (org-call-for-shift-select 'backward-word))
14451 (t (org-shiftselect-error))))
14453 (defun org-ctrl-c-ret ()
14454 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14455 (interactive)
14456 (cond
14457 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14458 (t (call-interactively 'org-insert-heading))))
14460 (defun org-copy-special ()
14461 "Copy region in table or copy current subtree.
14462 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14463 See the individual commands for more information."
14464 (interactive)
14465 (call-interactively
14466 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14468 (defun org-cut-special ()
14469 "Cut region in table or cut current subtree.
14470 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14471 See the individual commands for more information."
14472 (interactive)
14473 (call-interactively
14474 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14476 (defun org-paste-special (arg)
14477 "Paste rectangular region into table, or past subtree relative to level.
14478 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14479 See the individual commands for more information."
14480 (interactive "P")
14481 (if (org-at-table-p)
14482 (org-table-paste-rectangle)
14483 (org-paste-subtree arg)))
14485 (defun org-edit-special ()
14486 "Call a special editor for the stuff at point.
14487 When at a table, call the formula editor with `org-table-edit-formulas'.
14488 When at the first line of an src example, call `org-edit-src-code'.
14489 When in an #+include line, visit the include file. Otherwise call
14490 `ffap' to visit the file at point."
14491 (interactive)
14492 (cond
14493 ((org-at-table-p)
14494 (call-interactively 'org-table-edit-formulas))
14495 ((save-excursion
14496 (beginning-of-line 1)
14497 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14498 (find-file (org-trim (match-string 1))))
14499 ((org-edit-src-code))
14500 ((org-edit-fixed-width-region))
14501 (t (call-interactively 'ffap))))
14504 (defun org-ctrl-c-ctrl-c (&optional arg)
14505 "Set tags in headline, or update according to changed information at point.
14507 This command does many different things, depending on context:
14509 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14510 this is what we do.
14512 - If the cursor is in a headline, prompt for tags and insert them
14513 into the current line, aligned to `org-tags-column'. When called
14514 with prefix arg, realign all tags in the current buffer.
14516 - If the cursor is in one of the special #+KEYWORD lines, this
14517 triggers scanning the buffer for these lines and updating the
14518 information.
14520 - If the cursor is inside a table, realign the table. This command
14521 works even if the automatic table editor has been turned off.
14523 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14524 the entire table.
14526 - If the cursor is at a footnote reference or definition, jump to
14527 the corresponding definition or references, respectively.
14529 - If the cursor is a the beginning of a dynamic block, update it.
14531 - If the cursor is inside a table created by the table.el package,
14532 activate that table.
14534 - If the current buffer is a remember buffer, close note and file
14535 it. A prefix argument of 1 files to the default location
14536 without further interaction. A prefix argument of 2 files to
14537 the currently clocking task.
14539 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14540 links in this buffer.
14542 - If the cursor is on a numbered item in a plain list, renumber the
14543 ordered list.
14545 - If the cursor is on a checkbox, toggle it."
14546 (interactive "P")
14547 (let ((org-enable-table-editor t))
14548 (cond
14549 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14550 org-occur-highlights
14551 org-latex-fragment-image-overlays)
14552 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14553 (org-remove-occur-highlights)
14554 (org-remove-latex-fragment-image-overlays)
14555 (message "Temporary highlights/overlays removed from current buffer"))
14556 ((and (local-variable-p 'org-finish-function (current-buffer))
14557 (fboundp org-finish-function))
14558 (funcall org-finish-function))
14559 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14560 ((org-at-property-p)
14561 (call-interactively 'org-property-action))
14562 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14563 ((org-on-heading-p) (call-interactively 'org-set-tags))
14564 ((org-at-table.el-p)
14565 (require 'table)
14566 (beginning-of-line 1)
14567 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14568 (call-interactively 'table-recognize-table))
14569 ((org-at-table-p)
14570 (org-table-maybe-eval-formula)
14571 (if arg
14572 (call-interactively 'org-table-recalculate)
14573 (org-table-maybe-recalculate-line))
14574 (call-interactively 'org-table-align))
14575 ((or (org-footnote-at-reference-p)
14576 (org-footnote-at-definition-p))
14577 (call-interactively 'org-footnote-action))
14578 ((org-at-item-checkbox-p)
14579 (call-interactively 'org-toggle-checkbox))
14580 ((org-at-item-p)
14581 (if arg
14582 (call-interactively 'org-toggle-checkbox)
14583 (call-interactively 'org-maybe-renumber-ordered-list)))
14584 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14585 ;; Dynamic block
14586 (beginning-of-line 1)
14587 (save-excursion (org-update-dblock)))
14588 ((save-excursion
14589 (beginning-of-line 1)
14590 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
14591 (cond
14592 ((equal (match-string 1) "TBLFM")
14593 ;; Recalculate the table before this line
14594 (save-excursion
14595 (beginning-of-line 1)
14596 (skip-chars-backward " \r\n\t")
14597 (if (org-at-table-p)
14598 (org-call-with-arg 'org-table-recalculate t))))
14600 ; (org-set-regexps-and-options)
14601 ; (org-restart-font-lock)
14602 (let ((org-inhibit-startup t)) (org-mode-restart))
14603 (message "Local setup has been refreshed"))))
14604 ((org-clock-update-time-maybe))
14605 (t (error "C-c C-c can do nothing useful at this location.")))))
14607 (defun org-mode-restart ()
14608 "Restart Org-mode, to scan again for special lines.
14609 Also updates the keyword regular expressions."
14610 (interactive)
14611 (org-mode)
14612 (message "Org-mode restarted"))
14614 (defun org-kill-note-or-show-branches ()
14615 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14616 (interactive)
14617 (if (not org-finish-function)
14618 (call-interactively 'show-branches)
14619 (let ((org-note-abort t))
14620 (funcall org-finish-function))))
14622 (defun org-return (&optional indent)
14623 "Goto next table row or insert a newline.
14624 Calls `org-table-next-row' or `newline', depending on context.
14625 See the individual commands for more information."
14626 (interactive)
14627 (cond
14628 ((bobp) (if indent (newline-and-indent) (newline)))
14629 ((org-at-table-p)
14630 (org-table-justify-field-maybe)
14631 (call-interactively 'org-table-next-row))
14632 ((and org-return-follows-link
14633 (eq (get-text-property (point) 'face) 'org-link))
14634 (call-interactively 'org-open-at-point))
14635 ((and (org-at-heading-p)
14636 (looking-at
14637 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14638 (org-show-entry)
14639 (end-of-line 1)
14640 (newline))
14641 (t (if indent (newline-and-indent) (newline)))))
14643 (defun org-return-indent ()
14644 "Goto next table row or insert a newline and indent.
14645 Calls `org-table-next-row' or `newline-and-indent', depending on
14646 context. See the individual commands for more information."
14647 (interactive)
14648 (org-return t))
14650 (defun org-ctrl-c-star ()
14651 "Compute table, or change heading status of lines.
14652 Calls `org-table-recalculate' or `org-toggle-heading',
14653 depending on context."
14654 (interactive)
14655 (cond
14656 ((org-at-table-p)
14657 (call-interactively 'org-table-recalculate))
14659 ;; Convert all lines in region to list items
14660 (call-interactively 'org-toggle-heading))))
14662 (defun org-ctrl-c-minus ()
14663 "Insert separator line in table or modify bullet status of line.
14664 Also turns a plain line or a region of lines into list items.
14665 Calls `org-table-insert-hline', `org-toggle-item', or
14666 `org-cycle-list-bullet', depending on context."
14667 (interactive)
14668 (cond
14669 ((org-at-table-p)
14670 (call-interactively 'org-table-insert-hline))
14671 ((org-region-active-p)
14672 (call-interactively 'org-toggle-item))
14673 ((org-in-item-p)
14674 (call-interactively 'org-cycle-list-bullet))
14676 (call-interactively 'org-toggle-item))))
14678 (defun org-toggle-item ()
14679 "Convert headings or normal lines to items, items to normal lines.
14680 If there is no active region, only the current line is considered.
14682 If the first line in the region is a headline, convert all headlines to items.
14684 If the first line in the region is an item, convert all items to normal lines.
14686 If the first line is normal text, add an item bullet to each line."
14687 (interactive)
14688 (let (l2 l beg end)
14689 (if (org-region-active-p)
14690 (setq beg (region-beginning) end (region-end))
14691 (setq beg (point-at-bol)
14692 end (min (1+ (point-at-eol)) (point-max))))
14693 (save-excursion
14694 (goto-char end)
14695 (setq l2 (org-current-line))
14696 (goto-char beg)
14697 (beginning-of-line 1)
14698 (setq l (1- (org-current-line)))
14699 (if (org-at-item-p)
14700 ;; We already have items, de-itemize
14701 (while (< (setq l (1+ l)) l2)
14702 (when (org-at-item-p)
14703 (goto-char (match-beginning 2))
14704 (delete-region (match-beginning 2) (match-end 2))
14705 (and (looking-at "[ \t]+") (replace-match "")))
14706 (beginning-of-line 2))
14707 (if (org-on-heading-p)
14708 ;; Headings, convert to items
14709 (while (< (setq l (1+ l)) l2)
14710 (if (looking-at org-outline-regexp)
14711 (replace-match "- " t t))
14712 (beginning-of-line 2))
14713 ;; normal lines, turn them into items
14714 (while (< (setq l (1+ l)) l2)
14715 (unless (org-at-item-p)
14716 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14717 (replace-match "\\1- \\2")))
14718 (beginning-of-line 2)))))))
14720 (defun org-toggle-heading (&optional nstars)
14721 "Convert headings to normal text, or items or text to headings.
14722 If there is no active region, only the current line is considered.
14724 If the first line is a heading, remove the stars from all headlines
14725 in the region.
14727 If the first line is a plain list item, turn all plain list items into
14728 headings.
14730 If the first line is a normal line, turn each and every line in the region
14731 into a heading.
14733 When converting a line into a heading, the number of stars is chosen
14734 such that the lines become children of the current entry. However, when
14735 a prefix argument is given, its value determines the number of stars to add."
14736 (interactive "P")
14737 (let (l2 l itemp beg end)
14738 (if (org-region-active-p)
14739 (setq beg (region-beginning) end (region-end))
14740 (setq beg (point-at-bol)
14741 end (min (1+ (point-at-eol)) (point-max))))
14742 (save-excursion
14743 (goto-char end)
14744 (setq l2 (org-current-line))
14745 (goto-char beg)
14746 (beginning-of-line 1)
14747 (setq l (1- (org-current-line)))
14748 (if (org-on-heading-p)
14749 ;; We already have headlines, de-star them
14750 (while (< (setq l (1+ l)) l2)
14751 (when (org-on-heading-p t)
14752 (and (looking-at outline-regexp) (replace-match "")))
14753 (beginning-of-line 2))
14754 (setq itemp (org-at-item-p))
14755 (let* ((stars
14756 (if nstars
14757 (make-string (prefix-numeric-value current-prefix-arg)
14759 (save-excursion
14760 (re-search-backward org-complex-heading-regexp nil t)
14761 (or (match-string 1) ""))))
14762 (add-stars (cond (nstars "")
14763 ((equal stars "") "*")
14764 (org-odd-levels-only "**")
14765 (t "*")))
14766 (rpl (concat stars add-stars " ")))
14767 (while (< (setq l (1+ l)) l2)
14768 (if itemp
14769 (and (org-at-item-p) (replace-match rpl t t))
14770 (unless (org-on-heading-p)
14771 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14772 (replace-match (concat rpl (match-string 2))))))
14773 (beginning-of-line 2)))))))
14775 (defun org-meta-return (&optional arg)
14776 "Insert a new heading or wrap a region in a table.
14777 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14778 See the individual commands for more information."
14779 (interactive "P")
14780 (cond
14781 ((run-hook-with-args-until-success 'org-metareturn-hook))
14782 ((org-at-table-p)
14783 (call-interactively 'org-table-wrap-region))
14784 (t (call-interactively 'org-insert-heading))))
14786 ;;; Menu entries
14788 ;; Define the Org-mode menus
14789 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14790 '("Tbl"
14791 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14792 ["Next Field" org-cycle (org-at-table-p)]
14793 ["Previous Field" org-shifttab (org-at-table-p)]
14794 ["Next Row" org-return (org-at-table-p)]
14795 "--"
14796 ["Blank Field" org-table-blank-field (org-at-table-p)]
14797 ["Edit Field" org-table-edit-field (org-at-table-p)]
14798 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14799 "--"
14800 ("Column"
14801 ["Move Column Left" org-metaleft (org-at-table-p)]
14802 ["Move Column Right" org-metaright (org-at-table-p)]
14803 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14804 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14805 ("Row"
14806 ["Move Row Up" org-metaup (org-at-table-p)]
14807 ["Move Row Down" org-metadown (org-at-table-p)]
14808 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14809 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14810 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14811 "--"
14812 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14813 ("Rectangle"
14814 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14815 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14816 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14817 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14818 "--"
14819 ("Calculate"
14820 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14821 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14822 ["Edit Formulas" org-edit-special (org-at-table-p)]
14823 "--"
14824 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14825 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14826 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14827 "--"
14828 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14829 "--"
14830 ["Sum Column/Rectangle" org-table-sum
14831 (or (org-at-table-p) (org-region-active-p))]
14832 ["Which Column?" org-table-current-column (org-at-table-p)])
14833 ["Debug Formulas"
14834 org-table-toggle-formula-debugger
14835 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14836 ["Show Col/Row Numbers"
14837 org-table-toggle-coordinate-overlays
14838 :style toggle
14839 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14840 "--"
14841 ["Create" org-table-create (and (not (org-at-table-p))
14842 org-enable-table-editor)]
14843 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14844 ["Import from File" org-table-import (not (org-at-table-p))]
14845 ["Export to File" org-table-export (org-at-table-p)]
14846 "--"
14847 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14849 (easy-menu-define org-org-menu org-mode-map "Org menu"
14850 '("Org"
14851 ("Show/Hide"
14852 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14853 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14854 ["Sparse Tree..." org-sparse-tree t]
14855 ["Reveal Context" org-reveal t]
14856 ["Show All" show-all t]
14857 "--"
14858 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14859 "--"
14860 ["New Heading" org-insert-heading t]
14861 ("Navigate Headings"
14862 ["Up" outline-up-heading t]
14863 ["Next" outline-next-visible-heading t]
14864 ["Previous" outline-previous-visible-heading t]
14865 ["Next Same Level" outline-forward-same-level t]
14866 ["Previous Same Level" outline-backward-same-level t]
14867 "--"
14868 ["Jump" org-goto t])
14869 ("Edit Structure"
14870 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14871 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14872 "--"
14873 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14874 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14875 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14876 "--"
14877 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14878 "--"
14879 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14880 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14881 ["Demote Heading" org-metaright (not (org-at-table-p))]
14882 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14883 "--"
14884 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14885 "--"
14886 ["Convert to odd levels" org-convert-to-odd-levels t]
14887 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14888 ("Editing"
14889 ["Emphasis..." org-emphasize t]
14890 ["Edit Source Example" org-edit-special t]
14891 "--"
14892 ["Footnote new/jump" org-footnote-action t]
14893 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14894 ("Archive"
14895 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14896 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14897 ; :active t :keys "C-u C-c C-x C-a"]
14898 ["Sparse trees open ARCHIVE trees"
14899 (setq org-sparse-tree-open-archived-trees
14900 (not org-sparse-tree-open-archived-trees))
14901 :style toggle :selected org-sparse-tree-open-archived-trees]
14902 ["Cycling opens ARCHIVE trees"
14903 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14904 :style toggle :selected org-cycle-open-archived-trees]
14905 "--"
14906 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14907 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14908 ; ["Check and Move Children" (org-archive-subtree '(4))
14909 ; :active t :keys "C-u C-c C-x C-s"]
14911 "--"
14912 ("Hyperlinks"
14913 ["Store Link (Global)" org-store-link t]
14914 ["Insert Link" org-insert-link t]
14915 ["Follow Link" org-open-at-point t]
14916 "--"
14917 ["Next link" org-next-link t]
14918 ["Previous link" org-previous-link t]
14919 "--"
14920 ["Descriptive Links"
14921 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14922 :style radio
14923 :selected (member '(org-link) buffer-invisibility-spec)]
14924 ["Literal Links"
14925 (progn
14926 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14927 :style radio
14928 :selected (not (member '(org-link) buffer-invisibility-spec))])
14929 "--"
14930 ("TODO Lists"
14931 ["TODO/DONE/-" org-todo t]
14932 ("Select keyword"
14933 ["Next keyword" org-shiftright (org-on-heading-p)]
14934 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14935 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14936 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14937 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14938 ["Show TODO Tree" org-show-todo-tree t]
14939 ["Global TODO list" org-todo-list t]
14940 "--"
14941 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14942 :selected org-enforce-todo-dependencies :style toggle :active t]
14943 "Settings for tree at point"
14944 ["Do Children sequentially" org-toggle-ordered-property :style radio
14945 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14946 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14947 ["Do Children parallel" org-toggle-ordered-property :style radio
14948 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14949 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14950 "--"
14951 ["Set Priority" org-priority t]
14952 ["Priority Up" org-shiftup t]
14953 ["Priority Down" org-shiftdown t]
14954 "--"
14955 ["Get news from all feeds" org-feed-update-all t]
14956 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
14957 ["Customize feeds" (customize-variable 'org-feed-alist) t])
14958 ("TAGS and Properties"
14959 ["Set Tags" org-set-tags-command t]
14960 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14961 "--"
14962 ["Set property" org-set-property t]
14963 ["Column view of properties" org-columns t]
14964 ["Insert Column View DBlock" org-insert-columns-dblock t])
14965 ("Dates and Scheduling"
14966 ["Timestamp" org-time-stamp t]
14967 ["Timestamp (inactive)" org-time-stamp-inactive t]
14968 ("Change Date"
14969 ["1 Day Later" org-shiftright t]
14970 ["1 Day Earlier" org-shiftleft t]
14971 ["1 ... Later" org-shiftup t]
14972 ["1 ... Earlier" org-shiftdown t])
14973 ["Compute Time Range" org-evaluate-time-range t]
14974 ["Schedule Item" org-schedule t]
14975 ["Deadline" org-deadline t]
14976 "--"
14977 ["Custom time format" org-toggle-time-stamp-overlays
14978 :style radio :selected org-display-custom-times]
14979 "--"
14980 ["Goto Calendar" org-goto-calendar t]
14981 ["Date from Calendar" org-date-from-calendar t]
14982 "--"
14983 ["Start/Restart Timer" org-timer-start t]
14984 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14985 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14986 ["Insert Timer String" org-timer t]
14987 ["Insert Timer Item" org-timer-item t])
14988 ("Logging work"
14989 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
14990 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
14991 ["Clock out" org-clock-out t]
14992 ["Clock cancel" org-clock-cancel t]
14993 "--"
14994 ["Mark as default task" org-clock-mark-default-task t]
14995 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
14996 ["Goto running clock" org-clock-goto t]
14997 "--"
14998 ["Display times" org-clock-display t]
14999 ["Create clock table" org-clock-report t]
15000 "--"
15001 ["Record DONE time"
15002 (progn (setq org-log-done (not org-log-done))
15003 (message "Switching to %s will %s record a timestamp"
15004 (car org-done-keywords)
15005 (if org-log-done "automatically" "not")))
15006 :style toggle :selected org-log-done])
15007 "--"
15008 ["Agenda Command..." org-agenda t]
15009 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15010 ("File List for Agenda")
15011 ("Special views current file"
15012 ["TODO Tree" org-show-todo-tree t]
15013 ["Check Deadlines" org-check-deadlines t]
15014 ["Timeline" org-timeline t]
15015 ["Tags/Property tree" org-match-sparse-tree t])
15016 "--"
15017 ["Export/Publish..." org-export t]
15018 ("LaTeX"
15019 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15020 :selected org-cdlatex-mode]
15021 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15022 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15023 ["Modify math symbol" org-cdlatex-math-modify
15024 (org-inside-LaTeX-fragment-p)]
15025 ["Insert citation" org-reftex-citation t]
15026 "--"
15027 ["Export LaTeX fragments as images"
15028 (if (featurep 'org-exp)
15029 (setq org-export-with-LaTeX-fragments
15030 (not org-export-with-LaTeX-fragments))
15031 (require 'org-exp))
15032 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15033 org-export-with-LaTeX-fragments)])
15034 "--"
15035 ("Documentation"
15036 ["Show Version" org-version t]
15037 ["Info Documentation" org-info t])
15038 ("Customize"
15039 ["Browse Org Group" org-customize t]
15040 "--"
15041 ["Expand This Menu" org-create-customize-menu
15042 (fboundp 'customize-menu-create)])
15043 "--"
15044 ("Refresh/Reload"
15045 ["Refresh setup current buffer" org-mode-restart t]
15046 ["Reload Org (after update)" org-reload t]
15047 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15050 (defun org-info (&optional node)
15051 "Read documentation for Org-mode in the info system.
15052 With optional NODE, go directly to that node."
15053 (interactive)
15054 (info (format "(org)%s" (or node ""))))
15056 (defun org-install-agenda-files-menu ()
15057 (let ((bl (buffer-list)))
15058 (save-excursion
15059 (while bl
15060 (set-buffer (pop bl))
15061 (if (org-mode-p) (setq bl nil)))
15062 (when (org-mode-p)
15063 (easy-menu-change
15064 '("Org") "File List for Agenda"
15065 (append
15066 (list
15067 ["Edit File List" (org-edit-agenda-file-list) t]
15068 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15069 ["Remove Current File from List" org-remove-file t]
15070 ["Cycle through agenda files" org-cycle-agenda-files t]
15071 ["Occur in all agenda files" org-occur-in-agenda-files t]
15072 "--")
15073 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15075 ;;;; Documentation
15077 ;;;###autoload
15078 (defun org-require-autoloaded-modules ()
15079 (interactive)
15080 (mapc 'require
15081 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15082 org-docbook org-exp org-html org-icalendar
15083 org-id org-latex
15084 org-publish org-remember org-table
15085 org-timer org-xoxo)))
15087 ;;;###autoload
15088 (defun org-reload (&optional uncompiled)
15089 "Reload all org lisp files.
15090 With prefix arg UNCOMPILED, load the uncompiled versions."
15091 (interactive "P")
15092 (require 'find-func)
15093 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15094 (dir-org (file-name-directory (org-find-library-name "org")))
15095 (dir-org-contrib (ignore-errors
15096 (file-name-directory
15097 (org-find-library-name "org-contribdir"))))
15098 (files
15099 (append (directory-files dir-org t file-re)
15100 (and dir-org-contrib
15101 (directory-files dir-org-contrib t file-re))))
15102 (remove-re (concat (if (featurep 'xemacs)
15103 "org-colview" "org-colview-xemacs")
15104 "\\'")))
15105 (setq files (mapcar 'file-name-sans-extension files))
15106 (setq files (mapcar
15107 (lambda (x) (if (string-match remove-re x) nil x))
15108 files))
15109 (setq files (delq nil files))
15110 (mapc
15111 (lambda (f)
15112 (when (featurep (intern (file-name-nondirectory f)))
15113 (if (and (not uncompiled)
15114 (file-exists-p (concat f ".elc")))
15115 (load (concat f ".elc") nil nil t)
15116 (load (concat f ".el") nil nil t))))
15117 files))
15118 (org-version))
15120 ;;;###autoload
15121 (defun org-customize ()
15122 "Call the customize function with org as argument."
15123 (interactive)
15124 (org-load-modules-maybe)
15125 (org-require-autoloaded-modules)
15126 (customize-browse 'org))
15128 (defun org-create-customize-menu ()
15129 "Create a full customization menu for Org-mode, insert it into the menu."
15130 (interactive)
15131 (org-load-modules-maybe)
15132 (org-require-autoloaded-modules)
15133 (if (fboundp 'customize-menu-create)
15134 (progn
15135 (easy-menu-change
15136 '("Org") "Customize"
15137 `(["Browse Org group" org-customize t]
15138 "--"
15139 ,(customize-menu-create 'org)
15140 ["Set" Custom-set t]
15141 ["Save" Custom-save t]
15142 ["Reset to Current" Custom-reset-current t]
15143 ["Reset to Saved" Custom-reset-saved t]
15144 ["Reset to Standard Settings" Custom-reset-standard t]))
15145 (message "\"Org\"-menu now contains full customization menu"))
15146 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15148 ;;;; Miscellaneous stuff
15150 ;;; Generally useful functions
15152 (defun org-find-text-property-in-string (prop s)
15153 "Return the first non-nil value of property PROP in string S."
15154 (or (get-text-property 0 prop s)
15155 (get-text-property (or (next-single-property-change 0 prop s) 0)
15156 prop s)))
15158 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15159 "Display the given MESSAGE as a warning."
15160 (if (fboundp 'display-warning)
15161 (display-warning 'org message
15162 (if (featurep 'xemacs)
15163 'warning
15164 :warning))
15165 (let ((buf (get-buffer-create "*Org warnings*")))
15166 (with-current-buffer buf
15167 (goto-char (point-max))
15168 (insert "Warning (Org): " message)
15169 (unless (bolp)
15170 (newline)))
15171 (display-buffer buf)
15172 (sit-for 0))))
15174 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15175 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15176 (if (and marker (marker-buffer marker)
15177 (buffer-live-p (marker-buffer marker)))
15178 (progn
15179 (switch-to-buffer (marker-buffer marker))
15180 (if (or (> marker (point-max)) (< marker (point-min)))
15181 (widen))
15182 (goto-char marker)
15183 (org-show-context 'org-goto))
15184 (if bookmark
15185 (bookmark-jump bookmark)
15186 (error "Cannot find location"))))
15188 (defun org-quote-csv-field (s)
15189 "Quote field for inclusion in CSV material."
15190 (if (string-match "[\",]" s)
15191 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15194 (defun org-plist-delete (plist property)
15195 "Delete PROPERTY from PLIST.
15196 This is in contrast to merely setting it to 0."
15197 (let (p)
15198 (while plist
15199 (if (not (eq property (car plist)))
15200 (setq p (plist-put p (car plist) (nth 1 plist))))
15201 (setq plist (cddr plist)))
15204 (defun org-force-self-insert (N)
15205 "Needed to enforce self-insert under remapping."
15206 (interactive "p")
15207 (self-insert-command N))
15209 (defun org-string-width (s)
15210 "Compute width of string, ignoring invisible characters.
15211 This ignores character with invisibility property `org-link', and also
15212 characters with property `org-cwidth', because these will become invisible
15213 upon the next fontification round."
15214 (let (b l)
15215 (when (or (eq t buffer-invisibility-spec)
15216 (assq 'org-link buffer-invisibility-spec))
15217 (while (setq b (text-property-any 0 (length s)
15218 'invisible 'org-link s))
15219 (setq s (concat (substring s 0 b)
15220 (substring s (or (next-single-property-change
15221 b 'invisible s) (length s)))))))
15222 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15223 (setq s (concat (substring s 0 b)
15224 (substring s (or (next-single-property-change
15225 b 'org-cwidth s) (length s))))))
15226 (setq l (string-width s) b -1)
15227 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15228 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15231 (defun org-get-indentation (&optional line)
15232 "Get the indentation of the current line, interpreting tabs.
15233 When LINE is given, assume it represents a line and compute its indentation."
15234 (if line
15235 (if (string-match "^ *" (org-remove-tabs line))
15236 (match-end 0))
15237 (save-excursion
15238 (beginning-of-line 1)
15239 (skip-chars-forward " \t")
15240 (current-column))))
15242 (defun org-remove-tabs (s &optional width)
15243 "Replace tabulators in S with spaces.
15244 Assumes that s is a single line, starting in column 0."
15245 (setq width (or width tab-width))
15246 (while (string-match "\t" s)
15247 (setq s (replace-match
15248 (make-string
15249 (- (* width (/ (+ (match-beginning 0) width) width))
15250 (match-beginning 0)) ?\ )
15251 t t s)))
15254 (defun org-fix-indentation (line ind)
15255 "Fix indentation in LINE.
15256 IND is a cons cell with target and minimum indentation.
15257 If the current indentation in LINE is smaller than the minimum,
15258 leave it alone. If it is larger than ind, set it to the target."
15259 (let* ((l (org-remove-tabs line))
15260 (i (org-get-indentation l))
15261 (i1 (car ind)) (i2 (cdr ind)))
15262 (if (>= i i2) (setq l (substring line i2)))
15263 (if (> i1 0)
15264 (concat (make-string i1 ?\ ) l)
15265 l)))
15267 (defun org-remove-indentation (code &optional n)
15268 "Remove the maximum common indentation from the lines in CODE.
15269 N may optionally be the number of spaces to remove."
15270 (with-temp-buffer
15271 (insert code)
15272 (org-do-remove-indentation n)
15273 (buffer-string)))
15275 (defun org-do-remove-indentation (&optional n)
15276 "Remove the maximum common indentation from the buffer."
15277 (untabify (point-min) (point-max))
15278 (let ((min 10000) re)
15279 (if n
15280 (setq min n)
15281 (goto-char (point-min))
15282 (while (re-search-forward "^ *[^ \n]" nil t)
15283 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15284 (unless (or (= min 0) (= min 10000))
15285 (setq re (format "^ \\{%d\\}" min))
15286 (goto-char (point-min))
15287 (while (re-search-forward re nil t)
15288 (replace-match "")
15289 (end-of-line 1))
15290 min)))
15292 (defun org-base-buffer (buffer)
15293 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15294 (if (not buffer)
15295 buffer
15296 (or (buffer-base-buffer buffer)
15297 buffer)))
15299 (defun org-trim (s)
15300 "Remove whitespace at beginning and end of string."
15301 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15302 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15305 (defun org-wrap (string &optional width lines)
15306 "Wrap string to either a number of lines, or a width in characters.
15307 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15308 that costs. If there is a word longer than WIDTH, the text is actually
15309 wrapped to the length of that word.
15310 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15311 many lines, whatever width that takes.
15312 The return value is a list of lines, without newlines at the end."
15313 (let* ((words (org-split-string string "[ \t\n]+"))
15314 (maxword (apply 'max (mapcar 'org-string-width words)))
15315 w ll)
15316 (cond (width
15317 (org-do-wrap words (max maxword width)))
15318 (lines
15319 (setq w maxword)
15320 (setq ll (org-do-wrap words maxword))
15321 (if (<= (length ll) lines)
15323 (setq ll words)
15324 (while (> (length ll) lines)
15325 (setq w (1+ w))
15326 (setq ll (org-do-wrap words w)))
15327 ll))
15328 (t (error "Cannot wrap this")))))
15330 (defun org-do-wrap (words width)
15331 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15332 (let (lines line)
15333 (while words
15334 (setq line (pop words))
15335 (while (and words (< (+ (length line) (length (car words))) width))
15336 (setq line (concat line " " (pop words))))
15337 (setq lines (push line lines)))
15338 (nreverse lines)))
15340 (defun org-split-string (string &optional separators)
15341 "Splits STRING into substrings at SEPARATORS.
15342 No empty strings are returned if there are matches at the beginning
15343 and end of string."
15344 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15345 (start 0)
15346 notfirst
15347 (list nil))
15348 (while (and (string-match rexp string
15349 (if (and notfirst
15350 (= start (match-beginning 0))
15351 (< start (length string)))
15352 (1+ start) start))
15353 (< (match-beginning 0) (length string)))
15354 (setq notfirst t)
15355 (or (eq (match-beginning 0) 0)
15356 (and (eq (match-beginning 0) (match-end 0))
15357 (eq (match-beginning 0) start))
15358 (setq list
15359 (cons (substring string start (match-beginning 0))
15360 list)))
15361 (setq start (match-end 0)))
15362 (or (eq start (length string))
15363 (setq list
15364 (cons (substring string start)
15365 list)))
15366 (nreverse list)))
15368 (defun org-quote-vert (s)
15369 "Replace \"|\" with \"\\vert\"."
15370 (while (string-match "|" s)
15371 (setq s (replace-match "\\vert" t t s)))
15374 (defun org-uuidgen-p (s)
15375 "Is S an ID created by UUIDGEN?"
15376 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15378 (defun org-context ()
15379 "Return a list of contexts of the current cursor position.
15380 If several contexts apply, all are returned.
15381 Each context entry is a list with a symbol naming the context, and
15382 two positions indicating start and end of the context. Possible
15383 contexts are:
15385 :headline anywhere in a headline
15386 :headline-stars on the leading stars in a headline
15387 :todo-keyword on a TODO keyword (including DONE) in a headline
15388 :tags on the TAGS in a headline
15389 :priority on the priority cookie in a headline
15390 :item on the first line of a plain list item
15391 :item-bullet on the bullet/number of a plain list item
15392 :checkbox on the checkbox in a plain list item
15393 :table in an org-mode table
15394 :table-special on a special filed in a table
15395 :table-table in a table.el table
15396 :link on a hyperlink
15397 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15398 :target on a <<target>>
15399 :radio-target on a <<<radio-target>>>
15400 :latex-fragment on a LaTeX fragment
15401 :latex-preview on a LaTeX fragment with overlayed preview image
15403 This function expects the position to be visible because it uses font-lock
15404 faces as a help to recognize the following contexts: :table-special, :link,
15405 and :keyword."
15406 (let* ((f (get-text-property (point) 'face))
15407 (faces (if (listp f) f (list f)))
15408 (p (point)) clist o)
15409 ;; First the large context
15410 (cond
15411 ((org-on-heading-p t)
15412 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15413 (when (progn
15414 (beginning-of-line 1)
15415 (looking-at org-todo-line-tags-regexp))
15416 (push (org-point-in-group p 1 :headline-stars) clist)
15417 (push (org-point-in-group p 2 :todo-keyword) clist)
15418 (push (org-point-in-group p 4 :tags) clist))
15419 (goto-char p)
15420 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15421 (if (looking-at "\\[#[A-Z0-9]\\]")
15422 (push (org-point-in-group p 0 :priority) clist)))
15424 ((org-at-item-p)
15425 (push (org-point-in-group p 2 :item-bullet) clist)
15426 (push (list :item (point-at-bol)
15427 (save-excursion (org-end-of-item) (point)))
15428 clist)
15429 (and (org-at-item-checkbox-p)
15430 (push (org-point-in-group p 0 :checkbox) clist)))
15432 ((org-at-table-p)
15433 (push (list :table (org-table-begin) (org-table-end)) clist)
15434 (if (memq 'org-formula faces)
15435 (push (list :table-special
15436 (previous-single-property-change p 'face)
15437 (next-single-property-change p 'face)) clist)))
15438 ((org-at-table-p 'any)
15439 (push (list :table-table) clist)))
15440 (goto-char p)
15442 ;; Now the small context
15443 (cond
15444 ((org-at-timestamp-p)
15445 (push (org-point-in-group p 0 :timestamp) clist))
15446 ((memq 'org-link faces)
15447 (push (list :link
15448 (previous-single-property-change p 'face)
15449 (next-single-property-change p 'face)) clist))
15450 ((memq 'org-special-keyword faces)
15451 (push (list :keyword
15452 (previous-single-property-change p 'face)
15453 (next-single-property-change p 'face)) clist))
15454 ((org-on-target-p)
15455 (push (org-point-in-group p 0 :target) clist)
15456 (goto-char (1- (match-beginning 0)))
15457 (if (looking-at org-radio-target-regexp)
15458 (push (org-point-in-group p 0 :radio-target) clist))
15459 (goto-char p))
15460 ((setq o (car (delq nil
15461 (mapcar
15462 (lambda (x)
15463 (if (memq x org-latex-fragment-image-overlays) x))
15464 (org-overlays-at (point))))))
15465 (push (list :latex-fragment
15466 (org-overlay-start o) (org-overlay-end o)) clist)
15467 (push (list :latex-preview
15468 (org-overlay-start o) (org-overlay-end o)) clist))
15469 ((org-inside-LaTeX-fragment-p)
15470 ;; FIXME: positions wrong.
15471 (push (list :latex-fragment (point) (point)) clist)))
15473 (setq clist (nreverse (delq nil clist)))
15474 clist))
15476 ;; FIXME: Compare with at-regexp-p Do we need both?
15477 (defun org-in-regexp (re &optional nlines visually)
15478 "Check if point is inside a match of regexp.
15479 Normally only the current line is checked, but you can include NLINES extra
15480 lines both before and after point into the search.
15481 If VISUALLY is set, require that the cursor is not after the match but
15482 really on, so that the block visually is on the match."
15483 (catch 'exit
15484 (let ((pos (point))
15485 (eol (point-at-eol (+ 1 (or nlines 0))))
15486 (inc (if visually 1 0)))
15487 (save-excursion
15488 (beginning-of-line (- 1 (or nlines 0)))
15489 (while (re-search-forward re eol t)
15490 (if (and (<= (match-beginning 0) pos)
15491 (>= (+ inc (match-end 0)) pos))
15492 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15494 (defun org-at-regexp-p (regexp)
15495 "Is point inside a match of REGEXP in the current line?"
15496 (catch 'exit
15497 (save-excursion
15498 (let ((pos (point)) (end (point-at-eol)))
15499 (beginning-of-line 1)
15500 (while (re-search-forward regexp end t)
15501 (if (and (<= (match-beginning 0) pos)
15502 (>= (match-end 0) pos))
15503 (throw 'exit t)))
15504 nil))))
15506 (defun org-occur-in-agenda-files (regexp &optional nlines)
15507 "Call `multi-occur' with buffers for all agenda files."
15508 (interactive "sOrg-files matching: \np")
15509 (let* ((files (org-agenda-files))
15510 (tnames (mapcar 'file-truename files))
15511 (extra org-agenda-text-search-extra-files)
15513 (when (eq (car extra) 'agenda-archives)
15514 (setq extra (cdr extra))
15515 (setq files (org-add-archive-files files)))
15516 (while (setq f (pop extra))
15517 (unless (member (file-truename f) tnames)
15518 (add-to-list 'files f 'append)
15519 (add-to-list 'tnames (file-truename f) 'append)))
15520 (multi-occur
15521 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15522 regexp)))
15524 (if (boundp 'occur-mode-find-occurrence-hook)
15525 ;; Emacs 23
15526 (add-hook 'occur-mode-find-occurrence-hook
15527 (lambda ()
15528 (when (org-mode-p)
15529 (org-reveal))))
15530 ;; Emacs 22
15531 (defadvice occur-mode-goto-occurrence
15532 (after org-occur-reveal activate)
15533 (and (org-mode-p) (org-reveal)))
15534 (defadvice occur-mode-goto-occurrence-other-window
15535 (after org-occur-reveal activate)
15536 (and (org-mode-p) (org-reveal)))
15537 (defadvice occur-mode-display-occurrence
15538 (after org-occur-reveal activate)
15539 (when (org-mode-p)
15540 (let ((pos (occur-mode-find-occurrence)))
15541 (with-current-buffer (marker-buffer pos)
15542 (save-excursion
15543 (goto-char pos)
15544 (org-reveal)))))))
15546 (defun org-uniquify (list)
15547 "Remove duplicate elements from LIST."
15548 (let (res)
15549 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15550 res))
15552 (defun org-delete-all (elts list)
15553 "Remove all elements in ELTS from LIST."
15554 (while elts
15555 (setq list (delete (pop elts) list)))
15556 list)
15558 (defun org-back-over-empty-lines ()
15559 "Move backwards over whitespace, to the beginning of the first empty line.
15560 Returns the number of empty lines passed."
15561 (let ((pos (point)))
15562 (skip-chars-backward " \t\n\r")
15563 (beginning-of-line 2)
15564 (goto-char (min (point) pos))
15565 (count-lines (point) pos)))
15567 (defun org-skip-whitespace ()
15568 (skip-chars-forward " \t\n\r"))
15570 (defun org-point-in-group (point group &optional context)
15571 "Check if POINT is in match-group GROUP.
15572 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15573 match. If the match group does ot exist or point is not inside it,
15574 return nil."
15575 (and (match-beginning group)
15576 (>= point (match-beginning group))
15577 (<= point (match-end group))
15578 (if context
15579 (list context (match-beginning group) (match-end group))
15580 t)))
15582 (defun org-switch-to-buffer-other-window (&rest args)
15583 "Switch to buffer in a second window on the current frame.
15584 In particular, do not allow pop-up frames."
15585 (let (pop-up-frames special-display-buffer-names special-display-regexps
15586 special-display-function)
15587 (apply 'switch-to-buffer-other-window args)))
15589 (defun org-combine-plists (&rest plists)
15590 "Create a single property list from all plists in PLISTS.
15591 The process starts by copying the first list, and then setting properties
15592 from the other lists. Settings in the last list are the most significant
15593 ones and overrule settings in the other lists."
15594 (let ((rtn (copy-sequence (pop plists)))
15595 p v ls)
15596 (while plists
15597 (setq ls (pop plists))
15598 (while ls
15599 (setq p (pop ls) v (pop ls))
15600 (setq rtn (plist-put rtn p v))))
15601 rtn))
15603 (defun org-move-line-down (arg)
15604 "Move the current line down. With prefix argument, move it past ARG lines."
15605 (interactive "p")
15606 (let ((col (current-column))
15607 beg end pos)
15608 (beginning-of-line 1) (setq beg (point))
15609 (beginning-of-line 2) (setq end (point))
15610 (beginning-of-line (+ 1 arg))
15611 (setq pos (move-marker (make-marker) (point)))
15612 (insert (delete-and-extract-region beg end))
15613 (goto-char pos)
15614 (org-move-to-column col)))
15616 (defun org-move-line-up (arg)
15617 "Move the current line up. With prefix argument, move it past ARG lines."
15618 (interactive "p")
15619 (let ((col (current-column))
15620 beg end pos)
15621 (beginning-of-line 1) (setq beg (point))
15622 (beginning-of-line 2) (setq end (point))
15623 (beginning-of-line (- arg))
15624 (setq pos (move-marker (make-marker) (point)))
15625 (insert (delete-and-extract-region beg end))
15626 (goto-char pos)
15627 (org-move-to-column col)))
15629 (defun org-replace-escapes (string table)
15630 "Replace %-escapes in STRING with values in TABLE.
15631 TABLE is an association list with keys like \"%a\" and string values.
15632 The sequences in STRING may contain normal field width and padding information,
15633 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15634 so values can contain further %-escapes if they are define later in TABLE."
15635 (let ((case-fold-search nil)
15636 e re rpl)
15637 (while (setq e (pop table))
15638 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15639 (while (string-match re string)
15640 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15641 (cdr e)))
15642 (setq string (replace-match rpl t t string))))
15643 string))
15646 (defun org-sublist (list start end)
15647 "Return a section of LIST, from START to END.
15648 Counting starts at 1."
15649 (let (rtn (c start))
15650 (setq list (nthcdr (1- start) list))
15651 (while (and list (<= c end))
15652 (push (pop list) rtn)
15653 (setq c (1+ c)))
15654 (nreverse rtn)))
15656 (defun org-find-base-buffer-visiting (file)
15657 "Like `find-buffer-visiting' but always return the base buffer and
15658 not an indirect buffer."
15659 (let ((buf (or (get-file-buffer file)
15660 (find-buffer-visiting file))))
15661 (if buf
15662 (or (buffer-base-buffer buf) buf)
15663 nil)))
15665 (defun org-image-file-name-regexp (&optional extensions)
15666 "Return regexp matching the file names of images.
15667 If EXTENSIONS is given, only match these."
15668 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15669 (image-file-name-regexp)
15670 (let ((image-file-name-extensions
15671 (or extensions
15672 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15673 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15674 (concat "\\."
15675 (regexp-opt (nconc (mapcar 'upcase
15676 image-file-name-extensions)
15677 image-file-name-extensions)
15679 "\\'"))))
15681 (defun org-file-image-p (file &optional extensions)
15682 "Return non-nil if FILE is an image."
15683 (save-match-data
15684 (string-match (org-image-file-name-regexp extensions) file)))
15686 (defun org-get-cursor-date ()
15687 "Return the date at cursor in as a time.
15688 This works in the calendar and in the agenda, anywhere else it just
15689 returns the current time."
15690 (let (date day defd)
15691 (cond
15692 ((eq major-mode 'calendar-mode)
15693 (setq date (calendar-cursor-to-date)
15694 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15695 ((eq major-mode 'org-agenda-mode)
15696 (setq day (get-text-property (point) 'day))
15697 (if day
15698 (setq date (calendar-gregorian-from-absolute day)
15699 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15700 (nth 2 date))))))
15701 (or defd (current-time))))
15703 (defvar org-agenda-action-marker (make-marker)
15704 "Marker pointing to the entry for the next agenda action.")
15706 (defun org-mark-entry-for-agenda-action ()
15707 "Mark the current entry as target of an agenda action.
15708 Agenda actions are actions executed from the agenda with the key `k',
15709 which make use of the date at the cursor."
15710 (interactive)
15711 (move-marker org-agenda-action-marker
15712 (save-excursion (org-back-to-heading t) (point))
15713 (current-buffer))
15714 (message
15715 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15717 ;;; Paragraph filling stuff.
15718 ;; We want this to be just right, so use the full arsenal.
15720 (defun org-indent-line-function ()
15721 "Indent line like previous, but further if previous was headline or item."
15722 (interactive)
15723 (let* ((pos (point))
15724 (itemp (org-at-item-p))
15725 (case-fold-search t)
15726 (org-drawer-regexp (or org-drawer-regexp "\000"))
15727 column bpos bcol tpos tcol bullet btype bullet-type)
15728 ;; Find the previous relevant line
15729 (beginning-of-line 1)
15730 (cond
15731 ((looking-at "#") (setq column 0))
15732 ((looking-at "\\*+ ") (setq column 0))
15733 ((and (looking-at "[ \t]*:END:")
15734 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15735 (save-excursion
15736 (goto-char (1- (match-beginning 1)))
15737 (setq column (current-column))))
15738 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
15739 (save-excursion
15740 (re-search-backward
15741 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
15742 (setq column (org-get-indentation (match-string 0))))
15744 (beginning-of-line 0)
15745 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15746 (not (looking-at "[ \t]*:END:"))
15747 (not (looking-at org-drawer-regexp)))
15748 (beginning-of-line 0))
15749 (cond
15750 ((looking-at "\\*+[ \t]+")
15751 (if (not org-adapt-indentation)
15752 (setq column 0)
15753 (goto-char (match-end 0))
15754 (setq column (current-column))))
15755 ((looking-at org-drawer-regexp)
15756 (goto-char (1- (match-beginning 1)))
15757 (setq column (current-column)))
15758 ((looking-at "\\([ \t]*\\):END:")
15759 (goto-char (match-end 1))
15760 (setq column (current-column)))
15761 ((org-in-item-p)
15762 (org-beginning-of-item)
15763 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15764 (setq bpos (match-beginning 1) tpos (match-end 0)
15765 bcol (progn (goto-char bpos) (current-column))
15766 tcol (progn (goto-char tpos) (current-column))
15767 bullet (match-string 1)
15768 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15769 (if (> tcol (+ bcol org-description-max-indent))
15770 (setq tcol (+ bcol 5)))
15771 (if (not itemp)
15772 (setq column tcol)
15773 (goto-char pos)
15774 (beginning-of-line 1)
15775 (if (looking-at "\\S-")
15776 (progn
15777 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15778 (setq bullet (match-string 1)
15779 btype (if (string-match "[0-9]" bullet) "n" bullet))
15780 (setq column (if (equal btype bullet-type) bcol tcol)))
15781 (setq column (org-get-indentation)))))
15782 (t (setq column (org-get-indentation))))))
15783 (goto-char pos)
15784 (if (<= (current-column) (current-indentation))
15785 (org-indent-line-to column)
15786 (save-excursion (org-indent-line-to column)))
15787 (setq column (current-column))
15788 (beginning-of-line 1)
15789 (if (looking-at
15790 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15791 (replace-match (concat "\\1" (format org-property-format
15792 (match-string 2) (match-string 3)))
15793 t nil))
15794 (org-move-to-column column)))
15796 (defun org-set-autofill-regexps ()
15797 (interactive)
15798 ;; In the paragraph separator we include headlines, because filling
15799 ;; text in a line directly attached to a headline would otherwise
15800 ;; fill the headline as well.
15801 (org-set-local 'comment-start-skip "^#+[ \t]*")
15802 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15803 ;; The paragraph starter includes hand-formatted lists.
15804 (org-set-local 'paragraph-start
15805 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15806 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15807 ;; But only if the user has not turned off tables or fixed-width regions
15808 (org-set-local
15809 'auto-fill-inhibit-regexp
15810 (concat "\\*+ \\|#\\+"
15811 "\\|[ \t]*" org-keyword-time-regexp
15812 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15813 (concat
15814 "\\|[ \t]*["
15815 (if org-enable-table-editor "|" "")
15816 (if org-enable-fixed-width-editor ":" "")
15817 "]"))))
15818 ;; We use our own fill-paragraph function, to make sure that tables
15819 ;; and fixed-width regions are not wrapped. That function will pass
15820 ;; through to `fill-paragraph' when appropriate.
15821 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15822 ; Adaptive filling: To get full control, first make sure that
15823 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15824 (org-set-local 'adaptive-fill-regexp "\000")
15825 (org-set-local 'adaptive-fill-function
15826 'org-adaptive-fill-function)
15827 (org-set-local
15828 'align-mode-rules-list
15829 '((org-in-buffer-settings
15830 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15831 (modes . '(org-mode))))))
15833 (defun org-fill-paragraph (&optional justify)
15834 "Re-align a table, pass through to fill-paragraph if no table."
15835 (let ((table-p (org-at-table-p))
15836 (table.el-p (org-at-table.el-p)))
15837 (cond ((and (equal (char-after (point-at-bol)) ?*)
15838 (save-excursion (goto-char (point-at-bol))
15839 (looking-at outline-regexp)))
15840 t) ; skip headlines
15841 (table.el-p t) ; skip table.el tables
15842 (table-p (org-table-align) t) ; align org-mode tables
15843 (t nil)))) ; call paragraph-fill
15845 ;; For reference, this is the default value of adaptive-fill-regexp
15846 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15848 (defun org-adaptive-fill-function ()
15849 "Return a fill prefix for org-mode files.
15850 In particular, this makes sure hanging paragraphs for hand-formatted lists
15851 work correctly."
15852 (cond ((looking-at "#[ \t]+")
15853 (match-string 0))
15854 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15855 (save-excursion
15856 (if (> (match-end 1) (+ (match-beginning 1)
15857 org-description-max-indent))
15858 (goto-char (+ (match-beginning 1) 5))
15859 (goto-char (match-end 0)))
15860 (make-string (current-column) ?\ )))
15861 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15862 (save-excursion
15863 (goto-char (match-end 0))
15864 (make-string (current-column) ?\ )))
15865 (t nil)))
15867 ;;; Other stuff.
15869 (defun org-toggle-fixed-width-section (arg)
15870 "Toggle the fixed-width export.
15871 If there is no active region, the QUOTE keyword at the current headline is
15872 inserted or removed. When present, it causes the text between this headline
15873 and the next to be exported as fixed-width text, and unmodified.
15874 If there is an active region, this command adds or removes a colon as the
15875 first character of this line. If the first character of a line is a colon,
15876 this line is also exported in fixed-width font."
15877 (interactive "P")
15878 (let* ((cc 0)
15879 (regionp (org-region-active-p))
15880 (beg (if regionp (region-beginning) (point)))
15881 (end (if regionp (region-end)))
15882 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15883 (case-fold-search nil)
15884 (re "[ \t]*\\(: \\)")
15885 off)
15886 (if regionp
15887 (save-excursion
15888 (goto-char beg)
15889 (setq cc (current-column))
15890 (beginning-of-line 1)
15891 (setq off (looking-at re))
15892 (while (> nlines 0)
15893 (setq nlines (1- nlines))
15894 (beginning-of-line 1)
15895 (cond
15896 (arg
15897 (org-move-to-column cc t)
15898 (insert ": \n")
15899 (forward-line -1))
15900 ((and off (looking-at re))
15901 (replace-match "" t t nil 1))
15902 ((not off) (org-move-to-column cc t) (insert ": ")))
15903 (forward-line 1)))
15904 (save-excursion
15905 (org-back-to-heading)
15906 (if (looking-at (concat outline-regexp
15907 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15908 (replace-match "" t t nil 1)
15909 (if (looking-at outline-regexp)
15910 (progn
15911 (goto-char (match-end 0))
15912 (insert org-quote-string " "))))))))
15914 (defun org-reftex-citation ()
15915 "Use reftex-citation to insert a citation into the buffer.
15916 This looks for a line like
15918 #+BIBLIOGRAPHY: foo plain option:-d
15920 and derives from it that foo.bib is the bbliography file relevant
15921 for this document. It then installs the necessary environment for RefTeX
15922 to work in this buffer and calls `reftex-citation' to insert a citation
15923 into the buffer.
15925 Export of such citations to both LaTeX and HTML is handled by the contributed
15926 package org-exp-bibtex by Taru Karttunen."
15927 (interactive)
15928 (let ((reftex-docstruct-symbol 'rds)
15929 (reftex-cite-format "\\cite{%l}")
15930 rds bib)
15931 (save-excursion
15932 (save-restriction
15933 (widen)
15934 (let ((case-fold-search t)
15935 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15936 (if (not (save-excursion
15937 (or (re-search-forward re nil t)
15938 (re-search-backward re nil t))))
15939 (error "No bibliography defined in file")
15940 (setq bib (concat (match-string 1) ".bib")
15941 rds (list (list 'bib bib)))))))
15942 (call-interactively 'reftex-citation)))
15944 ;;;; Functions extending outline functionality
15946 (defun org-beginning-of-line (&optional arg)
15947 "Go to the beginning of the current line. If that is invisible, continue
15948 to a visible line beginning. This makes the function of C-a more intuitive.
15949 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15950 first attempt, and only move to after the tags when the cursor is already
15951 beyond the end of the headline."
15952 (interactive "P")
15953 (let ((pos (point))
15954 (special (if (consp org-special-ctrl-a/e)
15955 (car org-special-ctrl-a/e)
15956 org-special-ctrl-a/e))
15957 refpos)
15958 (beginning-of-line 1)
15959 (if (and arg (fboundp 'move-beginning-of-line))
15960 (call-interactively 'move-beginning-of-line)
15961 (if (bobp)
15963 (backward-char 1)
15964 (if (org-invisible-p)
15965 (while (and (not (bobp)) (org-invisible-p))
15966 (backward-char 1)
15967 (beginning-of-line 1))
15968 (forward-char 1))))
15969 (when special
15970 (cond
15971 ((and (looking-at org-complex-heading-regexp)
15972 (= (char-after (match-end 1)) ?\ ))
15973 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15974 (point-at-eol)))
15975 (goto-char
15976 (if (eq special t)
15977 (cond ((> pos refpos) refpos)
15978 ((= pos (point)) refpos)
15979 (t (point)))
15980 (cond ((> pos (point)) (point))
15981 ((not (eq last-command this-command)) (point))
15982 (t refpos)))))
15983 ((org-at-item-p)
15984 (goto-char
15985 (if (eq special t)
15986 (cond ((> pos (match-end 4)) (match-end 4))
15987 ((= pos (point)) (match-end 4))
15988 (t (point)))
15989 (cond ((> pos (point)) (point))
15990 ((not (eq last-command this-command)) (point))
15991 (t (match-end 4))))))))
15992 (org-no-warnings
15993 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15995 (defun org-end-of-line (&optional arg)
15996 "Go to the end of the line.
15997 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15998 first attempt, and only move to after the tags when the cursor is already
15999 beyond the end of the headline."
16000 (interactive "P")
16001 (let ((special (if (consp org-special-ctrl-a/e)
16002 (cdr org-special-ctrl-a/e)
16003 org-special-ctrl-a/e)))
16004 (if (or (not special)
16005 (not (org-on-heading-p))
16006 arg)
16007 (call-interactively (if (fboundp 'move-end-of-line)
16008 'move-end-of-line
16009 'end-of-line))
16010 (let ((pos (point)))
16011 (beginning-of-line 1)
16012 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16013 (if (eq special t)
16014 (if (or (< pos (match-beginning 1))
16015 (= pos (match-end 0)))
16016 (goto-char (match-beginning 1))
16017 (goto-char (match-end 0)))
16018 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16019 (goto-char (match-end 0))
16020 (goto-char (match-beginning 1))))
16021 (call-interactively (if (fboundp 'move-end-of-line)
16022 'move-end-of-line
16023 'end-of-line)))))
16024 (org-no-warnings
16025 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16027 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16028 (define-key org-mode-map "\C-e" 'org-end-of-line)
16030 (defun org-backward-sentence (&optional arg)
16031 "Go to beginning of sentence, or beginning of table field.
16032 This will call `backward-sentence' or `org-table-beginning-of-field',
16033 depending on context."
16034 (interactive "P")
16035 (cond
16036 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16037 (t (call-interactively 'backward-sentence))))
16039 (defun org-forward-sentence (&optional arg)
16040 "Go to end of sentence, or end of table field.
16041 This will call `forward-sentence' or `org-table-end-of-field',
16042 depending on context."
16043 (interactive "P")
16044 (cond
16045 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16046 (t (call-interactively 'forward-sentence))))
16048 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16049 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16051 (defun org-kill-line (&optional arg)
16052 "Kill line, to tags or end of line."
16053 (interactive "P")
16054 (cond
16055 ((or (not org-special-ctrl-k)
16056 (bolp)
16057 (not (org-on-heading-p)))
16058 (call-interactively 'kill-line))
16059 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16060 (kill-region (point) (match-beginning 1))
16061 (org-set-tags nil t))
16062 (t (kill-region (point) (point-at-eol)))))
16064 (define-key org-mode-map "\C-k" 'org-kill-line)
16066 (defun org-yank (&optional arg)
16067 "Yank. If the kill is a subtree, treat it specially.
16068 This command will look at the current kill and check if is a single
16069 subtree, or a series of subtrees[1]. If it passes the test, and if the
16070 cursor is at the beginning of a line or after the stars of a currently
16071 empty headline, then the yank is handled specially. How exactly depends
16072 on the value of the following variables, both set by default.
16074 org-yank-folded-subtrees
16075 When set, the subtree(s) will be folded after insertion, but only
16076 if doing so would now swallow text after the yanked text.
16078 org-yank-adjusted-subtrees
16079 When set, the subtree will be promoted or demoted in order to
16080 fit into the local outline tree structure, which means that the level
16081 will be adjusted so that it becomes the smaller one of the two
16082 *visible* surrounding headings.
16084 Any prefix to this command will cause `yank' to be called directly with
16085 no special treatment. In particular, a simple `C-u' prefix will just
16086 plainly yank the text as it is.
16088 \[1] The test checks if the first non-white line is a heading
16089 and if there are no other headings with fewer stars."
16090 (interactive "P")
16091 (org-yank-generic 'yank arg))
16093 (defun org-yank-generic (command arg)
16094 "Perform some yank-like command.
16096 This function implements the behavior described in the `org-yank'
16097 documentation. However, it has been generalized to work for any
16098 interactive command with similar behavior."
16100 ;; pretend to be command COMMAND
16101 (setq this-command command)
16103 (if arg
16104 (call-interactively command)
16106 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16107 (and (org-kill-is-subtree-p)
16108 (or (bolp)
16109 (and (looking-at "[ \t]*$")
16110 (string-match
16111 "\\`\\*+\\'"
16112 (buffer-substring (point-at-bol) (point)))))))
16113 swallowp)
16114 (cond
16115 ((and subtreep org-yank-folded-subtrees)
16116 (let ((beg (point))
16117 end)
16118 (if (and subtreep org-yank-adjusted-subtrees)
16119 (org-paste-subtree nil nil 'for-yank)
16120 (call-interactively command))
16122 (setq end (point))
16123 (goto-char beg)
16124 (when (and (bolp) subtreep
16125 (not (setq swallowp
16126 (org-yank-folding-would-swallow-text beg end))))
16127 (or (looking-at outline-regexp)
16128 (re-search-forward (concat "^" outline-regexp) end t))
16129 (while (and (< (point) end) (looking-at outline-regexp))
16130 (hide-subtree)
16131 (org-cycle-show-empty-lines 'folded)
16132 (condition-case nil
16133 (outline-forward-same-level 1)
16134 (error (goto-char end)))))
16135 (when swallowp
16136 (message
16137 "Inserted text not folded because that would swallow text"))
16139 (goto-char end)
16140 (skip-chars-forward " \t\n\r")
16141 (beginning-of-line 1)
16142 (push-mark beg 'nomsg)))
16143 ((and subtreep org-yank-adjusted-subtrees)
16144 (let ((beg (point-at-bol)))
16145 (org-paste-subtree nil nil 'for-yank)
16146 (push-mark beg 'nomsg)))
16148 (call-interactively command))))))
16150 (defun org-yank-folding-would-swallow-text (beg end)
16151 "Would hide-subtree at BEG swallow any text after END?"
16152 (let (level)
16153 (save-excursion
16154 (goto-char beg)
16155 (when (or (looking-at outline-regexp)
16156 (re-search-forward (concat "^" outline-regexp) end t))
16157 (setq level (org-outline-level)))
16158 (goto-char end)
16159 (skip-chars-forward " \t\r\n\v\f")
16160 (if (or (eobp)
16161 (and (bolp) (looking-at org-outline-regexp)
16162 (<= (org-outline-level) level)))
16163 nil ; Nothing would be swallowed
16164 t)))) ; something would swallow
16166 (define-key org-mode-map "\C-y" 'org-yank)
16168 (defun org-invisible-p ()
16169 "Check if point is at a character currently not visible."
16170 ;; Early versions of noutline don't have `outline-invisible-p'.
16171 (if (fboundp 'outline-invisible-p)
16172 (outline-invisible-p)
16173 (get-char-property (point) 'invisible)))
16175 (defun org-invisible-p2 ()
16176 "Check if point is at a character currently not visible."
16177 (save-excursion
16178 (if (and (eolp) (not (bobp))) (backward-char 1))
16179 ;; Early versions of noutline don't have `outline-invisible-p'.
16180 (if (fboundp 'outline-invisible-p)
16181 (outline-invisible-p)
16182 (get-char-property (point) 'invisible))))
16184 (defun org-back-to-heading (&optional invisible-ok)
16185 "Call `outline-back-to-heading', but provide a better error message."
16186 (condition-case nil
16187 (outline-back-to-heading invisible-ok)
16188 (error (error "Before first headline at position %d in buffer %s"
16189 (point) (current-buffer)))))
16191 (defun org-before-first-heading-p ()
16192 "Before first heading?"
16193 (save-excursion
16194 (null (re-search-backward "^\\*+ " nil t))))
16196 (defalias 'org-on-heading-p 'outline-on-heading-p)
16197 (defalias 'org-at-heading-p 'outline-on-heading-p)
16198 (defun org-at-heading-or-item-p ()
16199 (or (org-on-heading-p) (org-at-item-p)))
16201 (defun org-on-target-p ()
16202 (or (org-in-regexp org-radio-target-regexp)
16203 (org-in-regexp org-target-regexp)))
16205 (defun org-up-heading-all (arg)
16206 "Move to the heading line of which the present line is a subheading.
16207 This function considers both visible and invisible heading lines.
16208 With argument, move up ARG levels."
16209 (if (fboundp 'outline-up-heading-all)
16210 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16211 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16213 (defun org-up-heading-safe ()
16214 "Move to the heading line of which the present line is a subheading.
16215 This version will not throw an error. It will return the level of the
16216 headline found, or nil if no higher level is found.
16218 Also, this function will be a lot faster than `outline-up-heading',
16219 because it relies on stars being the outline starters. This can really
16220 make a significant difference in outlines with very many siblings."
16221 (let (start-level re)
16222 (org-back-to-heading t)
16223 (setq start-level (funcall outline-level))
16224 (if (equal start-level 1)
16226 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16227 (if (re-search-backward re nil t)
16228 (funcall outline-level)))))
16230 (defun org-first-sibling-p ()
16231 "Is this heading the first child of its parents?"
16232 (interactive)
16233 (let ((re (concat "^" outline-regexp))
16234 level l)
16235 (unless (org-at-heading-p t)
16236 (error "Not at a heading"))
16237 (setq level (funcall outline-level))
16238 (save-excursion
16239 (if (not (re-search-backward re nil t))
16241 (setq l (funcall outline-level))
16242 (< l level)))))
16244 (defun org-goto-sibling (&optional previous)
16245 "Goto the next sibling, even if it is invisible.
16246 When PREVIOUS is set, go to the previous sibling instead. Returns t
16247 when a sibling was found. When none is found, return nil and don't
16248 move point."
16249 (let ((fun (if previous 're-search-backward 're-search-forward))
16250 (pos (point))
16251 (re (concat "^" outline-regexp))
16252 level l)
16253 (when (condition-case nil (org-back-to-heading t) (error nil))
16254 (setq level (funcall outline-level))
16255 (catch 'exit
16256 (or previous (forward-char 1))
16257 (while (funcall fun re nil t)
16258 (setq l (funcall outline-level))
16259 (when (< l level) (goto-char pos) (throw 'exit nil))
16260 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16261 (goto-char pos)
16262 nil))))
16264 (defun org-show-siblings ()
16265 "Show all siblings of the current headline."
16266 (save-excursion
16267 (while (org-goto-sibling) (org-flag-heading nil)))
16268 (save-excursion
16269 (while (org-goto-sibling 'previous)
16270 (org-flag-heading nil))))
16272 (defun org-show-hidden-entry ()
16273 "Show an entry where even the heading is hidden."
16274 (save-excursion
16275 (org-show-entry)))
16277 (defun org-flag-heading (flag &optional entry)
16278 "Flag the current heading. FLAG non-nil means make invisible.
16279 When ENTRY is non-nil, show the entire entry."
16280 (save-excursion
16281 (org-back-to-heading t)
16282 ;; Check if we should show the entire entry
16283 (if entry
16284 (progn
16285 (org-show-entry)
16286 (save-excursion
16287 (and (outline-next-heading)
16288 (org-flag-heading nil))))
16289 (outline-flag-region (max (point-min) (1- (point)))
16290 (save-excursion (outline-end-of-heading) (point))
16291 flag))))
16293 (defun org-forward-same-level (arg)
16294 "Move forward to the ARG'th subheading at same level as this one.
16295 Stop at the first and last subheadings of a superior heading.
16296 This is like outline-forward-same-level, but invisible headings are ok."
16297 (interactive "p")
16298 (org-back-to-heading t)
16299 (while (> arg 0)
16300 (let ((point-to-move-to (save-excursion
16301 (org-get-next-sibling))))
16302 (if point-to-move-to
16303 (progn
16304 (goto-char point-to-move-to)
16305 (setq arg (1- arg)))
16306 (progn
16307 (setq arg 0)
16308 (error "No following same-level heading"))))))
16310 (defun org-get-next-sibling ()
16311 "Move to next heading of the same level, and return point.
16312 If there is no such heading, return nil.
16313 This is like outline-next-sibling, but invisible headings are ok."
16314 (let ((level (funcall outline-level)))
16315 (outline-next-heading)
16316 (while (and (not (eobp)) (> (funcall outline-level) level))
16317 (outline-next-heading))
16318 (if (or (eobp) (< (funcall outline-level) level))
16320 (point))))
16322 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16323 ;; This contains an exact copy of the original function, but it uses
16324 ;; `org-back-to-heading', to make it work also in invisible
16325 ;; trees. And is uses an invisible-OK argument.
16326 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16327 ;; Furthermore, when used inside Org, finding the end of a large subtree
16328 ;; with many children and grandchildren etc, this can be much faster
16329 ;; than the outline version.
16330 (org-back-to-heading invisible-OK)
16331 (let ((first t)
16332 (level (funcall outline-level)))
16333 (if (and (org-mode-p) (< level 1000))
16334 ;; A true heading (not a plain list item), in Org-mode
16335 ;; This means we can easily find the end by looking
16336 ;; only for the right number of stars. Using a regexp to do
16337 ;; this is so much faster than using a Lisp loop.
16338 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16339 (forward-char 1)
16340 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16341 ;; something else, do it the slow way
16342 (while (and (not (eobp))
16343 (or first (> (funcall outline-level) level)))
16344 (setq first nil)
16345 (outline-next-heading)))
16346 (unless to-heading
16347 (if (memq (preceding-char) '(?\n ?\^M))
16348 (progn
16349 ;; Go to end of line before heading
16350 (forward-char -1)
16351 (if (memq (preceding-char) '(?\n ?\^M))
16352 ;; leave blank line before heading
16353 (forward-char -1))))))
16354 (point))
16356 (defun org-show-subtree ()
16357 "Show everything after this heading at deeper levels."
16358 (outline-flag-region
16359 (point)
16360 (save-excursion
16361 (outline-end-of-subtree) (outline-next-heading) (point))
16362 nil))
16364 (defun org-show-entry ()
16365 "Show the body directly following this heading.
16366 Show the heading too, if it is currently invisible."
16367 (interactive)
16368 (save-excursion
16369 (condition-case nil
16370 (progn
16371 (org-back-to-heading t)
16372 (outline-flag-region
16373 (max (point-min) (1- (point)))
16374 (save-excursion
16375 (if (re-search-forward
16376 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16377 (match-beginning 1)
16378 (point-max)))
16379 nil))
16380 (error nil))))
16382 (defun org-make-options-regexp (kwds &optional extra)
16383 "Make a regular expression for keyword lines."
16384 (concat
16386 "#?[ \t]*\\+\\("
16387 (mapconcat 'regexp-quote kwds "\\|")
16388 (if extra (concat "\\|" extra))
16389 "\\):[ \t]*"
16390 "\\(.+\\)"))
16392 ;; Make isearch reveal the necessary context
16393 (defun org-isearch-end ()
16394 "Reveal context after isearch exits."
16395 (when isearch-success ; only if search was successful
16396 (if (featurep 'xemacs)
16397 ;; Under XEmacs, the hook is run in the correct place,
16398 ;; we directly show the context.
16399 (org-show-context 'isearch)
16400 ;; In Emacs the hook runs *before* restoring the overlays.
16401 ;; So we have to use a one-time post-command-hook to do this.
16402 ;; (Emacs 22 has a special variable, see function `org-mode')
16403 (unless (and (boundp 'isearch-mode-end-hook-quit)
16404 isearch-mode-end-hook-quit)
16405 ;; Only when the isearch was not quitted.
16406 (org-add-hook 'post-command-hook 'org-isearch-post-command
16407 'append 'local)))))
16409 (defun org-isearch-post-command ()
16410 "Remove self from hook, and show context."
16411 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16412 (org-show-context 'isearch))
16415 ;;;; Integration with and fixes for other packages
16417 ;;; Imenu support
16419 (defvar org-imenu-markers nil
16420 "All markers currently used by Imenu.")
16421 (make-variable-buffer-local 'org-imenu-markers)
16423 (defun org-imenu-new-marker (&optional pos)
16424 "Return a new marker for use by Imenu, and remember the marker."
16425 (let ((m (make-marker)))
16426 (move-marker m (or pos (point)))
16427 (push m org-imenu-markers)
16430 (defun org-imenu-get-tree ()
16431 "Produce the index for Imenu."
16432 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16433 (setq org-imenu-markers nil)
16434 (let* ((n org-imenu-depth)
16435 (re (concat "^" outline-regexp))
16436 (subs (make-vector (1+ n) nil))
16437 (last-level 0)
16438 m level head)
16439 (save-excursion
16440 (save-restriction
16441 (widen)
16442 (goto-char (point-max))
16443 (while (re-search-backward re nil t)
16444 (setq level (org-reduced-level (funcall outline-level)))
16445 (when (<= level n)
16446 (looking-at org-complex-heading-regexp)
16447 (setq head (org-link-display-format
16448 (org-match-string-no-properties 4))
16449 m (org-imenu-new-marker))
16450 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16451 (if (>= level last-level)
16452 (push (cons head m) (aref subs level))
16453 (push (cons head (aref subs (1+ level))) (aref subs level))
16454 (loop for i from (1+ level) to n do (aset subs i nil)))
16455 (setq last-level level)))))
16456 (aref subs 1)))
16458 (eval-after-load "imenu"
16459 '(progn
16460 (add-hook 'imenu-after-jump-hook
16461 (lambda ()
16462 (if (eq major-mode 'org-mode)
16463 (org-show-context 'org-goto))))))
16465 (defun org-link-display-format (link)
16466 "Replace a link with either the description, or the link target
16467 if no description is present"
16468 (save-match-data
16469 (if (string-match org-bracket-link-analytic-regexp link)
16470 (replace-match (or (match-string 5 link)
16471 (concat (match-string 1 link)
16472 (match-string 3 link)))
16473 nil nil link)
16474 link)))
16476 ;; Speedbar support
16478 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16479 "Overlay marking the agenda restriction line in speedbar.")
16480 (org-overlay-put org-speedbar-restriction-lock-overlay
16481 'face 'org-agenda-restriction-lock)
16482 (org-overlay-put org-speedbar-restriction-lock-overlay
16483 'help-echo "Agendas are currently limited to this item.")
16484 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16486 (defun org-speedbar-set-agenda-restriction ()
16487 "Restrict future agenda commands to the location at point in speedbar.
16488 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16489 (interactive)
16490 (require 'org-agenda)
16491 (let (p m tp np dir txt)
16492 (cond
16493 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16494 'org-imenu t))
16495 (setq m (get-text-property p 'org-imenu-marker))
16496 (save-excursion
16497 (save-restriction
16498 (set-buffer (marker-buffer m))
16499 (goto-char m)
16500 (org-agenda-set-restriction-lock 'subtree))))
16501 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16502 'speedbar-function 'speedbar-find-file))
16503 (setq tp (previous-single-property-change
16504 (1+ p) 'speedbar-function)
16505 np (next-single-property-change
16506 tp 'speedbar-function)
16507 dir (speedbar-line-directory)
16508 txt (buffer-substring-no-properties (or tp (point-min))
16509 (or np (point-max))))
16510 (save-excursion
16511 (save-restriction
16512 (set-buffer (find-file-noselect
16513 (let ((default-directory dir))
16514 (expand-file-name txt))))
16515 (unless (org-mode-p)
16516 (error "Cannot restrict to non-Org-mode file"))
16517 (org-agenda-set-restriction-lock 'file))))
16518 (t (error "Don't know how to restrict Org-mode's agenda")))
16519 (org-move-overlay org-speedbar-restriction-lock-overlay
16520 (point-at-bol) (point-at-eol))
16521 (setq current-prefix-arg nil)
16522 (org-agenda-maybe-redo)))
16524 (eval-after-load "speedbar"
16525 '(progn
16526 (speedbar-add-supported-extension ".org")
16527 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16528 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16529 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16530 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16531 (add-hook 'speedbar-visiting-tag-hook
16532 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16535 ;;; Fixes and Hacks for problems with other packages
16537 ;; Make flyspell not check words in links, to not mess up our keymap
16538 (defun org-mode-flyspell-verify ()
16539 "Don't let flyspell put overlays at active buttons."
16540 (and (not (get-text-property (point) 'keymap))
16541 (not (get-text-property (point) 'org-no-flyspell))))
16543 (defun org-remove-flyspell-overlays-in (beg end)
16544 "Remove flyspell overlays in region."
16545 (and (org-bound-and-true-p flyspell-mode)
16546 (fboundp 'flyspell-delete-region-overlays)
16547 (flyspell-delete-region-overlays beg end))
16548 (add-text-properties beg end '(org-no-flyspell t)))
16550 ;; Make `bookmark-jump' show the jump location if it was hidden.
16551 (eval-after-load "bookmark"
16552 '(if (boundp 'bookmark-after-jump-hook)
16553 ;; We can use the hook
16554 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16555 ;; Hook not available, use advice
16556 (defadvice bookmark-jump (after org-make-visible activate)
16557 "Make the position visible."
16558 (org-bookmark-jump-unhide))))
16560 ;; Make sure saveplace show the location if it was hidden
16561 (eval-after-load "saveplace"
16562 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16563 "Make the position visible."
16564 (org-bookmark-jump-unhide)))
16566 (defun org-bookmark-jump-unhide ()
16567 "Unhide the current position, to show the bookmark location."
16568 (and (org-mode-p)
16569 (or (org-invisible-p)
16570 (save-excursion (goto-char (max (point-min) (1- (point))))
16571 (org-invisible-p)))
16572 (org-show-context 'bookmark-jump)))
16574 ;; Make session.el ignore our circular variable
16575 (eval-after-load "session"
16576 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16578 ;;;; Experimental code
16580 (defun org-closed-in-range ()
16581 "Sparse tree of items closed in a certain time range.
16582 Still experimental, may disappear in the future."
16583 (interactive)
16584 ;; Get the time interval from the user.
16585 (let* ((time1 (time-to-seconds
16586 (org-read-date nil 'to-time nil "Starting date: ")))
16587 (time2 (time-to-seconds
16588 (org-read-date nil 'to-time nil "End date:")))
16589 ;; callback function
16590 (callback (lambda ()
16591 (let ((time
16592 (time-to-seconds
16593 (apply 'encode-time
16594 (org-parse-time-string
16595 (match-string 1))))))
16596 ;; check if time in interval
16597 (and (>= time time1) (<= time time2))))))
16598 ;; make tree, check each match with the callback
16599 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16601 ;;;; Finish up
16603 (provide 'org)
16605 (run-hooks 'org-load-hook)
16607 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16609 ;;; org.el ends here