Release 6.24
[org-mode.git] / lisp / org.el
bloba0b220932d3ae3a472382824bf501a0df50ae7e9
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.24
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-footnote)
93 ;;;; Customization variables
95 ;;; Version
97 (defconst org-version "6.24"
98 "The version number of the file org.el.")
100 (defun org-version (&optional here)
101 "Show the org-mode version in the echo area.
102 With prefix arg HERE, insert it at point."
103 (interactive "P")
104 (let ((version (format "Org-mode version %s" org-version)))
105 (message version)
106 (if here
107 (insert version))))
109 ;;; Compatibility constants
111 ;;; The custom variables
113 (defgroup org nil
114 "Outline-based notes management and organizer."
115 :tag "Org"
116 :group 'outlines
117 :group 'hypermedia
118 :group 'calendar)
120 (defcustom org-load-hook nil
121 "Hook that is run after org.el has been loaded."
122 :group 'org
123 :type 'hook)
125 (defvar org-modules) ; defined below
126 (defvar org-modules-loaded nil
127 "Have the modules been loaded already?")
129 (defun org-load-modules-maybe (&optional force)
130 "Load all extensions listed in `org-modules'."
131 (when (or force (not org-modules-loaded))
132 (mapc (lambda (ext)
133 (condition-case nil (require ext)
134 (error (message "Problems while trying to load feature `%s'" ext))))
135 org-modules)
136 (setq org-modules-loaded t)))
138 (defun org-set-modules (var value)
139 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
140 (set var value)
141 (when (featurep 'org)
142 (org-load-modules-maybe 'force)))
144 (when (org-bound-and-true-p org-modules)
145 (let ((a (member 'org-infojs org-modules)))
146 (and a (setcar a 'org-jsinfo))))
148 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
149 "Modules that should always be loaded together with org.el.
150 If a description starts with <C>, the file is not part of Emacs
151 and loading it will require that you have downloaded and properly installed
152 the org-mode distribution.
154 You can also use this system to load external packages (i.e. neither Org
155 core modules, not modules from the CONTRIB directory). Just add symbols
156 to the end of the list. If the package is called org-xyz.el, then you need
157 to add the symbol `xyz', and the package must have a call to
159 (provide 'org-xyz)"
160 :group 'org
161 :set 'org-set-modules
162 :type
163 '(set :greedy t
164 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
165 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
166 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
167 (const :tag " id: Global IDs for identifying entries" org-id)
168 (const :tag " info: Links to Info nodes" org-info)
169 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
170 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
171 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
172 (const :tag " mew Links to Mew folders/messages" org-mew)
173 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
174 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
175 (const :tag " vm: Links to VM folders/messages" org-vm)
176 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
177 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
178 (const :tag " mouse: Additional mouse support" org-mouse)
180 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
181 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
182 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
183 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
184 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
185 (const :tag "C collector: Collect properties into tables" org-collector)
186 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
187 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
188 (const :tag "C eval: Include command output as text" org-eval)
189 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
190 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
191 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
192 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
193 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
194 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
195 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
196 (const :tag "C mtags: Support for muse-like tags" org-mtags)
197 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
198 (const :tag "C R: Computation using the R language" org-R)
199 (const :tag "C registry: A registry for Org links" org-registry)
200 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
201 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
202 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
203 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
204 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
206 (defcustom org-support-shift-select nil
207 "Non-nil means, make shift-cursor commands select text when possible.
209 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
210 selecting a region, or enlarge thusly regions started in this way.
211 In Org-mode, in special contexts, these same keys are used for other
212 purposes, important enough to compete with shift selection. Org tries
213 to balance these needs by supporting `shift-select-mode' outside these
214 special contexts, under control of this variable.
216 The default of this variable is nil, to avoid confusing behavior. Shifted
217 cursor keys will then execute Org commands in the following contexts:
218 - on a headline, changing TODO state (left/right) and priority (up/down)
219 - on a time stamp, changing the time
220 - in a plain list item, changing the bullet type
221 - in a property definition line, switching between allowed values
222 - in the BEGIN line of a clock table (changing the time block).
223 Outside these contexts, the commands will throw an error.
225 When this variable is t and the cursor is not in a special context,
226 Org-mode will support shift-selection for making and enlarging regions.
227 To make this more effective, the bullet cycling will no longer happen
228 anywhere in an item line, but only if the cursor is exactly on the bullet.
230 If you set this variable to the symbol `always', then the keys
231 will not be special in headlines, property lines, and item lines, to make
232 shift selection work there as well. If this is what you want, you can
233 use the following alternative commands: `C-c C-t' and `C-c ,' to
234 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
235 TODO sets, `C-c -' to cycle item bullet types, and properties can be
236 edited by hand or in column view.
238 However, when the cursor is on a timestamp, shift-cursor commands
239 will still edit the time stamp - this is just too good to give up.
241 XEmacs user should have this variable set to nil, because shift-select-mode
242 is Emacs 23 only."
243 :group 'org
244 :type '(choice
245 (const :tag "Never" nil)
246 (const :tag "When outside special context" t)
247 (const :tag "Everywhere except timestamps" always)))
249 (defgroup org-startup nil
250 "Options concerning startup of Org-mode."
251 :tag "Org Startup"
252 :group 'org)
254 (defcustom org-startup-folded t
255 "Non-nil means, entering Org-mode will switch to OVERVIEW.
256 This can also be configured on a per-file basis by adding one of
257 the following lines anywhere in the buffer:
259 #+STARTUP: fold
260 #+STARTUP: nofold
261 #+STARTUP: content"
262 :group 'org-startup
263 :type '(choice
264 (const :tag "nofold: show all" nil)
265 (const :tag "fold: overview" t)
266 (const :tag "content: all headlines" content)))
268 (defcustom org-startup-truncated t
269 "Non-nil means, entering Org-mode will set `truncate-lines'.
270 This is useful since some lines containing links can be very long and
271 uninteresting. Also tables look terrible when wrapped."
272 :group 'org-startup
273 :type 'boolean)
275 (defcustom org-startup-align-all-tables nil
276 "Non-nil means, align all tables when visiting a file.
277 This is useful when the column width in tables is forced with <N> cookies
278 in table fields. Such tables will look correct only after the first re-align.
279 This can also be configured on a per-file basis by adding one of
280 the following lines anywhere in the buffer:
281 #+STARTUP: align
282 #+STARTUP: noalign"
283 :group 'org-startup
284 :type 'boolean)
286 (defcustom org-insert-mode-line-in-empty-file nil
287 "Non-nil means insert the first line setting Org-mode in empty files.
288 When the function `org-mode' is called interactively in an empty file, this
289 normally means that the file name does not automatically trigger Org-mode.
290 To ensure that the file will always be in Org-mode in the future, a
291 line enforcing Org-mode will be inserted into the buffer, if this option
292 has been set."
293 :group 'org-startup
294 :type 'boolean)
296 (defcustom org-replace-disputed-keys nil
297 "Non-nil means use alternative key bindings for some keys.
298 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
299 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
300 If you want to use Org-mode together with one of these other modes,
301 or more generally if you would like to move some Org-mode commands to
302 other keys, set this variable and configure the keys with the variable
303 `org-disputed-keys'.
305 This option is only relevant at load-time of Org-mode, and must be set
306 *before* org.el is loaded. Changing it requires a restart of Emacs to
307 become effective."
308 :group 'org-startup
309 :type 'boolean)
311 (defcustom org-use-extra-keys nil
312 "Non-nil means use extra key sequence definitions for certain
313 commands. This happens automatically if you run XEmacs or if
314 window-system is nil. This variable lets you do the same
315 manually. You must set it before loading org.
317 Example: on Carbon Emacs 22 running graphically, with an external
318 keyboard on a Powerbook, the default way of setting M-left might
319 not work for either Alt or ESC. Setting this variable will make
320 it work for ESC."
321 :group 'org-startup
322 :type 'boolean)
324 (if (fboundp 'defvaralias)
325 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
327 (defcustom org-disputed-keys
328 '(([(shift up)] . [(meta p)])
329 ([(shift down)] . [(meta n)])
330 ([(shift left)] . [(meta -)])
331 ([(shift right)] . [(meta +)])
332 ([(control shift right)] . [(meta shift +)])
333 ([(control shift left)] . [(meta shift -)]))
334 "Keys for which Org-mode and other modes compete.
335 This is an alist, cars are the default keys, second element specifies
336 the alternative to use when `org-replace-disputed-keys' is t.
338 Keys can be specified in any syntax supported by `define-key'.
339 The value of this option takes effect only at Org-mode's startup,
340 therefore you'll have to restart Emacs to apply it after changing."
341 :group 'org-startup
342 :type 'alist)
344 (defun org-key (key)
345 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
346 Or return the original if not disputed."
347 (if org-replace-disputed-keys
348 (let* ((nkey (key-description key))
349 (x (org-find-if (lambda (x)
350 (equal (key-description (car x)) nkey))
351 org-disputed-keys)))
352 (if x (cdr x) key))
353 key))
355 (defun org-find-if (predicate seq)
356 (catch 'exit
357 (while seq
358 (if (funcall predicate (car seq))
359 (throw 'exit (car seq))
360 (pop seq)))))
362 (defun org-defkey (keymap key def)
363 "Define a key, possibly translated, as returned by `org-key'."
364 (define-key keymap (org-key key) def))
366 (defcustom org-ellipsis nil
367 "The ellipsis to use in the Org-mode outline.
368 When nil, just use the standard three dots. When a string, use that instead,
369 When a face, use the standard 3 dots, but with the specified face.
370 The change affects only Org-mode (which will then use its own display table).
371 Changing this requires executing `M-x org-mode' in a buffer to become
372 effective."
373 :group 'org-startup
374 :type '(choice (const :tag "Default" nil)
375 (face :tag "Face" :value org-warning)
376 (string :tag "String" :value "...#")))
378 (defvar org-display-table nil
379 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
381 (defgroup org-keywords nil
382 "Keywords in Org-mode."
383 :tag "Org Keywords"
384 :group 'org)
386 (defcustom org-deadline-string "DEADLINE:"
387 "String to mark deadline entries.
388 A deadline is this string, followed by a time stamp. Should be a word,
389 terminated by a colon. You can insert a schedule keyword and
390 a timestamp with \\[org-deadline].
391 Changes become only effective after restarting Emacs."
392 :group 'org-keywords
393 :type 'string)
395 (defcustom org-scheduled-string "SCHEDULED:"
396 "String to mark scheduled TODO entries.
397 A schedule is this string, followed by a time stamp. Should be a word,
398 terminated by a colon. You can insert a schedule keyword and
399 a timestamp with \\[org-schedule].
400 Changes become only effective after restarting Emacs."
401 :group 'org-keywords
402 :type 'string)
404 (defcustom org-closed-string "CLOSED:"
405 "String used as the prefix for timestamps logging closing a TODO entry."
406 :group 'org-keywords
407 :type 'string)
409 (defcustom org-clock-string "CLOCK:"
410 "String used as prefix for timestamps clocking work hours on an item."
411 :group 'org-keywords
412 :type 'string)
414 (defcustom org-comment-string "COMMENT"
415 "Entries starting with this keyword will never be exported.
416 An entry can be toggled between COMMENT and normal with
417 \\[org-toggle-comment].
418 Changes become only effective after restarting Emacs."
419 :group 'org-keywords
420 :type 'string)
422 (defcustom org-quote-string "QUOTE"
423 "Entries starting with this keyword will be exported in fixed-width font.
424 Quoting applies only to the text in the entry following the headline, and does
425 not extend beyond the next headline, even if that is lower level.
426 An entry can be toggled between QUOTE and normal with
427 \\[org-toggle-fixed-width-section]."
428 :group 'org-keywords
429 :type 'string)
431 (defconst org-repeat-re
432 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
433 "Regular expression for specifying repeated events.
434 After a match, group 1 contains the repeat expression.")
436 (defgroup org-structure nil
437 "Options concerning the general structure of Org-mode files."
438 :tag "Org Structure"
439 :group 'org)
441 (defgroup org-reveal-location nil
442 "Options about how to make context of a location visible."
443 :tag "Org Reveal Location"
444 :group 'org-structure)
446 (defconst org-context-choice
447 '(choice
448 (const :tag "Always" t)
449 (const :tag "Never" nil)
450 (repeat :greedy t :tag "Individual contexts"
451 (cons
452 (choice :tag "Context"
453 (const agenda)
454 (const org-goto)
455 (const occur-tree)
456 (const tags-tree)
457 (const link-search)
458 (const mark-goto)
459 (const bookmark-jump)
460 (const isearch)
461 (const default))
462 (boolean))))
463 "Contexts for the reveal options.")
465 (defcustom org-show-hierarchy-above '((default . t))
466 "Non-nil means, show full hierarchy when revealing a location.
467 Org-mode often shows locations in an org-mode file which might have
468 been invisible before. When this is set, the hierarchy of headings
469 above the exposed location is shown.
470 Turning this off for example for sparse trees makes them very compact.
471 Instead of t, this can also be an alist specifying this option for different
472 contexts. Valid contexts are
473 agenda when exposing an entry from the agenda
474 org-goto when using the command `org-goto' on key C-c C-j
475 occur-tree when using the command `org-occur' on key C-c /
476 tags-tree when constructing a sparse tree based on tags matches
477 link-search when exposing search matches associated with a link
478 mark-goto when exposing the jump goal of a mark
479 bookmark-jump when exposing a bookmark location
480 isearch when exiting from an incremental search
481 default default for all contexts not set explicitly"
482 :group 'org-reveal-location
483 :type org-context-choice)
485 (defcustom org-show-following-heading '((default . nil))
486 "Non-nil means, show following heading when revealing a location.
487 Org-mode often shows locations in an org-mode file which might have
488 been invisible before. When this is set, the heading following the
489 match is shown.
490 Turning this off for example for sparse trees makes them very compact,
491 but makes it harder to edit the location of the match. In such a case,
492 use the command \\[org-reveal] to show more context.
493 Instead of t, this can also be an alist specifying this option for different
494 contexts. See `org-show-hierarchy-above' for valid contexts."
495 :group 'org-reveal-location
496 :type org-context-choice)
498 (defcustom org-show-siblings '((default . nil) (isearch t))
499 "Non-nil means, show all sibling heading when revealing a location.
500 Org-mode often shows locations in an org-mode file which might have
501 been invisible before. When this is set, the sibling of the current entry
502 heading are all made visible. If `org-show-hierarchy-above' is t,
503 the same happens on each level of the hierarchy above the current entry.
505 By default this is on for the isearch context, off for all other contexts.
506 Turning this off for example for sparse trees makes them very compact,
507 but makes it harder to edit the location of the match. In such a case,
508 use the command \\[org-reveal] to show more context.
509 Instead of t, this can also be an alist specifying this option for different
510 contexts. See `org-show-hierarchy-above' for valid contexts."
511 :group 'org-reveal-location
512 :type org-context-choice)
514 (defcustom org-show-entry-below '((default . nil))
515 "Non-nil means, show the entry below a headline when revealing a location.
516 Org-mode often shows locations in an org-mode file which might have
517 been invisible before. When this is set, the text below the headline that is
518 exposed is also shown.
520 By default this is off for all contexts.
521 Instead of t, this can also be an alist specifying this option for different
522 contexts. See `org-show-hierarchy-above' for valid contexts."
523 :group 'org-reveal-location
524 :type org-context-choice)
526 (defcustom org-indirect-buffer-display 'other-window
527 "How should indirect tree buffers be displayed?
528 This applies to indirect buffers created with the commands
529 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
530 Valid values are:
531 current-window Display in the current window
532 other-window Just display in another window.
533 dedicated-frame Create one new frame, and re-use it each time.
534 new-frame Make a new frame each time. Note that in this case
535 previously-made indirect buffers are kept, and you need to
536 kill these buffers yourself."
537 :group 'org-structure
538 :group 'org-agenda-windows
539 :type '(choice
540 (const :tag "In current window" current-window)
541 (const :tag "In current frame, other window" other-window)
542 (const :tag "Each time a new frame" new-frame)
543 (const :tag "One dedicated frame" dedicated-frame)))
545 (defgroup org-cycle nil
546 "Options concerning visibility cycling in Org-mode."
547 :tag "Org Cycle"
548 :group 'org-structure)
550 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
551 "Names of drawers. Drawers are not opened by cycling on the headline above.
552 Drawers only open with a TAB on the drawer line itself. A drawer looks like
553 this:
554 :DRAWERNAME:
555 .....
556 :END:
557 The drawer \"PROPERTIES\" is special for capturing properties through
558 the property API.
560 Drawers can be defined on the per-file basis with a line like:
562 #+DRAWERS: HIDDEN STATE PROPERTIES"
563 :group 'org-structure
564 :type '(repeat (string :tag "Drawer Name")))
566 (defcustom org-cycle-global-at-bob nil
567 "Cycle globally if cursor is at beginning of buffer and not at a headline.
568 This makes it possible to do global cycling without having to use S-TAB or
569 C-u TAB. For this special case to work, the first line of the buffer
570 must not be a headline - it may be empty or some other text. When used in
571 this way, `org-cycle-hook' is disables temporarily, to make sure the
572 cursor stays at the beginning of the buffer.
573 When this option is nil, don't do anything special at the beginning
574 of the buffer."
575 :group 'org-cycle
576 :type 'boolean)
578 (defcustom org-cycle-emulate-tab t
579 "Where should `org-cycle' emulate TAB.
580 nil Never
581 white Only in completely white lines
582 whitestart Only at the beginning of lines, before the first non-white char
583 t Everywhere except in headlines
584 exc-hl-bol Everywhere except at the start of a headline
585 If TAB is used in a place where it does not emulate TAB, the current subtree
586 visibility is cycled."
587 :group 'org-cycle
588 :type '(choice (const :tag "Never" nil)
589 (const :tag "Only in completely white lines" white)
590 (const :tag "Before first char in a line" whitestart)
591 (const :tag "Everywhere except in headlines" t)
592 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
595 (defcustom org-cycle-separator-lines 2
596 "Number of empty lines needed to keep an empty line between collapsed trees.
597 If you leave an empty line between the end of a subtree and the following
598 headline, this empty line is hidden when the subtree is folded.
599 Org-mode will leave (exactly) one empty line visible if the number of
600 empty lines is equal or larger to the number given in this variable.
601 So the default 2 means, at least 2 empty lines after the end of a subtree
602 are needed to produce free space between a collapsed subtree and the
603 following headline.
605 Special case: when 0, never leave empty lines in collapsed view."
606 :group 'org-cycle
607 :type 'integer)
608 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
610 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
611 org-cycle-hide-drawers
612 org-cycle-show-empty-lines
613 org-optimize-window-after-visibility-change)
614 "Hook that is run after `org-cycle' has changed the buffer visibility.
615 The function(s) in this hook must accept a single argument which indicates
616 the new state that was set by the most recent `org-cycle' command. The
617 argument is a symbol. After a global state change, it can have the values
618 `overview', `content', or `all'. After a local state change, it can have
619 the values `folded', `children', or `subtree'."
620 :group 'org-cycle
621 :type 'hook)
623 (defgroup org-edit-structure nil
624 "Options concerning structure editing in Org-mode."
625 :tag "Org Edit Structure"
626 :group 'org-structure)
628 (defcustom org-odd-levels-only nil
629 "Non-nil means, skip even levels and only use odd levels for the outline.
630 This has the effect that two stars are being added/taken away in
631 promotion/demotion commands. It also influences how levels are
632 handled by the exporters.
633 Changing it requires restart of `font-lock-mode' to become effective
634 for fontification also in regions already fontified.
635 You may also set this on a per-file basis by adding one of the following
636 lines to the buffer:
638 #+STARTUP: odd
639 #+STARTUP: oddeven"
640 :group 'org-edit-structure
641 :group 'org-font-lock
642 :type 'boolean)
644 (defcustom org-adapt-indentation t
645 "Non-nil means, adapt indentation when promoting and demoting.
646 When this is set and the *entire* text in an entry is indented, the
647 indentation is increased by one space in a demotion command, and
648 decreased by one in a promotion command. If any line in the entry
649 body starts at column 0, indentation is not changed at all."
650 :group 'org-edit-structure
651 :type 'boolean)
653 (defcustom org-special-ctrl-a/e nil
654 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
656 When t, `C-a' will bring back the cursor to the beginning of the
657 headline text, i.e. after the stars and after a possible TODO keyword.
658 In an item, this will be the position after the bullet.
659 When the cursor is already at that position, another `C-a' will bring
660 it to the beginning of the line.
662 `C-e' will jump to the end of the headline, ignoring the presence of tags
663 in the headline. A second `C-e' will then jump to the true end of the
664 line, after any tags.
666 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
667 and only a directly following, identical keypress will bring the cursor
668 to the special positions.
670 This may also be a cons cell where the behavior for `C-a' and `C-e' is
671 set separately."
672 :group 'org-edit-structure
673 :type '(choice
674 (const :tag "off" nil)
675 (const :tag "after stars/bullet and before tags first" t)
676 (const :tag "true line boundary first" reversed)
677 (cons :tag "Set C-a and C-e separately"
678 (choice :tag "Special C-a"
679 (const :tag "off" nil)
680 (const :tag "after stars/bullet first" t)
681 (const :tag "before stars/bullet first" reversed))
682 (choice :tag "Special C-e"
683 (const :tag "off" nil)
684 (const :tag "before tags first" t)
685 (const :tag "after tags first" reversed)))))
686 (if (fboundp 'defvaralias)
687 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
689 (defcustom org-special-ctrl-k nil
690 "Non-nil means `C-k' will behave specially in headlines.
691 When nil, `C-k' will call the default `kill-line' command.
692 When t, the following will happen while the cursor is in the headline:
694 - When the cursor is at the beginning of a headline, kill the entire
695 line and possible the folded subtree below the line.
696 - When in the middle of the headline text, kill the headline up to the tags.
697 - When after the headline text, kill the tags."
698 :group 'org-edit-structure
699 :type 'boolean)
701 (defcustom org-yank-folded-subtrees t
702 "Non-nil means, when yanking subtrees, fold them.
703 If the kill is a single subtree, or a sequence of subtrees, i.e. if
704 it starts with a heading and all other headings in it are either children
705 or siblings, then fold all the subtrees. However, do this only if no
706 text after the yank would be swallowed into a folded tree by this action."
707 :group 'org-edit-structure
708 :type 'boolean)
710 (defcustom org-yank-adjusted-subtrees nil
711 "Non-nil means, when yanking subtrees, adjust the level.
712 With this setting, `org-paste-subtree' is used to insert the subtree, see
713 this function for details."
714 :group 'org-edit-structure
715 :type 'boolean)
717 (defcustom org-M-RET-may-split-line '((default . t))
718 "Non-nil means, M-RET will split the line at the cursor position.
719 When nil, it will go to the end of the line before making a
720 new line.
721 You may also set this option in a different way for different
722 contexts. Valid contexts are:
724 headline when creating a new headline
725 item when creating a new item
726 table in a table field
727 default the value to be used for all contexts not explicitly
728 customized"
729 :group 'org-structure
730 :group 'org-table
731 :type '(choice
732 (const :tag "Always" t)
733 (const :tag "Never" nil)
734 (repeat :greedy t :tag "Individual contexts"
735 (cons
736 (choice :tag "Context"
737 (const headline)
738 (const item)
739 (const table)
740 (const default))
741 (boolean)))))
744 (defcustom org-insert-heading-respect-content nil
745 "Non-nil means, insert new headings after the current subtree.
746 When nil, the new heading is created directly after the current line.
747 The commands \\[org-insert-heading-respect-content] and
748 \\[org-insert-todo-heading-respect-content] turn this variable on
749 for the duration of the command."
750 :group 'org-structure
751 :type 'boolean)
753 (defcustom org-blank-before-new-entry '((heading . auto)
754 (plain-list-item . auto))
755 "Should `org-insert-heading' leave a blank line before new heading/item?
756 The value is an alist, with `heading' and `plain-list-item' as car,
757 and a boolean flag as cdr. For plain lists, if the variable
758 `org-empty-line-terminates-plain-lists' is set, the setting here
759 is ignored and no empty line is inserted, to keep the list in tact."
760 :group 'org-edit-structure
761 :type '(list
762 (cons (const heading)
763 (choice (const :tag "Never" nil)
764 (const :tag "Always" t)
765 (const :tag "Auto" auto)))
766 (cons (const plain-list-item)
767 (choice (const :tag "Never" nil)
768 (const :tag "Always" t)
769 (const :tag "Auto" auto)))))
771 (defcustom org-insert-heading-hook nil
772 "Hook being run after inserting a new heading."
773 :group 'org-edit-structure
774 :type 'hook)
776 (defcustom org-enable-fixed-width-editor t
777 "Non-nil means, lines starting with \":\" are treated as fixed-width.
778 This currently only means, they are never auto-wrapped.
779 When nil, such lines will be treated like ordinary lines.
780 See also the QUOTE keyword."
781 :group 'org-edit-structure
782 :type 'boolean)
784 (defcustom org-edit-src-region-extra nil
785 "Additional regexps to identify regions for editing with `org-edit-src-code'.
786 For examples see the function `org-edit-src-find-region-and-lang'.
787 The regular expression identifying the begin marker should end with a newline,
788 and the regexp marking the end line should start with a newline, to make sure
789 there are kept outside the narrowed region."
790 :group 'org-edit-structure
791 :type '(repeat
792 (list
793 (regexp :tag "begin regexp")
794 (regexp :tag "end regexp")
795 (choice :tag "language"
796 (string :tag "specify")
797 (integer :tag "from match group")
798 (const :tag "from `lang' element")
799 (const :tag "from `style' element")))))
801 (defcustom org-coderef-label-format "(ref:%s)"
802 "The default coderef format.
803 This format string will be used to search for coderef labels in literal
804 examples (EXAMPLE and SRC blocks). The format can be overwritten
805 an individual literal example with the -f option, like
807 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
809 #+END_SRC
811 If you want to use this for HTML export, make sure that the format does
812 not introduce special font-locking, and avoid the HTML special
813 characters `<', `>', and `&'. The reason for this restriction is that
814 the labels are searched for only after htmlize has done its job."
815 :group 'org-edit-structure ; FIXME this is not in the right group
816 :type 'string)
818 (defcustom org-edit-fixed-width-region-mode 'artist-mode
819 "The mode that should be used to edit fixed-width regions.
820 These are the regions where each line starts with a colon."
821 :group 'org-edit-structure
822 :type '(choice
823 (const artist-mode)
824 (const picture-mode)
825 (const fundamental-mode)
826 (function :tag "Other (specify)")))
828 (defcustom org-goto-auto-isearch t
829 "Non-nil means, typing characters in org-goto starts incremental search."
830 :group 'org-edit-structure
831 :type 'boolean)
833 (defgroup org-sparse-trees nil
834 "Options concerning sparse trees in Org-mode."
835 :tag "Org Sparse Trees"
836 :group 'org-structure)
838 (defcustom org-highlight-sparse-tree-matches t
839 "Non-nil means, highlight all matches that define a sparse tree.
840 The highlights will automatically disappear the next time the buffer is
841 changed by an edit command."
842 :group 'org-sparse-trees
843 :type 'boolean)
845 (defcustom org-remove-highlights-with-change t
846 "Non-nil means, any change to the buffer will remove temporary highlights.
847 Such highlights are created by `org-occur' and `org-clock-display'.
848 When nil, `C-c C-c needs to be used to get rid of the highlights.
849 The highlights created by `org-preview-latex-fragment' always need
850 `C-c C-c' to be removed."
851 :group 'org-sparse-trees
852 :group 'org-time
853 :type 'boolean)
856 (defcustom org-occur-hook '(org-first-headline-recenter)
857 "Hook that is run after `org-occur' has constructed a sparse tree.
858 This can be used to recenter the window to show as much of the structure
859 as possible."
860 :group 'org-sparse-trees
861 :type 'hook)
863 (defgroup org-imenu-and-speedbar nil
864 "Options concerning imenu and speedbar in Org-mode."
865 :tag "Org Imenu and Speedbar"
866 :group 'org-structure)
868 (defcustom org-imenu-depth 2
869 "The maximum level for Imenu access to Org-mode headlines.
870 This also applied for speedbar access."
871 :group 'org-imenu-and-speedbar
872 :type 'number)
874 (defgroup org-table nil
875 "Options concerning tables in Org-mode."
876 :tag "Org Table"
877 :group 'org)
879 (defcustom org-enable-table-editor 'optimized
880 "Non-nil means, lines starting with \"|\" are handled by the table editor.
881 When nil, such lines will be treated like ordinary lines.
883 When equal to the symbol `optimized', the table editor will be optimized to
884 do the following:
885 - Automatic overwrite mode in front of whitespace in table fields.
886 This makes the structure of the table stay in tact as long as the edited
887 field does not exceed the column width.
888 - Minimize the number of realigns. Normally, the table is aligned each time
889 TAB or RET are pressed to move to another field. With optimization this
890 happens only if changes to a field might have changed the column width.
891 Optimization requires replacing the functions `self-insert-command',
892 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
893 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
894 very good at guessing when a re-align will be necessary, but you can always
895 force one with \\[org-ctrl-c-ctrl-c].
897 If you would like to use the optimized version in Org-mode, but the
898 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
900 This variable can be used to turn on and off the table editor during a session,
901 but in order to toggle optimization, a restart is required.
903 See also the variable `org-table-auto-blank-field'."
904 :group 'org-table
905 :type '(choice
906 (const :tag "off" nil)
907 (const :tag "on" t)
908 (const :tag "on, optimized" optimized)))
910 (defcustom org-self-insert-cluster-for-undo t
911 "Non-nil means cluster self-insert commands for undo when possible.
912 If this is set, then, like in the Emacs command loop, 20 consequtive
913 characters will be undone together.
914 This is configurable, because there is some impact on typing performance."
915 :group 'org-table
916 :type 'boolean)
918 (defcustom org-table-tab-recognizes-table.el t
919 "Non-nil means, TAB will automatically notice a table.el table.
920 When it sees such a table, it moves point into it and - if necessary -
921 calls `table-recognize-table'."
922 :group 'org-table-editing
923 :type 'boolean)
925 (defgroup org-link nil
926 "Options concerning links in Org-mode."
927 :tag "Org Link"
928 :group 'org)
930 (defvar org-link-abbrev-alist-local nil
931 "Buffer-local version of `org-link-abbrev-alist', which see.
932 The value of this is taken from the #+LINK lines.")
933 (make-variable-buffer-local 'org-link-abbrev-alist-local)
935 (defcustom org-link-abbrev-alist nil
936 "Alist of link abbreviations.
937 The car of each element is a string, to be replaced at the start of a link.
938 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
939 links in Org-mode buffers can have an optional tag after a double colon, e.g.
941 [[linkkey:tag][description]]
943 The 'linkkey' must be a word word, starting with a letter, followed
944 by letters, numbers, '-' or '_'.
946 If REPLACE is a string, the tag will simply be appended to create the link.
947 If the string contains \"%s\", the tag will be inserted there. Alternatively,
948 the placeholder \"%h\" will cause a url-encoded version of the tag to
949 be inserted at that point (see the function `url-hexify-string').
951 REPLACE may also be a function that will be called with the tag as the
952 only argument to create the link, which should be returned as a string.
954 See the manual for examples."
955 :group 'org-link
956 :type '(repeat
957 (cons
958 (string :tag "Protocol")
959 (choice
960 (string :tag "Format")
961 (function)))))
963 (defcustom org-descriptive-links t
964 "Non-nil means, hide link part and only show description of bracket links.
965 Bracket links are like [[link][description]]. This variable sets the initial
966 state in new org-mode buffers. The setting can then be toggled on a
967 per-buffer basis from the Org->Hyperlinks menu."
968 :group 'org-link
969 :type 'boolean)
971 (defcustom org-link-file-path-type 'adaptive
972 "How the path name in file links should be stored.
973 Valid values are:
975 relative Relative to the current directory, i.e. the directory of the file
976 into which the link is being inserted.
977 absolute Absolute path, if possible with ~ for home directory.
978 noabbrev Absolute path, no abbreviation of home directory.
979 adaptive Use relative path for files in the current directory and sub-
980 directories of it. For other files, use an absolute path."
981 :group 'org-link
982 :type '(choice
983 (const relative)
984 (const absolute)
985 (const noabbrev)
986 (const adaptive)))
988 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
989 "Types of links that should be activated in Org-mode files.
990 This is a list of symbols, each leading to the activation of a certain link
991 type. In principle, it does not hurt to turn on most link types - there may
992 be a small gain when turning off unused link types. The types are:
994 bracket The recommended [[link][description]] or [[link]] links with hiding.
995 angular Links in angular brackets that may contain whitespace like
996 <bbdb:Carsten Dominik>.
997 plain Plain links in normal text, no whitespace, like http://google.com.
998 radio Text that is matched by a radio target, see manual for details.
999 tag Tag settings in a headline (link to tag search).
1000 date Time stamps (link to calendar).
1001 footnote Footnote labels.
1003 Changing this variable requires a restart of Emacs to become effective."
1004 :group 'org-link
1005 :type '(set :greedy t
1006 (const :tag "Double bracket links (new style)" bracket)
1007 (const :tag "Angular bracket links (old style)" angular)
1008 (const :tag "Plain text links" plain)
1009 (const :tag "Radio target matches" radio)
1010 (const :tag "Tags" tag)
1011 (const :tag "Timestamps" date)
1012 (const :tag "Footnotes" footnote)))
1014 (defcustom org-make-link-description-function nil
1015 "Function to use to generate link descriptions from links. If
1016 nil the link location will be used. This function must take two
1017 parameters; the first is the link and the second the description
1018 org-insert-link has generated, and should return the description
1019 to use."
1020 :group 'org-link
1021 :type 'function)
1023 (defgroup org-link-store nil
1024 "Options concerning storing links in Org-mode."
1025 :tag "Org Store Link"
1026 :group 'org-link)
1028 (defcustom org-email-link-description-format "Email %c: %.30s"
1029 "Format of the description part of a link to an email or usenet message.
1030 The following %-escapes will be replaced by corresponding information:
1032 %F full \"From\" field
1033 %f name, taken from \"From\" field, address if no name
1034 %T full \"To\" field
1035 %t first name in \"To\" field, address if no name
1036 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1037 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1038 %s subject
1039 %m message-id.
1041 You may use normal field width specification between the % and the letter.
1042 This is for example useful to limit the length of the subject.
1044 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1045 :group 'org-link-store
1046 :type 'string)
1048 (defcustom org-from-is-user-regexp
1049 (let (r1 r2)
1050 (when (and user-mail-address (not (string= user-mail-address "")))
1051 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1052 (when (and user-full-name (not (string= user-full-name "")))
1053 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1054 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1055 "Regexp matched against the \"From:\" header of an email or usenet message.
1056 It should match if the message is from the user him/herself."
1057 :group 'org-link-store
1058 :type 'regexp)
1060 (defcustom org-link-to-org-use-id 'create-if-interactive
1061 "Non-nil means, storing a link to an Org file will use entry IDs.
1063 Note that before this variable is even considered, org-id must be loaded,
1064 to please customize `org-modules' and turn it on.
1066 The variable can have the following values:
1068 t Create an ID if needed to make a link to the current entry.
1070 create-if-interactive
1071 If `org-store-link' is called directly (interactively, as a user
1072 command), do create an ID to support the link. But when doing the
1073 job for remember, only use the ID if it already exists. The
1074 purpose of this setting is to avoid proliferation of unwanted
1075 IDs, just because you happen to be in an Org file when you
1076 call `org-remember' that automatically and preemptively
1077 creates a link. If you do want to get an ID link in a remember
1078 template to an entry not having an ID, create it first by
1079 explicitly creating a link to it, using `C-c C-l' first.
1081 use-existing
1082 Use existing ID, do not create one.
1084 nil Never use an ID to make a link, instead link using a text search for
1085 the headline text."
1086 :group 'org-link-store
1087 :type '(choice
1088 (const :tag "Create ID to make link" t)
1089 (const :tag "Create if string link interactively"
1090 'create-if-interactive)
1091 (const :tag "Only use existing" 'use-existing)
1092 (const :tag "Do not use ID to create link" nil)))
1094 (defcustom org-context-in-file-links t
1095 "Non-nil means, file links from `org-store-link' contain context.
1096 A search string will be added to the file name with :: as separator and
1097 used to find the context when the link is activated by the command
1098 `org-open-at-point'.
1099 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1100 negates this setting for the duration of the command."
1101 :group 'org-link-store
1102 :type 'boolean)
1104 (defcustom org-keep-stored-link-after-insertion nil
1105 "Non-nil means, keep link in list for entire session.
1107 The command `org-store-link' adds a link pointing to the current
1108 location to an internal list. These links accumulate during a session.
1109 The command `org-insert-link' can be used to insert links into any
1110 Org-mode file (offering completion for all stored links). When this
1111 option is nil, every link which has been inserted once using \\[org-insert-link]
1112 will be removed from the list, to make completing the unused links
1113 more efficient."
1114 :group 'org-link-store
1115 :type 'boolean)
1117 (defgroup org-link-follow nil
1118 "Options concerning following links in Org-mode."
1119 :tag "Org Follow Link"
1120 :group 'org-link)
1122 (defcustom org-link-translation-function nil
1123 "Function to translate links with different syntax to Org syntax.
1124 This can be used to translate links created for example by the Planner
1125 or emacs-wiki packages to Org syntax.
1126 The function must accept two parameters, a TYPE containing the link
1127 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1128 which is everything after the link protocol. It should return a cons
1129 with possibly modified values of type and path.
1130 Org contains a function for this, so if you set this variable to
1131 `org-translate-link-from-planner', you should be able follow many
1132 links created by planner."
1133 :group 'org-link-follow
1134 :type 'function)
1136 (defcustom org-follow-link-hook nil
1137 "Hook that is run after a link has been followed."
1138 :group 'org-link-follow
1139 :type 'hook)
1141 (defcustom org-tab-follows-link nil
1142 "Non-nil means, on links TAB will follow the link.
1143 Needs to be set before org.el is loaded.
1144 This really should not be used, it does not make sense, and the
1145 implementation is bad."
1146 :group 'org-link-follow
1147 :type 'boolean)
1149 (defcustom org-return-follows-link nil
1150 "Non-nil means, on links RET will follow the link.
1151 Needs to be set before org.el is loaded."
1152 :group 'org-link-follow
1153 :type 'boolean)
1155 (defcustom org-mouse-1-follows-link
1156 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1157 "Non-nil means, mouse-1 on a link will follow the link.
1158 A longer mouse click will still set point. Does not work on XEmacs.
1159 Needs to be set before org.el is loaded."
1160 :group 'org-link-follow
1161 :type 'boolean)
1163 (defcustom org-mark-ring-length 4
1164 "Number of different positions to be recorded in the ring
1165 Changing this requires a restart of Emacs to work correctly."
1166 :group 'org-link-follow
1167 :type 'integer)
1169 (defcustom org-link-frame-setup
1170 '((vm . vm-visit-folder-other-frame)
1171 (gnus . gnus-other-frame)
1172 (file . find-file-other-window))
1173 "Setup the frame configuration for following links.
1174 When following a link with Emacs, it may often be useful to display
1175 this link in another window or frame. This variable can be used to
1176 set this up for the different types of links.
1177 For VM, use any of
1178 `vm-visit-folder'
1179 `vm-visit-folder-other-frame'
1180 For Gnus, use any of
1181 `gnus'
1182 `gnus-other-frame'
1183 `org-gnus-no-new-news'
1184 For FILE, use any of
1185 `find-file'
1186 `find-file-other-window'
1187 `find-file-other-frame'
1188 For the calendar, use the variable `calendar-setup'.
1189 For BBDB, it is currently only possible to display the matches in
1190 another window."
1191 :group 'org-link-follow
1192 :type '(list
1193 (cons (const vm)
1194 (choice
1195 (const vm-visit-folder)
1196 (const vm-visit-folder-other-window)
1197 (const vm-visit-folder-other-frame)))
1198 (cons (const gnus)
1199 (choice
1200 (const gnus)
1201 (const gnus-other-frame)
1202 (const org-gnus-no-new-news)))
1203 (cons (const file)
1204 (choice
1205 (const find-file)
1206 (const find-file-other-window)
1207 (const find-file-other-frame)))))
1209 (defcustom org-display-internal-link-with-indirect-buffer nil
1210 "Non-nil means, use indirect buffer to display infile links.
1211 Activating internal links (from one location in a file to another location
1212 in the same file) normally just jumps to the location. When the link is
1213 activated with a C-u prefix (or with mouse-3), the link is displayed in
1214 another window. When this option is set, the other window actually displays
1215 an indirect buffer clone of the current buffer, to avoid any visibility
1216 changes to the current buffer."
1217 :group 'org-link-follow
1218 :type 'boolean)
1220 (defcustom org-open-non-existing-files nil
1221 "Non-nil means, `org-open-file' will open non-existing files.
1222 When nil, an error will be generated."
1223 :group 'org-link-follow
1224 :type 'boolean)
1226 (defcustom org-open-directory-means-index-dot-org nil
1227 "Non-nil means, a link to a directory really means to index.org.
1228 When nil, following a directory link will run dired or open a finder/explorer
1229 window on that directory."
1230 :group 'org-link-follow
1231 :type 'boolean)
1233 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1234 "Function and arguments to call for following mailto links.
1235 This is a list with the first element being a lisp function, and the
1236 remaining elements being arguments to the function. In string arguments,
1237 %a will be replaced by the address, and %s will be replaced by the subject
1238 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1239 :group 'org-link-follow
1240 :type '(choice
1241 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1242 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1243 (const :tag "message-mail" (message-mail "%a" "%s"))
1244 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1246 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1247 "Non-nil means, ask for confirmation before executing shell links.
1248 Shell links can be dangerous: just think about a link
1250 [[shell:rm -rf ~/*][Google Search]]
1252 This link would show up in your Org-mode document as \"Google Search\",
1253 but really it would remove your entire home directory.
1254 Therefore we advise against setting this variable to nil.
1255 Just change it to `y-or-n-p' of you want to confirm with a
1256 single keystroke rather than having to type \"yes\"."
1257 :group 'org-link-follow
1258 :type '(choice
1259 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1260 (const :tag "with y-or-n (faster)" y-or-n-p)
1261 (const :tag "no confirmation (dangerous)" nil)))
1263 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1264 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1265 Elisp links can be dangerous: just think about a link
1267 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1269 This link would show up in your Org-mode document as \"Google Search\",
1270 but really it would remove your entire home directory.
1271 Therefore we advise against setting this variable to nil.
1272 Just change it to `y-or-n-p' of you want to confirm with a
1273 single keystroke rather than having to type \"yes\"."
1274 :group 'org-link-follow
1275 :type '(choice
1276 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1277 (const :tag "with y-or-n (faster)" y-or-n-p)
1278 (const :tag "no confirmation (dangerous)" nil)))
1280 (defconst org-file-apps-defaults-gnu
1281 '((remote . emacs)
1282 (system . mailcap)
1283 (t . mailcap))
1284 "Default file applications on a UNIX or GNU/Linux system.
1285 See `org-file-apps'.")
1287 (defconst org-file-apps-defaults-macosx
1288 '((remote . emacs)
1289 (t . "open %s")
1290 (system . "open %s")
1291 ("ps.gz" . "gv %s")
1292 ("eps.gz" . "gv %s")
1293 ("dvi" . "xdvi %s")
1294 ("fig" . "xfig %s"))
1295 "Default file applications on a MacOS X system.
1296 The system \"open\" is known as a default, but we use X11 applications
1297 for some files for which the OS does not have a good default.
1298 See `org-file-apps'.")
1300 (defconst org-file-apps-defaults-windowsnt
1301 (list
1302 '(remote . emacs)
1303 (cons t
1304 (list (if (featurep 'xemacs)
1305 'mswindows-shell-execute
1306 'w32-shell-execute)
1307 "open" 'file))
1308 (cons 'system
1309 (list (if (featurep 'xemacs)
1310 'mswindows-shell-execute
1311 'w32-shell-execute)
1312 "open" 'file)))
1313 "Default file applications on a Windows NT system.
1314 The system \"open\" is used for most files.
1315 See `org-file-apps'.")
1317 (defcustom org-file-apps
1319 (auto-mode . emacs)
1320 ("\\.x?html?\\'" . default)
1321 ("\\.pdf\\'" . default)
1323 "External applications for opening `file:path' items in a document.
1324 Org-mode uses system defaults for different file types, but
1325 you can use this variable to set the application for a given file
1326 extension. The entries in this list are cons cells where the car identifies
1327 files and the cdr the corresponding command. Possible values for the
1328 file identifier are
1329 \"regex\" Regular expression matched against the file name. For backward
1330 compatibility, this can also be a string with only alphanumeric
1331 characters, which is then interpreted as an extension.
1332 `directory' Matches a directory
1333 `remote' Matches a remote file, accessible through tramp or efs.
1334 Remote files most likely should be visited through Emacs
1335 because external applications cannot handle such paths.
1336 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1337 so all files Emacs knows how to handle. Using this with
1338 command `emacs' will open most files in Emacs. Beware that this
1339 will also open html files inside Emacs, unless you add
1340 (\"html\" . default) to the list as well.
1341 t Default for files not matched by any of the other options.
1342 `system' The system command to open files, like `open' on Windows
1343 and Mac OS X, and mailcap under GNU/Linux. This is the command
1344 that will be selected if you call `C-c C-o' with a double
1345 `C-u C-u' prefix.
1347 Possible values for the command are:
1348 `emacs' The file will be visited by the current Emacs process.
1349 `default' Use the default application for this file type, which is the
1350 association for t in the list, most likely in the system-specific
1351 part.
1352 This can be used to overrule an unwanted setting in the
1353 system-specific variable.
1354 `system' Use the system command for opening files, like \"open\".
1355 This command is specified by the entry whose car is `system'.
1356 Most likely, the system-specific version of this variable
1357 does define this command, but you can overrule/replace it
1358 here.
1359 string A command to be executed by a shell; %s will be replaced
1360 by the path to the file.
1361 sexp A Lisp form which will be evaluated. The file path will
1362 be available in the Lisp variable `file'.
1363 For more examples, see the system specific constants
1364 `org-file-apps-defaults-macosx'
1365 `org-file-apps-defaults-windowsnt'
1366 `org-file-apps-defaults-gnu'."
1367 :group 'org-link-follow
1368 :type '(repeat
1369 (cons (choice :value ""
1370 (string :tag "Extension")
1371 (const :tag "System command to open files" system)
1372 (const :tag "Default for unrecognized files" t)
1373 (const :tag "Remote file" remote)
1374 (const :tag "Links to a directory" directory)
1375 (const :tag "Any files that have Emacs modes"
1376 auto-mode))
1377 (choice :value ""
1378 (const :tag "Visit with Emacs" emacs)
1379 (const :tag "Use default" default)
1380 (const :tag "Use the system command" system)
1381 (string :tag "Command")
1382 (sexp :tag "Lisp form")))))
1384 (defgroup org-refile nil
1385 "Options concerning refiling entries in Org-mode."
1386 :tag "Org Refile"
1387 :group 'org)
1389 (defcustom org-directory "~/org"
1390 "Directory with org files.
1391 This is just a default location to look for Org files. There is no need
1392 at all to put your files into this directory. It is only used in the
1393 following situations:
1395 1. When a remember template specifies a target file that is not an
1396 absolute path. The path will then be interpreted relative to
1397 `org-directory'
1398 2. When a remember note is filed away in an interactive way (when exiting the
1399 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1400 with `org-directory' as the default path."
1401 :group 'org-refile
1402 :group 'org-remember
1403 :type 'directory)
1405 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1406 "Default target for storing notes.
1407 Used by the hooks for remember.el. This can be a string, or nil to mean
1408 the value of `remember-data-file'.
1409 You can set this on a per-template basis with the variable
1410 `org-remember-templates'."
1411 :group 'org-refile
1412 :group 'org-remember
1413 :type '(choice
1414 (const :tag "Default from remember-data-file" nil)
1415 file))
1417 (defcustom org-goto-interface 'outline
1418 "The default interface to be used for `org-goto'.
1419 Allowed values are:
1420 outline The interface shows an outline of the relevant file
1421 and the correct heading is found by moving through
1422 the outline or by searching with incremental search.
1423 outline-path-completion Headlines in the current buffer are offered via
1424 completion. This is the interface also used by
1425 the refile command."
1426 :group 'org-refile
1427 :type '(choice
1428 (const :tag "Outline" outline)
1429 (const :tag "Outline-path-completion" outline-path-completion)))
1431 (defcustom org-goto-max-level 5
1432 "Maximum level to be considered when running org-goto with refile interface."
1433 :group 'org-refile
1434 :type 'number)
1436 (defcustom org-reverse-note-order nil
1437 "Non-nil means, store new notes at the beginning of a file or entry.
1438 When nil, new notes will be filed to the end of a file or entry.
1439 This can also be a list with cons cells of regular expressions that
1440 are matched against file names, and values."
1441 :group 'org-remember
1442 :group 'org-refile
1443 :type '(choice
1444 (const :tag "Reverse always" t)
1445 (const :tag "Reverse never" nil)
1446 (repeat :tag "By file name regexp"
1447 (cons regexp boolean))))
1449 (defcustom org-refile-targets nil
1450 "Targets for refiling entries with \\[org-refile].
1451 This is list of cons cells. Each cell contains:
1452 - a specification of the files to be considered, either a list of files,
1453 or a symbol whose function or variable value will be used to retrieve
1454 a file name or a list of file names. If you use `org-agenda-files' for
1455 that, all agenda files will be scanned for targets. Nil means, consider
1456 headings in the current buffer.
1457 - A specification of how to find candidate refile targets. This may be
1458 any of:
1459 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1460 This tag has to be present in all target headlines, inheritance will
1461 not be considered.
1462 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1463 todo keyword.
1464 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1465 headlines that are refiling targets.
1466 - a cons cell (:level . N). Any headline of level N is considered a target.
1467 Note that, when `org-odd-levels-only' is set, level corresponds to
1468 order in hierarchy, not to the number of stars.
1469 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1470 Note that, when `org-odd-levels-only' is set, level corresponds to
1471 order in hierarchy, not to the number of stars.
1473 When this variable is nil, all top-level headlines in the current buffer
1474 are used, equivalent to the value `((nil . (:level . 1))'."
1475 :group 'org-refile
1476 :type '(repeat
1477 (cons
1478 (choice :value org-agenda-files
1479 (const :tag "All agenda files" org-agenda-files)
1480 (const :tag "Current buffer" nil)
1481 (function) (variable) (file))
1482 (choice :tag "Identify target headline by"
1483 (cons :tag "Specific tag" (const :value :tag) (string))
1484 (cons :tag "TODO keyword" (const :value :todo) (string))
1485 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1486 (cons :tag "Level number" (const :value :level) (integer))
1487 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1489 (defcustom org-refile-use-outline-path nil
1490 "Non-nil means, provide refile targets as paths.
1491 So a level 3 headline will be available as level1/level2/level3.
1492 When the value is `file', also include the file name (without directory)
1493 into the path. When `full-file-path', include the full file path."
1494 :group 'org-refile
1495 :type '(choice
1496 (const :tag "Not" nil)
1497 (const :tag "Yes" t)
1498 (const :tag "Start with file name" file)
1499 (const :tag "Start with full file path" full-file-path)))
1501 (defcustom org-outline-path-complete-in-steps t
1502 "Non-nil means, complete the outline path in hierarchical steps.
1503 When Org-mode uses the refile interface to select an outline path
1504 \(see variable `org-refile-use-outline-path'), the completion of
1505 the path can be done is a single go, or if can be done in steps down
1506 the headline hierarchy. Going in steps is probably the best if you
1507 do not use a special completion package like `ido' or `icicles'.
1508 However, when using these packages, going in one step can be very
1509 fast, while still showing the whole path to the entry."
1510 :group 'org-refile
1511 :type 'boolean)
1513 (defgroup org-todo nil
1514 "Options concerning TODO items in Org-mode."
1515 :tag "Org TODO"
1516 :group 'org)
1518 (defgroup org-progress nil
1519 "Options concerning Progress logging in Org-mode."
1520 :tag "Org Progress"
1521 :group 'org-time)
1523 (defvar org-todo-interpretation-widgets
1525 (:tag "Sequence (cycling hits every state)" sequence)
1526 (:tag "Type (cycling directly to DONE)" type))
1527 "The available interpretation symbols for customizing
1528 `org-todo-keywords'.
1529 Interested libraries should add to this list.")
1531 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1532 "List of TODO entry keyword sequences and their interpretation.
1533 \\<org-mode-map>This is a list of sequences.
1535 Each sequence starts with a symbol, either `sequence' or `type',
1536 indicating if the keywords should be interpreted as a sequence of
1537 action steps, or as different types of TODO items. The first
1538 keywords are states requiring action - these states will select a headline
1539 for inclusion into the global TODO list Org-mode produces. If one of
1540 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1541 signify that no further action is necessary. If \"|\" is not found,
1542 the last keyword is treated as the only DONE state of the sequence.
1544 The command \\[org-todo] cycles an entry through these states, and one
1545 additional state where no keyword is present. For details about this
1546 cycling, see the manual.
1548 TODO keywords and interpretation can also be set on a per-file basis with
1549 the special #+SEQ_TODO and #+TYP_TODO lines.
1551 Each keyword can optionally specify a character for fast state selection
1552 \(in combination with the variable `org-use-fast-todo-selection')
1553 and specifiers for state change logging, using the same syntax
1554 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1555 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1556 indicates to record a time stamp each time this state is selected.
1558 Each keyword may also specify if a timestamp or a note should be
1559 recorded when entering or leaving the state, by adding additional
1560 characters in the parenthesis after the keyword. This looks like this:
1561 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1562 record only the time of the state change. With X and Y being either
1563 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1564 Y when leaving the state if and only if the *target* state does not
1565 define X. You may omit any of the fast-selection key or X or /Y,
1566 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1568 For backward compatibility, this variable may also be just a list
1569 of keywords - in this case the interpretation (sequence or type) will be
1570 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1571 :group 'org-todo
1572 :group 'org-keywords
1573 :type '(choice
1574 (repeat :tag "Old syntax, just keywords"
1575 (string :tag "Keyword"))
1576 (repeat :tag "New syntax"
1577 (cons
1578 (choice
1579 :tag "Interpretation"
1580 ;;Quick and dirty way to see
1581 ;;`org-todo-interpretations'. This takes the
1582 ;;place of item arguments
1583 :convert-widget
1584 (lambda (widget)
1585 (widget-put widget
1586 :args (mapcar
1587 #'(lambda (x)
1588 (widget-convert
1589 (cons 'const x)))
1590 org-todo-interpretation-widgets))
1591 widget))
1592 (repeat
1593 (string :tag "Keyword"))))))
1595 (defvar org-todo-keywords-1 nil
1596 "All TODO and DONE keywords active in a buffer.")
1597 (make-variable-buffer-local 'org-todo-keywords-1)
1598 (defvar org-todo-keywords-for-agenda nil)
1599 (defvar org-done-keywords-for-agenda nil)
1600 (defvar org-todo-keyword-alist-for-agenda nil)
1601 (defvar org-tag-alist-for-agenda nil)
1602 (defvar org-agenda-contributing-files nil)
1603 (defvar org-not-done-keywords nil)
1604 (make-variable-buffer-local 'org-not-done-keywords)
1605 (defvar org-done-keywords nil)
1606 (make-variable-buffer-local 'org-done-keywords)
1607 (defvar org-todo-heads nil)
1608 (make-variable-buffer-local 'org-todo-heads)
1609 (defvar org-todo-sets nil)
1610 (make-variable-buffer-local 'org-todo-sets)
1611 (defvar org-todo-log-states nil)
1612 (make-variable-buffer-local 'org-todo-log-states)
1613 (defvar org-todo-kwd-alist nil)
1614 (make-variable-buffer-local 'org-todo-kwd-alist)
1615 (defvar org-todo-key-alist nil)
1616 (make-variable-buffer-local 'org-todo-key-alist)
1617 (defvar org-todo-key-trigger nil)
1618 (make-variable-buffer-local 'org-todo-key-trigger)
1620 (defcustom org-todo-interpretation 'sequence
1621 "Controls how TODO keywords are interpreted.
1622 This variable is in principle obsolete and is only used for
1623 backward compatibility, if the interpretation of todo keywords is
1624 not given already in `org-todo-keywords'. See that variable for
1625 more information."
1626 :group 'org-todo
1627 :group 'org-keywords
1628 :type '(choice (const sequence)
1629 (const type)))
1631 (defcustom org-use-fast-todo-selection t
1632 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1633 This variable describes if and under what circumstances the cycling
1634 mechanism for TODO keywords will be replaced by a single-key, direct
1635 selection scheme.
1637 When nil, fast selection is never used.
1639 When the symbol `prefix', it will be used when `org-todo' is called with
1640 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1641 in an agenda buffer.
1643 When t, fast selection is used by default. In this case, the prefix
1644 argument forces cycling instead.
1646 In all cases, the special interface is only used if access keys have actually
1647 been assigned by the user, i.e. if keywords in the configuration are followed
1648 by a letter in parenthesis, like TODO(t)."
1649 :group 'org-todo
1650 :type '(choice
1651 (const :tag "Never" nil)
1652 (const :tag "By default" t)
1653 (const :tag "Only with C-u C-c C-t" prefix)))
1655 (defcustom org-provide-todo-statistics t
1656 "Non-nil means, update todo statistics after insert and toggle.
1657 When this is set, todo statistics is updated in the parent of the current
1658 entry each time a todo state is changed."
1659 :group 'org-todo
1660 :type 'boolean)
1662 (defcustom org-after-todo-state-change-hook nil
1663 "Hook which is run after the state of a TODO item was changed.
1664 The new state (a string with a TODO keyword, or nil) is available in the
1665 Lisp variable `state'."
1666 :group 'org-todo
1667 :type 'hook)
1669 (defvar org-blocker-hook nil
1670 "Hook for functions that are allowed to block a state change.
1672 Each function gets as its single argument a property list, see
1673 `org-trigger-hook' for more information about this list.
1675 If any of the functions in this hook returns nil, the state change
1676 is blocked.")
1678 (defvar org-trigger-hook nil
1679 "Hook for functions that are triggered by a state change.
1681 Each function gets as its single argument a property list with at least
1682 the following elements:
1684 (:type type-of-change :position pos-at-entry-start
1685 :from old-state :to new-state)
1687 Depending on the type, more properties may be present.
1689 This mechanism is currently implemented for:
1691 TODO state changes
1692 ------------------
1693 :type todo-state-change
1694 :from previous state (keyword as a string), or nil, or a symbol
1695 'todo' or 'done', to indicate the general type of state.
1696 :to new state, like in :from")
1698 (defcustom org-enforce-todo-dependencies nil
1699 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1700 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1701 be blocked if any prior sibling is not yet done.
1702 This variable needs to be set before org.el is loaded, and you need to
1703 restart Emacs after a change to make the change effective. The only way
1704 to change is while Emacs is running is through the customize interface."
1705 :set (lambda (var val)
1706 (set var val)
1707 (if val
1708 (add-hook 'org-blocker-hook
1709 'org-block-todo-from-children-or-siblings)
1710 (remove-hook 'org-blocker-hook
1711 'org-block-todo-from-children-or-siblings)))
1712 :group 'org-todo
1713 :type 'boolean)
1715 (defcustom org-enforce-todo-checkbox-dependencies nil
1716 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1717 When this is nil, checkboxes have no influence on switching TODO states.
1718 When non-nil, you first need to check off all check boxes before the TODO
1719 entry can be switched to DONE.
1720 This variable needs to be set before org.el is loaded, and you need to
1721 restart Emacs after a change to make the change effective. The only way
1722 to change is while Emacs is running is through the customize interface."
1723 :set (lambda (var val)
1724 (set var val)
1725 (if val
1726 (add-hook 'org-blocker-hook
1727 'org-block-todo-from-checkboxes)
1728 (remove-hook 'org-blocker-hook
1729 'org-block-todo-from-checkboxes)))
1730 :group 'org-todo
1731 :type 'boolean)
1733 (defcustom org-todo-state-tags-triggers nil
1734 "Tag changes that should be triggered by TODO state changes.
1735 This is a list. Each entry is
1737 (state-change (tag . flag) .......)
1739 State-change can be a string with a state, and empty string to indicate the
1740 state that has no TODO keyword, or it can be one of the symbols `todo'
1741 or `done', meaning any not-done or done state, respectively."
1742 :group 'org-todo
1743 :group 'org-tags
1744 :type '(repeat
1745 (cons (choice :tag "When changing to"
1746 (const :tag "Not-done state" todo)
1747 (const :tag "Done state" done)
1748 (string :tag "State"))
1749 (repeat
1750 (cons :tag "Tag action"
1751 (string :tag "Tag")
1752 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1754 (defcustom org-log-done nil
1755 "Information to record when a task moves to the DONE state.
1757 Possible values are:
1759 nil Don't add anything, just change the keyword
1760 time Add a time stamp to the task
1761 note Prompt a closing note and add it with template `org-log-note-headings'
1763 This option can also be set with on a per-file-basis with
1765 #+STARTUP: nologdone
1766 #+STARTUP: logdone
1767 #+STARTUP: lognotedone
1769 You can have local logging settings for a subtree by setting the LOGGING
1770 property to one or more of these keywords."
1771 :group 'org-todo
1772 :group 'org-progress
1773 :type '(choice
1774 (const :tag "No logging" nil)
1775 (const :tag "Record CLOSED timestamp" time)
1776 (const :tag "Record CLOSED timestamp with closing note." note)))
1778 ;; Normalize old uses of org-log-done.
1779 (cond
1780 ((eq org-log-done t) (setq org-log-done 'time))
1781 ((and (listp org-log-done) (memq 'done org-log-done))
1782 (setq org-log-done 'note)))
1784 (defcustom org-log-note-clock-out nil
1785 "Non-nil means, record a note when clocking out of an item.
1786 This can also be configured on a per-file basis by adding one of
1787 the following lines anywhere in the buffer:
1789 #+STARTUP: lognoteclock-out
1790 #+STARTUP: nolognoteclock-out"
1791 :group 'org-todo
1792 :group 'org-progress
1793 :type 'boolean)
1795 (defcustom org-log-done-with-time t
1796 "Non-nil means, the CLOSED time stamp will contain date and time.
1797 When nil, only the date will be recorded."
1798 :group 'org-progress
1799 :type 'boolean)
1801 (defcustom org-log-note-headings
1802 '((done . "CLOSING NOTE %t")
1803 (state . "State %-12s from %-12S %t")
1804 (note . "Note taken on %t")
1805 (clock-out . ""))
1806 "Headings for notes added to entries.
1807 The value is an alist, with the car being a symbol indicating the note
1808 context, and the cdr is the heading to be used. The heading may also be the
1809 empty string.
1810 %t in the heading will be replaced by a time stamp.
1811 %s will be replaced by the new TODO state, in double quotes.
1812 %S will be replaced by the old TODO state, in double quotes.
1813 %u will be replaced by the user name.
1814 %U will be replaced by the full user name."
1815 :group 'org-todo
1816 :group 'org-progress
1817 :type '(list :greedy t
1818 (cons (const :tag "Heading when closing an item" done) string)
1819 (cons (const :tag
1820 "Heading when changing todo state (todo sequence only)"
1821 state) string)
1822 (cons (const :tag "Heading when just taking a note" note) string)
1823 (cons (const :tag "Heading when clocking out" clock-out) string)))
1825 (unless (assq 'note org-log-note-headings)
1826 (push '(note . "%t") org-log-note-headings))
1828 (defcustom org-log-into-drawer nil
1829 "Non-nil means, insert state change notes and time stamps into a drawer.
1830 When nil, state changes notes will be inserted after the headline and
1831 any scheduling and clock lines, but not inside a drawer.
1833 The value of this variable should be the name of the drawer to use.
1834 LOGBOOK is proposed at the default drawer for this purpose, you can
1835 also set this to a string to define the drawer of your choice.
1837 A value of t is also allowed, representing \"LOGBOOK\".
1839 If this variable is set, `org-log-state-notes-insert-after-drawers'
1840 will be ignored."
1841 :group 'org-todo
1842 :group 'org-progress
1843 :type '(choice
1844 (const :tag "Not into a drawer" nil)
1845 (const :tag "LOGBOOK" t)
1846 (string :tag "Other")))
1848 (if (fboundp 'defvaralias)
1849 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1851 (defcustom org-log-state-notes-insert-after-drawers nil
1852 "Non-nil means, insert state change notes after any drawers in entry.
1853 Only the drawers that *immediately* follow the headline and the
1854 deadline/scheduled line are skipped.
1855 When nil, insert notes right after the heading and perhaps the line
1856 with deadline/scheduling if present.
1858 This variable will have no effect if `org-log-into-drawer' is
1859 set."
1860 :group 'org-todo
1861 :group 'org-progress
1862 :type 'boolean)
1864 (defcustom org-log-states-order-reversed t
1865 "Non-nil means, the latest state change note will be directly after heading.
1866 When nil, the notes will be orderer according to time."
1867 :group 'org-todo
1868 :group 'org-progress
1869 :type 'boolean)
1871 (defcustom org-log-repeat 'time
1872 "Non-nil means, record moving through the DONE state when triggering repeat.
1873 An auto-repeating tasks is immediately switched back to TODO when marked
1874 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1875 the TODO keyword definition, or recording a closing note by setting
1876 `org-log-done', there will be no record of the task moving through DONE.
1877 This variable forces taking a note anyway. Possible values are:
1879 nil Don't force a record
1880 time Record a time stamp
1881 note Record a note
1883 This option can also be set with on a per-file-basis with
1885 #+STARTUP: logrepeat
1886 #+STARTUP: lognoterepeat
1887 #+STARTUP: nologrepeat
1889 You can have local logging settings for a subtree by setting the LOGGING
1890 property to one or more of these keywords."
1891 :group 'org-todo
1892 :group 'org-progress
1893 :type '(choice
1894 (const :tag "Don't force a record" nil)
1895 (const :tag "Force recording the DONE state" time)
1896 (const :tag "Force recording a note with the DONE state" note)))
1899 (defgroup org-priorities nil
1900 "Priorities in Org-mode."
1901 :tag "Org Priorities"
1902 :group 'org-todo)
1904 (defcustom org-highest-priority ?A
1905 "The highest priority of TODO items. A character like ?A, ?B etc.
1906 Must have a smaller ASCII number than `org-lowest-priority'."
1907 :group 'org-priorities
1908 :type 'character)
1910 (defcustom org-lowest-priority ?C
1911 "The lowest priority of TODO items. A character like ?A, ?B etc.
1912 Must have a larger ASCII number than `org-highest-priority'."
1913 :group 'org-priorities
1914 :type 'character)
1916 (defcustom org-default-priority ?B
1917 "The default priority of TODO items.
1918 This is the priority an item get if no explicit priority is given."
1919 :group 'org-priorities
1920 :type 'character)
1922 (defcustom org-priority-start-cycle-with-default t
1923 "Non-nil means, start with default priority when starting to cycle.
1924 When this is nil, the first step in the cycle will be (depending on the
1925 command used) one higher or lower that the default priority."
1926 :group 'org-priorities
1927 :type 'boolean)
1929 (defgroup org-time nil
1930 "Options concerning time stamps and deadlines in Org-mode."
1931 :tag "Org Time"
1932 :group 'org)
1934 (defcustom org-insert-labeled-timestamps-at-point nil
1935 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1936 When nil, these labeled time stamps are forces into the second line of an
1937 entry, just after the headline. When scheduling from the global TODO list,
1938 the time stamp will always be forced into the second line."
1939 :group 'org-time
1940 :type 'boolean)
1942 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1943 "Formats for `format-time-string' which are used for time stamps.
1944 It is not recommended to change this constant.")
1946 (defcustom org-time-stamp-rounding-minutes '(0 5)
1947 "Number of minutes to round time stamps to.
1948 These are two values, the first applies when first creating a time stamp.
1949 The second applies when changing it with the commands `S-up' and `S-down'.
1950 When changing the time stamp, this means that it will change in steps
1951 of N minutes, as given by the second value.
1953 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1954 numbers should be factors of 60, so for example 5, 10, 15.
1956 When this is larger than 1, you can still force an exact time-stamp by using
1957 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1958 and by using a prefix arg to `S-up/down' to specify the exact number
1959 of minutes to shift."
1960 :group 'org-time
1961 :get '(lambda (var) ; Make sure all entries have 5 elements
1962 (if (integerp (default-value var))
1963 (list (default-value var) 5)
1964 (default-value var)))
1965 :type '(list
1966 (integer :tag "when inserting times")
1967 (integer :tag "when modifying times")))
1969 ;; Normalize old customizations of this variable.
1970 (when (integerp org-time-stamp-rounding-minutes)
1971 (setq org-time-stamp-rounding-minutes
1972 (list org-time-stamp-rounding-minutes
1973 org-time-stamp-rounding-minutes)))
1975 (defcustom org-display-custom-times nil
1976 "Non-nil means, overlay custom formats over all time stamps.
1977 The formats are defined through the variable `org-time-stamp-custom-formats'.
1978 To turn this on on a per-file basis, insert anywhere in the file:
1979 #+STARTUP: customtime"
1980 :group 'org-time
1981 :set 'set-default
1982 :type 'sexp)
1983 (make-variable-buffer-local 'org-display-custom-times)
1985 (defcustom org-time-stamp-custom-formats
1986 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1987 "Custom formats for time stamps. See `format-time-string' for the syntax.
1988 These are overlayed over the default ISO format if the variable
1989 `org-display-custom-times' is set. Time like %H:%M should be at the
1990 end of the second format."
1991 :group 'org-time
1992 :type 'sexp)
1994 (defun org-time-stamp-format (&optional long inactive)
1995 "Get the right format for a time string."
1996 (let ((f (if long (cdr org-time-stamp-formats)
1997 (car org-time-stamp-formats))))
1998 (if inactive
1999 (concat "[" (substring f 1 -1) "]")
2000 f)))
2002 (defcustom org-time-clocksum-format "%d:%02d"
2003 "The format string used when creating CLOCKSUM lines, or when
2004 org-mode generates a time duration."
2005 :group 'org-time
2006 :type 'string)
2008 (defcustom org-deadline-warning-days 14
2009 "No. of days before expiration during which a deadline becomes active.
2010 This variable governs the display in sparse trees and in the agenda.
2011 When 0 or negative, it means use this number (the absolute value of it)
2012 even if a deadline has a different individual lead time specified.
2014 Custom commands can set this variable in the options section."
2015 :group 'org-time
2016 :group 'org-agenda-daily/weekly
2017 :type 'number)
2019 (defcustom org-read-date-prefer-future t
2020 "Non-nil means, assume future for incomplete date input from user.
2021 This affects the following situations:
2022 1. The user gives a day, but no month.
2023 For example, if today is the 15th, and you enter \"3\", Org-mode will
2024 read this as the third of *next* month. However, if you enter \"17\",
2025 it will be considered as *this* month.
2026 2. The user gives a month but not a year.
2027 For example, if it is april and you enter \"feb 2\", this will be read
2028 as feb 2, *next* year. \"May 5\", however, will be this year.
2030 Currently this does not work for ISO week specifications.
2032 When this option is nil, the current month and year will always be used
2033 as defaults."
2034 :group 'org-time
2035 :type 'boolean)
2037 (defcustom org-read-date-display-live t
2038 "Non-nil means, display current interpretation of date prompt live.
2039 This display will be in an overlay, in the minibuffer."
2040 :group 'org-time
2041 :type 'boolean)
2043 (defcustom org-read-date-popup-calendar t
2044 "Non-nil means, pop up a calendar when prompting for a date.
2045 In the calendar, the date can be selected with mouse-1. However, the
2046 minibuffer will also be active, and you can simply enter the date as well.
2047 When nil, only the minibuffer will be available."
2048 :group 'org-time
2049 :type 'boolean)
2050 (if (fboundp 'defvaralias)
2051 (defvaralias 'org-popup-calendar-for-date-prompt
2052 'org-read-date-popup-calendar))
2054 (defcustom org-extend-today-until 0
2055 "The hour when your day really ends. Must be an integer.
2056 This has influence for the following applications:
2057 - When switching the agenda to \"today\". It it is still earlier than
2058 the time given here, the day recognized as TODAY is actually yesterday.
2059 - When a date is read from the user and it is still before the time given
2060 here, the current date and time will be assumed to be yesterday, 23:59.
2061 Also, timestamps inserted in remember templates follow this rule.
2063 IMPORTANT: This is a feature whose implementation is and likely will
2064 remain incomplete. Really, it is only here because past midnight seems to
2065 be the favorite working time of John Wiegley :-)"
2066 :group 'org-time
2067 :type 'number)
2069 (defcustom org-edit-timestamp-down-means-later nil
2070 "Non-nil means, S-down will increase the time in a time stamp.
2071 When nil, S-up will increase."
2072 :group 'org-time
2073 :type 'boolean)
2075 (defcustom org-calendar-follow-timestamp-change t
2076 "Non-nil means, make the calendar window follow timestamp changes.
2077 When a timestamp is modified and the calendar window is visible, it will be
2078 moved to the new date."
2079 :group 'org-time
2080 :type 'boolean)
2082 (defgroup org-tags nil
2083 "Options concerning tags in Org-mode."
2084 :tag "Org Tags"
2085 :group 'org)
2087 (defcustom org-tag-alist nil
2088 "List of tags allowed in Org-mode files.
2089 When this list is nil, Org-mode will base TAG input on what is already in the
2090 buffer.
2091 The value of this variable is an alist, the car of each entry must be a
2092 keyword as a string, the cdr may be a character that is used to select
2093 that tag through the fast-tag-selection interface.
2094 See the manual for details."
2095 :group 'org-tags
2096 :type '(repeat
2097 (choice
2098 (cons (string :tag "Tag name")
2099 (character :tag "Access char"))
2100 (const :tag "Start radio group" (:startgroup))
2101 (const :tag "End radio group" (:endgroup))
2102 (const :tag "New line" (:newline)))))
2104 (defcustom org-tag-persistent-alist nil
2105 "List of tags that will always appear in all Org-mode files.
2106 This is in addition to any in buffer settings or customizations
2107 of `org-tag-alist'.
2108 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2109 The value of this variable is an alist, the car of each entry must be a
2110 keyword as a string, the cdr may be a character that is used to select
2111 that tag through the fast-tag-selection interface.
2112 See the manual for details.
2113 To disable these tags on a per-file basis, insert anywhere in the file:
2114 #+STARTUP: noptag"
2115 :group 'org-tags
2116 :type '(repeat
2117 (choice
2118 (cons (string :tag "Tag name")
2119 (character :tag "Access char"))
2120 (const :tag "Start radio group" (:startgroup))
2121 (const :tag "End radio group" (:endgroup))
2122 (const :tag "New line" (:newline)))))
2124 (defvar org-file-tags nil
2125 "List of tags that can be inherited by all entries in the file.
2126 The tags will be inherited if the variable `org-use-tag-inheritance'
2127 says they should be.
2128 This variable is populated from #+TAG lines.")
2130 (defcustom org-use-fast-tag-selection 'auto
2131 "Non-nil means, use fast tag selection scheme.
2132 This is a special interface to select and deselect tags with single keys.
2133 When nil, fast selection is never used.
2134 When the symbol `auto', fast selection is used if and only if selection
2135 characters for tags have been configured, either through the variable
2136 `org-tag-alist' or through a #+TAGS line in the buffer.
2137 When t, fast selection is always used and selection keys are assigned
2138 automatically if necessary."
2139 :group 'org-tags
2140 :type '(choice
2141 (const :tag "Always" t)
2142 (const :tag "Never" nil)
2143 (const :tag "When selection characters are configured" 'auto)))
2145 (defcustom org-fast-tag-selection-single-key nil
2146 "Non-nil means, fast tag selection exits after first change.
2147 When nil, you have to press RET to exit it.
2148 During fast tag selection, you can toggle this flag with `C-c'.
2149 This variable can also have the value `expert'. In this case, the window
2150 displaying the tags menu is not even shown, until you press C-c again."
2151 :group 'org-tags
2152 :type '(choice
2153 (const :tag "No" nil)
2154 (const :tag "Yes" t)
2155 (const :tag "Expert" expert)))
2157 (defvar org-fast-tag-selection-include-todo nil
2158 "Non-nil means, fast tags selection interface will also offer TODO states.
2159 This is an undocumented feature, you should not rely on it.")
2161 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2162 "The column to which tags should be indented in a headline.
2163 If this number is positive, it specifies the column. If it is negative,
2164 it means that the tags should be flushright to that column. For example,
2165 -80 works well for a normal 80 character screen."
2166 :group 'org-tags
2167 :type 'integer)
2169 (defcustom org-auto-align-tags t
2170 "Non-nil means, realign tags after pro/demotion of TODO state change.
2171 These operations change the length of a headline and therefore shift
2172 the tags around. With this options turned on, after each such operation
2173 the tags are again aligned to `org-tags-column'."
2174 :group 'org-tags
2175 :type 'boolean)
2177 (defcustom org-use-tag-inheritance t
2178 "Non-nil means, tags in levels apply also for sublevels.
2179 When nil, only the tags directly given in a specific line apply there.
2180 This may also be a list of tags that should be inherited, or a regexp that
2181 matches tags that should be inherited. Additional control is possible
2182 with the variable `org-tags-exclude-from-inheritance' which gives an
2183 explicit list of tags to be excluded from inheritance., even if the value of
2184 `org-use-tag-inheritance' would select it for inheritance.
2186 If this option is t, a match early-on in a tree can lead to a large
2187 number of matches in the subtree when constructing the agenda or creating
2188 a sparse tree. If you only want to see the first match in a tree during
2189 a search, check out the variable `org-tags-match-list-sublevels'."
2190 :group 'org-tags
2191 :type '(choice
2192 (const :tag "Not" nil)
2193 (const :tag "Always" t)
2194 (repeat :tag "Specific tags" (string :tag "Tag"))
2195 (regexp :tag "Tags matched by regexp")))
2197 (defcustom org-tags-exclude-from-inheritance nil
2198 "List of tags that should never be inherited.
2199 This is a way to exclude a few tags from inheritance. For way to do
2200 the opposite, to actively allow inheritance for selected tags,
2201 see the variable `org-use-tag-inheritance'."
2202 :group 'org-tags
2203 :type '(repeat (string :tag "Tag")))
2205 (defun org-tag-inherit-p (tag)
2206 "Check if TAG is one that should be inherited."
2207 (cond
2208 ((member tag org-tags-exclude-from-inheritance) nil)
2209 ((eq org-use-tag-inheritance t) t)
2210 ((not org-use-tag-inheritance) nil)
2211 ((stringp org-use-tag-inheritance)
2212 (string-match org-use-tag-inheritance tag))
2213 ((listp org-use-tag-inheritance)
2214 (member tag org-use-tag-inheritance))
2215 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2217 (defcustom org-tags-match-list-sublevels t
2218 "Non-nil means list also sublevels of headlines matching tag search.
2219 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2220 the sublevels of a headline matching a tag search often also match
2221 the same search. Listing all of them can create very long lists.
2222 Setting this variable to nil causes subtrees of a match to be skipped.
2223 This option is off by default, because inheritance in on. If you turn
2224 inheritance off, you very likely want to turn this option on.
2226 As a special case, if the tag search is restricted to TODO items, the
2227 value of this variable is ignored and sublevels are always checked, to
2228 make sure all corresponding TODO items find their way into the list.
2230 This variable is semi-obsolete and probably should always be true. It
2231 is better to limit inheritance to certain tags using the variables
2232 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2233 :group 'org-tags
2234 :type 'boolean)
2236 (defvar org-tags-history nil
2237 "History of minibuffer reads for tags.")
2238 (defvar org-last-tags-completion-table nil
2239 "The last used completion table for tags.")
2240 (defvar org-after-tags-change-hook nil
2241 "Hook that is run after the tags in a line have changed.")
2243 (defgroup org-properties nil
2244 "Options concerning properties in Org-mode."
2245 :tag "Org Properties"
2246 :group 'org)
2248 (defcustom org-property-format "%-10s %s"
2249 "How property key/value pairs should be formatted by `indent-line'.
2250 When `indent-line' hits a property definition, it will format the line
2251 according to this format, mainly to make sure that the values are
2252 lined-up with respect to each other."
2253 :group 'org-properties
2254 :type 'string)
2256 (defcustom org-use-property-inheritance nil
2257 "Non-nil means, properties apply also for sublevels.
2259 This setting is chiefly used during property searches. Turning it on can
2260 cause significant overhead when doing a search, which is why it is not
2261 on by default.
2263 When nil, only the properties directly given in the current entry count.
2264 When t, every property is inherited. The value may also be a list of
2265 properties that should have inheritance, or a regular expression matching
2266 properties that should be inherited.
2268 However, note that some special properties use inheritance under special
2269 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2270 and the properties ending in \"_ALL\" when they are used as descriptor
2271 for valid values of a property.
2273 Note for programmers:
2274 When querying an entry with `org-entry-get', you can control if inheritance
2275 should be used. By default, `org-entry-get' looks only at the local
2276 properties. You can request inheritance by setting the inherit argument
2277 to t (to force inheritance) or to `selective' (to respect the setting
2278 in this variable)."
2279 :group 'org-properties
2280 :type '(choice
2281 (const :tag "Not" nil)
2282 (const :tag "Always" t)
2283 (repeat :tag "Specific properties" (string :tag "Property"))
2284 (regexp :tag "Properties matched by regexp")))
2286 (defun org-property-inherit-p (property)
2287 "Check if PROPERTY is one that should be inherited."
2288 (cond
2289 ((eq org-use-property-inheritance t) t)
2290 ((not org-use-property-inheritance) nil)
2291 ((stringp org-use-property-inheritance)
2292 (string-match org-use-property-inheritance property))
2293 ((listp org-use-property-inheritance)
2294 (member property org-use-property-inheritance))
2295 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2297 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2298 "The default column format, if no other format has been defined.
2299 This variable can be set on the per-file basis by inserting a line
2301 #+COLUMNS: %25ITEM ....."
2302 :group 'org-properties
2303 :type 'string)
2305 (defcustom org-columns-ellipses ".."
2306 "The ellipses to be used when a field in column view is truncated.
2307 When this is the empty string, as many characters as possible are shown,
2308 but then there will be no visual indication that the field has been truncated.
2309 When this is a string of length N, the last N characters of a truncated
2310 field are replaced by this string. If the column is narrower than the
2311 ellipses string, only part of the ellipses string will be shown."
2312 :group 'org-properties
2313 :type 'string)
2315 (defcustom org-columns-modify-value-for-display-function nil
2316 "Function that modifies values for display in column view.
2317 For example, it can be used to cut out a certain part from a time stamp.
2318 The function must take 2 arguments:
2320 column-title The title of the column (*not* the property name)
2321 value The value that should be modified.
2323 The function should return the value that should be displayed,
2324 or nil if the normal value should be used."
2325 :group 'org-properties
2326 :type 'function)
2328 (defcustom org-effort-property "Effort"
2329 "The property that is being used to keep track of effort estimates.
2330 Effort estimates given in this property need to have the format H:MM."
2331 :group 'org-properties
2332 :group 'org-progress
2333 :type '(string :tag "Property"))
2335 (defconst org-global-properties-fixed
2336 '(("VISIBILITY_ALL" . "folded children content all"))
2337 "List of property/value pairs that can be inherited by any entry.
2339 These are fixed values, for the preset properties. The user variable
2340 that can be used to add to this list is `org-global-properties'.
2342 The entries in this list are cons cells where the car is a property
2343 name and cdr is a string with the value. If the value represents
2344 multiple items like an \"_ALL\" property, separate the items by
2345 spaces.")
2347 (defcustom org-global-properties nil
2348 "List of property/value pairs that can be inherited by any entry.
2350 This list will be combined with the constant `org-global-properties-fixed'.
2352 The entries in this list are cons cells where the car is a property
2353 name and cdr is a string with the value.
2355 You can set buffer-local values for the same purpose in the variable
2356 `org-file-properties' this by adding lines like
2358 #+PROPERTY: NAME VALUE"
2359 :group 'org-properties
2360 :type '(repeat
2361 (cons (string :tag "Property")
2362 (string :tag "Value"))))
2364 (defvar org-file-properties nil
2365 "List of property/value pairs that can be inherited by any entry.
2366 Valid for the current buffer.
2367 This variable is populated from #+PROPERTY lines.")
2368 (make-variable-buffer-local 'org-file-properties)
2370 (defgroup org-agenda nil
2371 "Options concerning agenda views in Org-mode."
2372 :tag "Org Agenda"
2373 :group 'org)
2375 (defvar org-category nil
2376 "Variable used by org files to set a category for agenda display.
2377 Such files should use a file variable to set it, for example
2379 # -*- mode: org; org-category: \"ELisp\"
2381 or contain a special line
2383 #+CATEGORY: ELisp
2385 If the file does not specify a category, then file's base name
2386 is used instead.")
2387 (make-variable-buffer-local 'org-category)
2388 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2390 (defcustom org-agenda-files nil
2391 "The files to be used for agenda display.
2392 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2393 \\[org-remove-file]. You can also use customize to edit the list.
2395 If an entry is a directory, all files in that directory that are matched by
2396 `org-agenda-file-regexp' will be part of the file list.
2398 If the value of the variable is not a list but a single file name, then
2399 the list of agenda files is actually stored and maintained in that file, one
2400 agenda file per line."
2401 :group 'org-agenda
2402 :type '(choice
2403 (repeat :tag "List of files and directories" file)
2404 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2406 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2407 "Regular expression to match files for `org-agenda-files'.
2408 If any element in the list in that variable contains a directory instead
2409 of a normal file, all files in that directory that are matched by this
2410 regular expression will be included."
2411 :group 'org-agenda
2412 :type 'regexp)
2414 (defcustom org-agenda-text-search-extra-files nil
2415 "List of extra files to be searched by text search commands.
2416 These files will be search in addition to the agenda files by the
2417 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2418 Note that these files will only be searched for text search commands,
2419 not for the other agenda views like todo lists, tag searches or the weekly
2420 agenda. This variable is intended to list notes and possibly archive files
2421 that should also be searched by these two commands.
2422 In fact, if the first element in the list is the symbol `agenda-archives',
2423 than all archive files of all agenda files will be added to the search
2424 scope."
2425 :group 'org-agenda
2426 :type '(set :greedy t
2427 (const :tag "Agenda Archives" agenda-archives)
2428 (repeat :inline t (file))))
2430 (if (fboundp 'defvaralias)
2431 (defvaralias 'org-agenda-multi-occur-extra-files
2432 'org-agenda-text-search-extra-files))
2434 (defcustom org-agenda-skip-unavailable-files nil
2435 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2436 A nil value means to remove them, after a query, from the list."
2437 :group 'org-agenda
2438 :type 'boolean)
2440 (defcustom org-calendar-to-agenda-key [?c]
2441 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2442 The command `org-calendar-goto-agenda' will be bound to this key. The
2443 default is the character `c' because then `c' can be used to switch back and
2444 forth between agenda and calendar."
2445 :group 'org-agenda
2446 :type 'sexp)
2448 (defcustom org-calendar-agenda-action-key [?k]
2449 "The key to be installed in `calendar-mode-map' for agenda-action.
2450 The command `org-agenda-action' will be bound to this key. The
2451 default is the character `k' because we use the same key in the agenda."
2452 :group 'org-agenda
2453 :type 'sexp)
2455 (eval-after-load "calendar"
2456 '(progn
2457 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2458 'org-calendar-goto-agenda)
2459 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2460 'org-agenda-action)))
2462 (defgroup org-latex nil
2463 "Options for embedding LaTeX code into Org-mode."
2464 :tag "Org LaTeX"
2465 :group 'org)
2467 (defcustom org-format-latex-options
2468 '(:foreground default :background default :scale 1.0
2469 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2470 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2471 "Options for creating images from LaTeX fragments.
2472 This is a property list with the following properties:
2473 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2474 `default' means use the foreground of the default face.
2475 :background the background color, or \"Transparent\".
2476 `default' means use the background of the default face.
2477 :scale a scaling factor for the size of the images.
2478 :html-foreground, :html-background, :html-scale
2479 the same numbers for HTML export.
2480 :matchers a list indicating which matchers should be used to
2481 find LaTeX fragments. Valid members of this list are:
2482 \"begin\" find environments
2483 \"$1\" find single characters surrounded by $.$
2484 \"$\" find math expressions surrounded by $...$
2485 \"$$\" find math expressions surrounded by $$....$$
2486 \"\\(\" find math expressions surrounded by \\(...\\)
2487 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2488 :group 'org-latex
2489 :type 'plist)
2491 (defcustom org-format-latex-header "\\documentclass{article}
2492 \\usepackage{fullpage} % do not remove
2493 \\usepackage{amssymb}
2494 \\usepackage[usenames]{color}
2495 \\usepackage{amsmath}
2496 \\usepackage{latexsym}
2497 \\usepackage[mathscr]{eucal}
2498 \\pagestyle{empty} % do not remove"
2499 "The document header used for processing LaTeX fragments."
2500 :group 'org-latex
2501 :type 'string)
2504 (defgroup org-font-lock nil
2505 "Font-lock settings for highlighting in Org-mode."
2506 :tag "Org Font Lock"
2507 :group 'org)
2509 (defcustom org-level-color-stars-only nil
2510 "Non-nil means fontify only the stars in each headline.
2511 When nil, the entire headline is fontified.
2512 Changing it requires restart of `font-lock-mode' to become effective
2513 also in regions already fontified."
2514 :group 'org-font-lock
2515 :type 'boolean)
2517 (defcustom org-hide-leading-stars nil
2518 "Non-nil means, hide the first N-1 stars in a headline.
2519 This works by using the face `org-hide' for these stars. This
2520 face is white for a light background, and black for a dark
2521 background. You may have to customize the face `org-hide' to
2522 make this work.
2523 Changing it requires restart of `font-lock-mode' to become effective
2524 also in regions already fontified.
2525 You may also set this on a per-file basis by adding one of the following
2526 lines to the buffer:
2528 #+STARTUP: hidestars
2529 #+STARTUP: showstars"
2530 :group 'org-font-lock
2531 :type 'boolean)
2533 (defcustom org-fontify-done-headline nil
2534 "Non-nil means, change the face of a headline if it is marked DONE.
2535 Normally, only the TODO/DONE keyword indicates the state of a headline.
2536 When this is non-nil, the headline after the keyword is set to the
2537 `org-headline-done' as an additional indication."
2538 :group 'org-font-lock
2539 :type 'boolean)
2541 (defcustom org-fontify-emphasized-text t
2542 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2543 Changing this variable requires a restart of Emacs to take effect."
2544 :group 'org-font-lock
2545 :type 'boolean)
2547 (defcustom org-highlight-latex-fragments-and-specials nil
2548 "Non-nil means, fontify what is treated specially by the exporters."
2549 :group 'org-font-lock
2550 :type 'boolean)
2552 (defcustom org-hide-emphasis-markers nil
2553 "Non-nil mean font-lock should hide the emphasis marker characters."
2554 :group 'org-font-lock
2555 :type 'boolean)
2557 (defvar org-emph-re nil
2558 "Regular expression for matching emphasis.")
2559 (defvar org-verbatim-re nil
2560 "Regular expression for matching verbatim text.")
2561 (defvar org-emphasis-regexp-components) ; defined just below
2562 (defvar org-emphasis-alist) ; defined just below
2563 (defun org-set-emph-re (var val)
2564 "Set variable and compute the emphasis regular expression."
2565 (set var val)
2566 (when (and (boundp 'org-emphasis-alist)
2567 (boundp 'org-emphasis-regexp-components)
2568 org-emphasis-alist org-emphasis-regexp-components)
2569 (let* ((e org-emphasis-regexp-components)
2570 (pre (car e))
2571 (post (nth 1 e))
2572 (border (nth 2 e))
2573 (body (nth 3 e))
2574 (nl (nth 4 e))
2575 (body1 (concat body "*?"))
2576 (markers (mapconcat 'car org-emphasis-alist ""))
2577 (vmarkers (mapconcat
2578 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2579 org-emphasis-alist "")))
2580 ;; make sure special characters appear at the right position in the class
2581 (if (string-match "\\^" markers)
2582 (setq markers (concat (replace-match "" t t markers) "^")))
2583 (if (string-match "-" markers)
2584 (setq markers (concat (replace-match "" t t markers) "-")))
2585 (if (string-match "\\^" vmarkers)
2586 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2587 (if (string-match "-" vmarkers)
2588 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2589 (if (> nl 0)
2590 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2591 (int-to-string nl) "\\}")))
2592 ;; Make the regexp
2593 (setq org-emph-re
2594 (concat "\\([" pre "]\\|^\\)"
2595 "\\("
2596 "\\([" markers "]\\)"
2597 "\\("
2598 "[^" border "]\\|"
2599 "[^" border "]"
2600 body1
2601 "[^" border "]"
2602 "\\)"
2603 "\\3\\)"
2604 "\\([" post "]\\|$\\)"))
2605 (setq org-verbatim-re
2606 (concat "\\([" pre "]\\|^\\)"
2607 "\\("
2608 "\\([" vmarkers "]\\)"
2609 "\\("
2610 "[^" border "]\\|"
2611 "[^" border "]"
2612 body1
2613 "[^" border "]"
2614 "\\)"
2615 "\\3\\)"
2616 "\\([" post "]\\|$\\)")))))
2618 (defcustom org-emphasis-regexp-components
2619 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2620 "Components used to build the regular expression for emphasis.
2621 This is a list with 6 entries. Terminology: In an emphasis string
2622 like \" *strong word* \", we call the initial space PREMATCH, the final
2623 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2624 and \"trong wor\" is the body. The different components in this variable
2625 specify what is allowed/forbidden in each part:
2627 pre Chars allowed as prematch. Beginning of line will be allowed too.
2628 post Chars allowed as postmatch. End of line will be allowed too.
2629 border The chars *forbidden* as border characters.
2630 body-regexp A regexp like \".\" to match a body character. Don't use
2631 non-shy groups here, and don't allow newline here.
2632 newline The maximum number of newlines allowed in an emphasis exp.
2634 Use customize to modify this, or restart Emacs after changing it."
2635 :group 'org-font-lock
2636 :set 'org-set-emph-re
2637 :type '(list
2638 (sexp :tag "Allowed chars in pre ")
2639 (sexp :tag "Allowed chars in post ")
2640 (sexp :tag "Forbidden chars in border ")
2641 (sexp :tag "Regexp for body ")
2642 (integer :tag "number of newlines allowed")
2643 (option (boolean :tag "Please ignore this button"))))
2645 (defcustom org-emphasis-alist
2646 `(("*" bold "<b>" "</b>")
2647 ("/" italic "<i>" "</i>")
2648 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2649 ("=" org-code "<code>" "</code>" verbatim)
2650 ("~" org-verbatim "<code>" "</code>" verbatim)
2651 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2652 "<del>" "</del>")
2654 "Special syntax for emphasized text.
2655 Text starting and ending with a special character will be emphasized, for
2656 example *bold*, _underlined_ and /italic/. This variable sets the marker
2657 characters, the face to be used by font-lock for highlighting in Org-mode
2658 Emacs buffers, and the HTML tags to be used for this.
2659 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2660 Use customize to modify this, or restart Emacs after changing it."
2661 :group 'org-font-lock
2662 :set 'org-set-emph-re
2663 :type '(repeat
2664 (list
2665 (string :tag "Marker character")
2666 (choice
2667 (face :tag "Font-lock-face")
2668 (plist :tag "Face property list"))
2669 (string :tag "HTML start tag")
2670 (string :tag "HTML end tag")
2671 (option (const verbatim)))))
2673 ;;; Miscellaneous options
2675 (defgroup org-completion nil
2676 "Completion in Org-mode."
2677 :tag "Org Completion"
2678 :group 'org)
2680 (defcustom org-completion-use-ido nil
2681 "Non-nil means, use ido completion wherever possible.
2682 Note that `ido-mode' must be active for this variable to be relevant.
2683 If you decide to turn this variable on, you might well want to turn off
2684 `org-outline-path-complete-in-steps'."
2685 :group 'org-completion
2686 :type 'boolean)
2688 (defcustom org-completion-fallback-command 'hippie-expand
2689 "The expansion command called by \\[org-complete] in normal context.
2690 Normal means, no org-mode-specific context."
2691 :group 'org-completion
2692 :type 'function)
2694 ;;; Functions and variables from ther packages
2695 ;; Declared here to avoid compiler warnings
2697 ;; XEmacs only
2698 (defvar outline-mode-menu-heading)
2699 (defvar outline-mode-menu-show)
2700 (defvar outline-mode-menu-hide)
2701 (defvar zmacs-regions) ; XEmacs regions
2703 ;; Emacs only
2704 (defvar mark-active)
2706 ;; Various packages
2707 (declare-function find-library-name "find-func" (library))
2708 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2709 (declare-function calendar-forward-day "cal-move" (arg))
2710 (declare-function calendar-goto-date "cal-move" (date))
2711 (declare-function calendar-goto-today "cal-move" ())
2712 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2713 (defvar calc-embedded-close-formula)
2714 (defvar calc-embedded-open-formula)
2715 (declare-function cdlatex-tab "ext:cdlatex" ())
2716 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2717 (defvar font-lock-unfontify-region-function)
2718 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2719 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2720 (defvar iswitchb-temp-buflist)
2721 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2722 (defvar org-agenda-tags-todo-honor-ignore-options)
2723 (declare-function org-agenda-skip "org-agenda" ())
2724 (declare-function org-format-agenda-item "org-agenda"
2725 (extra txt &optional category tags dotime noprefix remove-re))
2726 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2727 (declare-function org-agenda-change-all-lines "org-agenda"
2728 (newhead hdmarker &optional fixface just-this))
2729 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2730 (declare-function org-agenda-maybe-redo "org-agenda" ())
2731 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2732 (beg end))
2733 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2734 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2735 "org-agenda" (&optional end))
2737 (declare-function parse-time-string "parse-time" (string))
2738 (declare-function remember "remember" (&optional initial))
2739 (declare-function remember-buffer-desc "remember" ())
2740 (declare-function remember-finalize "remember" ())
2741 (defvar remember-save-after-remembering)
2742 (defvar remember-data-file)
2743 (defvar remember-register)
2744 (defvar remember-buffer)
2745 (defvar remember-handler-functions)
2746 (defvar remember-annotation-functions)
2747 (defvar texmathp-why)
2748 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2749 (declare-function table--at-cell-p "table" (position &optional object at-column))
2751 (defvar w3m-current-url)
2752 (defvar w3m-current-title)
2754 (defvar org-latex-regexps)
2756 ;;; Autoload and prepare some org modules
2758 ;; Some table stuff that needs to be defined here, because it is used
2759 ;; by the functions setting up org-mode or checking for table context.
2761 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2762 "Detects an org-type or table-type table.")
2763 (defconst org-table-line-regexp "^[ \t]*|"
2764 "Detects an org-type table line.")
2765 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2766 "Detects an org-type table line.")
2767 (defconst org-table-hline-regexp "^[ \t]*|-"
2768 "Detects an org-type table hline.")
2769 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2770 "Detects a table-type table hline.")
2771 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2772 "Searching from within a table (any type) this finds the first line
2773 outside the table.")
2775 ;; Autoload the functions in org-table.el that are needed by functions here.
2777 (eval-and-compile
2778 (org-autoload "org-table"
2779 '(org-table-align org-table-begin org-table-blank-field
2780 org-table-convert org-table-convert-region org-table-copy-down
2781 org-table-copy-region org-table-create
2782 org-table-create-or-convert-from-region
2783 org-table-create-with-table.el org-table-current-dline
2784 org-table-cut-region org-table-delete-column org-table-edit-field
2785 org-table-edit-formulas org-table-end org-table-eval-formula
2786 org-table-export org-table-field-info
2787 org-table-get-stored-formulas org-table-goto-column
2788 org-table-hline-and-move org-table-import org-table-insert-column
2789 org-table-insert-hline org-table-insert-row org-table-iterate
2790 org-table-justify-field-maybe org-table-kill-row
2791 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2792 org-table-move-column org-table-move-column-left
2793 org-table-move-column-right org-table-move-row
2794 org-table-move-row-down org-table-move-row-up
2795 org-table-next-field org-table-next-row org-table-paste-rectangle
2796 org-table-previous-field org-table-recalculate
2797 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2798 org-table-toggle-coordinate-overlays
2799 org-table-toggle-formula-debugger org-table-wrap-region
2800 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2802 (defun org-at-table-p (&optional table-type)
2803 "Return t if the cursor is inside an org-type table.
2804 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2805 (if org-enable-table-editor
2806 (save-excursion
2807 (beginning-of-line 1)
2808 (looking-at (if table-type org-table-any-line-regexp
2809 org-table-line-regexp)))
2810 nil))
2811 (defsubst org-table-p () (org-at-table-p))
2813 (defun org-at-table.el-p ()
2814 "Return t if and only if we are at a table.el table."
2815 (and (org-at-table-p 'any)
2816 (save-excursion
2817 (goto-char (org-table-begin 'any))
2818 (looking-at org-table1-hline-regexp))))
2819 (defun org-table-recognize-table.el ()
2820 "If there is a table.el table nearby, recognize it and move into it."
2821 (if org-table-tab-recognizes-table.el
2822 (if (org-at-table.el-p)
2823 (progn
2824 (beginning-of-line 1)
2825 (if (looking-at org-table-dataline-regexp)
2827 (if (looking-at org-table1-hline-regexp)
2828 (progn
2829 (beginning-of-line 2)
2830 (if (looking-at org-table-any-border-regexp)
2831 (beginning-of-line -1)))))
2832 (if (re-search-forward "|" (org-table-end t) t)
2833 (progn
2834 (require 'table)
2835 (if (table--at-cell-p (point))
2837 (message "recognizing table.el table...")
2838 (table-recognize-table)
2839 (message "recognizing table.el table...done")))
2840 (error "This should not happen..."))
2842 nil)
2843 nil))
2845 (defun org-at-table-hline-p ()
2846 "Return t if the cursor is inside a hline in a table."
2847 (if org-enable-table-editor
2848 (save-excursion
2849 (beginning-of-line 1)
2850 (looking-at org-table-hline-regexp))
2851 nil))
2853 (defvar org-table-clean-did-remove-column nil)
2855 (defun org-table-map-tables (function)
2856 "Apply FUNCTION to the start of all tables in the buffer."
2857 (save-excursion
2858 (save-restriction
2859 (widen)
2860 (goto-char (point-min))
2861 (while (re-search-forward org-table-any-line-regexp nil t)
2862 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2863 (beginning-of-line 1)
2864 (if (looking-at org-table-line-regexp)
2865 (save-excursion (funcall function)))
2866 (re-search-forward org-table-any-border-regexp nil 1))))
2867 (message "Mapping tables: done"))
2869 ;; Declare and autoload functions from org-exp.el
2871 (declare-function org-default-export-plist "org-exp")
2872 (declare-function org-infile-export-plist "org-exp")
2873 (declare-function org-get-current-options "org-exp")
2874 (eval-and-compile
2875 (org-autoload "org-exp"
2876 '(org-export org-export-as-ascii org-export-visible
2877 org-insert-export-options-template org-export-as-html-and-open
2878 org-export-as-html-batch org-export-as-html-to-buffer
2879 org-replace-region-by-html org-export-region-as-html
2880 org-export-as-html org-export-icalendar-this-file
2881 org-export-icalendar-all-agenda-files
2882 org-table-clean-before-export
2883 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2885 ;; Declare and autoload functions from org-agenda.el
2887 (eval-and-compile
2888 (org-autoload "org-agenda"
2889 '(org-agenda org-agenda-list org-search-view
2890 org-todo-list org-tags-view org-agenda-list-stuck-projects
2891 org-diary org-agenda-to-appt
2892 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2894 ;; Autoload org-remember
2896 (eval-and-compile
2897 (org-autoload "org-remember"
2898 '(org-remember-insinuate org-remember-annotation
2899 org-remember-apply-template org-remember org-remember-handler)))
2901 ;; Autoload org-clock.el
2904 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2905 (beg end))
2906 (declare-function org-clock-update-mode-line "org-clock" ())
2907 (defvar org-clock-start-time)
2908 (defvar org-clock-marker (make-marker)
2909 "Marker recording the last clock-in.")
2911 (eval-and-compile
2912 (org-autoload
2913 "org-clock"
2914 '(org-clock-in org-clock-out org-clock-cancel
2915 org-clock-goto org-clock-sum org-clock-display
2916 org-clock-remove-overlays org-clock-report
2917 org-clocktable-shift org-dblock-write:clocktable
2918 org-get-clocktable)))
2920 (defun org-clock-update-time-maybe ()
2921 "If this is a CLOCK line, update it and return t.
2922 Otherwise, return nil."
2923 (interactive)
2924 (save-excursion
2925 (beginning-of-line 1)
2926 (skip-chars-forward " \t")
2927 (when (looking-at org-clock-string)
2928 (let ((re (concat "[ \t]*" org-clock-string
2929 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2930 "\\([ \t]*=>.*\\)?\\)?"))
2931 ts te h m s neg)
2932 (cond
2933 ((not (looking-at re))
2934 nil)
2935 ((not (match-end 2))
2936 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2937 (> org-clock-marker (point))
2938 (<= org-clock-marker (point-at-eol)))
2939 ;; The clock is running here
2940 (setq org-clock-start-time
2941 (apply 'encode-time
2942 (org-parse-time-string (match-string 1))))
2943 (org-clock-update-mode-line)))
2945 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2946 (end-of-line 1)
2947 (setq ts (match-string 1)
2948 te (match-string 3))
2949 (setq s (- (time-to-seconds
2950 (apply 'encode-time (org-parse-time-string te)))
2951 (time-to-seconds
2952 (apply 'encode-time (org-parse-time-string ts))))
2953 neg (< s 0)
2954 s (abs s)
2955 h (floor (/ s 3600))
2956 s (- s (* 3600 h))
2957 m (floor (/ s 60))
2958 s (- s (* 60 s)))
2959 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2960 t))))))
2962 (defun org-check-running-clock ()
2963 "Check if the current buffer contains the running clock.
2964 If yes, offer to stop it and to save the buffer with the changes."
2965 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2966 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2967 (buffer-name))))
2968 (org-clock-out)
2969 (when (y-or-n-p "Save changed buffer?")
2970 (save-buffer))))
2972 (defun org-clocktable-try-shift (dir n)
2973 "Check if this line starts a clock table, if yes, shift the time block."
2974 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2975 (org-clocktable-shift dir n)))
2977 ;; Autoload org-timer.el
2979 ;(declare-function org-timer "org-timer")
2981 (eval-and-compile
2982 (org-autoload
2983 "org-timer"
2984 '(org-timer-start org-timer org-timer-item
2985 org-timer-change-times-in-region)))
2988 ;; Autoload archiving code
2989 ;; The stuff that is needed for cycling and tags has to be defined here.
2991 (defgroup org-archive nil
2992 "Options concerning archiving in Org-mode."
2993 :tag "Org Archive"
2994 :group 'org-structure)
2996 (defcustom org-archive-location "%s_archive::"
2997 "The location where subtrees should be archived.
2999 The value of this variable is a string, consisting of two parts,
3000 separated by a double-colon. The first part is a filename and
3001 the second part is a headline.
3003 When the filename is omitted, archiving happens in the same file.
3004 %s in the filename will be replaced by the current file
3005 name (without the directory part). Archiving to a different file
3006 is useful to keep archived entries from contributing to the
3007 Org-mode Agenda.
3009 The archived entries will be filed as subtrees of the specified
3010 headline. When the headline is omitted, the subtrees are simply
3011 filed away at the end of the file, as top-level entries. Also in
3012 the heading you can use %s to represent the file name, this can be
3013 useful when using the same archive for a number of different files.
3015 Here are a few examples:
3016 \"%s_archive::\"
3017 If the current file is Projects.org, archive in file
3018 Projects.org_archive, as top-level trees. This is the default.
3020 \"::* Archived Tasks\"
3021 Archive in the current file, under the top-level headline
3022 \"* Archived Tasks\".
3024 \"~/org/archive.org::\"
3025 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3027 \"~/org/archive.org::From %s\"
3028 Archive in file ~/org/archive.org (absolute path), und headlines
3029 \"From FILENAME\" where file name is the current file name.
3031 \"basement::** Finished Tasks\"
3032 Archive in file ./basement (relative path), as level 3 trees
3033 below the level 2 heading \"** Finished Tasks\".
3035 You may set this option on a per-file basis by adding to the buffer a
3036 line like
3038 #+ARCHIVE: basement::** Finished Tasks
3040 You may also define it locally for a subtree by setting an ARCHIVE property
3041 in the entry. If such a property is found in an entry, or anywhere up
3042 the hierarchy, it will be used."
3043 :group 'org-archive
3044 :type 'string)
3046 (defcustom org-archive-tag "ARCHIVE"
3047 "The tag that marks a subtree as archived.
3048 An archived subtree does not open during visibility cycling, and does
3049 not contribute to the agenda listings.
3050 After changing this, font-lock must be restarted in the relevant buffers to
3051 get the proper fontification."
3052 :group 'org-archive
3053 :group 'org-keywords
3054 :type 'string)
3056 (defcustom org-agenda-skip-archived-trees t
3057 "Non-nil means, the agenda will skip any items located in archived trees.
3058 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3059 variable is no longer recommended, you should leave it at the value t.
3060 Instead, use the key `v' to cycle the archives-mode in the agenda."
3061 :group 'org-archive
3062 :group 'org-agenda-skip
3063 :type 'boolean)
3065 (defcustom org-cycle-open-archived-trees nil
3066 "Non-nil means, `org-cycle' will open archived trees.
3067 An archived tree is a tree marked with the tag ARCHIVE.
3068 When nil, archived trees will stay folded. You can still open them with
3069 normal outline commands like `show-all', but not with the cycling commands."
3070 :group 'org-archive
3071 :group 'org-cycle
3072 :type 'boolean)
3074 (defcustom org-sparse-tree-open-archived-trees nil
3075 "Non-nil means sparse tree construction shows matches in archived trees.
3076 When nil, matches in these trees are highlighted, but the trees are kept in
3077 collapsed state."
3078 :group 'org-archive
3079 :group 'org-sparse-trees
3080 :type 'boolean)
3082 (defun org-cycle-hide-archived-subtrees (state)
3083 "Re-hide all archived subtrees after a visibility state change."
3084 (when (and (not org-cycle-open-archived-trees)
3085 (not (memq state '(overview folded))))
3086 (save-excursion
3087 (let* ((globalp (memq state '(contents all)))
3088 (beg (if globalp (point-min) (point)))
3089 (end (if globalp (point-max) (org-end-of-subtree t))))
3090 (org-hide-archived-subtrees beg end)
3091 (goto-char beg)
3092 (if (looking-at (concat ".*:" org-archive-tag ":"))
3093 (message "%s" (substitute-command-keys
3094 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3096 (defun org-force-cycle-archived ()
3097 "Cycle subtree even if it is archived."
3098 (interactive)
3099 (setq this-command 'org-cycle)
3100 (let ((org-cycle-open-archived-trees t))
3101 (call-interactively 'org-cycle)))
3103 (defun org-hide-archived-subtrees (beg end)
3104 "Re-hide all archived subtrees after a visibility state change."
3105 (save-excursion
3106 (let* ((re (concat ":" org-archive-tag ":")))
3107 (goto-char beg)
3108 (while (re-search-forward re end t)
3109 (and (org-on-heading-p) (hide-subtree))
3110 (org-end-of-subtree t)))))
3112 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3114 (eval-and-compile
3115 (org-autoload "org-archive"
3116 '(org-add-archive-files org-archive-subtree
3117 org-archive-to-archive-sibling org-toggle-archive-tag)))
3119 ;; Autoload Column View Code
3121 (declare-function org-columns-number-to-string "org-colview")
3122 (declare-function org-columns-get-format-and-top-level "org-colview")
3123 (declare-function org-columns-compute "org-colview")
3125 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3126 '(org-columns-number-to-string org-columns-get-format-and-top-level
3127 org-columns-compute org-agenda-columns org-columns-remove-overlays
3128 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3130 ;; Autoload ID code
3132 (declare-function org-id-store-link "org-id")
3133 (declare-function org-id-locations-load "org-id")
3134 (declare-function org-id-locations-save "org-id")
3135 (defvar org-id-track-globally)
3136 (org-autoload "org-id"
3137 '(org-id-get-create org-id-new org-id-copy org-id-get
3138 org-id-get-with-outline-path-completion
3139 org-id-get-with-outline-drilling
3140 org-id-goto org-id-find org-id-store-link))
3142 ;; Autoload Plotting Code
3144 (org-autoload "org-plot"
3145 '(org-plot/gnuplot))
3147 ;;; Variables for pre-computed regular expressions, all buffer local
3149 (defvar org-drawer-regexp nil
3150 "Matches first line of a hidden block.")
3151 (make-variable-buffer-local 'org-drawer-regexp)
3152 (defvar org-todo-regexp nil
3153 "Matches any of the TODO state keywords.")
3154 (make-variable-buffer-local 'org-todo-regexp)
3155 (defvar org-not-done-regexp nil
3156 "Matches any of the TODO state keywords except the last one.")
3157 (make-variable-buffer-local 'org-not-done-regexp)
3158 (defvar org-todo-line-regexp nil
3159 "Matches a headline and puts TODO state into group 2 if present.")
3160 (make-variable-buffer-local 'org-todo-line-regexp)
3161 (defvar org-complex-heading-regexp nil
3162 "Matches a headline and puts everything into groups:
3163 group 1: the stars
3164 group 2: The todo keyword, maybe
3165 group 3: Priority cookie
3166 group 4: True headline
3167 group 5: Tags")
3168 (make-variable-buffer-local 'org-complex-heading-regexp)
3169 (defvar org-todo-line-tags-regexp nil
3170 "Matches a headline and puts TODO state into group 2 if present.
3171 Also put tags into group 4 if tags are present.")
3172 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3173 (defvar org-nl-done-regexp nil
3174 "Matches newline followed by a headline with the DONE keyword.")
3175 (make-variable-buffer-local 'org-nl-done-regexp)
3176 (defvar org-looking-at-done-regexp nil
3177 "Matches the DONE keyword a point.")
3178 (make-variable-buffer-local 'org-looking-at-done-regexp)
3179 (defvar org-ds-keyword-length 12
3180 "Maximum length of the Deadline and SCHEDULED keywords.")
3181 (make-variable-buffer-local 'org-ds-keyword-length)
3182 (defvar org-deadline-regexp nil
3183 "Matches the DEADLINE keyword.")
3184 (make-variable-buffer-local 'org-deadline-regexp)
3185 (defvar org-deadline-time-regexp nil
3186 "Matches the DEADLINE keyword together with a time stamp.")
3187 (make-variable-buffer-local 'org-deadline-time-regexp)
3188 (defvar org-deadline-line-regexp nil
3189 "Matches the DEADLINE keyword and the rest of the line.")
3190 (make-variable-buffer-local 'org-deadline-line-regexp)
3191 (defvar org-scheduled-regexp nil
3192 "Matches the SCHEDULED keyword.")
3193 (make-variable-buffer-local 'org-scheduled-regexp)
3194 (defvar org-scheduled-time-regexp nil
3195 "Matches the SCHEDULED keyword together with a time stamp.")
3196 (make-variable-buffer-local 'org-scheduled-time-regexp)
3197 (defvar org-closed-time-regexp nil
3198 "Matches the CLOSED keyword together with a time stamp.")
3199 (make-variable-buffer-local 'org-closed-time-regexp)
3201 (defvar org-keyword-time-regexp nil
3202 "Matches any of the 4 keywords, together with the time stamp.")
3203 (make-variable-buffer-local 'org-keyword-time-regexp)
3204 (defvar org-keyword-time-not-clock-regexp nil
3205 "Matches any of the 3 keywords, together with the time stamp.")
3206 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3207 (defvar org-maybe-keyword-time-regexp nil
3208 "Matches a timestamp, possibly preceeded by a keyword.")
3209 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3210 (defvar org-planning-or-clock-line-re nil
3211 "Matches a line with planning or clock info.")
3212 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3214 (defconst org-plain-time-of-day-regexp
3215 (concat
3216 "\\(\\<[012]?[0-9]"
3217 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3218 "\\(--?"
3219 "\\(\\<[012]?[0-9]"
3220 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3221 "\\)?")
3222 "Regular expression to match a plain time or time range.
3223 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3224 groups carry important information:
3225 0 the full match
3226 1 the first time, range or not
3227 8 the second time, if it is a range.")
3229 (defconst org-plain-time-extension-regexp
3230 (concat
3231 "\\(\\<[012]?[0-9]"
3232 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3233 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3234 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3235 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3236 groups carry important information:
3237 0 the full match
3238 7 hours of duration
3239 9 minutes of duration")
3241 (defconst org-stamp-time-of-day-regexp
3242 (concat
3243 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3244 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3245 "\\(--?"
3246 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3247 "Regular expression to match a timestamp time or time range.
3248 After a match, the following groups carry important information:
3249 0 the full match
3250 1 date plus weekday, for backreferencing to make sure both times on same day
3251 2 the first time, range or not
3252 4 the second time, if it is a range.")
3254 (defconst org-startup-options
3255 '(("fold" org-startup-folded t)
3256 ("overview" org-startup-folded t)
3257 ("nofold" org-startup-folded nil)
3258 ("showall" org-startup-folded nil)
3259 ("content" org-startup-folded content)
3260 ("hidestars" org-hide-leading-stars t)
3261 ("showstars" org-hide-leading-stars nil)
3262 ("odd" org-odd-levels-only t)
3263 ("oddeven" org-odd-levels-only nil)
3264 ("align" org-startup-align-all-tables t)
3265 ("noalign" org-startup-align-all-tables nil)
3266 ("customtime" org-display-custom-times t)
3267 ("logdone" org-log-done time)
3268 ("lognotedone" org-log-done note)
3269 ("nologdone" org-log-done nil)
3270 ("lognoteclock-out" org-log-note-clock-out t)
3271 ("nolognoteclock-out" org-log-note-clock-out nil)
3272 ("logrepeat" org-log-repeat state)
3273 ("lognoterepeat" org-log-repeat note)
3274 ("nologrepeat" org-log-repeat nil)
3275 ("fninline" org-footnote-define-inline t)
3276 ("nofninline" org-footnote-define-inline nil)
3277 ("fnlocal" org-footnote-section nil)
3278 ("fnauto" org-footnote-auto-label t)
3279 ("fnprompt" org-footnote-auto-label nil)
3280 ("fnconfirm" org-footnote-auto-label confirm)
3281 ("fnplain" org-footnote-auto-label plain)
3282 ("constcgs" constants-unit-system cgs)
3283 ("constSI" constants-unit-system SI)
3284 ("noptag" org-tag-persistent-alist nil))
3285 "Variable associated with STARTUP options for org-mode.
3286 Each element is a list of three items: The startup options as written
3287 in the #+STARTUP line, the corresponding variable, and the value to
3288 set this variable to if the option is found. An optional forth element PUSH
3289 means to push this value onto the list in the variable.")
3291 (defun org-set-regexps-and-options ()
3292 "Precompute regular expressions for current buffer."
3293 (when (org-mode-p)
3294 (org-set-local 'org-todo-kwd-alist nil)
3295 (org-set-local 'org-todo-key-alist nil)
3296 (org-set-local 'org-todo-key-trigger nil)
3297 (org-set-local 'org-todo-keywords-1 nil)
3298 (org-set-local 'org-done-keywords nil)
3299 (org-set-local 'org-todo-heads nil)
3300 (org-set-local 'org-todo-sets nil)
3301 (org-set-local 'org-todo-log-states nil)
3302 (org-set-local 'org-file-properties nil)
3303 (org-set-local 'org-file-tags nil)
3304 (let ((re (org-make-options-regexp
3305 '("CATEGORY" "TODO" "COLUMNS"
3306 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3307 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3308 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3309 (splitre "[ \t]+")
3310 kwds kws0 kwsa key log value cat arch tags const links hw dws
3311 tail sep kws1 prio props ftags drawers
3312 ext-setup-or-nil setup-contents (start 0))
3313 (save-excursion
3314 (save-restriction
3315 (widen)
3316 (goto-char (point-min))
3317 (while (or (and ext-setup-or-nil
3318 (string-match re ext-setup-or-nil start)
3319 (setq start (match-end 0)))
3320 (and (setq ext-setup-or-nil nil start 0)
3321 (re-search-forward re nil t)))
3322 (setq key (upcase (match-string 1 ext-setup-or-nil))
3323 value (org-match-string-no-properties 2 ext-setup-or-nil))
3324 (cond
3325 ((equal key "CATEGORY")
3326 (if (string-match "[ \t]+$" value)
3327 (setq value (replace-match "" t t value)))
3328 (setq cat value))
3329 ((member key '("SEQ_TODO" "TODO"))
3330 (push (cons 'sequence (org-split-string value splitre)) kwds))
3331 ((equal key "TYP_TODO")
3332 (push (cons 'type (org-split-string value splitre)) kwds))
3333 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3334 ;; general TODO-like setup
3335 (push (cons (intern (downcase (match-string 1 key)))
3336 (org-split-string value splitre)) kwds))
3337 ((equal key "TAGS")
3338 (setq tags (append tags (if tags '("\\n") nil)
3339 (org-split-string value splitre))))
3340 ((equal key "COLUMNS")
3341 (org-set-local 'org-columns-default-format value))
3342 ((equal key "LINK")
3343 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3344 (push (cons (match-string 1 value)
3345 (org-trim (match-string 2 value)))
3346 links)))
3347 ((equal key "PRIORITIES")
3348 (setq prio (org-split-string value " +")))
3349 ((equal key "PROPERTY")
3350 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3351 (push (cons (match-string 1 value) (match-string 2 value))
3352 props)))
3353 ((equal key "FILETAGS")
3354 (when (string-match "\\S-" value)
3355 (setq ftags
3356 (append
3357 ftags
3358 (apply 'append
3359 (mapcar (lambda (x) (org-split-string x ":"))
3360 (org-split-string value)))))))
3361 ((equal key "DRAWERS")
3362 (setq drawers (org-split-string value splitre)))
3363 ((equal key "CONSTANTS")
3364 (setq const (append const (org-split-string value splitre))))
3365 ((equal key "STARTUP")
3366 (let ((opts (org-split-string value splitre))
3367 l var val)
3368 (while (setq l (pop opts))
3369 (when (setq l (assoc l org-startup-options))
3370 (setq var (nth 1 l) val (nth 2 l))
3371 (if (not (nth 3 l))
3372 (set (make-local-variable var) val)
3373 (if (not (listp (symbol-value var)))
3374 (set (make-local-variable var) nil))
3375 (set (make-local-variable var) (symbol-value var))
3376 (add-to-list var val))))))
3377 ((equal key "ARCHIVE")
3378 (string-match " *$" value)
3379 (setq arch (replace-match "" t t value))
3380 (remove-text-properties 0 (length arch)
3381 '(face t fontified t) arch))
3382 ((equal key "SETUPFILE")
3383 (setq setup-contents (org-file-contents
3384 (expand-file-name
3385 (org-remove-double-quotes value))
3386 'noerror))
3387 (if (not ext-setup-or-nil)
3388 (setq ext-setup-or-nil setup-contents start 0)
3389 (setq ext-setup-or-nil
3390 (concat (substring ext-setup-or-nil 0 start)
3391 "\n" setup-contents "\n"
3392 (substring ext-setup-or-nil start)))))
3393 ))))
3394 (when cat
3395 (org-set-local 'org-category (intern cat))
3396 (push (cons "CATEGORY" cat) props))
3397 (when prio
3398 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3399 (setq prio (mapcar 'string-to-char prio))
3400 (org-set-local 'org-highest-priority (nth 0 prio))
3401 (org-set-local 'org-lowest-priority (nth 1 prio))
3402 (org-set-local 'org-default-priority (nth 2 prio)))
3403 (and props (org-set-local 'org-file-properties (nreverse props)))
3404 (and ftags (org-set-local 'org-file-tags ftags))
3405 (and drawers (org-set-local 'org-drawers drawers))
3406 (and arch (org-set-local 'org-archive-location arch))
3407 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3408 ;; Process the TODO keywords
3409 (unless kwds
3410 ;; Use the global values as if they had been given locally.
3411 (setq kwds (default-value 'org-todo-keywords))
3412 (if (stringp (car kwds))
3413 (setq kwds (list (cons org-todo-interpretation
3414 (default-value 'org-todo-keywords)))))
3415 (setq kwds (reverse kwds)))
3416 (setq kwds (nreverse kwds))
3417 (let (inter kws kw)
3418 (while (setq kws (pop kwds))
3419 (let ((kws (or
3420 (run-hook-with-args-until-success
3421 'org-todo-setup-filter-hook kws)
3422 kws)))
3423 (setq inter (pop kws) sep (member "|" kws)
3424 kws0 (delete "|" (copy-sequence kws))
3425 kwsa nil
3426 kws1 (mapcar
3427 (lambda (x)
3428 ;; 1 2
3429 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3430 (progn
3431 (setq kw (match-string 1 x)
3432 key (and (match-end 2) (match-string 2 x))
3433 log (org-extract-log-state-settings x))
3434 (push (cons kw (and key (string-to-char key))) kwsa)
3435 (and log (push log org-todo-log-states))
3437 (error "Invalid TODO keyword %s" x)))
3438 kws0)
3439 kwsa (if kwsa (append '((:startgroup))
3440 (nreverse kwsa)
3441 '((:endgroup))))
3442 hw (car kws1)
3443 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3444 tail (list inter hw (car dws) (org-last dws))))
3445 (add-to-list 'org-todo-heads hw 'append)
3446 (push kws1 org-todo-sets)
3447 (setq org-done-keywords (append org-done-keywords dws nil))
3448 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3449 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3450 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3451 (setq org-todo-sets (nreverse org-todo-sets)
3452 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3453 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3454 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3455 ;; Process the constants
3456 (when const
3457 (let (e cst)
3458 (while (setq e (pop const))
3459 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3460 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3461 (setq org-table-formula-constants-local cst)))
3463 ;; Process the tags.
3464 (when tags
3465 (let (e tgs)
3466 (while (setq e (pop tags))
3467 (cond
3468 ((equal e "{") (push '(:startgroup) tgs))
3469 ((equal e "}") (push '(:endgroup) tgs))
3470 ((equal e "\\n") (push '(:newline) tgs))
3471 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3472 (push (cons (match-string 1 e)
3473 (string-to-char (match-string 2 e)))
3474 tgs))
3475 (t (push (list e) tgs))))
3476 (org-set-local 'org-tag-alist nil)
3477 (while (setq e (pop tgs))
3478 (or (and (stringp (car e))
3479 (assoc (car e) org-tag-alist))
3480 (push e org-tag-alist)))))
3482 ;; Compute the regular expressions and other local variables
3483 (if (not org-done-keywords)
3484 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3485 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3486 (length org-scheduled-string)
3487 (length org-clock-string)
3488 (length org-closed-string)))
3489 org-drawer-regexp
3490 (concat "^[ \t]*:\\("
3491 (mapconcat 'regexp-quote org-drawers "\\|")
3492 "\\):[ \t]*$")
3493 org-not-done-keywords
3494 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3495 org-todo-regexp
3496 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3497 "\\|") "\\)\\>")
3498 org-not-done-regexp
3499 (concat "\\<\\("
3500 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3501 "\\)\\>")
3502 org-todo-line-regexp
3503 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3504 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3505 "\\)\\>\\)?[ \t]*\\(.*\\)")
3506 org-complex-heading-regexp
3507 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3508 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3509 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3510 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3511 org-nl-done-regexp
3512 (concat "\n\\*+[ \t]+"
3513 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3514 "\\)" "\\>")
3515 org-todo-line-tags-regexp
3516 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3517 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3518 (org-re
3519 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3520 org-looking-at-done-regexp
3521 (concat "^" "\\(?:"
3522 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3523 "\\>")
3524 org-deadline-regexp (concat "\\<" org-deadline-string)
3525 org-deadline-time-regexp
3526 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3527 org-deadline-line-regexp
3528 (concat "\\<\\(" org-deadline-string "\\).*")
3529 org-scheduled-regexp
3530 (concat "\\<" org-scheduled-string)
3531 org-scheduled-time-regexp
3532 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3533 org-closed-time-regexp
3534 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3535 org-keyword-time-regexp
3536 (concat "\\<\\(" org-scheduled-string
3537 "\\|" org-deadline-string
3538 "\\|" org-closed-string
3539 "\\|" org-clock-string "\\)"
3540 " *[[<]\\([^]>]+\\)[]>]")
3541 org-keyword-time-not-clock-regexp
3542 (concat "\\<\\(" org-scheduled-string
3543 "\\|" org-deadline-string
3544 "\\|" org-closed-string
3545 "\\)"
3546 " *[[<]\\([^]>]+\\)[]>]")
3547 org-maybe-keyword-time-regexp
3548 (concat "\\(\\<\\(" org-scheduled-string
3549 "\\|" org-deadline-string
3550 "\\|" org-closed-string
3551 "\\|" org-clock-string "\\)\\)?"
3552 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3553 org-planning-or-clock-line-re
3554 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3555 "\\|" org-deadline-string
3556 "\\|" org-closed-string "\\|" org-clock-string
3557 "\\)\\>\\)")
3559 (org-compute-latex-and-specials-regexp)
3560 (org-set-font-lock-defaults))))
3562 (defun org-file-contents (file &optional noerror)
3563 "Return the contents of FILE, as a string."
3564 (if (or (not file)
3565 (not (file-readable-p file)))
3566 (if noerror
3567 (progn
3568 (message "Cannot read file %s" file)
3569 (ding) (sit-for 2)
3571 (error "Cannot read file %s" file))
3572 (with-temp-buffer
3573 (insert-file-contents file)
3574 (buffer-string))))
3576 (defun org-extract-log-state-settings (x)
3577 "Extract the log state setting from a TODO keyword string.
3578 This will extract info from a string like \"WAIT(w@/!)\"."
3579 (let (kw key log1 log2)
3580 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3581 (setq kw (match-string 1 x)
3582 key (and (match-end 2) (match-string 2 x))
3583 log1 (and (match-end 3) (match-string 3 x))
3584 log2 (and (match-end 4) (match-string 4 x)))
3585 (and (or log1 log2)
3586 (list kw
3587 (and log1 (if (equal log1 "!") 'time 'note))
3588 (and log2 (if (equal log2 "!") 'time 'note)))))))
3590 (defun org-remove-keyword-keys (list)
3591 "Remove a pair of parenthesis at the end of each string in LIST."
3592 (mapcar (lambda (x)
3593 (if (string-match "(.*)$" x)
3594 (substring x 0 (match-beginning 0))
3596 list))
3598 ;; FIXME: this could be done much better, using second characters etc.
3599 (defun org-assign-fast-keys (alist)
3600 "Assign fast keys to a keyword-key alist.
3601 Respect keys that are already there."
3602 (let (new e k c c1 c2 (char ?a))
3603 (while (setq e (pop alist))
3604 (cond
3605 ((equal e '(:startgroup)) (push e new))
3606 ((equal e '(:endgroup)) (push e new))
3607 ((equal e '(:newline)) (push e new))
3609 (setq k (car e) c2 nil)
3610 (if (cdr e)
3611 (setq c (cdr e))
3612 ;; automatically assign a character.
3613 (setq c1 (string-to-char
3614 (downcase (substring
3615 k (if (= (string-to-char k) ?@) 1 0)))))
3616 (if (or (rassoc c1 new) (rassoc c1 alist))
3617 (while (or (rassoc char new) (rassoc char alist))
3618 (setq char (1+ char)))
3619 (setq c2 c1))
3620 (setq c (or c2 char)))
3621 (push (cons k c) new))))
3622 (nreverse new)))
3624 ;;; Some variables used in various places
3626 (defvar org-window-configuration nil
3627 "Used in various places to store a window configuration.")
3628 (defvar org-finish-function nil
3629 "Function to be called when `C-c C-c' is used.
3630 This is for getting out of special buffers like remember.")
3633 ;; FIXME: Occasionally check by commenting these, to make sure
3634 ;; no other functions uses these, forgetting to let-bind them.
3635 (defvar entry)
3636 (defvar state)
3637 (defvar last-state)
3638 (defvar date)
3639 (defvar description)
3641 ;; Defined somewhere in this file, but used before definition.
3642 (defvar org-html-entities)
3643 (defvar org-struct-menu)
3644 (defvar org-org-menu)
3645 (defvar org-tbl-menu)
3646 (defvar org-agenda-keymap)
3648 ;;;; Define the Org-mode
3650 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3651 (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."))
3654 ;; We use a before-change function to check if a table might need
3655 ;; an update.
3656 (defvar org-table-may-need-update t
3657 "Indicates that a table might need an update.
3658 This variable is set by `org-before-change-function'.
3659 `org-table-align' sets it back to nil.")
3660 (defun org-before-change-function (beg end)
3661 "Every change indicates that a table might need an update."
3662 (setq org-table-may-need-update t))
3663 (defvar org-mode-map)
3664 (defvar org-mode-hook nil
3665 "Mode hook for Org-mode, run after the mode was turned on.")
3666 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3667 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3668 (defvar org-table-buffer-is-an nil)
3669 (defconst org-outline-regexp "\\*+ ")
3671 ;;;###autoload
3672 (define-derived-mode org-mode outline-mode "Org"
3673 "Outline-based notes management and organizer, alias
3674 \"Carsten's outline-mode for keeping track of everything.\"
3676 Org-mode develops organizational tasks around a NOTES file which
3677 contains information about projects as plain text. Org-mode is
3678 implemented on top of outline-mode, which is ideal to keep the content
3679 of large files well structured. It supports ToDo items, deadlines and
3680 time stamps, which magically appear in the diary listing of the Emacs
3681 calendar. Tables are easily created with a built-in table editor.
3682 Plain text URL-like links connect to websites, emails (VM), Usenet
3683 messages (Gnus), BBDB entries, and any files related to the project.
3684 For printing and sharing of notes, an Org-mode file (or a part of it)
3685 can be exported as a structured ASCII or HTML file.
3687 The following commands are available:
3689 \\{org-mode-map}"
3691 ;; Get rid of Outline menus, they are not needed
3692 ;; Need to do this here because define-derived-mode sets up
3693 ;; the keymap so late. Still, it is a waste to call this each time
3694 ;; we switch another buffer into org-mode.
3695 (if (featurep 'xemacs)
3696 (when (boundp 'outline-mode-menu-heading)
3697 ;; Assume this is Greg's port, it used easymenu
3698 (easy-menu-remove outline-mode-menu-heading)
3699 (easy-menu-remove outline-mode-menu-show)
3700 (easy-menu-remove outline-mode-menu-hide))
3701 (define-key org-mode-map [menu-bar headings] 'undefined)
3702 (define-key org-mode-map [menu-bar hide] 'undefined)
3703 (define-key org-mode-map [menu-bar show] 'undefined))
3705 (org-load-modules-maybe)
3706 (easy-menu-add org-org-menu)
3707 (easy-menu-add org-tbl-menu)
3708 (org-install-agenda-files-menu)
3709 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3710 (org-add-to-invisibility-spec '(org-cwidth))
3711 (when (featurep 'xemacs)
3712 (org-set-local 'line-move-ignore-invisible t))
3713 (org-set-local 'outline-regexp org-outline-regexp)
3714 (org-set-local 'outline-level 'org-outline-level)
3715 (when (and org-ellipsis
3716 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3717 (fboundp 'make-glyph-code))
3718 (unless org-display-table
3719 (setq org-display-table (make-display-table)))
3720 (set-display-table-slot
3721 org-display-table 4
3722 (vconcat (mapcar
3723 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3724 org-ellipsis)))
3725 (if (stringp org-ellipsis) org-ellipsis "..."))))
3726 (setq buffer-display-table org-display-table))
3727 (org-set-regexps-and-options)
3728 (when (and org-tag-faces (not org-tags-special-faces-re))
3729 ;; tag faces set outside customize.... force initialization.
3730 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3731 ;; Calc embedded
3732 (org-set-local 'calc-embedded-open-mode "# ")
3733 (modify-syntax-entry ?# "<")
3734 (modify-syntax-entry ?@ "w")
3735 (if org-startup-truncated (setq truncate-lines t))
3736 (org-set-local 'font-lock-unfontify-region-function
3737 'org-unfontify-region)
3738 ;; Activate before-change-function
3739 (org-set-local 'org-table-may-need-update t)
3740 (org-add-hook 'before-change-functions 'org-before-change-function nil
3741 'local)
3742 ;; Check for running clock before killing a buffer
3743 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3744 ;; Paragraphs and auto-filling
3745 (org-set-autofill-regexps)
3746 (setq indent-line-function 'org-indent-line-function)
3747 (org-update-radio-target-regexp)
3748 ;; Make sure dependence stuff works reliably, even for users who set it
3749 ;; too late :-(
3750 (if org-enforce-todo-dependencies
3751 (add-hook 'org-blocker-hook
3752 'org-block-todo-from-children-or-siblings)
3753 (remove-hook 'org-blocker-hook
3754 'org-block-todo-from-children-or-siblings))
3755 (if org-enforce-todo-checkbox-dependencies
3756 (add-hook 'org-blocker-hook
3757 'org-block-todo-from-checkboxes)
3758 (remove-hook 'org-blocker-hook
3759 'org-block-todo-from-checkboxes))
3761 ;; Comment characters
3762 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3763 (org-set-local 'comment-padding " ")
3765 ;; Align options lines
3766 (org-set-local
3767 'align-mode-rules-list
3768 '((org-in-buffer-settings
3769 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3770 (modes . '(org-mode)))))
3772 ;; Imenu
3773 (org-set-local 'imenu-create-index-function
3774 'org-imenu-get-tree)
3776 ;; Make isearch reveal context
3777 (if (or (featurep 'xemacs)
3778 (not (boundp 'outline-isearch-open-invisible-function)))
3779 ;; Emacs 21 and XEmacs make use of the hook
3780 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3781 ;; Emacs 22 deals with this through a special variable
3782 (org-set-local 'outline-isearch-open-invisible-function
3783 (lambda (&rest ignore) (org-show-context 'isearch))))
3785 ;; If empty file that did not turn on org-mode automatically, make it to.
3786 (if (and org-insert-mode-line-in-empty-file
3787 (interactive-p)
3788 (= (point-min) (point-max)))
3789 (insert "# -*- mode: org -*-\n\n"))
3791 (unless org-inhibit-startup
3792 (when org-startup-align-all-tables
3793 (let ((bmp (buffer-modified-p)))
3794 (org-table-map-tables 'org-table-align)
3795 (set-buffer-modified-p bmp)))
3796 (org-set-startup-visibility)))
3798 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3800 (defun org-current-time ()
3801 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3802 (if (> (car org-time-stamp-rounding-minutes) 1)
3803 (let ((r (car org-time-stamp-rounding-minutes))
3804 (time (decode-time)))
3805 (apply 'encode-time
3806 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3807 (nthcdr 2 time))))
3808 (current-time)))
3810 ;;;; Font-Lock stuff, including the activators
3812 (defvar org-mouse-map (make-sparse-keymap))
3813 (org-defkey org-mouse-map
3814 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3815 (org-defkey org-mouse-map
3816 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3817 (when org-mouse-1-follows-link
3818 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3819 (when org-tab-follows-link
3820 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3821 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3823 (require 'font-lock)
3825 (defconst org-non-link-chars "]\t\n\r<>")
3826 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3827 "shell" "elisp"))
3828 (defvar org-link-types-re nil
3829 "Matches a link that has a url-like prefix like \"http:\"")
3830 (defvar org-link-re-with-space nil
3831 "Matches a link with spaces, optional angular brackets around it.")
3832 (defvar org-link-re-with-space2 nil
3833 "Matches a link with spaces, optional angular brackets around it.")
3834 (defvar org-link-re-with-space3 nil
3835 "Matches a link with spaces, only for internal part in bracket links.")
3836 (defvar org-angle-link-re nil
3837 "Matches link with angular brackets, spaces are allowed.")
3838 (defvar org-plain-link-re nil
3839 "Matches plain link, without spaces.")
3840 (defvar org-bracket-link-regexp nil
3841 "Matches a link in double brackets.")
3842 (defvar org-bracket-link-analytic-regexp nil
3843 "Regular expression used to analyze links.
3844 Here is what the match groups contain after a match:
3845 1: http:
3846 2: http
3847 3: path
3848 4: [desc]
3849 5: desc")
3850 (defvar org-bracket-link-analytic-regexp++ nil
3851 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3852 (defvar org-any-link-re nil
3853 "Regular expression matching any link.")
3855 (defun org-make-link-regexps ()
3856 "Update the link regular expressions.
3857 This should be called after the variable `org-link-types' has changed."
3858 (setq org-link-types-re
3859 (concat
3860 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3861 org-link-re-with-space
3862 (concat
3863 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3864 "\\([^" org-non-link-chars " ]"
3865 "[^" org-non-link-chars "]*"
3866 "[^" org-non-link-chars " ]\\)>?")
3867 org-link-re-with-space2
3868 (concat
3869 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3870 "\\([^" org-non-link-chars " ]"
3871 "[^\t\n\r]*"
3872 "[^" org-non-link-chars " ]\\)>?")
3873 org-link-re-with-space3
3874 (concat
3875 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3876 "\\([^" org-non-link-chars " ]"
3877 "[^\t\n\r]*\\)")
3878 org-angle-link-re
3879 (concat
3880 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3881 "\\([^" org-non-link-chars " ]"
3882 "[^" org-non-link-chars "]*"
3883 "\\)>")
3884 org-plain-link-re
3885 (concat
3886 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3887 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3888 org-bracket-link-regexp
3889 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3890 org-bracket-link-analytic-regexp
3891 (concat
3892 "\\[\\["
3893 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3894 "\\([^]]+\\)"
3895 "\\]"
3896 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3897 "\\]")
3898 org-bracket-link-analytic-regexp++
3899 (concat
3900 "\\[\\["
3901 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3902 "\\([^]]+\\)"
3903 "\\]"
3904 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3905 "\\]")
3906 org-any-link-re
3907 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3908 org-angle-link-re "\\)\\|\\("
3909 org-plain-link-re "\\)")))
3911 (org-make-link-regexps)
3913 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3914 "Regular expression for fast time stamp matching.")
3915 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3916 "Regular expression for fast time stamp matching.")
3917 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3918 "Regular expression matching time strings for analysis.
3919 This one does not require the space after the date, so it can be used
3920 on a string that terminates immediately after the date.")
3921 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3922 "Regular expression matching time strings for analysis.")
3923 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3924 "Regular expression matching time stamps, with groups.")
3925 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3926 "Regular expression matching time stamps (also [..]), with groups.")
3927 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3928 "Regular expression matching a time stamp range.")
3929 (defconst org-tr-regexp-both
3930 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3931 "Regular expression matching a time stamp range.")
3932 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3933 org-ts-regexp "\\)?")
3934 "Regular expression matching a time stamp or time stamp range.")
3935 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3936 org-ts-regexp-both "\\)?")
3937 "Regular expression matching a time stamp or time stamp range.
3938 The time stamps may be either active or inactive.")
3940 (defvar org-emph-face nil)
3942 (defun org-do-emphasis-faces (limit)
3943 "Run through the buffer and add overlays to links."
3944 (let (rtn)
3945 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3946 (if (not (= (char-after (match-beginning 3))
3947 (char-after (match-beginning 4))))
3948 (progn
3949 (setq rtn t)
3950 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3951 'face
3952 (nth 1 (assoc (match-string 3)
3953 org-emphasis-alist)))
3954 (add-text-properties (match-beginning 2) (match-end 2)
3955 '(font-lock-multiline t))
3956 (when org-hide-emphasis-markers
3957 (add-text-properties (match-end 4) (match-beginning 5)
3958 '(invisible org-link))
3959 (add-text-properties (match-beginning 3) (match-end 3)
3960 '(invisible org-link)))))
3961 (backward-char 1))
3962 rtn))
3964 (defun org-emphasize (&optional char)
3965 "Insert or change an emphasis, i.e. a font like bold or italic.
3966 If there is an active region, change that region to a new emphasis.
3967 If there is no region, just insert the marker characters and position
3968 the cursor between them.
3969 CHAR should be either the marker character, or the first character of the
3970 HTML tag associated with that emphasis. If CHAR is a space, the means
3971 to remove the emphasis of the selected region.
3972 If char is not given (for example in an interactive call) it
3973 will be prompted for."
3974 (interactive)
3975 (let ((eal org-emphasis-alist) e det
3976 (erc org-emphasis-regexp-components)
3977 (prompt "")
3978 (string "") beg end move tag c s)
3979 (if (org-region-active-p)
3980 (setq beg (region-beginning) end (region-end)
3981 string (buffer-substring beg end))
3982 (setq move t))
3984 (while (setq e (pop eal))
3985 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3986 c (aref tag 0))
3987 (push (cons c (string-to-char (car e))) det)
3988 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3989 (substring tag 1)))))
3990 (setq det (nreverse det))
3991 (unless char
3992 (message "%s" (concat "Emphasis marker or tag:" prompt))
3993 (setq char (read-char-exclusive)))
3994 (setq char (or (cdr (assoc char det)) char))
3995 (if (equal char ?\ )
3996 (setq s "" move nil)
3997 (unless (assoc (char-to-string char) org-emphasis-alist)
3998 (error "No such emphasis marker: \"%c\"" char))
3999 (setq s (char-to-string char)))
4000 (while (and (> (length string) 1)
4001 (equal (substring string 0 1) (substring string -1))
4002 (assoc (substring string 0 1) org-emphasis-alist))
4003 (setq string (substring string 1 -1)))
4004 (setq string (concat s string s))
4005 (if beg (delete-region beg end))
4006 (unless (or (bolp)
4007 (string-match (concat "[" (nth 0 erc) "\n]")
4008 (char-to-string (char-before (point)))))
4009 (insert " "))
4010 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4011 (char-to-string (char-after (point))))
4012 (insert " ") (backward-char 1))
4013 (insert string)
4014 (and move (backward-char 1))))
4016 (defconst org-nonsticky-props
4017 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4020 (defun org-activate-plain-links (limit)
4021 "Run through the buffer and add overlays to links."
4022 (catch 'exit
4023 (let (f)
4024 (while (re-search-forward org-plain-link-re limit t)
4025 (setq f (get-text-property (match-beginning 0) 'face))
4026 (if (or (eq f 'org-tag)
4027 (and (listp f) (memq 'org-tag f)))
4029 (add-text-properties (match-beginning 0) (match-end 0)
4030 (list 'mouse-face 'highlight
4031 'rear-nonsticky org-nonsticky-props
4032 'keymap org-mouse-map
4034 (throw 'exit t))))))
4036 (defun org-activate-code (limit)
4037 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4038 (progn
4039 (remove-text-properties (match-beginning 0) (match-end 0)
4040 '(display t invisible t intangible t))
4041 t)))
4043 (defun org-activate-angle-links (limit)
4044 "Run through the buffer and add overlays to links."
4045 (if (re-search-forward org-angle-link-re limit t)
4046 (progn
4047 (add-text-properties (match-beginning 0) (match-end 0)
4048 (list 'mouse-face 'highlight
4049 'rear-nonsticky org-nonsticky-props
4050 'keymap org-mouse-map
4052 t)))
4054 (defun org-activate-footnote-links (limit)
4055 "Run through the buffer and add overlays to links."
4056 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4057 limit t)
4058 (progn
4059 (add-text-properties (match-beginning 2) (match-end 2)
4060 (list 'mouse-face 'highlight
4061 'rear-nonsticky org-nonsticky-props
4062 'keymap org-mouse-map
4063 'help-echo
4064 (if (= (point-at-bol) (match-beginning 2))
4065 "Footnote definition"
4066 "Footnote reference")
4068 t)))
4070 (defun org-activate-bracket-links (limit)
4071 "Run through the buffer and add overlays to bracketed links."
4072 (if (re-search-forward org-bracket-link-regexp limit t)
4073 (let* ((help (concat "LINK: "
4074 (org-match-string-no-properties 1)))
4075 ;; FIXME: above we should remove the escapes.
4076 ;; but that requires another match, protecting match data,
4077 ;; a lot of overhead for font-lock.
4078 (ip (org-maybe-intangible
4079 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4080 'keymap org-mouse-map 'mouse-face 'highlight
4081 'font-lock-multiline t 'help-echo help)))
4082 (vp (list 'rear-nonsticky org-nonsticky-props
4083 'keymap org-mouse-map 'mouse-face 'highlight
4084 ' font-lock-multiline t 'help-echo help)))
4085 ;; We need to remove the invisible property here. Table narrowing
4086 ;; may have made some of this invisible.
4087 (remove-text-properties (match-beginning 0) (match-end 0)
4088 '(invisible nil))
4089 (if (match-end 3)
4090 (progn
4091 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4092 (add-text-properties (match-beginning 3) (match-end 3) vp)
4093 (add-text-properties (match-end 3) (match-end 0) ip))
4094 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4095 (add-text-properties (match-beginning 1) (match-end 1) vp)
4096 (add-text-properties (match-end 1) (match-end 0) ip))
4097 t)))
4099 (defun org-activate-dates (limit)
4100 "Run through the buffer and add overlays to dates."
4101 (if (re-search-forward org-tsr-regexp-both limit t)
4102 (progn
4103 (add-text-properties (match-beginning 0) (match-end 0)
4104 (list 'mouse-face 'highlight
4105 'rear-nonsticky org-nonsticky-props
4106 'keymap org-mouse-map))
4107 (when org-display-custom-times
4108 (if (match-end 3)
4109 (org-display-custom-time (match-beginning 3) (match-end 3)))
4110 (org-display-custom-time (match-beginning 1) (match-end 1)))
4111 t)))
4113 (defvar org-target-link-regexp nil
4114 "Regular expression matching radio targets in plain text.")
4115 (make-variable-buffer-local 'org-target-link-regexp)
4116 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4117 "Regular expression matching a link target.")
4118 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4119 "Regular expression matching a radio target.")
4120 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4121 "Regular expression matching any target.")
4123 (defun org-activate-target-links (limit)
4124 "Run through the buffer and add overlays to target matches."
4125 (when org-target-link-regexp
4126 (let ((case-fold-search t))
4127 (if (re-search-forward org-target-link-regexp limit t)
4128 (progn
4129 (add-text-properties (match-beginning 0) (match-end 0)
4130 (list 'mouse-face 'highlight
4131 'rear-nonsticky org-nonsticky-props
4132 'keymap org-mouse-map
4133 'help-echo "Radio target link"
4134 'org-linked-text t))
4135 t)))))
4137 (defun org-update-radio-target-regexp ()
4138 "Find all radio targets in this file and update the regular expression."
4139 (interactive)
4140 (when (memq 'radio org-activate-links)
4141 (setq org-target-link-regexp
4142 (org-make-target-link-regexp (org-all-targets 'radio)))
4143 (org-restart-font-lock)))
4145 (defun org-hide-wide-columns (limit)
4146 (let (s e)
4147 (setq s (text-property-any (point) (or limit (point-max))
4148 'org-cwidth t))
4149 (when s
4150 (setq e (next-single-property-change s 'org-cwidth))
4151 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4152 (goto-char e)
4153 t)))
4155 (defvar org-latex-and-specials-regexp nil
4156 "Regular expression for highlighting export special stuff.")
4157 (defvar org-match-substring-regexp)
4158 (defvar org-match-substring-with-braces-regexp)
4159 (defvar org-export-html-special-string-regexps)
4161 (defun org-compute-latex-and-specials-regexp ()
4162 "Compute regular expression for stuff treated specially by exporters."
4163 (if (not org-highlight-latex-fragments-and-specials)
4164 (org-set-local 'org-latex-and-specials-regexp nil)
4165 (require 'org-exp)
4166 (let*
4167 ((matchers (plist-get org-format-latex-options :matchers))
4168 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4169 org-latex-regexps)))
4170 (options (org-combine-plists (org-default-export-plist)
4171 (org-infile-export-plist)))
4172 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4173 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4174 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4175 (org-export-html-expand (plist-get options :expand-quoted-html))
4176 (org-export-with-special-strings (plist-get options :special-strings))
4177 (re-sub
4178 (cond
4179 ((equal org-export-with-sub-superscripts '{})
4180 (list org-match-substring-with-braces-regexp))
4181 (org-export-with-sub-superscripts
4182 (list org-match-substring-regexp))
4183 (t nil)))
4184 (re-latex
4185 (if org-export-with-LaTeX-fragments
4186 (mapcar (lambda (x) (nth 1 x)) latexs)))
4187 (re-macros
4188 (if org-export-with-TeX-macros
4189 (list (concat "\\\\"
4190 (regexp-opt
4191 (append (mapcar 'car org-html-entities)
4192 (if (boundp 'org-latex-entities)
4193 org-latex-entities nil))
4194 'words))) ; FIXME
4196 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4197 (re-special (if org-export-with-special-strings
4198 (mapcar (lambda (x) (car x))
4199 org-export-html-special-string-regexps)))
4200 (re-rest
4201 (delq nil
4202 (list
4203 (if org-export-html-expand "@<[^>\n]+>")
4204 ))))
4205 (org-set-local
4206 'org-latex-and-specials-regexp
4207 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4208 re-rest) "\\|")))))
4210 (defun org-do-latex-and-special-faces (limit)
4211 "Run through the buffer and add overlays to links."
4212 (when org-latex-and-specials-regexp
4213 (let (rtn d)
4214 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4215 limit t))
4216 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4217 'face))
4218 '(org-code org-verbatim underline)))
4219 (progn
4220 (setq rtn t
4221 d (cond ((member (char-after (1+ (match-beginning 0)))
4222 '(?_ ?^)) 1)
4223 (t 0)))
4224 (font-lock-prepend-text-property
4225 (+ d (match-beginning 0)) (match-end 0)
4226 'face 'org-latex-and-export-specials)
4227 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4228 '(font-lock-multiline t)))))
4229 rtn)))
4231 (defun org-restart-font-lock ()
4232 "Restart font-lock-mode, to force refontification."
4233 (when (and (boundp 'font-lock-mode) font-lock-mode)
4234 (font-lock-mode -1)
4235 (font-lock-mode 1)))
4237 (defun org-all-targets (&optional radio)
4238 "Return a list of all targets in this file.
4239 With optional argument RADIO, only find radio targets."
4240 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4241 rtn)
4242 (save-excursion
4243 (goto-char (point-min))
4244 (while (re-search-forward re nil t)
4245 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4246 rtn)))
4248 (defun org-make-target-link-regexp (targets)
4249 "Make regular expression matching all strings in TARGETS.
4250 The regular expression finds the targets also if there is a line break
4251 between words."
4252 (and targets
4253 (concat
4254 "\\<\\("
4255 (mapconcat
4256 (lambda (x)
4257 (while (string-match " +" x)
4258 (setq x (replace-match "\\s-+" t t x)))
4260 targets
4261 "\\|")
4262 "\\)\\>")))
4264 (defun org-activate-tags (limit)
4265 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4266 (progn
4267 (add-text-properties (match-beginning 1) (match-end 1)
4268 (list 'mouse-face 'highlight
4269 'rear-nonsticky org-nonsticky-props
4270 'keymap org-mouse-map))
4271 t)))
4273 (defun org-outline-level ()
4274 (save-excursion
4275 (looking-at outline-regexp)
4276 (if (match-beginning 1)
4277 (+ (org-get-string-indentation (match-string 1)) 1000)
4278 (1- (- (match-end 0) (match-beginning 0))))))
4280 (defvar org-font-lock-keywords nil)
4282 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4283 "Regular expression matching a property line.")
4285 (defvar org-font-lock-hook nil
4286 "Functions to be called for special font lock stuff.")
4288 (defun org-font-lock-hook (limit)
4289 (run-hook-with-args 'org-font-lock-hook limit))
4291 (defun org-set-font-lock-defaults ()
4292 (let* ((em org-fontify-emphasized-text)
4293 (lk org-activate-links)
4294 (org-font-lock-extra-keywords
4295 (list
4296 ;; Call the hook
4297 '(org-font-lock-hook)
4298 ;; Headlines
4299 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4300 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4301 ;; Table lines
4302 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4303 (1 'org-table t))
4304 ;; Table internals
4305 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4306 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4307 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4308 ;; Drawers
4309 (list org-drawer-regexp '(0 'org-special-keyword t))
4310 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4311 ;; Properties
4312 (list org-property-re
4313 '(1 'org-special-keyword t)
4314 '(3 'org-property-value t))
4315 (if org-format-transports-properties-p
4316 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4317 ;; Links
4318 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4319 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4320 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4321 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4322 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4323 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4324 (if (memq 'footnote lk) '(org-activate-footnote-links
4325 (2 'org-footnote t)))
4326 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4327 '(org-hide-wide-columns (0 nil append))
4328 ;; TODO lines
4329 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4330 '(1 (org-get-todo-face 1) t))
4331 ;; DONE
4332 (if org-fontify-done-headline
4333 (list (concat "^[*]+ +\\<\\("
4334 (mapconcat 'regexp-quote org-done-keywords "\\|")
4335 "\\)\\(.*\\)")
4336 '(2 'org-headline-done t))
4337 nil)
4338 ;; Priorities
4339 '(org-font-lock-add-priority-faces)
4340 ;; Tags
4341 '(org-font-lock-add-tag-faces)
4342 ;; Special keywords
4343 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4344 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4345 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4346 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4347 ;; Emphasis
4348 (if em
4349 (if (featurep 'xemacs)
4350 '(org-do-emphasis-faces (0 nil append))
4351 '(org-do-emphasis-faces)))
4352 ;; Checkboxes
4353 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4354 2 'bold prepend)
4355 (if org-provide-checkbox-statistics
4356 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4357 (0 (org-get-checkbox-statistics-face) t)))
4358 ;; Description list items
4359 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4360 2 'bold prepend)
4361 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4362 '(1 'org-archived prepend))
4363 ;; Specials
4364 '(org-do-latex-and-special-faces)
4365 ;; Code
4366 '(org-activate-code (1 'org-code t))
4367 ;; COMMENT
4368 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4369 "\\|" org-quote-string "\\)\\>")
4370 '(1 'org-special-keyword t))
4371 '("^#.*" (0 'font-lock-comment-face t))
4373 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4374 ;; Now set the full font-lock-keywords
4375 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4376 (org-set-local 'font-lock-defaults
4377 '(org-font-lock-keywords t nil nil backward-paragraph))
4378 (kill-local-variable 'font-lock-keywords) nil))
4380 (defvar org-m nil)
4381 (defvar org-l nil)
4382 (defvar org-f nil)
4383 (defun org-get-level-face (n)
4384 "Get the right face for match N in font-lock matching of headlines."
4385 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4386 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4387 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4388 (cond
4389 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4390 ((eq n 2) org-f)
4391 (t (if org-level-color-stars-only nil org-f))))
4393 (defun org-get-todo-face (kwd)
4394 "Get the right face for a TODO keyword KWD.
4395 If KWD is a number, get the corresponding match group."
4396 (if (numberp kwd) (setq kwd (match-string kwd)))
4397 (or (cdr (assoc kwd org-todo-keyword-faces))
4398 (and (member kwd org-done-keywords) 'org-done)
4399 'org-todo))
4401 (defun org-font-lock-add-tag-faces (limit)
4402 "Add the special tag faces."
4403 (when (and org-tag-faces org-tags-special-faces-re)
4404 (while (re-search-forward org-tags-special-faces-re limit t)
4405 (add-text-properties (match-beginning 1) (match-end 1)
4406 (list 'face (org-get-tag-face 1)
4407 'font-lock-fontified t))
4408 (backward-char 1))))
4410 (defun org-font-lock-add-priority-faces (limit)
4411 "Add the special priority faces."
4412 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4413 (add-text-properties
4414 (match-beginning 0) (match-end 0)
4415 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4416 org-priority-faces))
4417 'org-special-keyword)
4418 'font-lock-fontified t))))
4420 (defun org-get-tag-face (kwd)
4421 "Get the right face for a TODO keyword KWD.
4422 If KWD is a number, get the corresponding match group."
4423 (if (numberp kwd) (setq kwd (match-string kwd)))
4424 (or (cdr (assoc kwd org-tag-faces))
4425 'org-tag))
4427 (defun org-unfontify-region (beg end &optional maybe_loudly)
4428 "Remove fontification and activation overlays from links."
4429 (font-lock-default-unfontify-region beg end)
4430 (let* ((buffer-undo-list t)
4431 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4432 (inhibit-modification-hooks t)
4433 deactivate-mark buffer-file-name buffer-file-truename)
4434 (remove-text-properties beg end
4435 '(mouse-face t keymap t org-linked-text t
4436 invisible t intangible t))))
4438 ;;;; Visibility cycling, including org-goto and indirect buffer
4440 ;;; Cycling
4442 (defvar org-cycle-global-status nil)
4443 (make-variable-buffer-local 'org-cycle-global-status)
4444 (defvar org-cycle-subtree-status nil)
4445 (make-variable-buffer-local 'org-cycle-subtree-status)
4447 ;;;###autoload
4448 (defun org-cycle (&optional arg)
4449 "Visibility cycling for Org-mode.
4451 - When this function is called with a prefix argument, rotate the entire
4452 buffer through 3 states (global cycling)
4453 1. OVERVIEW: Show only top-level headlines.
4454 2. CONTENTS: Show all headlines of all levels, but no body text.
4455 3. SHOW ALL: Show everything.
4456 When called with two C-u C-u prefixes, switch to the startup visibility,
4457 determined by the variable `org-startup-folded', and by any VISIBILITY
4458 properties in the buffer.
4459 When called with three C-u C-u C-u prefixed, show the entire buffer,
4460 including drawers.
4462 - When point is at the beginning of a headline, rotate the subtree started
4463 by this line through 3 different states (local cycling)
4464 1. FOLDED: Only the main headline is shown.
4465 2. CHILDREN: The main headline and the direct children are shown.
4466 From this state, you can move to one of the children
4467 and zoom in further.
4468 3. SUBTREE: Show the entire subtree, including body text.
4470 - When there is a numeric prefix, go up to a heading with level ARG, do
4471 a `show-subtree' and return to the previous cursor position. If ARG
4472 is negative, go up that many levels.
4474 - When point is not at the beginning of a headline, execute the global
4475 binding for TAB, which is re-indenting the line. See the option
4476 `org-cycle-emulate-tab' for details.
4478 - Special case: if point is at the beginning of the buffer and there is
4479 no headline in line 1, this function will act as if called with prefix arg.
4480 But only if also the variable `org-cycle-global-at-bob' is t."
4481 (interactive "P")
4482 (org-load-modules-maybe)
4483 (let* ((outline-regexp
4484 (if (and (org-mode-p) org-cycle-include-plain-lists)
4485 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4486 outline-regexp))
4487 (bob-special (and org-cycle-global-at-bob (bobp)
4488 (not (looking-at outline-regexp))))
4489 (org-cycle-hook
4490 (if bob-special
4491 (delq 'org-optimize-window-after-visibility-change
4492 (copy-sequence org-cycle-hook))
4493 org-cycle-hook))
4494 (pos (point)))
4496 (if (or bob-special (equal arg '(4)))
4497 ;; special case: use global cycling
4498 (setq arg t))
4500 (cond
4502 ((equal arg '(16))
4503 (org-set-startup-visibility)
4504 (message "Startup visibility, plus VISIBILITY properties"))
4506 ((equal arg '(64))
4507 (show-all)
4508 (message "Entire buffer visible, including drawers"))
4510 ((org-at-table-p 'any)
4511 ;; Enter the table or move to the next field in the table
4512 (or (org-table-recognize-table.el)
4513 (progn
4514 (if arg (org-table-edit-field t)
4515 (org-table-justify-field-maybe)
4516 (call-interactively 'org-table-next-field)))))
4518 ((eq arg t) ;; Global cycling
4520 (cond
4521 ((and (eq last-command this-command)
4522 (eq org-cycle-global-status 'overview))
4523 ;; We just created the overview - now do table of contents
4524 ;; This can be slow in very large buffers, so indicate action
4525 (message "CONTENTS...")
4526 (org-content)
4527 (message "CONTENTS...done")
4528 (setq org-cycle-global-status 'contents)
4529 (run-hook-with-args 'org-cycle-hook 'contents))
4531 ((and (eq last-command this-command)
4532 (eq org-cycle-global-status 'contents))
4533 ;; We just showed the table of contents - now show everything
4534 (show-all)
4535 (message "SHOW ALL")
4536 (setq org-cycle-global-status 'all)
4537 (run-hook-with-args 'org-cycle-hook 'all))
4540 ;; Default action: go to overview
4541 (org-overview)
4542 (message "OVERVIEW")
4543 (setq org-cycle-global-status 'overview)
4544 (run-hook-with-args 'org-cycle-hook 'overview))))
4546 ((and org-drawers org-drawer-regexp
4547 (save-excursion
4548 (beginning-of-line 1)
4549 (looking-at org-drawer-regexp)))
4550 ;; Toggle block visibility
4551 (org-flag-drawer
4552 (not (get-char-property (match-end 0) 'invisible))))
4554 ((integerp arg)
4555 ;; Show-subtree, ARG levels up from here.
4556 (save-excursion
4557 (org-back-to-heading)
4558 (outline-up-heading (if (< arg 0) (- arg)
4559 (- (funcall outline-level) arg)))
4560 (org-show-subtree)))
4562 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4563 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4564 ;; At a heading: rotate between three different views
4565 (org-back-to-heading)
4566 (let ((goal-column 0) eoh eol eos)
4567 ;; First, some boundaries
4568 (save-excursion
4569 (org-back-to-heading)
4570 (save-excursion
4571 (beginning-of-line 2)
4572 (while (and (not (eobp)) ;; this is like `next-line'
4573 (get-char-property (1- (point)) 'invisible))
4574 (beginning-of-line 2)) (setq eol (point)))
4575 (outline-end-of-heading) (setq eoh (point))
4576 (org-end-of-subtree t)
4577 (unless (eobp)
4578 (skip-chars-forward " \t\n")
4579 (beginning-of-line 1) ; in case this is an item
4581 (setq eos (1- (point))))
4582 ;; Find out what to do next and set `this-command'
4583 (cond
4584 ((= eos eoh)
4585 ;; Nothing is hidden behind this heading
4586 (message "EMPTY ENTRY")
4587 (setq org-cycle-subtree-status nil)
4588 (save-excursion
4589 (goto-char eos)
4590 (outline-next-heading)
4591 (if (org-invisible-p) (org-flag-heading nil))))
4592 ((or (>= eol eos)
4593 (not (string-match "\\S-" (buffer-substring eol eos))))
4594 ;; Entire subtree is hidden in one line: open it
4595 (org-show-entry)
4596 (show-children)
4597 (message "CHILDREN")
4598 (save-excursion
4599 (goto-char eos)
4600 (outline-next-heading)
4601 (if (org-invisible-p) (org-flag-heading nil)))
4602 (setq org-cycle-subtree-status 'children)
4603 (run-hook-with-args 'org-cycle-hook 'children))
4604 ((and (eq last-command this-command)
4605 (eq org-cycle-subtree-status 'children))
4606 ;; We just showed the children, now show everything.
4607 (org-show-subtree)
4608 (message "SUBTREE")
4609 (setq org-cycle-subtree-status 'subtree)
4610 (run-hook-with-args 'org-cycle-hook 'subtree))
4612 ;; Default action: hide the subtree.
4613 (hide-subtree)
4614 (message "FOLDED")
4615 (setq org-cycle-subtree-status 'folded)
4616 (run-hook-with-args 'org-cycle-hook 'folded)))))
4618 ;; TAB emulation and template completion
4619 (buffer-read-only (org-back-to-heading))
4621 ((org-try-structure-completion))
4623 ((org-try-cdlatex-tab))
4625 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4626 (or (not (bolp))
4627 (not (looking-at outline-regexp))))
4628 (call-interactively (global-key-binding "\t")))
4630 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4631 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4632 (or (and (eq org-cycle-emulate-tab 'white)
4633 (= (match-end 0) (point-at-eol)))
4634 (and (eq org-cycle-emulate-tab 'whitestart)
4635 (>= (match-end 0) pos))))
4637 (eq org-cycle-emulate-tab t))
4638 (call-interactively (global-key-binding "\t")))
4640 (t (save-excursion
4641 (org-back-to-heading)
4642 (org-cycle))))))
4644 ;;;###autoload
4645 (defun org-global-cycle (&optional arg)
4646 "Cycle the global visibility. For details see `org-cycle'.
4647 With C-u prefix arg, switch to startup visibility.
4648 With a numeric prefix, show all headlines up to that level."
4649 (interactive "P")
4650 (let ((org-cycle-include-plain-lists
4651 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4652 (cond
4653 ((integerp arg)
4654 (show-all)
4655 (hide-sublevels arg)
4656 (setq org-cycle-global-status 'contents))
4657 ((equal arg '(4))
4658 (org-set-startup-visibility)
4659 (message "Startup visibility, plus VISIBILITY properties."))
4661 (org-cycle '(4))))))
4663 (defun org-set-startup-visibility ()
4664 "Set the visibility required by startup options and properties."
4665 (cond
4666 ((eq org-startup-folded t)
4667 (org-cycle '(4)))
4668 ((eq org-startup-folded 'content)
4669 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4670 (org-cycle '(4)) (org-cycle '(4)))))
4671 (org-set-visibility-according-to-property 'no-cleanup)
4672 (org-cycle-hide-archived-subtrees 'all)
4673 (org-cycle-hide-drawers 'all)
4674 (org-cycle-show-empty-lines 'all))
4676 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4677 "Switch subtree visibilities according to :VISIBILITY: property."
4678 (interactive)
4679 (let (org-show-entry-below state)
4680 (save-excursion
4681 (goto-char (point-min))
4682 (while (re-search-forward
4683 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4684 nil t)
4685 (setq state (match-string 1))
4686 (save-excursion
4687 (org-back-to-heading t)
4688 (hide-subtree)
4689 (org-reveal)
4690 (cond
4691 ((equal state '("fold" "folded"))
4692 (hide-subtree))
4693 ((equal state "children")
4694 (org-show-hidden-entry)
4695 (show-children))
4696 ((equal state "content")
4697 (save-excursion
4698 (save-restriction
4699 (org-narrow-to-subtree)
4700 (org-content))))
4701 ((member state '("all" "showall"))
4702 (show-subtree)))))
4703 (unless no-cleanup
4704 (org-cycle-hide-archived-subtrees 'all)
4705 (org-cycle-hide-drawers 'all)
4706 (org-cycle-show-empty-lines 'all)))))
4708 (defun org-overview ()
4709 "Switch to overview mode, showing only top-level headlines.
4710 Really, this shows all headlines with level equal or greater than the level
4711 of the first headline in the buffer. This is important, because if the
4712 first headline is not level one, then (hide-sublevels 1) gives confusing
4713 results."
4714 (interactive)
4715 (let ((level (save-excursion
4716 (goto-char (point-min))
4717 (if (re-search-forward (concat "^" outline-regexp) nil t)
4718 (progn
4719 (goto-char (match-beginning 0))
4720 (funcall outline-level))))))
4721 (and level (hide-sublevels level))))
4723 (defun org-content (&optional arg)
4724 "Show all headlines in the buffer, like a table of contents.
4725 With numerical argument N, show content up to level N."
4726 (interactive "P")
4727 (save-excursion
4728 ;; Visit all headings and show their offspring
4729 (and (integerp arg) (org-overview))
4730 (goto-char (point-max))
4731 (catch 'exit
4732 (while (and (progn (condition-case nil
4733 (outline-previous-visible-heading 1)
4734 (error (goto-char (point-min))))
4736 (looking-at outline-regexp))
4737 (if (integerp arg)
4738 (show-children (1- arg))
4739 (show-branches))
4740 (if (bobp) (throw 'exit nil))))))
4743 (defun org-optimize-window-after-visibility-change (state)
4744 "Adjust the window after a change in outline visibility.
4745 This function is the default value of the hook `org-cycle-hook'."
4746 (when (get-buffer-window (current-buffer))
4747 (cond
4748 ((eq state 'content) nil)
4749 ((eq state 'all) nil)
4750 ((eq state 'folded) nil)
4751 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4752 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4754 (defun org-compact-display-after-subtree-move ()
4755 "Show a compacter version of the tree of the entry's parent."
4756 (save-excursion
4757 (if (org-up-heading-safe)
4758 (progn
4759 (hide-subtree)
4760 (show-entry)
4761 (show-children)
4762 (org-cycle-show-empty-lines 'children)
4763 (org-cycle-hide-drawers 'children))
4764 (org-overview))))
4766 (defun org-cycle-show-empty-lines (state)
4767 "Show empty lines above all visible headlines.
4768 The region to be covered depends on STATE when called through
4769 `org-cycle-hook'. Lisp program can use t for STATE to get the
4770 entire buffer covered. Note that an empty line is only shown if there
4771 are at least `org-cycle-separator-lines' empty lines before the headline."
4772 (when (> org-cycle-separator-lines 0)
4773 (save-excursion
4774 (let* ((n org-cycle-separator-lines)
4775 (re (cond
4776 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4777 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4778 (t (let ((ns (number-to-string (- n 2))))
4779 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4780 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4781 beg end)
4782 (cond
4783 ((memq state '(overview contents t))
4784 (setq beg (point-min) end (point-max)))
4785 ((memq state '(children folded))
4786 (setq beg (point) end (progn (org-end-of-subtree t t)
4787 (beginning-of-line 2)
4788 (point)))))
4789 (when beg
4790 (goto-char beg)
4791 (while (re-search-forward re end t)
4792 (if (not (get-char-property (match-end 1) 'invisible))
4793 (outline-flag-region
4794 (match-beginning 1) (match-end 1) nil)))))))
4795 ;; Never hide empty lines at the end of the file.
4796 (save-excursion
4797 (goto-char (point-max))
4798 (outline-previous-heading)
4799 (outline-end-of-heading)
4800 (if (and (looking-at "[ \t\n]+")
4801 (= (match-end 0) (point-max)))
4802 (outline-flag-region (point) (match-end 0) nil))))
4804 (defun org-show-empty-lines-in-parent ()
4805 "Move to the parent and re-show empty lines before visible headlines."
4806 (save-excursion
4807 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4808 (org-cycle-show-empty-lines context))))
4810 (defun org-cycle-hide-drawers (state)
4811 "Re-hide all drawers after a visibility state change."
4812 (when (and (org-mode-p)
4813 (not (memq state '(overview folded))))
4814 (save-excursion
4815 (let* ((globalp (memq state '(contents all)))
4816 (beg (if globalp (point-min) (point)))
4817 (end (if globalp (point-max) (org-end-of-subtree t))))
4818 (goto-char beg)
4819 (while (re-search-forward org-drawer-regexp end t)
4820 (org-flag-drawer t))))))
4822 (defun org-flag-drawer (flag)
4823 (save-excursion
4824 (beginning-of-line 1)
4825 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4826 (let ((b (match-end 0))
4827 (outline-regexp org-outline-regexp))
4828 (if (re-search-forward
4829 "^[ \t]*:END:"
4830 (save-excursion (outline-next-heading) (point)) t)
4831 (outline-flag-region b (point-at-eol) flag)
4832 (error ":END: line missing"))))))
4834 (defun org-subtree-end-visible-p ()
4835 "Is the end of the current subtree visible?"
4836 (pos-visible-in-window-p
4837 (save-excursion (org-end-of-subtree t) (point))))
4839 (defun org-first-headline-recenter (&optional N)
4840 "Move cursor to the first headline and recenter the headline.
4841 Optional argument N means, put the headline into the Nth line of the window."
4842 (goto-char (point-min))
4843 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4844 (beginning-of-line)
4845 (recenter (prefix-numeric-value N))))
4847 ;;; Org-goto
4849 (defvar org-goto-window-configuration nil)
4850 (defvar org-goto-marker nil)
4851 (defvar org-goto-map
4852 (let ((map (make-sparse-keymap)))
4853 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4854 (while (setq cmd (pop cmds))
4855 (substitute-key-definition cmd cmd map global-map)))
4856 (suppress-keymap map)
4857 (org-defkey map "\C-m" 'org-goto-ret)
4858 (org-defkey map [(return)] 'org-goto-ret)
4859 (org-defkey map [(left)] 'org-goto-left)
4860 (org-defkey map [(right)] 'org-goto-right)
4861 (org-defkey map [(control ?g)] 'org-goto-quit)
4862 (org-defkey map "\C-i" 'org-cycle)
4863 (org-defkey map [(tab)] 'org-cycle)
4864 (org-defkey map [(down)] 'outline-next-visible-heading)
4865 (org-defkey map [(up)] 'outline-previous-visible-heading)
4866 (if org-goto-auto-isearch
4867 (if (fboundp 'define-key-after)
4868 (define-key-after map [t] 'org-goto-local-auto-isearch)
4869 nil)
4870 (org-defkey map "q" 'org-goto-quit)
4871 (org-defkey map "n" 'outline-next-visible-heading)
4872 (org-defkey map "p" 'outline-previous-visible-heading)
4873 (org-defkey map "f" 'outline-forward-same-level)
4874 (org-defkey map "b" 'outline-backward-same-level)
4875 (org-defkey map "u" 'outline-up-heading))
4876 (org-defkey map "/" 'org-occur)
4877 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4878 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4879 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4880 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4881 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4882 map))
4884 (defconst org-goto-help
4885 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4886 RET=jump to location [Q]uit and return to previous location
4887 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4889 (defvar org-goto-start-pos) ; dynamically scoped parameter
4891 ;; FIXME: Docstring doe not mention both interfaces
4892 (defun org-goto (&optional alternative-interface)
4893 "Look up a different location in the current file, keeping current visibility.
4895 When you want look-up or go to a different location in a document, the
4896 fastest way is often to fold the entire buffer and then dive into the tree.
4897 This method has the disadvantage, that the previous location will be folded,
4898 which may not be what you want.
4900 This command works around this by showing a copy of the current buffer
4901 in an indirect buffer, in overview mode. You can dive into the tree in
4902 that copy, use org-occur and incremental search to find a location.
4903 When pressing RET or `Q', the command returns to the original buffer in
4904 which the visibility is still unchanged. After RET is will also jump to
4905 the location selected in the indirect buffer and expose the
4906 the headline hierarchy above."
4907 (interactive "P")
4908 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4909 (org-refile-use-outline-path t)
4910 (interface
4911 (if (not alternative-interface)
4912 org-goto-interface
4913 (if (eq org-goto-interface 'outline)
4914 'outline-path-completion
4915 'outline)))
4916 (org-goto-start-pos (point))
4917 (selected-point
4918 (if (eq interface 'outline)
4919 (car (org-get-location (current-buffer) org-goto-help))
4920 (nth 3 (org-refile-get-location "Goto: ")))))
4921 (if selected-point
4922 (progn
4923 (org-mark-ring-push org-goto-start-pos)
4924 (goto-char selected-point)
4925 (if (or (org-invisible-p) (org-invisible-p2))
4926 (org-show-context 'org-goto)))
4927 (message "Quit"))))
4929 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4930 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4931 (defvar org-goto-local-auto-isearch-map) ; defined below
4933 (defun org-get-location (buf help)
4934 "Let the user select a location in the Org-mode buffer BUF.
4935 This function uses a recursive edit. It returns the selected position
4936 or nil."
4937 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4938 (isearch-hide-immediately nil)
4939 (isearch-search-fun-function
4940 (lambda () 'org-goto-local-search-headings))
4941 (org-goto-selected-point org-goto-exit-command))
4942 (save-excursion
4943 (save-window-excursion
4944 (delete-other-windows)
4945 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4946 (switch-to-buffer
4947 (condition-case nil
4948 (make-indirect-buffer (current-buffer) "*org-goto*")
4949 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4950 (with-output-to-temp-buffer "*Help*"
4951 (princ help))
4952 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4953 (setq buffer-read-only nil)
4954 (let ((org-startup-truncated t)
4955 (org-startup-folded nil)
4956 (org-startup-align-all-tables nil))
4957 (org-mode)
4958 (org-overview))
4959 (setq buffer-read-only t)
4960 (if (and (boundp 'org-goto-start-pos)
4961 (integer-or-marker-p org-goto-start-pos))
4962 (let ((org-show-hierarchy-above t)
4963 (org-show-siblings t)
4964 (org-show-following-heading t))
4965 (goto-char org-goto-start-pos)
4966 (and (org-invisible-p) (org-show-context)))
4967 (goto-char (point-min)))
4968 (let (org-special-ctrl-a/e) (org-beginning-of-line))
4969 (message "Select location and press RET")
4970 (use-local-map org-goto-map)
4971 (recursive-edit)
4973 (kill-buffer "*org-goto*")
4974 (cons org-goto-selected-point org-goto-exit-command)))
4976 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4977 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4978 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4979 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4981 (defun org-goto-local-search-headings (string bound noerror)
4982 "Search and make sure that any matches are in headlines."
4983 (catch 'return
4984 (while (if isearch-forward
4985 (search-forward string bound noerror)
4986 (search-backward string bound noerror))
4987 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4988 (and (member :headline context)
4989 (not (member :tags context))))
4990 (throw 'return (point))))))
4992 (defun org-goto-local-auto-isearch ()
4993 "Start isearch."
4994 (interactive)
4995 (goto-char (point-min))
4996 (let ((keys (this-command-keys)))
4997 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4998 (isearch-mode t)
4999 (isearch-process-search-char (string-to-char keys)))))
5001 (defun org-goto-ret (&optional arg)
5002 "Finish `org-goto' by going to the new location."
5003 (interactive "P")
5004 (setq org-goto-selected-point (point)
5005 org-goto-exit-command 'return)
5006 (throw 'exit nil))
5008 (defun org-goto-left ()
5009 "Finish `org-goto' by going to the new location."
5010 (interactive)
5011 (if (org-on-heading-p)
5012 (progn
5013 (beginning-of-line 1)
5014 (setq org-goto-selected-point (point)
5015 org-goto-exit-command 'left)
5016 (throw 'exit nil))
5017 (error "Not on a heading")))
5019 (defun org-goto-right ()
5020 "Finish `org-goto' by going to the new location."
5021 (interactive)
5022 (if (org-on-heading-p)
5023 (progn
5024 (setq org-goto-selected-point (point)
5025 org-goto-exit-command 'right)
5026 (throw 'exit nil))
5027 (error "Not on a heading")))
5029 (defun org-goto-quit ()
5030 "Finish `org-goto' without cursor motion."
5031 (interactive)
5032 (setq org-goto-selected-point nil)
5033 (setq org-goto-exit-command 'quit)
5034 (throw 'exit nil))
5036 ;;; Indirect buffer display of subtrees
5038 (defvar org-indirect-dedicated-frame nil
5039 "This is the frame being used for indirect tree display.")
5040 (defvar org-last-indirect-buffer nil)
5042 (defun org-tree-to-indirect-buffer (&optional arg)
5043 "Create indirect buffer and narrow it to current subtree.
5044 With numerical prefix ARG, go up to this level and then take that tree.
5045 If ARG is negative, go up that many levels.
5046 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5047 indirect buffer previously made with this command, to avoid proliferation of
5048 indirect buffers. However, when you call the command with a `C-u' prefix, or
5049 when `org-indirect-buffer-display' is `new-frame', the last buffer
5050 is kept so that you can work with several indirect buffers at the same time.
5051 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5052 requests that a new frame be made for the new buffer, so that the dedicated
5053 frame is not changed."
5054 (interactive "P")
5055 (let ((cbuf (current-buffer))
5056 (cwin (selected-window))
5057 (pos (point))
5058 beg end level heading ibuf)
5059 (save-excursion
5060 (org-back-to-heading t)
5061 (when (numberp arg)
5062 (setq level (org-outline-level))
5063 (if (< arg 0) (setq arg (+ level arg)))
5064 (while (> (setq level (org-outline-level)) arg)
5065 (outline-up-heading 1 t)))
5066 (setq beg (point)
5067 heading (org-get-heading))
5068 (org-end-of-subtree t) (setq end (point)))
5069 (if (and (buffer-live-p org-last-indirect-buffer)
5070 (not (eq org-indirect-buffer-display 'new-frame))
5071 (not arg))
5072 (kill-buffer org-last-indirect-buffer))
5073 (setq ibuf (org-get-indirect-buffer cbuf)
5074 org-last-indirect-buffer ibuf)
5075 (cond
5076 ((or (eq org-indirect-buffer-display 'new-frame)
5077 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5078 (select-frame (make-frame))
5079 (delete-other-windows)
5080 (switch-to-buffer ibuf)
5081 (org-set-frame-title heading))
5082 ((eq org-indirect-buffer-display 'dedicated-frame)
5083 (raise-frame
5084 (select-frame (or (and org-indirect-dedicated-frame
5085 (frame-live-p org-indirect-dedicated-frame)
5086 org-indirect-dedicated-frame)
5087 (setq org-indirect-dedicated-frame (make-frame)))))
5088 (delete-other-windows)
5089 (switch-to-buffer ibuf)
5090 (org-set-frame-title (concat "Indirect: " heading)))
5091 ((eq org-indirect-buffer-display 'current-window)
5092 (switch-to-buffer ibuf))
5093 ((eq org-indirect-buffer-display 'other-window)
5094 (pop-to-buffer ibuf))
5095 (t (error "Invalid value.")))
5096 (if (featurep 'xemacs)
5097 (save-excursion (org-mode) (turn-on-font-lock)))
5098 (narrow-to-region beg end)
5099 (show-all)
5100 (goto-char pos)
5101 (and (window-live-p cwin) (select-window cwin))))
5103 (defun org-get-indirect-buffer (&optional buffer)
5104 (setq buffer (or buffer (current-buffer)))
5105 (let ((n 1) (base (buffer-name buffer)) bname)
5106 (while (buffer-live-p
5107 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5108 (setq n (1+ n)))
5109 (condition-case nil
5110 (make-indirect-buffer buffer bname 'clone)
5111 (error (make-indirect-buffer buffer bname)))))
5113 (defun org-set-frame-title (title)
5114 "Set the title of the current frame to the string TITLE."
5115 ;; FIXME: how to name a single frame in XEmacs???
5116 (unless (featurep 'xemacs)
5117 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5119 ;;;; Structure editing
5121 ;;; Inserting headlines
5123 (defun org-previous-line-empty-p ()
5124 (save-excursion
5125 (and (not (bobp))
5126 (or (beginning-of-line 0) t)
5127 (save-match-data
5128 (looking-at "[ \t]*$")))))
5130 (defun org-insert-heading (&optional force-heading)
5131 "Insert a new heading or item with same depth at point.
5132 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5133 If point is at the beginning of a headline, insert a sibling before the
5134 current headline. If point is not at the beginning, do not split the line,
5135 but create the new headline after the current line."
5136 (interactive "P")
5137 (if (= (buffer-size) 0)
5138 (insert "\n* ")
5139 (when (or force-heading (not (org-insert-item)))
5140 (let* ((empty-line-p nil)
5141 (head (save-excursion
5142 (condition-case nil
5143 (progn
5144 (org-back-to-heading)
5145 (setq empty-line-p (org-previous-line-empty-p))
5146 (match-string 0))
5147 (error "*"))))
5148 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5149 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5150 pos hide-previous previous-pos)
5151 (cond
5152 ((and (org-on-heading-p) (bolp)
5153 (or (bobp)
5154 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5155 ;; insert before the current line
5156 (open-line (if blank 2 1)))
5157 ((and (bolp)
5158 (or (bobp)
5159 (save-excursion
5160 (backward-char 1) (not (org-invisible-p)))))
5161 ;; insert right here
5162 nil)
5164 ;; somewhere in the line
5165 (save-excursion
5166 (setq previous-pos (point-at-bol))
5167 (end-of-line)
5168 (setq hide-previous (org-invisible-p)))
5169 (and org-insert-heading-respect-content (org-show-subtree))
5170 (let ((split
5171 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5172 (save-excursion
5173 (let ((p (point)))
5174 (goto-char (point-at-bol))
5175 (and (looking-at org-complex-heading-regexp)
5176 (> p (match-beginning 4)))))))
5177 tags pos)
5178 (cond
5179 (org-insert-heading-respect-content
5180 (org-end-of-subtree nil t)
5181 (or (bolp) (newline))
5182 (or (org-previous-line-empty-p)
5183 (and blank (newline)))
5184 (open-line 1))
5185 ((org-on-heading-p)
5186 (when hide-previous
5187 (show-children)
5188 (org-show-entry))
5189 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5190 (setq tags (and (match-end 2) (match-string 2)))
5191 (and (match-end 1)
5192 (delete-region (match-beginning 1) (match-end 1)))
5193 (setq pos (point-at-bol))
5194 (or split (end-of-line 1))
5195 (delete-horizontal-space)
5196 (newline (if blank 2 1))
5197 (when tags
5198 (save-excursion
5199 (goto-char pos)
5200 (end-of-line 1)
5201 (insert " " tags)
5202 (org-set-tags nil 'align))))
5204 (or split (end-of-line 1))
5205 (newline (if blank 2 1)))))))
5206 (insert head) (just-one-space)
5207 (setq pos (point))
5208 (end-of-line 1)
5209 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5210 (when (and org-insert-heading-respect-content hide-previous)
5211 (save-excursion
5212 (goto-char previous-pos)
5213 (hide-subtree)))
5214 (run-hooks 'org-insert-heading-hook)))))
5216 (defun org-get-heading (&optional no-tags)
5217 "Return the heading of the current entry, without the stars."
5218 (save-excursion
5219 (org-back-to-heading t)
5220 (if (looking-at
5221 (if no-tags
5222 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5223 "\\*+[ \t]+\\([^\r\n]*\\)"))
5224 (match-string 1) "")))
5226 (defun org-heading-components ()
5227 "Return the components of the current heading.
5228 This is a list with the following elements:
5229 - the level as an integer
5230 - the reduced level, different if `org-odd-levels-only' is set.
5231 - the TODO keyword, or nil
5232 - the priority character, like ?A, or nil if no priority is given
5233 - the headline text itself, or the tags string if no headline text
5234 - the tags string, or nil."
5235 (save-excursion
5236 (org-back-to-heading t)
5237 (if (looking-at org-complex-heading-regexp)
5238 (list (length (match-string 1))
5239 (org-reduced-level (length (match-string 1)))
5240 (org-match-string-no-properties 2)
5241 (and (match-end 3) (aref (match-string 3) 2))
5242 (org-match-string-no-properties 4)
5243 (org-match-string-no-properties 5)))))
5245 (defun org-insert-heading-after-current ()
5246 "Insert a new heading with same level as current, after current subtree."
5247 (interactive)
5248 (org-back-to-heading)
5249 (org-insert-heading)
5250 (org-move-subtree-down)
5251 (end-of-line 1))
5253 (defun org-insert-heading-respect-content ()
5254 (interactive)
5255 (let ((org-insert-heading-respect-content t))
5256 (org-insert-heading t)))
5258 (defun org-insert-todo-heading-respect-content (&optional force-state)
5259 (interactive "P")
5260 (let ((org-insert-heading-respect-content t))
5261 (org-insert-todo-heading force-state t)))
5263 (defun org-insert-todo-heading (arg &optional force-heading)
5264 "Insert a new heading with the same level and TODO state as current heading.
5265 If the heading has no TODO state, or if the state is DONE, use the first
5266 state (TODO by default). Also with prefix arg, force first state."
5267 (interactive "P")
5268 (when (or force-heading (not (org-insert-item 'checkbox)))
5269 (org-insert-heading force-heading)
5270 (save-excursion
5271 (org-back-to-heading)
5272 (outline-previous-heading)
5273 (looking-at org-todo-line-regexp))
5274 (let*
5275 ((new-mark-x
5276 (if (or arg
5277 (not (match-beginning 2))
5278 (member (match-string 2) org-done-keywords))
5279 (car org-todo-keywords-1)
5280 (match-string 2)))
5281 (new-mark
5283 (run-hook-with-args-until-success
5284 'org-todo-get-default-hook new-mark-x nil)
5285 new-mark-x)))
5286 (insert new-mark " "))
5287 (when org-provide-todo-statistics
5288 (org-update-parent-todo-statistics))))
5290 (defun org-insert-subheading (arg)
5291 "Insert a new subheading and demote it.
5292 Works for outline headings and for plain lists alike."
5293 (interactive "P")
5294 (org-insert-heading arg)
5295 (cond
5296 ((org-on-heading-p) (org-do-demote))
5297 ((org-at-item-p) (org-indent-item 1))))
5299 (defun org-insert-todo-subheading (arg)
5300 "Insert a new subheading with TODO keyword or checkbox and demote it.
5301 Works for outline headings and for plain lists alike."
5302 (interactive "P")
5303 (org-insert-todo-heading arg)
5304 (cond
5305 ((org-on-heading-p) (org-do-demote))
5306 ((org-at-item-p) (org-indent-item 1))))
5308 ;;; Promotion and Demotion
5310 (defun org-promote-subtree ()
5311 "Promote the entire subtree.
5312 See also `org-promote'."
5313 (interactive)
5314 (save-excursion
5315 (org-map-tree 'org-promote))
5316 (org-fix-position-after-promote))
5318 (defun org-demote-subtree ()
5319 "Demote the entire subtree. See `org-demote'.
5320 See also `org-promote'."
5321 (interactive)
5322 (save-excursion
5323 (org-map-tree 'org-demote))
5324 (org-fix-position-after-promote))
5327 (defun org-do-promote ()
5328 "Promote the current heading higher up the tree.
5329 If the region is active in `transient-mark-mode', promote all headings
5330 in the region."
5331 (interactive)
5332 (save-excursion
5333 (if (org-region-active-p)
5334 (org-map-region 'org-promote (region-beginning) (region-end))
5335 (org-promote)))
5336 (org-fix-position-after-promote))
5338 (defun org-do-demote ()
5339 "Demote the current heading lower down the tree.
5340 If the region is active in `transient-mark-mode', demote all headings
5341 in the region."
5342 (interactive)
5343 (save-excursion
5344 (if (org-region-active-p)
5345 (org-map-region 'org-demote (region-beginning) (region-end))
5346 (org-demote)))
5347 (org-fix-position-after-promote))
5349 (defun org-fix-position-after-promote ()
5350 "Make sure that after pro/demotion cursor position is right."
5351 (let ((pos (point)))
5352 (when (save-excursion
5353 (beginning-of-line 1)
5354 (looking-at org-todo-line-regexp)
5355 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5356 (cond ((eobp) (insert " "))
5357 ((eolp) (insert " "))
5358 ((equal (char-after) ?\ ) (forward-char 1))))))
5360 (defun org-reduced-level (l)
5361 "Compute the effective level of a heading.
5362 This takes into account the setting of `org-odd-levels-only'."
5363 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5365 (defun org-get-valid-level (level &optional change)
5366 "Rectify a level change under the influence of `org-odd-levels-only'
5367 LEVEL is a current level, CHANGE is by how much the level should be
5368 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5369 even level numbers will become the next higher odd number."
5370 (if org-odd-levels-only
5371 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5372 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5373 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5374 (max 1 (+ level (or change 0)))))
5376 (if (boundp 'define-obsolete-function-alias)
5377 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5378 (define-obsolete-function-alias 'org-get-legal-level
5379 'org-get-valid-level)
5380 (define-obsolete-function-alias 'org-get-legal-level
5381 'org-get-valid-level "23.1")))
5383 (defun org-promote ()
5384 "Promote the current heading higher up the tree.
5385 If the region is active in `transient-mark-mode', promote all headings
5386 in the region."
5387 (org-back-to-heading t)
5388 (let* ((level (save-match-data (funcall outline-level)))
5389 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5390 (diff (abs (- level (length up-head) -1))))
5391 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5392 (replace-match up-head nil t)
5393 ;; Fixup tag positioning
5394 (and org-auto-align-tags (org-set-tags nil t))
5395 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5397 (defun org-demote ()
5398 "Demote the current heading lower down the tree.
5399 If the region is active in `transient-mark-mode', demote all headings
5400 in the region."
5401 (org-back-to-heading t)
5402 (let* ((level (save-match-data (funcall outline-level)))
5403 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5404 (diff (abs (- level (length down-head) -1))))
5405 (replace-match down-head nil t)
5406 ;; Fixup tag positioning
5407 (and org-auto-align-tags (org-set-tags nil t))
5408 (if org-adapt-indentation (org-fixup-indentation diff))))
5410 (defun org-map-tree (fun)
5411 "Call FUN for every heading underneath the current one."
5412 (org-back-to-heading)
5413 (let ((level (funcall outline-level)))
5414 (save-excursion
5415 (funcall fun)
5416 (while (and (progn
5417 (outline-next-heading)
5418 (> (funcall outline-level) level))
5419 (not (eobp)))
5420 (funcall fun)))))
5422 (defun org-map-region (fun beg end)
5423 "Call FUN for every heading between BEG and END."
5424 (let ((org-ignore-region t))
5425 (save-excursion
5426 (setq end (copy-marker end))
5427 (goto-char beg)
5428 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5429 (< (point) end))
5430 (funcall fun))
5431 (while (and (progn
5432 (outline-next-heading)
5433 (< (point) end))
5434 (not (eobp)))
5435 (funcall fun)))))
5437 (defun org-fixup-indentation (diff)
5438 "Change the indentation in the current entry by DIFF
5439 However, if any line in the current entry has no indentation, or if it
5440 would end up with no indentation after the change, nothing at all is done."
5441 (save-excursion
5442 (let ((end (save-excursion (outline-next-heading)
5443 (point-marker)))
5444 (prohibit (if (> diff 0)
5445 "^\\S-"
5446 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5447 col)
5448 (unless (save-excursion (end-of-line 1)
5449 (re-search-forward prohibit end t))
5450 (while (and (< (point) end)
5451 (re-search-forward "^[ \t]+" end t))
5452 (goto-char (match-end 0))
5453 (setq col (current-column))
5454 (if (< diff 0) (replace-match ""))
5455 (org-indent-to-column (+ diff col))))
5456 (move-marker end nil))))
5458 (defun org-convert-to-odd-levels ()
5459 "Convert an org-mode file with all levels allowed to one with odd levels.
5460 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5461 level 5 etc."
5462 (interactive)
5463 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5464 (let ((org-odd-levels-only nil) n)
5465 (save-excursion
5466 (goto-char (point-min))
5467 (while (re-search-forward "^\\*\\*+ " nil t)
5468 (setq n (- (length (match-string 0)) 2))
5469 (while (>= (setq n (1- n)) 0)
5470 (org-demote))
5471 (end-of-line 1))))))
5474 (defun org-convert-to-oddeven-levels ()
5475 "Convert an org-mode file with only odd levels to one with odd and even levels.
5476 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5477 section with an even level, conversion would destroy the structure of the file. An error
5478 is signaled in this case."
5479 (interactive)
5480 (goto-char (point-min))
5481 ;; First check if there are no even levels
5482 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5483 (org-show-context t)
5484 (error "Not all levels are odd in this file. Conversion not possible."))
5485 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5486 (let ((org-odd-levels-only nil) n)
5487 (save-excursion
5488 (goto-char (point-min))
5489 (while (re-search-forward "^\\*\\*+ " nil t)
5490 (setq n (/ (1- (length (match-string 0))) 2))
5491 (while (>= (setq n (1- n)) 0)
5492 (org-promote))
5493 (end-of-line 1))))))
5495 (defun org-tr-level (n)
5496 "Make N odd if required."
5497 (if org-odd-levels-only (1+ (/ n 2)) n))
5499 ;;; Vertical tree motion, cutting and pasting of subtrees
5501 (defun org-move-subtree-up (&optional arg)
5502 "Move the current subtree up past ARG headlines of the same level."
5503 (interactive "p")
5504 (org-move-subtree-down (- (prefix-numeric-value arg))))
5506 (defun org-move-subtree-down (&optional arg)
5507 "Move the current subtree down past ARG headlines of the same level."
5508 (interactive "p")
5509 (setq arg (prefix-numeric-value arg))
5510 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5511 'outline-get-last-sibling))
5512 (ins-point (make-marker))
5513 (cnt (abs arg))
5514 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5515 ;; Select the tree
5516 (org-back-to-heading)
5517 (setq beg0 (point))
5518 (save-excursion
5519 (setq ne-beg (org-back-over-empty-lines))
5520 (setq beg (point)))
5521 (save-match-data
5522 (save-excursion (outline-end-of-heading)
5523 (setq folded (org-invisible-p)))
5524 (outline-end-of-subtree))
5525 (outline-next-heading)
5526 (setq ne-end (org-back-over-empty-lines))
5527 (setq end (point))
5528 (goto-char beg0)
5529 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5530 ;; include less whitespace
5531 (save-excursion
5532 (goto-char beg)
5533 (forward-line (- ne-beg ne-end))
5534 (setq beg (point))))
5535 ;; Find insertion point, with error handling
5536 (while (> cnt 0)
5537 (or (and (funcall movfunc) (looking-at outline-regexp))
5538 (progn (goto-char beg0)
5539 (error "Cannot move past superior level or buffer limit")))
5540 (setq cnt (1- cnt)))
5541 (if (> arg 0)
5542 ;; Moving forward - still need to move over subtree
5543 (progn (org-end-of-subtree t t)
5544 (save-excursion
5545 (org-back-over-empty-lines)
5546 (or (bolp) (newline)))))
5547 (setq ne-ins (org-back-over-empty-lines))
5548 (move-marker ins-point (point))
5549 (setq txt (buffer-substring beg end))
5550 (org-save-markers-in-region beg end)
5551 (delete-region beg end)
5552 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5553 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5554 (let ((bbb (point)))
5555 (insert-before-markers txt)
5556 (org-reinstall-markers-in-region bbb)
5557 (move-marker ins-point bbb))
5558 (or (bolp) (insert "\n"))
5559 (setq ins-end (point))
5560 (goto-char ins-point)
5561 (org-skip-whitespace)
5562 (when (and (< arg 0)
5563 (org-first-sibling-p)
5564 (> ne-ins ne-beg))
5565 ;; Move whitespace back to beginning
5566 (save-excursion
5567 (goto-char ins-end)
5568 (let ((kill-whole-line t))
5569 (kill-line (- ne-ins ne-beg)) (point)))
5570 (insert (make-string (- ne-ins ne-beg) ?\n)))
5571 (move-marker ins-point nil)
5572 (org-compact-display-after-subtree-move)
5573 (org-show-empty-lines-in-parent)
5574 (unless folded
5575 (org-show-entry)
5576 (show-children)
5577 (org-cycle-hide-drawers 'children))))
5579 (defvar org-subtree-clip ""
5580 "Clipboard for cut and paste of subtrees.
5581 This is actually only a copy of the kill, because we use the normal kill
5582 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5584 (defvar org-subtree-clip-folded nil
5585 "Was the last copied subtree folded?
5586 This is used to fold the tree back after pasting.")
5588 (defun org-cut-subtree (&optional n)
5589 "Cut the current subtree into the clipboard.
5590 With prefix arg N, cut this many sequential subtrees.
5591 This is a short-hand for marking the subtree and then cutting it."
5592 (interactive "p")
5593 (org-copy-subtree n 'cut))
5595 (defun org-copy-subtree (&optional n cut force-store-markers)
5596 "Cut the current subtree into the clipboard.
5597 With prefix arg N, cut this many sequential subtrees.
5598 This is a short-hand for marking the subtree and then copying it.
5599 If CUT is non-nil, actually cut the subtree.
5600 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5601 of some markers in the region, even if CUT is non-nil. This is
5602 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5603 (interactive "p")
5604 (let (beg end folded (beg0 (point)))
5605 (if (interactive-p)
5606 (org-back-to-heading nil) ; take what looks like a subtree
5607 (org-back-to-heading t)) ; take what is really there
5608 (org-back-over-empty-lines)
5609 (setq beg (point))
5610 (skip-chars-forward " \t\r\n")
5611 (save-match-data
5612 (save-excursion (outline-end-of-heading)
5613 (setq folded (org-invisible-p)))
5614 (condition-case nil
5615 (outline-forward-same-level (1- n))
5616 (error nil))
5617 (org-end-of-subtree t t))
5618 (org-back-over-empty-lines)
5619 (setq end (point))
5620 (goto-char beg0)
5621 (when (> end beg)
5622 (setq org-subtree-clip-folded folded)
5623 (when (or cut force-store-markers)
5624 (org-save-markers-in-region beg end))
5625 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5626 (setq org-subtree-clip (current-kill 0))
5627 (message "%s: Subtree(s) with %d characters"
5628 (if cut "Cut" "Copied")
5629 (length org-subtree-clip)))))
5631 (defun org-paste-subtree (&optional level tree for-yank)
5632 "Paste the clipboard as a subtree, with modification of headline level.
5633 The entire subtree is promoted or demoted in order to match a new headline
5634 level.
5636 If the cursor is at the beginning of a headline, the same level as
5637 that headline is used to paste the tree
5639 If not, the new level is derived from the *visible* headings
5640 before and after the insertion point, and taken to be the inferior headline
5641 level of the two. So if the previous visible heading is level 3 and the
5642 next is level 4 (or vice versa), level 4 will be used for insertion.
5643 This makes sure that the subtree remains an independent subtree and does
5644 not swallow low level entries.
5646 You can also force a different level, either by using a numeric prefix
5647 argument, or by inserting the heading marker by hand. For example, if the
5648 cursor is after \"*****\", then the tree will be shifted to level 5.
5650 If optional TREE is given, use this text instead of the kill ring.
5652 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5653 move back over whitespace before inserting, and move point to the end of
5654 the inserted text when done."
5655 (interactive "P")
5656 (unless (org-kill-is-subtree-p tree)
5657 (error "%s"
5658 (substitute-command-keys
5659 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5660 (let* ((visp (not (org-invisible-p)))
5661 (txt (or tree (and kill-ring (current-kill 0))))
5662 (^re (concat "^\\(" outline-regexp "\\)"))
5663 (re (concat "\\(" outline-regexp "\\)"))
5664 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5666 (old-level (if (string-match ^re txt)
5667 (- (match-end 0) (match-beginning 0) 1)
5668 -1))
5669 (force-level (cond (level (prefix-numeric-value level))
5670 ((and (looking-at "[ \t]*$")
5671 (string-match
5672 ^re_ (buffer-substring
5673 (point-at-bol) (point))))
5674 (- (match-end 1) (match-beginning 1)))
5675 ((and (bolp)
5676 (looking-at org-outline-regexp))
5677 (- (match-end 0) (point) 1))
5678 (t nil)))
5679 (previous-level (save-excursion
5680 (condition-case nil
5681 (progn
5682 (outline-previous-visible-heading 1)
5683 (if (looking-at re)
5684 (- (match-end 0) (match-beginning 0) 1)
5686 (error 1))))
5687 (next-level (save-excursion
5688 (condition-case nil
5689 (progn
5690 (or (looking-at outline-regexp)
5691 (outline-next-visible-heading 1))
5692 (if (looking-at re)
5693 (- (match-end 0) (match-beginning 0) 1)
5695 (error 1))))
5696 (new-level (or force-level (max previous-level next-level)))
5697 (shift (if (or (= old-level -1)
5698 (= new-level -1)
5699 (= old-level new-level))
5701 (- new-level old-level)))
5702 (delta (if (> shift 0) -1 1))
5703 (func (if (> shift 0) 'org-demote 'org-promote))
5704 (org-odd-levels-only nil)
5705 beg end newend)
5706 ;; Remove the forced level indicator
5707 (if force-level
5708 (delete-region (point-at-bol) (point)))
5709 ;; Paste
5710 (beginning-of-line 1)
5711 (unless for-yank (org-back-over-empty-lines))
5712 (setq beg (point))
5713 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5714 (insert-before-markers txt)
5715 (unless (string-match "\n\\'" txt) (insert "\n"))
5716 (setq newend (point))
5717 (org-reinstall-markers-in-region beg)
5718 (setq end (point))
5719 (goto-char beg)
5720 (skip-chars-forward " \t\n\r")
5721 (setq beg (point))
5722 (if (and (org-invisible-p) visp)
5723 (save-excursion (outline-show-heading)))
5724 ;; Shift if necessary
5725 (unless (= shift 0)
5726 (save-restriction
5727 (narrow-to-region beg end)
5728 (while (not (= shift 0))
5729 (org-map-region func (point-min) (point-max))
5730 (setq shift (+ delta shift)))
5731 (goto-char (point-min))
5732 (setq newend (point-max))))
5733 (when (or (interactive-p) for-yank)
5734 (message "Clipboard pasted as level %d subtree" new-level))
5735 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5736 kill-ring
5737 (eq org-subtree-clip (current-kill 0))
5738 org-subtree-clip-folded)
5739 ;; The tree was folded before it was killed/copied
5740 (hide-subtree))
5741 (and for-yank (goto-char newend))))
5743 (defun org-kill-is-subtree-p (&optional txt)
5744 "Check if the current kill is an outline subtree, or a set of trees.
5745 Returns nil if kill does not start with a headline, or if the first
5746 headline level is not the largest headline level in the tree.
5747 So this will actually accept several entries of equal levels as well,
5748 which is OK for `org-paste-subtree'.
5749 If optional TXT is given, check this string instead of the current kill."
5750 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5751 (start-level (and kill
5752 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5753 org-outline-regexp "\\)")
5754 kill)
5755 (- (match-end 2) (match-beginning 2) 1)))
5756 (re (concat "^" org-outline-regexp))
5757 (start (1+ (or (match-beginning 2) -1))))
5758 (if (not start-level)
5759 (progn
5760 nil) ;; does not even start with a heading
5761 (catch 'exit
5762 (while (setq start (string-match re kill (1+ start)))
5763 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5764 (throw 'exit nil)))
5765 t))))
5767 (defvar org-markers-to-move nil
5768 "Markers that should be moved with a cut-and-paste operation.
5769 Those markers are stored together with their positions relative to
5770 the start of the region.")
5772 (defun org-save-markers-in-region (beg end)
5773 "Check markers in region.
5774 If these markers are between BEG and END, record their position relative
5775 to BEG, so that after moving the block of text, we can put the markers back
5776 into place.
5777 This function gets called just before an entry or tree gets cut from the
5778 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5779 called immediately, to move the markers with the entries."
5780 (setq org-markers-to-move nil)
5781 (when (featurep 'org-clock)
5782 (org-clock-save-markers-for-cut-and-paste beg end))
5783 (when (featurep 'org-agenda)
5784 (org-agenda-save-markers-for-cut-and-paste beg end)))
5786 (defun org-check-and-save-marker (marker beg end)
5787 "Check if MARKER is between BEG and END.
5788 If yes, remember the marker and the distance to BEG."
5789 (when (and (marker-buffer marker)
5790 (equal (marker-buffer marker) (current-buffer)))
5791 (if (and (>= marker beg) (< marker end))
5792 (push (cons marker (- marker beg)) org-markers-to-move))))
5794 (defun org-reinstall-markers-in-region (beg)
5795 "Move all remembered markers to their position relative to BEG."
5796 (mapc (lambda (x)
5797 (move-marker (car x) (+ beg (cdr x))))
5798 org-markers-to-move)
5799 (setq org-markers-to-move nil))
5801 (defun org-narrow-to-subtree ()
5802 "Narrow buffer to the current subtree."
5803 (interactive)
5804 (save-excursion
5805 (save-match-data
5806 (narrow-to-region
5807 (progn (org-back-to-heading) (point))
5808 (progn (org-end-of-subtree t) (point))))))
5811 ;;; Outline Sorting
5813 (defun org-sort (with-case)
5814 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5815 Optional argument WITH-CASE means sort case-sensitively.
5816 With a double prefix argument, also remove duplicate entries."
5817 (interactive "P")
5818 (if (org-at-table-p)
5819 (org-call-with-arg 'org-table-sort-lines with-case)
5820 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5822 (defun org-sort-remove-invisible (s)
5823 (remove-text-properties 0 (length s) org-rm-props s)
5824 (while (string-match org-bracket-link-regexp s)
5825 (setq s (replace-match (if (match-end 2)
5826 (match-string 3 s)
5827 (match-string 1 s)) t t s)))
5830 (defvar org-priority-regexp) ; defined later in the file
5832 (defun org-sort-entries-or-items
5833 (&optional with-case sorting-type getkey-func compare-func property)
5834 "Sort entries on a certain level of an outline tree.
5835 If there is an active region, the entries in the region are sorted.
5836 Else, if the cursor is before the first entry, sort the top-level items.
5837 Else, the children of the entry at point are sorted.
5839 Sorting can be alphabetically, numerically, and by date/time as given by
5840 the first time stamp in the entry. The command prompts for the sorting
5841 type unless it has been given to the function through the SORTING-TYPE
5842 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5843 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5844 called with point at the beginning of the record. It must return either
5845 a string or a number that should serve as the sorting key for that record.
5847 Comparing entries ignores case by default. However, with an optional argument
5848 WITH-CASE, the sorting considers case as well."
5849 (interactive "P")
5850 (let ((case-func (if with-case 'identity 'downcase))
5851 start beg end stars re re2
5852 txt what tmp plain-list-p)
5853 ;; Find beginning and end of region to sort
5854 (cond
5855 ((org-region-active-p)
5856 ;; we will sort the region
5857 (setq end (region-end)
5858 what "region")
5859 (goto-char (region-beginning))
5860 (if (not (org-on-heading-p)) (outline-next-heading))
5861 (setq start (point)))
5862 ((org-at-item-p)
5863 ;; we will sort this plain list
5864 (org-beginning-of-item-list) (setq start (point))
5865 (org-end-of-item-list) (setq end (point))
5866 (goto-char start)
5867 (setq plain-list-p t
5868 what "plain list"))
5869 ((or (org-on-heading-p)
5870 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5871 ;; we will sort the children of the current headline
5872 (org-back-to-heading)
5873 (setq start (point)
5874 end (progn (org-end-of-subtree t t)
5875 (org-back-over-empty-lines)
5876 (point))
5877 what "children")
5878 (goto-char start)
5879 (show-subtree)
5880 (outline-next-heading))
5882 ;; we will sort the top-level entries in this file
5883 (goto-char (point-min))
5884 (or (org-on-heading-p) (outline-next-heading))
5885 (setq start (point) end (point-max) what "top-level")
5886 (goto-char start)
5887 (show-all)))
5889 (setq beg (point))
5890 (if (>= beg end) (error "Nothing to sort"))
5892 (unless plain-list-p
5893 (looking-at "\\(\\*+\\)")
5894 (setq stars (match-string 1)
5895 re (concat "^" (regexp-quote stars) " +")
5896 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5897 txt (buffer-substring beg end))
5898 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5899 (if (and (not (equal stars "*")) (string-match re2 txt))
5900 (error "Region to sort contains a level above the first entry")))
5902 (unless sorting-type
5903 (message
5904 (if plain-list-p
5905 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5906 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty todo[o]rder [f]unc A/N/T/P/O/F means reversed:")
5907 what)
5908 (setq sorting-type (read-char-exclusive))
5910 (and (= (downcase sorting-type) ?f)
5911 (setq getkey-func
5912 (org-ido-completing-read "Sort using function: "
5913 obarray 'fboundp t nil nil))
5914 (setq getkey-func (intern getkey-func)))
5916 (and (= (downcase sorting-type) ?r)
5917 (setq property
5918 (org-ido-completing-read "Property: "
5919 (mapcar 'list (org-buffer-property-keys t))
5920 nil t))))
5922 (message "Sorting entries...")
5924 (save-restriction
5925 (narrow-to-region start end)
5927 (let ((dcst (downcase sorting-type))
5928 (now (current-time)))
5929 (sort-subr
5930 (/= dcst sorting-type)
5931 ;; This function moves to the beginning character of the "record" to
5932 ;; be sorted.
5933 (if plain-list-p
5934 (lambda nil
5935 (if (org-at-item-p) t (goto-char (point-max))))
5936 (lambda nil
5937 (if (re-search-forward re nil t)
5938 (goto-char (match-beginning 0))
5939 (goto-char (point-max)))))
5940 ;; This function moves to the last character of the "record" being
5941 ;; sorted.
5942 (if plain-list-p
5943 'org-end-of-item
5944 (lambda nil
5945 (save-match-data
5946 (condition-case nil
5947 (outline-forward-same-level 1)
5948 (error
5949 (goto-char (point-max)))))))
5951 ;; This function returns the value that gets sorted against.
5952 (if plain-list-p
5953 (lambda nil
5954 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5955 (cond
5956 ((= dcst ?n)
5957 (string-to-number (buffer-substring (match-end 0)
5958 (point-at-eol))))
5959 ((= dcst ?a)
5960 (buffer-substring (match-end 0) (point-at-eol)))
5961 ((= dcst ?t)
5962 (if (re-search-forward org-ts-regexp
5963 (point-at-eol) t)
5964 (org-time-string-to-time (match-string 0))
5965 now))
5966 ((= dcst ?f)
5967 (if getkey-func
5968 (progn
5969 (setq tmp (funcall getkey-func))
5970 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5971 tmp)
5972 (error "Invalid key function `%s'" getkey-func)))
5973 (t (error "Invalid sorting type `%c'" sorting-type)))))
5974 (lambda nil
5975 (cond
5976 ((= dcst ?n)
5977 (if (looking-at org-complex-heading-regexp)
5978 (string-to-number (match-string 4))
5979 nil))
5980 ((= dcst ?a)
5981 (if (looking-at org-complex-heading-regexp)
5982 (funcall case-func (match-string 4))
5983 nil))
5984 ((= dcst ?t)
5985 (if (re-search-forward org-ts-regexp
5986 (save-excursion
5987 (forward-line 2)
5988 (point)) t)
5989 (org-time-string-to-time (match-string 0))
5990 now))
5991 ((= dcst ?p)
5992 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5993 (string-to-char (match-string 2))
5994 org-default-priority))
5995 ((= dcst ?r)
5996 (or (org-entry-get nil property) ""))
5997 ((= dcst ?o)
5998 (if (looking-at org-complex-heading-regexp)
5999 (- 9999 (length (member (match-string 2)
6000 org-todo-keywords-1)))))
6001 ((= dcst ?f)
6002 (if getkey-func
6003 (progn
6004 (setq tmp (funcall getkey-func))
6005 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6006 tmp)
6007 (error "Invalid key function `%s'" getkey-func)))
6008 (t (error "Invalid sorting type `%c'" sorting-type)))))
6010 (cond
6011 ((= dcst ?a) 'string<)
6012 ((= dcst ?t) 'time-less-p)
6013 ((= dcst ?f) compare-func)
6014 (t nil)))))
6015 (message "Sorting entries...done")))
6017 (defun org-do-sort (table what &optional with-case sorting-type)
6018 "Sort TABLE of WHAT according to SORTING-TYPE.
6019 The user will be prompted for the SORTING-TYPE if the call to this
6020 function does not specify it. WHAT is only for the prompt, to indicate
6021 what is being sorted. The sorting key will be extracted from
6022 the car of the elements of the table.
6023 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6024 (unless sorting-type
6025 (message
6026 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6027 what)
6028 (setq sorting-type (read-char-exclusive)))
6029 (let ((dcst (downcase sorting-type))
6030 extractfun comparefun)
6031 ;; Define the appropriate functions
6032 (cond
6033 ((= dcst ?n)
6034 (setq extractfun 'string-to-number
6035 comparefun (if (= dcst sorting-type) '< '>)))
6036 ((= dcst ?a)
6037 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6038 (lambda(x) (downcase (org-sort-remove-invisible x))))
6039 comparefun (if (= dcst sorting-type)
6040 'string<
6041 (lambda (a b) (and (not (string< a b))
6042 (not (string= a b)))))))
6043 ((= dcst ?t)
6044 (setq extractfun
6045 (lambda (x)
6046 (if (or (string-match org-ts-regexp x)
6047 (string-match org-ts-regexp-both x))
6048 (time-to-seconds
6049 (org-time-string-to-time (match-string 0 x)))
6051 comparefun (if (= dcst sorting-type) '< '>)))
6052 (t (error "Invalid sorting type `%c'" sorting-type)))
6054 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6055 table)
6056 (lambda (a b) (funcall comparefun (car a) (car b))))))
6058 ;;; Editing source examples
6060 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6061 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6062 (defvar org-edit-src-force-single-line nil)
6063 (defvar org-edit-src-from-org-mode nil)
6064 (defvar org-edit-src-picture nil)
6066 (define-minor-mode org-exit-edit-mode
6067 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6069 (defun org-edit-src-code ()
6070 "Edit the source code example at point.
6071 An indirect buffer is created, and that buffer is then narrowed to the
6072 example at point and switched to the correct language mode. When done,
6073 exit by killing the buffer with \\[org-edit-src-exit]."
6074 (interactive)
6075 (let ((line (org-current-line))
6076 (case-fold-search t)
6077 (msg (substitute-command-keys
6078 "Edit, then exit with C-c ' (C-c and single quote)"))
6079 (info (org-edit-src-find-region-and-lang))
6080 (org-mode-p (eq major-mode 'org-mode))
6081 beg end lang lang-f single lfmt)
6082 (if (not info)
6084 (setq beg (nth 0 info)
6085 end (nth 1 info)
6086 lang (nth 2 info)
6087 single (nth 3 info)
6088 lfmt (nth 4 info)
6089 lang-f (intern (concat lang "-mode")))
6090 (unless (functionp lang-f)
6091 (error "No such language mode: %s" lang-f))
6092 (goto-line line)
6093 (if (get-buffer "*Org Edit Src Example*")
6094 (kill-buffer "*Org Edit Src Example*"))
6095 (switch-to-buffer (make-indirect-buffer (current-buffer)
6096 "*Org Edit Src Example*"))
6097 (narrow-to-region beg end)
6098 (remove-text-properties beg end '(display nil invisible nil
6099 intangible nil))
6100 (let ((org-inhibit-startup t))
6101 (funcall lang-f))
6102 (set (make-local-variable 'org-edit-src-force-single-line) single)
6103 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6104 (when lfmt
6105 (set (make-local-variable 'org-coderef-label-format) lfmt))
6106 (when org-mode-p
6107 (goto-char (point-min))
6108 (while (re-search-forward "^," nil t)
6109 (replace-match "")))
6110 (goto-line line)
6111 (org-exit-edit-mode)
6112 (org-set-local 'header-line-format msg)
6113 (message "%s" msg)
6114 t)))
6116 (defun org-edit-fixed-width-region ()
6117 "Edit the fixed-width ascii drawing at point.
6118 This must be a region where each line starts with a colon followed by
6119 a space character.
6120 An indirect buffer is created, and that buffer is then narrowed to the
6121 example at point and switched to artist-mode. When done,
6122 exit by killing the buffer with \\[org-edit-src-exit]."
6123 (interactive)
6124 (let ((line (org-current-line))
6125 (case-fold-search t)
6126 (msg (substitute-command-keys
6127 "Edit, then exit with C-c ' (C-c and single quote)"))
6128 (org-mode-p (eq major-mode 'org-mode))
6129 beg end)
6130 (beginning-of-line 1)
6131 (if (looking-at "[ \t]*[^:\n \t]")
6133 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6134 (setq beg (point) end beg)
6135 (save-excursion
6136 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6137 (setq beg (point-at-bol 2))
6138 (setq beg (point))))
6139 (save-excursion
6140 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6141 (setq end (1- (match-beginning 0)))
6142 (setq end (point))))
6143 (goto-line line))
6144 (if (get-buffer "*Org Edit Picture*")
6145 (kill-buffer "*Org Edit Picture*"))
6146 (switch-to-buffer (make-indirect-buffer (current-buffer)
6147 "*Org Edit Picture*"))
6148 (narrow-to-region beg end)
6149 (remove-text-properties beg end '(display nil invisible nil
6150 intangible nil))
6151 (when (fboundp 'font-lock-unfontify-region)
6152 (font-lock-unfontify-region (point-min) (point-max)))
6153 (cond
6154 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6155 (fundamental-mode)
6156 (artist-mode 1))
6157 (t (funcall org-edit-fixed-width-region-mode)))
6158 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6159 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6160 (set (make-local-variable 'org-edit-src-picture) t)
6161 (goto-char (point-min))
6162 (while (re-search-forward "^[ \t]*: ?" nil t)
6163 (replace-match ""))
6164 (goto-line line)
6165 (org-exit-edit-mode)
6166 (org-set-local 'header-line-format msg)
6167 (message "%s" msg)
6168 t)))
6171 (defun org-edit-src-find-region-and-lang ()
6172 "Find the region and language for a local edit.
6173 Return a list with beginning and end of the region, a string representing
6174 the language, a switch telling of the content should be in a single line."
6175 (let ((re-list
6176 (append
6177 org-edit-src-region-extra
6179 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6180 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6181 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6182 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6183 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6184 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6185 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6186 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6187 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6188 ("^#\\+html:" "\n" "html" single-line)
6189 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6190 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6191 ("^#\\+latex:" "\n" "latex" single-line)
6192 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6193 ("^#\\+ascii:" "\n" "ascii" single-line)
6195 (pos (point))
6196 re1 re2 single beg end lang lfmt match-re1)
6197 (catch 'exit
6198 (while (setq entry (pop re-list))
6199 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6200 single (nth 3 entry))
6201 (save-excursion
6202 (if (or (looking-at re1)
6203 (re-search-backward re1 nil t))
6204 (progn
6205 (setq match-re1 (match-string 0))
6206 (setq beg (match-end 0)
6207 lang (org-edit-src-get-lang lang)
6208 lfmt (org-edit-src-get-label-format match-re1))
6209 (if (and (re-search-forward re2 nil t)
6210 (>= (match-end 0) pos))
6211 (throw 'exit (list beg (match-beginning 0)
6212 lang single lfmt))))
6213 (if (or (looking-at re2)
6214 (re-search-forward re2 nil t))
6215 (progn
6216 (setq end (match-beginning 0))
6217 (if (and (re-search-backward re1 nil t)
6218 (<= (match-beginning 0) pos))
6219 (progn
6220 (setq lfmt (org-edit-src-get-label-format
6221 (match-string 0)))
6222 (throw 'exit
6223 (list (match-end 0) end
6224 (org-edit-src-get-lang lang)
6225 single lfmt))))))))))))
6227 (defun org-edit-src-get-lang (lang)
6228 "Extract the src language."
6229 (let ((m (match-string 0)))
6230 (cond
6231 ((stringp lang) lang)
6232 ((integerp lang) (match-string lang))
6233 ((and (eq lang 'lang)
6234 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6235 (match-string 1 m))
6236 ((and (eq lang 'style)
6237 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6238 (match-string 1 m))
6239 (t "fundamental"))))
6241 (defun org-edit-src-get-label-format (s)
6242 "Extract the label format."
6243 (save-match-data
6244 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6245 (match-string 1 s))))
6247 (defun org-edit-src-exit ()
6248 "Exit special edit and protect problematic lines."
6249 (interactive)
6250 (unless (buffer-base-buffer (current-buffer))
6251 (error "This is not an indirect buffer, something is wrong..."))
6252 (unless (> (point-min) 1)
6253 (error "This buffer is not narrowed, something is wrong..."))
6254 (goto-char (point-min))
6255 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6256 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6257 (when (org-bound-and-true-p org-edit-src-force-single-line)
6258 (goto-char (point-min))
6259 (while (re-search-forward "\n" nil t)
6260 (replace-match " "))
6261 (goto-char (point-min))
6262 (if (looking-at "\\s-*") (replace-match " "))
6263 (if (re-search-forward "\\s-+\\'" nil t)
6264 (replace-match "")))
6265 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6266 (goto-char (point-min))
6267 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6268 (replace-match ",\\1"))
6269 (when font-lock-mode
6270 (font-lock-unfontify-region (point-min) (point-max)))
6271 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6272 (when (org-bound-and-true-p org-edit-src-picture)
6273 (untabify (point-min) (point-max))
6274 (goto-char (point-min))
6275 (while (re-search-forward "^" nil t)
6276 (replace-match ": "))
6277 (when font-lock-mode
6278 (font-lock-unfontify-region (point-min) (point-max)))
6279 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6280 (kill-buffer (current-buffer))
6281 (and (org-mode-p) (org-restart-font-lock)))
6284 ;;; The orgstruct minor mode
6286 ;; Define a minor mode which can be used in other modes in order to
6287 ;; integrate the org-mode structure editing commands.
6289 ;; This is really a hack, because the org-mode structure commands use
6290 ;; keys which normally belong to the major mode. Here is how it
6291 ;; works: The minor mode defines all the keys necessary to operate the
6292 ;; structure commands, but wraps the commands into a function which
6293 ;; tests if the cursor is currently at a headline or a plain list
6294 ;; item. If that is the case, the structure command is used,
6295 ;; temporarily setting many Org-mode variables like regular
6296 ;; expressions for filling etc. However, when any of those keys is
6297 ;; used at a different location, function uses `key-binding' to look
6298 ;; up if the key has an associated command in another currently active
6299 ;; keymap (minor modes, major mode, global), and executes that
6300 ;; command. There might be problems if any of the keys is otherwise
6301 ;; used as a prefix key.
6303 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6304 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6305 ;; addresses this by checking explicitly for both bindings.
6307 (defvar orgstruct-mode-map (make-sparse-keymap)
6308 "Keymap for the minor `orgstruct-mode'.")
6310 (defvar org-local-vars nil
6311 "List of local variables, for use by `orgstruct-mode'")
6313 ;;;###autoload
6314 (define-minor-mode orgstruct-mode
6315 "Toggle the minor more `orgstruct-mode'.
6316 This mode is for using Org-mode structure commands in other modes.
6317 The following key behave as if Org-mode was active, if the cursor
6318 is on a headline, or on a plain list item (both in the definition
6319 of Org-mode).
6321 M-up Move entry/item up
6322 M-down Move entry/item down
6323 M-left Promote
6324 M-right Demote
6325 M-S-up Move entry/item up
6326 M-S-down Move entry/item down
6327 M-S-left Promote subtree
6328 M-S-right Demote subtree
6329 M-q Fill paragraph and items like in Org-mode
6330 C-c ^ Sort entries
6331 C-c - Cycle list bullet
6332 TAB Cycle item visibility
6333 M-RET Insert new heading/item
6334 S-M-RET Insert new TODO heading / Checkbox item
6335 C-c C-c Set tags / toggle checkbox"
6336 nil " OrgStruct" nil
6337 (org-load-modules-maybe)
6338 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6340 ;;;###autoload
6341 (defun turn-on-orgstruct ()
6342 "Unconditionally turn on `orgstruct-mode'."
6343 (orgstruct-mode 1))
6345 (defun orgstruct++-mode (&optional arg)
6346 "Toggle `orgstruct-mode', the enhanced version of it.
6347 In addition to setting orgstruct-mode, this also exports all indentation and
6348 autofilling variables from org-mode into the buffer. It will also
6349 recognize item context in multiline items.
6350 Note that turning off orgstruct-mode will *not* remove the
6351 indentation/paragraph settings. This can only be done by refreshing the
6352 major mode, for example with \[normal-mode]."
6353 (interactive "P")
6354 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6355 (if (< arg 1)
6356 (orgstruct-mode -1)
6357 (orgstruct-mode 1)
6358 (let (var val)
6359 (mapc
6360 (lambda (x)
6361 (when (string-match
6362 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6363 (symbol-name (car x)))
6364 (setq var (car x) val (nth 1 x))
6365 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6366 org-local-vars)
6367 (org-set-local 'orgstruct-is-++ t))))
6369 (defvar orgstruct-is-++ nil
6370 "Is orgstruct-mode in ++ version in the current-buffer?")
6371 (make-variable-buffer-local 'orgstruct-is-++)
6373 ;;;###autoload
6374 (defun turn-on-orgstruct++ ()
6375 "Unconditionally turn on `orgstruct++-mode'."
6376 (orgstruct++-mode 1))
6378 (defun orgstruct-error ()
6379 "Error when there is no default binding for a structure key."
6380 (interactive)
6381 (error "This key has no function outside structure elements"))
6383 (defun orgstruct-setup ()
6384 "Setup orgstruct keymaps."
6385 (let ((nfunc 0)
6386 (bindings
6387 (list
6388 '([(meta up)] org-metaup)
6389 '([(meta down)] org-metadown)
6390 '([(meta left)] org-metaleft)
6391 '([(meta right)] org-metaright)
6392 '([(meta shift up)] org-shiftmetaup)
6393 '([(meta shift down)] org-shiftmetadown)
6394 '([(meta shift left)] org-shiftmetaleft)
6395 '([(meta shift right)] org-shiftmetaright)
6396 '([(shift up)] org-shiftup)
6397 '([(shift down)] org-shiftdown)
6398 '([(shift left)] org-shiftleft)
6399 '([(shift right)] org-shiftright)
6400 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6401 '("\M-q" fill-paragraph)
6402 '("\C-c^" org-sort)
6403 '("\C-c-" org-cycle-list-bullet)))
6404 elt key fun cmd)
6405 (while (setq elt (pop bindings))
6406 (setq nfunc (1+ nfunc))
6407 (setq key (org-key (car elt))
6408 fun (nth 1 elt)
6409 cmd (orgstruct-make-binding fun nfunc key))
6410 (org-defkey orgstruct-mode-map key cmd))
6412 ;; Special treatment needed for TAB and RET
6413 (org-defkey orgstruct-mode-map [(tab)]
6414 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6415 (org-defkey orgstruct-mode-map "\C-i"
6416 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6418 (org-defkey orgstruct-mode-map "\M-\C-m"
6419 (orgstruct-make-binding 'org-insert-heading 105
6420 "\M-\C-m" [(meta return)]))
6421 (org-defkey orgstruct-mode-map [(meta return)]
6422 (orgstruct-make-binding 'org-insert-heading 106
6423 [(meta return)] "\M-\C-m"))
6425 (org-defkey orgstruct-mode-map [(shift meta return)]
6426 (orgstruct-make-binding 'org-insert-todo-heading 107
6427 [(meta return)] "\M-\C-m"))
6429 (unless org-local-vars
6430 (setq org-local-vars (org-get-local-variables)))
6434 (defun orgstruct-make-binding (fun n &rest keys)
6435 "Create a function for binding in the structure minor mode.
6436 FUN is the command to call inside a table. N is used to create a unique
6437 command name. KEYS are keys that should be checked in for a command
6438 to execute outside of tables."
6439 (eval
6440 (list 'defun
6441 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6442 '(arg)
6443 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6444 "Outside of structure, run the binding of `"
6445 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6446 "'.")
6447 '(interactive "p")
6448 (list 'if
6449 `(org-context-p 'headline 'item
6450 (and orgstruct-is-++
6451 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6452 'item-body))
6453 (list 'org-run-like-in-org-mode (list 'quote fun))
6454 (list 'let '(orgstruct-mode)
6455 (list 'call-interactively
6456 (append '(or)
6457 (mapcar (lambda (k)
6458 (list 'key-binding k))
6459 keys)
6460 '('orgstruct-error))))))))
6462 (defun org-context-p (&rest contexts)
6463 "Check if local context is any of CONTEXTS.
6464 Possible values in the list of contexts are `table', `headline', and `item'."
6465 (let ((pos (point)))
6466 (goto-char (point-at-bol))
6467 (prog1 (or (and (memq 'table contexts)
6468 (looking-at "[ \t]*|"))
6469 (and (memq 'headline contexts)
6470 ;;????????? (looking-at "\\*+"))
6471 (looking-at outline-regexp))
6472 (and (memq 'item contexts)
6473 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6474 (and (memq 'item-body contexts)
6475 (org-in-item-p)))
6476 (goto-char pos))))
6478 (defun org-get-local-variables ()
6479 "Return a list of all local variables in an org-mode buffer."
6480 (let (varlist)
6481 (with-current-buffer (get-buffer-create "*Org tmp*")
6482 (erase-buffer)
6483 (org-mode)
6484 (setq varlist (buffer-local-variables)))
6485 (kill-buffer "*Org tmp*")
6486 (delq nil
6487 (mapcar
6488 (lambda (x)
6489 (setq x
6490 (if (symbolp x)
6491 (list x)
6492 (list (car x) (list 'quote (cdr x)))))
6493 (if (string-match
6494 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6495 (symbol-name (car x)))
6496 x nil))
6497 varlist))))
6499 ;;;###autoload
6500 (defun org-run-like-in-org-mode (cmd)
6501 "Run a command, pretending that the current buffer is in Org-mode.
6502 This will temporarily bind local variables that are typically bound in
6503 Org-mode to the values they have in Org-mode, and then interactively
6504 call CMD."
6505 (org-load-modules-maybe)
6506 (unless org-local-vars
6507 (setq org-local-vars (org-get-local-variables)))
6508 (eval (list 'let org-local-vars
6509 (list 'call-interactively (list 'quote cmd)))))
6511 ;;;; Archiving
6513 (defun org-get-category (&optional pos)
6514 "Get the category applying to position POS."
6515 (get-text-property (or pos (point)) 'org-category))
6517 (defun org-refresh-category-properties ()
6518 "Refresh category text properties in the buffer."
6519 (let ((def-cat (cond
6520 ((null org-category)
6521 (if buffer-file-name
6522 (file-name-sans-extension
6523 (file-name-nondirectory buffer-file-name))
6524 "???"))
6525 ((symbolp org-category) (symbol-name org-category))
6526 (t org-category)))
6527 beg end cat pos optionp)
6528 (org-unmodified
6529 (save-excursion
6530 (save-restriction
6531 (widen)
6532 (goto-char (point-min))
6533 (put-text-property (point) (point-max) 'org-category def-cat)
6534 (while (re-search-forward
6535 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6536 (setq pos (match-end 0)
6537 optionp (equal (char-after (match-beginning 0)) ?#)
6538 cat (org-trim (match-string 2)))
6539 (if optionp
6540 (setq beg (point-at-bol) end (point-max))
6541 (org-back-to-heading t)
6542 (setq beg (point) end (org-end-of-subtree t t)))
6543 (put-text-property beg end 'org-category cat)
6544 (goto-char pos)))))))
6547 ;;;; Link Stuff
6549 ;;; Link abbreviations
6551 (defun org-link-expand-abbrev (link)
6552 "Apply replacements as defined in `org-link-abbrev-alist."
6553 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6554 (let* ((key (match-string 1 link))
6555 (as (or (assoc key org-link-abbrev-alist-local)
6556 (assoc key org-link-abbrev-alist)))
6557 (tag (and (match-end 2) (match-string 3 link)))
6558 rpl)
6559 (if (not as)
6560 link
6561 (setq rpl (cdr as))
6562 (cond
6563 ((symbolp rpl) (funcall rpl tag))
6564 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6565 ((string-match "%h" rpl)
6566 (replace-match (url-hexify-string (or tag "")) t t rpl))
6567 (t (concat rpl tag)))))
6568 link))
6570 ;;; Storing and inserting links
6572 (defvar org-insert-link-history nil
6573 "Minibuffer history for links inserted with `org-insert-link'.")
6575 (defvar org-stored-links nil
6576 "Contains the links stored with `org-store-link'.")
6578 (defvar org-store-link-plist nil
6579 "Plist with info about the most recently link created with `org-store-link'.")
6581 (defvar org-link-protocols nil
6582 "Link protocols added to Org-mode using `org-add-link-type'.")
6584 (defvar org-store-link-functions nil
6585 "List of functions that are called to create and store a link.
6586 Each function will be called in turn until one returns a non-nil
6587 value. Each function should check if it is responsible for creating
6588 this link (for example by looking at the major mode).
6589 If not, it must exit and return nil.
6590 If yes, it should return a non-nil value after a calling
6591 `org-store-link-props' with a list of properties and values.
6592 Special properties are:
6594 :type The link prefix. like \"http\". This must be given.
6595 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6596 This is obligatory as well.
6597 :description Optional default description for the second pair
6598 of brackets in an Org-mode link. The user can still change
6599 this when inserting this link into an Org-mode buffer.
6601 In addition to these, any additional properties can be specified
6602 and then used in remember templates.")
6604 (defun org-add-link-type (type &optional follow export)
6605 "Add TYPE to the list of `org-link-types'.
6606 Re-compute all regular expressions depending on `org-link-types'
6608 FOLLOW and EXPORT are two functions.
6610 FOLLOW should take the link path as the single argument and do whatever
6611 is necessary to follow the link, for example find a file or display
6612 a mail message.
6614 EXPORT should format the link path for export to one of the export formats.
6615 It should be a function accepting three arguments:
6617 path the path of the link, the text after the prefix (like \"http:\")
6618 desc the description of the link, if any, nil if there was no description
6619 format the export format, a symbol like `html' or `latex'.
6621 The function may use the FORMAT information to return different values
6622 depending on the format. The return value will be put literally into
6623 the exported file.
6624 Org-mode has a built-in default for exporting links. If you are happy with
6625 this default, there is no need to define an export function for the link
6626 type. For a simple example of an export function, see `org-bbdb.el'."
6627 (add-to-list 'org-link-types type t)
6628 (org-make-link-regexps)
6629 (if (assoc type org-link-protocols)
6630 (setcdr (assoc type org-link-protocols) (list follow export))
6631 (push (list type follow export) org-link-protocols)))
6633 ;;;###autoload
6634 (defun org-store-link (arg)
6635 "\\<org-mode-map>Store an org-link to the current location.
6636 This link is added to `org-stored-links' and can later be inserted
6637 into an org-buffer with \\[org-insert-link].
6639 For some link types, a prefix arg is interpreted:
6640 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6641 For file links, arg negates `org-context-in-file-links'."
6642 (interactive "P")
6643 (org-load-modules-maybe)
6644 (setq org-store-link-plist nil) ; reset
6645 (let (link cpltxt desc description search txt)
6646 (cond
6648 ((run-hook-with-args-until-success 'org-store-link-functions)
6649 (setq link (plist-get org-store-link-plist :link)
6650 desc (or (plist-get org-store-link-plist :description) link)))
6652 ((equal (buffer-name) "*Org Edit Src Example*")
6653 (let (label gc)
6654 (while (or (not label)
6655 (save-excursion
6656 (save-restriction
6657 (widen)
6658 (goto-char (point-min))
6659 (re-search-forward
6660 (regexp-quote (format org-coderef-label-format label))
6661 nil t))))
6662 (when label (message "Label exists already") (sit-for 2))
6663 (setq label (read-string "Code line label: " label)))
6664 (end-of-line 1)
6665 (setq link (format org-coderef-label-format label))
6666 (setq gc (- 79 (length link)))
6667 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6668 (insert link)
6669 (setq link (concat "(" label ")") desc nil)))
6671 ((eq major-mode 'calendar-mode)
6672 (let ((cd (calendar-cursor-to-date)))
6673 (setq link
6674 (format-time-string
6675 (car org-time-stamp-formats)
6676 (apply 'encode-time
6677 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6678 nil nil nil))))
6679 (org-store-link-props :type "calendar" :date cd)))
6681 ((eq major-mode 'w3-mode)
6682 (setq cpltxt (url-view-url t)
6683 link (org-make-link cpltxt))
6684 (org-store-link-props :type "w3" :url (url-view-url t)))
6686 ((eq major-mode 'w3m-mode)
6687 (setq cpltxt (or w3m-current-title w3m-current-url)
6688 link (org-make-link w3m-current-url))
6689 (org-store-link-props :type "w3m" :url (url-view-url t)))
6691 ((setq search (run-hook-with-args-until-success
6692 'org-create-file-search-functions))
6693 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6694 "::" search))
6695 (setq cpltxt (or description link)))
6697 ((eq major-mode 'image-mode)
6698 (setq cpltxt (concat "file:"
6699 (abbreviate-file-name buffer-file-name))
6700 link (org-make-link cpltxt))
6701 (org-store-link-props :type "image" :file buffer-file-name))
6703 ((eq major-mode 'dired-mode)
6704 ;; link to the file in the current line
6705 (setq cpltxt (concat "file:"
6706 (abbreviate-file-name
6707 (expand-file-name
6708 (dired-get-filename nil t))))
6709 link (org-make-link cpltxt)))
6711 ((and buffer-file-name (org-mode-p))
6712 (cond
6713 ((org-in-regexp "<<\\(.*?\\)>>")
6714 (setq cpltxt
6715 (concat "file:"
6716 (abbreviate-file-name buffer-file-name)
6717 "::" (match-string 1))
6718 link (org-make-link cpltxt)))
6719 ((and (featurep 'org-id)
6720 (or (eq org-link-to-org-use-id t)
6721 (and (eq org-link-to-org-use-id 'create-if-interactive)
6722 (interactive-p))
6723 (and org-link-to-org-use-id
6724 (condition-case nil
6725 (org-entry-get nil "ID")
6726 (error nil)))))
6727 ;; We can make a link using the ID.
6728 (setq link (condition-case nil
6729 (prog1 (org-id-store-link)
6730 (setq desc (plist-get org-store-link-plist
6731 :description)))
6732 (error
6733 ;; probably before first headline, link to file only
6734 (concat "file:"
6735 (abbreviate-file-name buffer-file-name))))))
6737 ;; Just link to current headline
6738 (setq cpltxt (concat "file:"
6739 (abbreviate-file-name buffer-file-name)))
6740 ;; Add a context search string
6741 (when (org-xor org-context-in-file-links arg)
6742 (setq txt (cond
6743 ((org-on-heading-p) nil)
6744 ((org-region-active-p)
6745 (buffer-substring (region-beginning) (region-end)))
6746 (t nil)))
6747 (when (or (null txt) (string-match "\\S-" txt))
6748 (setq cpltxt
6749 (concat cpltxt "::"
6750 (condition-case nil
6751 (org-make-org-heading-search-string txt)
6752 (error "")))
6753 desc "NONE")))
6754 (if (string-match "::\\'" cpltxt)
6755 (setq cpltxt (substring cpltxt 0 -2)))
6756 (setq link (org-make-link cpltxt)))))
6758 ((buffer-file-name (buffer-base-buffer))
6759 ;; Just link to this file here.
6760 (setq cpltxt (concat "file:"
6761 (abbreviate-file-name
6762 (buffer-file-name (buffer-base-buffer)))))
6763 ;; Add a context string
6764 (when (org-xor org-context-in-file-links arg)
6765 (setq txt (if (org-region-active-p)
6766 (buffer-substring (region-beginning) (region-end))
6767 (buffer-substring (point-at-bol) (point-at-eol))))
6768 ;; Only use search option if there is some text.
6769 (when (string-match "\\S-" txt)
6770 (setq cpltxt
6771 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6772 desc "NONE")))
6773 (setq link (org-make-link cpltxt)))
6775 ((interactive-p)
6776 (error "Cannot link to a buffer which is not visiting a file"))
6778 (t (setq link nil)))
6780 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6781 (setq link (or link cpltxt)
6782 desc (or desc cpltxt))
6783 (if (equal desc "NONE") (setq desc nil))
6785 (if (and (interactive-p) link)
6786 (progn
6787 (setq org-stored-links
6788 (cons (list link desc) org-stored-links))
6789 (message "Stored: %s" (or desc link)))
6790 (and link (org-make-link-string link desc)))))
6792 (defun org-store-link-props (&rest plist)
6793 "Store link properties, extract names and addresses."
6794 (let (x adr)
6795 (when (setq x (plist-get plist :from))
6796 (setq adr (mail-extract-address-components x))
6797 (setq plist (plist-put plist :fromname (car adr)))
6798 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6799 (when (setq x (plist-get plist :to))
6800 (setq adr (mail-extract-address-components x))
6801 (setq plist (plist-put plist :toname (car adr)))
6802 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6803 (let ((from (plist-get plist :from))
6804 (to (plist-get plist :to)))
6805 (when (and from to org-from-is-user-regexp)
6806 (setq plist
6807 (plist-put plist :fromto
6808 (if (string-match org-from-is-user-regexp from)
6809 (concat "to %t")
6810 (concat "from %f"))))))
6811 (setq org-store-link-plist plist))
6813 (defun org-add-link-props (&rest plist)
6814 "Add these properties to the link property list."
6815 (let (key value)
6816 (while plist
6817 (setq key (pop plist) value (pop plist))
6818 (setq org-store-link-plist
6819 (plist-put org-store-link-plist key value)))))
6821 (defun org-email-link-description (&optional fmt)
6822 "Return the description part of an email link.
6823 This takes information from `org-store-link-plist' and formats it
6824 according to FMT (default from `org-email-link-description-format')."
6825 (setq fmt (or fmt org-email-link-description-format))
6826 (let* ((p org-store-link-plist)
6827 (to (plist-get p :toaddress))
6828 (from (plist-get p :fromaddress))
6829 (table
6830 (list
6831 (cons "%c" (plist-get p :fromto))
6832 (cons "%F" (plist-get p :from))
6833 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6834 (cons "%T" (plist-get p :to))
6835 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6836 (cons "%s" (plist-get p :subject))
6837 (cons "%m" (plist-get p :message-id)))))
6838 (when (string-match "%c" fmt)
6839 ;; Check if the user wrote this message
6840 (if (and org-from-is-user-regexp from to
6841 (save-match-data (string-match org-from-is-user-regexp from)))
6842 (setq fmt (replace-match "to %t" t t fmt))
6843 (setq fmt (replace-match "from %f" t t fmt))))
6844 (org-replace-escapes fmt table)))
6846 (defun org-make-org-heading-search-string (&optional string heading)
6847 "Make search string for STRING or current headline."
6848 (interactive)
6849 (let ((s (or string (org-get-heading))))
6850 (unless (and string (not heading))
6851 ;; We are using a headline, clean up garbage in there.
6852 (if (string-match org-todo-regexp s)
6853 (setq s (replace-match "" t t s)))
6854 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6855 (setq s (replace-match "" t t s)))
6856 (setq s (org-trim s))
6857 (if (string-match (concat "^\\(" org-quote-string "\\|"
6858 org-comment-string "\\)") s)
6859 (setq s (replace-match "" t t s)))
6860 (while (string-match org-ts-regexp s)
6861 (setq s (replace-match "" t t s))))
6862 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6863 (setq s (replace-match " " t t s)))
6864 (or string (setq s (concat "*" s))) ; Add * for headlines
6865 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6867 (defun org-make-link (&rest strings)
6868 "Concatenate STRINGS."
6869 (apply 'concat strings))
6871 (defun org-make-link-string (link &optional description)
6872 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6873 (unless (string-match "\\S-" link)
6874 (error "Empty link"))
6875 (when (stringp description)
6876 ;; Remove brackets from the description, they are fatal.
6877 (while (string-match "\\[" description)
6878 (setq description (replace-match "{" t t description)))
6879 (while (string-match "\\]" description)
6880 (setq description (replace-match "}" t t description))))
6881 (when (equal (org-link-escape link) description)
6882 ;; No description needed, it is identical
6883 (setq description nil))
6884 (when (and (not description)
6885 (not (equal link (org-link-escape link))))
6886 (setq description (org-extract-attributes link)))
6887 (concat "[[" (org-link-escape link) "]"
6888 (if description (concat "[" description "]") "")
6889 "]"))
6891 (defconst org-link-escape-chars
6892 '((?\ . "%20")
6893 (?\[ . "%5B")
6894 (?\] . "%5D")
6895 (?\340 . "%E0") ; `a
6896 (?\342 . "%E2") ; ^a
6897 (?\347 . "%E7") ; ,c
6898 (?\350 . "%E8") ; `e
6899 (?\351 . "%E9") ; 'e
6900 (?\352 . "%EA") ; ^e
6901 (?\356 . "%EE") ; ^i
6902 (?\364 . "%F4") ; ^o
6903 (?\371 . "%F9") ; `u
6904 (?\373 . "%FB") ; ^u
6905 (?\; . "%3B")
6906 (?? . "%3F")
6907 (?= . "%3D")
6908 (?+ . "%2B")
6910 "Association list of escapes for some characters problematic in links.
6911 This is the list that is used for internal purposes.")
6913 (defconst org-link-escape-chars-browser
6914 '((?\ . "%20")) ; 32 for the SPC char
6915 "Association list of escapes for some characters problematic in links.
6916 This is the list that is used before handing over to the browser.")
6918 (defun org-link-escape (text &optional table)
6919 "Escape characters in TEXT that are problematic for links."
6920 (setq table (or table org-link-escape-chars))
6921 (when text
6922 (let ((re (mapconcat (lambda (x) (regexp-quote
6923 (char-to-string (car x))))
6924 table "\\|")))
6925 (while (string-match re text)
6926 (setq text
6927 (replace-match
6928 (cdr (assoc (string-to-char (match-string 0 text))
6929 table))
6930 t t text)))
6931 text)))
6933 (defun org-link-unescape (text &optional table)
6934 "Reverse the action of `org-link-escape'."
6935 (setq table (or table org-link-escape-chars))
6936 (when text
6937 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6938 table "\\|")))
6939 (while (string-match re text)
6940 (setq text
6941 (replace-match
6942 (char-to-string (car (rassoc (match-string 0 text) table)))
6943 t t text)))
6944 text)))
6946 (defun org-xor (a b)
6947 "Exclusive or."
6948 (if a (not b) b))
6950 (defun org-fixup-message-id-for-http (s)
6951 "Replace special characters in a message id, so it can be used in an http query."
6952 (while (string-match "<" s)
6953 (setq s (replace-match "%3C" t t s)))
6954 (while (string-match ">" s)
6955 (setq s (replace-match "%3E" t t s)))
6956 (while (string-match "@" s)
6957 (setq s (replace-match "%40" t t s)))
6960 ;;;###autoload
6961 (defun org-insert-link-global ()
6962 "Insert a link like Org-mode does.
6963 This command can be called in any mode to insert a link in Org-mode syntax."
6964 (interactive)
6965 (org-load-modules-maybe)
6966 (org-run-like-in-org-mode 'org-insert-link))
6968 (defun org-insert-link (&optional complete-file link-location)
6969 "Insert a link. At the prompt, enter the link.
6971 Completion can be used to insert any of the link protocol prefixes like
6972 http or ftp in use.
6974 The history can be used to select a link previously stored with
6975 `org-store-link'. When the empty string is entered (i.e. if you just
6976 press RET at the prompt), the link defaults to the most recently
6977 stored link. As SPC triggers completion in the minibuffer, you need to
6978 use M-SPC or C-q SPC to force the insertion of a space character.
6980 You will also be prompted for a description, and if one is given, it will
6981 be displayed in the buffer instead of the link.
6983 If there is already a link at point, this command will allow you to edit link
6984 and description parts.
6986 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6987 be selected using completion. The path to the file will be relative to the
6988 current directory if the file is in the current directory or a subdirectory.
6989 Otherwise, the link will be the absolute path as completed in the minibuffer
6990 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6991 option `org-link-file-path-type'.
6993 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6994 the current directory or below.
6996 With three \\[universal-argument] prefixes, negate the meaning of
6997 `org-keep-stored-link-after-insertion'.
6999 If `org-make-link-description-function' is non-nil, this function will be
7000 called with the link target, and the result will be the default
7001 link description.
7003 If the LINK-LOCATION parameter is non-nil, this value will be
7004 used as the link location instead of reading one interactively."
7005 (interactive "P")
7006 (let* ((wcf (current-window-configuration))
7007 (region (if (org-region-active-p)
7008 (buffer-substring (region-beginning) (region-end))))
7009 (remove (and region (list (region-beginning) (region-end))))
7010 (desc region)
7011 tmphist ; byte-compile incorrectly complains about this
7012 (link link-location)
7013 entry file)
7014 (cond
7015 (link-location) ; specified by arg, just use it.
7016 ((org-in-regexp org-bracket-link-regexp 1)
7017 ;; We do have a link at point, and we are going to edit it.
7018 (setq remove (list (match-beginning 0) (match-end 0)))
7019 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7020 (setq link (read-string "Link: "
7021 (org-link-unescape
7022 (org-match-string-no-properties 1)))))
7023 ((or (org-in-regexp org-angle-link-re)
7024 (org-in-regexp org-plain-link-re))
7025 ;; Convert to bracket link
7026 (setq remove (list (match-beginning 0) (match-end 0))
7027 link (read-string "Link: "
7028 (org-remove-angle-brackets (match-string 0)))))
7029 ((member complete-file '((4) (16)))
7030 ;; Completing read for file names.
7031 (setq file (read-file-name "File: "))
7032 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7033 (pwd1 (file-name-as-directory (abbreviate-file-name
7034 (expand-file-name ".")))))
7035 (cond
7036 ((equal complete-file '(16))
7037 (setq link (org-make-link
7038 "file:"
7039 (abbreviate-file-name (expand-file-name file)))))
7040 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7041 (setq link (org-make-link "file:" (match-string 1 file))))
7042 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7043 (expand-file-name file))
7044 (setq link (org-make-link
7045 "file:" (match-string 1 (expand-file-name file)))))
7046 (t (setq link (org-make-link "file:" file))))))
7048 ;; Read link, with completion for stored links.
7049 (with-output-to-temp-buffer "*Org Links*"
7050 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7051 (when org-stored-links
7052 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7053 (princ (mapconcat
7054 (lambda (x)
7055 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7056 (reverse org-stored-links) "\n"))))
7057 (let ((cw (selected-window)))
7058 (select-window (get-buffer-window "*Org Links*"))
7059 (setq truncate-lines t)
7060 (org-fit-window-to-buffer)
7061 (select-window cw))
7062 ;; Fake a link history, containing the stored links.
7063 (setq tmphist (append (mapcar 'car org-stored-links)
7064 org-insert-link-history))
7065 (unwind-protect
7066 (setq link
7067 (let ((org-completion-use-ido nil))
7068 (org-completing-read
7069 "Link: "
7070 (append
7071 (mapcar (lambda (x) (list (concat (car x) ":")))
7072 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7073 (mapcar (lambda (x) (list (concat x ":")))
7074 org-link-types))
7075 nil nil nil
7076 'tmphist
7077 (or (car (car org-stored-links))))))
7078 (set-window-configuration wcf)
7079 (kill-buffer "*Org Links*"))
7080 (setq entry (assoc link org-stored-links))
7081 (or entry (push link org-insert-link-history))
7082 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7083 (not org-keep-stored-link-after-insertion))
7084 (setq org-stored-links (delq (assoc link org-stored-links)
7085 org-stored-links)))
7086 (setq desc (or desc (nth 1 entry)))))
7088 (if (string-match org-plain-link-re link)
7089 ;; URL-like link, normalize the use of angular brackets.
7090 (setq link (org-make-link (org-remove-angle-brackets link))))
7092 ;; Check if we are linking to the current file with a search option
7093 ;; If yes, simplify the link by using only the search option.
7094 (when (and buffer-file-name
7095 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7096 (let* ((path (match-string 1 link))
7097 (case-fold-search nil)
7098 (search (match-string 2 link)))
7099 (save-match-data
7100 (if (equal (file-truename buffer-file-name) (file-truename path))
7101 ;; We are linking to this same file, with a search option
7102 (setq link search)))))
7104 ;; Check if we can/should use a relative path. If yes, simplify the link
7105 (when (string-match "^file:\\(.*\\)" link)
7106 (let* ((path (match-string 1 link))
7107 (origpath path)
7108 (case-fold-search nil))
7109 (cond
7110 ((or (eq org-link-file-path-type 'absolute)
7111 (equal complete-file '(16)))
7112 (setq path (abbreviate-file-name (expand-file-name path))))
7113 ((eq org-link-file-path-type 'noabbrev)
7114 (setq path (expand-file-name path)))
7115 ((eq org-link-file-path-type 'relative)
7116 (setq path (file-relative-name path)))
7118 (save-match-data
7119 (if (string-match (concat "^" (regexp-quote
7120 (file-name-as-directory
7121 (expand-file-name "."))))
7122 (expand-file-name path))
7123 ;; We are linking a file with relative path name.
7124 (setq path (substring (expand-file-name path)
7125 (match-end 0)))
7126 (setq path (abbreviate-file-name (expand-file-name path)))))))
7127 (setq link (concat "file:" path))
7128 (if (equal desc origpath)
7129 (setq desc path))))
7131 (if org-make-link-description-function
7132 (setq desc (funcall org-make-link-description-function link desc)))
7134 (setq desc (read-string "Description: " desc))
7135 (unless (string-match "\\S-" desc) (setq desc nil))
7136 (if remove (apply 'delete-region remove))
7137 (insert (org-make-link-string link desc))))
7139 (defun org-completing-read (&rest args)
7140 "Completing-read with SPACE being a normal character."
7141 (let ((minibuffer-local-completion-map
7142 (copy-keymap minibuffer-local-completion-map)))
7143 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7144 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7145 (apply 'org-ido-completing-read args)))
7147 (defun org-completing-read-no-ido (&rest args)
7148 (let (org-completion-use-ido)
7149 (apply 'org-completing-read args)))
7151 (defun org-ido-completing-read (&rest args)
7152 "Completing-read using `ido-mode' speedups if available"
7153 (if (and org-completion-use-ido
7154 (fboundp 'ido-completing-read)
7155 (boundp 'ido-mode) ido-mode
7156 (listp (second args)))
7157 (let ((ido-enter-matching-directory nil))
7158 (apply 'ido-completing-read (concat (car args))
7159 (mapcar (lambda (x) (car x)) (nth 1 args))
7160 (cddr args)))
7161 (apply 'completing-read args)))
7164 (defun org-extract-attributes (s)
7165 "Extract the attributes cookie from a string and set as text property."
7166 (let (a attr (start 0) key value)
7167 (save-match-data
7168 (when (string-match "{{\\([^}]+\\)}}$" s)
7169 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7170 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7171 (setq key (match-string 1 a) value (match-string 2 a)
7172 start (match-end 0)
7173 attr (plist-put attr (intern key) value))))
7174 (org-add-props s nil 'org-attr attr))
7177 (defun org-attributes-to-string (plist)
7178 "Format a property list into an HTML attribute list."
7179 (let ((s "") key value)
7180 (while plist
7181 (setq key (pop plist) value (pop plist))
7182 (and value
7183 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7186 ;;; Opening/following a link
7188 (defvar org-link-search-failed nil)
7190 (defun org-next-link ()
7191 "Move forward to the next link.
7192 If the link is in hidden text, expose it."
7193 (interactive)
7194 (when (and org-link-search-failed (eq this-command last-command))
7195 (goto-char (point-min))
7196 (message "Link search wrapped back to beginning of buffer"))
7197 (setq org-link-search-failed nil)
7198 (let* ((pos (point))
7199 (ct (org-context))
7200 (a (assoc :link ct)))
7201 (if a (goto-char (nth 2 a)))
7202 (if (re-search-forward org-any-link-re nil t)
7203 (progn
7204 (goto-char (match-beginning 0))
7205 (if (org-invisible-p) (org-show-context)))
7206 (goto-char pos)
7207 (setq org-link-search-failed t)
7208 (error "No further link found"))))
7210 (defun org-previous-link ()
7211 "Move backward to the previous link.
7212 If the link is in hidden text, expose it."
7213 (interactive)
7214 (when (and org-link-search-failed (eq this-command last-command))
7215 (goto-char (point-max))
7216 (message "Link search wrapped back to end of buffer"))
7217 (setq org-link-search-failed nil)
7218 (let* ((pos (point))
7219 (ct (org-context))
7220 (a (assoc :link ct)))
7221 (if a (goto-char (nth 1 a)))
7222 (if (re-search-backward org-any-link-re nil t)
7223 (progn
7224 (goto-char (match-beginning 0))
7225 (if (org-invisible-p) (org-show-context)))
7226 (goto-char pos)
7227 (setq org-link-search-failed t)
7228 (error "No further link found"))))
7230 (defun org-translate-link (s)
7231 "Translate a link string if a translation function has been defined."
7232 (if (and org-link-translation-function
7233 (fboundp org-link-translation-function)
7234 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7235 (progn
7236 (setq s (funcall org-link-translation-function
7237 (match-string 1) (match-string 2)))
7238 (concat (car s) ":" (cdr s)))
7241 (defun org-translate-link-from-planner (type path)
7242 "Translate a link from Emacs Planner syntax so that Org can follow it.
7243 This is still an experimental function, your mileage may vary."
7244 (cond
7245 ((member type '("http" "https" "news" "ftp"))
7246 ;; standard Internet links are the same.
7247 nil)
7248 ((and (equal type "irc") (string-match "^//" path))
7249 ;; Planner has two / at the beginning of an irc link, we have 1.
7250 ;; We should have zero, actually....
7251 (setq path (substring path 1)))
7252 ((and (equal type "lisp") (string-match "^/" path))
7253 ;; Planner has a slash, we do not.
7254 (setq type "elisp" path (substring path 1)))
7255 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7256 ;; A typical message link. Planner has the id after the fina slash,
7257 ;; we separate it with a hash mark
7258 (setq path (concat (match-string 1 path) "#"
7259 (org-remove-angle-brackets (match-string 2 path)))))
7261 (cons type path))
7263 (defun org-find-file-at-mouse (ev)
7264 "Open file link or URL at mouse."
7265 (interactive "e")
7266 (mouse-set-point ev)
7267 (org-open-at-point 'in-emacs))
7269 (defun org-open-at-mouse (ev)
7270 "Open file link or URL at mouse."
7271 (interactive "e")
7272 (mouse-set-point ev)
7273 (if (eq major-mode 'org-agenda-mode)
7274 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7275 (org-open-at-point))
7277 (defvar org-window-config-before-follow-link nil
7278 "The window configuration before following a link.
7279 This is saved in case the need arises to restore it.")
7281 (defvar org-open-link-marker (make-marker)
7282 "Marker pointing to the location where `org-open-at-point; was called.")
7284 ;;;###autoload
7285 (defun org-open-at-point-global ()
7286 "Follow a link like Org-mode does.
7287 This command can be called in any mode to follow a link that has
7288 Org-mode syntax."
7289 (interactive)
7290 (org-run-like-in-org-mode 'org-open-at-point))
7292 ;;;###autoload
7293 (defun org-open-link-from-string (s &optional arg)
7294 "Open a link in the string S, as if it was in Org-mode."
7295 (interactive "sLink: \nP")
7296 (with-temp-buffer
7297 (let ((org-inhibit-startup t))
7298 (org-mode)
7299 (insert s)
7300 (goto-char (point-min))
7301 (org-open-at-point arg))))
7303 (defun org-open-at-point (&optional in-emacs)
7304 "Open link at or after point.
7305 If there is no link at point, this function will search forward up to
7306 the end of the current subtree.
7307 Normally, files will be opened by an appropriate application. If the
7308 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7309 With a double prefix argument, try to open outside of Emacs, in the
7310 application the system uses for this file type."
7311 (interactive "P")
7312 (org-load-modules-maybe)
7313 (move-marker org-open-link-marker (point))
7314 (setq org-window-config-before-follow-link (current-window-configuration))
7315 (org-remove-occur-highlights nil nil t)
7316 (cond
7317 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7318 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7319 (org-footnote-action))
7321 (let (type path link line search (pos (point)))
7322 (catch 'match
7323 (save-excursion
7324 (skip-chars-forward "^]\n\r")
7325 (when (org-in-regexp org-bracket-link-regexp)
7326 (setq link (org-extract-attributes
7327 (org-link-unescape (org-match-string-no-properties 1))))
7328 (while (string-match " *\n *" link)
7329 (setq link (replace-match " " t t link)))
7330 (setq link (org-link-expand-abbrev link))
7331 (cond
7332 ((or (file-name-absolute-p link)
7333 (string-match "^\\.\\.?/" link))
7334 (setq type "file" path link))
7335 ((string-match org-link-re-with-space3 link)
7336 (setq type (match-string 1 link) path (match-string 2 link)))
7337 (t (setq type "thisfile" path link)))
7338 (throw 'match t)))
7340 (when (get-text-property (point) 'org-linked-text)
7341 (setq type "thisfile"
7342 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7343 (1+ (point)) (point))
7344 path (buffer-substring
7345 (previous-single-property-change pos 'org-linked-text)
7346 (next-single-property-change pos 'org-linked-text)))
7347 (throw 'match t))
7349 (save-excursion
7350 (when (or (org-in-regexp org-angle-link-re)
7351 (org-in-regexp org-plain-link-re))
7352 (setq type (match-string 1) path (match-string 2))
7353 (throw 'match t)))
7354 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7355 (setq type "tree-match"
7356 path (match-string 1))
7357 (throw 'match t))
7358 (save-excursion
7359 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7360 (setq type "tags"
7361 path (match-string 1))
7362 (while (string-match ":" path)
7363 (setq path (replace-match "+" t t path)))
7364 (throw 'match t))))
7365 (unless path
7366 (error "No link found"))
7367 ;; Remove any trailing spaces in path
7368 (if (string-match " +\\'" path)
7369 (setq path (replace-match "" t t path)))
7370 (if (and org-link-translation-function
7371 (fboundp org-link-translation-function))
7372 ;; Check if we need to translate the link
7373 (let ((tmp (funcall org-link-translation-function type path)))
7374 (setq type (car tmp) path (cdr tmp))))
7376 (cond
7378 ((assoc type org-link-protocols)
7379 (funcall (nth 1 (assoc type org-link-protocols)) path))
7381 ((equal type "mailto")
7382 (let ((cmd (car org-link-mailto-program))
7383 (args (cdr org-link-mailto-program)) args1
7384 (address path) (subject "") a)
7385 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7386 (setq address (match-string 1 path)
7387 subject (org-link-escape (match-string 2 path))))
7388 (while args
7389 (cond
7390 ((not (stringp (car args))) (push (pop args) args1))
7391 (t (setq a (pop args))
7392 (if (string-match "%a" a)
7393 (setq a (replace-match address t t a)))
7394 (if (string-match "%s" a)
7395 (setq a (replace-match subject t t a)))
7396 (push a args1))))
7397 (apply cmd (nreverse args1))))
7399 ((member type '("http" "https" "ftp" "news"))
7400 (browse-url (concat type ":" (org-link-escape
7401 path org-link-escape-chars-browser))))
7403 ((member type '("message"))
7404 (browse-url (concat type ":" path)))
7406 ((string= type "tags")
7407 (org-tags-view in-emacs path))
7408 ((string= type "thisfile")
7409 (if in-emacs
7410 (switch-to-buffer-other-window
7411 (org-get-buffer-for-internal-link (current-buffer)))
7412 (org-mark-ring-push))
7413 (let ((cmd `(org-link-search
7414 ,path
7415 ,(cond ((equal in-emacs '(4)) 'occur)
7416 ((equal in-emacs '(16)) 'org-occur)
7417 (t nil))
7418 ,pos)))
7419 (condition-case nil (eval cmd)
7420 (error (progn (widen) (eval cmd))))))
7422 ((string= type "tree-match")
7423 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7425 ((string= type "file")
7426 (if (string-match "::\\([0-9]+\\)\\'" path)
7427 (setq line (string-to-number (match-string 1 path))
7428 path (substring path 0 (match-beginning 0)))
7429 (if (string-match "::\\(.+\\)\\'" path)
7430 (setq search (match-string 1 path)
7431 path (substring path 0 (match-beginning 0)))))
7432 (if (string-match "[*?{]" (file-name-nondirectory path))
7433 (dired path)
7434 (org-open-file path in-emacs line search)))
7436 ((string= type "news")
7437 (require 'org-gnus)
7438 (org-gnus-follow-link path))
7440 ((string= type "shell")
7441 (let ((cmd path))
7442 (if (or (not org-confirm-shell-link-function)
7443 (funcall org-confirm-shell-link-function
7444 (format "Execute \"%s\" in shell? "
7445 (org-add-props cmd nil
7446 'face 'org-warning))))
7447 (progn
7448 (message "Executing %s" cmd)
7449 (shell-command cmd))
7450 (error "Abort"))))
7452 ((string= type "elisp")
7453 (let ((cmd path))
7454 (if (or (not org-confirm-elisp-link-function)
7455 (funcall org-confirm-elisp-link-function
7456 (format "Execute \"%s\" as elisp? "
7457 (org-add-props cmd nil
7458 'face 'org-warning))))
7459 (message "%s => %s" cmd
7460 (if (equal (string-to-char cmd) ?\()
7461 (eval (read cmd))
7462 (call-interactively (read cmd))))
7463 (error "Abort"))))
7466 (browse-url-at-point))))))
7467 (move-marker org-open-link-marker nil)
7468 (run-hook-with-args 'org-follow-link-hook))
7470 ;;;; Time estimates
7472 (defun org-get-effort (&optional pom)
7473 "Get the effort estimate for the current entry."
7474 (org-entry-get pom org-effort-property))
7476 ;;; File search
7478 (defvar org-create-file-search-functions nil
7479 "List of functions to construct the right search string for a file link.
7480 These functions are called in turn with point at the location to
7481 which the link should point.
7483 A function in the hook should first test if it would like to
7484 handle this file type, for example by checking the major-mode or
7485 the file extension. If it decides not to handle this file, it
7486 should just return nil to give other functions a chance. If it
7487 does handle the file, it must return the search string to be used
7488 when following the link. The search string will be part of the
7489 file link, given after a double colon, and `org-open-at-point'
7490 will automatically search for it. If special measures must be
7491 taken to make the search successful, another function should be
7492 added to the companion hook `org-execute-file-search-functions',
7493 which see.
7495 A function in this hook may also use `setq' to set the variable
7496 `description' to provide a suggestion for the descriptive text to
7497 be used for this link when it gets inserted into an Org-mode
7498 buffer with \\[org-insert-link].")
7500 (defvar org-execute-file-search-functions nil
7501 "List of functions to execute a file search triggered by a link.
7503 Functions added to this hook must accept a single argument, the
7504 search string that was part of the file link, the part after the
7505 double colon. The function must first check if it would like to
7506 handle this search, for example by checking the major-mode or the
7507 file extension. If it decides not to handle this search, it
7508 should just return nil to give other functions a chance. If it
7509 does handle the search, it must return a non-nil value to keep
7510 other functions from trying.
7512 Each function can access the current prefix argument through the
7513 variable `current-prefix-argument'. Note that a single prefix is
7514 used to force opening a link in Emacs, so it may be good to only
7515 use a numeric or double prefix to guide the search function.
7517 In case this is needed, a function in this hook can also restore
7518 the window configuration before `org-open-at-point' was called using:
7520 (set-window-configuration org-window-config-before-follow-link)")
7522 (defun org-link-search (s &optional type avoid-pos)
7523 "Search for a link search option.
7524 If S is surrounded by forward slashes, it is interpreted as a
7525 regular expression. In org-mode files, this will create an `org-occur'
7526 sparse tree. In ordinary files, `occur' will be used to list matches.
7527 If the current buffer is in `dired-mode', grep will be used to search
7528 in all files. If AVOID-POS is given, ignore matches near that position."
7529 (let ((case-fold-search t)
7530 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7531 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7532 (append '(("") (" ") ("\t") ("\n"))
7533 org-emphasis-alist)
7534 "\\|") "\\)"))
7535 (pos (point))
7536 (pre nil) (post nil)
7537 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7538 (cond
7539 ;; First check if there are any special
7540 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7541 ;; Now try the builtin stuff
7542 ((save-excursion
7543 (goto-char (point-min))
7544 (and
7545 (re-search-forward
7546 (concat "<<" (regexp-quote s0) ">>") nil t)
7547 (setq type 'dedicated
7548 pos (match-beginning 0))))
7549 ;; There is an exact target for this
7550 (goto-char pos))
7551 ((and (string-match "^(\\(.*\\))$" s0)
7552 (save-excursion
7553 (goto-char (point-min))
7554 (and
7555 (re-search-forward
7556 (concat "[^[]" (regexp-quote
7557 (format org-coderef-label-format
7558 (match-string 1 s0))))
7559 nil t)
7560 (setq type 'dedicated
7561 pos (1+ (match-beginning 0))))))
7562 ;; There is a coderef target for this
7563 (goto-char pos))
7564 ((string-match "^/\\(.*\\)/$" s)
7565 ;; A regular expression
7566 (cond
7567 ((org-mode-p)
7568 (org-occur (match-string 1 s)))
7569 ;;((eq major-mode 'dired-mode)
7570 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7571 (t (org-do-occur (match-string 1 s)))))
7573 ;; A normal search strings
7574 (when (equal (string-to-char s) ?*)
7575 ;; Anchor on headlines, post may include tags.
7576 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7577 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7578 s (substring s 1)))
7579 (remove-text-properties
7580 0 (length s)
7581 '(face nil mouse-face nil keymap nil fontified nil) s)
7582 ;; Make a series of regular expressions to find a match
7583 (setq words (org-split-string s "[ \n\r\t]+")
7585 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7586 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7587 "\\)" markers)
7588 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7589 re2a (concat "[ \t\r\n]" re2a_)
7590 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7591 re4 (concat "[^a-zA-Z_]" re4_)
7593 re1 (concat pre re2 post)
7594 re3 (concat pre (if pre re4_ re4) post)
7595 re5 (concat pre ".*" re4)
7596 re2 (concat pre re2)
7597 re2a (concat pre (if pre re2a_ re2a))
7598 re4 (concat pre (if pre re4_ re4))
7599 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7600 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7601 re5 "\\)"
7603 (cond
7604 ((eq type 'org-occur) (org-occur reall))
7605 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7606 (t (goto-char (point-min))
7607 (setq type 'fuzzy)
7608 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7609 (org-search-not-self 1 re1 nil t)
7610 (org-search-not-self 1 re2 nil t)
7611 (org-search-not-self 1 re2a nil t)
7612 (org-search-not-self 1 re3 nil t)
7613 (org-search-not-self 1 re4 nil t)
7614 (org-search-not-self 1 re5 nil t)
7616 (goto-char (match-beginning 1))
7617 (goto-char pos)
7618 (error "No match")))))
7620 ;; Normal string-search
7621 (goto-char (point-min))
7622 (if (search-forward s nil t)
7623 (goto-char (match-beginning 0))
7624 (error "No match"))))
7625 (and (org-mode-p) (org-show-context 'link-search))
7626 type))
7628 (defun org-search-not-self (group &rest args)
7629 "Execute `re-search-forward', but only accept matches that do not
7630 enclose the position of `org-open-link-marker'."
7631 (let ((m org-open-link-marker))
7632 (catch 'exit
7633 (while (apply 're-search-forward args)
7634 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7635 (goto-char (match-end group))
7636 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7637 (> (match-beginning 0) (marker-position m))
7638 (< (match-end 0) (marker-position m)))
7639 (save-match-data
7640 (or (not (org-in-regexp
7641 org-bracket-link-analytic-regexp 1))
7642 (not (match-end 4)) ; no description
7643 (and (<= (match-beginning 4) (point))
7644 (>= (match-end 4) (point))))))
7645 (throw 'exit (point))))))))
7647 (defun org-get-buffer-for-internal-link (buffer)
7648 "Return a buffer to be used for displaying the link target of internal links."
7649 (cond
7650 ((not org-display-internal-link-with-indirect-buffer)
7651 buffer)
7652 ((string-match "(Clone)$" (buffer-name buffer))
7653 (message "Buffer is already a clone, not making another one")
7654 ;; we also do not modify visibility in this case
7655 buffer)
7656 (t ; make a new indirect buffer for displaying the link
7657 (let* ((bn (buffer-name buffer))
7658 (ibn (concat bn "(Clone)"))
7659 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7660 (with-current-buffer ib (org-overview))
7661 ib))))
7663 (defun org-do-occur (regexp &optional cleanup)
7664 "Call the Emacs command `occur'.
7665 If CLEANUP is non-nil, remove the printout of the regular expression
7666 in the *Occur* buffer. This is useful if the regex is long and not useful
7667 to read."
7668 (occur regexp)
7669 (when cleanup
7670 (let ((cwin (selected-window)) win beg end)
7671 (when (setq win (get-buffer-window "*Occur*"))
7672 (select-window win))
7673 (goto-char (point-min))
7674 (when (re-search-forward "match[a-z]+" nil t)
7675 (setq beg (match-end 0))
7676 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7677 (setq end (1- (match-beginning 0)))))
7678 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7679 (goto-char (point-min))
7680 (select-window cwin))))
7682 ;;; The mark ring for links jumps
7684 (defvar org-mark-ring nil
7685 "Mark ring for positions before jumps in Org-mode.")
7686 (defvar org-mark-ring-last-goto nil
7687 "Last position in the mark ring used to go back.")
7688 ;; Fill and close the ring
7689 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7690 (loop for i from 1 to org-mark-ring-length do
7691 (push (make-marker) org-mark-ring))
7692 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7693 org-mark-ring)
7695 (defun org-mark-ring-push (&optional pos buffer)
7696 "Put the current position or POS into the mark ring and rotate it."
7697 (interactive)
7698 (setq pos (or pos (point)))
7699 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7700 (move-marker (car org-mark-ring)
7701 (or pos (point))
7702 (or buffer (current-buffer)))
7703 (message "%s"
7704 (substitute-command-keys
7705 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7707 (defun org-mark-ring-goto (&optional n)
7708 "Jump to the previous position in the mark ring.
7709 With prefix arg N, jump back that many stored positions. When
7710 called several times in succession, walk through the entire ring.
7711 Org-mode commands jumping to a different position in the current file,
7712 or to another Org-mode file, automatically push the old position
7713 onto the ring."
7714 (interactive "p")
7715 (let (p m)
7716 (if (eq last-command this-command)
7717 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7718 (setq p org-mark-ring))
7719 (setq org-mark-ring-last-goto p)
7720 (setq m (car p))
7721 (switch-to-buffer (marker-buffer m))
7722 (goto-char m)
7723 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7725 (defun org-remove-angle-brackets (s)
7726 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7727 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7729 (defun org-add-angle-brackets (s)
7730 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7731 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7733 (defun org-remove-double-quotes (s)
7734 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7735 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7738 ;;; Following specific links
7740 (defun org-follow-timestamp-link ()
7741 (cond
7742 ((org-at-date-range-p t)
7743 (let ((org-agenda-start-on-weekday)
7744 (t1 (match-string 1))
7745 (t2 (match-string 2)))
7746 (setq t1 (time-to-days (org-time-string-to-time t1))
7747 t2 (time-to-days (org-time-string-to-time t2)))
7748 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7749 ((org-at-timestamp-p t)
7750 (org-agenda-list nil (time-to-days (org-time-string-to-time
7751 (substring (match-string 1) 0 10)))
7753 (t (error "This should not happen"))))
7756 ;;; Following file links
7757 (defvar org-wait nil)
7758 (defun org-open-file (path &optional in-emacs line search)
7759 "Open the file at PATH.
7760 First, this expands any special file name abbreviations. Then the
7761 configuration variable `org-file-apps' is checked if it contains an
7762 entry for this file type, and if yes, the corresponding command is launched.
7764 If no application is found, Emacs simply visits the file.
7766 With optional prefix argument IN-EMACS, Emacs will visit the file.
7767 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7768 and o use an external application to visit the file.
7770 Optional LINE specifies a line to go to, optional SEARCH a string to
7771 search for. If LINE or SEARCH is given, the file will always be
7772 opened in Emacs.
7773 If the file does not exist, an error is thrown."
7774 (setq in-emacs (or in-emacs line search))
7775 (let* ((file (if (equal path "")
7776 buffer-file-name
7777 (substitute-in-file-name (expand-file-name path))))
7778 (apps (append org-file-apps (org-default-apps)))
7779 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7780 (dirp (if remp nil (file-directory-p file)))
7781 (file (if (and dirp org-open-directory-means-index-dot-org)
7782 (concat (file-name-as-directory file) "index.org")
7783 file))
7784 (a-m-a-p (assq 'auto-mode apps))
7785 (dfile (downcase file))
7786 (old-buffer (current-buffer))
7787 (old-pos (point))
7788 (old-mode major-mode)
7789 ext cmd)
7790 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7791 (setq ext (match-string 1 dfile))
7792 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7793 (setq ext (match-string 1 dfile))))
7794 (cond
7795 ((equal in-emacs '(16))
7796 (setq cmd (cdr (assoc 'system apps))))
7797 (in-emacs (setq cmd 'emacs))
7799 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7800 (and dirp (cdr (assoc 'directory apps)))
7801 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7802 'string-match)
7803 (cdr (assoc ext apps))
7804 (cdr (assoc t apps))))))
7805 (when (eq cmd 'system)
7806 (setq cmd (cdr (assoc 'system apps))))
7807 (when (eq cmd 'default)
7808 (setq cmd (cdr (assoc t apps))))
7809 (when (eq cmd 'mailcap)
7810 (require 'mailcap)
7811 (mailcap-parse-mailcaps)
7812 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7813 (command (mailcap-mime-info mime-type)))
7814 (if (stringp command)
7815 (setq cmd command)
7816 (setq cmd 'emacs))))
7817 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7818 (not (file-exists-p file))
7819 (not org-open-non-existing-files))
7820 (error "No such file: %s" file))
7821 (cond
7822 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7823 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7824 (while (string-match "['\"]%s['\"]" cmd)
7825 (setq cmd (replace-match "%s" t t cmd)))
7826 (while (string-match "%s" cmd)
7827 (setq cmd (replace-match
7828 (save-match-data
7829 (shell-quote-argument
7830 (convert-standard-filename file)))
7831 t t cmd)))
7832 (save-window-excursion
7833 (start-process-shell-command cmd nil cmd)
7834 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7836 ((or (stringp cmd)
7837 (eq cmd 'emacs))
7838 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7839 (widen)
7840 (if line (goto-line line)
7841 (if search (org-link-search search))))
7842 ((consp cmd)
7843 (let ((file (convert-standard-filename file)))
7844 (eval cmd)))
7845 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7846 (and (org-mode-p) (eq old-mode 'org-mode)
7847 (or (not (equal old-buffer (current-buffer)))
7848 (not (equal old-pos (point))))
7849 (org-mark-ring-push old-pos old-buffer))))
7851 (defun org-default-apps ()
7852 "Return the default applications for this operating system."
7853 (cond
7854 ((eq system-type 'darwin)
7855 org-file-apps-defaults-macosx)
7856 ((eq system-type 'windows-nt)
7857 org-file-apps-defaults-windowsnt)
7858 (t org-file-apps-defaults-gnu)))
7860 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7861 "Convert extensions to regular expressions in the cars of LIST.
7862 Also, weed out any non-string entries, because the return value is used
7863 only for regexp matching.
7864 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7865 point to the symbol `emacs', indicating that the file should
7866 be opened in Emacs."
7867 (append
7868 (delq nil
7869 (mapcar (lambda (x)
7870 (if (not (stringp (car x)))
7872 (if (string-match "\\W" (car x))
7874 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7875 list))
7876 (if add-auto-mode
7877 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7879 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7880 (defun org-file-remote-p (file)
7881 "Test whether FILE specifies a location on a remote system.
7882 Return non-nil if the location is indeed remote.
7884 For example, the filename \"/user@host:/foo\" specifies a location
7885 on the system \"/user@host:\"."
7886 (cond ((fboundp 'file-remote-p)
7887 (file-remote-p file))
7888 ((fboundp 'tramp-handle-file-remote-p)
7889 (tramp-handle-file-remote-p file))
7890 ((and (boundp 'ange-ftp-name-format)
7891 (string-match (car ange-ftp-name-format) file))
7893 (t nil)))
7896 ;;;; Refiling
7898 (defun org-get-org-file ()
7899 "Read a filename, with default directory `org-directory'."
7900 (let ((default (or org-default-notes-file remember-data-file)))
7901 (read-file-name (format "File name [%s]: " default)
7902 (file-name-as-directory org-directory)
7903 default)))
7905 (defun org-notes-order-reversed-p ()
7906 "Check if the current file should receive notes in reversed order."
7907 (cond
7908 ((not org-reverse-note-order) nil)
7909 ((eq t org-reverse-note-order) t)
7910 ((not (listp org-reverse-note-order)) nil)
7911 (t (catch 'exit
7912 (let ((all org-reverse-note-order)
7913 entry)
7914 (while (setq entry (pop all))
7915 (if (string-match (car entry) buffer-file-name)
7916 (throw 'exit (cdr entry))))
7917 nil)))))
7919 (defvar org-refile-target-table nil
7920 "The list of refile targets, created by `org-refile'.")
7922 (defvar org-agenda-new-buffers nil
7923 "Buffers created to visit agenda files.")
7925 (defun org-get-refile-targets (&optional default-buffer)
7926 "Produce a table with refile targets."
7927 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7928 targets txt re files f desc descre fast-path-p level)
7929 (message "Getting targets...")
7930 (with-current-buffer (or default-buffer (current-buffer))
7931 (while (setq entry (pop entries))
7932 (setq files (car entry) desc (cdr entry))
7933 (setq fast-path-p nil)
7934 (cond
7935 ((null files) (setq files (list (current-buffer))))
7936 ((eq files 'org-agenda-files)
7937 (setq files (org-agenda-files 'unrestricted)))
7938 ((and (symbolp files) (fboundp files))
7939 (setq files (funcall files)))
7940 ((and (symbolp files) (boundp files))
7941 (setq files (symbol-value files))))
7942 (if (stringp files) (setq files (list files)))
7943 (cond
7944 ((eq (car desc) :tag)
7945 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7946 ((eq (car desc) :todo)
7947 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7948 ((eq (car desc) :regexp)
7949 (setq descre (cdr desc)))
7950 ((eq (car desc) :level)
7951 (setq descre (concat "^\\*\\{" (number-to-string
7952 (if org-odd-levels-only
7953 (1- (* 2 (cdr desc)))
7954 (cdr desc)))
7955 "\\}[ \t]")))
7956 ((eq (car desc) :maxlevel)
7957 (setq fast-path-p t)
7958 (setq descre (concat "^\\*\\{1," (number-to-string
7959 (if org-odd-levels-only
7960 (1- (* 2 (cdr desc)))
7961 (cdr desc)))
7962 "\\}[ \t]")))
7963 (t (error "Bad refiling target description %s" desc)))
7964 (while (setq f (pop files))
7965 (save-excursion
7966 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7967 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7968 (setq f (expand-file-name f))
7969 (save-excursion
7970 (save-restriction
7971 (widen)
7972 (goto-char (point-min))
7973 (while (re-search-forward descre nil t)
7974 (goto-char (point-at-bol))
7975 (when (looking-at org-complex-heading-regexp)
7976 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7977 txt (org-link-display-format (match-string 4))
7978 re (concat "^" (regexp-quote
7979 (buffer-substring (match-beginning 1)
7980 (match-end 4)))))
7981 (if (match-end 5) (setq re (concat re "[ \t]+"
7982 (regexp-quote
7983 (match-string 5)))))
7984 (setq re (concat re "[ \t]*$"))
7985 (when org-refile-use-outline-path
7986 (setq txt (mapconcat 'org-protect-slash
7987 (append
7988 (if (eq org-refile-use-outline-path 'file)
7989 (list (file-name-nondirectory
7990 (buffer-file-name (buffer-base-buffer))))
7991 (if (eq org-refile-use-outline-path 'full-file-path)
7992 (list (buffer-file-name (buffer-base-buffer)))))
7993 (org-get-outline-path fast-path-p level txt)
7994 (list txt))
7995 "/")))
7996 (push (list txt f re (point)) targets))
7997 (goto-char (point-at-eol))))))))
7998 (message "Getting targets...done")
7999 (nreverse targets))))
8001 (defun org-protect-slash (s)
8002 (while (string-match "/" s)
8003 (setq s (replace-match "\\" t t s)))
8006 (defvar org-olpa (make-vector 20 nil))
8008 (defun org-get-outline-path (&optional fastp level heading)
8009 "Return the outline path to the current entry, as a list."
8010 (if fastp
8011 (progn
8012 (if (> level 19)
8013 (error "Outline path failure, more than 19 levels."))
8014 (loop for i from level upto 19 do
8015 (aset org-olpa i nil))
8016 (prog1
8017 (delq nil (append org-olpa nil))
8018 (aset org-olpa level heading)))
8019 (let (rtn)
8020 (save-excursion
8021 (while (org-up-heading-safe)
8022 (when (looking-at org-complex-heading-regexp)
8023 (push (org-match-string-no-properties 4) rtn)))
8024 rtn))))
8026 (defvar org-refile-history nil
8027 "History for refiling operations.")
8029 (defun org-refile (&optional goto default-buffer)
8030 "Move the entry at point to another heading.
8031 The list of target headings is compiled using the information in
8032 `org-refile-targets', which see. This list is created before each use
8033 and will therefore always be up-to-date.
8035 At the target location, the entry is filed as a subitem of the target heading.
8036 Depending on `org-reverse-note-order', the new subitem will either be the
8037 first or the last subitem.
8039 If there is an active region, all entries in that region will be moved.
8040 However, the region must fulfil the requirement that the first heading
8041 is the first one sets the top-level of the moved text - at most siblings
8042 below it are allowed.
8044 With prefix arg GOTO, the command will only visit the target location,
8045 not actually move anything.
8046 With a double prefix `C-u C-u', go to the location where the last refiling
8047 operation has put the subtree."
8048 (interactive "P")
8049 (let* ((cbuf (current-buffer))
8050 (regionp (org-region-active-p))
8051 (region-start (and regionp (region-beginning)))
8052 (region-end (and regionp (region-end)))
8053 (region-length (and regionp (- region-end region-start)))
8054 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8055 pos it nbuf file re level reversed)
8056 (when regionp (goto-char region-start)
8057 (unless (org-kill-is-subtree-p
8058 (buffer-substring region-start region-end))
8059 (error "The region is not a (sequence of) subtree(s)")))
8060 (if (equal goto '(16))
8061 (org-refile-goto-last-stored)
8062 (when (setq it (org-refile-get-location
8063 (if goto "Goto: " "Refile to: ") default-buffer))
8064 (setq file (nth 1 it)
8065 re (nth 2 it)
8066 pos (nth 3 it))
8067 (if (and (equal (buffer-file-name) file)
8068 (if regionp
8069 (and (>= pos region-start)
8070 (<= pos region-end))
8071 (and (>= pos (point))
8072 (< pos (save-excursion
8073 (org-end-of-subtree t t))))))
8074 (error "Cannot refile to position inside the tree or region"))
8076 (setq nbuf (or (find-buffer-visiting file)
8077 (find-file-noselect file)))
8078 (if goto
8079 (progn
8080 (switch-to-buffer nbuf)
8081 (goto-char pos)
8082 (org-show-context 'org-goto))
8083 (if regionp
8084 (progn
8085 (kill-new (buffer-substring region-start region-end))
8086 (org-save-markers-in-region region-start region-end))
8087 (org-copy-subtree 1 nil t))
8088 (save-excursion
8089 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8090 (find-file-noselect file))))
8091 (setq reversed (org-notes-order-reversed-p))
8092 (save-excursion
8093 (save-restriction
8094 (widen)
8095 (goto-char pos)
8096 (looking-at outline-regexp)
8097 (setq level (org-get-valid-level (funcall outline-level) 1))
8098 (goto-char
8099 (if reversed
8100 (or (outline-next-heading) (point-max))
8101 (or (save-excursion (outline-get-next-sibling))
8102 (org-end-of-subtree t t)
8103 (point-max))))
8104 (if (not (bolp)) (newline))
8105 (bookmark-set "org-refile-last-stored")
8106 (org-paste-subtree level))))
8107 (if regionp
8108 (delete-region (point) (+ (point) region-length))
8109 (org-cut-subtree))
8110 (setq org-markers-to-move nil)
8111 (message "Refiled to \"%s\"" (car it)))))))
8113 (defun org-refile-goto-last-stored ()
8114 "Go to the location where the last refile was stored."
8115 (interactive)
8116 (bookmark-jump "org-refile-last-stored")
8117 (message "This is the location of the last refile"))
8119 (defun org-refile-get-location (&optional prompt default-buffer)
8120 "Prompt the user for a refile location, using PROMPT."
8121 (let ((org-refile-targets org-refile-targets)
8122 (org-refile-use-outline-path org-refile-use-outline-path))
8123 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8124 (unless org-refile-target-table
8125 (error "No refile targets"))
8126 (let* ((cbuf (current-buffer))
8127 (partial-completion-mode nil)
8128 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8129 (cfunc (if (and org-refile-use-outline-path
8130 org-outline-path-complete-in-steps)
8131 'org-olpath-completing-read
8132 'org-ido-completing-read))
8133 (extra (if org-refile-use-outline-path "/" ""))
8134 (filename (and cfn (expand-file-name cfn)))
8135 (tbl (mapcar
8136 (lambda (x)
8137 (if (not (equal filename (nth 1 x)))
8138 (cons (concat (car x) extra " ("
8139 (file-name-nondirectory (nth 1 x)) ")")
8140 (cdr x))
8141 (cons (concat (car x) extra) (cdr x))))
8142 org-refile-target-table))
8143 (completion-ignore-case t))
8144 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8145 tbl)))
8147 (defun org-olpath-completing-read (prompt collection &rest args)
8148 "Read an outline path like a file name."
8149 (let ((thetable collection)
8150 (org-completion-use-ido nil)) ; does not work with ido.
8151 (apply
8152 'org-ido-completing-read prompt
8153 (lambda (string predicate &optional flag)
8154 (let (rtn r f (l (length string)))
8155 (cond
8156 ((eq flag nil)
8157 ;; try completion
8158 (try-completion string thetable))
8159 ((eq flag t)
8160 ;; all-completions
8161 (setq rtn (all-completions string thetable predicate))
8162 (mapcar
8163 (lambda (x)
8164 (setq r (substring x l))
8165 (if (string-match " ([^)]*)$" x)
8166 (setq f (match-string 0 x))
8167 (setq f ""))
8168 (if (string-match "/" r)
8169 (concat string (substring r 0 (match-end 0)) f)
8171 rtn))
8172 ((eq flag 'lambda)
8173 ;; exact match?
8174 (assoc string thetable)))
8176 args)))
8178 ;;;; Dynamic blocks
8180 (defun org-find-dblock (name)
8181 "Find the first dynamic block with name NAME in the buffer.
8182 If not found, stay at current position and return nil."
8183 (let (pos)
8184 (save-excursion
8185 (goto-char (point-min))
8186 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8187 nil t)
8188 (match-beginning 0))))
8189 (if pos (goto-char pos))
8190 pos))
8192 (defconst org-dblock-start-re
8193 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8194 "Matches the startline of a dynamic block, with parameters.")
8196 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8197 "Matches the end of a dynamic block.")
8199 (defun org-create-dblock (plist)
8200 "Create a dynamic block section, with parameters taken from PLIST.
8201 PLIST must contain a :name entry which is used as name of the block."
8202 (unless (bolp) (newline))
8203 (let ((name (plist-get plist :name)))
8204 (insert "#+BEGIN: " name)
8205 (while plist
8206 (if (eq (car plist) :name)
8207 (setq plist (cddr plist))
8208 (insert " " (prin1-to-string (pop plist)))))
8209 (insert "\n\n#+END:\n")
8210 (beginning-of-line -2)))
8212 (defun org-prepare-dblock ()
8213 "Prepare dynamic block for refresh.
8214 This empties the block, puts the cursor at the insert position and returns
8215 the property list including an extra property :name with the block name."
8216 (unless (looking-at org-dblock-start-re)
8217 (error "Not at a dynamic block"))
8218 (let* ((begdel (1+ (match-end 0)))
8219 (name (org-no-properties (match-string 1)))
8220 (params (append (list :name name)
8221 (read (concat "(" (match-string 3) ")")))))
8222 (unless (re-search-forward org-dblock-end-re nil t)
8223 (error "Dynamic block not terminated"))
8224 (setq params
8225 (append params
8226 (list :content (buffer-substring
8227 begdel (match-beginning 0)))))
8228 (delete-region begdel (match-beginning 0))
8229 (goto-char begdel)
8230 (open-line 1)
8231 params))
8233 (defun org-map-dblocks (&optional command)
8234 "Apply COMMAND to all dynamic blocks in the current buffer.
8235 If COMMAND is not given, use `org-update-dblock'."
8236 (let ((cmd (or command 'org-update-dblock))
8237 pos)
8238 (save-excursion
8239 (goto-char (point-min))
8240 (while (re-search-forward org-dblock-start-re nil t)
8241 (goto-char (setq pos (match-beginning 0)))
8242 (condition-case nil
8243 (funcall cmd)
8244 (error (message "Error during update of dynamic block")))
8245 (goto-char pos)
8246 (unless (re-search-forward org-dblock-end-re nil t)
8247 (error "Dynamic block not terminated"))))))
8249 (defun org-dblock-update (&optional arg)
8250 "User command for updating dynamic blocks.
8251 Update the dynamic block at point. With prefix ARG, update all dynamic
8252 blocks in the buffer."
8253 (interactive "P")
8254 (if arg
8255 (org-update-all-dblocks)
8256 (or (looking-at org-dblock-start-re)
8257 (org-beginning-of-dblock))
8258 (org-update-dblock)))
8260 (defun org-update-dblock ()
8261 "Update the dynamic block at point
8262 This means to empty the block, parse for parameters and then call
8263 the correct writing function."
8264 (save-window-excursion
8265 (let* ((pos (point))
8266 (line (org-current-line))
8267 (params (org-prepare-dblock))
8268 (name (plist-get params :name))
8269 (cmd (intern (concat "org-dblock-write:" name))))
8270 (message "Updating dynamic block `%s' at line %d..." name line)
8271 (funcall cmd params)
8272 (message "Updating dynamic block `%s' at line %d...done" name line)
8273 (goto-char pos))))
8275 (defun org-beginning-of-dblock ()
8276 "Find the beginning of the dynamic block at point.
8277 Error if there is no such block at point."
8278 (let ((pos (point))
8279 beg)
8280 (end-of-line 1)
8281 (if (and (re-search-backward org-dblock-start-re nil t)
8282 (setq beg (match-beginning 0))
8283 (re-search-forward org-dblock-end-re nil t)
8284 (> (match-end 0) pos))
8285 (goto-char beg)
8286 (goto-char pos)
8287 (error "Not in a dynamic block"))))
8289 (defun org-update-all-dblocks ()
8290 "Update all dynamic blocks in the buffer.
8291 This function can be used in a hook."
8292 (when (org-mode-p)
8293 (org-map-dblocks 'org-update-dblock)))
8296 ;;;; Completion
8298 (defconst org-additional-option-like-keywords
8299 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8300 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8301 "BEGIN_EXAMPLE" "END_EXAMPLE"
8302 "BEGIN_QUOTE" "END_QUOTE"
8303 "BEGIN_VERSE" "END_VERSE"
8304 "BEGIN_SRC" "END_SRC"
8305 "CATEGORY" "COLUMNS"
8306 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8308 (defcustom org-structure-template-alist
8310 ("s" "#+begin_src ?\n\n#+end_src"
8311 "<src lang=\"?\">\n\n</src>")
8312 ("e" "#+begin_example\n?\n#+end_example"
8313 "<example>\n?\n</example>")
8314 ("q" "#+begin_quote\n?\n#+end_quote"
8315 "<quote>\n?\n</quote>")
8316 ("v" "#+begin_verse\n?\n#+end_verse"
8317 "<verse>\n?\n/verse>")
8318 ("l" "#+begin_latex\n?\n#+end_latex"
8319 "<literal style=\"latex\">\n?\n</literal>")
8320 ("L" "#+latex: "
8321 "<literal style=\"latex\">?</literal>")
8322 ("h" "#+begin_html\n?\n#+end_html"
8323 "<literal style=\"html\">\n?\n</literal>")
8324 ("H" "#+html: "
8325 "<literal style=\"html\">?</literal>")
8326 ("a" "#+begin_ascii\n?\n#+end_ascii")
8327 ("A" "#+ascii: ")
8328 ("i" "#+include %file ?"
8329 "<include file=%file markup=\"?\">")
8331 "Structure completion elements.
8332 This is a list of abbreviation keys and values. The value gets inserted
8333 it you type @samp{.} followed by the key and then the completion key,
8334 usually `M-TAB'. %file will be replaced by a file name after prompting
8335 for the file using completion.
8336 There are two templates for each key, the first uses the original Org syntax,
8337 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8338 the default when the /org-mtags.el/ module has been loaded. See also the
8339 variable `org-mtags-prefer-muse-templates'.
8340 This is an experimental feature, it is undecided if it is going to stay in."
8341 :group 'org-completion
8342 :type '(repeat
8343 (string :tag "Key")
8344 (string :tag "Template")
8345 (string :tag "Muse Template")))
8347 (defun org-try-structure-completion ()
8348 "Try to complete a structure template before point.
8349 This looks for strings like \"<e\" on an otherwise empty line and
8350 expands them."
8351 (let ((l (buffer-substring (point-at-bol) (point)))
8353 (when (and (looking-at "[ \t]*$")
8354 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8355 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8356 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8357 (match-beginning 1)) a)
8358 t)))
8360 (defun org-complete-expand-structure-template (start cell)
8361 "Expand a structure template."
8362 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8363 (rpl (nth (if musep 2 1) cell)))
8364 (delete-region start (point))
8365 (when (string-match "\\`#\\+" rpl)
8366 (cond
8367 ((bolp))
8368 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8369 (delete-region (point-at-bol) (point)))
8370 (t (newline))))
8371 (setq start (point))
8372 (if (string-match "%file" rpl)
8373 (setq rpl (replace-match
8374 (concat
8375 "\""
8376 (save-match-data
8377 (abbreviate-file-name (read-file-name "Include file: ")))
8378 "\"")
8379 t t rpl)))
8380 (insert rpl)
8381 (if (re-search-backward "\\?" start t) (delete-char 1))))
8384 (defun org-complete (&optional arg)
8385 "Perform completion on word at point.
8386 At the beginning of a headline, this completes TODO keywords as given in
8387 `org-todo-keywords'.
8388 If the current word is preceded by a backslash, completes the TeX symbols
8389 that are supported for HTML support.
8390 If the current word is preceded by \"#+\", completes special words for
8391 setting file options.
8392 In the line after \"#+STARTUP:, complete valid keywords.\"
8393 At all other locations, this simply calls the value of
8394 `org-completion-fallback-command'."
8395 (interactive "P")
8396 (org-without-partial-completion
8397 (catch 'exit
8398 (let* ((a nil)
8399 (end (point))
8400 (beg1 (save-excursion
8401 (skip-chars-backward (org-re "[:alnum:]_@"))
8402 (point)))
8403 (beg (save-excursion
8404 (skip-chars-backward "a-zA-Z0-9_:$")
8405 (point)))
8406 (confirm (lambda (x) (stringp (car x))))
8407 (searchhead (equal (char-before beg) ?*))
8408 (struct
8409 (when (and (member (char-before beg1) '(?. ?<))
8410 (setq a (assoc (buffer-substring beg1 (point))
8411 org-structure-template-alist)))
8412 (org-complete-expand-structure-template (1- beg1) a)
8413 (throw 'exit t)))
8414 (tag (and (equal (char-before beg1) ?:)
8415 (equal (char-after (point-at-bol)) ?*)))
8416 (prop (and (equal (char-before beg1) ?:)
8417 (not (equal (char-after (point-at-bol)) ?*))))
8418 (texp (equal (char-before beg) ?\\))
8419 (link (equal (char-before beg) ?\[))
8420 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8421 beg)
8422 "#+"))
8423 (startup (string-match "^#\\+STARTUP:.*"
8424 (buffer-substring (point-at-bol) (point))))
8425 (completion-ignore-case opt)
8426 (type nil)
8427 (tbl nil)
8428 (table (cond
8429 (opt
8430 (setq type :opt)
8431 (require 'org-exp)
8432 (append
8433 (mapcar
8434 (lambda (x)
8435 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8436 (cons (match-string 2 x) (match-string 1 x)))
8437 (org-split-string (org-get-current-options) "\n"))
8438 (mapcar 'list org-additional-option-like-keywords)))
8439 (startup
8440 (setq type :startup)
8441 org-startup-options)
8442 (link (append org-link-abbrev-alist-local
8443 org-link-abbrev-alist))
8444 (texp
8445 (setq type :tex)
8446 org-html-entities)
8447 ((string-match "\\`\\*+[ \t]+\\'"
8448 (buffer-substring (point-at-bol) beg))
8449 (setq type :todo)
8450 (mapcar 'list org-todo-keywords-1))
8451 (searchhead
8452 (setq type :searchhead)
8453 (save-excursion
8454 (goto-char (point-min))
8455 (while (re-search-forward org-todo-line-regexp nil t)
8456 (push (list
8457 (org-make-org-heading-search-string
8458 (match-string 3) t))
8459 tbl)))
8460 tbl)
8461 (tag (setq type :tag beg beg1)
8462 (or org-tag-alist (org-get-buffer-tags)))
8463 (prop (setq type :prop beg beg1)
8464 (mapcar 'list (org-buffer-property-keys nil t t)))
8465 (t (progn
8466 (call-interactively org-completion-fallback-command)
8467 (throw 'exit nil)))))
8468 (pattern (buffer-substring-no-properties beg end))
8469 (completion (try-completion pattern table confirm)))
8470 (cond ((eq completion t)
8471 (if (not (assoc (upcase pattern) table))
8472 (message "Already complete")
8473 (if (and (equal type :opt)
8474 (not (member (car (assoc (upcase pattern) table))
8475 org-additional-option-like-keywords)))
8476 (insert (substring (cdr (assoc (upcase pattern) table))
8477 (length pattern)))
8478 (if (memq type '(:tag :prop)) (insert ":")))))
8479 ((null completion)
8480 (message "Can't find completion for \"%s\"" pattern)
8481 (ding))
8482 ((not (string= pattern completion))
8483 (delete-region beg end)
8484 (if (string-match " +$" completion)
8485 (setq completion (replace-match "" t t completion)))
8486 (insert completion)
8487 (if (get-buffer-window "*Completions*")
8488 (delete-window (get-buffer-window "*Completions*")))
8489 (if (assoc completion table)
8490 (if (eq type :todo) (insert " ")
8491 (if (memq type '(:tag :prop)) (insert ":"))))
8492 (if (and (equal type :opt) (assoc completion table))
8493 (message "%s" (substitute-command-keys
8494 "Press \\[org-complete] again to insert example settings"))))
8496 (message "Making completion list...")
8497 (let ((list (sort (all-completions pattern table confirm)
8498 'string<)))
8499 (with-output-to-temp-buffer "*Completions*"
8500 (condition-case nil
8501 ;; Protection needed for XEmacs and emacs 21
8502 (display-completion-list list pattern)
8503 (error (display-completion-list list)))))
8504 (message "Making completion list...%s" "done")))))))
8506 ;;;; TODO, DEADLINE, Comments
8508 (defun org-toggle-comment ()
8509 "Change the COMMENT state of an entry."
8510 (interactive)
8511 (save-excursion
8512 (org-back-to-heading)
8513 (let (case-fold-search)
8514 (if (looking-at (concat outline-regexp
8515 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8516 (replace-match "" t t nil 1)
8517 (if (looking-at outline-regexp)
8518 (progn
8519 (goto-char (match-end 0))
8520 (insert org-comment-string " ")))))))
8522 (defvar org-last-todo-state-is-todo nil
8523 "This is non-nil when the last TODO state change led to a TODO state.
8524 If the last change removed the TODO tag or switched to DONE, then
8525 this is nil.")
8527 (defvar org-setting-tags nil) ; dynamically skipped
8529 (defun org-parse-local-options (string var)
8530 "Parse STRING for startup setting relevant for variable VAR."
8531 (let ((rtn (symbol-value var))
8532 e opts)
8533 (save-match-data
8534 (if (or (not string) (not (string-match "\\S-" string)))
8536 (setq opts (delq nil (mapcar (lambda (x)
8537 (setq e (assoc x org-startup-options))
8538 (if (eq (nth 1 e) var) e nil))
8539 (org-split-string string "[ \t]+"))))
8540 (if (not opts)
8542 (setq rtn nil)
8543 (while (setq e (pop opts))
8544 (if (not (nth 3 e))
8545 (setq rtn (nth 2 e))
8546 (if (not (listp rtn)) (setq rtn nil))
8547 (push (nth 2 e) rtn)))
8548 rtn)))))
8550 (defvar org-todo-setup-filter-hook nil
8551 "Hook for functions that pre-filter todo specs.
8553 Each function takes a todo spec and returns either `nil' or the spec
8554 transformed into canonical form." )
8556 (defvar org-todo-get-default-hook nil
8557 "Hook for functions that get a default item for todo.
8559 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8560 `nil' or a string to be used for the todo mark." )
8562 (defvar org-agenda-headline-snapshot-before-repeat)
8563 (defun org-todo (&optional arg)
8564 "Change the TODO state of an item.
8565 The state of an item is given by a keyword at the start of the heading,
8566 like
8567 *** TODO Write paper
8568 *** DONE Call mom
8570 The different keywords are specified in the variable `org-todo-keywords'.
8571 By default the available states are \"TODO\" and \"DONE\".
8572 So for this example: when the item starts with TODO, it is changed to DONE.
8573 When it starts with DONE, the DONE is removed. And when neither TODO nor
8574 DONE are present, add TODO at the beginning of the heading.
8576 With C-u prefix arg, use completion to determine the new state.
8577 With numeric prefix arg, switch to that state.
8578 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8579 With a tripple C-u prefix, circumvent any state blocking.
8581 For calling through lisp, arg is also interpreted in the following way:
8582 'none -> empty state
8583 \"\"(empty string) -> switch to empty state
8584 'done -> switch to DONE
8585 'nextset -> switch to the next set of keywords
8586 'previousset -> switch to the previous set of keywords
8587 \"WAITING\" -> switch to the specified keyword, but only if it
8588 really is a member of `org-todo-keywords'."
8589 (interactive "P")
8590 (if (equal arg '(16)) (setq arg 'nextset))
8591 (let ((org-blocker-hook org-blocker-hook))
8592 (when (equal arg '(64))
8593 (setq arg nil org-blocker-hook nil))
8594 (save-excursion
8595 (catch 'exit
8596 (org-back-to-heading)
8597 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8598 (or (looking-at (concat " +" org-todo-regexp " *"))
8599 (looking-at " *"))
8600 (let* ((match-data (match-data))
8601 (startpos (point-at-bol))
8602 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8603 (org-log-done org-log-done)
8604 (org-log-repeat org-log-repeat)
8605 (org-todo-log-states org-todo-log-states)
8606 (this (match-string 1))
8607 (hl-pos (match-beginning 0))
8608 (head (org-get-todo-sequence-head this))
8609 (ass (assoc head org-todo-kwd-alist))
8610 (interpret (nth 1 ass))
8611 (done-word (nth 3 ass))
8612 (final-done-word (nth 4 ass))
8613 (last-state (or this ""))
8614 (completion-ignore-case t)
8615 (member (member this org-todo-keywords-1))
8616 (tail (cdr member))
8617 (state (cond
8618 ((and org-todo-key-trigger
8619 (or (and (equal arg '(4))
8620 (eq org-use-fast-todo-selection 'prefix))
8621 (and (not arg) org-use-fast-todo-selection
8622 (not (eq org-use-fast-todo-selection
8623 'prefix)))))
8624 ;; Use fast selection
8625 (org-fast-todo-selection))
8626 ((and (equal arg '(4))
8627 (or (not org-use-fast-todo-selection)
8628 (not org-todo-key-trigger)))
8629 ;; Read a state with completion
8630 (org-ido-completing-read
8631 "State: " (mapcar (lambda(x) (list x))
8632 org-todo-keywords-1)
8633 nil t))
8634 ((eq arg 'right)
8635 (if this
8636 (if tail (car tail) nil)
8637 (car org-todo-keywords-1)))
8638 ((eq arg 'left)
8639 (if (equal member org-todo-keywords-1)
8641 (if this
8642 (nth (- (length org-todo-keywords-1)
8643 (length tail) 2)
8644 org-todo-keywords-1)
8645 (org-last org-todo-keywords-1))))
8646 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8647 (setq arg nil))) ; hack to fall back to cycling
8648 (arg
8649 ;; user or caller requests a specific state
8650 (cond
8651 ((equal arg "") nil)
8652 ((eq arg 'none) nil)
8653 ((eq arg 'done) (or done-word (car org-done-keywords)))
8654 ((eq arg 'nextset)
8655 (or (car (cdr (member head org-todo-heads)))
8656 (car org-todo-heads)))
8657 ((eq arg 'previousset)
8658 (let ((org-todo-heads (reverse org-todo-heads)))
8659 (or (car (cdr (member head org-todo-heads)))
8660 (car org-todo-heads))))
8661 ((car (member arg org-todo-keywords-1)))
8662 ((nth (1- (prefix-numeric-value arg))
8663 org-todo-keywords-1))))
8664 ((null member) (or head (car org-todo-keywords-1)))
8665 ((equal this final-done-word) nil) ;; -> make empty
8666 ((null tail) nil) ;; -> first entry
8667 ((memq interpret '(type priority))
8668 (if (eq this-command last-command)
8669 (car tail)
8670 (if (> (length tail) 0)
8671 (or done-word (car org-done-keywords))
8672 nil)))
8674 (car tail))))
8675 (state (or
8676 (run-hook-with-args-until-success
8677 'org-todo-get-default-hook state last-state)
8678 state))
8679 (next (if state (concat " " state " ") " "))
8680 (change-plist (list :type 'todo-state-change :from this :to state
8681 :position startpos))
8682 dolog now-done-p)
8683 (when org-blocker-hook
8684 (setq org-last-todo-state-is-todo
8685 (not (member this org-done-keywords)))
8686 (unless (save-excursion
8687 (save-match-data
8688 (run-hook-with-args-until-failure
8689 'org-blocker-hook change-plist)))
8690 (if (interactive-p)
8691 (error "TODO state change from %s to %s blocked" this state)
8692 ;; fail silently
8693 (message "TODO state change from %s to %s blocked" this state)
8694 (throw 'exit nil))))
8695 (store-match-data match-data)
8696 (replace-match next t t)
8697 (unless (pos-visible-in-window-p hl-pos)
8698 (message "TODO state changed to %s" (org-trim next)))
8699 (unless head
8700 (setq head (org-get-todo-sequence-head state)
8701 ass (assoc head org-todo-kwd-alist)
8702 interpret (nth 1 ass)
8703 done-word (nth 3 ass)
8704 final-done-word (nth 4 ass)))
8705 (when (memq arg '(nextset previousset))
8706 (message "Keyword-Set %d/%d: %s"
8707 (- (length org-todo-sets) -1
8708 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8709 (length org-todo-sets)
8710 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8711 (setq org-last-todo-state-is-todo
8712 (not (member state org-done-keywords)))
8713 (setq now-done-p (and (member state org-done-keywords)
8714 (not (member this org-done-keywords))))
8715 (and logging (org-local-logging logging))
8716 (when (and (or org-todo-log-states org-log-done)
8717 (not (memq arg '(nextset previousset))))
8718 ;; we need to look at recording a time and note
8719 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8720 (nth 2 (assoc this org-todo-log-states))))
8721 (when (and state
8722 (member state org-not-done-keywords)
8723 (not (member this org-not-done-keywords)))
8724 ;; This is now a todo state and was not one before
8725 ;; If there was a CLOSED time stamp, get rid of it.
8726 (org-add-planning-info nil nil 'closed))
8727 (when (and now-done-p org-log-done)
8728 ;; It is now done, and it was not done before
8729 (org-add-planning-info 'closed (org-current-time))
8730 (if (and (not dolog) (eq 'note org-log-done))
8731 (org-add-log-setup 'done state this 'findpos 'note)))
8732 (when (and state dolog)
8733 ;; This is a non-nil state, and we need to log it
8734 (org-add-log-setup 'state state this 'findpos dolog)))
8735 ;; Fixup tag positioning
8736 (org-todo-trigger-tag-changes state)
8737 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8738 (when org-provide-todo-statistics
8739 (org-update-parent-todo-statistics))
8740 (run-hooks 'org-after-todo-state-change-hook)
8741 (if (and arg (not (member state org-done-keywords)))
8742 (setq head (org-get-todo-sequence-head state)))
8743 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8744 ;; Do we need to trigger a repeat?
8745 (when now-done-p
8746 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8747 ;; This is for the agenda, take a snapshot of the headline.
8748 (save-match-data
8749 (setq org-agenda-headline-snapshot-before-repeat
8750 (org-get-heading))))
8751 (org-auto-repeat-maybe state))
8752 ;; Fixup cursor location if close to the keyword
8753 (if (and (outline-on-heading-p)
8754 (not (bolp))
8755 (save-excursion (beginning-of-line 1)
8756 (looking-at org-todo-line-regexp))
8757 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8758 (progn
8759 (goto-char (or (match-end 2) (match-end 1)))
8760 (just-one-space)))
8761 (when org-trigger-hook
8762 (save-excursion
8763 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8765 (defun org-block-todo-from-children-or-siblings (change-plist)
8766 "Block turning an entry into a TODO, using the hierarchy.
8767 This checks whether the current task should be blocked from state
8768 changes. Such blocking occurs when:
8770 1. The task has children which are not all in a completed state.
8772 2. A task has a parent with the property :ORDERED:, and there
8773 are siblings prior to the current task with incomplete
8774 status."
8775 (catch 'dont-block
8776 ;; If this is not a todo state change, or if this entry is already DONE,
8777 ;; do not block
8778 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8779 (member (plist-get change-plist :from)
8780 (cons 'done org-done-keywords))
8781 (member (plist-get change-plist :to)
8782 (cons 'todo org-not-done-keywords)))
8783 (throw 'dont-block t))
8784 ;; If this task has children, and any are undone, it's blocked
8785 (save-excursion
8786 (org-back-to-heading t)
8787 (let ((this-level (funcall outline-level)))
8788 (outline-next-heading)
8789 (let ((child-level (funcall outline-level)))
8790 (while (and (not (eobp))
8791 (> child-level this-level))
8792 ;; this todo has children, check whether they are all
8793 ;; completed
8794 (if (and (not (org-entry-is-done-p))
8795 (org-entry-is-todo-p))
8796 (throw 'dont-block nil))
8797 (outline-next-heading)
8798 (setq child-level (funcall outline-level))))))
8799 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8800 ;; any previous siblings are undone, it's blocked
8801 (save-excursion
8802 (org-back-to-heading t)
8803 (when (save-excursion
8804 (ignore-errors
8805 (org-up-heading-all 1)
8806 (org-entry-get (point) "ORDERED")))
8807 (let* ((this-level (funcall outline-level))
8808 (current-level this-level))
8809 (while (and (not (bobp))
8810 (= current-level this-level))
8811 (outline-previous-heading)
8812 (setq current-level (funcall outline-level))
8813 (if (= current-level this-level)
8814 ;; this todo has children, check whether they are all
8815 ;; completed
8816 (if (and (not (org-entry-is-done-p))
8817 (org-entry-is-todo-p))
8818 (throw 'dont-block nil)))))))
8819 t)) ; don't block
8821 (defcustom org-track-ordered-property-with-tag nil
8822 "Should the ORDERED property also be shown as a tag?
8823 The ORDERED property decides if an entry should require subtasks to be
8824 completed in sequence. Since a property is not very visible, setting
8825 this option means that toggling the ORDERED property with the command
8826 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
8827 not relevant for the behavior, but it makes things more visible.
8829 Note that toggling the tag with tags commands will not change the property
8830 and therefore not influence behavior!
8832 This can be t, meaning the tag ORDERED should be used, It can also be a
8833 string to select a different tag for this task."
8834 :group 'org-todo
8835 :type '(choice
8836 (const :tag "No tracking" nil)
8837 (const :tag "Track with ORDERED tag" t)
8838 (string :tag "Use other tag")))
8840 (defun org-toggle-ordered-property ()
8841 "Toggle the ORDERED property of the current entry.
8842 For better visibility, you can track the value of this property with a tag.
8843 See variable `org-track-ordered-property-with-tag'."
8844 (interactive)
8845 (let* ((t1 org-track-ordered-property-with-tag)
8846 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
8847 (save-excursion
8848 (org-back-to-heading)
8849 (if (org-entry-get nil "ORDERED")
8850 (progn
8851 (org-delete-property "ORDERED")
8852 (and tag (org-toggle-tag tag 'off))
8853 (message "Subtasks can be completed in arbitrary order"))
8854 (org-entry-put nil "ORDERED" "t")
8855 (and tag (org-toggle-tag tag 'on))
8856 (message "Subtasks must be completed in sequence")))))
8858 (defvar org-blocked-by-checkboxes) ; dynamically scoped
8859 (defun org-block-todo-from-checkboxes (change-plist)
8860 "Block turning an entry into a TODO, using checkboxes.
8861 This checks whether the current task should be blocked from state
8862 changes because there are uncheckd boxes in this entry."
8863 (catch 'dont-block
8864 ;; If this is not a todo state change, or if this entry is already DONE,
8865 ;; do not block
8866 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8867 (member (plist-get change-plist :from)
8868 (cons 'done org-done-keywords))
8869 (member (plist-get change-plist :to)
8870 (cons 'todo org-not-done-keywords)))
8871 (throw 'dont-block t))
8872 ;; If this task has checkboxes that are not checked, it's blocked
8873 (save-excursion
8874 (org-back-to-heading t)
8875 (let ((beg (point)) end)
8876 (outline-next-heading)
8877 (setq end (point))
8878 (goto-char beg)
8879 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8880 end t)
8881 (progn
8882 (if (boundp 'org-blocked-by-checkboxes)
8883 (setq org-blocked-by-checkboxes t))
8884 (throw 'dont-block nil)))))
8885 t)) ; do not block
8887 (defun org-update-parent-todo-statistics ()
8888 "Update any statistics cookie in the parent of the current headline."
8889 (interactive)
8890 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8891 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
8892 (catch 'exit
8893 (save-excursion
8894 (setq level (org-up-heading-safe))
8895 (unless level
8896 (throw 'exit nil))
8897 (while (re-search-forward box-re (point-at-eol) t)
8898 (setq cnt-all 0 cnt-done 0 cookie-present t)
8899 (setq is-percent (match-end 2))
8900 (save-match-data
8901 (unless (outline-next-heading) (throw 'exit nil))
8902 (while (looking-at org-todo-line-regexp)
8903 (setq kwd (match-string 2))
8904 (and kwd (setq cnt-all (1+ cnt-all)))
8905 (and (member kwd org-done-keywords)
8906 (setq cnt-done (1+ cnt-done)))
8907 (condition-case nil
8908 (org-forward-same-level 1)
8909 (error (end-of-line 1)))))
8910 (replace-match
8911 (if is-percent
8912 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8913 (format "[%d/%d]" cnt-done cnt-all))))
8914 (when cookie-present
8915 (run-hook-with-args 'org-after-todo-statistics-hook
8916 cnt-done (- cnt-all cnt-done)))))))
8918 (defvar org-after-todo-statistics-hook nil
8919 "Hook that is called after a TODO statistics cookie has been updated.
8920 Each function is called with two arguments: the number of not-done entries
8921 and the number of done entries.
8923 For example, the following function, when added to this hook, will switch
8924 an entry to DONE when all children are done, and back to TODO when new
8925 entries are set to a TODO status. Note that this hook is only called
8926 when there is a statistics cookie in the headline!
8928 (defun org-summary-todo (n-done n-not-done)
8929 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8930 (let (org-log-done org-log-states) ; turn off logging
8931 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8934 (defun org-todo-trigger-tag-changes (state)
8935 "Apply the changes defined in `org-todo-state-tags-triggers'."
8936 (let ((l org-todo-state-tags-triggers)
8937 changes)
8938 (when (or (not state) (equal state ""))
8939 (setq changes (append changes (cdr (assoc "" l)))))
8940 (when (and (stringp state) (> (length state) 0))
8941 (setq changes (append changes (cdr (assoc state l)))))
8942 (when (member state org-not-done-keywords)
8943 (setq changes (append changes (cdr (assoc 'todo l)))))
8944 (when (member state org-done-keywords)
8945 (setq changes (append changes (cdr (assoc 'done l)))))
8946 (dolist (c changes)
8947 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8949 (defun org-local-logging (value)
8950 "Get logging settings from a property VALUE."
8951 (let* (words w a)
8952 ;; directly set the variables, they are already local.
8953 (setq org-log-done nil
8954 org-log-repeat nil
8955 org-todo-log-states nil)
8956 (setq words (org-split-string value))
8957 (while (setq w (pop words))
8958 (cond
8959 ((setq a (assoc w org-startup-options))
8960 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8961 (set (nth 1 a) (nth 2 a))))
8962 ((setq a (org-extract-log-state-settings w))
8963 (and (member (car a) org-todo-keywords-1)
8964 (push a org-todo-log-states)))))))
8966 (defun org-get-todo-sequence-head (kwd)
8967 "Return the head of the TODO sequence to which KWD belongs.
8968 If KWD is not set, check if there is a text property remembering the
8969 right sequence."
8970 (let (p)
8971 (cond
8972 ((not kwd)
8973 (or (get-text-property (point-at-bol) 'org-todo-head)
8974 (progn
8975 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8976 nil (point-at-eol)))
8977 (get-text-property p 'org-todo-head))))
8978 ((not (member kwd org-todo-keywords-1))
8979 (car org-todo-keywords-1))
8980 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8982 (defun org-fast-todo-selection ()
8983 "Fast TODO keyword selection with single keys.
8984 Returns the new TODO keyword, or nil if no state change should occur."
8985 (let* ((fulltable org-todo-key-alist)
8986 (done-keywords org-done-keywords) ;; needed for the faces.
8987 (maxlen (apply 'max (mapcar
8988 (lambda (x)
8989 (if (stringp (car x)) (string-width (car x)) 0))
8990 fulltable)))
8991 (expert nil)
8992 (fwidth (+ maxlen 3 1 3))
8993 (ncol (/ (- (window-width) 4) fwidth))
8994 tg cnt e c tbl
8995 groups ingroup)
8996 (save-excursion
8997 (save-window-excursion
8998 (if expert
8999 (set-buffer (get-buffer-create " *Org todo*"))
9000 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9001 (erase-buffer)
9002 (org-set-local 'org-done-keywords done-keywords)
9003 (setq tbl fulltable cnt 0)
9004 (while (setq e (pop tbl))
9005 (cond
9006 ((equal e '(:startgroup))
9007 (push '() groups) (setq ingroup t)
9008 (when (not (= cnt 0))
9009 (setq cnt 0)
9010 (insert "\n"))
9011 (insert "{ "))
9012 ((equal e '(:endgroup))
9013 (setq ingroup nil cnt 0)
9014 (insert "}\n"))
9015 ((equal e '(:newline))
9016 (when (not (= cnt 0))
9017 (setq cnt 0)
9018 (insert "\n")
9019 (setq e (car tbl))
9020 (while (equal (car tbl) '(:newline))
9021 (insert "\n")
9022 (setq tbl (cdr tbl)))))
9024 (setq tg (car e) c (cdr e))
9025 (if ingroup (push tg (car groups)))
9026 (setq tg (org-add-props tg nil 'face
9027 (org-get-todo-face tg)))
9028 (if (and (= cnt 0) (not ingroup)) (insert " "))
9029 (insert "[" c "] " tg (make-string
9030 (- fwidth 4 (length tg)) ?\ ))
9031 (when (= (setq cnt (1+ cnt)) ncol)
9032 (insert "\n")
9033 (if ingroup (insert " "))
9034 (setq cnt 0)))))
9035 (insert "\n")
9036 (goto-char (point-min))
9037 (if (not expert) (org-fit-window-to-buffer))
9038 (message "[a-z..]:Set [SPC]:clear")
9039 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9040 (cond
9041 ((or (= c ?\C-g)
9042 (and (= c ?q) (not (rassoc c fulltable))))
9043 (setq quit-flag t))
9044 ((= c ?\ ) nil)
9045 ((setq e (rassoc c fulltable) tg (car e))
9047 (t (setq quit-flag t)))))))
9049 (defun org-entry-is-todo-p ()
9050 (member (org-get-todo-state) org-not-done-keywords))
9052 (defun org-entry-is-done-p ()
9053 (member (org-get-todo-state) org-done-keywords))
9055 (defun org-get-todo-state ()
9056 (save-excursion
9057 (org-back-to-heading t)
9058 (and (looking-at org-todo-line-regexp)
9059 (match-end 2)
9060 (match-string 2))))
9062 (defun org-at-date-range-p (&optional inactive-ok)
9063 "Is the cursor inside a date range?"
9064 (interactive)
9065 (save-excursion
9066 (catch 'exit
9067 (let ((pos (point)))
9068 (skip-chars-backward "^[<\r\n")
9069 (skip-chars-backward "<[")
9070 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9071 (>= (match-end 0) pos)
9072 (throw 'exit t))
9073 (skip-chars-backward "^<[\r\n")
9074 (skip-chars-backward "<[")
9075 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9076 (>= (match-end 0) pos)
9077 (throw 'exit t)))
9078 nil)))
9080 (defun org-get-repeat ()
9081 "Check if there is a deadline/schedule with repeater in this entry."
9082 (save-match-data
9083 (save-excursion
9084 (org-back-to-heading t)
9085 (if (re-search-forward
9086 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9087 (match-string 1)))))
9089 (defvar org-last-changed-timestamp)
9090 (defvar org-last-inserted-timestamp)
9091 (defvar org-log-post-message)
9092 (defvar org-log-note-purpose)
9093 (defvar org-log-note-how)
9094 (defvar org-log-note-extra)
9095 (defun org-auto-repeat-maybe (done-word)
9096 "Check if the current headline contains a repeated deadline/schedule.
9097 If yes, set TODO state back to what it was and change the base date
9098 of repeating deadline/scheduled time stamps to new date.
9099 This function is run automatically after each state change to a DONE state."
9100 ;; last-state is dynamically scoped into this function
9101 (let* ((repeat (org-get-repeat))
9102 (aa (assoc last-state org-todo-kwd-alist))
9103 (interpret (nth 1 aa))
9104 (head (nth 2 aa))
9105 (whata '(("d" . day) ("m" . month) ("y" . year)))
9106 (msg "Entry repeats: ")
9107 (org-log-done nil)
9108 (org-todo-log-states nil)
9109 (nshiftmax 10) (nshift 0)
9110 re type n what ts time)
9111 (when repeat
9112 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9113 (org-todo (if (eq interpret 'type) last-state head))
9114 (when org-log-repeat
9115 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9116 (memq 'org-add-log-note post-command-hook))
9117 ;; OK, we are already setup for some record
9118 (if (eq org-log-repeat 'note)
9119 ;; make sure we take a note, not only a time stamp
9120 (setq org-log-note-how 'note))
9121 ;; Set up for taking a record
9122 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9123 last-state
9124 'findpos org-log-repeat)))
9125 (org-back-to-heading t)
9126 (org-add-planning-info nil nil 'closed)
9127 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9128 org-deadline-time-regexp "\\)\\|\\("
9129 org-ts-regexp "\\)"))
9130 (while (re-search-forward
9131 re (save-excursion (outline-next-heading) (point)) t)
9132 (setq type (if (match-end 1) org-scheduled-string
9133 (if (match-end 3) org-deadline-string "Plain:"))
9134 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9135 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9136 (setq n (string-to-number (match-string 2 ts))
9137 what (match-string 3 ts))
9138 (if (equal what "w") (setq n (* n 7) what "d"))
9139 ;; Preparation, see if we need to modify the start date for the change
9140 (when (match-end 1)
9141 (setq time (save-match-data (org-time-string-to-time ts)))
9142 (cond
9143 ((equal (match-string 1 ts) ".")
9144 ;; Shift starting date to today
9145 (org-timestamp-change
9146 (- (time-to-days (current-time)) (time-to-days time))
9147 'day))
9148 ((equal (match-string 1 ts) "+")
9149 (while (or (= nshift 0)
9150 (<= (time-to-days time) (time-to-days (current-time))))
9151 (when (= (incf nshift) nshiftmax)
9152 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9153 (error "Abort")))
9154 (org-timestamp-change n (cdr (assoc what whata)))
9155 (org-at-timestamp-p t)
9156 (setq ts (match-string 1))
9157 (setq time (save-match-data (org-time-string-to-time ts))))
9158 (org-timestamp-change (- n) (cdr (assoc what whata)))
9159 ;; rematch, so that we have everything in place for the real shift
9160 (org-at-timestamp-p t)
9161 (setq ts (match-string 1))
9162 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9163 (org-timestamp-change n (cdr (assoc what whata)))
9164 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9165 (setq org-log-post-message msg)
9166 (message "%s" msg))))
9168 (defun org-show-todo-tree (arg)
9169 "Make a compact tree which shows all headlines marked with TODO.
9170 The tree will show the lines where the regexp matches, and all higher
9171 headlines above the match.
9172 With a \\[universal-argument] prefix, also show the DONE entries.
9173 With a numeric prefix N, construct a sparse tree for the Nth element
9174 of `org-todo-keywords-1'."
9175 (interactive "P")
9176 (let ((case-fold-search nil)
9177 (kwd-re
9178 (cond ((null arg) org-not-done-regexp)
9179 ((equal arg '(4))
9180 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9181 (mapcar 'list org-todo-keywords-1))))
9182 (concat "\\("
9183 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9184 "\\)\\>")))
9185 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9186 (regexp-quote (nth (1- (prefix-numeric-value arg))
9187 org-todo-keywords-1)))
9188 (t (error "Invalid prefix argument: %s" arg)))))
9189 (message "%d TODO entries found"
9190 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9192 (defun org-deadline (&optional remove time)
9193 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9194 With argument REMOVE, remove any deadline from the item.
9195 When TIME is set, it should be an internal time specification, and the
9196 scheduling will use the corresponding date."
9197 (interactive "P")
9198 (if remove
9199 (progn
9200 (org-remove-timestamp-with-keyword org-deadline-string)
9201 (message "Item no longer has a deadline."))
9202 (if (org-get-repeat)
9203 (error "Cannot change deadline on task with repeater, please do that by hand")
9204 (org-add-planning-info 'deadline time 'closed)
9205 (message "Deadline on %s" org-last-inserted-timestamp))))
9207 (defun org-schedule (&optional remove time)
9208 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9209 With argument REMOVE, remove any scheduling date from the item.
9210 When TIME is set, it should be an internal time specification, and the
9211 scheduling will use the corresponding date."
9212 (interactive "P")
9213 (if remove
9214 (progn
9215 (org-remove-timestamp-with-keyword org-scheduled-string)
9216 (message "Item is no longer scheduled."))
9217 (if (org-get-repeat)
9218 (error "Cannot reschedule task with repeater, please do that by hand")
9219 (org-add-planning-info 'scheduled time 'closed)
9220 (message "Scheduled to %s" org-last-inserted-timestamp))))
9222 (defun org-get-scheduled-time (pom &optional inherit)
9223 "Get the scheduled time as a time tuple, of a format suitable
9224 for calling org-schedule with, or if there is no scheduling,
9225 returns nil."
9226 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9227 (when time
9228 (apply 'encode-time (org-parse-time-string time)))))
9230 (defun org-get-deadline-time (pom &optional inherit)
9231 "Get the deadine as a time tuple, of a format suitable for
9232 calling org-deadlin with, or if there is no scheduling, returns
9233 nil."
9234 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9235 (when time
9236 (apply 'encode-time (org-parse-time-string time)))))
9238 (defun org-remove-timestamp-with-keyword (keyword)
9239 "Remove all time stamps with KEYWORD in the current entry."
9240 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9241 beg)
9242 (save-excursion
9243 (org-back-to-heading t)
9244 (setq beg (point))
9245 (org-end-of-subtree t t)
9246 (while (re-search-backward re beg t)
9247 (replace-match "")
9248 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9249 (equal (char-before) ?\ ))
9250 (backward-delete-char 1)
9251 (if (string-match "^[ \t]*$" (buffer-substring
9252 (point-at-bol) (point-at-eol)))
9253 (delete-region (point-at-bol)
9254 (min (point-max) (1+ (point-at-eol))))))))))
9256 (defun org-add-planning-info (what &optional time &rest remove)
9257 "Insert new timestamp with keyword in the line directly after the headline.
9258 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9259 If non is given, the user is prompted for a date.
9260 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9261 be removed."
9262 (interactive)
9263 (let (org-time-was-given org-end-time-was-given ts
9264 end default-time default-input)
9266 (catch 'exit
9267 (when (and (not time) (memq what '(scheduled deadline)))
9268 ;; Try to get a default date/time from existing timestamp
9269 (save-excursion
9270 (org-back-to-heading t)
9271 (setq end (save-excursion (outline-next-heading) (point)))
9272 (when (re-search-forward (if (eq what 'scheduled)
9273 org-scheduled-time-regexp
9274 org-deadline-time-regexp)
9275 end t)
9276 (setq ts (match-string 1)
9277 default-time
9278 (apply 'encode-time (org-parse-time-string ts))
9279 default-input (and ts (org-get-compact-tod ts))))))
9280 (when what
9281 ;; If necessary, get the time from the user
9282 (setq time (or time (org-read-date nil 'to-time nil nil
9283 default-time default-input))))
9285 (when (and org-insert-labeled-timestamps-at-point
9286 (member what '(scheduled deadline)))
9287 (insert
9288 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9289 (org-insert-time-stamp time org-time-was-given
9290 nil nil nil (list org-end-time-was-given))
9291 (setq what nil))
9292 (save-excursion
9293 (save-restriction
9294 (let (col list elt ts buffer-invisibility-spec)
9295 (org-back-to-heading t)
9296 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9297 (goto-char (match-end 1))
9298 (setq col (current-column))
9299 (goto-char (match-end 0))
9300 (if (eobp) (insert "\n") (forward-char 1))
9301 (when (and (not what)
9302 (not (looking-at
9303 (concat "[ \t]*"
9304 org-keyword-time-not-clock-regexp))))
9305 ;; Nothing to add, nothing to remove...... :-)
9306 (throw 'exit nil))
9307 (if (and (not (looking-at outline-regexp))
9308 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9309 "[^\r\n]*"))
9310 (not (equal (match-string 1) org-clock-string)))
9311 (narrow-to-region (match-beginning 0) (match-end 0))
9312 (insert-before-markers "\n")
9313 (backward-char 1)
9314 (narrow-to-region (point) (point))
9315 (and org-adapt-indentation (org-indent-to-column col)))
9316 ;; Check if we have to remove something.
9317 (setq list (cons what remove))
9318 (while list
9319 (setq elt (pop list))
9320 (goto-char (point-min))
9321 (when (or (and (eq elt 'scheduled)
9322 (re-search-forward org-scheduled-time-regexp nil t))
9323 (and (eq elt 'deadline)
9324 (re-search-forward org-deadline-time-regexp nil t))
9325 (and (eq elt 'closed)
9326 (re-search-forward org-closed-time-regexp nil t)))
9327 (replace-match "")
9328 (if (looking-at "--+<[^>]+>") (replace-match ""))
9329 (if (looking-at " +") (replace-match ""))))
9330 (goto-char (point-max))
9331 (when what
9332 (insert
9333 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9334 (cond ((eq what 'scheduled) org-scheduled-string)
9335 ((eq what 'deadline) org-deadline-string)
9336 ((eq what 'closed) org-closed-string))
9337 " ")
9338 (setq ts (org-insert-time-stamp
9339 time
9340 (or org-time-was-given
9341 (and (eq what 'closed) org-log-done-with-time))
9342 (eq what 'closed)
9343 nil nil (list org-end-time-was-given)))
9344 (end-of-line 1))
9345 (goto-char (point-min))
9346 (widen)
9347 (if (and (looking-at "[ \t]+\n")
9348 (equal (char-before) ?\n))
9349 (delete-region (1- (point)) (point-at-eol)))
9350 ts))))))
9352 (defvar org-log-note-marker (make-marker))
9353 (defvar org-log-note-purpose nil)
9354 (defvar org-log-note-state nil)
9355 (defvar org-log-note-previous-state nil)
9356 (defvar org-log-note-how nil)
9357 (defvar org-log-note-extra nil)
9358 (defvar org-log-note-window-configuration nil)
9359 (defvar org-log-note-return-to (make-marker))
9360 (defvar org-log-post-message nil
9361 "Message to be displayed after a log note has been stored.
9362 The auto-repeater uses this.")
9364 (defun org-add-note ()
9365 "Add a note to the current entry.
9366 This is done in the same way as adding a state change note."
9367 (interactive)
9368 (org-add-log-setup 'note nil nil 'findpos nil))
9370 (defvar org-property-end-re)
9371 (defun org-add-log-setup (&optional purpose state prev-state
9372 findpos how &optional extra)
9373 "Set up the post command hook to take a note.
9374 If this is about to TODO state change, the new state is expected in STATE.
9375 When FINDPOS is non-nil, find the correct position for the note in
9376 the current entry. If not, assume that it can be inserted at point.
9377 HOW is an indicator what kind of note should be created.
9378 EXTRA is additional text that will be inserted into the notes buffer."
9379 (let ((drawer (cond ((stringp org-log-into-drawer)
9380 org-log-into-drawer)
9381 (org-log-into-drawer "LOGBOOK")
9382 (t nil))))
9383 (save-restriction
9384 (save-excursion
9385 (when findpos
9386 (org-back-to-heading t)
9387 (narrow-to-region (point) (save-excursion
9388 (outline-next-heading) (point)))
9389 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9390 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9391 "[^\r\n]*\\)?"))
9392 (goto-char (match-end 0))
9393 (cond
9394 (drawer
9395 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9396 nil t)
9397 (progn
9398 (goto-char (match-end 0))
9399 (or org-log-states-order-reversed
9400 (and (re-search-forward org-property-end-re nil t)
9401 (goto-char (1- (match-beginning 0))))))
9402 (insert "\n:" drawer ":\n:END:")
9403 (beginning-of-line 0)
9404 (org-indent-line-function)
9405 (beginning-of-line 2)
9406 (org-indent-line-function)
9407 (end-of-line 0)))
9408 ((and org-log-state-notes-insert-after-drawers
9409 (save-excursion
9410 (forward-line) (looking-at org-drawer-regexp)))
9411 (forward-line)
9412 (while (looking-at org-drawer-regexp)
9413 (goto-char (match-end 0))
9414 (re-search-forward org-property-end-re (point-max) t)
9415 (forward-line))
9416 (forward-line -1)))
9417 (unless org-log-states-order-reversed
9418 (and (= (char-after) ?\n) (forward-char 1))
9419 (org-skip-over-state-notes)
9420 (skip-chars-backward " \t\n\r")))
9421 (move-marker org-log-note-marker (point))
9422 (setq org-log-note-purpose purpose
9423 org-log-note-state state
9424 org-log-note-previous-state prev-state
9425 org-log-note-how how
9426 org-log-note-extra extra)
9427 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9429 (defun org-skip-over-state-notes ()
9430 "Skip past the list of State notes in an entry."
9431 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9432 (while (looking-at "[ \t]*- State")
9433 (condition-case nil
9434 (org-next-item)
9435 (error (org-end-of-item)))))
9437 (defun org-add-log-note (&optional purpose)
9438 "Pop up a window for taking a note, and add this note later at point."
9439 (remove-hook 'post-command-hook 'org-add-log-note)
9440 (setq org-log-note-window-configuration (current-window-configuration))
9441 (delete-other-windows)
9442 (move-marker org-log-note-return-to (point))
9443 (switch-to-buffer (marker-buffer org-log-note-marker))
9444 (goto-char org-log-note-marker)
9445 (org-switch-to-buffer-other-window "*Org Note*")
9446 (erase-buffer)
9447 (if (memq org-log-note-how '(time state))
9448 (let (current-prefix-arg) (org-store-log-note))
9449 (let ((org-inhibit-startup t)) (org-mode))
9450 (insert (format "# Insert note for %s.
9451 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9452 (cond
9453 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9454 ((eq org-log-note-purpose 'done) "closed todo item")
9455 ((eq org-log-note-purpose 'state)
9456 (format "state change from \"%s\" to \"%s\""
9457 (or org-log-note-previous-state "")
9458 (or org-log-note-state "")))
9459 ((eq org-log-note-purpose 'note)
9460 "this entry")
9461 (t (error "This should not happen")))))
9462 (if org-log-note-extra (insert org-log-note-extra))
9463 (org-set-local 'org-finish-function 'org-store-log-note)))
9465 (defvar org-note-abort nil) ; dynamically scoped
9466 (defun org-store-log-note ()
9467 "Finish taking a log note, and insert it to where it belongs."
9468 (let ((txt (buffer-string))
9469 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9470 lines ind)
9471 (kill-buffer (current-buffer))
9472 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9473 (setq txt (replace-match "" t t txt)))
9474 (if (string-match "\\s-+\\'" txt)
9475 (setq txt (replace-match "" t t txt)))
9476 (setq lines (org-split-string txt "\n"))
9477 (when (and note (string-match "\\S-" note))
9478 (setq note
9479 (org-replace-escapes
9480 note
9481 (list (cons "%u" (user-login-name))
9482 (cons "%U" user-full-name)
9483 (cons "%t" (format-time-string
9484 (org-time-stamp-format 'long 'inactive)
9485 (current-time)))
9486 (cons "%s" (if org-log-note-state
9487 (concat "\"" org-log-note-state "\"")
9488 ""))
9489 (cons "%S" (if org-log-note-previous-state
9490 (concat "\"" org-log-note-previous-state "\"")
9491 "\"\"")))))
9492 (if lines (setq note (concat note " \\\\")))
9493 (push note lines))
9494 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9495 (when lines
9496 (save-excursion
9497 (set-buffer (marker-buffer org-log-note-marker))
9498 (save-excursion
9499 (goto-char org-log-note-marker)
9500 (move-marker org-log-note-marker nil)
9501 (end-of-line 1)
9502 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9503 (insert "- " (pop lines))
9504 (org-indent-line-function)
9505 (beginning-of-line 1)
9506 (looking-at "[ \t]*")
9507 (setq ind (concat (match-string 0) " "))
9508 (end-of-line 1)
9509 (while lines (insert "\n" ind (pop lines)))
9510 (message "Note stored")
9511 (org-back-to-heading t)
9512 (org-cycle-hide-drawers 'children)))))
9513 (set-window-configuration org-log-note-window-configuration)
9514 (with-current-buffer (marker-buffer org-log-note-return-to)
9515 (goto-char org-log-note-return-to))
9516 (move-marker org-log-note-return-to nil)
9517 (and org-log-post-message (message "%s" org-log-post-message)))
9519 (defun org-sparse-tree (&optional arg)
9520 "Create a sparse tree, prompt for the details.
9521 This command can create sparse trees. You first need to select the type
9522 of match used to create the tree:
9524 t Show entries with a specific TODO keyword.
9525 m Show entries selected by a tags/property match.
9526 p Enter a property name and its value (both with completion on existing
9527 names/values) and show entries with that property.
9528 r Show entries matching a regular expression
9529 d Show deadlines due within `org-deadline-warning-days'."
9530 (interactive "P")
9531 (let (ans kwd value)
9532 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date")
9533 (setq ans (read-char-exclusive))
9534 (cond
9535 ((equal ans ?d)
9536 (call-interactively 'org-check-deadlines))
9537 ((equal ans ?b)
9538 (call-interactively 'org-check-before-date))
9539 ((equal ans ?t)
9540 (org-show-todo-tree '(4)))
9541 ((member ans '(?T ?m))
9542 (call-interactively 'org-match-sparse-tree))
9543 ((member ans '(?p ?P))
9544 (setq kwd (org-ido-completing-read "Property: "
9545 (mapcar 'list (org-buffer-property-keys))))
9546 (setq value (org-ido-completing-read "Value: "
9547 (mapcar 'list (org-property-values kwd))))
9548 (unless (string-match "\\`{.*}\\'" value)
9549 (setq value (concat "\"" value "\"")))
9550 (org-match-sparse-tree arg (concat kwd "=" value)))
9551 ((member ans '(?r ?R ?/))
9552 (call-interactively 'org-occur))
9553 (t (error "No such sparse tree command \"%c\"" ans)))))
9555 (defvar org-occur-highlights nil
9556 "List of overlays used for occur matches.")
9557 (make-variable-buffer-local 'org-occur-highlights)
9558 (defvar org-occur-parameters nil
9559 "Parameters of the active org-occur calls.
9560 This is a list, each call to org-occur pushes as cons cell,
9561 containing the regular expression and the callback, onto the list.
9562 The list can contain several entries if `org-occur' has been called
9563 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9564 will only contain one set of parameters. When the highlights are
9565 removed (for example with `C-c C-c', or with the next edit (depending
9566 on `org-remove-highlights-with-change'), this variable is emptied
9567 as well.")
9568 (make-variable-buffer-local 'org-occur-parameters)
9570 (defun org-occur (regexp &optional keep-previous callback)
9571 "Make a compact tree which shows all matches of REGEXP.
9572 The tree will show the lines where the regexp matches, and all higher
9573 headlines above the match. It will also show the heading after the match,
9574 to make sure editing the matching entry is easy.
9575 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9576 call to `org-occur' will be kept, to allow stacking of calls to this
9577 command.
9578 If CALLBACK is non-nil, it is a function which is called to confirm
9579 that the match should indeed be shown."
9580 (interactive "sRegexp: \nP")
9581 (unless keep-previous
9582 (org-remove-occur-highlights nil nil t))
9583 (push (cons regexp callback) org-occur-parameters)
9584 (let ((cnt 0))
9585 (save-excursion
9586 (goto-char (point-min))
9587 (if (or (not keep-previous) ; do not want to keep
9588 (not org-occur-highlights)) ; no previous matches
9589 ;; hide everything
9590 (org-overview))
9591 (while (re-search-forward regexp nil t)
9592 (when (or (not callback)
9593 (save-match-data (funcall callback)))
9594 (setq cnt (1+ cnt))
9595 (when org-highlight-sparse-tree-matches
9596 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9597 (org-show-context 'occur-tree))))
9598 (when org-remove-highlights-with-change
9599 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9600 nil 'local))
9601 (unless org-sparse-tree-open-archived-trees
9602 (org-hide-archived-subtrees (point-min) (point-max)))
9603 (run-hooks 'org-occur-hook)
9604 (if (interactive-p)
9605 (message "%d match(es) for regexp %s" cnt regexp))
9606 cnt))
9608 (defun org-show-context (&optional key)
9609 "Make sure point and context and visible.
9610 How much context is shown depends upon the variables
9611 `org-show-hierarchy-above', `org-show-following-heading'. and
9612 `org-show-siblings'."
9613 (let ((heading-p (org-on-heading-p t))
9614 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9615 (following-p (org-get-alist-option org-show-following-heading key))
9616 (entry-p (org-get-alist-option org-show-entry-below key))
9617 (siblings-p (org-get-alist-option org-show-siblings key)))
9618 (catch 'exit
9619 ;; Show heading or entry text
9620 (if (and heading-p (not entry-p))
9621 (org-flag-heading nil) ; only show the heading
9622 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9623 (org-show-hidden-entry))) ; show entire entry
9624 (when following-p
9625 ;; Show next sibling, or heading below text
9626 (save-excursion
9627 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9628 (org-flag-heading nil))))
9629 (when siblings-p (org-show-siblings))
9630 (when hierarchy-p
9631 ;; show all higher headings, possibly with siblings
9632 (save-excursion
9633 (while (and (condition-case nil
9634 (progn (org-up-heading-all 1) t)
9635 (error nil))
9636 (not (bobp)))
9637 (org-flag-heading nil)
9638 (when siblings-p (org-show-siblings))))))))
9640 (defun org-reveal (&optional siblings)
9641 "Show current entry, hierarchy above it, and the following headline.
9642 This can be used to show a consistent set of context around locations
9643 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9644 not t for the search context.
9646 With optional argument SIBLINGS, on each level of the hierarchy all
9647 siblings are shown. This repairs the tree structure to what it would
9648 look like when opened with hierarchical calls to `org-cycle'."
9649 (interactive "P")
9650 (let ((org-show-hierarchy-above t)
9651 (org-show-following-heading t)
9652 (org-show-siblings (if siblings t org-show-siblings)))
9653 (org-show-context nil)))
9655 (defun org-highlight-new-match (beg end)
9656 "Highlight from BEG to END and mark the highlight is an occur headline."
9657 (let ((ov (org-make-overlay beg end)))
9658 (org-overlay-put ov 'face 'secondary-selection)
9659 (push ov org-occur-highlights)))
9661 (defun org-remove-occur-highlights (&optional beg end noremove)
9662 "Remove the occur highlights from the buffer.
9663 BEG and END are ignored. If NOREMOVE is nil, remove this function
9664 from the `before-change-functions' in the current buffer."
9665 (interactive)
9666 (unless org-inhibit-highlight-removal
9667 (mapc 'org-delete-overlay org-occur-highlights)
9668 (setq org-occur-highlights nil)
9669 (setq org-occur-parameters nil)
9670 (unless noremove
9671 (remove-hook 'before-change-functions
9672 'org-remove-occur-highlights 'local))))
9674 ;;;; Priorities
9676 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9677 "Regular expression matching the priority indicator.")
9679 (defvar org-remove-priority-next-time nil)
9681 (defun org-priority-up ()
9682 "Increase the priority of the current item."
9683 (interactive)
9684 (org-priority 'up))
9686 (defun org-priority-down ()
9687 "Decrease the priority of the current item."
9688 (interactive)
9689 (org-priority 'down))
9691 (defun org-priority (&optional action)
9692 "Change the priority of an item by ARG.
9693 ACTION can be `set', `up', `down', or a character."
9694 (interactive)
9695 (setq action (or action 'set))
9696 (let (current new news have remove)
9697 (save-excursion
9698 (org-back-to-heading t)
9699 (if (looking-at org-priority-regexp)
9700 (setq current (string-to-char (match-string 2))
9701 have t)
9702 (setq current org-default-priority))
9703 (cond
9704 ((or (eq action 'set)
9705 (if (featurep 'xemacs) (characterp action) (integerp action)))
9706 (if (not (eq action 'set))
9707 (setq new action)
9708 (message "Priority %c-%c, SPC to remove: "
9709 org-highest-priority org-lowest-priority)
9710 (setq new (read-char-exclusive)))
9711 (if (and (= (upcase org-highest-priority) org-highest-priority)
9712 (= (upcase org-lowest-priority) org-lowest-priority))
9713 (setq new (upcase new)))
9714 (cond ((equal new ?\ ) (setq remove t))
9715 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9716 (error "Priority must be between `%c' and `%c'"
9717 org-highest-priority org-lowest-priority))))
9718 ((eq action 'up)
9719 (if (and (not have) (eq last-command this-command))
9720 (setq new org-lowest-priority)
9721 (setq new (if (and org-priority-start-cycle-with-default (not have))
9722 org-default-priority (1- current)))))
9723 ((eq action 'down)
9724 (if (and (not have) (eq last-command this-command))
9725 (setq new org-highest-priority)
9726 (setq new (if (and org-priority-start-cycle-with-default (not have))
9727 org-default-priority (1+ current)))))
9728 (t (error "Invalid action")))
9729 (if (or (< (upcase new) org-highest-priority)
9730 (> (upcase new) org-lowest-priority))
9731 (setq remove t))
9732 (setq news (format "%c" new))
9733 (if have
9734 (if remove
9735 (replace-match "" t t nil 1)
9736 (replace-match news t t nil 2))
9737 (if remove
9738 (error "No priority cookie found in line")
9739 (looking-at org-todo-line-regexp)
9740 (if (match-end 2)
9741 (progn
9742 (goto-char (match-end 2))
9743 (insert " [#" news "]"))
9744 (goto-char (match-beginning 3))
9745 (insert "[#" news "] ")))))
9746 (org-preserve-lc (org-set-tags nil 'align))
9747 (if remove
9748 (message "Priority removed")
9749 (message "Priority of current item set to %s" news))))
9752 (defun org-get-priority (s)
9753 "Find priority cookie and return priority."
9754 (save-match-data
9755 (if (not (string-match org-priority-regexp s))
9756 (* 1000 (- org-lowest-priority org-default-priority))
9757 (* 1000 (- org-lowest-priority
9758 (string-to-char (match-string 2 s)))))))
9760 ;;;; Tags
9762 (defvar org-agenda-archives-mode)
9763 (defvar org-scanner-tags nil
9764 "The current tag list while the tags scanner is running.")
9765 (defvar org-trust-scanner-tags nil
9766 "Should `org-get-tags-at' use the tags fro the scanner.
9767 This is for internal dynamical scoping only.
9768 When this is non-nil, the function `org-get-tags-at' will return the value
9769 of `org-scanner-tags' instead of building the list by itself. This
9770 can lead to large speed-ups when the tags scanner is used in a file with
9771 many entries, and when the list of tags is retrieved, for example to
9772 obtain a list of properties. Building the tags list for each entry in such
9773 a file becomes an N^2 operation - but with this variable set, it scales
9774 as N.")
9776 (defun org-scan-tags (action matcher &optional todo-only)
9777 "Scan headline tags with inheritance and produce output ACTION.
9779 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9780 or `agenda' to produce an entry list for an agenda view. It can also be
9781 a Lisp form or a function that should be called at each matched headline, in
9782 this case the return value is a list of all return values from these calls.
9784 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9785 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9786 only lines with a TODO keyword are included in the output."
9787 (require 'org-agenda)
9788 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9789 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9790 (org-re
9791 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9792 (props (list 'face 'default
9793 'done-face 'org-done
9794 'undone-face 'default
9795 'mouse-face 'highlight
9796 'org-not-done-regexp org-not-done-regexp
9797 'org-todo-regexp org-todo-regexp
9798 'keymap org-agenda-keymap
9799 'help-echo
9800 (format "mouse-2 or RET jump to org file %s"
9801 (abbreviate-file-name
9802 (or (buffer-file-name (buffer-base-buffer))
9803 (buffer-name (buffer-base-buffer)))))))
9804 (case-fold-search nil)
9805 lspos tags tags-list
9806 (tags-alist (list (cons 0 org-file-tags)))
9807 (llast 0) rtn rtn1 level category i txt
9808 todo marker entry priority)
9809 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9810 (setq action (list 'lambda nil action)))
9811 (save-excursion
9812 (goto-char (point-min))
9813 (when (eq action 'sparse-tree)
9814 (org-overview)
9815 (org-remove-occur-highlights))
9816 (while (re-search-forward re nil t)
9817 (catch :skip
9818 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
9819 tags (if (match-end 4) (org-match-string-no-properties 4)))
9820 (goto-char (setq lspos (1+ (match-beginning 0))))
9821 (setq level (org-reduced-level (funcall outline-level))
9822 category (org-get-category))
9823 (setq i llast llast level)
9824 ;; remove tag lists from same and sublevels
9825 (while (>= i level)
9826 (when (setq entry (assoc i tags-alist))
9827 (setq tags-alist (delete entry tags-alist)))
9828 (setq i (1- i)))
9829 ;; add the next tags
9830 (when tags
9831 (setq tags (org-split-string tags ":")
9832 tags-alist
9833 (cons (cons level tags) tags-alist)))
9834 ;; compile tags for current headline
9835 (setq tags-list
9836 (if org-use-tag-inheritance
9837 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9838 tags)
9839 org-scanner-tags tags-list)
9840 (when org-use-tag-inheritance
9841 (setcdr (car tags-alist)
9842 (mapcar (lambda (x)
9843 (setq x (copy-sequence x))
9844 (org-add-prop-inherited x))
9845 (cdar tags-alist))))
9846 (when (and tags org-use-tag-inheritance
9847 (or (not (eq t org-use-tag-inheritance))
9848 org-tags-exclude-from-inheritance))
9849 ;; selective inheritance, remove uninherited ones
9850 (setcdr (car tags-alist)
9851 (org-remove-uniherited-tags (cdar tags-alist))))
9852 (when (and (or (not todo-only)
9853 (and (member todo org-not-done-keywords)
9854 (or (not org-agenda-tags-todo-honor-ignore-options)
9855 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9856 (let ((case-fold-search t)) (eval matcher))
9858 (not (member org-archive-tag tags-list))
9859 ;; we have an archive tag, should we use this anyway?
9860 (or (not org-agenda-skip-archived-trees)
9861 (and (eq action 'agenda) org-agenda-archives-mode))))
9862 (unless (eq action 'sparse-tree) (org-agenda-skip))
9864 ;; select this headline
9866 (cond
9867 ((eq action 'sparse-tree)
9868 (and org-highlight-sparse-tree-matches
9869 (org-get-heading) (match-end 0)
9870 (org-highlight-new-match
9871 (match-beginning 0) (match-beginning 1)))
9872 (org-show-context 'tags-tree))
9873 ((eq action 'agenda)
9874 (setq txt (org-format-agenda-item
9876 (concat
9877 (if org-tags-match-list-sublevels
9878 (make-string (1- level) ?.) "")
9879 (org-get-heading))
9880 category
9881 ;(org-get-tags-at)
9882 tags-list
9884 priority (org-get-priority txt))
9885 (goto-char lspos)
9886 (setq marker (org-agenda-new-marker))
9887 (org-add-props txt props
9888 'org-marker marker 'org-hd-marker marker 'org-category category
9889 'todo-state todo
9890 'priority priority 'type "tagsmatch")
9891 (push txt rtn))
9892 ((functionp action)
9893 (save-excursion
9894 (setq rtn1 (funcall action))
9895 (push rtn1 rtn))
9896 (goto-char (point-at-eol)))
9897 (t (error "Invalid action")))
9899 ;; if we are to skip sublevels, jump to end of subtree
9900 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9901 (when (and (eq action 'sparse-tree)
9902 (not org-sparse-tree-open-archived-trees))
9903 (org-hide-archived-subtrees (point-min) (point-max)))
9904 (nreverse rtn)))
9906 (defun org-remove-uniherited-tags (tags)
9907 "Remove all tags that are not inherited from the list TAGS."
9908 (cond
9909 ((eq org-use-tag-inheritance t)
9910 (if org-tags-exclude-from-inheritance
9911 (org-delete-all org-tags-exclude-from-inheritance tags)
9912 tags))
9913 ((not org-use-tag-inheritance) nil)
9914 ((stringp org-use-tag-inheritance)
9915 (delq nil (mapcar
9916 (lambda (x)
9917 (if (and (string-match org-use-tag-inheritance x)
9918 (not (member x org-tags-exclude-from-inheritance)))
9919 x nil))
9920 tags)))
9921 ((listp org-use-tag-inheritance)
9922 (delq nil (mapcar
9923 (lambda (x)
9924 (if (member x org-use-tag-inheritance) x nil))
9925 tags)))))
9927 (defvar todo-only) ;; dynamically scoped
9929 (defun org-match-sparse-tree (&optional todo-only match)
9930 "Create a sparse tree according to tags string MATCH.
9931 MATCH can contain positive and negative selection of tags, like
9932 \"+WORK+URGENT-WITHBOSS\".
9933 If optional argument TODO-ONLY is non-nil, only select lines that are
9934 also TODO lines."
9935 (interactive "P")
9936 (org-prepare-agenda-buffers (list (current-buffer)))
9937 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9939 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
9941 (defvar org-cached-props nil)
9942 (defun org-cached-entry-get (pom property)
9943 (if (or (eq t org-use-property-inheritance)
9944 (and (stringp org-use-property-inheritance)
9945 (string-match org-use-property-inheritance property))
9946 (and (listp org-use-property-inheritance)
9947 (member property org-use-property-inheritance)))
9948 ;; Caching is not possible, check it directly
9949 (org-entry-get pom property 'inherit)
9950 ;; Get all properties, so that we can do complicated checks easily
9951 (cdr (assoc property (or org-cached-props
9952 (setq org-cached-props
9953 (org-entry-properties pom)))))))
9955 (defun org-global-tags-completion-table (&optional files)
9956 "Return the list of all tags in all agenda buffer/files."
9957 (save-excursion
9958 (org-uniquify
9959 (delq nil
9960 (apply 'append
9961 (mapcar
9962 (lambda (file)
9963 (set-buffer (find-file-noselect file))
9964 (append (org-get-buffer-tags)
9965 (mapcar (lambda (x) (if (stringp (car-safe x))
9966 (list (car-safe x)) nil))
9967 org-tag-alist)))
9968 (if (and files (car files))
9969 files
9970 (org-agenda-files))))))))
9972 (defun org-make-tags-matcher (match)
9973 "Create the TAGS//TODO matcher form for the selection string MATCH."
9974 ;; todo-only is scoped dynamically into this function, and the function
9975 ;; may change it if the matcher asks for it.
9976 (unless match
9977 ;; Get a new match request, with completion
9978 (let ((org-last-tags-completion-table
9979 (org-global-tags-completion-table)))
9980 (setq match (org-completing-read-no-ido
9981 "Match: " 'org-tags-completion-function nil nil nil
9982 'org-tags-history))))
9984 ;; Parse the string and create a lisp form
9985 (let ((match0 match)
9986 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9987 minus tag mm
9988 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9989 orterms term orlist re-p str-p level-p level-op time-p
9990 prop-p pn pv po cat-p gv rest)
9991 (if (string-match "/+" match)
9992 ;; match contains also a todo-matching request
9993 (progn
9994 (setq tagsmatch (substring match 0 (match-beginning 0))
9995 todomatch (substring match (match-end 0)))
9996 (if (string-match "^!" todomatch)
9997 (setq todo-only t todomatch (substring todomatch 1)))
9998 (if (string-match "^\\s-*$" todomatch)
9999 (setq todomatch nil)))
10000 ;; only matching tags
10001 (setq tagsmatch match todomatch nil))
10003 ;; Make the tags matcher
10004 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10005 (setq tagsmatcher t)
10006 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10007 (while (setq term (pop orterms))
10008 (while (and (equal (substring term -1) "\\") orterms)
10009 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10010 (while (string-match re term)
10011 (setq rest (substring term (match-end 0))
10012 minus (and (match-end 1)
10013 (equal (match-string 1 term) "-"))
10014 tag (match-string 2 term)
10015 re-p (equal (string-to-char tag) ?{)
10016 level-p (match-end 4)
10017 prop-p (match-end 5)
10018 mm (cond
10019 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10020 (level-p
10021 (setq level-op (org-op-to-function (match-string 3 term)))
10022 `(,level-op level ,(string-to-number
10023 (match-string 4 term))))
10024 (prop-p
10025 (setq pn (match-string 5 term)
10026 po (match-string 6 term)
10027 pv (match-string 7 term)
10028 cat-p (equal pn "CATEGORY")
10029 re-p (equal (string-to-char pv) ?{)
10030 str-p (equal (string-to-char pv) ?\")
10031 time-p (save-match-data
10032 (string-match "^\"[[<].*[]>]\"$" pv))
10033 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10034 (if time-p (setq pv (org-matcher-time pv)))
10035 (setq po (org-op-to-function po (if time-p 'time str-p)))
10036 (cond
10037 ((equal pn "CATEGORY")
10038 (setq gv '(get-text-property (point) 'org-category)))
10039 ((equal pn "TODO")
10040 (setq gv 'todo))
10042 (setq gv `(org-cached-entry-get nil ,pn))))
10043 (if re-p
10044 (if (eq po 'org<>)
10045 `(not (string-match ,pv (or ,gv "")))
10046 `(string-match ,pv (or ,gv "")))
10047 (if str-p
10048 `(,po (or ,gv "") ,pv)
10049 `(,po (string-to-number (or ,gv ""))
10050 ,(string-to-number pv) ))))
10051 (t `(member ,tag tags-list)))
10052 mm (if minus (list 'not mm) mm)
10053 term rest)
10054 (push mm tagsmatcher))
10055 (push (if (> (length tagsmatcher) 1)
10056 (cons 'and tagsmatcher)
10057 (car tagsmatcher))
10058 orlist)
10059 (setq tagsmatcher nil))
10060 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10061 (setq tagsmatcher
10062 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10063 ;; Make the todo matcher
10064 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10065 (setq todomatcher t)
10066 (setq orterms (org-split-string todomatch "|") orlist nil)
10067 (while (setq term (pop orterms))
10068 (while (string-match re term)
10069 (setq minus (and (match-end 1)
10070 (equal (match-string 1 term) "-"))
10071 kwd (match-string 2 term)
10072 re-p (equal (string-to-char kwd) ?{)
10073 term (substring term (match-end 0))
10074 mm (if re-p
10075 `(string-match ,(substring kwd 1 -1) todo)
10076 (list 'equal 'todo kwd))
10077 mm (if minus (list 'not mm) mm))
10078 (push mm todomatcher))
10079 (push (if (> (length todomatcher) 1)
10080 (cons 'and todomatcher)
10081 (car todomatcher))
10082 orlist)
10083 (setq todomatcher nil))
10084 (setq todomatcher (if (> (length orlist) 1)
10085 (cons 'or orlist) (car orlist))))
10087 ;; Return the string and lisp forms of the matcher
10088 (setq matcher (if todomatcher
10089 (list 'and tagsmatcher todomatcher)
10090 tagsmatcher))
10091 (cons match0 matcher)))
10093 (defun org-op-to-function (op &optional stringp)
10094 "Turn an operator into the appropriate function."
10095 (setq op
10096 (cond
10097 ((equal op "<" ) '(< string< org-time<))
10098 ((equal op ">" ) '(> org-string> org-time>))
10099 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10100 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10101 ((member op '("=" "==")) '(= string= org-time=))
10102 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10103 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10105 (defun org<> (a b) (not (= a b)))
10106 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10107 (defun org-string>= (a b) (not (string< a b)))
10108 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10109 (defun org-string<> (a b) (not (string= a b)))
10110 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10111 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10112 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10113 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10114 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10115 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10116 (defun org-2ft (s)
10117 "Convert S to a floating point time.
10118 If S is already a number, just return it. If it is a string, parse
10119 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10120 (cond
10121 ((numberp s) s)
10122 ((stringp s)
10123 (condition-case nil
10124 (float-time (apply 'encode-time (org-parse-time-string s)))
10125 (error 0.)))
10126 (t 0.)))
10128 (defun org-time-today ()
10129 "Time in seconds today at 0:00.
10130 Returns the float number of seconds since the beginning of the
10131 epoch to the beginning of today (00:00)."
10132 (float-time (apply 'encode-time
10133 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10135 (defun org-matcher-time (s)
10136 "Interpret a time comparison value."
10137 (save-match-data
10138 (cond
10139 ((string= s "<now>") (float-time))
10140 ((string= s "<today>") (org-time-today))
10141 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10142 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10143 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10144 (+ (org-time-today)
10145 (* (string-to-number (match-string 1 s))
10146 (cdr (assoc (match-string 2 s)
10147 '(("d" . 86400.0) ("w" . 604800.0)
10148 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10149 (t (org-2ft s)))))
10151 (defun org-match-any-p (re list)
10152 "Does re match any element of list?"
10153 (setq list (mapcar (lambda (x) (string-match re x)) list))
10154 (delq nil list))
10156 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10157 (defvar org-tags-overlay (org-make-overlay 1 1))
10158 (org-detach-overlay org-tags-overlay)
10160 (defun org-get-local-tags-at (&optional pos)
10161 "Get a list of tags defined in the current headline."
10162 (org-get-tags-at pos 'local))
10164 (defun org-get-local-tags ()
10165 "Get a list of tags defined in the current headline."
10166 (org-get-tags-at nil 'local))
10168 (defun org-get-tags-at (&optional pos local)
10169 "Get a list of all headline tags applicable at POS.
10170 POS defaults to point. If tags are inherited, the list contains
10171 the targets in the same sequence as the headlines appear, i.e.
10172 the tags of the current headline come last.
10173 When LOCAL is non-nil, only return tags from the current headline,
10174 ignore inherited ones."
10175 (interactive)
10176 (if (and org-trust-scanner-tags
10177 (or (not pos) (equal pos (point)))
10178 (not local))
10179 org-scanner-tags
10180 (let (tags ltags lastpos parent)
10181 (save-excursion
10182 (save-restriction
10183 (widen)
10184 (goto-char (or pos (point)))
10185 (save-match-data
10186 (catch 'done
10187 (condition-case nil
10188 (progn
10189 (org-back-to-heading t)
10190 (while (not (equal lastpos (point)))
10191 (setq lastpos (point))
10192 (when (looking-at
10193 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10194 (setq ltags (org-split-string
10195 (org-match-string-no-properties 1) ":"))
10196 (when parent
10197 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10198 (setq tags (append
10199 (if parent
10200 (org-remove-uniherited-tags ltags)
10201 ltags)
10202 tags)))
10203 (or org-use-tag-inheritance (throw 'done t))
10204 (if local (throw 'done t))
10205 (org-up-heading-all 1)
10206 (setq parent t)))
10207 (error nil)))))
10208 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10210 (defun org-add-prop-inherited (s)
10211 (add-text-properties 0 (length s) '(inherited t) s)
10214 (defun org-toggle-tag (tag &optional onoff)
10215 "Toggle the tag TAG for the current line.
10216 If ONOFF is `on' or `off', don't toggle but set to this state."
10217 (let (res current)
10218 (save-excursion
10219 (org-back-to-heading t)
10220 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10221 (point-at-eol) t)
10222 (progn
10223 (setq current (match-string 1))
10224 (replace-match ""))
10225 (setq current ""))
10226 (setq current (nreverse (org-split-string current ":")))
10227 (cond
10228 ((eq onoff 'on)
10229 (setq res t)
10230 (or (member tag current) (push tag current)))
10231 ((eq onoff 'off)
10232 (or (not (member tag current)) (setq current (delete tag current))))
10233 (t (if (member tag current)
10234 (setq current (delete tag current))
10235 (setq res t)
10236 (push tag current))))
10237 (end-of-line 1)
10238 (if current
10239 (progn
10240 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10241 (org-set-tags nil t))
10242 (delete-horizontal-space))
10243 (run-hooks 'org-after-tags-change-hook))
10244 res))
10246 (defun org-align-tags-here (to-col)
10247 ;; Assumes that this is a headline
10248 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10249 (beginning-of-line 1)
10250 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10251 (< pos (match-beginning 2)))
10252 (progn
10253 (setq tags-l (- (match-end 2) (match-beginning 2)))
10254 (goto-char (match-beginning 1))
10255 (insert " ")
10256 (delete-region (point) (1+ (match-beginning 2)))
10257 (setq ncol (max (1+ (current-column))
10258 (1+ col)
10259 (if (> to-col 0)
10260 to-col
10261 (- (abs to-col) tags-l))))
10262 (setq p (point))
10263 (insert (make-string (- ncol (current-column)) ?\ ))
10264 (setq ncol (current-column))
10265 (when indent-tabs-mode (tabify p (point-at-eol)))
10266 (org-move-to-column (min ncol col) t))
10267 (goto-char pos))))
10269 (defun org-set-tags-command (&optional arg just-align)
10270 "Call the set-tags command for the current entry."
10271 (interactive "P")
10272 (if (org-on-heading-p)
10273 (org-set-tags arg just-align)
10274 (save-excursion
10275 (org-back-to-heading t)
10276 (org-set-tags arg just-align))))
10278 (defun org-set-tags (&optional arg just-align)
10279 "Set the tags for the current headline.
10280 With prefix ARG, realign all tags in headings in the current buffer."
10281 (interactive "P")
10282 (let* ((re (concat "^" outline-regexp))
10283 (current (org-get-tags-string))
10284 (col (current-column))
10285 (org-setting-tags t)
10286 table current-tags inherited-tags ; computed below when needed
10287 tags p0 c0 c1 rpl)
10288 (if arg
10289 (save-excursion
10290 (goto-char (point-min))
10291 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10292 (while (re-search-forward re nil t)
10293 (org-set-tags nil t)
10294 (end-of-line 1)))
10295 (message "All tags realigned to column %d" org-tags-column))
10296 (if just-align
10297 (setq tags current)
10298 ;; Get a new set of tags from the user
10299 (save-excursion
10300 (setq table (append org-tag-persistent-alist
10301 (or org-tag-alist (org-get-buffer-tags)))
10302 org-last-tags-completion-table table
10303 current-tags (org-split-string current ":")
10304 inherited-tags (nreverse
10305 (nthcdr (length current-tags)
10306 (nreverse (org-get-tags-at))))
10307 tags
10308 (if (or (eq t org-use-fast-tag-selection)
10309 (and org-use-fast-tag-selection
10310 (delq nil (mapcar 'cdr table))))
10311 (org-fast-tag-selection
10312 current-tags inherited-tags table
10313 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10314 (let ((org-add-colon-after-tag-completion t))
10315 (org-trim
10316 (org-without-partial-completion
10317 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10318 nil nil current 'org-tags-history)))))))
10319 (while (string-match "[-+&]+" tags)
10320 ;; No boolean logic, just a list
10321 (setq tags (replace-match ":" t t tags))))
10323 (if (string-match "\\`[\t ]*\\'" tags)
10324 (setq tags "")
10325 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10326 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10328 ;; Insert new tags at the correct column
10329 (beginning-of-line 1)
10330 (cond
10331 ((and (equal current "") (equal tags "")))
10332 ((re-search-forward
10333 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10334 (point-at-eol) t)
10335 (if (equal tags "")
10336 (setq rpl "")
10337 (goto-char (match-beginning 0))
10338 (setq c0 (current-column) p0 (point)
10339 c1 (max (1+ c0) (if (> org-tags-column 0)
10340 org-tags-column
10341 (- (- org-tags-column) (length tags))))
10342 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10343 (replace-match rpl t t)
10344 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10345 tags)
10346 (t (error "Tags alignment failed")))
10347 (org-move-to-column col)
10348 (unless just-align
10349 (run-hooks 'org-after-tags-change-hook)))))
10351 (defun org-change-tag-in-region (beg end tag off)
10352 "Add or remove TAG for each entry in the region.
10353 This works in the agenda, and also in an org-mode buffer."
10354 (interactive
10355 (list (region-beginning) (region-end)
10356 (let ((org-last-tags-completion-table
10357 (if (org-mode-p)
10358 (org-get-buffer-tags)
10359 (org-global-tags-completion-table))))
10360 (org-ido-completing-read
10361 "Tag: " 'org-tags-completion-function nil nil nil
10362 'org-tags-history))
10363 (progn
10364 (message "[s]et or [r]emove? ")
10365 (equal (read-char-exclusive) ?r))))
10366 (if (fboundp 'deactivate-mark) (deactivate-mark))
10367 (let ((agendap (equal major-mode 'org-agenda-mode))
10368 l1 l2 m buf pos newhead (cnt 0))
10369 (goto-char end)
10370 (setq l2 (1- (org-current-line)))
10371 (goto-char beg)
10372 (setq l1 (org-current-line))
10373 (loop for l from l1 to l2 do
10374 (goto-line l)
10375 (setq m (get-text-property (point) 'org-hd-marker))
10376 (when (or (and (org-mode-p) (org-on-heading-p))
10377 (and agendap m))
10378 (setq buf (if agendap (marker-buffer m) (current-buffer))
10379 pos (if agendap m (point)))
10380 (with-current-buffer buf
10381 (save-excursion
10382 (save-restriction
10383 (goto-char pos)
10384 (setq cnt (1+ cnt))
10385 (org-toggle-tag tag (if off 'off 'on))
10386 (setq newhead (org-get-heading)))))
10387 (and agendap (org-agenda-change-all-lines newhead m))))
10388 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10390 (defun org-tags-completion-function (string predicate &optional flag)
10391 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10392 (confirm (lambda (x) (stringp (car x)))))
10393 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10394 (setq s1 (match-string 1 string)
10395 s2 (match-string 2 string))
10396 (setq s1 "" s2 string))
10397 (cond
10398 ((eq flag nil)
10399 ;; try completion
10400 (setq rtn (try-completion s2 ctable confirm))
10401 (if (stringp rtn)
10402 (setq rtn
10403 (concat s1 s2 (substring rtn (length s2))
10404 (if (and org-add-colon-after-tag-completion
10405 (assoc rtn ctable))
10406 ":" ""))))
10407 rtn)
10408 ((eq flag t)
10409 ;; all-completions
10410 (all-completions s2 ctable confirm)
10412 ((eq flag 'lambda)
10413 ;; exact match?
10414 (assoc s2 ctable)))
10417 (defun org-fast-tag-insert (kwd tags face &optional end)
10418 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10419 (insert (format "%-12s" (concat kwd ":"))
10420 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10421 (or end "")))
10423 (defun org-fast-tag-show-exit (flag)
10424 (save-excursion
10425 (goto-line 3)
10426 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10427 (replace-match ""))
10428 (when flag
10429 (end-of-line 1)
10430 (org-move-to-column (- (window-width) 19) t)
10431 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10433 (defun org-set-current-tags-overlay (current prefix)
10434 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10435 (if (featurep 'xemacs)
10436 (org-overlay-display org-tags-overlay (concat prefix s)
10437 'secondary-selection)
10438 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10439 (org-overlay-display org-tags-overlay (concat prefix s)))))
10441 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10442 "Fast tag selection with single keys.
10443 CURRENT is the current list of tags in the headline, INHERITED is the
10444 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10445 possibly with grouping information. TODO-TABLE is a similar table with
10446 TODO keywords, should these have keys assigned to them.
10447 If the keys are nil, a-z are automatically assigned.
10448 Returns the new tags string, or nil to not change the current settings."
10449 (let* ((fulltable (append table todo-table))
10450 (maxlen (apply 'max (mapcar
10451 (lambda (x)
10452 (if (stringp (car x)) (string-width (car x)) 0))
10453 fulltable)))
10454 (buf (current-buffer))
10455 (expert (eq org-fast-tag-selection-single-key 'expert))
10456 (buffer-tags nil)
10457 (fwidth (+ maxlen 3 1 3))
10458 (ncol (/ (- (window-width) 4) fwidth))
10459 (i-face 'org-done)
10460 (c-face 'org-todo)
10461 tg cnt e c char c1 c2 ntable tbl rtn
10462 ov-start ov-end ov-prefix
10463 (exit-after-next org-fast-tag-selection-single-key)
10464 (done-keywords org-done-keywords)
10465 groups ingroup)
10466 (save-excursion
10467 (beginning-of-line 1)
10468 (if (looking-at
10469 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10470 (setq ov-start (match-beginning 1)
10471 ov-end (match-end 1)
10472 ov-prefix "")
10473 (setq ov-start (1- (point-at-eol))
10474 ov-end (1+ ov-start))
10475 (skip-chars-forward "^\n\r")
10476 (setq ov-prefix
10477 (concat
10478 (buffer-substring (1- (point)) (point))
10479 (if (> (current-column) org-tags-column)
10481 (make-string (- org-tags-column (current-column)) ?\ ))))))
10482 (org-move-overlay org-tags-overlay ov-start ov-end)
10483 (save-window-excursion
10484 (if expert
10485 (set-buffer (get-buffer-create " *Org tags*"))
10486 (delete-other-windows)
10487 (split-window-vertically)
10488 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10489 (erase-buffer)
10490 (org-set-local 'org-done-keywords done-keywords)
10491 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10492 (org-fast-tag-insert "Current" current c-face "\n\n")
10493 (org-fast-tag-show-exit exit-after-next)
10494 (org-set-current-tags-overlay current ov-prefix)
10495 (setq tbl fulltable char ?a cnt 0)
10496 (while (setq e (pop tbl))
10497 (cond
10498 ((equal e '(:startgroup))
10499 (push '() groups) (setq ingroup t)
10500 (when (not (= cnt 0))
10501 (setq cnt 0)
10502 (insert "\n"))
10503 (insert "{ "))
10504 ((equal e '(:endgroup))
10505 (setq ingroup nil cnt 0)
10506 (insert "}\n"))
10507 ((equal e '(:newline))
10508 (when (not (= cnt 0))
10509 (setq cnt 0)
10510 (insert "\n")
10511 (setq e (car tbl))
10512 (while (equal (car tbl) '(:newline))
10513 (insert "\n")
10514 (setq tbl (cdr tbl)))))
10516 (setq tg (car e) c2 nil)
10517 (if (cdr e)
10518 (setq c (cdr e))
10519 ;; automatically assign a character.
10520 (setq c1 (string-to-char
10521 (downcase (substring
10522 tg (if (= (string-to-char tg) ?@) 1 0)))))
10523 (if (or (rassoc c1 ntable) (rassoc c1 table))
10524 (while (or (rassoc char ntable) (rassoc char table))
10525 (setq char (1+ char)))
10526 (setq c2 c1))
10527 (setq c (or c2 char)))
10528 (if ingroup (push tg (car groups)))
10529 (setq tg (org-add-props tg nil 'face
10530 (cond
10531 ((not (assoc tg table))
10532 (org-get-todo-face tg))
10533 ((member tg current) c-face)
10534 ((member tg inherited) i-face)
10535 (t nil))))
10536 (if (and (= cnt 0) (not ingroup)) (insert " "))
10537 (insert "[" c "] " tg (make-string
10538 (- fwidth 4 (length tg)) ?\ ))
10539 (push (cons tg c) ntable)
10540 (when (= (setq cnt (1+ cnt)) ncol)
10541 (insert "\n")
10542 (if ingroup (insert " "))
10543 (setq cnt 0)))))
10544 (setq ntable (nreverse ntable))
10545 (insert "\n")
10546 (goto-char (point-min))
10547 (if (not expert) (org-fit-window-to-buffer))
10548 (setq rtn
10549 (catch 'exit
10550 (while t
10551 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10552 (if groups " [!] no groups" " [!]groups")
10553 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10554 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10555 (cond
10556 ((= c ?\r) (throw 'exit t))
10557 ((= c ?!)
10558 (setq groups (not groups))
10559 (goto-char (point-min))
10560 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10561 ((= c ?\C-c)
10562 (if (not expert)
10563 (org-fast-tag-show-exit
10564 (setq exit-after-next (not exit-after-next)))
10565 (setq expert nil)
10566 (delete-other-windows)
10567 (split-window-vertically)
10568 (org-switch-to-buffer-other-window " *Org tags*")
10569 (org-fit-window-to-buffer)))
10570 ((or (= c ?\C-g)
10571 (and (= c ?q) (not (rassoc c ntable))))
10572 (org-detach-overlay org-tags-overlay)
10573 (setq quit-flag t))
10574 ((= c ?\ )
10575 (setq current nil)
10576 (if exit-after-next (setq exit-after-next 'now)))
10577 ((= c ?\t)
10578 (condition-case nil
10579 (setq tg (org-ido-completing-read
10580 "Tag: "
10581 (or buffer-tags
10582 (with-current-buffer buf
10583 (org-get-buffer-tags)))))
10584 (quit (setq tg "")))
10585 (when (string-match "\\S-" tg)
10586 (add-to-list 'buffer-tags (list tg))
10587 (if (member tg current)
10588 (setq current (delete tg current))
10589 (push tg current)))
10590 (if exit-after-next (setq exit-after-next 'now)))
10591 ((setq e (rassoc c todo-table) tg (car e))
10592 (with-current-buffer buf
10593 (save-excursion (org-todo tg)))
10594 (if exit-after-next (setq exit-after-next 'now)))
10595 ((setq e (rassoc c ntable) tg (car e))
10596 (if (member tg current)
10597 (setq current (delete tg current))
10598 (loop for g in groups do
10599 (if (member tg g)
10600 (mapc (lambda (x)
10601 (setq current (delete x current)))
10602 g)))
10603 (push tg current))
10604 (if exit-after-next (setq exit-after-next 'now))))
10606 ;; Create a sorted list
10607 (setq current
10608 (sort current
10609 (lambda (a b)
10610 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10611 (if (eq exit-after-next 'now) (throw 'exit t))
10612 (goto-char (point-min))
10613 (beginning-of-line 2)
10614 (delete-region (point) (point-at-eol))
10615 (org-fast-tag-insert "Current" current c-face)
10616 (org-set-current-tags-overlay current ov-prefix)
10617 (while (re-search-forward
10618 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10619 (setq tg (match-string 1))
10620 (add-text-properties
10621 (match-beginning 1) (match-end 1)
10622 (list 'face
10623 (cond
10624 ((member tg current) c-face)
10625 ((member tg inherited) i-face)
10626 (t (get-text-property (match-beginning 1) 'face))))))
10627 (goto-char (point-min)))))
10628 (org-detach-overlay org-tags-overlay)
10629 (if rtn
10630 (mapconcat 'identity current ":")
10631 nil))))
10633 (defun org-get-tags-string ()
10634 "Get the TAGS string in the current headline."
10635 (unless (org-on-heading-p t)
10636 (error "Not on a heading"))
10637 (save-excursion
10638 (beginning-of-line 1)
10639 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10640 (org-match-string-no-properties 1)
10641 "")))
10643 (defun org-get-tags ()
10644 "Get the list of tags specified in the current headline."
10645 (org-split-string (org-get-tags-string) ":"))
10647 (defun org-get-buffer-tags ()
10648 "Get a table of all tags used in the buffer, for completion."
10649 (let (tags)
10650 (save-excursion
10651 (goto-char (point-min))
10652 (while (re-search-forward
10653 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10654 (when (equal (char-after (point-at-bol 0)) ?*)
10655 (mapc (lambda (x) (add-to-list 'tags x))
10656 (org-split-string (org-match-string-no-properties 1) ":")))))
10657 (mapcar 'list tags)))
10659 ;;;; The mapping API
10661 ;;;###autoload
10662 (defun org-map-entries (func &optional match scope &rest skip)
10663 "Call FUNC at each headline selected by MATCH in SCOPE.
10665 FUNC is a function or a lisp form. The function will be called without
10666 arguments, with the cursor positioned at the beginning of the headline.
10667 The return values of all calls to the function will be collected and
10668 returned as a list.
10670 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10671 Only headlines that are matched by this query will be considered during
10672 the iteration. When MATCH is nil or t, all headlines will be
10673 visited by the iteration.
10675 SCOPE determines the scope of this command. It can be any of:
10677 nil The current buffer, respecting the restriction if any
10678 tree The subtree started with the entry at point
10679 file The current buffer, without restriction
10680 file-with-archives
10681 The current buffer, and any archives associated with it
10682 agenda All agenda files
10683 agenda-with-archives
10684 All agenda files with any archive files associated with them
10685 \(file1 file2 ...)
10686 If this is a list, all files in the list will be scanned
10688 The remaining args are treated as settings for the skipping facilities of
10689 the scanner. The following items can be given here:
10691 archive skip trees with the archive tag.
10692 comment skip trees with the COMMENT keyword
10693 function or Emacs Lisp form:
10694 will be used as value for `org-agenda-skip-function', so whenever
10695 the the function returns t, FUNC will not be called for that
10696 entry and search will continue from the point where the
10697 function leaves it.
10699 If your function needs to retrieve the tags including inherited tags
10700 at the *current* entry, you can use the value of the variable
10701 `org-scanner-tags' which will be much faster than getting the value
10702 with `org-get-tags-at'. If your function gets properties with
10703 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
10704 to t around the call to `org-entry-properties' to get the same speedup.
10705 Note that if your function moves around to retrieve tags and properties at
10706 a *different* entry, you cannot use these techniques."
10707 (let* ((org-agenda-archives-mode nil) ; just to make sure
10708 (org-agenda-skip-archived-trees (memq 'archive skip))
10709 (org-agenda-skip-comment-trees (memq 'comment skip))
10710 (org-agenda-skip-function
10711 (car (org-delete-all '(comment archive) skip)))
10712 (org-tags-match-list-sublevels t)
10713 matcher file res
10714 org-todo-keywords-for-agenda
10715 org-done-keywords-for-agenda
10716 org-todo-keyword-alist-for-agenda
10717 org-tag-alist-for-agenda)
10719 (cond
10720 ((eq match t) (setq matcher t))
10721 ((eq match nil) (setq matcher t))
10722 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10724 (save-excursion
10725 (save-restriction
10726 (when (eq scope 'tree)
10727 (org-back-to-heading t)
10728 (org-narrow-to-subtree)
10729 (setq scope nil))
10731 (if (not scope)
10732 (progn
10733 (org-prepare-agenda-buffers
10734 (list (buffer-file-name (current-buffer))))
10735 (setq res (org-scan-tags func matcher)))
10736 ;; Get the right scope
10737 (cond
10738 ((and scope (listp scope) (symbolp (car scope)))
10739 (setq scope (eval scope)))
10740 ((eq scope 'agenda)
10741 (setq scope (org-agenda-files t)))
10742 ((eq scope 'agenda-with-archives)
10743 (setq scope (org-agenda-files t))
10744 (setq scope (org-add-archive-files scope)))
10745 ((eq scope 'file)
10746 (setq scope (list (buffer-file-name))))
10747 ((eq scope 'file-with-archives)
10748 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10749 (org-prepare-agenda-buffers scope)
10750 (while (setq file (pop scope))
10751 (with-current-buffer (org-find-base-buffer-visiting file)
10752 (save-excursion
10753 (save-restriction
10754 (widen)
10755 (goto-char (point-min))
10756 (setq res (append res (org-scan-tags func matcher))))))))))
10757 res))
10759 ;;;; Properties
10761 ;;; Setting and retrieving properties
10763 (defconst org-special-properties
10764 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10765 "TIMESTAMP" "TIMESTAMP_IA")
10766 "The special properties valid in Org-mode.
10768 These are properties that are not defined in the property drawer,
10769 but in some other way.")
10771 (defconst org-default-properties
10772 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10773 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10774 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10775 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10776 "Some properties that are used by Org-mode for various purposes.
10777 Being in this list makes sure that they are offered for completion.")
10779 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10780 "Regular expression matching the first line of a property drawer.")
10782 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10783 "Regular expression matching the first line of a property drawer.")
10785 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10786 "Regular expression matching the first line of a property drawer.")
10788 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10789 "Regular expression matching the first line of a property drawer.")
10791 (defconst org-property-drawer-re
10792 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10793 org-property-end-re "\\)\n?")
10794 "Matches an entire property drawer.")
10796 (defconst org-clock-drawer-re
10797 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10798 org-property-end-re "\\)\n?")
10799 "Matches an entire clock drawer.")
10801 (defun org-property-action ()
10802 "Do an action on properties."
10803 (interactive)
10804 (let (c)
10805 (org-at-property-p)
10806 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10807 (setq c (read-char-exclusive))
10808 (cond
10809 ((equal c ?s)
10810 (call-interactively 'org-set-property))
10811 ((equal c ?d)
10812 (call-interactively 'org-delete-property))
10813 ((equal c ?D)
10814 (call-interactively 'org-delete-property-globally))
10815 ((equal c ?c)
10816 (call-interactively 'org-compute-property-at-point))
10817 (t (error "No such property action %c" c)))))
10819 (defun org-at-property-p ()
10820 "Is the cursor in a property line?"
10821 ;; FIXME: Does not check if we are actually in the drawer.
10822 ;; FIXME: also returns true on any drawers.....
10823 ;; This is used by C-c C-c for property action.
10824 (save-excursion
10825 (beginning-of-line 1)
10826 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10828 (defun org-get-property-block (&optional beg end force)
10829 "Return the (beg . end) range of the body of the property drawer.
10830 BEG and END can be beginning and end of subtree, if not given
10831 they will be found.
10832 If the drawer does not exist and FORCE is non-nil, create the drawer."
10833 (catch 'exit
10834 (save-excursion
10835 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10836 (end (or end (progn (outline-next-heading) (point)))))
10837 (goto-char beg)
10838 (if (re-search-forward org-property-start-re end t)
10839 (setq beg (1+ (match-end 0)))
10840 (if force
10841 (save-excursion
10842 (org-insert-property-drawer)
10843 (setq end (progn (outline-next-heading) (point))))
10844 (throw 'exit nil))
10845 (goto-char beg)
10846 (if (re-search-forward org-property-start-re end t)
10847 (setq beg (1+ (match-end 0)))))
10848 (if (re-search-forward org-property-end-re end t)
10849 (setq end (match-beginning 0))
10850 (or force (throw 'exit nil))
10851 (goto-char beg)
10852 (setq end beg)
10853 (org-indent-line-function)
10854 (insert ":END:\n"))
10855 (cons beg end)))))
10857 (defun org-entry-properties (&optional pom which)
10858 "Get all properties of the entry at point-or-marker POM.
10859 This includes the TODO keyword, the tags, time strings for deadline,
10860 scheduled, and clocking, and any additional properties defined in the
10861 entry. The return value is an alist, keys may occur multiple times
10862 if the property key was used several times.
10863 POM may also be nil, in which case the current entry is used.
10864 If WHICH is nil or `all', get all properties. If WHICH is
10865 `special' or `standard', only get that subclass."
10866 (setq which (or which 'all))
10867 (org-with-point-at pom
10868 (let ((clockstr (substring org-clock-string 0 -1))
10869 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10870 beg end range props sum-props key value string clocksum)
10871 (save-excursion
10872 (when (condition-case nil
10873 (and (org-mode-p) (org-back-to-heading t))
10874 (error nil))
10875 (setq beg (point))
10876 (setq sum-props (get-text-property (point) 'org-summaries))
10877 (setq clocksum (get-text-property (point) :org-clock-minutes))
10878 (outline-next-heading)
10879 (setq end (point))
10880 (when (memq which '(all special))
10881 ;; Get the special properties, like TODO and tags
10882 (goto-char beg)
10883 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10884 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10885 (when (looking-at org-priority-regexp)
10886 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10887 (when (and (setq value (org-get-tags-string))
10888 (string-match "\\S-" value))
10889 (push (cons "TAGS" value) props))
10890 (when (setq value (org-get-tags-at))
10891 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10892 props))
10893 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10894 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10895 string (if (equal key clockstr)
10896 (org-no-properties
10897 (org-trim
10898 (buffer-substring
10899 (match-beginning 3) (goto-char (point-at-eol)))))
10900 (substring (org-match-string-no-properties 3) 1 -1)))
10901 (unless key
10902 (if (= (char-after (match-beginning 3)) ?\[)
10903 (setq key "TIMESTAMP_IA")
10904 (setq key "TIMESTAMP")))
10905 (when (or (equal key clockstr) (not (assoc key props)))
10906 (push (cons key string) props)))
10910 (when (memq which '(all standard))
10911 ;; Get the standard properties, like :PROP: ...
10912 (setq range (org-get-property-block beg end))
10913 (when range
10914 (goto-char (car range))
10915 (while (re-search-forward
10916 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10917 (cdr range) t)
10918 (setq key (org-match-string-no-properties 1)
10919 value (org-trim (or (org-match-string-no-properties 2) "")))
10920 (unless (member key excluded)
10921 (push (cons key (or value "")) props)))))
10922 (if clocksum
10923 (push (cons "CLOCKSUM"
10924 (org-columns-number-to-string (/ (float clocksum) 60.)
10925 'add_times))
10926 props))
10927 (unless (assoc "CATEGORY" props)
10928 (setq value (or (org-get-category)
10929 (progn (org-refresh-category-properties)
10930 (org-get-category))))
10931 (push (cons "CATEGORY" value) props))
10932 (append sum-props (nreverse props)))))))
10934 (defun org-entry-get (pom property &optional inherit)
10935 "Get value of PROPERTY for entry at point-or-marker POM.
10936 If INHERIT is non-nil and the entry does not have the property,
10937 then also check higher levels of the hierarchy.
10938 If INHERIT is the symbol `selective', use inheritance only if the setting
10939 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10940 If the property is present but empty, the return value is the empty string.
10941 If the property is not present at all, nil is returned."
10942 (org-with-point-at pom
10943 (if (and inherit (if (eq inherit 'selective)
10944 (org-property-inherit-p property)
10946 (org-entry-get-with-inheritance property)
10947 (if (member property org-special-properties)
10948 ;; We need a special property. Use brute force, get all properties.
10949 (cdr (assoc property (org-entry-properties nil 'special)))
10950 (let ((range (org-get-property-block)))
10951 (if (and range
10952 (goto-char (car range))
10953 (re-search-forward
10954 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10955 (cdr range) t))
10956 ;; Found the property, return it.
10957 (if (match-end 1)
10958 (org-match-string-no-properties 1)
10959 "")))))))
10961 (defun org-property-or-variable-value (var &optional inherit)
10962 "Check if there is a property fixing the value of VAR.
10963 If yes, return this value. If not, return the current value of the variable."
10964 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10965 (if (and prop (stringp prop) (string-match "\\S-" prop))
10966 (read prop)
10967 (symbol-value var))))
10969 (defun org-entry-delete (pom property)
10970 "Delete the property PROPERTY from entry at point-or-marker POM."
10971 (org-with-point-at pom
10972 (if (member property org-special-properties)
10973 nil ; cannot delete these properties.
10974 (let ((range (org-get-property-block)))
10975 (if (and range
10976 (goto-char (car range))
10977 (re-search-forward
10978 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10979 (cdr range) t))
10980 (progn
10981 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10983 nil)))))
10985 ;; Multi-values properties are properties that contain multiple values
10986 ;; These values are assumed to be single words, separated by whitespace.
10987 (defun org-entry-add-to-multivalued-property (pom property value)
10988 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10989 (let* ((old (org-entry-get pom property))
10990 (values (and old (org-split-string old "[ \t]"))))
10991 (setq value (org-entry-protect-space value))
10992 (unless (member value values)
10993 (setq values (cons value values))
10994 (org-entry-put pom property
10995 (mapconcat 'identity values " ")))))
10997 (defun org-entry-remove-from-multivalued-property (pom property value)
10998 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10999 (let* ((old (org-entry-get pom property))
11000 (values (and old (org-split-string old "[ \t]"))))
11001 (setq value (org-entry-protect-space value))
11002 (when (member value values)
11003 (setq values (delete value values))
11004 (org-entry-put pom property
11005 (mapconcat 'identity values " ")))))
11007 (defun org-entry-member-in-multivalued-property (pom property value)
11008 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11009 (let* ((old (org-entry-get pom property))
11010 (values (and old (org-split-string old "[ \t]"))))
11011 (setq value (org-entry-protect-space value))
11012 (member value values)))
11014 (defun org-entry-get-multivalued-property (pom property)
11015 "Return a list of values in a multivalued property."
11016 (let* ((value (org-entry-get pom property))
11017 (values (and value (org-split-string value "[ \t]"))))
11018 (mapcar 'org-entry-restore-space values)))
11020 (defun org-entry-put-multivalued-property (pom property &rest values)
11021 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11022 VALUES should be a list of strings. Spaces will be protected."
11023 (org-entry-put pom property
11024 (mapconcat 'org-entry-protect-space values " "))
11025 (let* ((value (org-entry-get pom property))
11026 (values (and value (org-split-string value "[ \t]"))))
11027 (mapcar 'org-entry-restore-space values)))
11029 (defun org-entry-protect-space (s)
11030 "Protect spaces and newline in string S."
11031 (while (string-match " " s)
11032 (setq s (replace-match "%20" t t s)))
11033 (while (string-match "\n" s)
11034 (setq s (replace-match "%0A" t t s)))
11037 (defun org-entry-restore-space (s)
11038 "Restore spaces and newline in string S."
11039 (while (string-match "%20" s)
11040 (setq s (replace-match " " t t s)))
11041 (while (string-match "%0A" s)
11042 (setq s (replace-match "\n" t t s)))
11045 (defvar org-entry-property-inherited-from (make-marker)
11046 "Marker pointing to the entry from where a property was inherited.
11047 Each call to `org-entry-get-with-inheritance' will set this marker to the
11048 location of the entry where the inheritance search matched. If there was
11049 no match, the marker will point nowhere.
11050 Note that also `org-entry-get' calls this function, if the INHERIT flag
11051 is set.")
11053 (defun org-entry-get-with-inheritance (property)
11054 "Get entry property, and search higher levels if not present."
11055 (move-marker org-entry-property-inherited-from nil)
11056 (let (tmp)
11057 (save-excursion
11058 (save-restriction
11059 (widen)
11060 (catch 'ex
11061 (while t
11062 (when (setq tmp (org-entry-get nil property))
11063 (org-back-to-heading t)
11064 (move-marker org-entry-property-inherited-from (point))
11065 (throw 'ex tmp))
11066 (or (org-up-heading-safe) (throw 'ex nil)))))
11067 (or tmp
11068 (cdr (assoc property org-file-properties))
11069 (cdr (assoc property org-global-properties))
11070 (cdr (assoc property org-global-properties-fixed))))))
11072 (defun org-entry-put (pom property value)
11073 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11074 (org-with-point-at pom
11075 (org-back-to-heading t)
11076 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11077 range)
11078 (cond
11079 ((equal property "TODO")
11080 (when (and (stringp value) (string-match "\\S-" value)
11081 (not (member value org-todo-keywords-1)))
11082 (error "\"%s\" is not a valid TODO state" value))
11083 (if (or (not value)
11084 (not (string-match "\\S-" value)))
11085 (setq value 'none))
11086 (org-todo value)
11087 (org-set-tags nil 'align))
11088 ((equal property "PRIORITY")
11089 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11090 (string-to-char value) ?\ ))
11091 (org-set-tags nil 'align))
11092 ((equal property "SCHEDULED")
11093 (if (re-search-forward org-scheduled-time-regexp end t)
11094 (cond
11095 ((eq value 'earlier) (org-timestamp-change -1 'day))
11096 ((eq value 'later) (org-timestamp-change 1 'day))
11097 (t (call-interactively 'org-schedule)))
11098 (call-interactively 'org-schedule)))
11099 ((equal property "DEADLINE")
11100 (if (re-search-forward org-deadline-time-regexp end t)
11101 (cond
11102 ((eq value 'earlier) (org-timestamp-change -1 'day))
11103 ((eq value 'later) (org-timestamp-change 1 'day))
11104 (t (call-interactively 'org-deadline)))
11105 (call-interactively 'org-deadline)))
11106 ((member property org-special-properties)
11107 (error "The %s property can not yet be set with `org-entry-put'"
11108 property))
11109 (t ; a non-special property
11110 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11111 (setq range (org-get-property-block beg end 'force))
11112 (goto-char (car range))
11113 (if (re-search-forward
11114 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11115 (progn
11116 (delete-region (match-beginning 1) (match-end 1))
11117 (goto-char (match-beginning 1)))
11118 (goto-char (cdr range))
11119 (insert "\n")
11120 (backward-char 1)
11121 (org-indent-line-function)
11122 (insert ":" property ":"))
11123 (and value (insert " " value))
11124 (org-indent-line-function)))))))
11126 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11127 "Get all property keys in the current buffer.
11128 With INCLUDE-SPECIALS, also list the special properties that reflect things
11129 like tags and TODO state.
11130 With INCLUDE-DEFAULTS, also include properties that has special meaning
11131 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11132 With INCLUDE-COLUMNS, also include property names given in COLUMN
11133 formats in the current buffer."
11134 (let (rtn range cfmt s p)
11135 (save-excursion
11136 (save-restriction
11137 (widen)
11138 (goto-char (point-min))
11139 (while (re-search-forward org-property-start-re nil t)
11140 (setq range (org-get-property-block))
11141 (goto-char (car range))
11142 (while (re-search-forward
11143 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11144 (cdr range) t)
11145 (add-to-list 'rtn (org-match-string-no-properties 1)))
11146 (outline-next-heading))))
11148 (when include-specials
11149 (setq rtn (append org-special-properties rtn)))
11151 (when include-defaults
11152 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11154 (when include-columns
11155 (save-excursion
11156 (save-restriction
11157 (widen)
11158 (goto-char (point-min))
11159 (while (re-search-forward
11160 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11161 nil t)
11162 (setq cfmt (match-string 2) s 0)
11163 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11164 cfmt s)
11165 (setq s (match-end 0)
11166 p (match-string 1 cfmt))
11167 (unless (or (equal p "ITEM")
11168 (member p org-special-properties))
11169 (add-to-list 'rtn (match-string 1 cfmt))))))))
11171 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11173 (defun org-property-values (key)
11174 "Return a list of all values of property KEY."
11175 (save-excursion
11176 (save-restriction
11177 (widen)
11178 (goto-char (point-min))
11179 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11180 values)
11181 (while (re-search-forward re nil t)
11182 (add-to-list 'values (org-trim (match-string 1))))
11183 (delete "" values)))))
11185 (defun org-insert-property-drawer ()
11186 "Insert a property drawer into the current entry."
11187 (interactive)
11188 (org-back-to-heading t)
11189 (looking-at outline-regexp)
11190 (let ((indent (- (match-end 0)(match-beginning 0)))
11191 (beg (point))
11192 (re (concat "^[ \t]*" org-keyword-time-regexp))
11193 end hiddenp)
11194 (outline-next-heading)
11195 (setq end (point))
11196 (goto-char beg)
11197 (while (re-search-forward re end t))
11198 (setq hiddenp (org-invisible-p))
11199 (end-of-line 1)
11200 (and (equal (char-after) ?\n) (forward-char 1))
11201 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11202 (if (member (match-string 1) '("CLOCK:" ":END:"))
11203 ;; just skip this line
11204 (beginning-of-line 2)
11205 ;; Drawer start, find the end
11206 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11207 (beginning-of-line 1)))
11208 (org-skip-over-state-notes)
11209 (skip-chars-backward " \t\n\r")
11210 (if (eq (char-before) ?*) (forward-char 1))
11211 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11212 (beginning-of-line 0)
11213 (org-indent-to-column indent)
11214 (beginning-of-line 2)
11215 (org-indent-to-column indent)
11216 (beginning-of-line 0)
11217 (if hiddenp
11218 (save-excursion
11219 (org-back-to-heading t)
11220 (hide-entry))
11221 (org-flag-drawer t))))
11223 (defun org-set-property (property value)
11224 "In the current entry, set PROPERTY to VALUE.
11225 When called interactively, this will prompt for a property name, offering
11226 completion on existing and default properties. And then it will prompt
11227 for a value, offering completion either on allowed values (via an inherited
11228 xxx_ALL property) or on existing values in other instances of this property
11229 in the current file."
11230 (interactive
11231 (let* ((completion-ignore-case t)
11232 (keys (org-buffer-property-keys nil t t))
11233 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11234 (prop (if (member prop0 keys)
11235 prop0
11236 (or (cdr (assoc (downcase prop0)
11237 (mapcar (lambda (x) (cons (downcase x) x))
11238 keys)))
11239 prop0)))
11240 (cur (org-entry-get nil prop))
11241 (allowed (org-property-get-allowed-values nil prop 'table))
11242 (existing (mapcar 'list (org-property-values prop)))
11243 (val (if allowed
11244 (org-completing-read "Value: " allowed nil 'req-match)
11245 (let (org-completion-use-ido)
11246 (org-completing-read
11247 (concat "Value" (if (and cur (string-match "\\S-" cur))
11248 (concat "[" cur "]") "")
11249 ": ")
11250 existing nil nil "" nil cur)))))
11251 (list prop (if (equal val "") cur val))))
11252 (unless (equal (org-entry-get nil property) value)
11253 (org-entry-put nil property value)))
11255 (defun org-delete-property (property)
11256 "In the current entry, delete PROPERTY."
11257 (interactive
11258 (let* ((completion-ignore-case t)
11259 (prop (org-ido-completing-read
11260 "Property: " (org-entry-properties nil 'standard))))
11261 (list prop)))
11262 (message "Property %s %s" property
11263 (if (org-entry-delete nil property)
11264 "deleted"
11265 "was not present in the entry")))
11267 (defun org-delete-property-globally (property)
11268 "Remove PROPERTY globally, from all entries."
11269 (interactive
11270 (let* ((completion-ignore-case t)
11271 (prop (org-ido-completing-read
11272 "Globally remove property: "
11273 (mapcar 'list (org-buffer-property-keys)))))
11274 (list prop)))
11275 (save-excursion
11276 (save-restriction
11277 (widen)
11278 (goto-char (point-min))
11279 (let ((cnt 0))
11280 (while (re-search-forward
11281 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11282 nil t)
11283 (setq cnt (1+ cnt))
11284 (replace-match ""))
11285 (message "Property \"%s\" removed from %d entries" property cnt)))))
11287 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11289 (defun org-compute-property-at-point ()
11290 "Compute the property at point.
11291 This looks for an enclosing column format, extracts the operator and
11292 then applies it to the property in the column format's scope."
11293 (interactive)
11294 (unless (org-at-property-p)
11295 (error "Not at a property"))
11296 (let ((prop (org-match-string-no-properties 2)))
11297 (org-columns-get-format-and-top-level)
11298 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11299 (error "No operator defined for property %s" prop))
11300 (org-columns-compute prop)))
11302 (defun org-property-get-allowed-values (pom property &optional table)
11303 "Get allowed values for the property PROPERTY.
11304 When TABLE is non-nil, return an alist that can directly be used for
11305 completion."
11306 (let (vals)
11307 (cond
11308 ((equal property "TODO")
11309 (setq vals (org-with-point-at pom
11310 (append org-todo-keywords-1 '("")))))
11311 ((equal property "PRIORITY")
11312 (let ((n org-lowest-priority))
11313 (while (>= n org-highest-priority)
11314 (push (char-to-string n) vals)
11315 (setq n (1- n)))))
11316 ((member property org-special-properties))
11318 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11320 (when (and vals (string-match "\\S-" vals))
11321 (setq vals (car (read-from-string (concat "(" vals ")"))))
11322 (setq vals (mapcar (lambda (x)
11323 (cond ((stringp x) x)
11324 ((numberp x) (number-to-string x))
11325 ((symbolp x) (symbol-name x))
11326 (t "???")))
11327 vals)))))
11328 (if table (mapcar 'list vals) vals)))
11330 (defun org-property-previous-allowed-value (&optional previous)
11331 "Switch to the next allowed value for this property."
11332 (interactive)
11333 (org-property-next-allowed-value t))
11335 (defun org-property-next-allowed-value (&optional previous)
11336 "Switch to the next allowed value for this property."
11337 (interactive)
11338 (unless (org-at-property-p)
11339 (error "Not at a property"))
11340 (let* ((key (match-string 2))
11341 (value (match-string 3))
11342 (allowed (or (org-property-get-allowed-values (point) key)
11343 (and (member value '("[ ]" "[-]" "[X]"))
11344 '("[ ]" "[X]"))))
11345 nval)
11346 (unless allowed
11347 (error "Allowed values for this property have not been defined"))
11348 (if previous (setq allowed (reverse allowed)))
11349 (if (member value allowed)
11350 (setq nval (car (cdr (member value allowed)))))
11351 (setq nval (or nval (car allowed)))
11352 (if (equal nval value)
11353 (error "Only one allowed value for this property"))
11354 (org-at-property-p)
11355 (replace-match (concat " :" key ": " nval) t t)
11356 (org-indent-line-function)
11357 (beginning-of-line 1)
11358 (skip-chars-forward " \t")))
11360 (defun org-find-entry-with-id (ident)
11361 "Locate the entry that contains the ID property with exact value IDENT.
11362 IDENT can be a string, a symbol or a number, this function will search for
11363 the string representation of it.
11364 Return the position where this entry starts, or nil if there is no such entry."
11365 (interactive "sID: ")
11366 (let ((id (cond
11367 ((stringp ident) ident)
11368 ((symbol-name ident) (symbol-name ident))
11369 ((numberp ident) (number-to-string ident))
11370 (t (error "IDENT %s must be a string, symbol or number" ident))))
11371 (case-fold-search nil))
11372 (save-excursion
11373 (save-restriction
11374 (widen)
11375 (goto-char (point-min))
11376 (when (re-search-forward
11377 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11378 nil t)
11379 (org-back-to-heading)
11380 (point))))))
11382 ;;;; Timestamps
11384 (defvar org-last-changed-timestamp nil)
11385 (defvar org-last-inserted-timestamp nil
11386 "The last time stamp inserted with `org-insert-time-stamp'.")
11387 (defvar org-time-was-given) ; dynamically scoped parameter
11388 (defvar org-end-time-was-given) ; dynamically scoped parameter
11389 (defvar org-ts-what) ; dynamically scoped parameter
11391 (defun org-time-stamp (arg &optional inactive)
11392 "Prompt for a date/time and insert a time stamp.
11393 If the user specifies a time like HH:MM, or if this command is called
11394 with a prefix argument, the time stamp will contain date and time.
11395 Otherwise, only the date will be included. All parts of a date not
11396 specified by the user will be filled in from the current date/time.
11397 So if you press just return without typing anything, the time stamp
11398 will represent the current date/time. If there is already a timestamp
11399 at the cursor, it will be modified."
11400 (interactive "P")
11401 (let* ((ts nil)
11402 (default-time
11403 ;; Default time is either today, or, when entering a range,
11404 ;; the range start.
11405 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11406 (save-excursion
11407 (re-search-backward
11408 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11409 (- (point) 20) t)))
11410 (apply 'encode-time (org-parse-time-string (match-string 1)))
11411 (current-time)))
11412 (default-input (and ts (org-get-compact-tod ts)))
11413 org-time-was-given org-end-time-was-given time)
11414 (cond
11415 ((and (org-at-timestamp-p t)
11416 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11417 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11418 (insert "--")
11419 (setq time (let ((this-command this-command))
11420 (org-read-date arg 'totime nil nil
11421 default-time default-input)))
11422 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11423 ((org-at-timestamp-p t)
11424 (setq time (let ((this-command this-command))
11425 (org-read-date arg 'totime nil nil default-time default-input)))
11426 (when (org-at-timestamp-p t) ; just to get the match data
11427 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11428 (replace-match "")
11429 (setq org-last-changed-timestamp
11430 (org-insert-time-stamp
11431 time (or org-time-was-given arg)
11432 inactive nil nil (list org-end-time-was-given))))
11433 (message "Timestamp updated"))
11435 (setq time (let ((this-command this-command))
11436 (org-read-date arg 'totime nil nil default-time default-input)))
11437 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11438 nil nil (list org-end-time-was-given))))))
11440 ;; FIXME: can we use this for something else, like computing time differences?
11441 (defun org-get-compact-tod (s)
11442 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11443 (let* ((t1 (match-string 1 s))
11444 (h1 (string-to-number (match-string 2 s)))
11445 (m1 (string-to-number (match-string 3 s)))
11446 (t2 (and (match-end 4) (match-string 5 s)))
11447 (h2 (and t2 (string-to-number (match-string 6 s))))
11448 (m2 (and t2 (string-to-number (match-string 7 s))))
11449 dh dm)
11450 (if (not t2)
11452 (setq dh (- h2 h1) dm (- m2 m1))
11453 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11454 (concat t1 "+" (number-to-string dh)
11455 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11457 (defun org-time-stamp-inactive (&optional arg)
11458 "Insert an inactive time stamp.
11459 An inactive time stamp is enclosed in square brackets instead of angle
11460 brackets. It is inactive in the sense that it does not trigger agenda entries,
11461 does not link to the calendar and cannot be changed with the S-cursor keys.
11462 So these are more for recording a certain time/date."
11463 (interactive "P")
11464 (org-time-stamp arg 'inactive))
11466 (defvar org-date-ovl (org-make-overlay 1 1))
11467 (org-overlay-put org-date-ovl 'face 'org-warning)
11468 (org-detach-overlay org-date-ovl)
11470 (defvar org-ans1) ; dynamically scoped parameter
11471 (defvar org-ans2) ; dynamically scoped parameter
11473 (defvar org-plain-time-of-day-regexp) ; defined below
11475 (defvar org-overriding-default-time nil) ; dynamically scoped
11476 (defvar org-read-date-overlay nil)
11477 (defvar org-dcst nil) ; dynamically scoped
11479 (defun org-read-date (&optional with-time to-time from-string prompt
11480 default-time default-input)
11481 "Read a date, possibly a time, and make things smooth for the user.
11482 The prompt will suggest to enter an ISO date, but you can also enter anything
11483 which will at least partially be understood by `parse-time-string'.
11484 Unrecognized parts of the date will default to the current day, month, year,
11485 hour and minute. If this command is called to replace a timestamp at point,
11486 of to enter the second timestamp of a range, the default time is taken from the
11487 existing stamp. For example,
11488 3-2-5 --> 2003-02-05
11489 feb 15 --> currentyear-02-15
11490 sep 12 9 --> 2009-09-12
11491 12:45 --> today 12:45
11492 22 sept 0:34 --> currentyear-09-22 0:34
11493 12 --> currentyear-currentmonth-12
11494 Fri --> nearest Friday (today or later)
11495 etc.
11497 Furthermore you can specify a relative date by giving, as the *first* thing
11498 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11499 change in days weeks, months, years.
11500 With a single plus or minus, the date is relative to today. With a double
11501 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11502 +4d --> four days from today
11503 +4 --> same as above
11504 +2w --> two weeks from today
11505 ++5 --> five days from default date
11507 The function understands only English month and weekday abbreviations,
11508 but this can be configured with the variables `parse-time-months' and
11509 `parse-time-weekdays'.
11511 While prompting, a calendar is popped up - you can also select the
11512 date with the mouse (button 1). The calendar shows a period of three
11513 months. To scroll it to other months, use the keys `>' and `<'.
11514 If you don't like the calendar, turn it off with
11515 \(setq org-read-date-popup-calendar nil)
11517 With optional argument TO-TIME, the date will immediately be converted
11518 to an internal time.
11519 With an optional argument WITH-TIME, the prompt will suggest to also
11520 insert a time. Note that when WITH-TIME is not set, you can still
11521 enter a time, and this function will inform the calling routine about
11522 this change. The calling routine may then choose to change the format
11523 used to insert the time stamp into the buffer to include the time.
11524 With optional argument FROM-STRING, read from this string instead from
11525 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11526 the time/date that is used for everything that is not specified by the
11527 user."
11528 (require 'parse-time)
11529 (let* ((org-time-stamp-rounding-minutes
11530 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11531 (org-dcst org-display-custom-times)
11532 (ct (org-current-time))
11533 (def (or org-overriding-default-time default-time ct))
11534 (defdecode (decode-time def))
11535 (dummy (progn
11536 (when (< (nth 2 defdecode) org-extend-today-until)
11537 (setcar (nthcdr 2 defdecode) -1)
11538 (setcar (nthcdr 1 defdecode) 59)
11539 (setq def (apply 'encode-time defdecode)
11540 defdecode (decode-time def)))))
11541 (calendar-move-hook nil)
11542 (calendar-view-diary-initially-flag nil)
11543 (view-diary-entries-initially nil)
11544 (calendar-view-holidays-initially-flag nil)
11545 (view-calendar-holidays-initially nil)
11546 (timestr (format-time-string
11547 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11548 (prompt (concat (if prompt (concat prompt " ") "")
11549 (format "Date+time [%s]: " timestr)))
11550 ans (org-ans0 "") org-ans1 org-ans2 final)
11552 (cond
11553 (from-string (setq ans from-string))
11554 (org-read-date-popup-calendar
11555 (save-excursion
11556 (save-window-excursion
11557 (calendar)
11558 (calendar-forward-day (- (time-to-days def)
11559 (calendar-absolute-from-gregorian
11560 (calendar-current-date))))
11561 (org-eval-in-calendar nil t)
11562 (let* ((old-map (current-local-map))
11563 (map (copy-keymap calendar-mode-map))
11564 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11565 (org-defkey map (kbd "RET") 'org-calendar-select)
11566 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11567 'org-calendar-select-mouse)
11568 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11569 'org-calendar-select-mouse)
11570 (org-defkey minibuffer-local-map [(meta shift left)]
11571 (lambda () (interactive)
11572 (org-eval-in-calendar '(calendar-backward-month 1))))
11573 (org-defkey minibuffer-local-map [(meta shift right)]
11574 (lambda () (interactive)
11575 (org-eval-in-calendar '(calendar-forward-month 1))))
11576 (org-defkey minibuffer-local-map [(meta shift up)]
11577 (lambda () (interactive)
11578 (org-eval-in-calendar '(calendar-backward-year 1))))
11579 (org-defkey minibuffer-local-map [(meta shift down)]
11580 (lambda () (interactive)
11581 (org-eval-in-calendar '(calendar-forward-year 1))))
11582 (org-defkey minibuffer-local-map [(shift up)]
11583 (lambda () (interactive)
11584 (org-eval-in-calendar '(calendar-backward-week 1))))
11585 (org-defkey minibuffer-local-map [(shift down)]
11586 (lambda () (interactive)
11587 (org-eval-in-calendar '(calendar-forward-week 1))))
11588 (org-defkey minibuffer-local-map [(shift left)]
11589 (lambda () (interactive)
11590 (org-eval-in-calendar '(calendar-backward-day 1))))
11591 (org-defkey minibuffer-local-map [(shift right)]
11592 (lambda () (interactive)
11593 (org-eval-in-calendar '(calendar-forward-day 1))))
11594 (org-defkey minibuffer-local-map ">"
11595 (lambda () (interactive)
11596 (org-eval-in-calendar '(scroll-calendar-left 1))))
11597 (org-defkey minibuffer-local-map "<"
11598 (lambda () (interactive)
11599 (org-eval-in-calendar '(scroll-calendar-right 1))))
11600 (unwind-protect
11601 (progn
11602 (use-local-map map)
11603 (add-hook 'post-command-hook 'org-read-date-display)
11604 (setq org-ans0 (read-string prompt default-input nil nil))
11605 ;; org-ans0: from prompt
11606 ;; org-ans1: from mouse click
11607 ;; org-ans2: from calendar motion
11608 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11609 (remove-hook 'post-command-hook 'org-read-date-display)
11610 (use-local-map old-map)
11611 (when org-read-date-overlay
11612 (org-delete-overlay org-read-date-overlay)
11613 (setq org-read-date-overlay nil)))))))
11615 (t ; Naked prompt only
11616 (unwind-protect
11617 (setq ans (read-string prompt default-input nil timestr))
11618 (when org-read-date-overlay
11619 (org-delete-overlay org-read-date-overlay)
11620 (setq org-read-date-overlay nil)))))
11622 (setq final (org-read-date-analyze ans def defdecode))
11624 (if to-time
11625 (apply 'encode-time final)
11626 (if (and (boundp 'org-time-was-given) org-time-was-given)
11627 (format "%04d-%02d-%02d %02d:%02d"
11628 (nth 5 final) (nth 4 final) (nth 3 final)
11629 (nth 2 final) (nth 1 final))
11630 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11631 (defvar def)
11632 (defvar defdecode)
11633 (defvar with-time)
11634 (defun org-read-date-display ()
11635 "Display the current date prompt interpretation in the minibuffer."
11636 (when org-read-date-display-live
11637 (when org-read-date-overlay
11638 (org-delete-overlay org-read-date-overlay))
11639 (let ((p (point)))
11640 (end-of-line 1)
11641 (while (not (equal (buffer-substring
11642 (max (point-min) (- (point) 4)) (point))
11643 " "))
11644 (insert " "))
11645 (goto-char p))
11646 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11647 " " (or org-ans1 org-ans2)))
11648 (org-end-time-was-given nil)
11649 (f (org-read-date-analyze ans def defdecode))
11650 (fmts (if org-dcst
11651 org-time-stamp-custom-formats
11652 org-time-stamp-formats))
11653 (fmt (if (or with-time
11654 (and (boundp 'org-time-was-given) org-time-was-given))
11655 (cdr fmts)
11656 (car fmts)))
11657 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11658 (when (and org-end-time-was-given
11659 (string-match org-plain-time-of-day-regexp txt))
11660 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11661 org-end-time-was-given
11662 (substring txt (match-end 0)))))
11663 (setq org-read-date-overlay
11664 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11665 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11667 (defun org-read-date-analyze (ans def defdecode)
11668 "Analyse the combined answer of the date prompt."
11669 ;; FIXME: cleanup and comment
11670 (let (delta deltan deltaw deltadef year month day
11671 hour minute second wday pm h2 m2 tl wday1
11672 iso-year iso-weekday iso-week iso-year iso-date)
11674 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11675 (setq ans "+0"))
11677 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11678 (setq ans (replace-match "" t t ans)
11679 deltan (car delta)
11680 deltaw (nth 1 delta)
11681 deltadef (nth 2 delta)))
11683 ;; Check if there is an iso week date in there
11684 ;; If yes, sore the info and postpone interpreting it until the rest
11685 ;; of the parsing is done
11686 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11687 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11688 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11689 iso-week (string-to-number (match-string 2 ans)))
11690 (setq ans (replace-match "" t t ans)))
11692 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11693 (when (string-match
11694 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11695 (setq year (if (match-end 2)
11696 (string-to-number (match-string 2 ans))
11697 (string-to-number (format-time-string "%Y")))
11698 month (string-to-number (match-string 3 ans))
11699 day (string-to-number (match-string 4 ans)))
11700 (if (< year 100) (setq year (+ 2000 year)))
11701 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11702 t nil ans)))
11703 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11704 ;; If there is a time with am/pm, and *no* time without it, we convert
11705 ;; so that matching will be successful.
11706 (loop for i from 1 to 2 do ; twice, for end time as well
11707 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11708 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11709 (setq hour (string-to-number (match-string 1 ans))
11710 minute (if (match-end 3)
11711 (string-to-number (match-string 3 ans))
11713 pm (equal ?p
11714 (string-to-char (downcase (match-string 4 ans)))))
11715 (if (and (= hour 12) (not pm))
11716 (setq hour 0)
11717 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11718 (setq ans (replace-match (format "%02d:%02d" hour minute)
11719 t t ans))))
11721 ;; Check if a time range is given as a duration
11722 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11723 (setq hour (string-to-number (match-string 1 ans))
11724 h2 (+ hour (string-to-number (match-string 3 ans)))
11725 minute (string-to-number (match-string 2 ans))
11726 m2 (+ minute (if (match-end 5) (string-to-number
11727 (match-string 5 ans))0)))
11728 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11729 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11730 t t ans)))
11732 ;; Check if there is a time range
11733 (when (boundp 'org-end-time-was-given)
11734 (setq org-time-was-given nil)
11735 (when (and (string-match org-plain-time-of-day-regexp ans)
11736 (match-end 8))
11737 (setq org-end-time-was-given (match-string 8 ans))
11738 (setq ans (concat (substring ans 0 (match-beginning 7))
11739 (substring ans (match-end 7))))))
11741 (setq tl (parse-time-string ans)
11742 day (or (nth 3 tl) (nth 3 defdecode))
11743 month (or (nth 4 tl)
11744 (if (and org-read-date-prefer-future
11745 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11746 (1+ (nth 4 defdecode))
11747 (nth 4 defdecode)))
11748 year (or (nth 5 tl)
11749 (if (and org-read-date-prefer-future
11750 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11751 (1+ (nth 5 defdecode))
11752 (nth 5 defdecode)))
11753 hour (or (nth 2 tl) (nth 2 defdecode))
11754 minute (or (nth 1 tl) (nth 1 defdecode))
11755 second (or (nth 0 tl) 0)
11756 wday (nth 6 tl))
11758 ;; Special date definitions below
11759 (cond
11760 (iso-week
11761 ;; There was an iso week
11762 (setq year (or iso-year year)
11763 day (or iso-weekday wday 1)
11764 wday nil ; to make sure that the trigger below does not match
11765 iso-date (calendar-gregorian-from-absolute
11766 (calendar-absolute-from-iso
11767 (list iso-week day year))))
11768 ; FIXME: Should we also push ISO weeks into the future?
11769 ; (when (and org-read-date-prefer-future
11770 ; (not iso-year)
11771 ; (< (calendar-absolute-from-gregorian iso-date)
11772 ; (time-to-days (current-time))))
11773 ; (setq year (1+ year)
11774 ; iso-date (calendar-gregorian-from-absolute
11775 ; (calendar-absolute-from-iso
11776 ; (list iso-week day year)))))
11777 (setq month (car iso-date)
11778 year (nth 2 iso-date)
11779 day (nth 1 iso-date)))
11780 (deltan
11781 (unless deltadef
11782 (let ((now (decode-time (current-time))))
11783 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11784 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11785 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11786 ((equal deltaw "m") (setq month (+ month deltan)))
11787 ((equal deltaw "y") (setq year (+ year deltan)))))
11788 ((and wday (not (nth 3 tl)))
11789 ;; Weekday was given, but no day, so pick that day in the week
11790 ;; on or after the derived date.
11791 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11792 (unless (equal wday wday1)
11793 (setq day (+ day (% (- wday wday1 -7) 7))))))
11794 (if (and (boundp 'org-time-was-given)
11795 (nth 2 tl))
11796 (setq org-time-was-given t))
11797 (if (< year 100) (setq year (+ 2000 year)))
11798 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11799 (list second minute hour day month year)))
11801 (defvar parse-time-weekdays)
11803 (defun org-read-date-get-relative (s today default)
11804 "Check string S for special relative date string.
11805 TODAY and DEFAULT are internal times, for today and for a default.
11806 Return shift list (N what def-flag)
11807 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11808 N is the number of WHATs to shift.
11809 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11810 the DEFAULT date rather than TODAY."
11811 (when (and
11812 (string-match
11813 (concat
11814 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11815 "\\([0-9]+\\)?"
11816 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11817 "\\([ \t]\\|$\\)") s)
11818 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11819 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11820 (string-to-char (substring (match-string 1 s) -1))
11821 ?+))
11822 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11823 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11824 (what (if (match-end 3) (match-string 3 s) "d"))
11825 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11826 (date (if rel default today))
11827 (wday (nth 6 (decode-time date)))
11828 delta)
11829 (if wday1
11830 (progn
11831 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11832 (if (= dir ?-) (setq delta (- delta 7)))
11833 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11834 (list delta "d" rel))
11835 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11837 (defun org-eval-in-calendar (form &optional keepdate)
11838 "Eval FORM in the calendar window and return to current window.
11839 Also, store the cursor date in variable org-ans2."
11840 (let ((sw (selected-window)))
11841 (select-window (get-buffer-window "*Calendar*"))
11842 (eval form)
11843 (when (and (not keepdate) (calendar-cursor-to-date))
11844 (let* ((date (calendar-cursor-to-date))
11845 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11846 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11847 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11848 (select-window sw)))
11850 (defun org-calendar-select ()
11851 "Return to `org-read-date' with the date currently selected.
11852 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11853 (interactive)
11854 (when (calendar-cursor-to-date)
11855 (let* ((date (calendar-cursor-to-date))
11856 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11857 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11858 (if (active-minibuffer-window) (exit-minibuffer))))
11860 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11861 "Insert a date stamp for the date given by the internal TIME.
11862 WITH-HM means, use the stamp format that includes the time of the day.
11863 INACTIVE means use square brackets instead of angular ones, so that the
11864 stamp will not contribute to the agenda.
11865 PRE and POST are optional strings to be inserted before and after the
11866 stamp.
11867 The command returns the inserted time stamp."
11868 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11869 stamp)
11870 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11871 (insert-before-markers (or pre ""))
11872 (insert-before-markers (setq stamp (format-time-string fmt time)))
11873 (when (listp extra)
11874 (setq extra (car extra))
11875 (if (and (stringp extra)
11876 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11877 (setq extra (format "-%02d:%02d"
11878 (string-to-number (match-string 1 extra))
11879 (string-to-number (match-string 2 extra))))
11880 (setq extra nil)))
11881 (when extra
11882 (backward-char 1)
11883 (insert-before-markers extra)
11884 (forward-char 1))
11885 (insert-before-markers (or post ""))
11886 (setq org-last-inserted-timestamp stamp)))
11888 (defun org-toggle-time-stamp-overlays ()
11889 "Toggle the use of custom time stamp formats."
11890 (interactive)
11891 (setq org-display-custom-times (not org-display-custom-times))
11892 (unless org-display-custom-times
11893 (let ((p (point-min)) (bmp (buffer-modified-p)))
11894 (while (setq p (next-single-property-change p 'display))
11895 (if (and (get-text-property p 'display)
11896 (eq (get-text-property p 'face) 'org-date))
11897 (remove-text-properties
11898 p (setq p (next-single-property-change p 'display))
11899 '(display t))))
11900 (set-buffer-modified-p bmp)))
11901 (if (featurep 'xemacs)
11902 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11903 (org-restart-font-lock)
11904 (setq org-table-may-need-update t)
11905 (if org-display-custom-times
11906 (message "Time stamps are overlayed with custom format")
11907 (message "Time stamp overlays removed")))
11909 (defun org-display-custom-time (beg end)
11910 "Overlay modified time stamp format over timestamp between BEG and END."
11911 (let* ((ts (buffer-substring beg end))
11912 t1 w1 with-hm tf time str w2 (off 0))
11913 (save-match-data
11914 (setq t1 (org-parse-time-string ts t))
11915 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11916 (setq off (- (match-end 0) (match-beginning 0)))))
11917 (setq end (- end off))
11918 (setq w1 (- end beg)
11919 with-hm (and (nth 1 t1) (nth 2 t1))
11920 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11921 time (org-fix-decoded-time t1)
11922 str (org-add-props
11923 (format-time-string
11924 (substring tf 1 -1) (apply 'encode-time time))
11925 nil 'mouse-face 'highlight)
11926 w2 (length str))
11927 (if (not (= w2 w1))
11928 (add-text-properties (1+ beg) (+ 2 beg)
11929 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11930 (if (featurep 'xemacs)
11931 (progn
11932 (put-text-property beg end 'invisible t)
11933 (put-text-property beg end 'end-glyph (make-glyph str)))
11934 (put-text-property beg end 'display str))))
11936 (defun org-translate-time (string)
11937 "Translate all timestamps in STRING to custom format.
11938 But do this only if the variable `org-display-custom-times' is set."
11939 (when org-display-custom-times
11940 (save-match-data
11941 (let* ((start 0)
11942 (re org-ts-regexp-both)
11943 t1 with-hm inactive tf time str beg end)
11944 (while (setq start (string-match re string start))
11945 (setq beg (match-beginning 0)
11946 end (match-end 0)
11947 t1 (save-match-data
11948 (org-parse-time-string (substring string beg end) t))
11949 with-hm (and (nth 1 t1) (nth 2 t1))
11950 inactive (equal (substring string beg (1+ beg)) "[")
11951 tf (funcall (if with-hm 'cdr 'car)
11952 org-time-stamp-custom-formats)
11953 time (org-fix-decoded-time t1)
11954 str (format-time-string
11955 (concat
11956 (if inactive "[" "<") (substring tf 1 -1)
11957 (if inactive "]" ">"))
11958 (apply 'encode-time time))
11959 string (replace-match str t t string)
11960 start (+ start (length str)))))))
11961 string)
11963 (defun org-fix-decoded-time (time)
11964 "Set 0 instead of nil for the first 6 elements of time.
11965 Don't touch the rest."
11966 (let ((n 0))
11967 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11969 (defun org-days-to-time (timestamp-string)
11970 "Difference between TIMESTAMP-STRING and now in days."
11971 (- (time-to-days (org-time-string-to-time timestamp-string))
11972 (time-to-days (current-time))))
11974 (defun org-deadline-close (timestamp-string &optional ndays)
11975 "Is the time in TIMESTAMP-STRING close to the current date?"
11976 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11977 (and (< (org-days-to-time timestamp-string) ndays)
11978 (not (org-entry-is-done-p))))
11980 (defun org-get-wdays (ts)
11981 "Get the deadline lead time appropriate for timestring TS."
11982 (cond
11983 ((<= org-deadline-warning-days 0)
11984 ;; 0 or negative, enforce this value no matter what
11985 (- org-deadline-warning-days))
11986 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
11987 ;; lead time is specified.
11988 (floor (* (string-to-number (match-string 1 ts))
11989 (cdr (assoc (match-string 2 ts)
11990 '(("d" . 1) ("w" . 7)
11991 ("m" . 30.4) ("y" . 365.25)))))))
11992 ;; go for the default.
11993 (t org-deadline-warning-days)))
11995 (defun org-calendar-select-mouse (ev)
11996 "Return to `org-read-date' with the date currently selected.
11997 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11998 (interactive "e")
11999 (mouse-set-point ev)
12000 (when (calendar-cursor-to-date)
12001 (let* ((date (calendar-cursor-to-date))
12002 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12003 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12004 (if (active-minibuffer-window) (exit-minibuffer))))
12006 (defun org-check-deadlines (ndays)
12007 "Check if there are any deadlines due or past due.
12008 A deadline is considered due if it happens within `org-deadline-warning-days'
12009 days from today's date. If the deadline appears in an entry marked DONE,
12010 it is not shown. The prefix arg NDAYS can be used to test that many
12011 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12012 (interactive "P")
12013 (let* ((org-warn-days
12014 (cond
12015 ((equal ndays '(4)) 100000)
12016 (ndays (prefix-numeric-value ndays))
12017 (t (abs org-deadline-warning-days))))
12018 (case-fold-search nil)
12019 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12020 (callback
12021 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12023 (message "%d deadlines past-due or due within %d days"
12024 (org-occur regexp nil callback)
12025 org-warn-days)))
12027 (defun org-check-before-date (date)
12028 "Check if there are deadlines or scheduled entries before DATE."
12029 (interactive (list (org-read-date)))
12030 (let ((case-fold-search nil)
12031 (regexp (concat "\\<\\(" org-deadline-string
12032 "\\|" org-scheduled-string
12033 "\\) *<\\([^>]+\\)>"))
12034 (callback
12035 (lambda () (time-less-p
12036 (org-time-string-to-time (match-string 2))
12037 (org-time-string-to-time date)))))
12038 (message "%d entries before %s"
12039 (org-occur regexp nil callback) date)))
12041 (defun org-evaluate-time-range (&optional to-buffer)
12042 "Evaluate a time range by computing the difference between start and end.
12043 Normally the result is just printed in the echo area, but with prefix arg
12044 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12045 If the time range is actually in a table, the result is inserted into the
12046 next column.
12047 For time difference computation, a year is assumed to be exactly 365
12048 days in order to avoid rounding problems."
12049 (interactive "P")
12051 (org-clock-update-time-maybe)
12052 (save-excursion
12053 (unless (org-at-date-range-p t)
12054 (goto-char (point-at-bol))
12055 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12056 (if (not (org-at-date-range-p t))
12057 (error "Not at a time-stamp range, and none found in current line")))
12058 (let* ((ts1 (match-string 1))
12059 (ts2 (match-string 2))
12060 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12061 (match-end (match-end 0))
12062 (time1 (org-time-string-to-time ts1))
12063 (time2 (org-time-string-to-time ts2))
12064 (t1 (time-to-seconds time1))
12065 (t2 (time-to-seconds time2))
12066 (diff (abs (- t2 t1)))
12067 (negative (< (- t2 t1) 0))
12068 ;; (ys (floor (* 365 24 60 60)))
12069 (ds (* 24 60 60))
12070 (hs (* 60 60))
12071 (fy "%dy %dd %02d:%02d")
12072 (fy1 "%dy %dd")
12073 (fd "%dd %02d:%02d")
12074 (fd1 "%dd")
12075 (fh "%02d:%02d")
12076 y d h m align)
12077 (if havetime
12078 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12080 d (floor (/ diff ds)) diff (mod diff ds)
12081 h (floor (/ diff hs)) diff (mod diff hs)
12082 m (floor (/ diff 60)))
12083 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12085 d (floor (+ (/ diff ds) 0.5))
12086 h 0 m 0))
12087 (if (not to-buffer)
12088 (message "%s" (org-make-tdiff-string y d h m))
12089 (if (org-at-table-p)
12090 (progn
12091 (goto-char match-end)
12092 (setq align t)
12093 (and (looking-at " *|") (goto-char (match-end 0))))
12094 (goto-char match-end))
12095 (if (looking-at
12096 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12097 (replace-match ""))
12098 (if negative (insert " -"))
12099 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12100 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12101 (insert " " (format fh h m))))
12102 (if align (org-table-align))
12103 (message "Time difference inserted")))))
12105 (defun org-make-tdiff-string (y d h m)
12106 (let ((fmt "")
12107 (l nil))
12108 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12109 l (push y l)))
12110 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12111 l (push d l)))
12112 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12113 l (push h l)))
12114 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12115 l (push m l)))
12116 (apply 'format fmt (nreverse l))))
12118 (defun org-time-string-to-time (s)
12119 (apply 'encode-time (org-parse-time-string s)))
12121 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12122 "Convert a time stamp to an absolute day number.
12123 If there is a specifyer for a cyclic time stamp, get the closest date to
12124 DAYNR.
12125 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12126 (cond
12127 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12128 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12129 daynr
12130 (+ daynr 1000)))
12131 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12132 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12133 (time-to-days (current-time))) (match-string 0 s)
12134 prefer show-all))
12135 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12137 (defun org-days-to-iso-week (days)
12138 "Return the iso week number."
12139 (require 'cal-iso)
12140 (car (calendar-iso-from-absolute days)))
12142 (defun org-small-year-to-year (year)
12143 "Convert 2-digit years into 4-digit years.
12144 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12145 The year 2000 cannot be abbreviated. Any year larger than 99
12146 is returned unchanged."
12147 (if (< year 38)
12148 (setq year (+ 2000 year))
12149 (if (< year 100)
12150 (setq year (+ 1900 year))))
12151 year)
12153 (defun org-time-from-absolute (d)
12154 "Return the time corresponding to date D.
12155 D may be an absolute day number, or a calendar-type list (month day year)."
12156 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12157 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12159 (defun org-calendar-holiday ()
12160 "List of holidays, for Diary display in Org-mode."
12161 (require 'holidays)
12162 (let ((hl (funcall
12163 (if (fboundp 'calendar-check-holidays)
12164 'calendar-check-holidays 'check-calendar-holidays) date)))
12165 (if hl (mapconcat 'identity hl "; "))))
12167 (defun org-diary-sexp-entry (sexp entry date)
12168 "Process a SEXP diary ENTRY for DATE."
12169 (require 'diary-lib)
12170 (let ((result (if calendar-debug-sexp
12171 (let ((stack-trace-on-error t))
12172 (eval (car (read-from-string sexp))))
12173 (condition-case nil
12174 (eval (car (read-from-string sexp)))
12175 (error
12176 (beep)
12177 (message "Bad sexp at line %d in %s: %s"
12178 (org-current-line)
12179 (buffer-file-name) sexp)
12180 (sleep-for 2))))))
12181 (cond ((stringp result) result)
12182 ((and (consp result)
12183 (stringp (cdr result))) (cdr result))
12184 (result entry)
12185 (t nil))))
12187 (defun org-diary-to-ical-string (frombuf)
12188 "Get iCalendar entries from diary entries in buffer FROMBUF.
12189 This uses the icalendar.el library."
12190 (let* ((tmpdir (if (featurep 'xemacs)
12191 (temp-directory)
12192 temporary-file-directory))
12193 (tmpfile (make-temp-name
12194 (expand-file-name "orgics" tmpdir)))
12195 buf rtn b e)
12196 (save-excursion
12197 (set-buffer frombuf)
12198 (icalendar-export-region (point-min) (point-max) tmpfile)
12199 (setq buf (find-buffer-visiting tmpfile))
12200 (set-buffer buf)
12201 (goto-char (point-min))
12202 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12203 (setq b (match-beginning 0)))
12204 (goto-char (point-max))
12205 (if (re-search-backward "^END:VEVENT" nil t)
12206 (setq e (match-end 0)))
12207 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12208 (kill-buffer buf)
12209 (delete-file tmpfile)
12210 rtn))
12212 (defun org-closest-date (start current change prefer show-all)
12213 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12214 When PREFER is `past' return a date that is either CURRENT or past.
12215 When PREFER is `future', return a date that is either CURRENT or future.
12216 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12217 ;; Make the proper lists from the dates
12218 (catch 'exit
12219 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12220 dn dw sday cday n1 n2 n0
12221 d m y y1 y2 date1 date2 nmonths nm ny m2)
12223 (setq start (org-date-to-gregorian start)
12224 current (org-date-to-gregorian
12225 (if show-all
12226 current
12227 (time-to-days (current-time))))
12228 sday (calendar-absolute-from-gregorian start)
12229 cday (calendar-absolute-from-gregorian current))
12231 (if (<= cday sday) (throw 'exit sday))
12233 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12234 (setq dn (string-to-number (match-string 1 change))
12235 dw (cdr (assoc (match-string 2 change) a1)))
12236 (error "Invalid change specifyer: %s" change))
12237 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12238 (cond
12239 ((eq dw 'day)
12240 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12241 n2 (+ n1 dn)))
12242 ((eq dw 'year)
12243 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12244 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12245 (setq date1 (list m d y1)
12246 n1 (calendar-absolute-from-gregorian date1)
12247 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12248 n2 (calendar-absolute-from-gregorian date2)))
12249 ((eq dw 'month)
12250 ;; approx number of month between the two dates
12251 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12252 ;; How often does dn fit in there?
12253 (setq d (nth 1 start) m (car start) y (nth 2 start)
12254 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12255 m (+ m nm)
12256 ny (floor (/ m 12))
12257 y (+ y ny)
12258 m (- m (* ny 12)))
12259 (while (> m 12) (setq m (- m 12) y (1+ y)))
12260 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12261 (setq m2 (+ m dn) y2 y)
12262 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12263 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12264 (while (<= n2 cday)
12265 (setq n1 n2 m m2 y y2)
12266 (setq m2 (+ m dn) y2 y)
12267 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12268 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12269 ;; Make sure n1 is the earlier date
12270 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12271 (if show-all
12272 (cond
12273 ((eq prefer 'past) n1)
12274 ((eq prefer 'future) (if (= cday n1) n1 n2))
12275 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12276 (cond
12277 ((eq prefer 'past) n1)
12278 ((eq prefer 'future) (if (= cday n1) n1 n2))
12279 (t (if (= cday n1) n1 n2)))))))
12281 (defun org-date-to-gregorian (date)
12282 "Turn any specification of DATE into a gregorian date for the calendar."
12283 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12284 ((and (listp date) (= (length date) 3)) date)
12285 ((stringp date)
12286 (setq date (org-parse-time-string date))
12287 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12288 ((listp date)
12289 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12291 (defun org-parse-time-string (s &optional nodefault)
12292 "Parse the standard Org-mode time string.
12293 This should be a lot faster than the normal `parse-time-string'.
12294 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12295 hour and minute fields will be nil if not given."
12296 (if (string-match org-ts-regexp0 s)
12297 (list 0
12298 (if (or (match-beginning 8) (not nodefault))
12299 (string-to-number (or (match-string 8 s) "0")))
12300 (if (or (match-beginning 7) (not nodefault))
12301 (string-to-number (or (match-string 7 s) "0")))
12302 (string-to-number (match-string 4 s))
12303 (string-to-number (match-string 3 s))
12304 (string-to-number (match-string 2 s))
12305 nil nil nil)
12306 (make-list 9 0)))
12308 (defun org-timestamp-up (&optional arg)
12309 "Increase the date item at the cursor by one.
12310 If the cursor is on the year, change the year. If it is on the month or
12311 the day, change that.
12312 With prefix ARG, change by that many units."
12313 (interactive "p")
12314 (org-timestamp-change (prefix-numeric-value arg)))
12316 (defun org-timestamp-down (&optional arg)
12317 "Decrease the date item at the cursor by one.
12318 If the cursor is on the year, change the year. If it is on the month or
12319 the day, change that.
12320 With prefix ARG, change by that many units."
12321 (interactive "p")
12322 (org-timestamp-change (- (prefix-numeric-value arg))))
12324 (defun org-timestamp-up-day (&optional arg)
12325 "Increase the date in the time stamp by one day.
12326 With prefix ARG, change that many days."
12327 (interactive "p")
12328 (if (and (not (org-at-timestamp-p t))
12329 (org-on-heading-p))
12330 (org-todo 'up)
12331 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12333 (defun org-timestamp-down-day (&optional arg)
12334 "Decrease the date in the time stamp by one day.
12335 With prefix ARG, change that many days."
12336 (interactive "p")
12337 (if (and (not (org-at-timestamp-p t))
12338 (org-on-heading-p))
12339 (org-todo 'down)
12340 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12342 (defun org-at-timestamp-p (&optional inactive-ok)
12343 "Determine if the cursor is in or at a timestamp."
12344 (interactive)
12345 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12346 (pos (point))
12347 (ans (or (looking-at tsr)
12348 (save-excursion
12349 (skip-chars-backward "^[<\n\r\t")
12350 (if (> (point) (point-min)) (backward-char 1))
12351 (and (looking-at tsr)
12352 (> (- (match-end 0) pos) -1))))))
12353 (and ans
12354 (boundp 'org-ts-what)
12355 (setq org-ts-what
12356 (cond
12357 ((= pos (match-beginning 0)) 'bracket)
12358 ((= pos (1- (match-end 0))) 'bracket)
12359 ((org-pos-in-match-range pos 2) 'year)
12360 ((org-pos-in-match-range pos 3) 'month)
12361 ((org-pos-in-match-range pos 7) 'hour)
12362 ((org-pos-in-match-range pos 8) 'minute)
12363 ((or (org-pos-in-match-range pos 4)
12364 (org-pos-in-match-range pos 5)) 'day)
12365 ((and (> pos (or (match-end 8) (match-end 5)))
12366 (< pos (match-end 0)))
12367 (- pos (or (match-end 8) (match-end 5))))
12368 (t 'day))))
12369 ans))
12371 (defun org-toggle-timestamp-type ()
12372 "Toggle the type (<active> or [inactive]) of a time stamp."
12373 (interactive)
12374 (when (org-at-timestamp-p t)
12375 (let ((beg (match-beginning 0)) (end (match-end 0))
12376 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12377 (save-excursion
12378 (goto-char beg)
12379 (while (re-search-forward "[][<>]" end t)
12380 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12381 t t)))
12382 (message "Timestamp is now %sactive"
12383 (if (equal (char-after beg) ?<) "" "in")))))
12385 (defun org-timestamp-change (n &optional what)
12386 "Change the date in the time stamp at point.
12387 The date will be changed by N times WHAT. WHAT can be `day', `month',
12388 `year', `minute', `second'. If WHAT is not given, the cursor position
12389 in the timestamp determines what will be changed."
12390 (let ((pos (point))
12391 with-hm inactive
12392 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12393 org-ts-what
12394 extra rem
12395 ts time time0)
12396 (if (not (org-at-timestamp-p t))
12397 (error "Not at a timestamp"))
12398 (if (and (not what) (eq org-ts-what 'bracket))
12399 (org-toggle-timestamp-type)
12400 (if (and (not what) (not (eq org-ts-what 'day))
12401 org-display-custom-times
12402 (get-text-property (point) 'display)
12403 (not (get-text-property (1- (point)) 'display)))
12404 (setq org-ts-what 'day))
12405 (setq org-ts-what (or what org-ts-what)
12406 inactive (= (char-after (match-beginning 0)) ?\[)
12407 ts (match-string 0))
12408 (replace-match "")
12409 (if (string-match
12410 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12412 (setq extra (match-string 1 ts)))
12413 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12414 (setq with-hm t))
12415 (setq time0 (org-parse-time-string ts))
12416 (when (and (eq org-ts-what 'minute)
12417 (eq current-prefix-arg nil))
12418 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12419 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12420 (setcar (cdr time0) (+ (nth 1 time0)
12421 (if (> n 0) (- rem) (- dm rem))))))
12422 (setq time
12423 (encode-time (or (car time0) 0)
12424 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12425 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12426 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12427 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12428 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12429 (nthcdr 6 time0)))
12430 (when (integerp org-ts-what)
12431 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12432 (if (eq what 'calendar)
12433 (let ((cal-date (org-get-date-from-calendar)))
12434 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12435 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12436 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12437 (setcar time0 (or (car time0) 0))
12438 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12439 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12440 (setq time (apply 'encode-time time0))))
12441 (setq org-last-changed-timestamp
12442 (org-insert-time-stamp time with-hm inactive nil nil extra))
12443 (org-clock-update-time-maybe)
12444 (goto-char pos)
12445 ;; Try to recenter the calendar window, if any
12446 (if (and org-calendar-follow-timestamp-change
12447 (get-buffer-window "*Calendar*" t)
12448 (memq org-ts-what '(day month year)))
12449 (org-recenter-calendar (time-to-days time))))))
12451 (defun org-modify-ts-extra (s pos n dm)
12452 "Change the different parts of the lead-time and repeat fields in timestamp."
12453 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12454 ng h m new rem)
12455 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12456 (cond
12457 ((or (org-pos-in-match-range pos 2)
12458 (org-pos-in-match-range pos 3))
12459 (setq m (string-to-number (match-string 3 s))
12460 h (string-to-number (match-string 2 s)))
12461 (if (org-pos-in-match-range pos 2)
12462 (setq h (+ h n))
12463 (setq n (* dm (org-no-warnings (signum n))))
12464 (when (not (= 0 (setq rem (% m dm))))
12465 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12466 (setq m (+ m n)))
12467 (if (< m 0) (setq m (+ m 60) h (1- h)))
12468 (if (> m 59) (setq m (- m 60) h (1+ h)))
12469 (setq h (min 24 (max 0 h)))
12470 (setq ng 1 new (format "-%02d:%02d" h m)))
12471 ((org-pos-in-match-range pos 6)
12472 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12473 ((org-pos-in-match-range pos 5)
12474 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12476 ((org-pos-in-match-range pos 9)
12477 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12478 ((org-pos-in-match-range pos 8)
12479 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12481 (when ng
12482 (setq s (concat
12483 (substring s 0 (match-beginning ng))
12485 (substring s (match-end ng))))))
12488 (defun org-recenter-calendar (date)
12489 "If the calendar is visible, recenter it to DATE."
12490 (let* ((win (selected-window))
12491 (cwin (get-buffer-window "*Calendar*" t))
12492 (calendar-move-hook nil))
12493 (when cwin
12494 (select-window cwin)
12495 (calendar-goto-date (if (listp date) date
12496 (calendar-gregorian-from-absolute date)))
12497 (select-window win))))
12499 (defun org-goto-calendar (&optional arg)
12500 "Go to the Emacs calendar at the current date.
12501 If there is a time stamp in the current line, go to that date.
12502 A prefix ARG can be used to force the current date."
12503 (interactive "P")
12504 (let ((tsr org-ts-regexp) diff
12505 (calendar-move-hook nil)
12506 (calendar-view-holidays-initially-flag nil)
12507 (view-calendar-holidays-initially nil)
12508 (calendar-view-diary-initially-flag nil)
12509 (view-diary-entries-initially nil))
12510 (if (or (org-at-timestamp-p)
12511 (save-excursion
12512 (beginning-of-line 1)
12513 (looking-at (concat ".*" tsr))))
12514 (let ((d1 (time-to-days (current-time)))
12515 (d2 (time-to-days
12516 (org-time-string-to-time (match-string 1)))))
12517 (setq diff (- d2 d1))))
12518 (calendar)
12519 (calendar-goto-today)
12520 (if (and diff (not arg)) (calendar-forward-day diff))))
12522 (defun org-get-date-from-calendar ()
12523 "Return a list (month day year) of date at point in calendar."
12524 (with-current-buffer "*Calendar*"
12525 (save-match-data
12526 (calendar-cursor-to-date))))
12528 (defun org-date-from-calendar ()
12529 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12530 If there is already a time stamp at the cursor position, update it."
12531 (interactive)
12532 (if (org-at-timestamp-p t)
12533 (org-timestamp-change 0 'calendar)
12534 (let ((cal-date (org-get-date-from-calendar)))
12535 (org-insert-time-stamp
12536 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12538 (defun org-minutes-to-hh:mm-string (m)
12539 "Compute H:MM from a number of minutes."
12540 (let ((h (/ m 60)))
12541 (setq m (- m (* 60 h)))
12542 (format org-time-clocksum-format h m)))
12544 (defun org-hh:mm-string-to-minutes (s)
12545 "Convert a string H:MM to a number of minutes."
12546 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12547 (+ (* (string-to-number (match-string 1 s)) 60)
12548 (string-to-number (match-string 2 s)))
12551 ;;;; Files
12553 (defun org-save-all-org-buffers ()
12554 "Save all Org-mode buffers without user confirmation."
12555 (interactive)
12556 (message "Saving all Org-mode buffers...")
12557 (save-some-buffers t 'org-mode-p)
12558 (when (featurep 'org-id) (org-id-locations-save))
12559 (message "Saving all Org-mode buffers... done"))
12561 (defun org-revert-all-org-buffers ()
12562 "Revert all Org-mode buffers.
12563 Prompt for confirmation when there are unsaved changes.
12564 Be sure you know what you are doing before letting this function
12565 overwrite your changes.
12567 This function is useful in a setup where one tracks org files
12568 with a version control system, to revert on one machine after pulling
12569 changes from another. I believe the procedure must be like this:
12571 1. M-x org-save-all-org-buffers
12572 2. Pull changes from the other machine, resolve conflicts
12573 3. M-x org-revert-all-org-buffers"
12574 (interactive)
12575 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12576 (error "Abort"))
12577 (save-excursion
12578 (save-window-excursion
12579 (mapc
12580 (lambda (b)
12581 (when (and (with-current-buffer b (org-mode-p))
12582 (with-current-buffer b buffer-file-name))
12583 (switch-to-buffer b)
12584 (revert-buffer t 'no-confirm)))
12585 (buffer-list))
12586 (when (and (featurep 'org-id) org-id-track-globally)
12587 (org-id-locations-load)))))
12589 ;;;; Agenda files
12591 ;;;###autoload
12592 (defun org-iswitchb (&optional arg)
12593 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12594 With a prefix argument, restrict available to files.
12595 With two prefix arguments, restrict available buffers to agenda files.
12597 Due to some yet unresolved reason, the global function
12598 `iswitchb-mode' needs to be active for this function to work."
12599 (interactive "P")
12600 (require 'iswitchb)
12601 (let ((enabled iswitchb-mode) blist)
12602 (or enabled (iswitchb-mode 1))
12603 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12604 ((equal arg '(16)) (org-buffer-list 'agenda))
12605 (t (org-buffer-list))))
12606 (unwind-protect
12607 (let ((iswitchb-make-buflist-hook
12608 (lambda ()
12609 (setq iswitchb-temp-buflist
12610 (mapcar 'buffer-name blist)))))
12611 (switch-to-buffer
12612 (iswitchb-read-buffer
12613 "Switch-to: " nil t))
12614 (or enabled (iswitchb-mode -1))))))
12616 ;;;###autoload
12617 (defun org-ido-switchb (&optional arg)
12618 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12619 With a prefix argument, restrict available to files.
12620 With two prefix arguments, restrict available buffers to agenda files."
12621 (interactive "P")
12622 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12623 ((equal arg '(16)) (org-buffer-list 'agenda))
12624 (t (org-buffer-list)))))
12625 (switch-to-buffer
12626 (org-ido-completing-read "Org buffer: "
12627 (mapcar 'buffer-name blist)
12628 nil t))))
12630 (defun org-buffer-list (&optional predicate exclude-tmp)
12631 "Return a list of Org buffers.
12632 PREDICATE can be `export', `files' or `agenda'.
12634 export restrict the list to Export buffers.
12635 files restrict the list to buffers visiting Org files.
12636 agenda restrict the list to buffers visiting agenda files.
12638 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12639 (let* ((bfn nil)
12640 (agenda-files (and (eq predicate 'agenda)
12641 (mapcar 'file-truename (org-agenda-files t))))
12642 (filter
12643 (cond
12644 ((eq predicate 'files)
12645 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12646 ((eq predicate 'export)
12647 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12648 ((eq predicate 'agenda)
12649 (lambda (b)
12650 (with-current-buffer b
12651 (and (eq major-mode 'org-mode)
12652 (setq bfn (buffer-file-name b))
12653 (member (file-truename bfn) agenda-files)))))
12654 (t (lambda (b) (with-current-buffer b
12655 (or (eq major-mode 'org-mode)
12656 (string-match "\*Org .*Export"
12657 (buffer-name b)))))))))
12658 (delq nil
12659 (mapcar
12660 (lambda(b)
12661 (if (and (funcall filter b)
12662 (or (not exclude-tmp)
12663 (not (string-match "tmp" (buffer-name b)))))
12665 nil))
12666 (buffer-list)))))
12668 (defun org-agenda-files (&optional unrestricted archives)
12669 "Get the list of agenda files.
12670 Optional UNRESTRICTED means return the full list even if a restriction
12671 is currently in place.
12672 When ARCHIVES is t, include all archive files hat are really being
12673 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12674 `org-agenda-archives-mode' is t."
12675 (let ((files
12676 (cond
12677 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12678 ((stringp org-agenda-files) (org-read-agenda-file-list))
12679 ((listp org-agenda-files) org-agenda-files)
12680 (t (error "Invalid value of `org-agenda-files'")))))
12681 (setq files (apply 'append
12682 (mapcar (lambda (f)
12683 (if (file-directory-p f)
12684 (directory-files
12685 f t org-agenda-file-regexp)
12686 (list f)))
12687 files)))
12688 (when org-agenda-skip-unavailable-files
12689 (setq files (delq nil
12690 (mapcar (function
12691 (lambda (file)
12692 (and (file-readable-p file) file)))
12693 files))))
12694 (when (or (eq archives t)
12695 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12696 (setq files (org-add-archive-files files)))
12697 files))
12699 (defun org-edit-agenda-file-list ()
12700 "Edit the list of agenda files.
12701 Depending on setup, this either uses customize to edit the variable
12702 `org-agenda-files', or it visits the file that is holding the list. In the
12703 latter case, the buffer is set up in a way that saving it automatically kills
12704 the buffer and restores the previous window configuration."
12705 (interactive)
12706 (if (stringp org-agenda-files)
12707 (let ((cw (current-window-configuration)))
12708 (find-file org-agenda-files)
12709 (org-set-local 'org-window-configuration cw)
12710 (org-add-hook 'after-save-hook
12711 (lambda ()
12712 (set-window-configuration
12713 (prog1 org-window-configuration
12714 (kill-buffer (current-buffer))))
12715 (org-install-agenda-files-menu)
12716 (message "New agenda file list installed"))
12717 nil 'local)
12718 (message "%s" (substitute-command-keys
12719 "Edit list and finish with \\[save-buffer]")))
12720 (customize-variable 'org-agenda-files)))
12722 (defun org-store-new-agenda-file-list (list)
12723 "Set new value for the agenda file list and save it correctly."
12724 (if (stringp org-agenda-files)
12725 (let ((f org-agenda-files) b)
12726 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12727 (with-temp-file f
12728 (insert (mapconcat 'identity list "\n") "\n")))
12729 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12730 (setq org-agenda-files list)
12731 (customize-save-variable 'org-agenda-files org-agenda-files))))
12733 (defun org-read-agenda-file-list ()
12734 "Read the list of agenda files from a file."
12735 (when (file-directory-p org-agenda-files)
12736 (error "`org-agenda-files' cannot be a single directory"))
12737 (when (stringp org-agenda-files)
12738 (with-temp-buffer
12739 (insert-file-contents org-agenda-files)
12740 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12743 ;;;###autoload
12744 (defun org-cycle-agenda-files ()
12745 "Cycle through the files in `org-agenda-files'.
12746 If the current buffer visits an agenda file, find the next one in the list.
12747 If the current buffer does not, find the first agenda file."
12748 (interactive)
12749 (let* ((fs (org-agenda-files t))
12750 (files (append fs (list (car fs))))
12751 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12752 file)
12753 (unless files (error "No agenda files"))
12754 (catch 'exit
12755 (while (setq file (pop files))
12756 (if (equal (file-truename file) tcf)
12757 (when (car files)
12758 (find-file (car files))
12759 (throw 'exit t))))
12760 (find-file (car fs)))
12761 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12763 (defun org-agenda-file-to-front (&optional to-end)
12764 "Move/add the current file to the top of the agenda file list.
12765 If the file is not present in the list, it is added to the front. If it is
12766 present, it is moved there. With optional argument TO-END, add/move to the
12767 end of the list."
12768 (interactive "P")
12769 (let ((org-agenda-skip-unavailable-files nil)
12770 (file-alist (mapcar (lambda (x)
12771 (cons (file-truename x) x))
12772 (org-agenda-files t)))
12773 (ctf (file-truename buffer-file-name))
12774 x had)
12775 (setq x (assoc ctf file-alist) had x)
12777 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12778 (if to-end
12779 (setq file-alist (append (delq x file-alist) (list x)))
12780 (setq file-alist (cons x (delq x file-alist))))
12781 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12782 (org-install-agenda-files-menu)
12783 (message "File %s to %s of agenda file list"
12784 (if had "moved" "added") (if to-end "end" "front"))))
12786 (defun org-remove-file (&optional file)
12787 "Remove current file from the list of files in variable `org-agenda-files'.
12788 These are the files which are being checked for agenda entries.
12789 Optional argument FILE means, use this file instead of the current."
12790 (interactive)
12791 (let* ((org-agenda-skip-unavailable-files nil)
12792 (file (or file buffer-file-name))
12793 (true-file (file-truename file))
12794 (afile (abbreviate-file-name file))
12795 (files (delq nil (mapcar
12796 (lambda (x)
12797 (if (equal true-file
12798 (file-truename x))
12799 nil x))
12800 (org-agenda-files t)))))
12801 (if (not (= (length files) (length (org-agenda-files t))))
12802 (progn
12803 (org-store-new-agenda-file-list files)
12804 (org-install-agenda-files-menu)
12805 (message "Removed file: %s" afile))
12806 (message "File was not in list: %s (not removed)" afile))))
12808 (defun org-file-menu-entry (file)
12809 (vector file (list 'find-file file) t))
12811 (defun org-check-agenda-file (file)
12812 "Make sure FILE exists. If not, ask user what to do."
12813 (when (not (file-exists-p file))
12814 (message "non-existent file %s. [R]emove from list or [A]bort?"
12815 (abbreviate-file-name file))
12816 (let ((r (downcase (read-char-exclusive))))
12817 (cond
12818 ((equal r ?r)
12819 (org-remove-file file)
12820 (throw 'nextfile t))
12821 (t (error "Abort"))))))
12823 (defun org-get-agenda-file-buffer (file)
12824 "Get a buffer visiting FILE. If the buffer needs to be created, add
12825 it to the list of buffers which might be released later."
12826 (let ((buf (org-find-base-buffer-visiting file)))
12827 (if buf
12828 buf ; just return it
12829 ;; Make a new buffer and remember it
12830 (setq buf (find-file-noselect file))
12831 (if buf (push buf org-agenda-new-buffers))
12832 buf)))
12834 (defun org-release-buffers (blist)
12835 "Release all buffers in list, asking the user for confirmation when needed.
12836 When a buffer is unmodified, it is just killed. When modified, it is saved
12837 \(if the user agrees) and then killed."
12838 (let (buf file)
12839 (while (setq buf (pop blist))
12840 (setq file (buffer-file-name buf))
12841 (when (and (buffer-modified-p buf)
12842 file
12843 (y-or-n-p (format "Save file %s? " file)))
12844 (with-current-buffer buf (save-buffer)))
12845 (kill-buffer buf))))
12847 (defun org-prepare-agenda-buffers (files)
12848 "Create buffers for all agenda files, protect archived trees and comments."
12849 (interactive)
12850 (let ((pa '(:org-archived t))
12851 (pc '(:org-comment t))
12852 (pall '(:org-archived t :org-comment t))
12853 (inhibit-read-only t)
12854 (rea (concat ":" org-archive-tag ":"))
12855 bmp file re)
12856 (save-excursion
12857 (save-restriction
12858 (while (setq file (pop files))
12859 (if (bufferp file)
12860 (set-buffer file)
12861 (org-check-agenda-file file)
12862 (set-buffer (org-get-agenda-file-buffer file)))
12863 (widen)
12864 (setq bmp (buffer-modified-p))
12865 (org-refresh-category-properties)
12866 (setq org-todo-keywords-for-agenda
12867 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12868 (setq org-done-keywords-for-agenda
12869 (append org-done-keywords-for-agenda org-done-keywords))
12870 (setq org-todo-keyword-alist-for-agenda
12871 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12872 (setq org-tag-alist-for-agenda
12873 (append org-tag-alist-for-agenda org-tag-alist))
12875 (save-excursion
12876 (remove-text-properties (point-min) (point-max) pall)
12877 (when org-agenda-skip-archived-trees
12878 (goto-char (point-min))
12879 (while (re-search-forward rea nil t)
12880 (if (org-on-heading-p t)
12881 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12882 (goto-char (point-min))
12883 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12884 (while (re-search-forward re nil t)
12885 (add-text-properties
12886 (match-beginning 0) (org-end-of-subtree t) pc)))
12887 (set-buffer-modified-p bmp))))
12888 (setq org-todo-keyword-alist-for-agenda
12889 (org-uniquify org-todo-keyword-alist-for-agenda)
12890 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12892 ;;;; Embedded LaTeX
12894 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12895 "Keymap for the minor `org-cdlatex-mode'.")
12897 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12898 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12899 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12900 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12901 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12903 (defvar org-cdlatex-texmathp-advice-is-done nil
12904 "Flag remembering if we have applied the advice to texmathp already.")
12906 (define-minor-mode org-cdlatex-mode
12907 "Toggle the minor `org-cdlatex-mode'.
12908 This mode supports entering LaTeX environment and math in LaTeX fragments
12909 in Org-mode.
12910 \\{org-cdlatex-mode-map}"
12911 nil " OCDL" nil
12912 (when org-cdlatex-mode (require 'cdlatex))
12913 (unless org-cdlatex-texmathp-advice-is-done
12914 (setq org-cdlatex-texmathp-advice-is-done t)
12915 (defadvice texmathp (around org-math-always-on activate)
12916 "Always return t in org-mode buffers.
12917 This is because we want to insert math symbols without dollars even outside
12918 the LaTeX math segments. If Orgmode thinks that point is actually inside
12919 an embedded LaTeX fragment, let texmathp do its job.
12920 \\[org-cdlatex-mode-map]"
12921 (interactive)
12922 (let (p)
12923 (cond
12924 ((not (org-mode-p)) ad-do-it)
12925 ((eq this-command 'cdlatex-math-symbol)
12926 (setq ad-return-value t
12927 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12929 (let ((p (org-inside-LaTeX-fragment-p)))
12930 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12931 (setq ad-return-value t
12932 texmathp-why '("Org-mode embedded math" . 0))
12933 (if p ad-do-it)))))))))
12935 (defun turn-on-org-cdlatex ()
12936 "Unconditionally turn on `org-cdlatex-mode'."
12937 (org-cdlatex-mode 1))
12939 (defun org-inside-LaTeX-fragment-p ()
12940 "Test if point is inside a LaTeX fragment.
12941 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12942 sequence appearing also before point.
12943 Even though the matchers for math are configurable, this function assumes
12944 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12945 delimiters are skipped when they have been removed by customization.
12946 The return value is nil, or a cons cell with the delimiter and
12947 and the position of this delimiter.
12949 This function does a reasonably good job, but can locally be fooled by
12950 for example currency specifications. For example it will assume being in
12951 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12952 fragments that are properly closed, but during editing, we have to live
12953 with the uncertainty caused by missing closing delimiters. This function
12954 looks only before point, not after."
12955 (catch 'exit
12956 (let ((pos (point))
12957 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12958 (lim (progn
12959 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12960 (point)))
12961 dd-on str (start 0) m re)
12962 (goto-char pos)
12963 (when dodollar
12964 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12965 re (nth 1 (assoc "$" org-latex-regexps)))
12966 (while (string-match re str start)
12967 (cond
12968 ((= (match-end 0) (length str))
12969 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12970 ((= (match-end 0) (- (length str) 5))
12971 (throw 'exit nil))
12972 (t (setq start (match-end 0))))))
12973 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12974 (goto-char pos)
12975 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12976 (and (match-beginning 2) (throw 'exit nil))
12977 ;; count $$
12978 (while (re-search-backward "\\$\\$" lim t)
12979 (setq dd-on (not dd-on)))
12980 (goto-char pos)
12981 (if dd-on (cons "$$" m))))))
12984 (defun org-try-cdlatex-tab ()
12985 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12986 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12987 - inside a LaTeX fragment, or
12988 - after the first word in a line, where an abbreviation expansion could
12989 insert a LaTeX environment."
12990 (when org-cdlatex-mode
12991 (cond
12992 ((save-excursion
12993 (skip-chars-backward "a-zA-Z0-9*")
12994 (skip-chars-backward " \t")
12995 (bolp))
12996 (cdlatex-tab) t)
12997 ((org-inside-LaTeX-fragment-p)
12998 (cdlatex-tab) t)
12999 (t nil))))
13001 (defun org-cdlatex-underscore-caret (&optional arg)
13002 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13003 Revert to the normal definition outside of these fragments."
13004 (interactive "P")
13005 (if (org-inside-LaTeX-fragment-p)
13006 (call-interactively 'cdlatex-sub-superscript)
13007 (let (org-cdlatex-mode)
13008 (call-interactively (key-binding (vector last-input-event))))))
13010 (defun org-cdlatex-math-modify (&optional arg)
13011 "Execute `cdlatex-math-modify' in LaTeX fragments.
13012 Revert to the normal definition outside of these fragments."
13013 (interactive "P")
13014 (if (org-inside-LaTeX-fragment-p)
13015 (call-interactively 'cdlatex-math-modify)
13016 (let (org-cdlatex-mode)
13017 (call-interactively (key-binding (vector last-input-event))))))
13019 (defvar org-latex-fragment-image-overlays nil
13020 "List of overlays carrying the images of latex fragments.")
13021 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13023 (defun org-remove-latex-fragment-image-overlays ()
13024 "Remove all overlays with LaTeX fragment images in current buffer."
13025 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13026 (setq org-latex-fragment-image-overlays nil))
13028 (defun org-preview-latex-fragment (&optional subtree)
13029 "Preview the LaTeX fragment at point, or all locally or globally.
13030 If the cursor is in a LaTeX fragment, create the image and overlay
13031 it over the source code. If there is no fragment at point, display
13032 all fragments in the current text, from one headline to the next. With
13033 prefix SUBTREE, display all fragments in the current subtree. With a
13034 double prefix `C-u C-u', or when the cursor is before the first headline,
13035 display all fragments in the buffer.
13036 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13037 (interactive "P")
13038 (org-remove-latex-fragment-image-overlays)
13039 (save-excursion
13040 (save-restriction
13041 (let (beg end at msg)
13042 (cond
13043 ((or (equal subtree '(16))
13044 (not (save-excursion
13045 (re-search-backward (concat "^" outline-regexp) nil t))))
13046 (setq beg (point-min) end (point-max)
13047 msg "Creating images for buffer...%s"))
13048 ((equal subtree '(4))
13049 (org-back-to-heading)
13050 (setq beg (point) end (org-end-of-subtree t)
13051 msg "Creating images for subtree...%s"))
13053 (if (setq at (org-inside-LaTeX-fragment-p))
13054 (goto-char (max (point-min) (- (cdr at) 2)))
13055 (org-back-to-heading))
13056 (setq beg (point) end (progn (outline-next-heading) (point))
13057 msg (if at "Creating image...%s"
13058 "Creating images for entry...%s"))))
13059 (message msg "")
13060 (narrow-to-region beg end)
13061 (goto-char beg)
13062 (org-format-latex
13063 (concat "ltxpng/" (file-name-sans-extension
13064 (file-name-nondirectory
13065 buffer-file-name)))
13066 default-directory 'overlays msg at 'forbuffer)
13067 (message msg "done. Use `C-c C-c' to remove images.")))))
13069 (defvar org-latex-regexps
13070 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13071 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13072 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13073 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13074 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13075 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13076 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13077 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13078 "Regular expressions for matching embedded LaTeX.")
13080 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13081 "Replace LaTeX fragments with links to an image, and produce images."
13082 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13083 (let* ((prefixnodir (file-name-nondirectory prefix))
13084 (absprefix (expand-file-name prefix dir))
13085 (todir (file-name-directory absprefix))
13086 (opt org-format-latex-options)
13087 (matchers (plist-get opt :matchers))
13088 (re-list org-latex-regexps)
13089 (cnt 0) txt link beg end re e checkdir
13090 m n block linkfile movefile ov)
13091 ;; Check if there are old images files with this prefix, and remove them
13092 (when (file-directory-p todir)
13093 (mapc 'delete-file
13094 (directory-files
13095 todir 'full
13096 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13097 ;; Check the different regular expressions
13098 (while (setq e (pop re-list))
13099 (setq m (car e) re (nth 1 e) n (nth 2 e)
13100 block (if (nth 3 e) "\n\n" ""))
13101 (when (member m matchers)
13102 (goto-char (point-min))
13103 (while (re-search-forward re nil t)
13104 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13105 (not (get-text-property (match-beginning n)
13106 'org-protected)))
13107 (setq txt (match-string n)
13108 beg (match-beginning n) end (match-end n)
13109 cnt (1+ cnt)
13110 linkfile (format "%s_%04d.png" prefix cnt)
13111 movefile (format "%s_%04d.png" absprefix cnt)
13112 link (concat block "[[file:" linkfile "]]" block))
13113 (if msg (message msg cnt))
13114 (goto-char beg)
13115 (unless checkdir ; make sure the directory exists
13116 (setq checkdir t)
13117 (or (file-directory-p todir) (make-directory todir)))
13118 (org-create-formula-image
13119 txt movefile opt forbuffer)
13120 (if overlays
13121 (progn
13122 (setq ov (org-make-overlay beg end))
13123 (if (featurep 'xemacs)
13124 (progn
13125 (org-overlay-put ov 'invisible t)
13126 (org-overlay-put
13127 ov 'end-glyph
13128 (make-glyph (vector 'png :file movefile))))
13129 (org-overlay-put
13130 ov 'display
13131 (list 'image :type 'png :file movefile :ascent 'center)))
13132 (push ov org-latex-fragment-image-overlays)
13133 (goto-char end))
13134 (delete-region beg end)
13135 (insert link))))))))
13137 ;; This function borrows from Ganesh Swami's latex2png.el
13138 (defun org-create-formula-image (string tofile options buffer)
13139 (let* ((tmpdir (if (featurep 'xemacs)
13140 (temp-directory)
13141 temporary-file-directory))
13142 (texfilebase (make-temp-name
13143 (expand-file-name "orgtex" tmpdir)))
13144 (texfile (concat texfilebase ".tex"))
13145 (dvifile (concat texfilebase ".dvi"))
13146 (pngfile (concat texfilebase ".png"))
13147 (fnh (if (featurep 'xemacs)
13148 (font-height (get-face-font 'default))
13149 (face-attribute 'default :height nil)))
13150 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13151 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13152 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13153 "Black"))
13154 (bg (or (plist-get options (if buffer :background :html-background))
13155 "Transparent")))
13156 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13157 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13158 (with-temp-file texfile
13159 (insert org-format-latex-header
13160 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13161 (let ((dir default-directory))
13162 (condition-case nil
13163 (progn
13164 (cd tmpdir)
13165 (call-process "latex" nil nil nil texfile))
13166 (error nil))
13167 (cd dir))
13168 (if (not (file-exists-p dvifile))
13169 (progn (message "Failed to create dvi file from %s" texfile) nil)
13170 (condition-case nil
13171 (call-process "dvipng" nil nil nil
13172 "-E" "-fg" fg "-bg" bg
13173 "-D" dpi
13174 ;;"-x" scale "-y" scale
13175 "-T" "tight"
13176 "-o" pngfile
13177 dvifile)
13178 (error nil))
13179 (if (not (file-exists-p pngfile))
13180 (progn (message "Failed to create png file from %s" texfile) nil)
13181 ;; Use the requested file name and clean up
13182 (copy-file pngfile tofile 'replace)
13183 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13184 (delete-file (concat texfilebase e)))
13185 pngfile))))
13187 (defun org-dvipng-color (attr)
13188 "Return an rgb color specification for dvipng."
13189 (apply 'format "rgb %s %s %s"
13190 (mapcar 'org-normalize-color
13191 (color-values (face-attribute 'default attr nil)))))
13193 (defun org-normalize-color (value)
13194 "Return string to be used as color value for an RGB component."
13195 (format "%g" (/ value 65535.0)))
13197 ;;;; Key bindings
13199 ;; Make `C-c C-x' a prefix key
13200 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13202 ;; TAB key with modifiers
13203 (org-defkey org-mode-map "\C-i" 'org-cycle)
13204 (org-defkey org-mode-map [(tab)] 'org-cycle)
13205 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13206 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13207 (org-defkey org-mode-map "\M-\t" 'org-complete)
13208 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13209 ;; The following line is necessary under Suse GNU/Linux
13210 (unless (featurep 'xemacs)
13211 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13212 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13213 (define-key org-mode-map [backtab] 'org-shifttab)
13215 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13216 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13217 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13219 ;; Cursor keys with modifiers
13220 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13221 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13222 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13223 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13225 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13226 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13227 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13228 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13230 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13231 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13232 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13233 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13235 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13236 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13238 ;;; Extra keys for tty access.
13239 ;; We only set them when really needed because otherwise the
13240 ;; menus don't show the simple keys
13242 (when (or org-use-extra-keys
13243 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13244 (not window-system))
13245 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13246 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13247 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13248 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13249 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13250 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13251 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13252 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13253 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13254 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13255 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13256 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13257 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13258 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13259 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13260 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13261 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13262 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13263 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13264 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13265 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13266 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13268 ;; All the other keys
13270 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13271 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13272 (if (boundp 'narrow-map)
13273 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13274 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13275 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13276 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13277 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13278 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13279 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13280 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13281 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13282 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13283 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13284 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13285 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13286 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13287 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13288 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13289 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13290 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13291 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13292 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13293 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13294 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13295 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13296 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13297 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13298 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13299 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13300 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13301 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13302 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13303 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13304 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13305 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13306 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13307 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13308 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13309 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13310 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13311 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13312 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13313 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13314 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13315 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13316 (org-defkey org-mode-map "\C-c^" 'org-sort)
13317 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13318 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13319 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13320 (org-defkey org-mode-map "\C-m" 'org-return)
13321 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13322 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13323 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13324 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13325 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13326 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13327 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13328 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13329 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13330 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13331 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13332 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13333 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13334 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13335 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13336 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13337 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13339 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13340 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13341 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13342 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13344 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13345 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13346 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13347 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13348 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13349 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13350 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13351 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13352 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13353 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13354 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13355 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13356 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13358 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13359 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13360 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13361 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13363 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13365 (define-key org-mode-map "\C-c\C-xr" 'org-reload)
13367 (when (featurep 'xemacs)
13368 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13371 (defvar org-self-insert-command-undo-counter 0)
13373 (defvar org-table-auto-blank-field) ; defined in org-table.el
13374 (defun org-self-insert-command (N)
13375 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13376 If the cursor is in a table looking at whitespace, the whitespace is
13377 overwritten, and the table is not marked as requiring realignment."
13378 (interactive "p")
13379 (if (and
13380 (org-table-p)
13381 (progn
13382 ;; check if we blank the field, and if that triggers align
13383 (and (featurep 'org-table) org-table-auto-blank-field
13384 (member last-command
13385 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13386 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13387 ;; got extra space, this field does not determine column width
13388 (let (org-table-may-need-update) (org-table-blank-field))
13389 ;; no extra space, this field may determine column width
13390 (org-table-blank-field)))
13392 (eq N 1)
13393 (looking-at "[^|\n]* |"))
13394 (let (org-table-may-need-update)
13395 (goto-char (1- (match-end 0)))
13396 (delete-backward-char 1)
13397 (goto-char (match-beginning 0))
13398 (self-insert-command N))
13399 (setq org-table-may-need-update t)
13400 (self-insert-command N)
13401 (org-fix-tags-on-the-fly)
13402 (if org-self-insert-cluster-for-undo
13403 (if (not (eq last-command 'org-self-insert-command))
13404 (setq org-self-insert-command-undo-counter 1)
13405 (if (>= org-self-insert-command-undo-counter 20)
13406 (setq org-self-insert-command-undo-counter 1)
13407 (and (> org-self-insert-command-undo-counter 0)
13408 buffer-undo-list
13409 (not (cadr buffer-undo-list)) ; remove nil entry
13410 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13411 (setq org-self-insert-command-undo-counter
13412 (1+ org-self-insert-command-undo-counter)))))))
13414 (defun org-fix-tags-on-the-fly ()
13415 (when (and (equal (char-after (point-at-bol)) ?*)
13416 (org-on-heading-p))
13417 (org-align-tags-here org-tags-column)))
13419 (defun org-delete-backward-char (N)
13420 "Like `delete-backward-char', insert whitespace at field end in tables.
13421 When deleting backwards, in tables this function will insert whitespace in
13422 front of the next \"|\" separator, to keep the table aligned. The table will
13423 still be marked for re-alignment if the field did fill the entire column,
13424 because, in this case the deletion might narrow the column."
13425 (interactive "p")
13426 (if (and (org-table-p)
13427 (eq N 1)
13428 (string-match "|" (buffer-substring (point-at-bol) (point)))
13429 (looking-at ".*?|"))
13430 (let ((pos (point))
13431 (noalign (looking-at "[^|\n\r]* |"))
13432 (c org-table-may-need-update))
13433 (backward-delete-char N)
13434 (skip-chars-forward "^|")
13435 (insert " ")
13436 (goto-char (1- pos))
13437 ;; noalign: if there were two spaces at the end, this field
13438 ;; does not determine the width of the column.
13439 (if noalign (setq org-table-may-need-update c)))
13440 (backward-delete-char N)
13441 (org-fix-tags-on-the-fly)))
13443 (defun org-delete-char (N)
13444 "Like `delete-char', but insert whitespace at field end in tables.
13445 When deleting characters, in tables this function will insert whitespace in
13446 front of the next \"|\" separator, to keep the table aligned. The table will
13447 still be marked for re-alignment if the field did fill the entire column,
13448 because, in this case the deletion might narrow the column."
13449 (interactive "p")
13450 (if (and (org-table-p)
13451 (not (bolp))
13452 (not (= (char-after) ?|))
13453 (eq N 1))
13454 (if (looking-at ".*?|")
13455 (let ((pos (point))
13456 (noalign (looking-at "[^|\n\r]* |"))
13457 (c org-table-may-need-update))
13458 (replace-match (concat
13459 (substring (match-string 0) 1 -1)
13460 " |"))
13461 (goto-char pos)
13462 ;; noalign: if there were two spaces at the end, this field
13463 ;; does not determine the width of the column.
13464 (if noalign (setq org-table-may-need-update c)))
13465 (delete-char N))
13466 (delete-char N)
13467 (org-fix-tags-on-the-fly)))
13469 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13470 (put 'org-self-insert-command 'delete-selection t)
13471 (put 'orgtbl-self-insert-command 'delete-selection t)
13472 (put 'org-delete-char 'delete-selection 'supersede)
13473 (put 'org-delete-backward-char 'delete-selection 'supersede)
13474 (put 'org-yank 'delete-selection 'yank)
13476 ;; Make `flyspell-mode' delay after some commands
13477 (put 'org-self-insert-command 'flyspell-delayed t)
13478 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13479 (put 'org-delete-char 'flyspell-delayed t)
13480 (put 'org-delete-backward-char 'flyspell-delayed t)
13482 ;; Make pabbrev-mode expand after org-mode commands
13483 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13484 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13486 ;; How to do this: Measure non-white length of current string
13487 ;; If equal to column width, we should realign.
13489 (defun org-remap (map &rest commands)
13490 "In MAP, remap the functions given in COMMANDS.
13491 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13492 (let (new old)
13493 (while commands
13494 (setq old (pop commands) new (pop commands))
13495 (if (fboundp 'command-remapping)
13496 (org-defkey map (vector 'remap old) new)
13497 (substitute-key-definition old new map global-map)))))
13499 (when (eq org-enable-table-editor 'optimized)
13500 ;; If the user wants maximum table support, we need to hijack
13501 ;; some standard editing functions
13502 (org-remap org-mode-map
13503 'self-insert-command 'org-self-insert-command
13504 'delete-char 'org-delete-char
13505 'delete-backward-char 'org-delete-backward-char)
13506 (org-defkey org-mode-map "|" 'org-force-self-insert))
13508 (defvar org-ctrl-c-ctrl-c-hook nil
13509 "Hook for functions attaching themselves to `C-c C-c'.
13510 This can be used to add additional functionality to the C-c C-c key which
13511 executes context-dependent commands.
13512 Each function will be called with no arguments. The function must check
13513 if the context is appropriate for it to act. If yes, it should do its
13514 thing and then return a non-nil value. If the context is wrong,
13515 just do nothing.")
13517 (defvar org-metaleft-hook nil
13518 "Hook for functions attaching themselves to `M-left'.
13519 See `org-ctrl-c-ctrl-c-hook' for more information.")
13520 (defvar org-metaright-hook nil
13521 "Hook for functions attaching themselves to `M-right'.
13522 See `org-ctrl-c-ctrl-c-hook' for more information.")
13523 (defvar org-metaup-hook nil
13524 "Hook for functions attaching themselves to `M-up'.
13525 See `org-ctrl-c-ctrl-c-hook' for more information.")
13526 (defvar org-metadown-hook nil
13527 "Hook for functions attaching themselves to `M-down'.
13528 See `org-ctrl-c-ctrl-c-hook' for more information.")
13529 (defvar org-shiftmetaleft-hook nil
13530 "Hook for functions attaching themselves to `M-S-left'.
13531 See `org-ctrl-c-ctrl-c-hook' for more information.")
13532 (defvar org-shiftmetaright-hook nil
13533 "Hook for functions attaching themselves to `M-S-right'.
13534 See `org-ctrl-c-ctrl-c-hook' for more information.")
13535 (defvar org-shiftmetaup-hook nil
13536 "Hook for functions attaching themselves to `M-S-up'.
13537 See `org-ctrl-c-ctrl-c-hook' for more information.")
13538 (defvar org-shiftmetadown-hook nil
13539 "Hook for functions attaching themselves to `M-S-down'.
13540 See `org-ctrl-c-ctrl-c-hook' for more information.")
13541 (defvar org-metareturn-hook nil
13542 "Hook for functions attaching themselves to `M-RET'.
13543 See `org-ctrl-c-ctrl-c-hook' for more information.")
13545 (defun org-modifier-cursor-error ()
13546 "Throw an error, a modified cursor command was applied in wrong context."
13547 (error "This command is active in special context like tables, headlines or items"))
13549 (defun org-shiftselect-error ()
13550 "Throw an error because Shift-Cursor command was applied in wrong context."
13551 (if (and (boundp 'shift-select-mode) shift-select-mode)
13552 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13553 (error "This command works only in special context like headlines or timestamps.")))
13555 (defun org-call-for-shift-select (cmd)
13556 (let ((this-command-keys-shift-translated t))
13557 (call-interactively cmd)))
13559 (defun org-shifttab (&optional arg)
13560 "Global visibility cycling or move to previous table field.
13561 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13562 on context.
13563 See the individual commands for more information."
13564 (interactive "P")
13565 (cond
13566 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13567 ((integerp arg)
13568 (message "Content view to level: %d" arg)
13569 (org-content (prefix-numeric-value arg))
13570 (setq org-cycle-global-status 'overview))
13571 (t (call-interactively 'org-global-cycle))))
13573 (defun org-shiftmetaleft ()
13574 "Promote subtree or delete table column.
13575 Calls `org-promote-subtree', `org-outdent-item',
13576 or `org-table-delete-column', depending on context.
13577 See the individual commands for more information."
13578 (interactive)
13579 (cond
13580 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13581 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13582 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13583 ((org-at-item-p) (call-interactively 'org-outdent-item))
13584 (t (org-modifier-cursor-error))))
13586 (defun org-shiftmetaright ()
13587 "Demote subtree or insert table column.
13588 Calls `org-demote-subtree', `org-indent-item',
13589 or `org-table-insert-column', depending on context.
13590 See the individual commands for more information."
13591 (interactive)
13592 (cond
13593 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13594 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13595 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13596 ((org-at-item-p) (call-interactively 'org-indent-item))
13597 (t (org-modifier-cursor-error))))
13599 (defun org-shiftmetaup (&optional arg)
13600 "Move subtree up or kill table row.
13601 Calls `org-move-subtree-up' or `org-table-kill-row' or
13602 `org-move-item-up' depending on context. See the individual commands
13603 for more information."
13604 (interactive "P")
13605 (cond
13606 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13607 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13608 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13609 ((org-at-item-p) (call-interactively 'org-move-item-up))
13610 (t (org-modifier-cursor-error))))
13612 (defun org-shiftmetadown (&optional arg)
13613 "Move subtree down or insert table row.
13614 Calls `org-move-subtree-down' or `org-table-insert-row' or
13615 `org-move-item-down', depending on context. See the individual
13616 commands for more information."
13617 (interactive "P")
13618 (cond
13619 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13620 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13621 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13622 ((org-at-item-p) (call-interactively 'org-move-item-down))
13623 (t (org-modifier-cursor-error))))
13625 (defun org-metaleft (&optional arg)
13626 "Promote heading or move table column to left.
13627 Calls `org-do-promote' or `org-table-move-column', depending on context.
13628 With no specific context, calls the Emacs default `backward-word'.
13629 See the individual commands for more information."
13630 (interactive "P")
13631 (cond
13632 ((run-hook-with-args-until-success 'org-metaleft-hook))
13633 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13634 ((or (org-on-heading-p)
13635 (and (org-region-active-p)
13636 (save-excursion
13637 (goto-char (region-beginning))
13638 (org-on-heading-p))))
13639 (call-interactively 'org-do-promote))
13640 ((or (org-at-item-p)
13641 (and (org-region-active-p)
13642 (save-excursion
13643 (goto-char (region-beginning))
13644 (org-at-item-p))))
13645 (call-interactively 'org-outdent-item))
13646 (t (call-interactively 'backward-word))))
13648 (defun org-metaright (&optional arg)
13649 "Demote subtree or move table column to right.
13650 Calls `org-do-demote' or `org-table-move-column', depending on context.
13651 With no specific context, calls the Emacs default `forward-word'.
13652 See the individual commands for more information."
13653 (interactive "P")
13654 (cond
13655 ((run-hook-with-args-until-success 'org-metaright-hook))
13656 ((org-at-table-p) (call-interactively 'org-table-move-column))
13657 ((or (org-on-heading-p)
13658 (and (org-region-active-p)
13659 (save-excursion
13660 (goto-char (region-beginning))
13661 (org-on-heading-p))))
13662 (call-interactively 'org-do-demote))
13663 ((or (org-at-item-p)
13664 (and (org-region-active-p)
13665 (save-excursion
13666 (goto-char (region-beginning))
13667 (org-at-item-p))))
13668 (call-interactively 'org-indent-item))
13669 (t (call-interactively 'forward-word))))
13671 (defun org-metaup (&optional arg)
13672 "Move subtree up or move table row up.
13673 Calls `org-move-subtree-up' or `org-table-move-row' or
13674 `org-move-item-up', depending on context. See the individual commands
13675 for more information."
13676 (interactive "P")
13677 (cond
13678 ((run-hook-with-args-until-success 'org-metaup-hook))
13679 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13680 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13681 ((org-at-item-p) (call-interactively 'org-move-item-up))
13682 (t (transpose-lines 1) (beginning-of-line -1))))
13684 (defun org-metadown (&optional arg)
13685 "Move subtree down or move table row down.
13686 Calls `org-move-subtree-down' or `org-table-move-row' or
13687 `org-move-item-down', depending on context. See the individual
13688 commands for more information."
13689 (interactive "P")
13690 (cond
13691 ((run-hook-with-args-until-success 'org-metadown-hook))
13692 ((org-at-table-p) (call-interactively 'org-table-move-row))
13693 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13694 ((org-at-item-p) (call-interactively 'org-move-item-down))
13695 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13697 (defun org-shiftup (&optional arg)
13698 "Increase item in timestamp or increase priority of current headline.
13699 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13700 depending on context. See the individual commands for more information."
13701 (interactive "P")
13702 (cond
13703 ((and org-support-shift-select (org-region-active-p))
13704 (org-call-for-shift-select 'previous-line))
13705 ((org-at-timestamp-p t)
13706 (call-interactively (if org-edit-timestamp-down-means-later
13707 'org-timestamp-down 'org-timestamp-up)))
13708 ((and (not (eq org-support-shift-select 'always))
13709 (org-on-heading-p))
13710 (call-interactively 'org-priority-up))
13711 ((and (not org-support-shift-select) (org-at-item-p))
13712 (call-interactively 'org-previous-item))
13713 ((org-clocktable-try-shift 'up arg))
13714 (org-support-shift-select
13715 (org-call-for-shift-select 'previous-line))
13716 (t (org-shiftselect-error))))
13718 (defun org-shiftdown (&optional arg)
13719 "Decrease item in timestamp or decrease priority of current headline.
13720 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13721 depending on context. See the individual commands for more information."
13722 (interactive "P")
13723 (cond
13724 ((and org-support-shift-select (org-region-active-p))
13725 (org-call-for-shift-select 'next-line))
13726 ((org-at-timestamp-p t)
13727 (call-interactively (if org-edit-timestamp-down-means-later
13728 'org-timestamp-up 'org-timestamp-down)))
13729 ((and (not (eq org-support-shift-select 'always))
13730 (org-on-heading-p))
13731 (call-interactively 'org-priority-down))
13732 ((and (not org-support-shift-select) (org-at-item-p))
13733 (call-interactively 'org-next-item))
13734 ((org-clocktable-try-shift 'down arg))
13735 (org-support-shift-select
13736 (org-call-for-shift-select 'next-line))
13737 (t (org-shiftselect-error))))
13739 (defun org-shiftright (&optional arg)
13740 "Cycle the thing at point or in the current line, depending on context.
13741 Depending on context, this does one of the following:
13743 - switch a timestamp at point one day into the future
13744 - on a headline, switch to the next TODO keyword.
13745 - on an item, switch entire list to the next bullet type
13746 - on a property line, switch to the next allowed value
13747 - on a clocktable definition line, move time block into the future"
13748 (interactive "P")
13749 (cond
13750 ((and org-support-shift-select (org-region-active-p))
13751 (org-call-for-shift-select 'forward-char))
13752 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13753 ((and (not (eq org-support-shift-select 'always))
13754 (org-on-heading-p))
13755 (org-call-with-arg 'org-todo 'right))
13756 ((or (and org-support-shift-select
13757 (not (eq org-support-shift-select 'always))
13758 (org-at-item-bullet-p))
13759 (and (not org-support-shift-select) (org-at-item-p)))
13760 (org-call-with-arg 'org-cycle-list-bullet nil))
13761 ((and (not (eq org-support-shift-select 'always))
13762 (org-at-property-p))
13763 (call-interactively 'org-property-next-allowed-value))
13764 ((org-clocktable-try-shift 'right arg))
13765 (org-support-shift-select
13766 (org-call-for-shift-select 'forward-char))
13767 (t (org-shiftselect-error))))
13769 (defun org-shiftleft (&optional arg)
13770 "Cycle the thing at point or in the current line, depending on context.
13771 Depending on context, this does one of the following:
13773 - switch a timestamp at point one day into the past
13774 - on a headline, switch to the previous TODO keyword.
13775 - on an item, switch entire list to the previous bullet type
13776 - on a property line, switch to the previous allowed value
13777 - on a clocktable definition line, move time block into the past"
13778 (interactive "P")
13779 (cond
13780 ((and org-support-shift-select (org-region-active-p))
13781 (org-call-for-shift-select 'backward-char))
13782 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13783 ((and (not (eq org-support-shift-select 'always))
13784 (org-on-heading-p))
13785 (org-call-with-arg 'org-todo 'left))
13786 ((or (and org-support-shift-select
13787 (not (eq org-support-shift-select 'always))
13788 (org-at-item-bullet-p))
13789 (and (not org-support-shift-select) (org-at-item-p)))
13790 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13791 ((and (not (eq org-support-shift-select 'always))
13792 (org-at-property-p))
13793 (call-interactively 'org-property-previous-allowed-value))
13794 ((org-clocktable-try-shift 'left arg))
13795 (org-support-shift-select
13796 (org-call-for-shift-select 'backward-char))
13797 (t (org-shiftselect-error))))
13799 (defun org-shiftcontrolright ()
13800 "Switch to next TODO set."
13801 (interactive)
13802 (cond
13803 ((and org-support-shift-select (org-region-active-p))
13804 (org-call-for-shift-select 'forward-word))
13805 ((and (not (eq org-support-shift-select 'always))
13806 (org-on-heading-p))
13807 (org-call-with-arg 'org-todo 'nextset))
13808 (org-support-shift-select
13809 (org-call-for-shift-select 'forward-word))
13810 (t (org-shiftselect-error))))
13812 (defun org-shiftcontrolleft ()
13813 "Switch to previous TODO set."
13814 (interactive)
13815 (cond
13816 ((and org-support-shift-select (org-region-active-p))
13817 (org-call-for-shift-select 'backward-word))
13818 ((and (not (eq org-support-shift-select 'always))
13819 (org-on-heading-p))
13820 (org-call-with-arg 'org-todo 'previousset))
13821 (org-support-shift-select
13822 (org-call-for-shift-select 'backward-word))
13823 (t (org-shiftselect-error))))
13825 (defun org-ctrl-c-ret ()
13826 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13827 (interactive)
13828 (cond
13829 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13830 (t (call-interactively 'org-insert-heading))))
13832 (defun org-copy-special ()
13833 "Copy region in table or copy current subtree.
13834 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13835 See the individual commands for more information."
13836 (interactive)
13837 (call-interactively
13838 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13840 (defun org-cut-special ()
13841 "Cut region in table or cut current subtree.
13842 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13843 See the individual commands for more information."
13844 (interactive)
13845 (call-interactively
13846 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13848 (defun org-paste-special (arg)
13849 "Paste rectangular region into table, or past subtree relative to level.
13850 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13851 See the individual commands for more information."
13852 (interactive "P")
13853 (if (org-at-table-p)
13854 (org-table-paste-rectangle)
13855 (org-paste-subtree arg)))
13857 (defun org-edit-special ()
13858 "Call a special editor for the stuff at point.
13859 When at a table, call the formula editor with `org-table-edit-formulas'.
13860 When at the first line of an src example, call `org-edit-src-code'.
13861 When in an #+include line, visit the include file. Otherwise call
13862 `ffap' to visit the file at point."
13863 (interactive)
13864 (cond
13865 ((org-at-table-p)
13866 (call-interactively 'org-table-edit-formulas))
13867 ((save-excursion
13868 (beginning-of-line 1)
13869 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13870 (find-file (org-trim (match-string 1))))
13871 ((org-edit-src-code))
13872 ((org-edit-fixed-width-region))
13873 (t (call-interactively 'ffap))))
13876 (defun org-ctrl-c-ctrl-c (&optional arg)
13877 "Set tags in headline, or update according to changed information at point.
13879 This command does many different things, depending on context:
13881 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
13882 this is what we do.
13884 - If the cursor is in a headline, prompt for tags and insert them
13885 into the current line, aligned to `org-tags-column'. When called
13886 with prefix arg, realign all tags in the current buffer.
13888 - If the cursor is in one of the special #+KEYWORD lines, this
13889 triggers scanning the buffer for these lines and updating the
13890 information.
13892 - If the cursor is inside a table, realign the table. This command
13893 works even if the automatic table editor has been turned off.
13895 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13896 the entire table.
13898 - If the cursor is at a footnote reference or definition, jump to
13899 the corresponding definition or references, respectively.
13901 - If the cursor is a the beginning of a dynamic block, update it.
13903 - If the cursor is inside a table created by the table.el package,
13904 activate that table.
13906 - If the current buffer is a remember buffer, close note and file
13907 it. A prefix argument of 1 files to the default location
13908 without further interaction. A prefix argument of 2 files to
13909 the currently clocking task.
13911 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13912 links in this buffer.
13914 - If the cursor is on a numbered item in a plain list, renumber the
13915 ordered list.
13917 - If the cursor is on a checkbox, toggle it."
13918 (interactive "P")
13919 (let ((org-enable-table-editor t))
13920 (cond
13921 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13922 org-occur-highlights
13923 org-latex-fragment-image-overlays)
13924 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13925 (org-remove-occur-highlights)
13926 (org-remove-latex-fragment-image-overlays)
13927 (message "Temporary highlights/overlays removed from current buffer"))
13928 ((and (local-variable-p 'org-finish-function (current-buffer))
13929 (fboundp org-finish-function))
13930 (funcall org-finish-function))
13931 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
13932 ((org-at-property-p)
13933 (call-interactively 'org-property-action))
13934 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13935 ((org-on-heading-p) (call-interactively 'org-set-tags))
13936 ((org-at-table.el-p)
13937 (require 'table)
13938 (beginning-of-line 1)
13939 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13940 (call-interactively 'table-recognize-table))
13941 ((org-at-table-p)
13942 (org-table-maybe-eval-formula)
13943 (if arg
13944 (call-interactively 'org-table-recalculate)
13945 (org-table-maybe-recalculate-line))
13946 (call-interactively 'org-table-align))
13947 ((or (org-footnote-at-reference-p)
13948 (org-footnote-at-definition-p))
13949 (call-interactively 'org-footnote-action))
13950 ((org-at-item-checkbox-p)
13951 (call-interactively 'org-toggle-checkbox))
13952 ((org-at-item-p)
13953 (if arg
13954 (call-interactively 'org-toggle-checkbox)
13955 (call-interactively 'org-maybe-renumber-ordered-list)))
13956 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13957 ;; Dynamic block
13958 (beginning-of-line 1)
13959 (save-excursion (org-update-dblock)))
13960 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13961 (cond
13962 ((equal (match-string 1) "TBLFM")
13963 ;; Recalculate the table before this line
13964 (save-excursion
13965 (beginning-of-line 1)
13966 (skip-chars-backward " \r\n\t")
13967 (if (org-at-table-p)
13968 (org-call-with-arg 'org-table-recalculate t))))
13970 ; (org-set-regexps-and-options)
13971 ; (org-restart-font-lock)
13972 (let ((org-inhibit-startup t)) (org-mode-restart))
13973 (message "Local setup has been refreshed"))))
13974 (t (error "C-c C-c can do nothing useful at this location.")))))
13976 (defun org-mode-restart ()
13977 "Restart Org-mode, to scan again for special lines.
13978 Also updates the keyword regular expressions."
13979 (interactive)
13980 (org-mode)
13981 (message "Org-mode restarted"))
13983 (defun org-kill-note-or-show-branches ()
13984 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13985 (interactive)
13986 (if (not org-finish-function)
13987 (call-interactively 'show-branches)
13988 (let ((org-note-abort t))
13989 (funcall org-finish-function))))
13991 (defun org-return (&optional indent)
13992 "Goto next table row or insert a newline.
13993 Calls `org-table-next-row' or `newline', depending on context.
13994 See the individual commands for more information."
13995 (interactive)
13996 (cond
13997 ((bobp) (if indent (newline-and-indent) (newline)))
13998 ((org-at-table-p)
13999 (org-table-justify-field-maybe)
14000 (call-interactively 'org-table-next-row))
14001 ((and org-return-follows-link
14002 (eq (get-text-property (point) 'face) 'org-link))
14003 (call-interactively 'org-open-at-point))
14004 ((and (org-at-heading-p)
14005 (looking-at
14006 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14007 (org-show-entry)
14008 (end-of-line 1)
14009 (newline))
14010 (t (if indent (newline-and-indent) (newline)))))
14012 (defun org-return-indent ()
14013 "Goto next table row or insert a newline and indent.
14014 Calls `org-table-next-row' or `newline-and-indent', depending on
14015 context. See the individual commands for more information."
14016 (interactive)
14017 (org-return t))
14019 (defun org-ctrl-c-star ()
14020 "Compute table, or change heading status of lines.
14021 Calls `org-table-recalculate' or `org-toggle-heading',
14022 depending on context."
14023 (interactive)
14024 (cond
14025 ((org-at-table-p)
14026 (call-interactively 'org-table-recalculate))
14028 ;; Convert all lines in region to list items
14029 (call-interactively 'org-toggle-heading))))
14031 (defun org-ctrl-c-minus ()
14032 "Insert separator line in table or modify bullet status of line.
14033 Also turns a plain line or a region of lines into list items.
14034 Calls `org-table-insert-hline', `org-toggle-item', or
14035 `org-cycle-list-bullet', depending on context."
14036 (interactive)
14037 (cond
14038 ((org-at-table-p)
14039 (call-interactively 'org-table-insert-hline))
14040 ((org-region-active-p)
14041 (call-interactively 'org-toggle-item))
14042 ((org-in-item-p)
14043 (call-interactively 'org-cycle-list-bullet))
14045 (call-interactively 'org-toggle-item))))
14047 (defun org-toggle-item ()
14048 "Convert headings or normal lines to items, items to normal lines.
14049 If there is no active region, only the current line is considered.
14051 If the first line in the region is a headline, convert all headlines to items.
14053 If the first line in the region is an item, convert all items to normal lines.
14055 If the first line is normal text, add an item bullet to each line."
14056 (interactive)
14057 (let (l2 l beg end)
14058 (if (org-region-active-p)
14059 (setq beg (region-beginning) end (region-end))
14060 (setq beg (point-at-bol)
14061 end (min (1+ (point-at-eol)) (point-max))))
14062 (save-excursion
14063 (goto-char end)
14064 (setq l2 (org-current-line))
14065 (goto-char beg)
14066 (beginning-of-line 1)
14067 (setq l (1- (org-current-line)))
14068 (if (org-at-item-p)
14069 ;; We already have items, de-itemize
14070 (while (< (setq l (1+ l)) l2)
14071 (when (org-at-item-p)
14072 (goto-char (match-beginning 2))
14073 (delete-region (match-beginning 2) (match-end 2))
14074 (and (looking-at "[ \t]+") (replace-match "")))
14075 (beginning-of-line 2))
14076 (if (org-on-heading-p)
14077 ;; Headings, convert to items
14078 (while (< (setq l (1+ l)) l2)
14079 (if (looking-at org-outline-regexp)
14080 (replace-match "- " t t))
14081 (beginning-of-line 2))
14082 ;; normal lines, turn them into items
14083 (while (< (setq l (1+ l)) l2)
14084 (unless (org-at-item-p)
14085 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14086 (replace-match "\\1- \\2")))
14087 (beginning-of-line 2)))))))
14089 (defun org-toggle-heading (&optional nstars)
14090 "Convert headings to normal text, or items or text to headings.
14091 If there is no active region, only the current line is considered.
14093 If the first line is a heading, remove the stars from all headlines
14094 in the region.
14096 If the first line is a plain list item, turn all plain list items into
14097 headings.
14099 If the first line is a normal line, turn each and every line in the region
14100 into a heading.
14102 When converting a line into a heading, the number of stars is chosen
14103 such that the lines become children of the current entry. However, when
14104 a prefix argument is given, its value determines the number of stars to add."
14105 (interactive "P")
14106 (let (l2 l itemp beg end)
14107 (if (org-region-active-p)
14108 (setq beg (region-beginning) end (region-end))
14109 (setq beg (point-at-bol)
14110 end (min (1+ (point-at-eol)) (point-max))))
14111 (save-excursion
14112 (goto-char end)
14113 (setq l2 (org-current-line))
14114 (goto-char beg)
14115 (beginning-of-line 1)
14116 (setq l (1- (org-current-line)))
14117 (if (org-on-heading-p)
14118 ;; We already have headlines, de-star them
14119 (while (< (setq l (1+ l)) l2)
14120 (when (org-on-heading-p t)
14121 (and (looking-at outline-regexp) (replace-match "")))
14122 (beginning-of-line 2))
14123 (setq itemp (org-at-item-p))
14124 (let* ((stars
14125 (if nstars
14126 (make-string (prefix-numeric-value current-prefix-arg)
14128 (save-excursion
14129 (re-search-backward org-complex-heading-regexp nil t)
14130 (or (match-string 1) "*"))))
14131 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
14132 (rpl (concat stars add-stars " ")))
14133 (while (< (setq l (1+ l)) l2)
14134 (if itemp
14135 (and (org-at-item-p) (replace-match rpl t t))
14136 (unless (org-on-heading-p)
14137 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14138 (replace-match (concat rpl (match-string 2))))))
14139 (beginning-of-line 2)))))))
14141 (defun org-meta-return (&optional arg)
14142 "Insert a new heading or wrap a region in a table.
14143 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14144 See the individual commands for more information."
14145 (interactive "P")
14146 (cond
14147 ((run-hook-with-args-until-success 'org-metareturn-hook))
14148 ((org-at-table-p)
14149 (call-interactively 'org-table-wrap-region))
14150 (t (call-interactively 'org-insert-heading))))
14152 ;;; Menu entries
14154 ;; Define the Org-mode menus
14155 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14156 '("Tbl"
14157 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14158 ["Next Field" org-cycle (org-at-table-p)]
14159 ["Previous Field" org-shifttab (org-at-table-p)]
14160 ["Next Row" org-return (org-at-table-p)]
14161 "--"
14162 ["Blank Field" org-table-blank-field (org-at-table-p)]
14163 ["Edit Field" org-table-edit-field (org-at-table-p)]
14164 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14165 "--"
14166 ("Column"
14167 ["Move Column Left" org-metaleft (org-at-table-p)]
14168 ["Move Column Right" org-metaright (org-at-table-p)]
14169 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14170 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14171 ("Row"
14172 ["Move Row Up" org-metaup (org-at-table-p)]
14173 ["Move Row Down" org-metadown (org-at-table-p)]
14174 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14175 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14176 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14177 "--"
14178 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14179 ("Rectangle"
14180 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14181 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14182 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14183 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14184 "--"
14185 ("Calculate"
14186 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14187 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14188 ["Edit Formulas" org-edit-special (org-at-table-p)]
14189 "--"
14190 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14191 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14192 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14193 "--"
14194 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14195 "--"
14196 ["Sum Column/Rectangle" org-table-sum
14197 (or (org-at-table-p) (org-region-active-p))]
14198 ["Which Column?" org-table-current-column (org-at-table-p)])
14199 ["Debug Formulas"
14200 org-table-toggle-formula-debugger
14201 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14202 ["Show Col/Row Numbers"
14203 org-table-toggle-coordinate-overlays
14204 :style toggle
14205 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14206 "--"
14207 ["Create" org-table-create (and (not (org-at-table-p))
14208 org-enable-table-editor)]
14209 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14210 ["Import from File" org-table-import (not (org-at-table-p))]
14211 ["Export to File" org-table-export (org-at-table-p)]
14212 "--"
14213 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14215 (easy-menu-define org-org-menu org-mode-map "Org menu"
14216 '("Org"
14217 ("Show/Hide"
14218 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14219 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14220 ["Sparse Tree..." org-sparse-tree t]
14221 ["Reveal Context" org-reveal t]
14222 ["Show All" show-all t]
14223 "--"
14224 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14225 "--"
14226 ["New Heading" org-insert-heading t]
14227 ("Navigate Headings"
14228 ["Up" outline-up-heading t]
14229 ["Next" outline-next-visible-heading t]
14230 ["Previous" outline-previous-visible-heading t]
14231 ["Next Same Level" outline-forward-same-level t]
14232 ["Previous Same Level" outline-backward-same-level t]
14233 "--"
14234 ["Jump" org-goto t])
14235 ("Edit Structure"
14236 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14237 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14238 "--"
14239 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14240 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14241 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14242 "--"
14243 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14244 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14245 ["Demote Heading" org-metaright (not (org-at-table-p))]
14246 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14247 "--"
14248 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14249 "--"
14250 ["Convert to odd levels" org-convert-to-odd-levels t]
14251 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14252 ("Editing"
14253 ["Emphasis..." org-emphasize t]
14254 ["Edit Source Example" org-edit-special t]
14255 "--"
14256 ["Footnote new/jump" org-footnote-action t]
14257 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14258 ("Archive"
14259 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14260 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14261 ; :active t :keys "C-u C-c C-x C-a"]
14262 ["Sparse trees open ARCHIVE trees"
14263 (setq org-sparse-tree-open-archived-trees
14264 (not org-sparse-tree-open-archived-trees))
14265 :style toggle :selected org-sparse-tree-open-archived-trees]
14266 ["Cycling opens ARCHIVE trees"
14267 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14268 :style toggle :selected org-cycle-open-archived-trees]
14269 "--"
14270 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14271 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14272 ; ["Check and Move Children" (org-archive-subtree '(4))
14273 ; :active t :keys "C-u C-c C-x C-s"]
14275 "--"
14276 ("TODO Lists"
14277 ["TODO/DONE/-" org-todo t]
14278 ("Select keyword"
14279 ["Next keyword" org-shiftright (org-on-heading-p)]
14280 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14281 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14282 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14283 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14284 ["Show TODO Tree" org-show-todo-tree t]
14285 ["Global TODO list" org-todo-list t]
14286 "--"
14287 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14288 :selected org-enforce-todo-dependencies :style toggle :active t]
14289 "Settings for tree at point"
14290 ["Do Children sequentially" org-toggle-ordered-property :style radio
14291 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14292 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14293 ["Do Children parallel" org-toggle-ordered-property :style radio
14294 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14295 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14296 "--"
14297 ["Set Priority" org-priority t]
14298 ["Priority Up" org-shiftup t]
14299 ["Priority Down" org-shiftdown t])
14300 ("TAGS and Properties"
14301 ["Set Tags" org-set-tags-command t]
14302 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14303 "--"
14304 ["Set property" org-set-property t]
14305 ["Column view of properties" org-columns t]
14306 ["Insert Column View DBlock" org-insert-columns-dblock t])
14307 ("Dates and Scheduling"
14308 ["Timestamp" org-time-stamp t]
14309 ["Timestamp (inactive)" org-time-stamp-inactive t]
14310 ("Change Date"
14311 ["1 Day Later" org-shiftright t]
14312 ["1 Day Earlier" org-shiftleft t]
14313 ["1 ... Later" org-shiftup t]
14314 ["1 ... Earlier" org-shiftdown t])
14315 ["Compute Time Range" org-evaluate-time-range t]
14316 ["Schedule Item" org-schedule t]
14317 ["Deadline" org-deadline t]
14318 "--"
14319 ["Custom time format" org-toggle-time-stamp-overlays
14320 :style radio :selected org-display-custom-times]
14321 "--"
14322 ["Goto Calendar" org-goto-calendar t]
14323 ["Date from Calendar" org-date-from-calendar t]
14324 "--"
14325 ["Start/Restart Timer" org-timer-start t]
14326 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14327 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14328 ["Insert Timer String" org-timer t]
14329 ["Insert Timer Item" org-timer-item t])
14330 ("Logging work"
14331 ["Clock in" org-clock-in t]
14332 ["Clock out" org-clock-out t]
14333 ["Clock cancel" org-clock-cancel t]
14334 ["Goto running clock" org-clock-goto t]
14335 ["Display times" org-clock-display t]
14336 ["Create clock table" org-clock-report t]
14337 "--"
14338 ["Record DONE time"
14339 (progn (setq org-log-done (not org-log-done))
14340 (message "Switching to %s will %s record a timestamp"
14341 (car org-done-keywords)
14342 (if org-log-done "automatically" "not")))
14343 :style toggle :selected org-log-done])
14344 "--"
14345 ["Agenda Command..." org-agenda t]
14346 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14347 ("File List for Agenda")
14348 ("Special views current file"
14349 ["TODO Tree" org-show-todo-tree t]
14350 ["Check Deadlines" org-check-deadlines t]
14351 ["Timeline" org-timeline t]
14352 ["Tags/Property tree" org-match-sparse-tree t])
14353 "--"
14354 ("Hyperlinks"
14355 ["Store Link (Global)" org-store-link t]
14356 ["Insert Link" org-insert-link t]
14357 ["Follow Link" org-open-at-point t]
14358 "--"
14359 ["Next link" org-next-link t]
14360 ["Previous link" org-previous-link t]
14361 "--"
14362 ["Descriptive Links"
14363 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14364 :style radio
14365 :selected (member '(org-link) buffer-invisibility-spec)]
14366 ["Literal Links"
14367 (progn
14368 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14369 :style radio
14370 :selected (not (member '(org-link) buffer-invisibility-spec))])
14371 "--"
14372 ["Export/Publish..." org-export t]
14373 ("LaTeX"
14374 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14375 :selected org-cdlatex-mode]
14376 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14377 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14378 ["Modify math symbol" org-cdlatex-math-modify
14379 (org-inside-LaTeX-fragment-p)]
14380 ["Export LaTeX fragments as images"
14381 (if (featurep 'org-exp)
14382 (setq org-export-with-LaTeX-fragments
14383 (not org-export-with-LaTeX-fragments))
14384 (require 'org-exp))
14385 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14386 org-export-with-LaTeX-fragments)])
14387 "--"
14388 ("Documentation"
14389 ["Show Version" org-version t]
14390 ["Info Documentation" org-info t])
14391 ("Customize"
14392 ["Browse Org Group" org-customize t]
14393 "--"
14394 ["Expand This Menu" org-create-customize-menu
14395 (fboundp 'customize-menu-create)])
14396 "--"
14397 ("Refresh/Reload"
14398 ["Refresh setup current buffer" org-mode-restart t]
14399 ["Reload Org (after update)" org-reload t]
14400 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14403 (defun org-info (&optional node)
14404 "Read documentation for Org-mode in the info system.
14405 With optional NODE, go directly to that node."
14406 (interactive)
14407 (info (format "(org)%s" (or node ""))))
14409 (defun org-install-agenda-files-menu ()
14410 (let ((bl (buffer-list)))
14411 (save-excursion
14412 (while bl
14413 (set-buffer (pop bl))
14414 (if (org-mode-p) (setq bl nil)))
14415 (when (org-mode-p)
14416 (easy-menu-change
14417 '("Org") "File List for Agenda"
14418 (append
14419 (list
14420 ["Edit File List" (org-edit-agenda-file-list) t]
14421 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14422 ["Remove Current File from List" org-remove-file t]
14423 ["Cycle through agenda files" org-cycle-agenda-files t]
14424 ["Occur in all agenda files" org-occur-in-agenda-files t]
14425 "--")
14426 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14428 ;;;; Documentation
14430 ;;;###autoload
14431 (defun org-require-autoloaded-modules ()
14432 (interactive)
14433 (mapc 'require
14434 '(org-agenda org-archive org-attach org-clock org-colview
14435 org-exp org-id org-export-latex org-publish
14436 org-remember org-table org-timer)))
14438 ;;;###autoload
14439 (defun org-reload (&optional uncompiled)
14440 "Reload all org lisp files.
14441 With prefix arg UNCOMPILED, load the uncompiled versions."
14442 (interactive "P")
14443 (require 'find-func)
14444 (let* ((dir (file-name-directory (find-library-name "org")))
14445 (files (directory-files dir t "\\.el\\'"))
14446 (remove-re (concat (if (featurep 'xemacs)
14447 "org-colview" "org-colview-xemacs")
14448 "\\'")))
14449 (setq files (mapcar 'file-name-sans-extension files))
14450 (setq files (mapcar
14451 (lambda (x) (if (string-match remove-re x) nil x))
14452 files))
14453 (setq files (delq nil files))
14454 (mapc
14455 (lambda (f)
14456 (if (and (not uncompiled)
14457 (file-exists-p (concat f ".elc")))
14458 (load (concat f ".elc") nil nil t)
14459 (load (concat f ".el") nil nil t)))
14460 files)))
14462 ;;;###autoload
14463 (defun org-customize ()
14464 "Call the customize function with org as argument."
14465 (interactive)
14466 (org-load-modules-maybe)
14467 (org-require-autoloaded-modules)
14468 (customize-browse 'org))
14470 (defun org-create-customize-menu ()
14471 "Create a full customization menu for Org-mode, insert it into the menu."
14472 (interactive)
14473 (org-load-modules-maybe)
14474 (org-require-autoloaded-modules)
14475 (if (fboundp 'customize-menu-create)
14476 (progn
14477 (easy-menu-change
14478 '("Org") "Customize"
14479 `(["Browse Org group" org-customize t]
14480 "--"
14481 ,(customize-menu-create 'org)
14482 ["Set" Custom-set t]
14483 ["Save" Custom-save t]
14484 ["Reset to Current" Custom-reset-current t]
14485 ["Reset to Saved" Custom-reset-saved t]
14486 ["Reset to Standard Settings" Custom-reset-standard t]))
14487 (message "\"Org\"-menu now contains full customization menu"))
14488 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14490 ;;;; Miscellaneous stuff
14492 ;;; Generally useful functions
14494 (defun org-find-text-property-in-string (prop s)
14495 "Return the first non-nil value of property PROP in string S."
14496 (or (get-text-property 0 prop s)
14497 (get-text-property (or (next-single-property-change 0 prop s) 0)
14498 prop s)))
14500 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14501 "Display the given MESSAGE as a warning."
14502 (if (fboundp 'display-warning)
14503 (display-warning 'org message
14504 (if (featurep 'xemacs)
14505 'warning
14506 :warning))
14507 (let ((buf (get-buffer-create "*Org warnings*")))
14508 (with-current-buffer buf
14509 (goto-char (point-max))
14510 (insert "Warning (Org): " message)
14511 (unless (bolp)
14512 (newline)))
14513 (display-buffer buf)
14514 (sit-for 0))))
14516 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14517 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14518 (if (and marker (marker-buffer marker)
14519 (buffer-live-p (marker-buffer marker)))
14520 (progn
14521 (switch-to-buffer (marker-buffer marker))
14522 (if (or (> marker (point-max)) (< marker (point-min)))
14523 (widen))
14524 (goto-char marker)
14525 (org-show-context 'org-goto))
14526 (if bookmark
14527 (bookmark-jump bookmark)
14528 (error "Cannot find location"))))
14530 (defun org-quote-csv-field (s)
14531 "Quote field for inclusion in CSV material."
14532 (if (string-match "[\",]" s)
14533 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14536 (defun org-plist-delete (plist property)
14537 "Delete PROPERTY from PLIST.
14538 This is in contrast to merely setting it to 0."
14539 (let (p)
14540 (while plist
14541 (if (not (eq property (car plist)))
14542 (setq p (plist-put p (car plist) (nth 1 plist))))
14543 (setq plist (cddr plist)))
14546 (defun org-force-self-insert (N)
14547 "Needed to enforce self-insert under remapping."
14548 (interactive "p")
14549 (self-insert-command N))
14551 (defun org-string-width (s)
14552 "Compute width of string, ignoring invisible characters.
14553 This ignores character with invisibility property `org-link', and also
14554 characters with property `org-cwidth', because these will become invisible
14555 upon the next fontification round."
14556 (let (b l)
14557 (when (or (eq t buffer-invisibility-spec)
14558 (assq 'org-link buffer-invisibility-spec))
14559 (while (setq b (text-property-any 0 (length s)
14560 'invisible 'org-link s))
14561 (setq s (concat (substring s 0 b)
14562 (substring s (or (next-single-property-change
14563 b 'invisible s) (length s)))))))
14564 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14565 (setq s (concat (substring s 0 b)
14566 (substring s (or (next-single-property-change
14567 b 'org-cwidth s) (length s))))))
14568 (setq l (string-width s) b -1)
14569 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14570 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14573 (defun org-get-indentation (&optional line)
14574 "Get the indentation of the current line, interpreting tabs.
14575 When LINE is given, assume it represents a line and compute its indentation."
14576 (if line
14577 (if (string-match "^ *" (org-remove-tabs line))
14578 (match-end 0))
14579 (save-excursion
14580 (beginning-of-line 1)
14581 (skip-chars-forward " \t")
14582 (current-column))))
14584 (defun org-remove-tabs (s &optional width)
14585 "Replace tabulators in S with spaces.
14586 Assumes that s is a single line, starting in column 0."
14587 (setq width (or width tab-width))
14588 (while (string-match "\t" s)
14589 (setq s (replace-match
14590 (make-string
14591 (- (* width (/ (+ (match-beginning 0) width) width))
14592 (match-beginning 0)) ?\ )
14593 t t s)))
14596 (defun org-fix-indentation (line ind)
14597 "Fix indentation in LINE.
14598 IND is a cons cell with target and minimum indentation.
14599 If the current indentation in LINE is smaller than the minimum,
14600 leave it alone. If it is larger than ind, set it to the target."
14601 (let* ((l (org-remove-tabs line))
14602 (i (org-get-indentation l))
14603 (i1 (car ind)) (i2 (cdr ind)))
14604 (if (>= i i2) (setq l (substring line i2)))
14605 (if (> i1 0)
14606 (concat (make-string i1 ?\ ) l)
14607 l)))
14609 (defun org-base-buffer (buffer)
14610 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14611 (if (not buffer)
14612 buffer
14613 (or (buffer-base-buffer buffer)
14614 buffer)))
14616 (defun org-trim (s)
14617 "Remove whitespace at beginning and end of string."
14618 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14619 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14622 (defun org-wrap (string &optional width lines)
14623 "Wrap string to either a number of lines, or a width in characters.
14624 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14625 that costs. If there is a word longer than WIDTH, the text is actually
14626 wrapped to the length of that word.
14627 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14628 many lines, whatever width that takes.
14629 The return value is a list of lines, without newlines at the end."
14630 (let* ((words (org-split-string string "[ \t\n]+"))
14631 (maxword (apply 'max (mapcar 'org-string-width words)))
14632 w ll)
14633 (cond (width
14634 (org-do-wrap words (max maxword width)))
14635 (lines
14636 (setq w maxword)
14637 (setq ll (org-do-wrap words maxword))
14638 (if (<= (length ll) lines)
14640 (setq ll words)
14641 (while (> (length ll) lines)
14642 (setq w (1+ w))
14643 (setq ll (org-do-wrap words w)))
14644 ll))
14645 (t (error "Cannot wrap this")))))
14647 (defun org-do-wrap (words width)
14648 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14649 (let (lines line)
14650 (while words
14651 (setq line (pop words))
14652 (while (and words (< (+ (length line) (length (car words))) width))
14653 (setq line (concat line " " (pop words))))
14654 (setq lines (push line lines)))
14655 (nreverse lines)))
14657 (defun org-split-string (string &optional separators)
14658 "Splits STRING into substrings at SEPARATORS.
14659 No empty strings are returned if there are matches at the beginning
14660 and end of string."
14661 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14662 (start 0)
14663 notfirst
14664 (list nil))
14665 (while (and (string-match rexp string
14666 (if (and notfirst
14667 (= start (match-beginning 0))
14668 (< start (length string)))
14669 (1+ start) start))
14670 (< (match-beginning 0) (length string)))
14671 (setq notfirst t)
14672 (or (eq (match-beginning 0) 0)
14673 (and (eq (match-beginning 0) (match-end 0))
14674 (eq (match-beginning 0) start))
14675 (setq list
14676 (cons (substring string start (match-beginning 0))
14677 list)))
14678 (setq start (match-end 0)))
14679 (or (eq start (length string))
14680 (setq list
14681 (cons (substring string start)
14682 list)))
14683 (nreverse list)))
14685 (defun org-uuidgen-p (s)
14686 "Is S an ID created by UUIDGEN?"
14687 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
14689 (defun org-context ()
14690 "Return a list of contexts of the current cursor position.
14691 If several contexts apply, all are returned.
14692 Each context entry is a list with a symbol naming the context, and
14693 two positions indicating start and end of the context. Possible
14694 contexts are:
14696 :headline anywhere in a headline
14697 :headline-stars on the leading stars in a headline
14698 :todo-keyword on a TODO keyword (including DONE) in a headline
14699 :tags on the TAGS in a headline
14700 :priority on the priority cookie in a headline
14701 :item on the first line of a plain list item
14702 :item-bullet on the bullet/number of a plain list item
14703 :checkbox on the checkbox in a plain list item
14704 :table in an org-mode table
14705 :table-special on a special filed in a table
14706 :table-table in a table.el table
14707 :link on a hyperlink
14708 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14709 :target on a <<target>>
14710 :radio-target on a <<<radio-target>>>
14711 :latex-fragment on a LaTeX fragment
14712 :latex-preview on a LaTeX fragment with overlayed preview image
14714 This function expects the position to be visible because it uses font-lock
14715 faces as a help to recognize the following contexts: :table-special, :link,
14716 and :keyword."
14717 (let* ((f (get-text-property (point) 'face))
14718 (faces (if (listp f) f (list f)))
14719 (p (point)) clist o)
14720 ;; First the large context
14721 (cond
14722 ((org-on-heading-p t)
14723 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14724 (when (progn
14725 (beginning-of-line 1)
14726 (looking-at org-todo-line-tags-regexp))
14727 (push (org-point-in-group p 1 :headline-stars) clist)
14728 (push (org-point-in-group p 2 :todo-keyword) clist)
14729 (push (org-point-in-group p 4 :tags) clist))
14730 (goto-char p)
14731 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14732 (if (looking-at "\\[#[A-Z0-9]\\]")
14733 (push (org-point-in-group p 0 :priority) clist)))
14735 ((org-at-item-p)
14736 (push (org-point-in-group p 2 :item-bullet) clist)
14737 (push (list :item (point-at-bol)
14738 (save-excursion (org-end-of-item) (point)))
14739 clist)
14740 (and (org-at-item-checkbox-p)
14741 (push (org-point-in-group p 0 :checkbox) clist)))
14743 ((org-at-table-p)
14744 (push (list :table (org-table-begin) (org-table-end)) clist)
14745 (if (memq 'org-formula faces)
14746 (push (list :table-special
14747 (previous-single-property-change p 'face)
14748 (next-single-property-change p 'face)) clist)))
14749 ((org-at-table-p 'any)
14750 (push (list :table-table) clist)))
14751 (goto-char p)
14753 ;; Now the small context
14754 (cond
14755 ((org-at-timestamp-p)
14756 (push (org-point-in-group p 0 :timestamp) clist))
14757 ((memq 'org-link faces)
14758 (push (list :link
14759 (previous-single-property-change p 'face)
14760 (next-single-property-change p 'face)) clist))
14761 ((memq 'org-special-keyword faces)
14762 (push (list :keyword
14763 (previous-single-property-change p 'face)
14764 (next-single-property-change p 'face)) clist))
14765 ((org-on-target-p)
14766 (push (org-point-in-group p 0 :target) clist)
14767 (goto-char (1- (match-beginning 0)))
14768 (if (looking-at org-radio-target-regexp)
14769 (push (org-point-in-group p 0 :radio-target) clist))
14770 (goto-char p))
14771 ((setq o (car (delq nil
14772 (mapcar
14773 (lambda (x)
14774 (if (memq x org-latex-fragment-image-overlays) x))
14775 (org-overlays-at (point))))))
14776 (push (list :latex-fragment
14777 (org-overlay-start o) (org-overlay-end o)) clist)
14778 (push (list :latex-preview
14779 (org-overlay-start o) (org-overlay-end o)) clist))
14780 ((org-inside-LaTeX-fragment-p)
14781 ;; FIXME: positions wrong.
14782 (push (list :latex-fragment (point) (point)) clist)))
14784 (setq clist (nreverse (delq nil clist)))
14785 clist))
14787 ;; FIXME: Compare with at-regexp-p Do we need both?
14788 (defun org-in-regexp (re &optional nlines visually)
14789 "Check if point is inside a match of regexp.
14790 Normally only the current line is checked, but you can include NLINES extra
14791 lines both before and after point into the search.
14792 If VISUALLY is set, require that the cursor is not after the match but
14793 really on, so that the block visually is on the match."
14794 (catch 'exit
14795 (let ((pos (point))
14796 (eol (point-at-eol (+ 1 (or nlines 0))))
14797 (inc (if visually 1 0)))
14798 (save-excursion
14799 (beginning-of-line (- 1 (or nlines 0)))
14800 (while (re-search-forward re eol t)
14801 (if (and (<= (match-beginning 0) pos)
14802 (>= (+ inc (match-end 0)) pos))
14803 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14805 (defun org-at-regexp-p (regexp)
14806 "Is point inside a match of REGEXP in the current line?"
14807 (catch 'exit
14808 (save-excursion
14809 (let ((pos (point)) (end (point-at-eol)))
14810 (beginning-of-line 1)
14811 (while (re-search-forward regexp end t)
14812 (if (and (<= (match-beginning 0) pos)
14813 (>= (match-end 0) pos))
14814 (throw 'exit t)))
14815 nil))))
14817 (defun org-occur-in-agenda-files (regexp &optional nlines)
14818 "Call `multi-occur' with buffers for all agenda files."
14819 (interactive "sOrg-files matching: \np")
14820 (let* ((files (org-agenda-files))
14821 (tnames (mapcar 'file-truename files))
14822 (extra org-agenda-text-search-extra-files)
14824 (when (eq (car extra) 'agenda-archives)
14825 (setq extra (cdr extra))
14826 (setq files (org-add-archive-files files)))
14827 (while (setq f (pop extra))
14828 (unless (member (file-truename f) tnames)
14829 (add-to-list 'files f 'append)
14830 (add-to-list 'tnames (file-truename f) 'append)))
14831 (multi-occur
14832 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14833 regexp)))
14835 (if (boundp 'occur-mode-find-occurrence-hook)
14836 ;; Emacs 23
14837 (add-hook 'occur-mode-find-occurrence-hook
14838 (lambda ()
14839 (when (org-mode-p)
14840 (org-reveal))))
14841 ;; Emacs 22
14842 (defadvice occur-mode-goto-occurrence
14843 (after org-occur-reveal activate)
14844 (and (org-mode-p) (org-reveal)))
14845 (defadvice occur-mode-goto-occurrence-other-window
14846 (after org-occur-reveal activate)
14847 (and (org-mode-p) (org-reveal)))
14848 (defadvice occur-mode-display-occurrence
14849 (after org-occur-reveal activate)
14850 (when (org-mode-p)
14851 (let ((pos (occur-mode-find-occurrence)))
14852 (with-current-buffer (marker-buffer pos)
14853 (save-excursion
14854 (goto-char pos)
14855 (org-reveal)))))))
14857 (defun org-uniquify (list)
14858 "Remove duplicate elements from LIST."
14859 (let (res)
14860 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14861 res))
14863 (defun org-delete-all (elts list)
14864 "Remove all elements in ELTS from LIST."
14865 (while elts
14866 (setq list (delete (pop elts) list)))
14867 list)
14869 (defun org-back-over-empty-lines ()
14870 "Move backwards over whitespace, to the beginning of the first empty line.
14871 Returns the number of empty lines passed."
14872 (let ((pos (point)))
14873 (skip-chars-backward " \t\n\r")
14874 (beginning-of-line 2)
14875 (goto-char (min (point) pos))
14876 (count-lines (point) pos)))
14878 (defun org-skip-whitespace ()
14879 (skip-chars-forward " \t\n\r"))
14881 (defun org-point-in-group (point group &optional context)
14882 "Check if POINT is in match-group GROUP.
14883 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14884 match. If the match group does ot exist or point is not inside it,
14885 return nil."
14886 (and (match-beginning group)
14887 (>= point (match-beginning group))
14888 (<= point (match-end group))
14889 (if context
14890 (list context (match-beginning group) (match-end group))
14891 t)))
14893 (defun org-switch-to-buffer-other-window (&rest args)
14894 "Switch to buffer in a second window on the current frame.
14895 In particular, do not allow pop-up frames."
14896 (let (pop-up-frames special-display-buffer-names special-display-regexps
14897 special-display-function)
14898 (apply 'switch-to-buffer-other-window args)))
14900 (defun org-combine-plists (&rest plists)
14901 "Create a single property list from all plists in PLISTS.
14902 The process starts by copying the first list, and then setting properties
14903 from the other lists. Settings in the last list are the most significant
14904 ones and overrule settings in the other lists."
14905 (let ((rtn (copy-sequence (pop plists)))
14906 p v ls)
14907 (while plists
14908 (setq ls (pop plists))
14909 (while ls
14910 (setq p (pop ls) v (pop ls))
14911 (setq rtn (plist-put rtn p v))))
14912 rtn))
14914 (defun org-move-line-down (arg)
14915 "Move the current line down. With prefix argument, move it past ARG lines."
14916 (interactive "p")
14917 (let ((col (current-column))
14918 beg end pos)
14919 (beginning-of-line 1) (setq beg (point))
14920 (beginning-of-line 2) (setq end (point))
14921 (beginning-of-line (+ 1 arg))
14922 (setq pos (move-marker (make-marker) (point)))
14923 (insert (delete-and-extract-region beg end))
14924 (goto-char pos)
14925 (org-move-to-column col)))
14927 (defun org-move-line-up (arg)
14928 "Move the current line up. With prefix argument, move it past ARG lines."
14929 (interactive "p")
14930 (let ((col (current-column))
14931 beg end pos)
14932 (beginning-of-line 1) (setq beg (point))
14933 (beginning-of-line 2) (setq end (point))
14934 (beginning-of-line (- arg))
14935 (setq pos (move-marker (make-marker) (point)))
14936 (insert (delete-and-extract-region beg end))
14937 (goto-char pos)
14938 (org-move-to-column col)))
14940 (defun org-replace-escapes (string table)
14941 "Replace %-escapes in STRING with values in TABLE.
14942 TABLE is an association list with keys like \"%a\" and string values.
14943 The sequences in STRING may contain normal field width and padding information,
14944 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14945 so values can contain further %-escapes if they are define later in TABLE."
14946 (let ((case-fold-search nil)
14947 e re rpl)
14948 (while (setq e (pop table))
14949 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14950 (while (string-match re string)
14951 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14952 (cdr e)))
14953 (setq string (replace-match rpl t t string))))
14954 string))
14957 (defun org-sublist (list start end)
14958 "Return a section of LIST, from START to END.
14959 Counting starts at 1."
14960 (let (rtn (c start))
14961 (setq list (nthcdr (1- start) list))
14962 (while (and list (<= c end))
14963 (push (pop list) rtn)
14964 (setq c (1+ c)))
14965 (nreverse rtn)))
14967 (defun org-find-base-buffer-visiting (file)
14968 "Like `find-buffer-visiting' but alway return the base buffer and
14969 not an indirect buffer."
14970 (let ((buf (find-buffer-visiting file)))
14971 (if buf
14972 (or (buffer-base-buffer buf) buf)
14973 nil)))
14975 (defun org-image-file-name-regexp (&optional extensions)
14976 "Return regexp matching the file names of images.
14977 If EXTENSIONS is given, only match these."
14978 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14979 (image-file-name-regexp)
14980 (let ((image-file-name-extensions
14981 (or extensions
14982 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14983 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14984 (concat "\\."
14985 (regexp-opt (nconc (mapcar 'upcase
14986 image-file-name-extensions)
14987 image-file-name-extensions)
14989 "\\'"))))
14991 (defun org-file-image-p (file &optional extensions)
14992 "Return non-nil if FILE is an image."
14993 (save-match-data
14994 (string-match (org-image-file-name-regexp extensions) file)))
14996 (defun org-get-cursor-date ()
14997 "Return the date at cursor in as a time.
14998 This works in the calendar and in the agenda, anywhere else it just
14999 returns the current time."
15000 (let (date day defd)
15001 (cond
15002 ((eq major-mode 'calendar-mode)
15003 (setq date (calendar-cursor-to-date)
15004 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15005 ((eq major-mode 'org-agenda-mode)
15006 (setq day (get-text-property (point) 'day))
15007 (if day
15008 (setq date (calendar-gregorian-from-absolute day)
15009 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15010 (nth 2 date))))))
15011 (or defd (current-time))))
15013 (defvar org-agenda-action-marker (make-marker)
15014 "Marker pointing to the entry for the next agenda action.")
15016 (defun org-mark-entry-for-agenda-action ()
15017 "Mark the current entry as target of an agenda action.
15018 Agenda actions are actions executed from the agenda with the key `k',
15019 which make use of the date at the cursor."
15020 (interactive)
15021 (move-marker org-agenda-action-marker
15022 (save-excursion (org-back-to-heading t) (point))
15023 (current-buffer))
15024 (message
15025 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15027 ;;; Paragraph filling stuff.
15028 ;; We want this to be just right, so use the full arsenal.
15030 (defun org-indent-line-function ()
15031 "Indent line like previous, but further if previous was headline or item."
15032 (interactive)
15033 (let* ((pos (point))
15034 (itemp (org-at-item-p))
15035 (org-drawer-regexp (or org-drawer-regexp "\000"))
15036 column bpos bcol tpos tcol bullet btype bullet-type)
15037 ;; Find the previous relevant line
15038 (beginning-of-line 1)
15039 (cond
15040 ((looking-at "#") (setq column 0))
15041 ((looking-at "\\*+ ") (setq column 0))
15042 ((and (looking-at "[ \t]*:END:")
15043 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15044 (save-excursion
15045 (goto-char (1- (match-beginning 1)))
15046 (setq column (current-column))))
15048 (beginning-of-line 0)
15049 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15050 (not (looking-at "[ \t]*:END:"))
15051 (not (looking-at org-drawer-regexp)))
15052 (beginning-of-line 0))
15053 (cond
15054 ((looking-at "\\*+[ \t]+")
15055 (if (not org-adapt-indentation)
15056 (setq column 0)
15057 (goto-char (match-end 0))
15058 (setq column (current-column))))
15059 ((looking-at org-drawer-regexp)
15060 (goto-char (1- (match-beginning 1)))
15061 (setq column (current-column)))
15062 ((looking-at "\\([ \t]*\\):END:")
15063 (goto-char (match-end 1))
15064 (setq column (current-column)))
15065 ((org-in-item-p)
15066 (org-beginning-of-item)
15067 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15068 (setq bpos (match-beginning 1) tpos (match-end 0)
15069 bcol (progn (goto-char bpos) (current-column))
15070 tcol (progn (goto-char tpos) (current-column))
15071 bullet (match-string 1)
15072 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15073 (if (> tcol (+ bcol org-description-max-indent))
15074 (setq tcol (+ bcol 5)))
15075 (if (not itemp)
15076 (setq column tcol)
15077 (goto-char pos)
15078 (beginning-of-line 1)
15079 (if (looking-at "\\S-")
15080 (progn
15081 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15082 (setq bullet (match-string 1)
15083 btype (if (string-match "[0-9]" bullet) "n" bullet))
15084 (setq column (if (equal btype bullet-type) bcol tcol)))
15085 (setq column (org-get-indentation)))))
15086 (t (setq column (org-get-indentation))))))
15087 (goto-char pos)
15088 (if (<= (current-column) (current-indentation))
15089 (org-indent-line-to column)
15090 (save-excursion (org-indent-line-to column)))
15091 (setq column (current-column))
15092 (beginning-of-line 1)
15093 (if (looking-at
15094 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15095 (replace-match (concat "\\1" (format org-property-format
15096 (match-string 2) (match-string 3)))
15097 t nil))
15098 (org-move-to-column column)))
15100 (defun org-set-autofill-regexps ()
15101 (interactive)
15102 ;; In the paragraph separator we include headlines, because filling
15103 ;; text in a line directly attached to a headline would otherwise
15104 ;; fill the headline as well.
15105 (org-set-local 'comment-start-skip "^#+[ \t]*")
15106 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15107 ;; The paragraph starter includes hand-formatted lists.
15108 (org-set-local 'paragraph-start
15109 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15110 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15111 ;; But only if the user has not turned off tables or fixed-width regions
15112 (org-set-local
15113 'auto-fill-inhibit-regexp
15114 (concat "\\*+ \\|#\\+"
15115 "\\|[ \t]*" org-keyword-time-regexp
15116 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15117 (concat
15118 "\\|[ \t]*["
15119 (if org-enable-table-editor "|" "")
15120 (if org-enable-fixed-width-editor ":" "")
15121 "]"))))
15122 ;; We use our own fill-paragraph function, to make sure that tables
15123 ;; and fixed-width regions are not wrapped. That function will pass
15124 ;; through to `fill-paragraph' when appropriate.
15125 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15126 ; Adaptive filling: To get full control, first make sure that
15127 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15128 (org-set-local 'adaptive-fill-regexp "\000")
15129 (org-set-local 'adaptive-fill-function
15130 'org-adaptive-fill-function)
15131 (org-set-local
15132 'align-mode-rules-list
15133 '((org-in-buffer-settings
15134 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15135 (modes . '(org-mode))))))
15137 (defun org-fill-paragraph (&optional justify)
15138 "Re-align a table, pass through to fill-paragraph if no table."
15139 (let ((table-p (org-at-table-p))
15140 (table.el-p (org-at-table.el-p)))
15141 (cond ((and (equal (char-after (point-at-bol)) ?*)
15142 (save-excursion (goto-char (point-at-bol))
15143 (looking-at outline-regexp)))
15144 t) ; skip headlines
15145 (table.el-p t) ; skip table.el tables
15146 (table-p (org-table-align) t) ; align org-mode tables
15147 (t nil)))) ; call paragraph-fill
15149 ;; For reference, this is the default value of adaptive-fill-regexp
15150 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15152 (defun org-adaptive-fill-function ()
15153 "Return a fill prefix for org-mode files.
15154 In particular, this makes sure hanging paragraphs for hand-formatted lists
15155 work correctly."
15156 (cond ((looking-at "#[ \t]+")
15157 (match-string 0))
15158 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15159 (save-excursion
15160 (if (> (match-end 1) (+ (match-beginning 1)
15161 org-description-max-indent))
15162 (goto-char (+ (match-beginning 1) 5))
15163 (goto-char (match-end 0)))
15164 (make-string (current-column) ?\ )))
15165 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15166 (save-excursion
15167 (goto-char (match-end 0))
15168 (make-string (current-column) ?\ )))
15169 (t nil)))
15171 ;;; Other stuff.
15173 (defun org-toggle-fixed-width-section (arg)
15174 "Toggle the fixed-width export.
15175 If there is no active region, the QUOTE keyword at the current headline is
15176 inserted or removed. When present, it causes the text between this headline
15177 and the next to be exported as fixed-width text, and unmodified.
15178 If there is an active region, this command adds or removes a colon as the
15179 first character of this line. If the first character of a line is a colon,
15180 this line is also exported in fixed-width font."
15181 (interactive "P")
15182 (let* ((cc 0)
15183 (regionp (org-region-active-p))
15184 (beg (if regionp (region-beginning) (point)))
15185 (end (if regionp (region-end)))
15186 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15187 (case-fold-search nil)
15188 (re "[ \t]*\\(:\\)")
15189 off)
15190 (if regionp
15191 (save-excursion
15192 (goto-char beg)
15193 (setq cc (current-column))
15194 (beginning-of-line 1)
15195 (setq off (looking-at re))
15196 (while (> nlines 0)
15197 (setq nlines (1- nlines))
15198 (beginning-of-line 1)
15199 (cond
15200 (arg
15201 (org-move-to-column cc t)
15202 (insert ":\n")
15203 (forward-line -1))
15204 ((and off (looking-at re))
15205 (replace-match "" t t nil 1))
15206 ((not off) (org-move-to-column cc t) (insert ":")))
15207 (forward-line 1)))
15208 (save-excursion
15209 (org-back-to-heading)
15210 (if (looking-at (concat outline-regexp
15211 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15212 (replace-match "" t t nil 1)
15213 (if (looking-at outline-regexp)
15214 (progn
15215 (goto-char (match-end 0))
15216 (insert org-quote-string " "))))))))
15218 ;;;; Functions extending outline functionality
15220 (defun org-beginning-of-line (&optional arg)
15221 "Go to the beginning of the current line. If that is invisible, continue
15222 to a visible line beginning. This makes the function of C-a more intuitive.
15223 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15224 first attempt, and only move to after the tags when the cursor is already
15225 beyond the end of the headline."
15226 (interactive "P")
15227 (let ((pos (point))
15228 (special (if (consp org-special-ctrl-a/e)
15229 (car org-special-ctrl-a/e)
15230 org-special-ctrl-a/e))
15231 refpos)
15232 (beginning-of-line 1)
15233 (if (and arg (fboundp 'move-beginning-of-line))
15234 (call-interactively 'move-beginning-of-line)
15235 (if (bobp)
15237 (backward-char 1)
15238 (if (org-invisible-p)
15239 (while (and (not (bobp)) (org-invisible-p))
15240 (backward-char 1)
15241 (beginning-of-line 1))
15242 (forward-char 1))))
15243 (when special
15244 (cond
15245 ((and (looking-at org-complex-heading-regexp)
15246 (= (char-after (match-end 1)) ?\ ))
15247 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15248 (point-at-eol)))
15249 (goto-char
15250 (if (eq special t)
15251 (cond ((> pos refpos) refpos)
15252 ((= pos (point)) refpos)
15253 (t (point)))
15254 (cond ((> pos (point)) (point))
15255 ((not (eq last-command this-command)) (point))
15256 (t refpos)))))
15257 ((org-at-item-p)
15258 (goto-char
15259 (if (eq special t)
15260 (cond ((> pos (match-end 4)) (match-end 4))
15261 ((= pos (point)) (match-end 4))
15262 (t (point)))
15263 (cond ((> pos (point)) (point))
15264 ((not (eq last-command this-command)) (point))
15265 (t (match-end 4))))))))
15266 (org-no-warnings
15267 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15269 (defun org-end-of-line (&optional arg)
15270 "Go to the end of the line.
15271 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15272 first attempt, and only move to after the tags when the cursor is already
15273 beyond the end of the headline."
15274 (interactive "P")
15275 (let ((special (if (consp org-special-ctrl-a/e)
15276 (cdr org-special-ctrl-a/e)
15277 org-special-ctrl-a/e)))
15278 (if (or (not special)
15279 (not (org-on-heading-p))
15280 arg)
15281 (call-interactively (if (fboundp 'move-end-of-line)
15282 'move-end-of-line
15283 'end-of-line))
15284 (let ((pos (point)))
15285 (beginning-of-line 1)
15286 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15287 (if (eq special t)
15288 (if (or (< pos (match-beginning 1))
15289 (= pos (match-end 0)))
15290 (goto-char (match-beginning 1))
15291 (goto-char (match-end 0)))
15292 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15293 (goto-char (match-end 0))
15294 (goto-char (match-beginning 1))))
15295 (call-interactively (if (fboundp 'move-end-of-line)
15296 'move-end-of-line
15297 'end-of-line)))))
15298 (org-no-warnings
15299 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15301 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15302 (define-key org-mode-map "\C-e" 'org-end-of-line)
15304 (defun org-kill-line (&optional arg)
15305 "Kill line, to tags or end of line."
15306 (interactive "P")
15307 (cond
15308 ((or (not org-special-ctrl-k)
15309 (bolp)
15310 (not (org-on-heading-p)))
15311 (call-interactively 'kill-line))
15312 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15313 (kill-region (point) (match-beginning 1))
15314 (org-set-tags nil t))
15315 (t (kill-region (point) (point-at-eol)))))
15317 (define-key org-mode-map "\C-k" 'org-kill-line)
15319 (defun org-yank (&optional arg)
15320 "Yank. If the kill is a subtree, treat it specially.
15321 This command will look at the current kill and check if is a single
15322 subtree, or a series of subtrees[1]. If it passes the test, and if the
15323 cursor is at the beginning of a line or after the stars of a currently
15324 empty headline, then the yank is handled specially. How exactly depends
15325 on the value of the following variables, both set by default.
15327 org-yank-folded-subtrees
15328 When set, the subtree(s) will be folded after insertion, but only
15329 if doing so would now swallow text after the yanked text.
15331 org-yank-adjusted-subtrees
15332 When set, the subtree will be promoted or demoted in order to
15333 fit into the local outline tree structure, which means that the level
15334 will be adjusted so that it becomes the smaller one of the two
15335 *visible* surrounding headings.
15337 Any prefix to this command will cause `yank' to be called directly with
15338 no special treatment. In particular, a simple `C-u' prefix will just
15339 plainly yank the text as it is.
15341 \[1] Basically, the test checks if the first non-white line is a heading
15342 and if there are no other headings with fewer stars."
15343 (interactive "P")
15344 (setq this-command 'yank)
15345 (if arg
15346 (call-interactively 'yank)
15347 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15348 (and (org-kill-is-subtree-p)
15349 (or (bolp)
15350 (and (looking-at "[ \t]*$")
15351 (string-match
15352 "\\`\\*+\\'"
15353 (buffer-substring (point-at-bol) (point)))))))
15354 swallowp)
15355 (cond
15356 ((and subtreep org-yank-folded-subtrees)
15357 (let ((beg (point))
15358 end)
15359 (if (and subtreep org-yank-adjusted-subtrees)
15360 (org-paste-subtree nil nil 'for-yank)
15361 (call-interactively 'yank))
15362 (setq end (point))
15363 (goto-char beg)
15364 (when (and (bolp) subtreep
15365 (not (setq swallowp
15366 (org-yank-folding-would-swallow-text beg end))))
15367 (or (looking-at outline-regexp)
15368 (re-search-forward (concat "^" outline-regexp) end t))
15369 (while (and (< (point) end) (looking-at outline-regexp))
15370 (hide-subtree)
15371 (org-cycle-show-empty-lines 'folded)
15372 (condition-case nil
15373 (outline-forward-same-level 1)
15374 (error (goto-char end)))))
15375 (when swallowp
15376 (message
15377 "Yanked text not folded because that would swallow text"))
15378 (goto-char end)
15379 (skip-chars-forward " \t\n\r")
15380 (beginning-of-line 1)
15381 (push-mark beg 'nomsg)))
15382 ((and subtreep org-yank-adjusted-subtrees)
15383 (let ((beg (point-at-bol)))
15384 (org-paste-subtree nil nil 'for-yank)
15385 (push-mark beg 'nomsg)))
15387 (call-interactively 'yank))))))
15389 (defun org-yank-folding-would-swallow-text (beg end)
15390 "Would hide-subtree at BEG swallow any text after END?"
15391 (let (level)
15392 (save-excursion
15393 (goto-char beg)
15394 (when (or (looking-at outline-regexp)
15395 (re-search-forward (concat "^" outline-regexp) end t))
15396 (setq level (org-outline-level)))
15397 (goto-char end)
15398 (skip-chars-forward " \t\r\n\v\f")
15399 (if (or (eobp)
15400 (and (bolp) (looking-at org-outline-regexp)
15401 (<= (org-outline-level) level)))
15402 nil ; Nothing would be swallowed
15403 t)))) ; something would swallow
15405 (define-key org-mode-map "\C-y" 'org-yank)
15407 (defun org-invisible-p ()
15408 "Check if point is at a character currently not visible."
15409 ;; Early versions of noutline don't have `outline-invisible-p'.
15410 (if (fboundp 'outline-invisible-p)
15411 (outline-invisible-p)
15412 (get-char-property (point) 'invisible)))
15414 (defun org-invisible-p2 ()
15415 "Check if point is at a character currently not visible."
15416 (save-excursion
15417 (if (and (eolp) (not (bobp))) (backward-char 1))
15418 ;; Early versions of noutline don't have `outline-invisible-p'.
15419 (if (fboundp 'outline-invisible-p)
15420 (outline-invisible-p)
15421 (get-char-property (point) 'invisible))))
15423 (defun org-back-to-heading (&optional invisible-ok)
15424 "Call `outline-back-to-heading', but provide a better error message."
15425 (condition-case nil
15426 (outline-back-to-heading invisible-ok)
15427 (error (error "Before first headline at position %d in buffer %s"
15428 (point) (current-buffer)))))
15430 (defun org-before-first-heading-p ()
15431 "Before first heading?"
15432 (save-excursion
15433 (null (re-search-backward "^\\*+ " nil t))))
15435 (defalias 'org-on-heading-p 'outline-on-heading-p)
15436 (defalias 'org-at-heading-p 'outline-on-heading-p)
15437 (defun org-at-heading-or-item-p ()
15438 (or (org-on-heading-p) (org-at-item-p)))
15440 (defun org-on-target-p ()
15441 (or (org-in-regexp org-radio-target-regexp)
15442 (org-in-regexp org-target-regexp)))
15444 (defun org-up-heading-all (arg)
15445 "Move to the heading line of which the present line is a subheading.
15446 This function considers both visible and invisible heading lines.
15447 With argument, move up ARG levels."
15448 (if (fboundp 'outline-up-heading-all)
15449 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15450 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15452 (defun org-up-heading-safe ()
15453 "Move to the heading line of which the present line is a subheading.
15454 This version will not throw an error. It will return the level of the
15455 headline found, or nil if no higher level is found."
15456 (let (start-level re)
15457 (org-back-to-heading t)
15458 (setq start-level (funcall outline-level))
15459 (if (equal start-level 1)
15461 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15462 (if (re-search-backward re nil t)
15463 (funcall outline-level)))))
15465 (defun org-first-sibling-p ()
15466 "Is this heading the first child of its parents?"
15467 (interactive)
15468 (let ((re (concat "^" outline-regexp))
15469 level l)
15470 (unless (org-at-heading-p t)
15471 (error "Not at a heading"))
15472 (setq level (funcall outline-level))
15473 (save-excursion
15474 (if (not (re-search-backward re nil t))
15476 (setq l (funcall outline-level))
15477 (< l level)))))
15479 (defun org-goto-sibling (&optional previous)
15480 "Goto the next sibling, even if it is invisible.
15481 When PREVIOUS is set, go to the previous sibling instead. Returns t
15482 when a sibling was found. When none is found, return nil and don't
15483 move point."
15484 (let ((fun (if previous 're-search-backward 're-search-forward))
15485 (pos (point))
15486 (re (concat "^" outline-regexp))
15487 level l)
15488 (when (condition-case nil (org-back-to-heading t) (error nil))
15489 (setq level (funcall outline-level))
15490 (catch 'exit
15491 (or previous (forward-char 1))
15492 (while (funcall fun re nil t)
15493 (setq l (funcall outline-level))
15494 (when (< l level) (goto-char pos) (throw 'exit nil))
15495 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15496 (goto-char pos)
15497 nil))))
15499 (defun org-show-siblings ()
15500 "Show all siblings of the current headline."
15501 (save-excursion
15502 (while (org-goto-sibling) (org-flag-heading nil)))
15503 (save-excursion
15504 (while (org-goto-sibling 'previous)
15505 (org-flag-heading nil))))
15507 (defun org-show-hidden-entry ()
15508 "Show an entry where even the heading is hidden."
15509 (save-excursion
15510 (org-show-entry)))
15512 (defun org-flag-heading (flag &optional entry)
15513 "Flag the current heading. FLAG non-nil means make invisible.
15514 When ENTRY is non-nil, show the entire entry."
15515 (save-excursion
15516 (org-back-to-heading t)
15517 ;; Check if we should show the entire entry
15518 (if entry
15519 (progn
15520 (org-show-entry)
15521 (save-excursion
15522 (and (outline-next-heading)
15523 (org-flag-heading nil))))
15524 (outline-flag-region (max (point-min) (1- (point)))
15525 (save-excursion (outline-end-of-heading) (point))
15526 flag))))
15528 (defun org-forward-same-level (arg)
15529 "Move forward to the ARG'th subheading at same level as this one.
15530 Stop at the first and last subheadings of a superior heading.
15531 This is like outline-forward-same-level, but invisible headings are ok."
15532 (interactive "p")
15533 (org-back-to-heading t)
15534 (while (> arg 0)
15535 (let ((point-to-move-to (save-excursion
15536 (org-get-next-sibling))))
15537 (if point-to-move-to
15538 (progn
15539 (goto-char point-to-move-to)
15540 (setq arg (1- arg)))
15541 (progn
15542 (setq arg 0)
15543 (error "No following same-level heading"))))))
15545 (defun org-get-next-sibling ()
15546 "Move to next heading of the same level, and return point.
15547 If there is no such heading, return nil.
15548 This is like outline-next-sibling, but invisible headings are ok."
15549 (let ((level (funcall outline-level)))
15550 (outline-next-heading)
15551 (while (and (not (eobp)) (> (funcall outline-level) level))
15552 (outline-next-heading))
15553 (if (or (eobp) (< (funcall outline-level) level))
15555 (point))))
15557 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15558 ;; This is an exact copy of the original function, but it uses
15559 ;; `org-back-to-heading', to make it work also in invisible
15560 ;; trees. And is uses an invisible-OK argument.
15561 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15562 (org-back-to-heading invisible-OK)
15563 (let ((first t)
15564 (level (funcall outline-level)))
15565 (while (and (not (eobp))
15566 (or first (> (funcall outline-level) level)))
15567 (setq first nil)
15568 (outline-next-heading))
15569 (unless to-heading
15570 (if (memq (preceding-char) '(?\n ?\^M))
15571 (progn
15572 ;; Go to end of line before heading
15573 (forward-char -1)
15574 (if (memq (preceding-char) '(?\n ?\^M))
15575 ;; leave blank line before heading
15576 (forward-char -1))))))
15577 (point))
15579 (defun org-show-subtree ()
15580 "Show everything after this heading at deeper levels."
15581 (outline-flag-region
15582 (point)
15583 (save-excursion
15584 (outline-end-of-subtree) (outline-next-heading) (point))
15585 nil))
15587 (defun org-show-entry ()
15588 "Show the body directly following this heading.
15589 Show the heading too, if it is currently invisible."
15590 (interactive)
15591 (save-excursion
15592 (condition-case nil
15593 (progn
15594 (org-back-to-heading t)
15595 (outline-flag-region
15596 (max (point-min) (1- (point)))
15597 (save-excursion
15598 (if (re-search-forward
15599 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15600 (match-beginning 1)
15601 (point-max)))
15602 nil))
15603 (error nil))))
15605 (defun org-make-options-regexp (kwds &optional extra)
15606 "Make a regular expression for keyword lines."
15607 (concat
15609 "#?[ \t]*\\+\\("
15610 (mapconcat 'regexp-quote kwds "\\|")
15611 (if extra (concat "\\|" extra))
15612 "\\):[ \t]*"
15613 "\\(.+\\)"))
15615 ;; Make isearch reveal the necessary context
15616 (defun org-isearch-end ()
15617 "Reveal context after isearch exits."
15618 (when isearch-success ; only if search was successful
15619 (if (featurep 'xemacs)
15620 ;; Under XEmacs, the hook is run in the correct place,
15621 ;; we directly show the context.
15622 (org-show-context 'isearch)
15623 ;; In Emacs the hook runs *before* restoring the overlays.
15624 ;; So we have to use a one-time post-command-hook to do this.
15625 ;; (Emacs 22 has a special variable, see function `org-mode')
15626 (unless (and (boundp 'isearch-mode-end-hook-quit)
15627 isearch-mode-end-hook-quit)
15628 ;; Only when the isearch was not quitted.
15629 (org-add-hook 'post-command-hook 'org-isearch-post-command
15630 'append 'local)))))
15632 (defun org-isearch-post-command ()
15633 "Remove self from hook, and show context."
15634 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15635 (org-show-context 'isearch))
15638 ;;;; Integration with and fixes for other packages
15640 ;;; Imenu support
15642 (defvar org-imenu-markers nil
15643 "All markers currently used by Imenu.")
15644 (make-variable-buffer-local 'org-imenu-markers)
15646 (defun org-imenu-new-marker (&optional pos)
15647 "Return a new marker for use by Imenu, and remember the marker."
15648 (let ((m (make-marker)))
15649 (move-marker m (or pos (point)))
15650 (push m org-imenu-markers)
15653 (defun org-imenu-get-tree ()
15654 "Produce the index for Imenu."
15655 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15656 (setq org-imenu-markers nil)
15657 (let* ((n org-imenu-depth)
15658 (re (concat "^" outline-regexp))
15659 (subs (make-vector (1+ n) nil))
15660 (last-level 0)
15661 m level head)
15662 (save-excursion
15663 (save-restriction
15664 (widen)
15665 (goto-char (point-max))
15666 (while (re-search-backward re nil t)
15667 (setq level (org-reduced-level (funcall outline-level)))
15668 (when (<= level n)
15669 (looking-at org-complex-heading-regexp)
15670 (setq head (org-link-display-format
15671 (org-match-string-no-properties 4))
15672 m (org-imenu-new-marker))
15673 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15674 (if (>= level last-level)
15675 (push (cons head m) (aref subs level))
15676 (push (cons head (aref subs (1+ level))) (aref subs level))
15677 (loop for i from (1+ level) to n do (aset subs i nil)))
15678 (setq last-level level)))))
15679 (aref subs 1)))
15681 (eval-after-load "imenu"
15682 '(progn
15683 (add-hook 'imenu-after-jump-hook
15684 (lambda ()
15685 (if (eq major-mode 'org-mode)
15686 (org-show-context 'org-goto))))))
15688 (defun org-link-display-format (link)
15689 "Replace a link with either the description, or the link target
15690 if no description is present"
15691 (save-match-data
15692 (if (string-match org-bracket-link-analytic-regexp link)
15693 (replace-match (or (match-string 5 link)
15694 (concat (match-string 1 link)
15695 (match-string 3 link)))
15696 nil nil link)
15697 link)))
15699 ;; Speedbar support
15701 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15702 "Overlay marking the agenda restriction line in speedbar.")
15703 (org-overlay-put org-speedbar-restriction-lock-overlay
15704 'face 'org-agenda-restriction-lock)
15705 (org-overlay-put org-speedbar-restriction-lock-overlay
15706 'help-echo "Agendas are currently limited to this item.")
15707 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15709 (defun org-speedbar-set-agenda-restriction ()
15710 "Restrict future agenda commands to the location at point in speedbar.
15711 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15712 (interactive)
15713 (require 'org-agenda)
15714 (let (p m tp np dir txt)
15715 (cond
15716 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15717 'org-imenu t))
15718 (setq m (get-text-property p 'org-imenu-marker))
15719 (save-excursion
15720 (save-restriction
15721 (set-buffer (marker-buffer m))
15722 (goto-char m)
15723 (org-agenda-set-restriction-lock 'subtree))))
15724 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15725 'speedbar-function 'speedbar-find-file))
15726 (setq tp (previous-single-property-change
15727 (1+ p) 'speedbar-function)
15728 np (next-single-property-change
15729 tp 'speedbar-function)
15730 dir (speedbar-line-directory)
15731 txt (buffer-substring-no-properties (or tp (point-min))
15732 (or np (point-max))))
15733 (save-excursion
15734 (save-restriction
15735 (set-buffer (find-file-noselect
15736 (let ((default-directory dir))
15737 (expand-file-name txt))))
15738 (unless (org-mode-p)
15739 (error "Cannot restrict to non-Org-mode file"))
15740 (org-agenda-set-restriction-lock 'file))))
15741 (t (error "Don't know how to restrict Org-mode's agenda")))
15742 (org-move-overlay org-speedbar-restriction-lock-overlay
15743 (point-at-bol) (point-at-eol))
15744 (setq current-prefix-arg nil)
15745 (org-agenda-maybe-redo)))
15747 (eval-after-load "speedbar"
15748 '(progn
15749 (speedbar-add-supported-extension ".org")
15750 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15751 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15752 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15753 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15754 (add-hook 'speedbar-visiting-tag-hook
15755 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15758 ;;; Fixes and Hacks for problems with other packages
15760 ;; Make flyspell not check words in links, to not mess up our keymap
15761 (defun org-mode-flyspell-verify ()
15762 "Don't let flyspell put overlays at active buttons."
15763 (not (get-text-property (point) 'keymap)))
15765 ;; Make `bookmark-jump' show the jump location if it was hidden.
15766 (eval-after-load "bookmark"
15767 '(if (boundp 'bookmark-after-jump-hook)
15768 ;; We can use the hook
15769 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15770 ;; Hook not available, use advice
15771 (defadvice bookmark-jump (after org-make-visible activate)
15772 "Make the position visible."
15773 (org-bookmark-jump-unhide))))
15775 ;; Make sure saveplace show the location if it was hidden
15776 (eval-after-load "saveplace"
15777 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15778 "Make the position visible."
15779 (org-bookmark-jump-unhide)))
15781 (defun org-bookmark-jump-unhide ()
15782 "Unhide the current position, to show the bookmark location."
15783 (and (org-mode-p)
15784 (or (org-invisible-p)
15785 (save-excursion (goto-char (max (point-min) (1- (point))))
15786 (org-invisible-p)))
15787 (org-show-context 'bookmark-jump)))
15789 ;; Make session.el ignore our circular variable
15790 (eval-after-load "session"
15791 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15793 ;;;; Experimental code
15795 (defun org-closed-in-range ()
15796 "Sparse tree of items closed in a certain time range.
15797 Still experimental, may disappear in the future."
15798 (interactive)
15799 ;; Get the time interval from the user.
15800 (let* ((time1 (time-to-seconds
15801 (org-read-date nil 'to-time nil "Starting date: ")))
15802 (time2 (time-to-seconds
15803 (org-read-date nil 'to-time nil "End date:")))
15804 ;; callback function
15805 (callback (lambda ()
15806 (let ((time
15807 (time-to-seconds
15808 (apply 'encode-time
15809 (org-parse-time-string
15810 (match-string 1))))))
15811 ;; check if time in interval
15812 (and (>= time time1) (<= time time2))))))
15813 ;; make tree, check each match with the callback
15814 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15817 ;;;; Finish up
15819 (provide 'org)
15821 (run-hooks 'org-load-hook)
15823 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15825 ;;; org.el ends here