Bug fix
[org-mode.git] / lisp / org.el
blobc7b6152a23914fefe04d7c8cb7d712057259ad99
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.23trans
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.23trans"
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 depend: TODO dependencies for Org-mode" org-depend)
186 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
187 (const :tag "C eval: Include command output as text" org-eval)
188 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
189 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
190 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
191 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
192 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
193 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
194 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
195 (const :tag "C mtags: Support for muse-like tags" org-mtags)
196 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
197 (const :tag "C R: Computation using the R language" org-R)
198 (const :tag "C registry: A registry for Org links" org-registry)
199 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
200 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
201 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
202 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
203 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
205 (defcustom org-support-shift-select nil
206 "Non-nil means, make shift-cursor commands select text when possible.
208 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
209 selecting a region, or enlarge thusly regions started in this way.
210 In Org-mode, in special contexts, these same keys are used for other
211 purposes, important enough to compete with shift selection. Org tries
212 to balance these needs by supporting `shift-select-mode' outside these
213 special contexts, under control of this variable.
215 The default of this variable is nil, to avoid confusing behavior. Shifted
216 cursor keys will then execute Org commands in the following contexts:
217 - on a headline, changing TODO state (left/right) and priority (up/down)
218 - on a time stamp, changing the time
219 - in a plain list item, changing the bullet type
220 - in a property definition line, switching between allowed values
221 - in the BEGIN line of a clock table (changing the time block).
222 Outside these contexts, the commands will throw an error.
224 When this variable is t and the cursor is not in a special context,
225 Org-mode will support shift-selection for making and enlarging regions.
226 To make this more effective, the bullet cycling will no longer happen
227 anywhere in an item line, but only if the cursor is exactly on the bullet.
229 If you set this variable to the symbol `always', then the keys
230 will not be special in headlines, property lines, and item lines, to make
231 shift selection work there as well. If this is what you want, you can
232 use the following alternative commands: `C-c C-t' and `C-c ,' to
233 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
234 TODO sets, `C-c -' to cycle item bullet types, and properties can be
235 edited by hand or in column view.
237 However, when the cursor is on a timestamp, shift-cursor commands
238 will still edit the time stamp - this is just too good to give up.
240 XEmacs user should have this variable set to nil, because shift-select-mode
241 is Emacs 23 only."
242 :group 'org
243 :type '(choice
244 (const :tag "Never" nil)
245 (const :tag "When outside special context" t)
246 (const :tag "Everywhere except timestamps" always)))
248 (defgroup org-startup nil
249 "Options concerning startup of Org-mode."
250 :tag "Org Startup"
251 :group 'org)
253 (defcustom org-startup-folded t
254 "Non-nil means, entering Org-mode will switch to OVERVIEW.
255 This can also be configured on a per-file basis by adding one of
256 the following lines anywhere in the buffer:
258 #+STARTUP: fold
259 #+STARTUP: nofold
260 #+STARTUP: content"
261 :group 'org-startup
262 :type '(choice
263 (const :tag "nofold: show all" nil)
264 (const :tag "fold: overview" t)
265 (const :tag "content: all headlines" content)))
267 (defcustom org-startup-truncated t
268 "Non-nil means, entering Org-mode will set `truncate-lines'.
269 This is useful since some lines containing links can be very long and
270 uninteresting. Also tables look terrible when wrapped."
271 :group 'org-startup
272 :type 'boolean)
274 (defcustom org-startup-align-all-tables nil
275 "Non-nil means, align all tables when visiting a file.
276 This is useful when the column width in tables is forced with <N> cookies
277 in table fields. Such tables will look correct only after the first re-align.
278 This can also be configured on a per-file basis by adding one of
279 the following lines anywhere in the buffer:
280 #+STARTUP: align
281 #+STARTUP: noalign"
282 :group 'org-startup
283 :type 'boolean)
285 (defcustom org-insert-mode-line-in-empty-file nil
286 "Non-nil means insert the first line setting Org-mode in empty files.
287 When the function `org-mode' is called interactively in an empty file, this
288 normally means that the file name does not automatically trigger Org-mode.
289 To ensure that the file will always be in Org-mode in the future, a
290 line enforcing Org-mode will be inserted into the buffer, if this option
291 has been set."
292 :group 'org-startup
293 :type 'boolean)
295 (defcustom org-replace-disputed-keys nil
296 "Non-nil means use alternative key bindings for some keys.
297 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
298 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
299 If you want to use Org-mode together with one of these other modes,
300 or more generally if you would like to move some Org-mode commands to
301 other keys, set this variable and configure the keys with the variable
302 `org-disputed-keys'.
304 This option is only relevant at load-time of Org-mode, and must be set
305 *before* org.el is loaded. Changing it requires a restart of Emacs to
306 become effective."
307 :group 'org-startup
308 :type 'boolean)
310 (defcustom org-use-extra-keys nil
311 "Non-nil means use extra key sequence definitions for certain
312 commands. This happens automatically if you run XEmacs or if
313 window-system is nil. This variable lets you do the same
314 manually. You must set it before loading org.
316 Example: on Carbon Emacs 22 running graphically, with an external
317 keyboard on a Powerbook, the default way of setting M-left might
318 not work for either Alt or ESC. Setting this variable will make
319 it work for ESC."
320 :group 'org-startup
321 :type 'boolean)
323 (if (fboundp 'defvaralias)
324 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
326 (defcustom org-disputed-keys
327 '(([(shift up)] . [(meta p)])
328 ([(shift down)] . [(meta n)])
329 ([(shift left)] . [(meta -)])
330 ([(shift right)] . [(meta +)])
331 ([(control shift right)] . [(meta shift +)])
332 ([(control shift left)] . [(meta shift -)]))
333 "Keys for which Org-mode and other modes compete.
334 This is an alist, cars are the default keys, second element specifies
335 the alternative to use when `org-replace-disputed-keys' is t.
337 Keys can be specified in any syntax supported by `define-key'.
338 The value of this option takes effect only at Org-mode's startup,
339 therefore you'll have to restart Emacs to apply it after changing."
340 :group 'org-startup
341 :type 'alist)
343 (defun org-key (key)
344 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
345 Or return the original if not disputed."
346 (if org-replace-disputed-keys
347 (let* ((nkey (key-description key))
348 (x (org-find-if (lambda (x)
349 (equal (key-description (car x)) nkey))
350 org-disputed-keys)))
351 (if x (cdr x) key))
352 key))
354 (defun org-find-if (predicate seq)
355 (catch 'exit
356 (while seq
357 (if (funcall predicate (car seq))
358 (throw 'exit (car seq))
359 (pop seq)))))
361 (defun org-defkey (keymap key def)
362 "Define a key, possibly translated, as returned by `org-key'."
363 (define-key keymap (org-key key) def))
365 (defcustom org-ellipsis nil
366 "The ellipsis to use in the Org-mode outline.
367 When nil, just use the standard three dots. When a string, use that instead,
368 When a face, use the standard 3 dots, but with the specified face.
369 The change affects only Org-mode (which will then use its own display table).
370 Changing this requires executing `M-x org-mode' in a buffer to become
371 effective."
372 :group 'org-startup
373 :type '(choice (const :tag "Default" nil)
374 (face :tag "Face" :value org-warning)
375 (string :tag "String" :value "...#")))
377 (defvar org-display-table nil
378 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
380 (defgroup org-keywords nil
381 "Keywords in Org-mode."
382 :tag "Org Keywords"
383 :group 'org)
385 (defcustom org-deadline-string "DEADLINE:"
386 "String to mark deadline entries.
387 A deadline is this string, followed by a time stamp. Should be a word,
388 terminated by a colon. You can insert a schedule keyword and
389 a timestamp with \\[org-deadline].
390 Changes become only effective after restarting Emacs."
391 :group 'org-keywords
392 :type 'string)
394 (defcustom org-scheduled-string "SCHEDULED:"
395 "String to mark scheduled TODO entries.
396 A schedule is this string, followed by a time stamp. Should be a word,
397 terminated by a colon. You can insert a schedule keyword and
398 a timestamp with \\[org-schedule].
399 Changes become only effective after restarting Emacs."
400 :group 'org-keywords
401 :type 'string)
403 (defcustom org-closed-string "CLOSED:"
404 "String used as the prefix for timestamps logging closing a TODO entry."
405 :group 'org-keywords
406 :type 'string)
408 (defcustom org-clock-string "CLOCK:"
409 "String used as prefix for timestamps clocking work hours on an item."
410 :group 'org-keywords
411 :type 'string)
413 (defcustom org-comment-string "COMMENT"
414 "Entries starting with this keyword will never be exported.
415 An entry can be toggled between COMMENT and normal with
416 \\[org-toggle-comment].
417 Changes become only effective after restarting Emacs."
418 :group 'org-keywords
419 :type 'string)
421 (defcustom org-quote-string "QUOTE"
422 "Entries starting with this keyword will be exported in fixed-width font.
423 Quoting applies only to the text in the entry following the headline, and does
424 not extend beyond the next headline, even if that is lower level.
425 An entry can be toggled between QUOTE and normal with
426 \\[org-toggle-fixed-width-section]."
427 :group 'org-keywords
428 :type 'string)
430 (defconst org-repeat-re
431 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
432 "Regular expression for specifying repeated events.
433 After a match, group 1 contains the repeat expression.")
435 (defgroup org-structure nil
436 "Options concerning the general structure of Org-mode files."
437 :tag "Org Structure"
438 :group 'org)
440 (defgroup org-reveal-location nil
441 "Options about how to make context of a location visible."
442 :tag "Org Reveal Location"
443 :group 'org-structure)
445 (defconst org-context-choice
446 '(choice
447 (const :tag "Always" t)
448 (const :tag "Never" nil)
449 (repeat :greedy t :tag "Individual contexts"
450 (cons
451 (choice :tag "Context"
452 (const agenda)
453 (const org-goto)
454 (const occur-tree)
455 (const tags-tree)
456 (const link-search)
457 (const mark-goto)
458 (const bookmark-jump)
459 (const isearch)
460 (const default))
461 (boolean))))
462 "Contexts for the reveal options.")
464 (defcustom org-show-hierarchy-above '((default . t))
465 "Non-nil means, show full hierarchy when revealing a location.
466 Org-mode often shows locations in an org-mode file which might have
467 been invisible before. When this is set, the hierarchy of headings
468 above the exposed location is shown.
469 Turning this off for example for sparse trees makes them very compact.
470 Instead of t, this can also be an alist specifying this option for different
471 contexts. Valid contexts are
472 agenda when exposing an entry from the agenda
473 org-goto when using the command `org-goto' on key C-c C-j
474 occur-tree when using the command `org-occur' on key C-c /
475 tags-tree when constructing a sparse tree based on tags matches
476 link-search when exposing search matches associated with a link
477 mark-goto when exposing the jump goal of a mark
478 bookmark-jump when exposing a bookmark location
479 isearch when exiting from an incremental search
480 default default for all contexts not set explicitly"
481 :group 'org-reveal-location
482 :type org-context-choice)
484 (defcustom org-show-following-heading '((default . nil))
485 "Non-nil means, show following heading when revealing a location.
486 Org-mode often shows locations in an org-mode file which might have
487 been invisible before. When this is set, the heading following the
488 match is shown.
489 Turning this off for example for sparse trees makes them very compact,
490 but makes it harder to edit the location of the match. In such a case,
491 use the command \\[org-reveal] to show more context.
492 Instead of t, this can also be an alist specifying this option for different
493 contexts. See `org-show-hierarchy-above' for valid contexts."
494 :group 'org-reveal-location
495 :type org-context-choice)
497 (defcustom org-show-siblings '((default . nil) (isearch t))
498 "Non-nil means, show all sibling heading when revealing a location.
499 Org-mode often shows locations in an org-mode file which might have
500 been invisible before. When this is set, the sibling of the current entry
501 heading are all made visible. If `org-show-hierarchy-above' is t,
502 the same happens on each level of the hierarchy above the current entry.
504 By default this is on for the isearch context, off for all other contexts.
505 Turning this off for example for sparse trees makes them very compact,
506 but makes it harder to edit the location of the match. In such a case,
507 use the command \\[org-reveal] to show more context.
508 Instead of t, this can also be an alist specifying this option for different
509 contexts. See `org-show-hierarchy-above' for valid contexts."
510 :group 'org-reveal-location
511 :type org-context-choice)
513 (defcustom org-show-entry-below '((default . nil))
514 "Non-nil means, show the entry below a headline when revealing a location.
515 Org-mode often shows locations in an org-mode file which might have
516 been invisible before. When this is set, the text below the headline that is
517 exposed is also shown.
519 By default this is off for all contexts.
520 Instead of t, this can also be an alist specifying this option for different
521 contexts. See `org-show-hierarchy-above' for valid contexts."
522 :group 'org-reveal-location
523 :type org-context-choice)
525 (defcustom org-indirect-buffer-display 'other-window
526 "How should indirect tree buffers be displayed?
527 This applies to indirect buffers created with the commands
528 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
529 Valid values are:
530 current-window Display in the current window
531 other-window Just display in another window.
532 dedicated-frame Create one new frame, and re-use it each time.
533 new-frame Make a new frame each time. Note that in this case
534 previously-made indirect buffers are kept, and you need to
535 kill these buffers yourself."
536 :group 'org-structure
537 :group 'org-agenda-windows
538 :type '(choice
539 (const :tag "In current window" current-window)
540 (const :tag "In current frame, other window" other-window)
541 (const :tag "Each time a new frame" new-frame)
542 (const :tag "One dedicated frame" dedicated-frame)))
544 (defgroup org-cycle nil
545 "Options concerning visibility cycling in Org-mode."
546 :tag "Org Cycle"
547 :group 'org-structure)
549 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
550 "Names of drawers. Drawers are not opened by cycling on the headline above.
551 Drawers only open with a TAB on the drawer line itself. A drawer looks like
552 this:
553 :DRAWERNAME:
554 .....
555 :END:
556 The drawer \"PROPERTIES\" is special for capturing properties through
557 the property API.
559 Drawers can be defined on the per-file basis with a line like:
561 #+DRAWERS: HIDDEN STATE PROPERTIES"
562 :group 'org-structure
563 :type '(repeat (string :tag "Drawer Name")))
565 (defcustom org-cycle-global-at-bob nil
566 "Cycle globally if cursor is at beginning of buffer and not at a headline.
567 This makes it possible to do global cycling without having to use S-TAB or
568 C-u TAB. For this special case to work, the first line of the buffer
569 must not be a headline - it may be empty or some other text. When used in
570 this way, `org-cycle-hook' is disables temporarily, to make sure the
571 cursor stays at the beginning of the buffer.
572 When this option is nil, don't do anything special at the beginning
573 of the buffer."
574 :group 'org-cycle
575 :type 'boolean)
577 (defcustom org-cycle-emulate-tab t
578 "Where should `org-cycle' emulate TAB.
579 nil Never
580 white Only in completely white lines
581 whitestart Only at the beginning of lines, before the first non-white char
582 t Everywhere except in headlines
583 exc-hl-bol Everywhere except at the start of a headline
584 If TAB is used in a place where it does not emulate TAB, the current subtree
585 visibility is cycled."
586 :group 'org-cycle
587 :type '(choice (const :tag "Never" nil)
588 (const :tag "Only in completely white lines" white)
589 (const :tag "Before first char in a line" whitestart)
590 (const :tag "Everywhere except in headlines" t)
591 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
594 (defcustom org-cycle-separator-lines 2
595 "Number of empty lines needed to keep an empty line between collapsed trees.
596 If you leave an empty line between the end of a subtree and the following
597 headline, this empty line is hidden when the subtree is folded.
598 Org-mode will leave (exactly) one empty line visible if the number of
599 empty lines is equal or larger to the number given in this variable.
600 So the default 2 means, at least 2 empty lines after the end of a subtree
601 are needed to produce free space between a collapsed subtree and the
602 following headline.
604 Special case: when 0, never leave empty lines in collapsed view."
605 :group 'org-cycle
606 :type 'integer)
607 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
609 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
610 org-cycle-hide-drawers
611 org-cycle-show-empty-lines
612 org-optimize-window-after-visibility-change)
613 "Hook that is run after `org-cycle' has changed the buffer visibility.
614 The function(s) in this hook must accept a single argument which indicates
615 the new state that was set by the most recent `org-cycle' command. The
616 argument is a symbol. After a global state change, it can have the values
617 `overview', `content', or `all'. After a local state change, it can have
618 the values `folded', `children', or `subtree'."
619 :group 'org-cycle
620 :type 'hook)
622 (defgroup org-edit-structure nil
623 "Options concerning structure editing in Org-mode."
624 :tag "Org Edit Structure"
625 :group 'org-structure)
627 (defcustom org-odd-levels-only nil
628 "Non-nil means, skip even levels and only use odd levels for the outline.
629 This has the effect that two stars are being added/taken away in
630 promotion/demotion commands. It also influences how levels are
631 handled by the exporters.
632 Changing it requires restart of `font-lock-mode' to become effective
633 for fontification also in regions already fontified.
634 You may also set this on a per-file basis by adding one of the following
635 lines to the buffer:
637 #+STARTUP: odd
638 #+STARTUP: oddeven"
639 :group 'org-edit-structure
640 :group 'org-font-lock
641 :type 'boolean)
643 (defcustom org-adapt-indentation t
644 "Non-nil means, adapt indentation when promoting and demoting.
645 When this is set and the *entire* text in an entry is indented, the
646 indentation is increased by one space in a demotion command, and
647 decreased by one in a promotion command. If any line in the entry
648 body starts at column 0, indentation is not changed at all."
649 :group 'org-edit-structure
650 :type 'boolean)
652 (defcustom org-special-ctrl-a/e nil
653 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
655 When t, `C-a' will bring back the cursor to the beginning of the
656 headline text, i.e. after the stars and after a possible TODO keyword.
657 In an item, this will be the position after the bullet.
658 When the cursor is already at that position, another `C-a' will bring
659 it to the beginning of the line.
661 `C-e' will jump to the end of the headline, ignoring the presence of tags
662 in the headline. A second `C-e' will then jump to the true end of the
663 line, after any tags.
665 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
666 and only a directly following, identical keypress will bring the cursor
667 to the special positions.
669 This may also be a cons cell where the behavior for `C-a' and `C-e' is
670 set separately."
671 :group 'org-edit-structure
672 :type '(choice
673 (const :tag "off" nil)
674 (const :tag "after stars/bullet and before tags first" t)
675 (const :tag "true line boundary first" reversed)
676 (cons :tag "Set C-a and C-e separately"
677 (choice :tag "Special C-a"
678 (const :tag "off" nil)
679 (const :tag "after stars/bullet first" t)
680 (const :tag "before stars/bullet first" reversed))
681 (choice :tag "Special C-e"
682 (const :tag "off" nil)
683 (const :tag "before tags first" t)
684 (const :tag "after tags first" reversed)))))
685 (if (fboundp 'defvaralias)
686 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
688 (defcustom org-special-ctrl-k nil
689 "Non-nil means `C-k' will behave specially in headlines.
690 When nil, `C-k' will call the default `kill-line' command.
691 When t, the following will happen while the cursor is in the headline:
693 - When the cursor is at the beginning of a headline, kill the entire
694 line and possible the folded subtree below the line.
695 - When in the middle of the headline text, kill the headline up to the tags.
696 - When after the headline text, kill the tags."
697 :group 'org-edit-structure
698 :type 'boolean)
700 (defcustom org-yank-folded-subtrees t
701 "Non-nil means, when yanking subtrees, fold them.
702 If the kill is a single subtree, or a sequence of subtrees, i.e. if
703 it starts with a heading and all other headings in it are either children
704 or siblings, then fold all the subtrees. However, do this only if no
705 text after the yank would be swallowed into a folded tree by this action."
706 :group 'org-edit-structure
707 :type 'boolean)
709 (defcustom org-yank-adjusted-subtrees nil
710 "Non-nil means, when yanking subtrees, adjust the level.
711 With this setting, `org-paste-subtree' is used to insert the subtree, see
712 this function for details."
713 :group 'org-edit-structure
714 :type 'boolean)
716 (defcustom org-M-RET-may-split-line '((default . t))
717 "Non-nil means, M-RET will split the line at the cursor position.
718 When nil, it will go to the end of the line before making a
719 new line.
720 You may also set this option in a different way for different
721 contexts. Valid contexts are:
723 headline when creating a new headline
724 item when creating a new item
725 table in a table field
726 default the value to be used for all contexts not explicitly
727 customized"
728 :group 'org-structure
729 :group 'org-table
730 :type '(choice
731 (const :tag "Always" t)
732 (const :tag "Never" nil)
733 (repeat :greedy t :tag "Individual contexts"
734 (cons
735 (choice :tag "Context"
736 (const headline)
737 (const item)
738 (const table)
739 (const default))
740 (boolean)))))
743 (defcustom org-insert-heading-respect-content nil
744 "Non-nil means, insert new headings after the current subtree.
745 When nil, the new heading is created directly after the current line.
746 The commands \\[org-insert-heading-respect-content] and
747 \\[org-insert-todo-heading-respect-content] turn this variable on
748 for the duration of the command."
749 :group 'org-structure
750 :type 'boolean)
752 (defcustom org-blank-before-new-entry '((heading . auto)
753 (plain-list-item . auto))
754 "Should `org-insert-heading' leave a blank line before new heading/item?
755 The value is an alist, with `heading' and `plain-list-item' as car,
756 and a boolean flag as cdr. For plain lists, if the variable
757 `org-empty-line-terminates-plain-lists' is set, the setting here
758 is ignored and no empty line is inserted, to keep the list in tact."
759 :group 'org-edit-structure
760 :type '(list
761 (cons (const heading)
762 (choice (const :tag "Never" nil)
763 (const :tag "Always" t)
764 (const :tag "Auto" auto)))
765 (cons (const plain-list-item)
766 (choice (const :tag "Never" nil)
767 (const :tag "Always" t)
768 (const :tag "Auto" auto)))))
770 (defcustom org-insert-heading-hook nil
771 "Hook being run after inserting a new heading."
772 :group 'org-edit-structure
773 :type 'hook)
775 (defcustom org-enable-fixed-width-editor t
776 "Non-nil means, lines starting with \":\" are treated as fixed-width.
777 This currently only means, they are never auto-wrapped.
778 When nil, such lines will be treated like ordinary lines.
779 See also the QUOTE keyword."
780 :group 'org-edit-structure
781 :type 'boolean)
783 (defcustom org-edit-src-region-extra nil
784 "Additional regexps to identify regions for editing with `org-edit-src-code'.
785 For examples see the function `org-edit-src-find-region-and-lang'.
786 The regular expression identifying the begin marker should end with a newline,
787 and the regexp marking the end line should start with a newline, to make sure
788 there are kept outside the narrowed region."
789 :group 'org-edit-structure
790 :type '(repeat
791 (list
792 (regexp :tag "begin regexp")
793 (regexp :tag "end regexp")
794 (choice :tag "language"
795 (string :tag "specify")
796 (integer :tag "from match group")
797 (const :tag "from `lang' element")
798 (const :tag "from `style' element")))))
800 (defcustom org-coderef-label-format "(ref:%s)"
801 "The default coderef format.
802 This format string will be used to search for coderef labels in literal
803 examples (EXAMPLE and SRC blocks). The format can be overwritten
804 an individual literal example with the -f option, like
806 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
808 #+END_SRC
810 If you want to use this for HTML export, make sure that the format does
811 not introduce special font-locking, and avoid the HTML special
812 characters `<', `>', and `&'. The reason for this restriction is that
813 the labels are searched for only after htmlize has done its job."
814 :group 'org-edit-structure ; FIXME this is not in the right group
815 :type 'string)
817 (defcustom org-edit-fixed-width-region-mode 'artist-mode
818 "The mode that should be used to edit fixed-width regions.
819 These are the regions where each line starts with a colon."
820 :group 'org-edit-structure
821 :type '(choice
822 (const artist-mode)
823 (const picture-mode)
824 (const fundamental-mode)
825 (function :tag "Other (specify)")))
827 (defcustom org-goto-auto-isearch t
828 "Non-nil means, typing characters in org-goto starts incremental search."
829 :group 'org-edit-structure
830 :type 'boolean)
832 (defgroup org-sparse-trees nil
833 "Options concerning sparse trees in Org-mode."
834 :tag "Org Sparse Trees"
835 :group 'org-structure)
837 (defcustom org-highlight-sparse-tree-matches t
838 "Non-nil means, highlight all matches that define a sparse tree.
839 The highlights will automatically disappear the next time the buffer is
840 changed by an edit command."
841 :group 'org-sparse-trees
842 :type 'boolean)
844 (defcustom org-remove-highlights-with-change t
845 "Non-nil means, any change to the buffer will remove temporary highlights.
846 Such highlights are created by `org-occur' and `org-clock-display'.
847 When nil, `C-c C-c needs to be used to get rid of the highlights.
848 The highlights created by `org-preview-latex-fragment' always need
849 `C-c C-c' to be removed."
850 :group 'org-sparse-trees
851 :group 'org-time
852 :type 'boolean)
855 (defcustom org-occur-hook '(org-first-headline-recenter)
856 "Hook that is run after `org-occur' has constructed a sparse tree.
857 This can be used to recenter the window to show as much of the structure
858 as possible."
859 :group 'org-sparse-trees
860 :type 'hook)
862 (defgroup org-imenu-and-speedbar nil
863 "Options concerning imenu and speedbar in Org-mode."
864 :tag "Org Imenu and Speedbar"
865 :group 'org-structure)
867 (defcustom org-imenu-depth 2
868 "The maximum level for Imenu access to Org-mode headlines.
869 This also applied for speedbar access."
870 :group 'org-imenu-and-speedbar
871 :type 'number)
873 (defgroup org-table nil
874 "Options concerning tables in Org-mode."
875 :tag "Org Table"
876 :group 'org)
878 (defcustom org-enable-table-editor 'optimized
879 "Non-nil means, lines starting with \"|\" are handled by the table editor.
880 When nil, such lines will be treated like ordinary lines.
882 When equal to the symbol `optimized', the table editor will be optimized to
883 do the following:
884 - Automatic overwrite mode in front of whitespace in table fields.
885 This makes the structure of the table stay in tact as long as the edited
886 field does not exceed the column width.
887 - Minimize the number of realigns. Normally, the table is aligned each time
888 TAB or RET are pressed to move to another field. With optimization this
889 happens only if changes to a field might have changed the column width.
890 Optimization requires replacing the functions `self-insert-command',
891 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
892 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
893 very good at guessing when a re-align will be necessary, but you can always
894 force one with \\[org-ctrl-c-ctrl-c].
896 If you would like to use the optimized version in Org-mode, but the
897 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
899 This variable can be used to turn on and off the table editor during a session,
900 but in order to toggle optimization, a restart is required.
902 See also the variable `org-table-auto-blank-field'."
903 :group 'org-table
904 :type '(choice
905 (const :tag "off" nil)
906 (const :tag "on" t)
907 (const :tag "on, optimized" optimized)))
909 (defcustom org-self-insert-cluster-for-undo t
910 "Non-nil means cluster self-insert commands for undo when possible.
911 If this is set, then, like in the Emacs command loop, 20 consequtive
912 characters will be undone together.
913 This is configurable, because there is some impact on typing performance."
914 :group 'org-table
915 :type 'boolean)
917 (defcustom org-table-tab-recognizes-table.el t
918 "Non-nil means, TAB will automatically notice a table.el table.
919 When it sees such a table, it moves point into it and - if necessary -
920 calls `table-recognize-table'."
921 :group 'org-table-editing
922 :type 'boolean)
924 (defgroup org-link nil
925 "Options concerning links in Org-mode."
926 :tag "Org Link"
927 :group 'org)
929 (defvar org-link-abbrev-alist-local nil
930 "Buffer-local version of `org-link-abbrev-alist', which see.
931 The value of this is taken from the #+LINK lines.")
932 (make-variable-buffer-local 'org-link-abbrev-alist-local)
934 (defcustom org-link-abbrev-alist nil
935 "Alist of link abbreviations.
936 The car of each element is a string, to be replaced at the start of a link.
937 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
938 links in Org-mode buffers can have an optional tag after a double colon, e.g.
940 [[linkkey:tag][description]]
942 The 'linkkey' must be a word word, starting with a letter, followed
943 by letters, numbers, '-' or '_'.
945 If REPLACE is a string, the tag will simply be appended to create the link.
946 If the string contains \"%s\", the tag will be inserted there. Alternatively,
947 the placeholder \"%h\" will cause a url-encoded version of the tag to
948 be inserted at that point (see the function `url-hexify-string').
950 REPLACE may also be a function that will be called with the tag as the
951 only argument to create the link, which should be returned as a string.
953 See the manual for examples."
954 :group 'org-link
955 :type '(repeat
956 (cons
957 (string :tag "Protocol")
958 (choice
959 (string :tag "Format")
960 (function)))))
962 (defcustom org-descriptive-links t
963 "Non-nil means, hide link part and only show description of bracket links.
964 Bracket links are like [[link][description]]. This variable sets the initial
965 state in new org-mode buffers. The setting can then be toggled on a
966 per-buffer basis from the Org->Hyperlinks menu."
967 :group 'org-link
968 :type 'boolean)
970 (defcustom org-link-file-path-type 'adaptive
971 "How the path name in file links should be stored.
972 Valid values are:
974 relative Relative to the current directory, i.e. the directory of the file
975 into which the link is being inserted.
976 absolute Absolute path, if possible with ~ for home directory.
977 noabbrev Absolute path, no abbreviation of home directory.
978 adaptive Use relative path for files in the current directory and sub-
979 directories of it. For other files, use an absolute path."
980 :group 'org-link
981 :type '(choice
982 (const relative)
983 (const absolute)
984 (const noabbrev)
985 (const adaptive)))
987 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
988 "Types of links that should be activated in Org-mode files.
989 This is a list of symbols, each leading to the activation of a certain link
990 type. In principle, it does not hurt to turn on most link types - there may
991 be a small gain when turning off unused link types. The types are:
993 bracket The recommended [[link][description]] or [[link]] links with hiding.
994 angular Links in angular brackets that may contain whitespace like
995 <bbdb:Carsten Dominik>.
996 plain Plain links in normal text, no whitespace, like http://google.com.
997 radio Text that is matched by a radio target, see manual for details.
998 tag Tag settings in a headline (link to tag search).
999 date Time stamps (link to calendar).
1000 footnote Footnote labels.
1002 Changing this variable requires a restart of Emacs to become effective."
1003 :group 'org-link
1004 :type '(set :greedy t
1005 (const :tag "Double bracket links (new style)" bracket)
1006 (const :tag "Angular bracket links (old style)" angular)
1007 (const :tag "Plain text links" plain)
1008 (const :tag "Radio target matches" radio)
1009 (const :tag "Tags" tag)
1010 (const :tag "Timestamps" date)
1011 (const :tag "Footnotes" footnote)))
1013 (defcustom org-make-link-description-function nil
1014 "Function to use to generate link descriptions from links. If
1015 nil the link location will be used. This function must take two
1016 parameters; the first is the link and the second the description
1017 org-insert-link has generated, and should return the description
1018 to use."
1019 :group 'org-link
1020 :type 'function)
1022 (defgroup org-link-store nil
1023 "Options concerning storing links in Org-mode."
1024 :tag "Org Store Link"
1025 :group 'org-link)
1027 (defcustom org-email-link-description-format "Email %c: %.30s"
1028 "Format of the description part of a link to an email or usenet message.
1029 The following %-escapes will be replaced by corresponding information:
1031 %F full \"From\" field
1032 %f name, taken from \"From\" field, address if no name
1033 %T full \"To\" field
1034 %t first name in \"To\" field, address if no name
1035 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1036 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1037 %s subject
1038 %m message-id.
1040 You may use normal field width specification between the % and the letter.
1041 This is for example useful to limit the length of the subject.
1043 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1044 :group 'org-link-store
1045 :type 'string)
1047 (defcustom org-from-is-user-regexp
1048 (let (r1 r2)
1049 (when (and user-mail-address (not (string= user-mail-address "")))
1050 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1051 (when (and user-full-name (not (string= user-full-name "")))
1052 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1053 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1054 "Regexp matched against the \"From:\" header of an email or usenet message.
1055 It should match if the message is from the user him/herself."
1056 :group 'org-link-store
1057 :type 'regexp)
1059 (defcustom org-link-to-org-use-id 'create-if-interactive
1060 "Non-nil means, storing a link to an Org file will use entry IDs.
1062 Note that before this variable is even considered, org-id must be loaded,
1063 to please customize `org-modules' and turn it on.
1065 The variable can have the following values:
1067 t Create an ID if needed to make a link to the current entry.
1069 create-if-interactive
1070 If `org-store-link' is called directly (interactively, as a user
1071 command), do create an ID to support the link. But when doing the
1072 job for remember, only use the ID if it already exists. The
1073 purpose of this setting is to avoid proliferation of unwanted
1074 IDs, just because you happen to be in an Org file when you
1075 call `org-remember' that automatically and preemptively
1076 creates a link. If you do want to get an ID link in a remember
1077 template to an entry not having an ID, create it first by
1078 explicitly creating a link to it, using `C-c C-l' first.
1080 use-existing
1081 Use existing ID, do not create one.
1083 nil Never use an ID to make a link, instead link using a text search for
1084 the headline text."
1085 :group 'org-link-store
1086 :type '(choice
1087 (const :tag "Create ID to make link" t)
1088 (const :tag "Create if string link interactively"
1089 'create-if-interactive)
1090 (const :tag "Only use existing" 'use-existing)
1091 (const :tag "Do not use ID to create link" nil)))
1093 (defcustom org-context-in-file-links t
1094 "Non-nil means, file links from `org-store-link' contain context.
1095 A search string will be added to the file name with :: as separator and
1096 used to find the context when the link is activated by the command
1097 `org-open-at-point'.
1098 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1099 negates this setting for the duration of the command."
1100 :group 'org-link-store
1101 :type 'boolean)
1103 (defcustom org-keep-stored-link-after-insertion nil
1104 "Non-nil means, keep link in list for entire session.
1106 The command `org-store-link' adds a link pointing to the current
1107 location to an internal list. These links accumulate during a session.
1108 The command `org-insert-link' can be used to insert links into any
1109 Org-mode file (offering completion for all stored links). When this
1110 option is nil, every link which has been inserted once using \\[org-insert-link]
1111 will be removed from the list, to make completing the unused links
1112 more efficient."
1113 :group 'org-link-store
1114 :type 'boolean)
1116 (defgroup org-link-follow nil
1117 "Options concerning following links in Org-mode."
1118 :tag "Org Follow Link"
1119 :group 'org-link)
1121 (defcustom org-link-translation-function nil
1122 "Function to translate links with different syntax to Org syntax.
1123 This can be used to translate links created for example by the Planner
1124 or emacs-wiki packages to Org syntax.
1125 The function must accept two parameters, a TYPE containing the link
1126 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1127 which is everything after the link protocol. It should return a cons
1128 with possibly modified values of type and path.
1129 Org contains a function for this, so if you set this variable to
1130 `org-translate-link-from-planner', you should be able follow many
1131 links created by planner."
1132 :group 'org-link-follow
1133 :type 'function)
1135 (defcustom org-follow-link-hook nil
1136 "Hook that is run after a link has been followed."
1137 :group 'org-link-follow
1138 :type 'hook)
1140 (defcustom org-tab-follows-link nil
1141 "Non-nil means, on links TAB will follow the link.
1142 Needs to be set before org.el is loaded.
1143 This really should not be used, it does not make sense, and the
1144 implementation is bad."
1145 :group 'org-link-follow
1146 :type 'boolean)
1148 (defcustom org-return-follows-link nil
1149 "Non-nil means, on links RET will follow the link.
1150 Needs to be set before org.el is loaded."
1151 :group 'org-link-follow
1152 :type 'boolean)
1154 (defcustom org-mouse-1-follows-link
1155 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1156 "Non-nil means, mouse-1 on a link will follow the link.
1157 A longer mouse click will still set point. Does not work on XEmacs.
1158 Needs to be set before org.el is loaded."
1159 :group 'org-link-follow
1160 :type 'boolean)
1162 (defcustom org-mark-ring-length 4
1163 "Number of different positions to be recorded in the ring
1164 Changing this requires a restart of Emacs to work correctly."
1165 :group 'org-link-follow
1166 :type 'integer)
1168 (defcustom org-link-frame-setup
1169 '((vm . vm-visit-folder-other-frame)
1170 (gnus . gnus-other-frame)
1171 (file . find-file-other-window))
1172 "Setup the frame configuration for following links.
1173 When following a link with Emacs, it may often be useful to display
1174 this link in another window or frame. This variable can be used to
1175 set this up for the different types of links.
1176 For VM, use any of
1177 `vm-visit-folder'
1178 `vm-visit-folder-other-frame'
1179 For Gnus, use any of
1180 `gnus'
1181 `gnus-other-frame'
1182 `org-gnus-no-new-news'
1183 For FILE, use any of
1184 `find-file'
1185 `find-file-other-window'
1186 `find-file-other-frame'
1187 For the calendar, use the variable `calendar-setup'.
1188 For BBDB, it is currently only possible to display the matches in
1189 another window."
1190 :group 'org-link-follow
1191 :type '(list
1192 (cons (const vm)
1193 (choice
1194 (const vm-visit-folder)
1195 (const vm-visit-folder-other-window)
1196 (const vm-visit-folder-other-frame)))
1197 (cons (const gnus)
1198 (choice
1199 (const gnus)
1200 (const gnus-other-frame)
1201 (const org-gnus-no-new-news)))
1202 (cons (const file)
1203 (choice
1204 (const find-file)
1205 (const find-file-other-window)
1206 (const find-file-other-frame)))))
1208 (defcustom org-display-internal-link-with-indirect-buffer nil
1209 "Non-nil means, use indirect buffer to display infile links.
1210 Activating internal links (from one location in a file to another location
1211 in the same file) normally just jumps to the location. When the link is
1212 activated with a C-u prefix (or with mouse-3), the link is displayed in
1213 another window. When this option is set, the other window actually displays
1214 an indirect buffer clone of the current buffer, to avoid any visibility
1215 changes to the current buffer."
1216 :group 'org-link-follow
1217 :type 'boolean)
1219 (defcustom org-open-non-existing-files nil
1220 "Non-nil means, `org-open-file' will open non-existing files.
1221 When nil, an error will be generated."
1222 :group 'org-link-follow
1223 :type 'boolean)
1225 (defcustom org-open-directory-means-index-dot-org nil
1226 "Non-nil means, a link to a directory really means to index.org.
1227 When nil, following a directory link will run dired or open a finder/explorer
1228 window on that directory."
1229 :group 'org-link-follow
1230 :type 'boolean)
1232 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1233 "Function and arguments to call for following mailto links.
1234 This is a list with the first element being a lisp function, and the
1235 remaining elements being arguments to the function. In string arguments,
1236 %a will be replaced by the address, and %s will be replaced by the subject
1237 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1238 :group 'org-link-follow
1239 :type '(choice
1240 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1241 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1242 (const :tag "message-mail" (message-mail "%a" "%s"))
1243 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1245 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1246 "Non-nil means, ask for confirmation before executing shell links.
1247 Shell links can be dangerous: just think about a link
1249 [[shell:rm -rf ~/*][Google Search]]
1251 This link would show up in your Org-mode document as \"Google Search\",
1252 but really it would remove your entire home directory.
1253 Therefore we advise against setting this variable to nil.
1254 Just change it to `y-or-n-p' of you want to confirm with a
1255 single keystroke rather than having to type \"yes\"."
1256 :group 'org-link-follow
1257 :type '(choice
1258 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1259 (const :tag "with y-or-n (faster)" y-or-n-p)
1260 (const :tag "no confirmation (dangerous)" nil)))
1262 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1263 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1264 Elisp links can be dangerous: just think about a link
1266 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1268 This link would show up in your Org-mode document as \"Google Search\",
1269 but really it would remove your entire home directory.
1270 Therefore we advise against setting this variable to nil.
1271 Just change it to `y-or-n-p' of you want to confirm with a
1272 single keystroke rather than having to type \"yes\"."
1273 :group 'org-link-follow
1274 :type '(choice
1275 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1276 (const :tag "with y-or-n (faster)" y-or-n-p)
1277 (const :tag "no confirmation (dangerous)" nil)))
1279 (defconst org-file-apps-defaults-gnu
1280 '((remote . emacs)
1281 (system . mailcap)
1282 (t . mailcap))
1283 "Default file applications on a UNIX or GNU/Linux system.
1284 See `org-file-apps'.")
1286 (defconst org-file-apps-defaults-macosx
1287 '((remote . emacs)
1288 (t . "open %s")
1289 (system . "open %s")
1290 ("ps.gz" . "gv %s")
1291 ("eps.gz" . "gv %s")
1292 ("dvi" . "xdvi %s")
1293 ("fig" . "xfig %s"))
1294 "Default file applications on a MacOS X system.
1295 The system \"open\" is known as a default, but we use X11 applications
1296 for some files for which the OS does not have a good default.
1297 See `org-file-apps'.")
1299 (defconst org-file-apps-defaults-windowsnt
1300 (list
1301 '(remote . emacs)
1302 (cons t
1303 (list (if (featurep 'xemacs)
1304 'mswindows-shell-execute
1305 'w32-shell-execute)
1306 "open" 'file))
1307 (cons 'system
1308 (list (if (featurep 'xemacs)
1309 'mswindows-shell-execute
1310 'w32-shell-execute)
1311 "open" 'file)))
1312 "Default file applications on a Windows NT system.
1313 The system \"open\" is used for most files.
1314 See `org-file-apps'.")
1316 (defcustom org-file-apps
1318 (auto-mode . emacs)
1319 ("\\.x?html?\\'" . default)
1320 ("\\.pdf\\'" . default)
1322 "External applications for opening `file:path' items in a document.
1323 Org-mode uses system defaults for different file types, but
1324 you can use this variable to set the application for a given file
1325 extension. The entries in this list are cons cells where the car identifies
1326 files and the cdr the corresponding command. Possible values for the
1327 file identifier are
1328 \"regex\" Regular expression matched against the file name. For backward
1329 compatibility, this can also be a string with only alphanumeric
1330 characters, which is then interpreted as an extension.
1331 `directory' Matches a directory
1332 `remote' Matches a remote file, accessible through tramp or efs.
1333 Remote files most likely should be visited through Emacs
1334 because external applications cannot handle such paths.
1335 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1336 so all files Emacs knows how to handle. Using this with
1337 command `emacs' will open most files in Emacs. Beware that this
1338 will also open html files inside Emacs, unless you add
1339 (\"html\" . default) to the list as well.
1340 t Default for files not matched by any of the other options.
1341 `system' The system command to open files, like `open' on Windows
1342 and Mac OS X, and mailcap under GNU/Linux. This is the command
1343 that will be selected if you call `C-c C-o' with a double
1344 `C-u C-u' prefix.
1346 Possible values for the command are:
1347 `emacs' The file will be visited by the current Emacs process.
1348 `default' Use the default application for this file type, which is the
1349 association for t in the list, most likely in the system-specific
1350 part.
1351 This can be used to overrule an unwanted setting in the
1352 system-specific variable.
1353 `system' Use the system command for opening files, like \"open\".
1354 This command is specified by the entry whose car is `system'.
1355 Most likely, the system-specific version of this variable
1356 does define this command, but you can overrule/replace it
1357 here.
1358 string A command to be executed by a shell; %s will be replaced
1359 by the path to the file.
1360 sexp A Lisp form which will be evaluated. The file path will
1361 be available in the Lisp variable `file'.
1362 For more examples, see the system specific constants
1363 `org-file-apps-defaults-macosx'
1364 `org-file-apps-defaults-windowsnt'
1365 `org-file-apps-defaults-gnu'."
1366 :group 'org-link-follow
1367 :type '(repeat
1368 (cons (choice :value ""
1369 (string :tag "Extension")
1370 (const :tag "System command to open files" system)
1371 (const :tag "Default for unrecognized files" t)
1372 (const :tag "Remote file" remote)
1373 (const :tag "Links to a directory" directory)
1374 (const :tag "Any files that have Emacs modes"
1375 auto-mode))
1376 (choice :value ""
1377 (const :tag "Visit with Emacs" emacs)
1378 (const :tag "Use default" default)
1379 (const :tag "Use the system command" system)
1380 (string :tag "Command")
1381 (sexp :tag "Lisp form")))))
1383 (defgroup org-refile nil
1384 "Options concerning refiling entries in Org-mode."
1385 :tag "Org Refile"
1386 :group 'org)
1388 (defcustom org-directory "~/org"
1389 "Directory with org files.
1390 This is just a default location to look for Org files. There is no need
1391 at all to put your files into this directory. It is only used in the
1392 following situations:
1394 1. When a remember template specifies a target file that is not an
1395 absolute path. The path will then be interpreted relative to
1396 `org-directory'
1397 2. When a remember note is filed away in an interactive way (when exiting the
1398 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1399 with `org-directory' as the default path."
1400 :group 'org-refile
1401 :group 'org-remember
1402 :type 'directory)
1404 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1405 "Default target for storing notes.
1406 Used by the hooks for remember.el. This can be a string, or nil to mean
1407 the value of `remember-data-file'.
1408 You can set this on a per-template basis with the variable
1409 `org-remember-templates'."
1410 :group 'org-refile
1411 :group 'org-remember
1412 :type '(choice
1413 (const :tag "Default from remember-data-file" nil)
1414 file))
1416 (defcustom org-goto-interface 'outline
1417 "The default interface to be used for `org-goto'.
1418 Allowed values are:
1419 outline The interface shows an outline of the relevant file
1420 and the correct heading is found by moving through
1421 the outline or by searching with incremental search.
1422 outline-path-completion Headlines in the current buffer are offered via
1423 completion. This is the interface also used by
1424 the refile command."
1425 :group 'org-refile
1426 :type '(choice
1427 (const :tag "Outline" outline)
1428 (const :tag "Outline-path-completion" outline-path-completion)))
1430 (defcustom org-goto-max-level 5
1431 "Maximum level to be considered when running org-goto with refile interface."
1432 :group 'org-refile
1433 :type 'number)
1435 (defcustom org-reverse-note-order nil
1436 "Non-nil means, store new notes at the beginning of a file or entry.
1437 When nil, new notes will be filed to the end of a file or entry.
1438 This can also be a list with cons cells of regular expressions that
1439 are matched against file names, and values."
1440 :group 'org-remember
1441 :group 'org-refile
1442 :type '(choice
1443 (const :tag "Reverse always" t)
1444 (const :tag "Reverse never" nil)
1445 (repeat :tag "By file name regexp"
1446 (cons regexp boolean))))
1448 (defcustom org-refile-targets nil
1449 "Targets for refiling entries with \\[org-refile].
1450 This is list of cons cells. Each cell contains:
1451 - a specification of the files to be considered, either a list of files,
1452 or a symbol whose function or variable value will be used to retrieve
1453 a file name or a list of file names. If you use `org-agenda-files' for
1454 that, all agenda files will be scanned for targets. Nil means, consider
1455 headings in the current buffer.
1456 - A specification of how to find candidate refile targets. This may be
1457 any of:
1458 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1459 This tag has to be present in all target headlines, inheritance will
1460 not be considered.
1461 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1462 todo keyword.
1463 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1464 headlines that are refiling targets.
1465 - a cons cell (:level . N). Any headline of level N is considered a target.
1466 Note that, when `org-odd-levels-only' is set, level corresponds to
1467 order in hierarchy, not to the number of stars.
1468 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1469 Note that, when `org-odd-levels-only' is set, level corresponds to
1470 order in hierarchy, not to the number of stars.
1472 When this variable is nil, all top-level headlines in the current buffer
1473 are used, equivalent to the value `((nil . (:level . 1))'."
1474 :group 'org-refile
1475 :type '(repeat
1476 (cons
1477 (choice :value org-agenda-files
1478 (const :tag "All agenda files" org-agenda-files)
1479 (const :tag "Current buffer" nil)
1480 (function) (variable) (file))
1481 (choice :tag "Identify target headline by"
1482 (cons :tag "Specific tag" (const :value :tag) (string))
1483 (cons :tag "TODO keyword" (const :value :todo) (string))
1484 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1485 (cons :tag "Level number" (const :value :level) (integer))
1486 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1488 (defcustom org-refile-use-outline-path nil
1489 "Non-nil means, provide refile targets as paths.
1490 So a level 3 headline will be available as level1/level2/level3.
1491 When the value is `file', also include the file name (without directory)
1492 into the path. When `full-file-path', include the full file path."
1493 :group 'org-refile
1494 :type '(choice
1495 (const :tag "Not" nil)
1496 (const :tag "Yes" t)
1497 (const :tag "Start with file name" file)
1498 (const :tag "Start with full file path" full-file-path)))
1500 (defcustom org-outline-path-complete-in-steps t
1501 "Non-nil means, complete the outline path in hierarchical steps.
1502 When Org-mode uses the refile interface to select an outline path
1503 \(see variable `org-refile-use-outline-path'), the completion of
1504 the path can be done is a single go, or if can be done in steps down
1505 the headline hierarchy. Going in steps is probably the best if you
1506 do not use a special completion package like `ido' or `icicles'.
1507 However, when using these packages, going in one step can be very
1508 fast, while still showing the whole path to the entry."
1509 :group 'org-refile
1510 :type 'boolean)
1512 (defgroup org-todo nil
1513 "Options concerning TODO items in Org-mode."
1514 :tag "Org TODO"
1515 :group 'org)
1517 (defgroup org-progress nil
1518 "Options concerning Progress logging in Org-mode."
1519 :tag "Org Progress"
1520 :group 'org-time)
1522 (defvar org-todo-interpretation-widgets
1524 (:tag "Sequence (cycling hits every state)" sequence)
1525 (:tag "Type (cycling directly to DONE)" type))
1526 "The available interpretation symbols for customizing
1527 `org-todo-keywords'.
1528 Interested libraries should add to this list.")
1530 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1531 "List of TODO entry keyword sequences and their interpretation.
1532 \\<org-mode-map>This is a list of sequences.
1534 Each sequence starts with a symbol, either `sequence' or `type',
1535 indicating if the keywords should be interpreted as a sequence of
1536 action steps, or as different types of TODO items. The first
1537 keywords are states requiring action - these states will select a headline
1538 for inclusion into the global TODO list Org-mode produces. If one of
1539 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1540 signify that no further action is necessary. If \"|\" is not found,
1541 the last keyword is treated as the only DONE state of the sequence.
1543 The command \\[org-todo] cycles an entry through these states, and one
1544 additional state where no keyword is present. For details about this
1545 cycling, see the manual.
1547 TODO keywords and interpretation can also be set on a per-file basis with
1548 the special #+SEQ_TODO and #+TYP_TODO lines.
1550 Each keyword can optionally specify a character for fast state selection
1551 \(in combination with the variable `org-use-fast-todo-selection')
1552 and specifiers for state change logging, using the same syntax
1553 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1554 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1555 indicates to record a time stamp each time this state is selected.
1557 Each keyword may also specify if a timestamp or a note should be
1558 recorded when entering or leaving the state, by adding additional
1559 characters in the parenthesis after the keyword. This looks like this:
1560 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1561 record only the time of the state change. With X and Y being either
1562 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1563 Y when leaving the state if and only if the *target* state does not
1564 define X. You may omit any of the fast-selection key or X or /Y,
1565 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1567 For backward compatibility, this variable may also be just a list
1568 of keywords - in this case the interpretation (sequence or type) will be
1569 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1570 :group 'org-todo
1571 :group 'org-keywords
1572 :type '(choice
1573 (repeat :tag "Old syntax, just keywords"
1574 (string :tag "Keyword"))
1575 (repeat :tag "New syntax"
1576 (cons
1577 (choice
1578 :tag "Interpretation"
1579 ;;Quick and dirty way to see
1580 ;;`org-todo-interpretations'. This takes the
1581 ;;place of item arguments
1582 :convert-widget
1583 (lambda (widget)
1584 (widget-put widget
1585 :args (mapcar
1586 #'(lambda (x)
1587 (widget-convert
1588 (cons 'const x)))
1589 org-todo-interpretation-widgets))
1590 widget))
1591 (repeat
1592 (string :tag "Keyword"))))))
1594 (defvar org-todo-keywords-1 nil
1595 "All TODO and DONE keywords active in a buffer.")
1596 (make-variable-buffer-local 'org-todo-keywords-1)
1597 (defvar org-todo-keywords-for-agenda nil)
1598 (defvar org-done-keywords-for-agenda nil)
1599 (defvar org-todo-keyword-alist-for-agenda nil)
1600 (defvar org-tag-alist-for-agenda nil)
1601 (defvar org-agenda-contributing-files nil)
1602 (defvar org-not-done-keywords nil)
1603 (make-variable-buffer-local 'org-not-done-keywords)
1604 (defvar org-done-keywords nil)
1605 (make-variable-buffer-local 'org-done-keywords)
1606 (defvar org-todo-heads nil)
1607 (make-variable-buffer-local 'org-todo-heads)
1608 (defvar org-todo-sets nil)
1609 (make-variable-buffer-local 'org-todo-sets)
1610 (defvar org-todo-log-states nil)
1611 (make-variable-buffer-local 'org-todo-log-states)
1612 (defvar org-todo-kwd-alist nil)
1613 (make-variable-buffer-local 'org-todo-kwd-alist)
1614 (defvar org-todo-key-alist nil)
1615 (make-variable-buffer-local 'org-todo-key-alist)
1616 (defvar org-todo-key-trigger nil)
1617 (make-variable-buffer-local 'org-todo-key-trigger)
1619 (defcustom org-todo-interpretation 'sequence
1620 "Controls how TODO keywords are interpreted.
1621 This variable is in principle obsolete and is only used for
1622 backward compatibility, if the interpretation of todo keywords is
1623 not given already in `org-todo-keywords'. See that variable for
1624 more information."
1625 :group 'org-todo
1626 :group 'org-keywords
1627 :type '(choice (const sequence)
1628 (const type)))
1630 (defcustom org-use-fast-todo-selection t
1631 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1632 This variable describes if and under what circumstances the cycling
1633 mechanism for TODO keywords will be replaced by a single-key, direct
1634 selection scheme.
1636 When nil, fast selection is never used.
1638 When the symbol `prefix', it will be used when `org-todo' is called with
1639 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1640 in an agenda buffer.
1642 When t, fast selection is used by default. In this case, the prefix
1643 argument forces cycling instead.
1645 In all cases, the special interface is only used if access keys have actually
1646 been assigned by the user, i.e. if keywords in the configuration are followed
1647 by a letter in parenthesis, like TODO(t)."
1648 :group 'org-todo
1649 :type '(choice
1650 (const :tag "Never" nil)
1651 (const :tag "By default" t)
1652 (const :tag "Only with C-u C-c C-t" prefix)))
1654 (defcustom org-provide-todo-statistics t
1655 "Non-nil means, update todo statistics after insert and toggle.
1656 When this is set, todo statistics is updated in the parent of the current
1657 entry each time a todo state is changed."
1658 :group 'org-todo
1659 :type 'boolean)
1661 (defcustom org-after-todo-state-change-hook nil
1662 "Hook which is run after the state of a TODO item was changed.
1663 The new state (a string with a TODO keyword, or nil) is available in the
1664 Lisp variable `state'."
1665 :group 'org-todo
1666 :type 'hook)
1668 (defvar org-blocker-hook nil
1669 "Hook for functions that are allowed to block a state change.
1671 Each function gets as its single argument a property list, see
1672 `org-trigger-hook' for more information about this list.
1674 If any of the functions in this hook returns nil, the state change
1675 is blocked.")
1677 (defvar org-trigger-hook nil
1678 "Hook for functions that are triggered by a state change.
1680 Each function gets as its single argument a property list with at least
1681 the following elements:
1683 (:type type-of-change :position pos-at-entry-start
1684 :from old-state :to new-state)
1686 Depending on the type, more properties may be present.
1688 This mechanism is currently implemented for:
1690 TODO state changes
1691 ------------------
1692 :type todo-state-change
1693 :from previous state (keyword as a string), or nil, or a symbol
1694 'todo' or 'done', to indicate the general type of state.
1695 :to new state, like in :from")
1697 (defcustom org-enforce-todo-dependencies nil
1698 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1699 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1700 be blocked if any prior sibling is not yet done.
1701 This variable needs to be set before org.el is loaded, and you need to
1702 restart Emacs after a change to make the change effective. The only way
1703 to change is while Emacs is running is through the customize interface."
1704 :set (lambda (var val)
1705 (set var val)
1706 (if val
1707 (add-hook 'org-blocker-hook
1708 'org-block-todo-from-children-or-siblings)
1709 (remove-hook 'org-blocker-hook
1710 'org-block-todo-from-children-or-siblings)))
1711 :group 'org-todo
1712 :type 'boolean)
1714 (defcustom org-enforce-todo-checkbox-dependencies nil
1715 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1716 When this is nil, checkboxes have no influence on switching TODO states.
1717 When non-nil, you first need to check off all check boxes before the TODO
1718 entry can be switched to DONE.
1719 This variable needs to be set before org.el is loaded, and you need to
1720 restart Emacs after a change to make the change effective. The only way
1721 to change is while Emacs is running is through the customize interface."
1722 :set (lambda (var val)
1723 (set var val)
1724 (if val
1725 (add-hook 'org-blocker-hook
1726 'org-block-todo-from-checkboxes)
1727 (remove-hook 'org-blocker-hook
1728 'org-block-todo-from-checkboxes)))
1729 :group 'org-todo
1730 :type 'boolean)
1732 (defcustom org-todo-state-tags-triggers nil
1733 "Tag changes that should be triggered by TODO state changes.
1734 This is a list. Each entry is
1736 (state-change (tag . flag) .......)
1738 State-change can be a string with a state, and empty string to indicate the
1739 state that has no TODO keyword, or it can be one of the symbols `todo'
1740 or `done', meaning any not-done or done state, respectively."
1741 :group 'org-todo
1742 :group 'org-tags
1743 :type '(repeat
1744 (cons (choice :tag "When changing to"
1745 (const :tag "Not-done state" todo)
1746 (const :tag "Done state" done)
1747 (string :tag "State"))
1748 (repeat
1749 (cons :tag "Tag action"
1750 (string :tag "Tag")
1751 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1753 (defcustom org-log-done nil
1754 "Information to record when a task moves to the DONE state.
1756 Possible values are:
1758 nil Don't add anything, just change the keyword
1759 time Add a time stamp to the task
1760 note Prompt a closing note and add it with template `org-log-note-headings'
1762 This option can also be set with on a per-file-basis with
1764 #+STARTUP: nologdone
1765 #+STARTUP: logdone
1766 #+STARTUP: lognotedone
1768 You can have local logging settings for a subtree by setting the LOGGING
1769 property to one or more of these keywords."
1770 :group 'org-todo
1771 :group 'org-progress
1772 :type '(choice
1773 (const :tag "No logging" nil)
1774 (const :tag "Record CLOSED timestamp" time)
1775 (const :tag "Record CLOSED timestamp with closing note." note)))
1777 ;; Normalize old uses of org-log-done.
1778 (cond
1779 ((eq org-log-done t) (setq org-log-done 'time))
1780 ((and (listp org-log-done) (memq 'done org-log-done))
1781 (setq org-log-done 'note)))
1783 (defcustom org-log-note-clock-out nil
1784 "Non-nil means, record a note when clocking out of an item.
1785 This can also be configured on a per-file basis by adding one of
1786 the following lines anywhere in the buffer:
1788 #+STARTUP: lognoteclock-out
1789 #+STARTUP: nolognoteclock-out"
1790 :group 'org-todo
1791 :group 'org-progress
1792 :type 'boolean)
1794 (defcustom org-log-done-with-time t
1795 "Non-nil means, the CLOSED time stamp will contain date and time.
1796 When nil, only the date will be recorded."
1797 :group 'org-progress
1798 :type 'boolean)
1800 (defcustom org-log-note-headings
1801 '((done . "CLOSING NOTE %t")
1802 (state . "State %-12s from %-12S %t")
1803 (note . "Note taken on %t")
1804 (clock-out . ""))
1805 "Headings for notes added to entries.
1806 The value is an alist, with the car being a symbol indicating the note
1807 context, and the cdr is the heading to be used. The heading may also be the
1808 empty string.
1809 %t in the heading will be replaced by a time stamp.
1810 %s will be replaced by the new TODO state, in double quotes.
1811 %S will be replaced by the old TODO state, in double quotes.
1812 %u will be replaced by the user name.
1813 %U will be replaced by the full user name."
1814 :group 'org-todo
1815 :group 'org-progress
1816 :type '(list :greedy t
1817 (cons (const :tag "Heading when closing an item" done) string)
1818 (cons (const :tag
1819 "Heading when changing todo state (todo sequence only)"
1820 state) string)
1821 (cons (const :tag "Heading when just taking a note" note) string)
1822 (cons (const :tag "Heading when clocking out" clock-out) string)))
1824 (unless (assq 'note org-log-note-headings)
1825 (push '(note . "%t") org-log-note-headings))
1827 (defcustom org-log-into-drawer nil
1828 "Non-nil means, insert state change notes and time stamps into a drawer.
1829 When nil, state changes notes will be inserted after the headline and
1830 any scheduling and clock lines, but not inside a drawer.
1832 The value of this variable should be the name of the drawer to use.
1833 LOGBOOK is proposed at the default drawer for this purpose, you can
1834 also set this to a string to define the drawer of your choice.
1836 A value of t is also allowed, representing \"LOGBOOK\".
1838 If this variable is set, `org-log-state-notes-insert-after-drawers'
1839 will be ignored."
1840 :group 'org-todo
1841 :group 'org-progress
1842 :type '(choice
1843 (const :tag "Not into a drawer" nil)
1844 (const :tag "LOGBOOK" t)
1845 (string :tag "Other")))
1847 (if (fboundp 'defvaralias)
1848 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1850 (defcustom org-log-state-notes-insert-after-drawers nil
1851 "Non-nil means, insert state change notes after any drawers in entry.
1852 Only the drawers that *immediately* follow the headline and the
1853 deadline/scheduled line are skipped.
1854 When nil, insert notes right after the heading and perhaps the line
1855 with deadline/scheduling if present.
1857 This variable will have no effect if `org-log-into-drawer' is
1858 set."
1859 :group 'org-todo
1860 :group 'org-progress
1861 :type 'boolean)
1863 (defcustom org-log-states-order-reversed t
1864 "Non-nil means, the latest state change note will be directly after heading.
1865 When nil, the notes will be orderer according to time."
1866 :group 'org-todo
1867 :group 'org-progress
1868 :type 'boolean)
1870 (defcustom org-log-repeat 'time
1871 "Non-nil means, record moving through the DONE state when triggering repeat.
1872 An auto-repeating tasks is immediately switched back to TODO when marked
1873 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1874 the TODO keyword definition, or recording a closing note by setting
1875 `org-log-done', there will be no record of the task moving through DONE.
1876 This variable forces taking a note anyway. Possible values are:
1878 nil Don't force a record
1879 time Record a time stamp
1880 note Record a note
1882 This option can also be set with on a per-file-basis with
1884 #+STARTUP: logrepeat
1885 #+STARTUP: lognoterepeat
1886 #+STARTUP: nologrepeat
1888 You can have local logging settings for a subtree by setting the LOGGING
1889 property to one or more of these keywords."
1890 :group 'org-todo
1891 :group 'org-progress
1892 :type '(choice
1893 (const :tag "Don't force a record" nil)
1894 (const :tag "Force recording the DONE state" time)
1895 (const :tag "Force recording a note with the DONE state" note)))
1898 (defgroup org-priorities nil
1899 "Priorities in Org-mode."
1900 :tag "Org Priorities"
1901 :group 'org-todo)
1903 (defcustom org-highest-priority ?A
1904 "The highest priority of TODO items. A character like ?A, ?B etc.
1905 Must have a smaller ASCII number than `org-lowest-priority'."
1906 :group 'org-priorities
1907 :type 'character)
1909 (defcustom org-lowest-priority ?C
1910 "The lowest priority of TODO items. A character like ?A, ?B etc.
1911 Must have a larger ASCII number than `org-highest-priority'."
1912 :group 'org-priorities
1913 :type 'character)
1915 (defcustom org-default-priority ?B
1916 "The default priority of TODO items.
1917 This is the priority an item get if no explicit priority is given."
1918 :group 'org-priorities
1919 :type 'character)
1921 (defcustom org-priority-start-cycle-with-default t
1922 "Non-nil means, start with default priority when starting to cycle.
1923 When this is nil, the first step in the cycle will be (depending on the
1924 command used) one higher or lower that the default priority."
1925 :group 'org-priorities
1926 :type 'boolean)
1928 (defgroup org-time nil
1929 "Options concerning time stamps and deadlines in Org-mode."
1930 :tag "Org Time"
1931 :group 'org)
1933 (defcustom org-insert-labeled-timestamps-at-point nil
1934 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1935 When nil, these labeled time stamps are forces into the second line of an
1936 entry, just after the headline. When scheduling from the global TODO list,
1937 the time stamp will always be forced into the second line."
1938 :group 'org-time
1939 :type 'boolean)
1941 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1942 "Formats for `format-time-string' which are used for time stamps.
1943 It is not recommended to change this constant.")
1945 (defcustom org-time-stamp-rounding-minutes '(0 5)
1946 "Number of minutes to round time stamps to.
1947 These are two values, the first applies when first creating a time stamp.
1948 The second applies when changing it with the commands `S-up' and `S-down'.
1949 When changing the time stamp, this means that it will change in steps
1950 of N minutes, as given by the second value.
1952 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1953 numbers should be factors of 60, so for example 5, 10, 15.
1955 When this is larger than 1, you can still force an exact time-stamp by using
1956 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1957 and by using a prefix arg to `S-up/down' to specify the exact number
1958 of minutes to shift."
1959 :group 'org-time
1960 :get '(lambda (var) ; Make sure all entries have 5 elements
1961 (if (integerp (default-value var))
1962 (list (default-value var) 5)
1963 (default-value var)))
1964 :type '(list
1965 (integer :tag "when inserting times")
1966 (integer :tag "when modifying times")))
1968 ;; Normalize old customizations of this variable.
1969 (when (integerp org-time-stamp-rounding-minutes)
1970 (setq org-time-stamp-rounding-minutes
1971 (list org-time-stamp-rounding-minutes
1972 org-time-stamp-rounding-minutes)))
1974 (defcustom org-display-custom-times nil
1975 "Non-nil means, overlay custom formats over all time stamps.
1976 The formats are defined through the variable `org-time-stamp-custom-formats'.
1977 To turn this on on a per-file basis, insert anywhere in the file:
1978 #+STARTUP: customtime"
1979 :group 'org-time
1980 :set 'set-default
1981 :type 'sexp)
1982 (make-variable-buffer-local 'org-display-custom-times)
1984 (defcustom org-time-stamp-custom-formats
1985 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1986 "Custom formats for time stamps. See `format-time-string' for the syntax.
1987 These are overlayed over the default ISO format if the variable
1988 `org-display-custom-times' is set. Time like %H:%M should be at the
1989 end of the second format."
1990 :group 'org-time
1991 :type 'sexp)
1993 (defun org-time-stamp-format (&optional long inactive)
1994 "Get the right format for a time string."
1995 (let ((f (if long (cdr org-time-stamp-formats)
1996 (car org-time-stamp-formats))))
1997 (if inactive
1998 (concat "[" (substring f 1 -1) "]")
1999 f)))
2001 (defcustom org-time-clocksum-format "%d:%02d"
2002 "The format string used when creating CLOCKSUM lines, or when
2003 org-mode generates a time duration."
2004 :group 'org-time
2005 :type 'string)
2007 (defcustom org-deadline-warning-days 14
2008 "No. of days before expiration during which a deadline becomes active.
2009 This variable governs the display in sparse trees and in the agenda.
2010 When 0 or negative, it means use this number (the absolute value of it)
2011 even if a deadline has a different individual lead time specified.
2013 Custom commands can set this variable in the options section."
2014 :group 'org-time
2015 :group 'org-agenda-daily/weekly
2016 :type 'number)
2018 (defcustom org-read-date-prefer-future t
2019 "Non-nil means, assume future for incomplete date input from user.
2020 This affects the following situations:
2021 1. The user gives a day, but no month.
2022 For example, if today is the 15th, and you enter \"3\", Org-mode will
2023 read this as the third of *next* month. However, if you enter \"17\",
2024 it will be considered as *this* month.
2025 2. The user gives a month but not a year.
2026 For example, if it is april and you enter \"feb 2\", this will be read
2027 as feb 2, *next* year. \"May 5\", however, will be this year.
2029 Currently this does not work for ISO week specifications.
2031 When this option is nil, the current month and year will always be used
2032 as defaults."
2033 :group 'org-time
2034 :type 'boolean)
2036 (defcustom org-read-date-display-live t
2037 "Non-nil means, display current interpretation of date prompt live.
2038 This display will be in an overlay, in the minibuffer."
2039 :group 'org-time
2040 :type 'boolean)
2042 (defcustom org-read-date-popup-calendar t
2043 "Non-nil means, pop up a calendar when prompting for a date.
2044 In the calendar, the date can be selected with mouse-1. However, the
2045 minibuffer will also be active, and you can simply enter the date as well.
2046 When nil, only the minibuffer will be available."
2047 :group 'org-time
2048 :type 'boolean)
2049 (if (fboundp 'defvaralias)
2050 (defvaralias 'org-popup-calendar-for-date-prompt
2051 'org-read-date-popup-calendar))
2053 (defcustom org-extend-today-until 0
2054 "The hour when your day really ends. Must be an integer.
2055 This has influence for the following applications:
2056 - When switching the agenda to \"today\". It it is still earlier than
2057 the time given here, the day recognized as TODAY is actually yesterday.
2058 - When a date is read from the user and it is still before the time given
2059 here, the current date and time will be assumed to be yesterday, 23:59.
2060 Also, timestamps inserted in remember templates follow this rule.
2062 IMPORTANT: This is a feature whose implementation is and likely will
2063 remain incomplete. Really, it is only here because past midnight seems to
2064 be the favorite working time of John Wiegley :-)"
2065 :group 'org-time
2066 :type 'number)
2068 (defcustom org-edit-timestamp-down-means-later nil
2069 "Non-nil means, S-down will increase the time in a time stamp.
2070 When nil, S-up will increase."
2071 :group 'org-time
2072 :type 'boolean)
2074 (defcustom org-calendar-follow-timestamp-change t
2075 "Non-nil means, make the calendar window follow timestamp changes.
2076 When a timestamp is modified and the calendar window is visible, it will be
2077 moved to the new date."
2078 :group 'org-time
2079 :type 'boolean)
2081 (defgroup org-tags nil
2082 "Options concerning tags in Org-mode."
2083 :tag "Org Tags"
2084 :group 'org)
2086 (defcustom org-tag-alist nil
2087 "List of tags allowed in Org-mode files.
2088 When this list is nil, Org-mode will base TAG input on what is already in the
2089 buffer.
2090 The value of this variable is an alist, the car of each entry must be a
2091 keyword as a string, the cdr may be a character that is used to select
2092 that tag through the fast-tag-selection interface.
2093 See the manual for details."
2094 :group 'org-tags
2095 :type '(repeat
2096 (choice
2097 (cons (string :tag "Tag name")
2098 (character :tag "Access char"))
2099 (const :tag "Start radio group" (:startgroup))
2100 (const :tag "End radio group" (:endgroup))
2101 (const :tag "New line" (:newline)))))
2103 (defcustom org-tag-persistent-alist nil
2104 "List of tags that will always appear in all Org-mode files.
2105 This is in addition to any in buffer settings or customizations
2106 of `org-tag-alist'.
2107 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2108 The value of this variable is an alist, the car of each entry must be a
2109 keyword as a string, the cdr may be a character that is used to select
2110 that tag through the fast-tag-selection interface.
2111 See the manual for details.
2112 To disable these tags on a per-file basis, insert anywhere in the file:
2113 #+STARTUP: noptag"
2114 :group 'org-tags
2115 :type '(repeat
2116 (choice
2117 (cons (string :tag "Tag name")
2118 (character :tag "Access char"))
2119 (const :tag "Start radio group" (:startgroup))
2120 (const :tag "End radio group" (:endgroup))
2121 (const :tag "New line" (:newline)))))
2123 (defvar org-file-tags nil
2124 "List of tags that can be inherited by all entries in the file.
2125 The tags will be inherited if the variable `org-use-tag-inheritance'
2126 says they should be.
2127 This variable is populated from #+TAG lines.")
2129 (defcustom org-use-fast-tag-selection 'auto
2130 "Non-nil means, use fast tag selection scheme.
2131 This is a special interface to select and deselect tags with single keys.
2132 When nil, fast selection is never used.
2133 When the symbol `auto', fast selection is used if and only if selection
2134 characters for tags have been configured, either through the variable
2135 `org-tag-alist' or through a #+TAGS line in the buffer.
2136 When t, fast selection is always used and selection keys are assigned
2137 automatically if necessary."
2138 :group 'org-tags
2139 :type '(choice
2140 (const :tag "Always" t)
2141 (const :tag "Never" nil)
2142 (const :tag "When selection characters are configured" 'auto)))
2144 (defcustom org-fast-tag-selection-single-key nil
2145 "Non-nil means, fast tag selection exits after first change.
2146 When nil, you have to press RET to exit it.
2147 During fast tag selection, you can toggle this flag with `C-c'.
2148 This variable can also have the value `expert'. In this case, the window
2149 displaying the tags menu is not even shown, until you press C-c again."
2150 :group 'org-tags
2151 :type '(choice
2152 (const :tag "No" nil)
2153 (const :tag "Yes" t)
2154 (const :tag "Expert" expert)))
2156 (defvar org-fast-tag-selection-include-todo nil
2157 "Non-nil means, fast tags selection interface will also offer TODO states.
2158 This is an undocumented feature, you should not rely on it.")
2160 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2161 "The column to which tags should be indented in a headline.
2162 If this number is positive, it specifies the column. If it is negative,
2163 it means that the tags should be flushright to that column. For example,
2164 -80 works well for a normal 80 character screen."
2165 :group 'org-tags
2166 :type 'integer)
2168 (defcustom org-auto-align-tags t
2169 "Non-nil means, realign tags after pro/demotion of TODO state change.
2170 These operations change the length of a headline and therefore shift
2171 the tags around. With this options turned on, after each such operation
2172 the tags are again aligned to `org-tags-column'."
2173 :group 'org-tags
2174 :type 'boolean)
2176 (defcustom org-use-tag-inheritance t
2177 "Non-nil means, tags in levels apply also for sublevels.
2178 When nil, only the tags directly given in a specific line apply there.
2179 This may also be a list of tags that should be inherited, or a regexp that
2180 matches tags that should be inherited. Additional control is possible
2181 with the variable `org-tags-exclude-from-inheritance' which gives an
2182 explicit list of tags to be excluded from inheritance., even if the value of
2183 `org-use-tag-inheritance' would select it for inheritance.
2185 If this option is t, a match early-on in a tree can lead to a large
2186 number of matches in the subtree when constructing the agenda or creating
2187 a sparse tree. If you only want to see the first match in a tree during
2188 a search, check out the variable `org-tags-match-list-sublevels'."
2189 :group 'org-tags
2190 :type '(choice
2191 (const :tag "Not" nil)
2192 (const :tag "Always" t)
2193 (repeat :tag "Specific tags" (string :tag "Tag"))
2194 (regexp :tag "Tags matched by regexp")))
2196 (defcustom org-tags-exclude-from-inheritance nil
2197 "List of tags that should never be inherited.
2198 This is a way to exclude a few tags from inheritance. For way to do
2199 the opposite, to actively allow inheritance for selected tags,
2200 see the variable `org-use-tag-inheritance'."
2201 :group 'org-tags
2202 :type '(repeat (string :tag "Tag")))
2204 (defun org-tag-inherit-p (tag)
2205 "Check if TAG is one that should be inherited."
2206 (cond
2207 ((member tag org-tags-exclude-from-inheritance) nil)
2208 ((eq org-use-tag-inheritance t) t)
2209 ((not org-use-tag-inheritance) nil)
2210 ((stringp org-use-tag-inheritance)
2211 (string-match org-use-tag-inheritance tag))
2212 ((listp org-use-tag-inheritance)
2213 (member tag org-use-tag-inheritance))
2214 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2216 (defcustom org-tags-match-list-sublevels t
2217 "Non-nil means list also sublevels of headlines matching tag search.
2218 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2219 the sublevels of a headline matching a tag search often also match
2220 the same search. Listing all of them can create very long lists.
2221 Setting this variable to nil causes subtrees of a match to be skipped.
2222 This option is off by default, because inheritance in on. If you turn
2223 inheritance off, you very likely want to turn this option on.
2225 As a special case, if the tag search is restricted to TODO items, the
2226 value of this variable is ignored and sublevels are always checked, to
2227 make sure all corresponding TODO items find their way into the list.
2229 This variable is semi-obsolete and probably should always be true. It
2230 is better to limit inheritance to certain tags using the variables
2231 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2232 :group 'org-tags
2233 :type 'boolean)
2235 (defvar org-tags-history nil
2236 "History of minibuffer reads for tags.")
2237 (defvar org-last-tags-completion-table nil
2238 "The last used completion table for tags.")
2239 (defvar org-after-tags-change-hook nil
2240 "Hook that is run after the tags in a line have changed.")
2242 (defgroup org-properties nil
2243 "Options concerning properties in Org-mode."
2244 :tag "Org Properties"
2245 :group 'org)
2247 (defcustom org-property-format "%-10s %s"
2248 "How property key/value pairs should be formatted by `indent-line'.
2249 When `indent-line' hits a property definition, it will format the line
2250 according to this format, mainly to make sure that the values are
2251 lined-up with respect to each other."
2252 :group 'org-properties
2253 :type 'string)
2255 (defcustom org-use-property-inheritance nil
2256 "Non-nil means, properties apply also for sublevels.
2258 This setting is chiefly used during property searches. Turning it on can
2259 cause significant overhead when doing a search, which is why it is not
2260 on by default.
2262 When nil, only the properties directly given in the current entry count.
2263 When t, every property is inherited. The value may also be a list of
2264 properties that should have inheritance, or a regular expression matching
2265 properties that should be inherited.
2267 However, note that some special properties use inheritance under special
2268 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2269 and the properties ending in \"_ALL\" when they are used as descriptor
2270 for valid values of a property.
2272 Note for programmers:
2273 When querying an entry with `org-entry-get', you can control if inheritance
2274 should be used. By default, `org-entry-get' looks only at the local
2275 properties. You can request inheritance by setting the inherit argument
2276 to t (to force inheritance) or to `selective' (to respect the setting
2277 in this variable)."
2278 :group 'org-properties
2279 :type '(choice
2280 (const :tag "Not" nil)
2281 (const :tag "Always" t)
2282 (repeat :tag "Specific properties" (string :tag "Property"))
2283 (regexp :tag "Properties matched by regexp")))
2285 (defun org-property-inherit-p (property)
2286 "Check if PROPERTY is one that should be inherited."
2287 (cond
2288 ((eq org-use-property-inheritance t) t)
2289 ((not org-use-property-inheritance) nil)
2290 ((stringp org-use-property-inheritance)
2291 (string-match org-use-property-inheritance property))
2292 ((listp org-use-property-inheritance)
2293 (member property org-use-property-inheritance))
2294 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2296 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2297 "The default column format, if no other format has been defined.
2298 This variable can be set on the per-file basis by inserting a line
2300 #+COLUMNS: %25ITEM ....."
2301 :group 'org-properties
2302 :type 'string)
2304 (defcustom org-columns-ellipses ".."
2305 "The ellipses to be used when a field in column view is truncated.
2306 When this is the empty string, as many characters as possible are shown,
2307 but then there will be no visual indication that the field has been truncated.
2308 When this is a string of length N, the last N characters of a truncated
2309 field are replaced by this string. If the column is narrower than the
2310 ellipses string, only part of the ellipses string will be shown."
2311 :group 'org-properties
2312 :type 'string)
2314 (defcustom org-columns-modify-value-for-display-function nil
2315 "Function that modifies values for display in column view.
2316 For example, it can be used to cut out a certain part from a time stamp.
2317 The function must take 2 arguments:
2319 column-title The title of the column (*not* the property name)
2320 value The value that should be modified.
2322 The function should return the value that should be displayed,
2323 or nil if the normal value should be used."
2324 :group 'org-properties
2325 :type 'function)
2327 (defcustom org-effort-property "Effort"
2328 "The property that is being used to keep track of effort estimates.
2329 Effort estimates given in this property need to have the format H:MM."
2330 :group 'org-properties
2331 :group 'org-progress
2332 :type '(string :tag "Property"))
2334 (defconst org-global-properties-fixed
2335 '(("VISIBILITY_ALL" . "folded children content all"))
2336 "List of property/value pairs that can be inherited by any entry.
2338 These are fixed values, for the preset properties. The user variable
2339 that can be used to add to this list is `org-global-properties'.
2341 The entries in this list are cons cells where the car is a property
2342 name and cdr is a string with the value. If the value represents
2343 multiple items like an \"_ALL\" property, separate the items by
2344 spaces.")
2346 (defcustom org-global-properties nil
2347 "List of property/value pairs that can be inherited by any entry.
2349 This list will be combined with the constant `org-global-properties-fixed'.
2351 The entries in this list are cons cells where the car is a property
2352 name and cdr is a string with the value.
2354 You can set buffer-local values for the same purpose in the variable
2355 `org-file-properties' this by adding lines like
2357 #+PROPERTY: NAME VALUE"
2358 :group 'org-properties
2359 :type '(repeat
2360 (cons (string :tag "Property")
2361 (string :tag "Value"))))
2363 (defvar org-file-properties nil
2364 "List of property/value pairs that can be inherited by any entry.
2365 Valid for the current buffer.
2366 This variable is populated from #+PROPERTY lines.")
2367 (make-variable-buffer-local 'org-file-properties)
2369 (defgroup org-agenda nil
2370 "Options concerning agenda views in Org-mode."
2371 :tag "Org Agenda"
2372 :group 'org)
2374 (defvar org-category nil
2375 "Variable used by org files to set a category for agenda display.
2376 Such files should use a file variable to set it, for example
2378 # -*- mode: org; org-category: \"ELisp\"
2380 or contain a special line
2382 #+CATEGORY: ELisp
2384 If the file does not specify a category, then file's base name
2385 is used instead.")
2386 (make-variable-buffer-local 'org-category)
2387 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2389 (defcustom org-agenda-files nil
2390 "The files to be used for agenda display.
2391 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2392 \\[org-remove-file]. You can also use customize to edit the list.
2394 If an entry is a directory, all files in that directory that are matched by
2395 `org-agenda-file-regexp' will be part of the file list.
2397 If the value of the variable is not a list but a single file name, then
2398 the list of agenda files is actually stored and maintained in that file, one
2399 agenda file per line."
2400 :group 'org-agenda
2401 :type '(choice
2402 (repeat :tag "List of files and directories" file)
2403 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2405 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2406 "Regular expression to match files for `org-agenda-files'.
2407 If any element in the list in that variable contains a directory instead
2408 of a normal file, all files in that directory that are matched by this
2409 regular expression will be included."
2410 :group 'org-agenda
2411 :type 'regexp)
2413 (defcustom org-agenda-text-search-extra-files nil
2414 "List of extra files to be searched by text search commands.
2415 These files will be search in addition to the agenda files by the
2416 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2417 Note that these files will only be searched for text search commands,
2418 not for the other agenda views like todo lists, tag searches or the weekly
2419 agenda. This variable is intended to list notes and possibly archive files
2420 that should also be searched by these two commands.
2421 In fact, if the first element in the list is the symbol `agenda-archives',
2422 than all archive files of all agenda files will be added to the search
2423 scope."
2424 :group 'org-agenda
2425 :type '(set :greedy t
2426 (const :tag "Agenda Archives" agenda-archives)
2427 (repeat :inline t (file))))
2429 (if (fboundp 'defvaralias)
2430 (defvaralias 'org-agenda-multi-occur-extra-files
2431 'org-agenda-text-search-extra-files))
2433 (defcustom org-agenda-skip-unavailable-files nil
2434 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2435 A nil value means to remove them, after a query, from the list."
2436 :group 'org-agenda
2437 :type 'boolean)
2439 (defcustom org-calendar-to-agenda-key [?c]
2440 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2441 The command `org-calendar-goto-agenda' will be bound to this key. The
2442 default is the character `c' because then `c' can be used to switch back and
2443 forth between agenda and calendar."
2444 :group 'org-agenda
2445 :type 'sexp)
2447 (defcustom org-calendar-agenda-action-key [?k]
2448 "The key to be installed in `calendar-mode-map' for agenda-action.
2449 The command `org-agenda-action' will be bound to this key. The
2450 default is the character `k' because we use the same key in the agenda."
2451 :group 'org-agenda
2452 :type 'sexp)
2454 (eval-after-load "calendar"
2455 '(progn
2456 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2457 'org-calendar-goto-agenda)
2458 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2459 'org-agenda-action)))
2461 (defgroup org-latex nil
2462 "Options for embedding LaTeX code into Org-mode."
2463 :tag "Org LaTeX"
2464 :group 'org)
2466 (defcustom org-format-latex-options
2467 '(:foreground default :background default :scale 1.0
2468 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2469 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2470 "Options for creating images from LaTeX fragments.
2471 This is a property list with the following properties:
2472 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2473 `default' means use the foreground of the default face.
2474 :background the background color, or \"Transparent\".
2475 `default' means use the background of the default face.
2476 :scale a scaling factor for the size of the images.
2477 :html-foreground, :html-background, :html-scale
2478 the same numbers for HTML export.
2479 :matchers a list indicating which matchers should be used to
2480 find LaTeX fragments. Valid members of this list are:
2481 \"begin\" find environments
2482 \"$1\" find single characters surrounded by $.$
2483 \"$\" find math expressions surrounded by $...$
2484 \"$$\" find math expressions surrounded by $$....$$
2485 \"\\(\" find math expressions surrounded by \\(...\\)
2486 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2487 :group 'org-latex
2488 :type 'plist)
2490 (defcustom org-format-latex-header "\\documentclass{article}
2491 \\usepackage{fullpage} % do not remove
2492 \\usepackage{amssymb}
2493 \\usepackage[usenames]{color}
2494 \\usepackage{amsmath}
2495 \\usepackage{latexsym}
2496 \\usepackage[mathscr]{eucal}
2497 \\pagestyle{empty} % do not remove"
2498 "The document header used for processing LaTeX fragments."
2499 :group 'org-latex
2500 :type 'string)
2503 (defgroup org-font-lock nil
2504 "Font-lock settings for highlighting in Org-mode."
2505 :tag "Org Font Lock"
2506 :group 'org)
2508 (defcustom org-level-color-stars-only nil
2509 "Non-nil means fontify only the stars in each headline.
2510 When nil, the entire headline is fontified.
2511 Changing it requires restart of `font-lock-mode' to become effective
2512 also in regions already fontified."
2513 :group 'org-font-lock
2514 :type 'boolean)
2516 (defcustom org-hide-leading-stars nil
2517 "Non-nil means, hide the first N-1 stars in a headline.
2518 This works by using the face `org-hide' for these stars. This
2519 face is white for a light background, and black for a dark
2520 background. You may have to customize the face `org-hide' to
2521 make this work.
2522 Changing it requires restart of `font-lock-mode' to become effective
2523 also in regions already fontified.
2524 You may also set this on a per-file basis by adding one of the following
2525 lines to the buffer:
2527 #+STARTUP: hidestars
2528 #+STARTUP: showstars"
2529 :group 'org-font-lock
2530 :type 'boolean)
2532 (defcustom org-fontify-done-headline nil
2533 "Non-nil means, change the face of a headline if it is marked DONE.
2534 Normally, only the TODO/DONE keyword indicates the state of a headline.
2535 When this is non-nil, the headline after the keyword is set to the
2536 `org-headline-done' as an additional indication."
2537 :group 'org-font-lock
2538 :type 'boolean)
2540 (defcustom org-fontify-emphasized-text t
2541 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2542 Changing this variable requires a restart of Emacs to take effect."
2543 :group 'org-font-lock
2544 :type 'boolean)
2546 (defcustom org-highlight-latex-fragments-and-specials nil
2547 "Non-nil means, fontify what is treated specially by the exporters."
2548 :group 'org-font-lock
2549 :type 'boolean)
2551 (defcustom org-hide-emphasis-markers nil
2552 "Non-nil mean font-lock should hide the emphasis marker characters."
2553 :group 'org-font-lock
2554 :type 'boolean)
2556 (defvar org-emph-re nil
2557 "Regular expression for matching emphasis.")
2558 (defvar org-verbatim-re nil
2559 "Regular expression for matching verbatim text.")
2560 (defvar org-emphasis-regexp-components) ; defined just below
2561 (defvar org-emphasis-alist) ; defined just below
2562 (defun org-set-emph-re (var val)
2563 "Set variable and compute the emphasis regular expression."
2564 (set var val)
2565 (when (and (boundp 'org-emphasis-alist)
2566 (boundp 'org-emphasis-regexp-components)
2567 org-emphasis-alist org-emphasis-regexp-components)
2568 (let* ((e org-emphasis-regexp-components)
2569 (pre (car e))
2570 (post (nth 1 e))
2571 (border (nth 2 e))
2572 (body (nth 3 e))
2573 (nl (nth 4 e))
2574 (body1 (concat body "*?"))
2575 (markers (mapconcat 'car org-emphasis-alist ""))
2576 (vmarkers (mapconcat
2577 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2578 org-emphasis-alist "")))
2579 ;; make sure special characters appear at the right position in the class
2580 (if (string-match "\\^" markers)
2581 (setq markers (concat (replace-match "" t t markers) "^")))
2582 (if (string-match "-" markers)
2583 (setq markers (concat (replace-match "" t t markers) "-")))
2584 (if (string-match "\\^" vmarkers)
2585 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2586 (if (string-match "-" vmarkers)
2587 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2588 (if (> nl 0)
2589 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2590 (int-to-string nl) "\\}")))
2591 ;; Make the regexp
2592 (setq org-emph-re
2593 (concat "\\([" pre "]\\|^\\)"
2594 "\\("
2595 "\\([" markers "]\\)"
2596 "\\("
2597 "[^" border "]\\|"
2598 "[^" border "]"
2599 body1
2600 "[^" border "]"
2601 "\\)"
2602 "\\3\\)"
2603 "\\([" post "]\\|$\\)"))
2604 (setq org-verbatim-re
2605 (concat "\\([" pre "]\\|^\\)"
2606 "\\("
2607 "\\([" vmarkers "]\\)"
2608 "\\("
2609 "[^" border "]\\|"
2610 "[^" border "]"
2611 body1
2612 "[^" border "]"
2613 "\\)"
2614 "\\3\\)"
2615 "\\([" post "]\\|$\\)")))))
2617 (defcustom org-emphasis-regexp-components
2618 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2619 "Components used to build the regular expression for emphasis.
2620 This is a list with 6 entries. Terminology: In an emphasis string
2621 like \" *strong word* \", we call the initial space PREMATCH, the final
2622 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2623 and \"trong wor\" is the body. The different components in this variable
2624 specify what is allowed/forbidden in each part:
2626 pre Chars allowed as prematch. Beginning of line will be allowed too.
2627 post Chars allowed as postmatch. End of line will be allowed too.
2628 border The chars *forbidden* as border characters.
2629 body-regexp A regexp like \".\" to match a body character. Don't use
2630 non-shy groups here, and don't allow newline here.
2631 newline The maximum number of newlines allowed in an emphasis exp.
2633 Use customize to modify this, or restart Emacs after changing it."
2634 :group 'org-font-lock
2635 :set 'org-set-emph-re
2636 :type '(list
2637 (sexp :tag "Allowed chars in pre ")
2638 (sexp :tag "Allowed chars in post ")
2639 (sexp :tag "Forbidden chars in border ")
2640 (sexp :tag "Regexp for body ")
2641 (integer :tag "number of newlines allowed")
2642 (option (boolean :tag "Please ignore this button"))))
2644 (defcustom org-emphasis-alist
2645 `(("*" bold "<b>" "</b>")
2646 ("/" italic "<i>" "</i>")
2647 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2648 ("=" org-code "<code>" "</code>" verbatim)
2649 ("~" org-verbatim "<code>" "</code>" verbatim)
2650 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2651 "<del>" "</del>")
2653 "Special syntax for emphasized text.
2654 Text starting and ending with a special character will be emphasized, for
2655 example *bold*, _underlined_ and /italic/. This variable sets the marker
2656 characters, the face to be used by font-lock for highlighting in Org-mode
2657 Emacs buffers, and the HTML tags to be used for this.
2658 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2659 Use customize to modify this, or restart Emacs after changing it."
2660 :group 'org-font-lock
2661 :set 'org-set-emph-re
2662 :type '(repeat
2663 (list
2664 (string :tag "Marker character")
2665 (choice
2666 (face :tag "Font-lock-face")
2667 (plist :tag "Face property list"))
2668 (string :tag "HTML start tag")
2669 (string :tag "HTML end tag")
2670 (option (const verbatim)))))
2672 ;;; Miscellaneous options
2674 (defgroup org-completion nil
2675 "Completion in Org-mode."
2676 :tag "Org Completion"
2677 :group 'org)
2679 (defcustom org-completion-use-ido nil
2680 "Non-nil means, use ido completion wherever possible.
2681 Note that `ido-mode' must be active for this variable to be relevant.
2682 If you decide to turn this variable on, you might well want to turn off
2683 `org-outline-path-complete-in-steps'."
2684 :group 'org-completion
2685 :type 'boolean)
2687 (defcustom org-completion-fallback-command 'hippie-expand
2688 "The expansion command called by \\[org-complete] in normal context.
2689 Normal means, no org-mode-specific context."
2690 :group 'org-completion
2691 :type 'function)
2693 ;;; Functions and variables from ther packages
2694 ;; Declared here to avoid compiler warnings
2696 ;; XEmacs only
2697 (defvar outline-mode-menu-heading)
2698 (defvar outline-mode-menu-show)
2699 (defvar outline-mode-menu-hide)
2700 (defvar zmacs-regions) ; XEmacs regions
2702 ;; Emacs only
2703 (defvar mark-active)
2705 ;; Various packages
2706 (declare-function find-library-name "find-func" (library))
2707 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2708 (declare-function calendar-forward-day "cal-move" (arg))
2709 (declare-function calendar-goto-date "cal-move" (date))
2710 (declare-function calendar-goto-today "cal-move" ())
2711 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2712 (defvar calc-embedded-close-formula)
2713 (defvar calc-embedded-open-formula)
2714 (declare-function cdlatex-tab "ext:cdlatex" ())
2715 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2716 (defvar font-lock-unfontify-region-function)
2717 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2718 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2719 (defvar iswitchb-temp-buflist)
2720 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2721 (defvar org-agenda-tags-todo-honor-ignore-options)
2722 (declare-function org-agenda-skip "org-agenda" ())
2723 (declare-function org-format-agenda-item "org-agenda"
2724 (extra txt &optional category tags dotime noprefix remove-re))
2725 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2726 (declare-function org-agenda-change-all-lines "org-agenda"
2727 (newhead hdmarker &optional fixface just-this))
2728 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2729 (declare-function org-agenda-maybe-redo "org-agenda" ())
2730 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2731 (beg end))
2732 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2733 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2734 "org-agenda" (&optional end))
2736 (declare-function parse-time-string "parse-time" (string))
2737 (declare-function remember "remember" (&optional initial))
2738 (declare-function remember-buffer-desc "remember" ())
2739 (declare-function remember-finalize "remember" ())
2740 (defvar remember-save-after-remembering)
2741 (defvar remember-data-file)
2742 (defvar remember-register)
2743 (defvar remember-buffer)
2744 (defvar remember-handler-functions)
2745 (defvar remember-annotation-functions)
2746 (defvar texmathp-why)
2747 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2748 (declare-function table--at-cell-p "table" (position &optional object at-column))
2750 (defvar w3m-current-url)
2751 (defvar w3m-current-title)
2753 (defvar org-latex-regexps)
2755 ;;; Autoload and prepare some org modules
2757 ;; Some table stuff that needs to be defined here, because it is used
2758 ;; by the functions setting up org-mode or checking for table context.
2760 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2761 "Detects an org-type or table-type table.")
2762 (defconst org-table-line-regexp "^[ \t]*|"
2763 "Detects an org-type table line.")
2764 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2765 "Detects an org-type table line.")
2766 (defconst org-table-hline-regexp "^[ \t]*|-"
2767 "Detects an org-type table hline.")
2768 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2769 "Detects a table-type table hline.")
2770 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2771 "Searching from within a table (any type) this finds the first line
2772 outside the table.")
2774 ;; Autoload the functions in org-table.el that are needed by functions here.
2776 (eval-and-compile
2777 (org-autoload "org-table"
2778 '(org-table-align org-table-begin org-table-blank-field
2779 org-table-convert org-table-convert-region org-table-copy-down
2780 org-table-copy-region org-table-create
2781 org-table-create-or-convert-from-region
2782 org-table-create-with-table.el org-table-current-dline
2783 org-table-cut-region org-table-delete-column org-table-edit-field
2784 org-table-edit-formulas org-table-end org-table-eval-formula
2785 org-table-export org-table-field-info
2786 org-table-get-stored-formulas org-table-goto-column
2787 org-table-hline-and-move org-table-import org-table-insert-column
2788 org-table-insert-hline org-table-insert-row org-table-iterate
2789 org-table-justify-field-maybe org-table-kill-row
2790 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2791 org-table-move-column org-table-move-column-left
2792 org-table-move-column-right org-table-move-row
2793 org-table-move-row-down org-table-move-row-up
2794 org-table-next-field org-table-next-row org-table-paste-rectangle
2795 org-table-previous-field org-table-recalculate
2796 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2797 org-table-toggle-coordinate-overlays
2798 org-table-toggle-formula-debugger org-table-wrap-region
2799 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2801 (defun org-at-table-p (&optional table-type)
2802 "Return t if the cursor is inside an org-type table.
2803 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2804 (if org-enable-table-editor
2805 (save-excursion
2806 (beginning-of-line 1)
2807 (looking-at (if table-type org-table-any-line-regexp
2808 org-table-line-regexp)))
2809 nil))
2810 (defsubst org-table-p () (org-at-table-p))
2812 (defun org-at-table.el-p ()
2813 "Return t if and only if we are at a table.el table."
2814 (and (org-at-table-p 'any)
2815 (save-excursion
2816 (goto-char (org-table-begin 'any))
2817 (looking-at org-table1-hline-regexp))))
2818 (defun org-table-recognize-table.el ()
2819 "If there is a table.el table nearby, recognize it and move into it."
2820 (if org-table-tab-recognizes-table.el
2821 (if (org-at-table.el-p)
2822 (progn
2823 (beginning-of-line 1)
2824 (if (looking-at org-table-dataline-regexp)
2826 (if (looking-at org-table1-hline-regexp)
2827 (progn
2828 (beginning-of-line 2)
2829 (if (looking-at org-table-any-border-regexp)
2830 (beginning-of-line -1)))))
2831 (if (re-search-forward "|" (org-table-end t) t)
2832 (progn
2833 (require 'table)
2834 (if (table--at-cell-p (point))
2836 (message "recognizing table.el table...")
2837 (table-recognize-table)
2838 (message "recognizing table.el table...done")))
2839 (error "This should not happen..."))
2841 nil)
2842 nil))
2844 (defun org-at-table-hline-p ()
2845 "Return t if the cursor is inside a hline in a table."
2846 (if org-enable-table-editor
2847 (save-excursion
2848 (beginning-of-line 1)
2849 (looking-at org-table-hline-regexp))
2850 nil))
2852 (defvar org-table-clean-did-remove-column nil)
2854 (defun org-table-map-tables (function)
2855 "Apply FUNCTION to the start of all tables in the buffer."
2856 (save-excursion
2857 (save-restriction
2858 (widen)
2859 (goto-char (point-min))
2860 (while (re-search-forward org-table-any-line-regexp nil t)
2861 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2862 (beginning-of-line 1)
2863 (if (looking-at org-table-line-regexp)
2864 (save-excursion (funcall function)))
2865 (re-search-forward org-table-any-border-regexp nil 1))))
2866 (message "Mapping tables: done"))
2868 ;; Declare and autoload functions from org-exp.el
2870 (declare-function org-default-export-plist "org-exp")
2871 (declare-function org-infile-export-plist "org-exp")
2872 (declare-function org-get-current-options "org-exp")
2873 (eval-and-compile
2874 (org-autoload "org-exp"
2875 '(org-export org-export-as-ascii org-export-visible
2876 org-insert-export-options-template org-export-as-html-and-open
2877 org-export-as-html-batch org-export-as-html-to-buffer
2878 org-replace-region-by-html org-export-region-as-html
2879 org-export-as-html org-export-icalendar-this-file
2880 org-export-icalendar-all-agenda-files
2881 org-table-clean-before-export
2882 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2884 ;; Declare and autoload functions from org-agenda.el
2886 (eval-and-compile
2887 (org-autoload "org-agenda"
2888 '(org-agenda org-agenda-list org-search-view
2889 org-todo-list org-tags-view org-agenda-list-stuck-projects
2890 org-diary org-agenda-to-appt
2891 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2893 ;; Autoload org-remember
2895 (eval-and-compile
2896 (org-autoload "org-remember"
2897 '(org-remember-insinuate org-remember-annotation
2898 org-remember-apply-template org-remember org-remember-handler)))
2900 ;; Autoload org-clock.el
2903 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2904 (beg end))
2905 (declare-function org-clock-update-mode-line "org-clock" ())
2906 (defvar org-clock-start-time)
2907 (defvar org-clock-marker (make-marker)
2908 "Marker recording the last clock-in.")
2910 (eval-and-compile
2911 (org-autoload
2912 "org-clock"
2913 '(org-clock-in org-clock-out org-clock-cancel
2914 org-clock-goto org-clock-sum org-clock-display
2915 org-clock-remove-overlays org-clock-report
2916 org-clocktable-shift org-dblock-write:clocktable
2917 org-get-clocktable)))
2919 (defun org-clock-update-time-maybe ()
2920 "If this is a CLOCK line, update it and return t.
2921 Otherwise, return nil."
2922 (interactive)
2923 (save-excursion
2924 (beginning-of-line 1)
2925 (skip-chars-forward " \t")
2926 (when (looking-at org-clock-string)
2927 (let ((re (concat "[ \t]*" org-clock-string
2928 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2929 "\\([ \t]*=>.*\\)?\\)?"))
2930 ts te h m s neg)
2931 (cond
2932 ((not (looking-at re))
2933 nil)
2934 ((not (match-end 2))
2935 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2936 (> org-clock-marker (point))
2937 (<= org-clock-marker (point-at-eol)))
2938 ;; The clock is running here
2939 (setq org-clock-start-time
2940 (apply 'encode-time
2941 (org-parse-time-string (match-string 1))))
2942 (org-clock-update-mode-line)))
2944 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2945 (end-of-line 1)
2946 (setq ts (match-string 1)
2947 te (match-string 3))
2948 (setq s (- (time-to-seconds
2949 (apply 'encode-time (org-parse-time-string te)))
2950 (time-to-seconds
2951 (apply 'encode-time (org-parse-time-string ts))))
2952 neg (< s 0)
2953 s (abs s)
2954 h (floor (/ s 3600))
2955 s (- s (* 3600 h))
2956 m (floor (/ s 60))
2957 s (- s (* 60 s)))
2958 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2959 t))))))
2961 (defun org-check-running-clock ()
2962 "Check if the current buffer contains the running clock.
2963 If yes, offer to stop it and to save the buffer with the changes."
2964 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2965 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2966 (buffer-name))))
2967 (org-clock-out)
2968 (when (y-or-n-p "Save changed buffer?")
2969 (save-buffer))))
2971 (defun org-clocktable-try-shift (dir n)
2972 "Check if this line starts a clock table, if yes, shift the time block."
2973 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2974 (org-clocktable-shift dir n)))
2976 ;; Autoload org-timer.el
2978 ;(declare-function org-timer "org-timer")
2980 (eval-and-compile
2981 (org-autoload
2982 "org-timer"
2983 '(org-timer-start org-timer org-timer-item
2984 org-timer-change-times-in-region)))
2987 ;; Autoload archiving code
2988 ;; The stuff that is needed for cycling and tags has to be defined here.
2990 (defgroup org-archive nil
2991 "Options concerning archiving in Org-mode."
2992 :tag "Org Archive"
2993 :group 'org-structure)
2995 (defcustom org-archive-location "%s_archive::"
2996 "The location where subtrees should be archived.
2998 The value of this variable is a string, consisting of two parts,
2999 separated by a double-colon. The first part is a filename and
3000 the second part is a headline.
3002 When the filename is omitted, archiving happens in the same file.
3003 %s in the filename will be replaced by the current file
3004 name (without the directory part). Archiving to a different file
3005 is useful to keep archived entries from contributing to the
3006 Org-mode Agenda.
3008 The archived entries will be filed as subtrees of the specified
3009 headline. When the headline is omitted, the subtrees are simply
3010 filed away at the end of the file, as top-level entries. Also in
3011 the heading you can use %s to represent the file name, this can be
3012 useful when using the same archive for a number of different files.
3014 Here are a few examples:
3015 \"%s_archive::\"
3016 If the current file is Projects.org, archive in file
3017 Projects.org_archive, as top-level trees. This is the default.
3019 \"::* Archived Tasks\"
3020 Archive in the current file, under the top-level headline
3021 \"* Archived Tasks\".
3023 \"~/org/archive.org::\"
3024 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3026 \"~/org/archive.org::From %s\"
3027 Archive in file ~/org/archive.org (absolute path), und headlines
3028 \"From FILENAME\" where file name is the current file name.
3030 \"basement::** Finished Tasks\"
3031 Archive in file ./basement (relative path), as level 3 trees
3032 below the level 2 heading \"** Finished Tasks\".
3034 You may set this option on a per-file basis by adding to the buffer a
3035 line like
3037 #+ARCHIVE: basement::** Finished Tasks
3039 You may also define it locally for a subtree by setting an ARCHIVE property
3040 in the entry. If such a property is found in an entry, or anywhere up
3041 the hierarchy, it will be used."
3042 :group 'org-archive
3043 :type 'string)
3045 (defcustom org-archive-tag "ARCHIVE"
3046 "The tag that marks a subtree as archived.
3047 An archived subtree does not open during visibility cycling, and does
3048 not contribute to the agenda listings.
3049 After changing this, font-lock must be restarted in the relevant buffers to
3050 get the proper fontification."
3051 :group 'org-archive
3052 :group 'org-keywords
3053 :type 'string)
3055 (defcustom org-agenda-skip-archived-trees t
3056 "Non-nil means, the agenda will skip any items located in archived trees.
3057 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3058 variable is no longer recommended, you should leave it at the value t.
3059 Instead, use the key `v' to cycle the archives-mode in the agenda."
3060 :group 'org-archive
3061 :group 'org-agenda-skip
3062 :type 'boolean)
3064 (defcustom org-cycle-open-archived-trees nil
3065 "Non-nil means, `org-cycle' will open archived trees.
3066 An archived tree is a tree marked with the tag ARCHIVE.
3067 When nil, archived trees will stay folded. You can still open them with
3068 normal outline commands like `show-all', but not with the cycling commands."
3069 :group 'org-archive
3070 :group 'org-cycle
3071 :type 'boolean)
3073 (defcustom org-sparse-tree-open-archived-trees nil
3074 "Non-nil means sparse tree construction shows matches in archived trees.
3075 When nil, matches in these trees are highlighted, but the trees are kept in
3076 collapsed state."
3077 :group 'org-archive
3078 :group 'org-sparse-trees
3079 :type 'boolean)
3081 (defun org-cycle-hide-archived-subtrees (state)
3082 "Re-hide all archived subtrees after a visibility state change."
3083 (when (and (not org-cycle-open-archived-trees)
3084 (not (memq state '(overview folded))))
3085 (save-excursion
3086 (let* ((globalp (memq state '(contents all)))
3087 (beg (if globalp (point-min) (point)))
3088 (end (if globalp (point-max) (org-end-of-subtree t))))
3089 (org-hide-archived-subtrees beg end)
3090 (goto-char beg)
3091 (if (looking-at (concat ".*:" org-archive-tag ":"))
3092 (message "%s" (substitute-command-keys
3093 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3095 (defun org-force-cycle-archived ()
3096 "Cycle subtree even if it is archived."
3097 (interactive)
3098 (setq this-command 'org-cycle)
3099 (let ((org-cycle-open-archived-trees t))
3100 (call-interactively 'org-cycle)))
3102 (defun org-hide-archived-subtrees (beg end)
3103 "Re-hide all archived subtrees after a visibility state change."
3104 (save-excursion
3105 (let* ((re (concat ":" org-archive-tag ":")))
3106 (goto-char beg)
3107 (while (re-search-forward re end t)
3108 (and (org-on-heading-p) (hide-subtree))
3109 (org-end-of-subtree t)))))
3111 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3113 (eval-and-compile
3114 (org-autoload "org-archive"
3115 '(org-add-archive-files org-archive-subtree
3116 org-archive-to-archive-sibling org-toggle-archive-tag)))
3118 ;; Autoload Column View Code
3120 (declare-function org-columns-number-to-string "org-colview")
3121 (declare-function org-columns-get-format-and-top-level "org-colview")
3122 (declare-function org-columns-compute "org-colview")
3124 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3125 '(org-columns-number-to-string org-columns-get-format-and-top-level
3126 org-columns-compute org-agenda-columns org-columns-remove-overlays
3127 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3129 ;; Autoload ID code
3131 (declare-function org-id-store-link "org-id")
3132 (declare-function org-id-locations-load "org-id")
3133 (declare-function org-id-locations-save "org-id")
3134 (defvar org-id-track-globally)
3135 (org-autoload "org-id"
3136 '(org-id-get-create org-id-new org-id-copy org-id-get
3137 org-id-get-with-outline-path-completion
3138 org-id-get-with-outline-drilling
3139 org-id-goto org-id-find org-id-store-link))
3141 ;; Autoload Plotting Code
3143 (org-autoload "org-plot"
3144 '(org-plot/gnuplot))
3146 ;;; Variables for pre-computed regular expressions, all buffer local
3148 (defvar org-drawer-regexp nil
3149 "Matches first line of a hidden block.")
3150 (make-variable-buffer-local 'org-drawer-regexp)
3151 (defvar org-todo-regexp nil
3152 "Matches any of the TODO state keywords.")
3153 (make-variable-buffer-local 'org-todo-regexp)
3154 (defvar org-not-done-regexp nil
3155 "Matches any of the TODO state keywords except the last one.")
3156 (make-variable-buffer-local 'org-not-done-regexp)
3157 (defvar org-todo-line-regexp nil
3158 "Matches a headline and puts TODO state into group 2 if present.")
3159 (make-variable-buffer-local 'org-todo-line-regexp)
3160 (defvar org-complex-heading-regexp nil
3161 "Matches a headline and puts everything into groups:
3162 group 1: the stars
3163 group 2: The todo keyword, maybe
3164 group 3: Priority cookie
3165 group 4: True headline
3166 group 5: Tags")
3167 (make-variable-buffer-local 'org-complex-heading-regexp)
3168 (defvar org-todo-line-tags-regexp nil
3169 "Matches a headline and puts TODO state into group 2 if present.
3170 Also put tags into group 4 if tags are present.")
3171 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3172 (defvar org-nl-done-regexp nil
3173 "Matches newline followed by a headline with the DONE keyword.")
3174 (make-variable-buffer-local 'org-nl-done-regexp)
3175 (defvar org-looking-at-done-regexp nil
3176 "Matches the DONE keyword a point.")
3177 (make-variable-buffer-local 'org-looking-at-done-regexp)
3178 (defvar org-ds-keyword-length 12
3179 "Maximum length of the Deadline and SCHEDULED keywords.")
3180 (make-variable-buffer-local 'org-ds-keyword-length)
3181 (defvar org-deadline-regexp nil
3182 "Matches the DEADLINE keyword.")
3183 (make-variable-buffer-local 'org-deadline-regexp)
3184 (defvar org-deadline-time-regexp nil
3185 "Matches the DEADLINE keyword together with a time stamp.")
3186 (make-variable-buffer-local 'org-deadline-time-regexp)
3187 (defvar org-deadline-line-regexp nil
3188 "Matches the DEADLINE keyword and the rest of the line.")
3189 (make-variable-buffer-local 'org-deadline-line-regexp)
3190 (defvar org-scheduled-regexp nil
3191 "Matches the SCHEDULED keyword.")
3192 (make-variable-buffer-local 'org-scheduled-regexp)
3193 (defvar org-scheduled-time-regexp nil
3194 "Matches the SCHEDULED keyword together with a time stamp.")
3195 (make-variable-buffer-local 'org-scheduled-time-regexp)
3196 (defvar org-closed-time-regexp nil
3197 "Matches the CLOSED keyword together with a time stamp.")
3198 (make-variable-buffer-local 'org-closed-time-regexp)
3200 (defvar org-keyword-time-regexp nil
3201 "Matches any of the 4 keywords, together with the time stamp.")
3202 (make-variable-buffer-local 'org-keyword-time-regexp)
3203 (defvar org-keyword-time-not-clock-regexp nil
3204 "Matches any of the 3 keywords, together with the time stamp.")
3205 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3206 (defvar org-maybe-keyword-time-regexp nil
3207 "Matches a timestamp, possibly preceeded by a keyword.")
3208 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3209 (defvar org-planning-or-clock-line-re nil
3210 "Matches a line with planning or clock info.")
3211 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3213 (defconst org-plain-time-of-day-regexp
3214 (concat
3215 "\\(\\<[012]?[0-9]"
3216 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3217 "\\(--?"
3218 "\\(\\<[012]?[0-9]"
3219 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3220 "\\)?")
3221 "Regular expression to match a plain time or time range.
3222 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3223 groups carry important information:
3224 0 the full match
3225 1 the first time, range or not
3226 8 the second time, if it is a range.")
3228 (defconst org-plain-time-extension-regexp
3229 (concat
3230 "\\(\\<[012]?[0-9]"
3231 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3232 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3233 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3234 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3235 groups carry important information:
3236 0 the full match
3237 7 hours of duration
3238 9 minutes of duration")
3240 (defconst org-stamp-time-of-day-regexp
3241 (concat
3242 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3243 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3244 "\\(--?"
3245 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3246 "Regular expression to match a timestamp time or time range.
3247 After a match, the following groups carry important information:
3248 0 the full match
3249 1 date plus weekday, for backreferencing to make sure both times on same day
3250 2 the first time, range or not
3251 4 the second time, if it is a range.")
3253 (defconst org-startup-options
3254 '(("fold" org-startup-folded t)
3255 ("overview" org-startup-folded t)
3256 ("nofold" org-startup-folded nil)
3257 ("showall" org-startup-folded nil)
3258 ("content" org-startup-folded content)
3259 ("hidestars" org-hide-leading-stars t)
3260 ("showstars" org-hide-leading-stars nil)
3261 ("odd" org-odd-levels-only t)
3262 ("oddeven" org-odd-levels-only nil)
3263 ("align" org-startup-align-all-tables t)
3264 ("noalign" org-startup-align-all-tables nil)
3265 ("customtime" org-display-custom-times t)
3266 ("logdone" org-log-done time)
3267 ("lognotedone" org-log-done note)
3268 ("nologdone" org-log-done nil)
3269 ("lognoteclock-out" org-log-note-clock-out t)
3270 ("nolognoteclock-out" org-log-note-clock-out nil)
3271 ("logrepeat" org-log-repeat state)
3272 ("lognoterepeat" org-log-repeat note)
3273 ("nologrepeat" org-log-repeat nil)
3274 ("fninline" org-footnote-define-inline t)
3275 ("nofninline" org-footnote-define-inline nil)
3276 ("fnlocal" org-footnote-section nil)
3277 ("fnauto" org-footnote-auto-label t)
3278 ("fnprompt" org-footnote-auto-label nil)
3279 ("fnconfirm" org-footnote-auto-label confirm)
3280 ("fnplain" org-footnote-auto-label plain)
3281 ("constcgs" constants-unit-system cgs)
3282 ("constSI" constants-unit-system SI)
3283 ("noptag" org-tag-persistent-alist nil))
3284 "Variable associated with STARTUP options for org-mode.
3285 Each element is a list of three items: The startup options as written
3286 in the #+STARTUP line, the corresponding variable, and the value to
3287 set this variable to if the option is found. An optional forth element PUSH
3288 means to push this value onto the list in the variable.")
3290 (defun org-set-regexps-and-options ()
3291 "Precompute regular expressions for current buffer."
3292 (when (org-mode-p)
3293 (org-set-local 'org-todo-kwd-alist nil)
3294 (org-set-local 'org-todo-key-alist nil)
3295 (org-set-local 'org-todo-key-trigger nil)
3296 (org-set-local 'org-todo-keywords-1 nil)
3297 (org-set-local 'org-done-keywords nil)
3298 (org-set-local 'org-todo-heads nil)
3299 (org-set-local 'org-todo-sets nil)
3300 (org-set-local 'org-todo-log-states nil)
3301 (org-set-local 'org-file-properties nil)
3302 (org-set-local 'org-file-tags nil)
3303 (let ((re (org-make-options-regexp
3304 '("CATEGORY" "TODO" "COLUMNS"
3305 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3306 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3307 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3308 (splitre "[ \t]+")
3309 kwds kws0 kwsa key log value cat arch tags const links hw dws
3310 tail sep kws1 prio props ftags drawers
3311 ext-setup-or-nil setup-contents (start 0))
3312 (save-excursion
3313 (save-restriction
3314 (widen)
3315 (goto-char (point-min))
3316 (while (or (and ext-setup-or-nil
3317 (string-match re ext-setup-or-nil start)
3318 (setq start (match-end 0)))
3319 (and (setq ext-setup-or-nil nil start 0)
3320 (re-search-forward re nil t)))
3321 (setq key (upcase (match-string 1 ext-setup-or-nil))
3322 value (org-match-string-no-properties 2 ext-setup-or-nil))
3323 (cond
3324 ((equal key "CATEGORY")
3325 (if (string-match "[ \t]+$" value)
3326 (setq value (replace-match "" t t value)))
3327 (setq cat value))
3328 ((member key '("SEQ_TODO" "TODO"))
3329 (push (cons 'sequence (org-split-string value splitre)) kwds))
3330 ((equal key "TYP_TODO")
3331 (push (cons 'type (org-split-string value splitre)) kwds))
3332 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3333 ;; general TODO-like setup
3334 (push (cons (intern (downcase (match-string 1 key)))
3335 (org-split-string value splitre)) kwds))
3336 ((equal key "TAGS")
3337 (setq tags (append tags (if tags '("\\n") nil)
3338 (org-split-string value splitre))))
3339 ((equal key "COLUMNS")
3340 (org-set-local 'org-columns-default-format value))
3341 ((equal key "LINK")
3342 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3343 (push (cons (match-string 1 value)
3344 (org-trim (match-string 2 value)))
3345 links)))
3346 ((equal key "PRIORITIES")
3347 (setq prio (org-split-string value " +")))
3348 ((equal key "PROPERTY")
3349 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3350 (push (cons (match-string 1 value) (match-string 2 value))
3351 props)))
3352 ((equal key "FILETAGS")
3353 (when (string-match "\\S-" value)
3354 (setq ftags
3355 (append
3356 ftags
3357 (apply 'append
3358 (mapcar (lambda (x) (org-split-string x ":"))
3359 (org-split-string value)))))))
3360 ((equal key "DRAWERS")
3361 (setq drawers (org-split-string value splitre)))
3362 ((equal key "CONSTANTS")
3363 (setq const (append const (org-split-string value splitre))))
3364 ((equal key "STARTUP")
3365 (let ((opts (org-split-string value splitre))
3366 l var val)
3367 (while (setq l (pop opts))
3368 (when (setq l (assoc l org-startup-options))
3369 (setq var (nth 1 l) val (nth 2 l))
3370 (if (not (nth 3 l))
3371 (set (make-local-variable var) val)
3372 (if (not (listp (symbol-value var)))
3373 (set (make-local-variable var) nil))
3374 (set (make-local-variable var) (symbol-value var))
3375 (add-to-list var val))))))
3376 ((equal key "ARCHIVE")
3377 (string-match " *$" value)
3378 (setq arch (replace-match "" t t value))
3379 (remove-text-properties 0 (length arch)
3380 '(face t fontified t) arch))
3381 ((equal key "SETUPFILE")
3382 (setq setup-contents (org-file-contents
3383 (expand-file-name
3384 (org-remove-double-quotes value))
3385 'noerror))
3386 (if (not ext-setup-or-nil)
3387 (setq ext-setup-or-nil setup-contents start 0)
3388 (setq ext-setup-or-nil
3389 (concat (substring ext-setup-or-nil 0 start)
3390 "\n" setup-contents "\n"
3391 (substring ext-setup-or-nil start)))))
3392 ))))
3393 (when cat
3394 (org-set-local 'org-category (intern cat))
3395 (push (cons "CATEGORY" cat) props))
3396 (when prio
3397 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3398 (setq prio (mapcar 'string-to-char prio))
3399 (org-set-local 'org-highest-priority (nth 0 prio))
3400 (org-set-local 'org-lowest-priority (nth 1 prio))
3401 (org-set-local 'org-default-priority (nth 2 prio)))
3402 (and props (org-set-local 'org-file-properties (nreverse props)))
3403 (and ftags (org-set-local 'org-file-tags ftags))
3404 (and drawers (org-set-local 'org-drawers drawers))
3405 (and arch (org-set-local 'org-archive-location arch))
3406 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3407 ;; Process the TODO keywords
3408 (unless kwds
3409 ;; Use the global values as if they had been given locally.
3410 (setq kwds (default-value 'org-todo-keywords))
3411 (if (stringp (car kwds))
3412 (setq kwds (list (cons org-todo-interpretation
3413 (default-value 'org-todo-keywords)))))
3414 (setq kwds (reverse kwds)))
3415 (setq kwds (nreverse kwds))
3416 (let (inter kws kw)
3417 (while (setq kws (pop kwds))
3418 (let ((kws (or
3419 (run-hook-with-args-until-success
3420 'org-todo-setup-filter-hook kws)
3421 kws)))
3422 (setq inter (pop kws) sep (member "|" kws)
3423 kws0 (delete "|" (copy-sequence kws))
3424 kwsa nil
3425 kws1 (mapcar
3426 (lambda (x)
3427 ;; 1 2
3428 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3429 (progn
3430 (setq kw (match-string 1 x)
3431 key (and (match-end 2) (match-string 2 x))
3432 log (org-extract-log-state-settings x))
3433 (push (cons kw (and key (string-to-char key))) kwsa)
3434 (and log (push log org-todo-log-states))
3436 (error "Invalid TODO keyword %s" x)))
3437 kws0)
3438 kwsa (if kwsa (append '((:startgroup))
3439 (nreverse kwsa)
3440 '((:endgroup))))
3441 hw (car kws1)
3442 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3443 tail (list inter hw (car dws) (org-last dws))))
3444 (add-to-list 'org-todo-heads hw 'append)
3445 (push kws1 org-todo-sets)
3446 (setq org-done-keywords (append org-done-keywords dws nil))
3447 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3448 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3449 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3450 (setq org-todo-sets (nreverse org-todo-sets)
3451 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3452 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3453 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3454 ;; Process the constants
3455 (when const
3456 (let (e cst)
3457 (while (setq e (pop const))
3458 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3459 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3460 (setq org-table-formula-constants-local cst)))
3462 ;; Process the tags.
3463 (when tags
3464 (let (e tgs)
3465 (while (setq e (pop tags))
3466 (cond
3467 ((equal e "{") (push '(:startgroup) tgs))
3468 ((equal e "}") (push '(:endgroup) tgs))
3469 ((equal e "\\n") (push '(:newline) tgs))
3470 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3471 (push (cons (match-string 1 e)
3472 (string-to-char (match-string 2 e)))
3473 tgs))
3474 (t (push (list e) tgs))))
3475 (org-set-local 'org-tag-alist nil)
3476 (while (setq e (pop tgs))
3477 (or (and (stringp (car e))
3478 (assoc (car e) org-tag-alist))
3479 (push e org-tag-alist)))))
3481 ;; Compute the regular expressions and other local variables
3482 (if (not org-done-keywords)
3483 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3484 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3485 (length org-scheduled-string)
3486 (length org-clock-string)
3487 (length org-closed-string)))
3488 org-drawer-regexp
3489 (concat "^[ \t]*:\\("
3490 (mapconcat 'regexp-quote org-drawers "\\|")
3491 "\\):[ \t]*$")
3492 org-not-done-keywords
3493 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3494 org-todo-regexp
3495 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3496 "\\|") "\\)\\>")
3497 org-not-done-regexp
3498 (concat "\\<\\("
3499 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3500 "\\)\\>")
3501 org-todo-line-regexp
3502 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3503 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3504 "\\)\\>\\)?[ \t]*\\(.*\\)")
3505 org-complex-heading-regexp
3506 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3507 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3508 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3509 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3510 org-nl-done-regexp
3511 (concat "\n\\*+[ \t]+"
3512 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3513 "\\)" "\\>")
3514 org-todo-line-tags-regexp
3515 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3516 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3517 (org-re
3518 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3519 org-looking-at-done-regexp
3520 (concat "^" "\\(?:"
3521 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3522 "\\>")
3523 org-deadline-regexp (concat "\\<" org-deadline-string)
3524 org-deadline-time-regexp
3525 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3526 org-deadline-line-regexp
3527 (concat "\\<\\(" org-deadline-string "\\).*")
3528 org-scheduled-regexp
3529 (concat "\\<" org-scheduled-string)
3530 org-scheduled-time-regexp
3531 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3532 org-closed-time-regexp
3533 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3534 org-keyword-time-regexp
3535 (concat "\\<\\(" org-scheduled-string
3536 "\\|" org-deadline-string
3537 "\\|" org-closed-string
3538 "\\|" org-clock-string "\\)"
3539 " *[[<]\\([^]>]+\\)[]>]")
3540 org-keyword-time-not-clock-regexp
3541 (concat "\\<\\(" org-scheduled-string
3542 "\\|" org-deadline-string
3543 "\\|" org-closed-string
3544 "\\)"
3545 " *[[<]\\([^]>]+\\)[]>]")
3546 org-maybe-keyword-time-regexp
3547 (concat "\\(\\<\\(" org-scheduled-string
3548 "\\|" org-deadline-string
3549 "\\|" org-closed-string
3550 "\\|" org-clock-string "\\)\\)?"
3551 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3552 org-planning-or-clock-line-re
3553 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3554 "\\|" org-deadline-string
3555 "\\|" org-closed-string "\\|" org-clock-string
3556 "\\)\\>\\)")
3558 (org-compute-latex-and-specials-regexp)
3559 (org-set-font-lock-defaults))))
3561 (defun org-file-contents (file &optional noerror)
3562 "Return the contents of FILE, as a string."
3563 (if (or (not file)
3564 (not (file-readable-p file)))
3565 (if noerror
3566 (progn
3567 (message "Cannot read file %s" file)
3568 (ding) (sit-for 2)
3570 (error "Cannot read file %s" file))
3571 (with-temp-buffer
3572 (insert-file-contents file)
3573 (buffer-string))))
3575 (defun org-extract-log-state-settings (x)
3576 "Extract the log state setting from a TODO keyword string.
3577 This will extract info from a string like \"WAIT(w@/!)\"."
3578 (let (kw key log1 log2)
3579 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3580 (setq kw (match-string 1 x)
3581 key (and (match-end 2) (match-string 2 x))
3582 log1 (and (match-end 3) (match-string 3 x))
3583 log2 (and (match-end 4) (match-string 4 x)))
3584 (and (or log1 log2)
3585 (list kw
3586 (and log1 (if (equal log1 "!") 'time 'note))
3587 (and log2 (if (equal log2 "!") 'time 'note)))))))
3589 (defun org-remove-keyword-keys (list)
3590 "Remove a pair of parenthesis at the end of each string in LIST."
3591 (mapcar (lambda (x)
3592 (if (string-match "(.*)$" x)
3593 (substring x 0 (match-beginning 0))
3595 list))
3597 ;; FIXME: this could be done much better, using second characters etc.
3598 (defun org-assign-fast-keys (alist)
3599 "Assign fast keys to a keyword-key alist.
3600 Respect keys that are already there."
3601 (let (new e k c c1 c2 (char ?a))
3602 (while (setq e (pop alist))
3603 (cond
3604 ((equal e '(:startgroup)) (push e new))
3605 ((equal e '(:endgroup)) (push e new))
3606 ((equal e '(:newline)) (push e new))
3608 (setq k (car e) c2 nil)
3609 (if (cdr e)
3610 (setq c (cdr e))
3611 ;; automatically assign a character.
3612 (setq c1 (string-to-char
3613 (downcase (substring
3614 k (if (= (string-to-char k) ?@) 1 0)))))
3615 (if (or (rassoc c1 new) (rassoc c1 alist))
3616 (while (or (rassoc char new) (rassoc char alist))
3617 (setq char (1+ char)))
3618 (setq c2 c1))
3619 (setq c (or c2 char)))
3620 (push (cons k c) new))))
3621 (nreverse new)))
3623 ;;; Some variables used in various places
3625 (defvar org-window-configuration nil
3626 "Used in various places to store a window configuration.")
3627 (defvar org-finish-function nil
3628 "Function to be called when `C-c C-c' is used.
3629 This is for getting out of special buffers like remember.")
3632 ;; FIXME: Occasionally check by commenting these, to make sure
3633 ;; no other functions uses these, forgetting to let-bind them.
3634 (defvar entry)
3635 (defvar state)
3636 (defvar last-state)
3637 (defvar date)
3638 (defvar description)
3640 ;; Defined somewhere in this file, but used before definition.
3641 (defvar org-html-entities)
3642 (defvar org-struct-menu)
3643 (defvar org-org-menu)
3644 (defvar org-tbl-menu)
3645 (defvar org-agenda-keymap)
3647 ;;;; Define the Org-mode
3649 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3650 (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."))
3653 ;; We use a before-change function to check if a table might need
3654 ;; an update.
3655 (defvar org-table-may-need-update t
3656 "Indicates that a table might need an update.
3657 This variable is set by `org-before-change-function'.
3658 `org-table-align' sets it back to nil.")
3659 (defun org-before-change-function (beg end)
3660 "Every change indicates that a table might need an update."
3661 (setq org-table-may-need-update t))
3662 (defvar org-mode-map)
3663 (defvar org-mode-hook nil
3664 "Mode hook for Org-mode, run after the mode was turned on.")
3665 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3666 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3667 (defvar org-table-buffer-is-an nil)
3668 (defconst org-outline-regexp "\\*+ ")
3670 ;;;###autoload
3671 (define-derived-mode org-mode outline-mode "Org"
3672 "Outline-based notes management and organizer, alias
3673 \"Carsten's outline-mode for keeping track of everything.\"
3675 Org-mode develops organizational tasks around a NOTES file which
3676 contains information about projects as plain text. Org-mode is
3677 implemented on top of outline-mode, which is ideal to keep the content
3678 of large files well structured. It supports ToDo items, deadlines and
3679 time stamps, which magically appear in the diary listing of the Emacs
3680 calendar. Tables are easily created with a built-in table editor.
3681 Plain text URL-like links connect to websites, emails (VM), Usenet
3682 messages (Gnus), BBDB entries, and any files related to the project.
3683 For printing and sharing of notes, an Org-mode file (or a part of it)
3684 can be exported as a structured ASCII or HTML file.
3686 The following commands are available:
3688 \\{org-mode-map}"
3690 ;; Get rid of Outline menus, they are not needed
3691 ;; Need to do this here because define-derived-mode sets up
3692 ;; the keymap so late. Still, it is a waste to call this each time
3693 ;; we switch another buffer into org-mode.
3694 (if (featurep 'xemacs)
3695 (when (boundp 'outline-mode-menu-heading)
3696 ;; Assume this is Greg's port, it used easymenu
3697 (easy-menu-remove outline-mode-menu-heading)
3698 (easy-menu-remove outline-mode-menu-show)
3699 (easy-menu-remove outline-mode-menu-hide))
3700 (define-key org-mode-map [menu-bar headings] 'undefined)
3701 (define-key org-mode-map [menu-bar hide] 'undefined)
3702 (define-key org-mode-map [menu-bar show] 'undefined))
3704 (org-load-modules-maybe)
3705 (easy-menu-add org-org-menu)
3706 (easy-menu-add org-tbl-menu)
3707 (org-install-agenda-files-menu)
3708 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3709 (org-add-to-invisibility-spec '(org-cwidth))
3710 (when (featurep 'xemacs)
3711 (org-set-local 'line-move-ignore-invisible t))
3712 (org-set-local 'outline-regexp org-outline-regexp)
3713 (org-set-local 'outline-level 'org-outline-level)
3714 (when (and org-ellipsis
3715 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3716 (fboundp 'make-glyph-code))
3717 (unless org-display-table
3718 (setq org-display-table (make-display-table)))
3719 (set-display-table-slot
3720 org-display-table 4
3721 (vconcat (mapcar
3722 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3723 org-ellipsis)))
3724 (if (stringp org-ellipsis) org-ellipsis "..."))))
3725 (setq buffer-display-table org-display-table))
3726 (org-set-regexps-and-options)
3727 (when (and org-tag-faces (not org-tags-special-faces-re))
3728 ;; tag faces set outside customize.... force initialization.
3729 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3730 ;; Calc embedded
3731 (org-set-local 'calc-embedded-open-mode "# ")
3732 (modify-syntax-entry ?# "<")
3733 (modify-syntax-entry ?@ "w")
3734 (if org-startup-truncated (setq truncate-lines t))
3735 (org-set-local 'font-lock-unfontify-region-function
3736 'org-unfontify-region)
3737 ;; Activate before-change-function
3738 (org-set-local 'org-table-may-need-update t)
3739 (org-add-hook 'before-change-functions 'org-before-change-function nil
3740 'local)
3741 ;; Check for running clock before killing a buffer
3742 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3743 ;; Paragraphs and auto-filling
3744 (org-set-autofill-regexps)
3745 (setq indent-line-function 'org-indent-line-function)
3746 (org-update-radio-target-regexp)
3747 ;; Make sure dependence stuff works reliably, even for users who set it
3748 ;; too late :-(
3749 (if org-enforce-todo-dependencies
3750 (add-hook 'org-blocker-hook
3751 'org-block-todo-from-children-or-siblings)
3752 (remove-hook 'org-blocker-hook
3753 'org-block-todo-from-children-or-siblings))
3754 (if org-enforce-todo-checkbox-dependencies
3755 (add-hook 'org-blocker-hook
3756 'org-block-todo-from-checkboxes)
3757 (remove-hook 'org-blocker-hook
3758 'org-block-todo-from-checkboxes))
3760 ;; Comment characters
3761 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3762 (org-set-local 'comment-padding " ")
3764 ;; Align options lines
3765 (org-set-local
3766 'align-mode-rules-list
3767 '((org-in-buffer-settings
3768 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3769 (modes . '(org-mode)))))
3771 ;; Imenu
3772 (org-set-local 'imenu-create-index-function
3773 'org-imenu-get-tree)
3775 ;; Make isearch reveal context
3776 (if (or (featurep 'xemacs)
3777 (not (boundp 'outline-isearch-open-invisible-function)))
3778 ;; Emacs 21 and XEmacs make use of the hook
3779 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3780 ;; Emacs 22 deals with this through a special variable
3781 (org-set-local 'outline-isearch-open-invisible-function
3782 (lambda (&rest ignore) (org-show-context 'isearch))))
3784 ;; If empty file that did not turn on org-mode automatically, make it to.
3785 (if (and org-insert-mode-line-in-empty-file
3786 (interactive-p)
3787 (= (point-min) (point-max)))
3788 (insert "# -*- mode: org -*-\n\n"))
3790 (unless org-inhibit-startup
3791 (when org-startup-align-all-tables
3792 (let ((bmp (buffer-modified-p)))
3793 (org-table-map-tables 'org-table-align)
3794 (set-buffer-modified-p bmp)))
3795 (org-set-startup-visibility)))
3797 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3799 (defun org-current-time ()
3800 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3801 (if (> (car org-time-stamp-rounding-minutes) 1)
3802 (let ((r (car org-time-stamp-rounding-minutes))
3803 (time (decode-time)))
3804 (apply 'encode-time
3805 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3806 (nthcdr 2 time))))
3807 (current-time)))
3809 ;;;; Font-Lock stuff, including the activators
3811 (defvar org-mouse-map (make-sparse-keymap))
3812 (org-defkey org-mouse-map
3813 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3814 (org-defkey org-mouse-map
3815 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3816 (when org-mouse-1-follows-link
3817 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3818 (when org-tab-follows-link
3819 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3820 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3822 (require 'font-lock)
3824 (defconst org-non-link-chars "]\t\n\r<>")
3825 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3826 "shell" "elisp"))
3827 (defvar org-link-types-re nil
3828 "Matches a link that has a url-like prefix like \"http:\"")
3829 (defvar org-link-re-with-space nil
3830 "Matches a link with spaces, optional angular brackets around it.")
3831 (defvar org-link-re-with-space2 nil
3832 "Matches a link with spaces, optional angular brackets around it.")
3833 (defvar org-link-re-with-space3 nil
3834 "Matches a link with spaces, only for internal part in bracket links.")
3835 (defvar org-angle-link-re nil
3836 "Matches link with angular brackets, spaces are allowed.")
3837 (defvar org-plain-link-re nil
3838 "Matches plain link, without spaces.")
3839 (defvar org-bracket-link-regexp nil
3840 "Matches a link in double brackets.")
3841 (defvar org-bracket-link-analytic-regexp nil
3842 "Regular expression used to analyze links.
3843 Here is what the match groups contain after a match:
3844 1: http:
3845 2: http
3846 3: path
3847 4: [desc]
3848 5: desc")
3849 (defvar org-bracket-link-analytic-regexp++ nil
3850 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3851 (defvar org-any-link-re nil
3852 "Regular expression matching any link.")
3854 (defun org-make-link-regexps ()
3855 "Update the link regular expressions.
3856 This should be called after the variable `org-link-types' has changed."
3857 (setq org-link-types-re
3858 (concat
3859 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3860 org-link-re-with-space
3861 (concat
3862 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3863 "\\([^" org-non-link-chars " ]"
3864 "[^" org-non-link-chars "]*"
3865 "[^" org-non-link-chars " ]\\)>?")
3866 org-link-re-with-space2
3867 (concat
3868 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3869 "\\([^" org-non-link-chars " ]"
3870 "[^\t\n\r]*"
3871 "[^" org-non-link-chars " ]\\)>?")
3872 org-link-re-with-space3
3873 (concat
3874 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3875 "\\([^" org-non-link-chars " ]"
3876 "[^\t\n\r]*\\)")
3877 org-angle-link-re
3878 (concat
3879 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3880 "\\([^" org-non-link-chars " ]"
3881 "[^" org-non-link-chars "]*"
3882 "\\)>")
3883 org-plain-link-re
3884 (concat
3885 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3886 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3887 org-bracket-link-regexp
3888 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3889 org-bracket-link-analytic-regexp
3890 (concat
3891 "\\[\\["
3892 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3893 "\\([^]]+\\)"
3894 "\\]"
3895 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3896 "\\]")
3897 org-bracket-link-analytic-regexp++
3898 (concat
3899 "\\[\\["
3900 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3901 "\\([^]]+\\)"
3902 "\\]"
3903 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3904 "\\]")
3905 org-any-link-re
3906 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3907 org-angle-link-re "\\)\\|\\("
3908 org-plain-link-re "\\)")))
3910 (org-make-link-regexps)
3912 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3913 "Regular expression for fast time stamp matching.")
3914 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3915 "Regular expression for fast time stamp matching.")
3916 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3917 "Regular expression matching time strings for analysis.
3918 This one does not require the space after the date, so it can be used
3919 on a string that terminates immediately after the date.")
3920 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3921 "Regular expression matching time strings for analysis.")
3922 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3923 "Regular expression matching time stamps, with groups.")
3924 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3925 "Regular expression matching time stamps (also [..]), with groups.")
3926 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3927 "Regular expression matching a time stamp range.")
3928 (defconst org-tr-regexp-both
3929 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3930 "Regular expression matching a time stamp range.")
3931 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3932 org-ts-regexp "\\)?")
3933 "Regular expression matching a time stamp or time stamp range.")
3934 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3935 org-ts-regexp-both "\\)?")
3936 "Regular expression matching a time stamp or time stamp range.
3937 The time stamps may be either active or inactive.")
3939 (defvar org-emph-face nil)
3941 (defun org-do-emphasis-faces (limit)
3942 "Run through the buffer and add overlays to links."
3943 (let (rtn)
3944 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3945 (if (not (= (char-after (match-beginning 3))
3946 (char-after (match-beginning 4))))
3947 (progn
3948 (setq rtn t)
3949 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3950 'face
3951 (nth 1 (assoc (match-string 3)
3952 org-emphasis-alist)))
3953 (add-text-properties (match-beginning 2) (match-end 2)
3954 '(font-lock-multiline t))
3955 (when org-hide-emphasis-markers
3956 (add-text-properties (match-end 4) (match-beginning 5)
3957 '(invisible org-link))
3958 (add-text-properties (match-beginning 3) (match-end 3)
3959 '(invisible org-link)))))
3960 (backward-char 1))
3961 rtn))
3963 (defun org-emphasize (&optional char)
3964 "Insert or change an emphasis, i.e. a font like bold or italic.
3965 If there is an active region, change that region to a new emphasis.
3966 If there is no region, just insert the marker characters and position
3967 the cursor between them.
3968 CHAR should be either the marker character, or the first character of the
3969 HTML tag associated with that emphasis. If CHAR is a space, the means
3970 to remove the emphasis of the selected region.
3971 If char is not given (for example in an interactive call) it
3972 will be prompted for."
3973 (interactive)
3974 (let ((eal org-emphasis-alist) e det
3975 (erc org-emphasis-regexp-components)
3976 (prompt "")
3977 (string "") beg end move tag c s)
3978 (if (org-region-active-p)
3979 (setq beg (region-beginning) end (region-end)
3980 string (buffer-substring beg end))
3981 (setq move t))
3983 (while (setq e (pop eal))
3984 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3985 c (aref tag 0))
3986 (push (cons c (string-to-char (car e))) det)
3987 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3988 (substring tag 1)))))
3989 (setq det (nreverse det))
3990 (unless char
3991 (message "%s" (concat "Emphasis marker or tag:" prompt))
3992 (setq char (read-char-exclusive)))
3993 (setq char (or (cdr (assoc char det)) char))
3994 (if (equal char ?\ )
3995 (setq s "" move nil)
3996 (unless (assoc (char-to-string char) org-emphasis-alist)
3997 (error "No such emphasis marker: \"%c\"" char))
3998 (setq s (char-to-string char)))
3999 (while (and (> (length string) 1)
4000 (equal (substring string 0 1) (substring string -1))
4001 (assoc (substring string 0 1) org-emphasis-alist))
4002 (setq string (substring string 1 -1)))
4003 (setq string (concat s string s))
4004 (if beg (delete-region beg end))
4005 (unless (or (bolp)
4006 (string-match (concat "[" (nth 0 erc) "\n]")
4007 (char-to-string (char-before (point)))))
4008 (insert " "))
4009 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4010 (char-to-string (char-after (point))))
4011 (insert " ") (backward-char 1))
4012 (insert string)
4013 (and move (backward-char 1))))
4015 (defconst org-nonsticky-props
4016 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4019 (defun org-activate-plain-links (limit)
4020 "Run through the buffer and add overlays to links."
4021 (catch 'exit
4022 (let (f)
4023 (while (re-search-forward org-plain-link-re limit t)
4024 (setq f (get-text-property (match-beginning 0) 'face))
4025 (if (or (eq f 'org-tag)
4026 (and (listp f) (memq 'org-tag f)))
4028 (add-text-properties (match-beginning 0) (match-end 0)
4029 (list 'mouse-face 'highlight
4030 'rear-nonsticky org-nonsticky-props
4031 'keymap org-mouse-map
4033 (throw 'exit t))))))
4035 (defun org-activate-code (limit)
4036 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4037 (progn
4038 (remove-text-properties (match-beginning 0) (match-end 0)
4039 '(display t invisible t intangible t))
4040 t)))
4042 (defun org-activate-angle-links (limit)
4043 "Run through the buffer and add overlays to links."
4044 (if (re-search-forward org-angle-link-re limit t)
4045 (progn
4046 (add-text-properties (match-beginning 0) (match-end 0)
4047 (list 'mouse-face 'highlight
4048 'rear-nonsticky org-nonsticky-props
4049 'keymap org-mouse-map
4051 t)))
4053 (defun org-activate-footnote-links (limit)
4054 "Run through the buffer and add overlays to links."
4055 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4056 limit t)
4057 (progn
4058 (add-text-properties (match-beginning 2) (match-end 2)
4059 (list 'mouse-face 'highlight
4060 'rear-nonsticky org-nonsticky-props
4061 'keymap org-mouse-map
4062 'help-echo
4063 (if (= (point-at-bol) (match-beginning 2))
4064 "Footnote definition"
4065 "Footnote reference")
4067 t)))
4069 (defun org-activate-bracket-links (limit)
4070 "Run through the buffer and add overlays to bracketed links."
4071 (if (re-search-forward org-bracket-link-regexp limit t)
4072 (let* ((help (concat "LINK: "
4073 (org-match-string-no-properties 1)))
4074 ;; FIXME: above we should remove the escapes.
4075 ;; but that requires another match, protecting match data,
4076 ;; a lot of overhead for font-lock.
4077 (ip (org-maybe-intangible
4078 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4079 'keymap org-mouse-map 'mouse-face 'highlight
4080 'font-lock-multiline t 'help-echo help)))
4081 (vp (list 'rear-nonsticky org-nonsticky-props
4082 'keymap org-mouse-map 'mouse-face 'highlight
4083 ' font-lock-multiline t 'help-echo help)))
4084 ;; We need to remove the invisible property here. Table narrowing
4085 ;; may have made some of this invisible.
4086 (remove-text-properties (match-beginning 0) (match-end 0)
4087 '(invisible nil))
4088 (if (match-end 3)
4089 (progn
4090 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4091 (add-text-properties (match-beginning 3) (match-end 3) vp)
4092 (add-text-properties (match-end 3) (match-end 0) ip))
4093 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4094 (add-text-properties (match-beginning 1) (match-end 1) vp)
4095 (add-text-properties (match-end 1) (match-end 0) ip))
4096 t)))
4098 (defun org-activate-dates (limit)
4099 "Run through the buffer and add overlays to dates."
4100 (if (re-search-forward org-tsr-regexp-both limit t)
4101 (progn
4102 (add-text-properties (match-beginning 0) (match-end 0)
4103 (list 'mouse-face 'highlight
4104 'rear-nonsticky org-nonsticky-props
4105 'keymap org-mouse-map))
4106 (when org-display-custom-times
4107 (if (match-end 3)
4108 (org-display-custom-time (match-beginning 3) (match-end 3)))
4109 (org-display-custom-time (match-beginning 1) (match-end 1)))
4110 t)))
4112 (defvar org-target-link-regexp nil
4113 "Regular expression matching radio targets in plain text.")
4114 (make-variable-buffer-local 'org-target-link-regexp)
4115 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4116 "Regular expression matching a link target.")
4117 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4118 "Regular expression matching a radio target.")
4119 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4120 "Regular expression matching any target.")
4122 (defun org-activate-target-links (limit)
4123 "Run through the buffer and add overlays to target matches."
4124 (when org-target-link-regexp
4125 (let ((case-fold-search t))
4126 (if (re-search-forward org-target-link-regexp limit t)
4127 (progn
4128 (add-text-properties (match-beginning 0) (match-end 0)
4129 (list 'mouse-face 'highlight
4130 'rear-nonsticky org-nonsticky-props
4131 'keymap org-mouse-map
4132 'help-echo "Radio target link"
4133 'org-linked-text t))
4134 t)))))
4136 (defun org-update-radio-target-regexp ()
4137 "Find all radio targets in this file and update the regular expression."
4138 (interactive)
4139 (when (memq 'radio org-activate-links)
4140 (setq org-target-link-regexp
4141 (org-make-target-link-regexp (org-all-targets 'radio)))
4142 (org-restart-font-lock)))
4144 (defun org-hide-wide-columns (limit)
4145 (let (s e)
4146 (setq s (text-property-any (point) (or limit (point-max))
4147 'org-cwidth t))
4148 (when s
4149 (setq e (next-single-property-change s 'org-cwidth))
4150 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4151 (goto-char e)
4152 t)))
4154 (defvar org-latex-and-specials-regexp nil
4155 "Regular expression for highlighting export special stuff.")
4156 (defvar org-match-substring-regexp)
4157 (defvar org-match-substring-with-braces-regexp)
4158 (defvar org-export-html-special-string-regexps)
4160 (defun org-compute-latex-and-specials-regexp ()
4161 "Compute regular expression for stuff treated specially by exporters."
4162 (if (not org-highlight-latex-fragments-and-specials)
4163 (org-set-local 'org-latex-and-specials-regexp nil)
4164 (require 'org-exp)
4165 (let*
4166 ((matchers (plist-get org-format-latex-options :matchers))
4167 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4168 org-latex-regexps)))
4169 (options (org-combine-plists (org-default-export-plist)
4170 (org-infile-export-plist)))
4171 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4172 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4173 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4174 (org-export-html-expand (plist-get options :expand-quoted-html))
4175 (org-export-with-special-strings (plist-get options :special-strings))
4176 (re-sub
4177 (cond
4178 ((equal org-export-with-sub-superscripts '{})
4179 (list org-match-substring-with-braces-regexp))
4180 (org-export-with-sub-superscripts
4181 (list org-match-substring-regexp))
4182 (t nil)))
4183 (re-latex
4184 (if org-export-with-LaTeX-fragments
4185 (mapcar (lambda (x) (nth 1 x)) latexs)))
4186 (re-macros
4187 (if org-export-with-TeX-macros
4188 (list (concat "\\\\"
4189 (regexp-opt
4190 (append (mapcar 'car org-html-entities)
4191 (if (boundp 'org-latex-entities)
4192 org-latex-entities nil))
4193 'words))) ; FIXME
4195 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4196 (re-special (if org-export-with-special-strings
4197 (mapcar (lambda (x) (car x))
4198 org-export-html-special-string-regexps)))
4199 (re-rest
4200 (delq nil
4201 (list
4202 (if org-export-html-expand "@<[^>\n]+>")
4203 ))))
4204 (org-set-local
4205 'org-latex-and-specials-regexp
4206 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4207 re-rest) "\\|")))))
4209 (defun org-do-latex-and-special-faces (limit)
4210 "Run through the buffer and add overlays to links."
4211 (when org-latex-and-specials-regexp
4212 (let (rtn d)
4213 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4214 limit t))
4215 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4216 'face))
4217 '(org-code org-verbatim underline)))
4218 (progn
4219 (setq rtn t
4220 d (cond ((member (char-after (1+ (match-beginning 0)))
4221 '(?_ ?^)) 1)
4222 (t 0)))
4223 (font-lock-prepend-text-property
4224 (+ d (match-beginning 0)) (match-end 0)
4225 'face 'org-latex-and-export-specials)
4226 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4227 '(font-lock-multiline t)))))
4228 rtn)))
4230 (defun org-restart-font-lock ()
4231 "Restart font-lock-mode, to force refontification."
4232 (when (and (boundp 'font-lock-mode) font-lock-mode)
4233 (font-lock-mode -1)
4234 (font-lock-mode 1)))
4236 (defun org-all-targets (&optional radio)
4237 "Return a list of all targets in this file.
4238 With optional argument RADIO, only find radio targets."
4239 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4240 rtn)
4241 (save-excursion
4242 (goto-char (point-min))
4243 (while (re-search-forward re nil t)
4244 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4245 rtn)))
4247 (defun org-make-target-link-regexp (targets)
4248 "Make regular expression matching all strings in TARGETS.
4249 The regular expression finds the targets also if there is a line break
4250 between words."
4251 (and targets
4252 (concat
4253 "\\<\\("
4254 (mapconcat
4255 (lambda (x)
4256 (while (string-match " +" x)
4257 (setq x (replace-match "\\s-+" t t x)))
4259 targets
4260 "\\|")
4261 "\\)\\>")))
4263 (defun org-activate-tags (limit)
4264 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4265 (progn
4266 (add-text-properties (match-beginning 1) (match-end 1)
4267 (list 'mouse-face 'highlight
4268 'rear-nonsticky org-nonsticky-props
4269 'keymap org-mouse-map))
4270 t)))
4272 (defun org-outline-level ()
4273 (save-excursion
4274 (looking-at outline-regexp)
4275 (if (match-beginning 1)
4276 (+ (org-get-string-indentation (match-string 1)) 1000)
4277 (1- (- (match-end 0) (match-beginning 0))))))
4279 (defvar org-font-lock-keywords nil)
4281 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4282 "Regular expression matching a property line.")
4284 (defvar org-font-lock-hook nil
4285 "Functions to be called for special font lock stuff.")
4287 (defun org-font-lock-hook (limit)
4288 (run-hook-with-args 'org-font-lock-hook limit))
4290 (defun org-set-font-lock-defaults ()
4291 (let* ((em org-fontify-emphasized-text)
4292 (lk org-activate-links)
4293 (org-font-lock-extra-keywords
4294 (list
4295 ;; Call the hook
4296 '(org-font-lock-hook)
4297 ;; Headlines
4298 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4299 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4300 ;; Table lines
4301 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4302 (1 'org-table t))
4303 ;; Table internals
4304 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4305 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4306 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4307 ;; Drawers
4308 (list org-drawer-regexp '(0 'org-special-keyword t))
4309 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4310 ;; Properties
4311 (list org-property-re
4312 '(1 'org-special-keyword t)
4313 '(3 'org-property-value t))
4314 (if org-format-transports-properties-p
4315 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4316 ;; Links
4317 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4318 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4319 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4320 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4321 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4322 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4323 (if (memq 'footnote lk) '(org-activate-footnote-links
4324 (2 'org-footnote t)))
4325 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4326 '(org-hide-wide-columns (0 nil append))
4327 ;; TODO lines
4328 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4329 '(1 (org-get-todo-face 1) t))
4330 ;; DONE
4331 (if org-fontify-done-headline
4332 (list (concat "^[*]+ +\\<\\("
4333 (mapconcat 'regexp-quote org-done-keywords "\\|")
4334 "\\)\\(.*\\)")
4335 '(2 'org-headline-done t))
4336 nil)
4337 ;; Priorities
4338 '(org-font-lock-add-priority-faces)
4339 ;; Tags
4340 '(org-font-lock-add-tag-faces)
4341 ;; Special keywords
4342 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4343 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4344 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4345 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4346 ;; Emphasis
4347 (if em
4348 (if (featurep 'xemacs)
4349 '(org-do-emphasis-faces (0 nil append))
4350 '(org-do-emphasis-faces)))
4351 ;; Checkboxes
4352 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4353 2 'bold prepend)
4354 (if org-provide-checkbox-statistics
4355 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4356 (0 (org-get-checkbox-statistics-face) t)))
4357 ;; Description list items
4358 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4359 2 'bold prepend)
4360 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4361 '(1 'org-archived prepend))
4362 ;; Specials
4363 '(org-do-latex-and-special-faces)
4364 ;; Code
4365 '(org-activate-code (1 'org-code t))
4366 ;; COMMENT
4367 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4368 "\\|" org-quote-string "\\)\\>")
4369 '(1 'org-special-keyword t))
4370 '("^#.*" (0 'font-lock-comment-face t))
4372 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4373 ;; Now set the full font-lock-keywords
4374 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4375 (org-set-local 'font-lock-defaults
4376 '(org-font-lock-keywords t nil nil backward-paragraph))
4377 (kill-local-variable 'font-lock-keywords) nil))
4379 (defvar org-m nil)
4380 (defvar org-l nil)
4381 (defvar org-f nil)
4382 (defun org-get-level-face (n)
4383 "Get the right face for match N in font-lock matching of headlines."
4384 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4385 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4386 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4387 (cond
4388 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4389 ((eq n 2) org-f)
4390 (t (if org-level-color-stars-only nil org-f))))
4392 (defun org-get-todo-face (kwd)
4393 "Get the right face for a TODO keyword KWD.
4394 If KWD is a number, get the corresponding match group."
4395 (if (numberp kwd) (setq kwd (match-string kwd)))
4396 (or (cdr (assoc kwd org-todo-keyword-faces))
4397 (and (member kwd org-done-keywords) 'org-done)
4398 'org-todo))
4400 (defun org-font-lock-add-tag-faces (limit)
4401 "Add the special tag faces."
4402 (when (and org-tag-faces org-tags-special-faces-re)
4403 (while (re-search-forward org-tags-special-faces-re limit t)
4404 (add-text-properties (match-beginning 1) (match-end 1)
4405 (list 'face (org-get-tag-face 1)
4406 'font-lock-fontified t))
4407 (backward-char 1))))
4409 (defun org-font-lock-add-priority-faces (limit)
4410 "Add the special priority faces."
4411 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4412 (add-text-properties
4413 (match-beginning 0) (match-end 0)
4414 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4415 org-priority-faces))
4416 'org-special-keyword)
4417 'font-lock-fontified t))))
4419 (defun org-get-tag-face (kwd)
4420 "Get the right face for a TODO keyword KWD.
4421 If KWD is a number, get the corresponding match group."
4422 (if (numberp kwd) (setq kwd (match-string kwd)))
4423 (or (cdr (assoc kwd org-tag-faces))
4424 'org-tag))
4426 (defun org-unfontify-region (beg end &optional maybe_loudly)
4427 "Remove fontification and activation overlays from links."
4428 (font-lock-default-unfontify-region beg end)
4429 (let* ((buffer-undo-list t)
4430 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4431 (inhibit-modification-hooks t)
4432 deactivate-mark buffer-file-name buffer-file-truename)
4433 (remove-text-properties beg end
4434 '(mouse-face t keymap t org-linked-text t
4435 invisible t intangible t))))
4437 ;;;; Visibility cycling, including org-goto and indirect buffer
4439 ;;; Cycling
4441 (defvar org-cycle-global-status nil)
4442 (make-variable-buffer-local 'org-cycle-global-status)
4443 (defvar org-cycle-subtree-status nil)
4444 (make-variable-buffer-local 'org-cycle-subtree-status)
4446 ;;;###autoload
4447 (defun org-cycle (&optional arg)
4448 "Visibility cycling for Org-mode.
4450 - When this function is called with a prefix argument, rotate the entire
4451 buffer through 3 states (global cycling)
4452 1. OVERVIEW: Show only top-level headlines.
4453 2. CONTENTS: Show all headlines of all levels, but no body text.
4454 3. SHOW ALL: Show everything.
4455 When called with two C-u C-u prefixes, switch to the startup visibility,
4456 determined by the variable `org-startup-folded', and by any VISIBILITY
4457 properties in the buffer.
4458 When called with three C-u C-u C-u prefixed, show the entire buffer,
4459 including drawers.
4461 - When point is at the beginning of a headline, rotate the subtree started
4462 by this line through 3 different states (local cycling)
4463 1. FOLDED: Only the main headline is shown.
4464 2. CHILDREN: The main headline and the direct children are shown.
4465 From this state, you can move to one of the children
4466 and zoom in further.
4467 3. SUBTREE: Show the entire subtree, including body text.
4469 - When there is a numeric prefix, go up to a heading with level ARG, do
4470 a `show-subtree' and return to the previous cursor position. If ARG
4471 is negative, go up that many levels.
4473 - When point is not at the beginning of a headline, execute the global
4474 binding for TAB, which is re-indenting the line. See the option
4475 `org-cycle-emulate-tab' for details.
4477 - Special case: if point is at the beginning of the buffer and there is
4478 no headline in line 1, this function will act as if called with prefix arg.
4479 But only if also the variable `org-cycle-global-at-bob' is t."
4480 (interactive "P")
4481 (org-load-modules-maybe)
4482 (let* ((outline-regexp
4483 (if (and (org-mode-p) org-cycle-include-plain-lists)
4484 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4485 outline-regexp))
4486 (bob-special (and org-cycle-global-at-bob (bobp)
4487 (not (looking-at outline-regexp))))
4488 (org-cycle-hook
4489 (if bob-special
4490 (delq 'org-optimize-window-after-visibility-change
4491 (copy-sequence org-cycle-hook))
4492 org-cycle-hook))
4493 (pos (point)))
4495 (if (or bob-special (equal arg '(4)))
4496 ;; special case: use global cycling
4497 (setq arg t))
4499 (cond
4501 ((equal arg '(16))
4502 (org-set-startup-visibility)
4503 (message "Startup visibility, plus VISIBILITY properties"))
4505 ((equal arg '(64))
4506 (show-all)
4507 (message "Entire buffer visible, including drawers"))
4509 ((org-at-table-p 'any)
4510 ;; Enter the table or move to the next field in the table
4511 (or (org-table-recognize-table.el)
4512 (progn
4513 (if arg (org-table-edit-field t)
4514 (org-table-justify-field-maybe)
4515 (call-interactively 'org-table-next-field)))))
4517 ((eq arg t) ;; Global cycling
4519 (cond
4520 ((and (eq last-command this-command)
4521 (eq org-cycle-global-status 'overview))
4522 ;; We just created the overview - now do table of contents
4523 ;; This can be slow in very large buffers, so indicate action
4524 (message "CONTENTS...")
4525 (org-content)
4526 (message "CONTENTS...done")
4527 (setq org-cycle-global-status 'contents)
4528 (run-hook-with-args 'org-cycle-hook 'contents))
4530 ((and (eq last-command this-command)
4531 (eq org-cycle-global-status 'contents))
4532 ;; We just showed the table of contents - now show everything
4533 (show-all)
4534 (message "SHOW ALL")
4535 (setq org-cycle-global-status 'all)
4536 (run-hook-with-args 'org-cycle-hook 'all))
4539 ;; Default action: go to overview
4540 (org-overview)
4541 (message "OVERVIEW")
4542 (setq org-cycle-global-status 'overview)
4543 (run-hook-with-args 'org-cycle-hook 'overview))))
4545 ((and org-drawers org-drawer-regexp
4546 (save-excursion
4547 (beginning-of-line 1)
4548 (looking-at org-drawer-regexp)))
4549 ;; Toggle block visibility
4550 (org-flag-drawer
4551 (not (get-char-property (match-end 0) 'invisible))))
4553 ((integerp arg)
4554 ;; Show-subtree, ARG levels up from here.
4555 (save-excursion
4556 (org-back-to-heading)
4557 (outline-up-heading (if (< arg 0) (- arg)
4558 (- (funcall outline-level) arg)))
4559 (org-show-subtree)))
4561 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4562 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4563 ;; At a heading: rotate between three different views
4564 (org-back-to-heading)
4565 (let ((goal-column 0) eoh eol eos)
4566 ;; First, some boundaries
4567 (save-excursion
4568 (org-back-to-heading)
4569 (save-excursion
4570 (beginning-of-line 2)
4571 (while (and (not (eobp)) ;; this is like `next-line'
4572 (get-char-property (1- (point)) 'invisible))
4573 (beginning-of-line 2)) (setq eol (point)))
4574 (outline-end-of-heading) (setq eoh (point))
4575 (org-end-of-subtree t)
4576 (unless (eobp)
4577 (skip-chars-forward " \t\n")
4578 (beginning-of-line 1) ; in case this is an item
4580 (setq eos (1- (point))))
4581 ;; Find out what to do next and set `this-command'
4582 (cond
4583 ((= eos eoh)
4584 ;; Nothing is hidden behind this heading
4585 (message "EMPTY ENTRY")
4586 (setq org-cycle-subtree-status nil)
4587 (save-excursion
4588 (goto-char eos)
4589 (outline-next-heading)
4590 (if (org-invisible-p) (org-flag-heading nil))))
4591 ((or (>= eol eos)
4592 (not (string-match "\\S-" (buffer-substring eol eos))))
4593 ;; Entire subtree is hidden in one line: open it
4594 (org-show-entry)
4595 (show-children)
4596 (message "CHILDREN")
4597 (save-excursion
4598 (goto-char eos)
4599 (outline-next-heading)
4600 (if (org-invisible-p) (org-flag-heading nil)))
4601 (setq org-cycle-subtree-status 'children)
4602 (run-hook-with-args 'org-cycle-hook 'children))
4603 ((and (eq last-command this-command)
4604 (eq org-cycle-subtree-status 'children))
4605 ;; We just showed the children, now show everything.
4606 (org-show-subtree)
4607 (message "SUBTREE")
4608 (setq org-cycle-subtree-status 'subtree)
4609 (run-hook-with-args 'org-cycle-hook 'subtree))
4611 ;; Default action: hide the subtree.
4612 (hide-subtree)
4613 (message "FOLDED")
4614 (setq org-cycle-subtree-status 'folded)
4615 (run-hook-with-args 'org-cycle-hook 'folded)))))
4617 ;; TAB emulation and template completion
4618 (buffer-read-only (org-back-to-heading))
4620 ((org-try-structure-completion))
4622 ((org-try-cdlatex-tab))
4624 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4625 (or (not (bolp))
4626 (not (looking-at outline-regexp))))
4627 (call-interactively (global-key-binding "\t")))
4629 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4630 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4631 (or (and (eq org-cycle-emulate-tab 'white)
4632 (= (match-end 0) (point-at-eol)))
4633 (and (eq org-cycle-emulate-tab 'whitestart)
4634 (>= (match-end 0) pos))))
4636 (eq org-cycle-emulate-tab t))
4637 (call-interactively (global-key-binding "\t")))
4639 (t (save-excursion
4640 (org-back-to-heading)
4641 (org-cycle))))))
4643 ;;;###autoload
4644 (defun org-global-cycle (&optional arg)
4645 "Cycle the global visibility. For details see `org-cycle'.
4646 With C-u prefix arg, switch to startup visibility.
4647 With a numeric prefix, show all headlines up to that level."
4648 (interactive "P")
4649 (let ((org-cycle-include-plain-lists
4650 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4651 (cond
4652 ((integerp arg)
4653 (show-all)
4654 (hide-sublevels arg)
4655 (setq org-cycle-global-status 'contents))
4656 ((equal arg '(4))
4657 (org-set-startup-visibility)
4658 (message "Startup visibility, plus VISIBILITY properties."))
4660 (org-cycle '(4))))))
4662 (defun org-set-startup-visibility ()
4663 "Set the visibility required by startup options and properties."
4664 (cond
4665 ((eq org-startup-folded t)
4666 (org-cycle '(4)))
4667 ((eq org-startup-folded 'content)
4668 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4669 (org-cycle '(4)) (org-cycle '(4)))))
4670 (org-set-visibility-according-to-property 'no-cleanup)
4671 (org-cycle-hide-archived-subtrees 'all)
4672 (org-cycle-hide-drawers 'all)
4673 (org-cycle-show-empty-lines 'all))
4675 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4676 "Switch subtree visibilities according to :VISIBILITY: property."
4677 (interactive)
4678 (let (org-show-entry-below state)
4679 (save-excursion
4680 (goto-char (point-min))
4681 (while (re-search-forward
4682 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4683 nil t)
4684 (setq state (match-string 1))
4685 (save-excursion
4686 (org-back-to-heading t)
4687 (hide-subtree)
4688 (org-reveal)
4689 (cond
4690 ((equal state '("fold" "folded"))
4691 (hide-subtree))
4692 ((equal state "children")
4693 (org-show-hidden-entry)
4694 (show-children))
4695 ((equal state "content")
4696 (save-excursion
4697 (save-restriction
4698 (org-narrow-to-subtree)
4699 (org-content))))
4700 ((member state '("all" "showall"))
4701 (show-subtree)))))
4702 (unless no-cleanup
4703 (org-cycle-hide-archived-subtrees 'all)
4704 (org-cycle-hide-drawers 'all)
4705 (org-cycle-show-empty-lines 'all)))))
4707 (defun org-overview ()
4708 "Switch to overview mode, showing only top-level headlines.
4709 Really, this shows all headlines with level equal or greater than the level
4710 of the first headline in the buffer. This is important, because if the
4711 first headline is not level one, then (hide-sublevels 1) gives confusing
4712 results."
4713 (interactive)
4714 (let ((level (save-excursion
4715 (goto-char (point-min))
4716 (if (re-search-forward (concat "^" outline-regexp) nil t)
4717 (progn
4718 (goto-char (match-beginning 0))
4719 (funcall outline-level))))))
4720 (and level (hide-sublevels level))))
4722 (defun org-content (&optional arg)
4723 "Show all headlines in the buffer, like a table of contents.
4724 With numerical argument N, show content up to level N."
4725 (interactive "P")
4726 (save-excursion
4727 ;; Visit all headings and show their offspring
4728 (and (integerp arg) (org-overview))
4729 (goto-char (point-max))
4730 (catch 'exit
4731 (while (and (progn (condition-case nil
4732 (outline-previous-visible-heading 1)
4733 (error (goto-char (point-min))))
4735 (looking-at outline-regexp))
4736 (if (integerp arg)
4737 (show-children (1- arg))
4738 (show-branches))
4739 (if (bobp) (throw 'exit nil))))))
4742 (defun org-optimize-window-after-visibility-change (state)
4743 "Adjust the window after a change in outline visibility.
4744 This function is the default value of the hook `org-cycle-hook'."
4745 (when (get-buffer-window (current-buffer))
4746 (cond
4747 ((eq state 'content) nil)
4748 ((eq state 'all) nil)
4749 ((eq state 'folded) nil)
4750 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4751 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4753 (defun org-compact-display-after-subtree-move ()
4754 "Show a compacter version of the tree of the entry's parent."
4755 (save-excursion
4756 (if (org-up-heading-safe)
4757 (progn
4758 (hide-subtree)
4759 (show-entry)
4760 (show-children)
4761 (org-cycle-show-empty-lines 'children)
4762 (org-cycle-hide-drawers 'children))
4763 (org-overview))))
4765 (defun org-cycle-show-empty-lines (state)
4766 "Show empty lines above all visible headlines.
4767 The region to be covered depends on STATE when called through
4768 `org-cycle-hook'. Lisp program can use t for STATE to get the
4769 entire buffer covered. Note that an empty line is only shown if there
4770 are at least `org-cycle-separator-lines' empty lines before the headline."
4771 (when (> org-cycle-separator-lines 0)
4772 (save-excursion
4773 (let* ((n org-cycle-separator-lines)
4774 (re (cond
4775 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4776 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4777 (t (let ((ns (number-to-string (- n 2))))
4778 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4779 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4780 beg end)
4781 (cond
4782 ((memq state '(overview contents t))
4783 (setq beg (point-min) end (point-max)))
4784 ((memq state '(children folded))
4785 (setq beg (point) end (progn (org-end-of-subtree t t)
4786 (beginning-of-line 2)
4787 (point)))))
4788 (when beg
4789 (goto-char beg)
4790 (while (re-search-forward re end t)
4791 (if (not (get-char-property (match-end 1) 'invisible))
4792 (outline-flag-region
4793 (match-beginning 1) (match-end 1) nil)))))))
4794 ;; Never hide empty lines at the end of the file.
4795 (save-excursion
4796 (goto-char (point-max))
4797 (outline-previous-heading)
4798 (outline-end-of-heading)
4799 (if (and (looking-at "[ \t\n]+")
4800 (= (match-end 0) (point-max)))
4801 (outline-flag-region (point) (match-end 0) nil))))
4803 (defun org-show-empty-lines-in-parent ()
4804 "Move to the parent and re-show empty lines before visible headlines."
4805 (save-excursion
4806 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4807 (org-cycle-show-empty-lines context))))
4809 (defun org-cycle-hide-drawers (state)
4810 "Re-hide all drawers after a visibility state change."
4811 (when (and (org-mode-p)
4812 (not (memq state '(overview folded))))
4813 (save-excursion
4814 (let* ((globalp (memq state '(contents all)))
4815 (beg (if globalp (point-min) (point)))
4816 (end (if globalp (point-max) (org-end-of-subtree t))))
4817 (goto-char beg)
4818 (while (re-search-forward org-drawer-regexp end t)
4819 (org-flag-drawer t))))))
4821 (defun org-flag-drawer (flag)
4822 (save-excursion
4823 (beginning-of-line 1)
4824 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4825 (let ((b (match-end 0))
4826 (outline-regexp org-outline-regexp))
4827 (if (re-search-forward
4828 "^[ \t]*:END:"
4829 (save-excursion (outline-next-heading) (point)) t)
4830 (outline-flag-region b (point-at-eol) flag)
4831 (error ":END: line missing"))))))
4833 (defun org-subtree-end-visible-p ()
4834 "Is the end of the current subtree visible?"
4835 (pos-visible-in-window-p
4836 (save-excursion (org-end-of-subtree t) (point))))
4838 (defun org-first-headline-recenter (&optional N)
4839 "Move cursor to the first headline and recenter the headline.
4840 Optional argument N means, put the headline into the Nth line of the window."
4841 (goto-char (point-min))
4842 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4843 (beginning-of-line)
4844 (recenter (prefix-numeric-value N))))
4846 ;;; Org-goto
4848 (defvar org-goto-window-configuration nil)
4849 (defvar org-goto-marker nil)
4850 (defvar org-goto-map
4851 (let ((map (make-sparse-keymap)))
4852 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4853 (while (setq cmd (pop cmds))
4854 (substitute-key-definition cmd cmd map global-map)))
4855 (suppress-keymap map)
4856 (org-defkey map "\C-m" 'org-goto-ret)
4857 (org-defkey map [(return)] 'org-goto-ret)
4858 (org-defkey map [(left)] 'org-goto-left)
4859 (org-defkey map [(right)] 'org-goto-right)
4860 (org-defkey map [(control ?g)] 'org-goto-quit)
4861 (org-defkey map "\C-i" 'org-cycle)
4862 (org-defkey map [(tab)] 'org-cycle)
4863 (org-defkey map [(down)] 'outline-next-visible-heading)
4864 (org-defkey map [(up)] 'outline-previous-visible-heading)
4865 (if org-goto-auto-isearch
4866 (if (fboundp 'define-key-after)
4867 (define-key-after map [t] 'org-goto-local-auto-isearch)
4868 nil)
4869 (org-defkey map "q" 'org-goto-quit)
4870 (org-defkey map "n" 'outline-next-visible-heading)
4871 (org-defkey map "p" 'outline-previous-visible-heading)
4872 (org-defkey map "f" 'outline-forward-same-level)
4873 (org-defkey map "b" 'outline-backward-same-level)
4874 (org-defkey map "u" 'outline-up-heading))
4875 (org-defkey map "/" 'org-occur)
4876 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4877 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4878 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4879 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4880 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4881 map))
4883 (defconst org-goto-help
4884 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4885 RET=jump to location [Q]uit and return to previous location
4886 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4888 (defvar org-goto-start-pos) ; dynamically scoped parameter
4890 ;; FIXME: Docstring doe not mention both interfaces
4891 (defun org-goto (&optional alternative-interface)
4892 "Look up a different location in the current file, keeping current visibility.
4894 When you want look-up or go to a different location in a document, the
4895 fastest way is often to fold the entire buffer and then dive into the tree.
4896 This method has the disadvantage, that the previous location will be folded,
4897 which may not be what you want.
4899 This command works around this by showing a copy of the current buffer
4900 in an indirect buffer, in overview mode. You can dive into the tree in
4901 that copy, use org-occur and incremental search to find a location.
4902 When pressing RET or `Q', the command returns to the original buffer in
4903 which the visibility is still unchanged. After RET is will also jump to
4904 the location selected in the indirect buffer and expose the
4905 the headline hierarchy above."
4906 (interactive "P")
4907 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4908 (org-refile-use-outline-path t)
4909 (interface
4910 (if (not alternative-interface)
4911 org-goto-interface
4912 (if (eq org-goto-interface 'outline)
4913 'outline-path-completion
4914 'outline)))
4915 (org-goto-start-pos (point))
4916 (selected-point
4917 (if (eq interface 'outline)
4918 (car (org-get-location (current-buffer) org-goto-help))
4919 (nth 3 (org-refile-get-location "Goto: ")))))
4920 (if selected-point
4921 (progn
4922 (org-mark-ring-push org-goto-start-pos)
4923 (goto-char selected-point)
4924 (if (or (org-invisible-p) (org-invisible-p2))
4925 (org-show-context 'org-goto)))
4926 (message "Quit"))))
4928 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4929 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4930 (defvar org-goto-local-auto-isearch-map) ; defined below
4932 (defun org-get-location (buf help)
4933 "Let the user select a location in the Org-mode buffer BUF.
4934 This function uses a recursive edit. It returns the selected position
4935 or nil."
4936 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4937 (isearch-hide-immediately nil)
4938 (isearch-search-fun-function
4939 (lambda () 'org-goto-local-search-headings))
4940 (org-goto-selected-point org-goto-exit-command))
4941 (save-excursion
4942 (save-window-excursion
4943 (delete-other-windows)
4944 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4945 (switch-to-buffer
4946 (condition-case nil
4947 (make-indirect-buffer (current-buffer) "*org-goto*")
4948 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4949 (with-output-to-temp-buffer "*Help*"
4950 (princ help))
4951 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4952 (setq buffer-read-only nil)
4953 (let ((org-startup-truncated t)
4954 (org-startup-folded nil)
4955 (org-startup-align-all-tables nil))
4956 (org-mode)
4957 (org-overview))
4958 (setq buffer-read-only t)
4959 (if (and (boundp 'org-goto-start-pos)
4960 (integer-or-marker-p org-goto-start-pos))
4961 (let ((org-show-hierarchy-above t)
4962 (org-show-siblings t)
4963 (org-show-following-heading t))
4964 (goto-char org-goto-start-pos)
4965 (and (org-invisible-p) (org-show-context)))
4966 (goto-char (point-min)))
4967 (let (org-special-ctrl-a/e) (org-beginning-of-line))
4968 (message "Select location and press RET")
4969 (use-local-map org-goto-map)
4970 (recursive-edit)
4972 (kill-buffer "*org-goto*")
4973 (cons org-goto-selected-point org-goto-exit-command)))
4975 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4976 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4977 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4978 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4980 (defun org-goto-local-search-headings (string bound noerror)
4981 "Search and make sure that any matches are in headlines."
4982 (catch 'return
4983 (while (if isearch-forward
4984 (search-forward string bound noerror)
4985 (search-backward string bound noerror))
4986 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4987 (and (member :headline context)
4988 (not (member :tags context))))
4989 (throw 'return (point))))))
4991 (defun org-goto-local-auto-isearch ()
4992 "Start isearch."
4993 (interactive)
4994 (goto-char (point-min))
4995 (let ((keys (this-command-keys)))
4996 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4997 (isearch-mode t)
4998 (isearch-process-search-char (string-to-char keys)))))
5000 (defun org-goto-ret (&optional arg)
5001 "Finish `org-goto' by going to the new location."
5002 (interactive "P")
5003 (setq org-goto-selected-point (point)
5004 org-goto-exit-command 'return)
5005 (throw 'exit nil))
5007 (defun org-goto-left ()
5008 "Finish `org-goto' by going to the new location."
5009 (interactive)
5010 (if (org-on-heading-p)
5011 (progn
5012 (beginning-of-line 1)
5013 (setq org-goto-selected-point (point)
5014 org-goto-exit-command 'left)
5015 (throw 'exit nil))
5016 (error "Not on a heading")))
5018 (defun org-goto-right ()
5019 "Finish `org-goto' by going to the new location."
5020 (interactive)
5021 (if (org-on-heading-p)
5022 (progn
5023 (setq org-goto-selected-point (point)
5024 org-goto-exit-command 'right)
5025 (throw 'exit nil))
5026 (error "Not on a heading")))
5028 (defun org-goto-quit ()
5029 "Finish `org-goto' without cursor motion."
5030 (interactive)
5031 (setq org-goto-selected-point nil)
5032 (setq org-goto-exit-command 'quit)
5033 (throw 'exit nil))
5035 ;;; Indirect buffer display of subtrees
5037 (defvar org-indirect-dedicated-frame nil
5038 "This is the frame being used for indirect tree display.")
5039 (defvar org-last-indirect-buffer nil)
5041 (defun org-tree-to-indirect-buffer (&optional arg)
5042 "Create indirect buffer and narrow it to current subtree.
5043 With numerical prefix ARG, go up to this level and then take that tree.
5044 If ARG is negative, go up that many levels.
5045 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5046 indirect buffer previously made with this command, to avoid proliferation of
5047 indirect buffers. However, when you call the command with a `C-u' prefix, or
5048 when `org-indirect-buffer-display' is `new-frame', the last buffer
5049 is kept so that you can work with several indirect buffers at the same time.
5050 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5051 requests that a new frame be made for the new buffer, so that the dedicated
5052 frame is not changed."
5053 (interactive "P")
5054 (let ((cbuf (current-buffer))
5055 (cwin (selected-window))
5056 (pos (point))
5057 beg end level heading ibuf)
5058 (save-excursion
5059 (org-back-to-heading t)
5060 (when (numberp arg)
5061 (setq level (org-outline-level))
5062 (if (< arg 0) (setq arg (+ level arg)))
5063 (while (> (setq level (org-outline-level)) arg)
5064 (outline-up-heading 1 t)))
5065 (setq beg (point)
5066 heading (org-get-heading))
5067 (org-end-of-subtree t) (setq end (point)))
5068 (if (and (buffer-live-p org-last-indirect-buffer)
5069 (not (eq org-indirect-buffer-display 'new-frame))
5070 (not arg))
5071 (kill-buffer org-last-indirect-buffer))
5072 (setq ibuf (org-get-indirect-buffer cbuf)
5073 org-last-indirect-buffer ibuf)
5074 (cond
5075 ((or (eq org-indirect-buffer-display 'new-frame)
5076 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5077 (select-frame (make-frame))
5078 (delete-other-windows)
5079 (switch-to-buffer ibuf)
5080 (org-set-frame-title heading))
5081 ((eq org-indirect-buffer-display 'dedicated-frame)
5082 (raise-frame
5083 (select-frame (or (and org-indirect-dedicated-frame
5084 (frame-live-p org-indirect-dedicated-frame)
5085 org-indirect-dedicated-frame)
5086 (setq org-indirect-dedicated-frame (make-frame)))))
5087 (delete-other-windows)
5088 (switch-to-buffer ibuf)
5089 (org-set-frame-title (concat "Indirect: " heading)))
5090 ((eq org-indirect-buffer-display 'current-window)
5091 (switch-to-buffer ibuf))
5092 ((eq org-indirect-buffer-display 'other-window)
5093 (pop-to-buffer ibuf))
5094 (t (error "Invalid value.")))
5095 (if (featurep 'xemacs)
5096 (save-excursion (org-mode) (turn-on-font-lock)))
5097 (narrow-to-region beg end)
5098 (show-all)
5099 (goto-char pos)
5100 (and (window-live-p cwin) (select-window cwin))))
5102 (defun org-get-indirect-buffer (&optional buffer)
5103 (setq buffer (or buffer (current-buffer)))
5104 (let ((n 1) (base (buffer-name buffer)) bname)
5105 (while (buffer-live-p
5106 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5107 (setq n (1+ n)))
5108 (condition-case nil
5109 (make-indirect-buffer buffer bname 'clone)
5110 (error (make-indirect-buffer buffer bname)))))
5112 (defun org-set-frame-title (title)
5113 "Set the title of the current frame to the string TITLE."
5114 ;; FIXME: how to name a single frame in XEmacs???
5115 (unless (featurep 'xemacs)
5116 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5118 ;;;; Structure editing
5120 ;;; Inserting headlines
5122 (defun org-previous-line-empty-p ()
5123 (save-excursion
5124 (and (not (bobp))
5125 (or (beginning-of-line 0) t)
5126 (save-match-data
5127 (looking-at "[ \t]*$")))))
5129 (defun org-insert-heading (&optional force-heading)
5130 "Insert a new heading or item with same depth at point.
5131 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5132 If point is at the beginning of a headline, insert a sibling before the
5133 current headline. If point is not at the beginning, do not split the line,
5134 but create the new headline after the current line."
5135 (interactive "P")
5136 (if (= (buffer-size) 0)
5137 (insert "\n* ")
5138 (when (or force-heading (not (org-insert-item)))
5139 (let* ((empty-line-p nil)
5140 (head (save-excursion
5141 (condition-case nil
5142 (progn
5143 (org-back-to-heading)
5144 (setq empty-line-p (org-previous-line-empty-p))
5145 (match-string 0))
5146 (error "*"))))
5147 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5148 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5149 pos hide-previous previous-pos)
5150 (cond
5151 ((and (org-on-heading-p) (bolp)
5152 (or (bobp)
5153 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5154 ;; insert before the current line
5155 (open-line (if blank 2 1)))
5156 ((and (bolp)
5157 (or (bobp)
5158 (save-excursion
5159 (backward-char 1) (not (org-invisible-p)))))
5160 ;; insert right here
5161 nil)
5163 ;; somewhere in the line
5164 (save-excursion
5165 (setq previous-pos (point-at-bol))
5166 (end-of-line)
5167 (setq hide-previous (org-invisible-p)))
5168 (and org-insert-heading-respect-content (org-show-subtree))
5169 (let ((split
5170 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5171 (save-excursion
5172 (let ((p (point)))
5173 (goto-char (point-at-bol))
5174 (and (looking-at org-complex-heading-regexp)
5175 (> p (match-beginning 4)))))))
5176 tags pos)
5177 (cond
5178 (org-insert-heading-respect-content
5179 (org-end-of-subtree nil t)
5180 (or (bolp) (newline))
5181 (or (org-previous-line-empty-p)
5182 (and blank (newline)))
5183 (open-line 1))
5184 ((org-on-heading-p)
5185 (when hide-previous
5186 (show-children)
5187 (org-show-entry))
5188 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5189 (setq tags (and (match-end 2) (match-string 2)))
5190 (and (match-end 1)
5191 (delete-region (match-beginning 1) (match-end 1)))
5192 (setq pos (point-at-bol))
5193 (or split (end-of-line 1))
5194 (delete-horizontal-space)
5195 (newline (if blank 2 1))
5196 (when tags
5197 (save-excursion
5198 (goto-char pos)
5199 (end-of-line 1)
5200 (insert " " tags)
5201 (org-set-tags nil 'align))))
5203 (or split (end-of-line 1))
5204 (newline (if blank 2 1)))))))
5205 (insert head) (just-one-space)
5206 (setq pos (point))
5207 (end-of-line 1)
5208 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5209 (when (and org-insert-heading-respect-content hide-previous)
5210 (save-excursion
5211 (goto-char previous-pos)
5212 (hide-subtree)))
5213 (run-hooks 'org-insert-heading-hook)))))
5215 (defun org-get-heading (&optional no-tags)
5216 "Return the heading of the current entry, without the stars."
5217 (save-excursion
5218 (org-back-to-heading t)
5219 (if (looking-at
5220 (if no-tags
5221 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5222 "\\*+[ \t]+\\([^\r\n]*\\)"))
5223 (match-string 1) "")))
5225 (defun org-heading-components ()
5226 "Return the components of the current heading.
5227 This is a list with the following elements:
5228 - the level as an integer
5229 - the reduced level, different if `org-odd-levels-only' is set.
5230 - the TODO keyword, or nil
5231 - the priority character, like ?A, or nil if no priority is given
5232 - the headline text itself, or the tags string if no headline text
5233 - the tags string, or nil."
5234 (save-excursion
5235 (org-back-to-heading t)
5236 (if (looking-at org-complex-heading-regexp)
5237 (list (length (match-string 1))
5238 (org-reduced-level (length (match-string 1)))
5239 (org-match-string-no-properties 2)
5240 (and (match-end 3) (aref (match-string 3) 2))
5241 (org-match-string-no-properties 4)
5242 (org-match-string-no-properties 5)))))
5244 (defun org-insert-heading-after-current ()
5245 "Insert a new heading with same level as current, after current subtree."
5246 (interactive)
5247 (org-back-to-heading)
5248 (org-insert-heading)
5249 (org-move-subtree-down)
5250 (end-of-line 1))
5252 (defun org-insert-heading-respect-content ()
5253 (interactive)
5254 (let ((org-insert-heading-respect-content t))
5255 (org-insert-heading t)))
5257 (defun org-insert-todo-heading-respect-content (&optional force-state)
5258 (interactive "P")
5259 (let ((org-insert-heading-respect-content t))
5260 (org-insert-todo-heading force-state t)))
5262 (defun org-insert-todo-heading (arg &optional force-heading)
5263 "Insert a new heading with the same level and TODO state as current heading.
5264 If the heading has no TODO state, or if the state is DONE, use the first
5265 state (TODO by default). Also with prefix arg, force first state."
5266 (interactive "P")
5267 (when (or force-heading (not (org-insert-item 'checkbox)))
5268 (org-insert-heading force-heading)
5269 (save-excursion
5270 (org-back-to-heading)
5271 (outline-previous-heading)
5272 (looking-at org-todo-line-regexp))
5273 (let*
5274 ((new-mark-x
5275 (if (or arg
5276 (not (match-beginning 2))
5277 (member (match-string 2) org-done-keywords))
5278 (car org-todo-keywords-1)
5279 (match-string 2)))
5280 (new-mark
5282 (run-hook-with-args-until-success
5283 'org-todo-get-default-hook new-mark-x nil)
5284 new-mark-x)))
5285 (insert new-mark " "))
5286 (when org-provide-todo-statistics
5287 (org-update-parent-todo-statistics))))
5289 (defun org-insert-subheading (arg)
5290 "Insert a new subheading and demote it.
5291 Works for outline headings and for plain lists alike."
5292 (interactive "P")
5293 (org-insert-heading arg)
5294 (cond
5295 ((org-on-heading-p) (org-do-demote))
5296 ((org-at-item-p) (org-indent-item 1))))
5298 (defun org-insert-todo-subheading (arg)
5299 "Insert a new subheading with TODO keyword or checkbox and demote it.
5300 Works for outline headings and for plain lists alike."
5301 (interactive "P")
5302 (org-insert-todo-heading arg)
5303 (cond
5304 ((org-on-heading-p) (org-do-demote))
5305 ((org-at-item-p) (org-indent-item 1))))
5307 ;;; Promotion and Demotion
5309 (defun org-promote-subtree ()
5310 "Promote the entire subtree.
5311 See also `org-promote'."
5312 (interactive)
5313 (save-excursion
5314 (org-map-tree 'org-promote))
5315 (org-fix-position-after-promote))
5317 (defun org-demote-subtree ()
5318 "Demote the entire subtree. See `org-demote'.
5319 See also `org-promote'."
5320 (interactive)
5321 (save-excursion
5322 (org-map-tree 'org-demote))
5323 (org-fix-position-after-promote))
5326 (defun org-do-promote ()
5327 "Promote the current heading higher up the tree.
5328 If the region is active in `transient-mark-mode', promote all headings
5329 in the region."
5330 (interactive)
5331 (save-excursion
5332 (if (org-region-active-p)
5333 (org-map-region 'org-promote (region-beginning) (region-end))
5334 (org-promote)))
5335 (org-fix-position-after-promote))
5337 (defun org-do-demote ()
5338 "Demote the current heading lower down the tree.
5339 If the region is active in `transient-mark-mode', demote all headings
5340 in the region."
5341 (interactive)
5342 (save-excursion
5343 (if (org-region-active-p)
5344 (org-map-region 'org-demote (region-beginning) (region-end))
5345 (org-demote)))
5346 (org-fix-position-after-promote))
5348 (defun org-fix-position-after-promote ()
5349 "Make sure that after pro/demotion cursor position is right."
5350 (let ((pos (point)))
5351 (when (save-excursion
5352 (beginning-of-line 1)
5353 (looking-at org-todo-line-regexp)
5354 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5355 (cond ((eobp) (insert " "))
5356 ((eolp) (insert " "))
5357 ((equal (char-after) ?\ ) (forward-char 1))))))
5359 (defun org-reduced-level (l)
5360 "Compute the effective level of a heading.
5361 This takes into account the setting of `org-odd-levels-only'."
5362 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5364 (defun org-get-valid-level (level &optional change)
5365 "Rectify a level change under the influence of `org-odd-levels-only'
5366 LEVEL is a current level, CHANGE is by how much the level should be
5367 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5368 even level numbers will become the next higher odd number."
5369 (if org-odd-levels-only
5370 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5371 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5372 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5373 (max 1 (+ level (or change 0)))))
5375 (if (boundp 'define-obsolete-function-alias)
5376 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5377 (define-obsolete-function-alias 'org-get-legal-level
5378 'org-get-valid-level)
5379 (define-obsolete-function-alias 'org-get-legal-level
5380 'org-get-valid-level "23.1")))
5382 (defun org-promote ()
5383 "Promote the current heading higher up the tree.
5384 If the region is active in `transient-mark-mode', promote all headings
5385 in the region."
5386 (org-back-to-heading t)
5387 (let* ((level (save-match-data (funcall outline-level)))
5388 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5389 (diff (abs (- level (length up-head) -1))))
5390 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5391 (replace-match up-head nil t)
5392 ;; Fixup tag positioning
5393 (and org-auto-align-tags (org-set-tags nil t))
5394 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5396 (defun org-demote ()
5397 "Demote the current heading lower down the tree.
5398 If the region is active in `transient-mark-mode', demote all headings
5399 in the region."
5400 (org-back-to-heading t)
5401 (let* ((level (save-match-data (funcall outline-level)))
5402 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5403 (diff (abs (- level (length down-head) -1))))
5404 (replace-match down-head nil t)
5405 ;; Fixup tag positioning
5406 (and org-auto-align-tags (org-set-tags nil t))
5407 (if org-adapt-indentation (org-fixup-indentation diff))))
5409 (defun org-map-tree (fun)
5410 "Call FUN for every heading underneath the current one."
5411 (org-back-to-heading)
5412 (let ((level (funcall outline-level)))
5413 (save-excursion
5414 (funcall fun)
5415 (while (and (progn
5416 (outline-next-heading)
5417 (> (funcall outline-level) level))
5418 (not (eobp)))
5419 (funcall fun)))))
5421 (defun org-map-region (fun beg end)
5422 "Call FUN for every heading between BEG and END."
5423 (let ((org-ignore-region t))
5424 (save-excursion
5425 (setq end (copy-marker end))
5426 (goto-char beg)
5427 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5428 (< (point) end))
5429 (funcall fun))
5430 (while (and (progn
5431 (outline-next-heading)
5432 (< (point) end))
5433 (not (eobp)))
5434 (funcall fun)))))
5436 (defun org-fixup-indentation (diff)
5437 "Change the indentation in the current entry by DIFF
5438 However, if any line in the current entry has no indentation, or if it
5439 would end up with no indentation after the change, nothing at all is done."
5440 (save-excursion
5441 (let ((end (save-excursion (outline-next-heading)
5442 (point-marker)))
5443 (prohibit (if (> diff 0)
5444 "^\\S-"
5445 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5446 col)
5447 (unless (save-excursion (end-of-line 1)
5448 (re-search-forward prohibit end t))
5449 (while (and (< (point) end)
5450 (re-search-forward "^[ \t]+" end t))
5451 (goto-char (match-end 0))
5452 (setq col (current-column))
5453 (if (< diff 0) (replace-match ""))
5454 (org-indent-to-column (+ diff col))))
5455 (move-marker end nil))))
5457 (defun org-convert-to-odd-levels ()
5458 "Convert an org-mode file with all levels allowed to one with odd levels.
5459 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5460 level 5 etc."
5461 (interactive)
5462 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5463 (let ((org-odd-levels-only nil) n)
5464 (save-excursion
5465 (goto-char (point-min))
5466 (while (re-search-forward "^\\*\\*+ " nil t)
5467 (setq n (- (length (match-string 0)) 2))
5468 (while (>= (setq n (1- n)) 0)
5469 (org-demote))
5470 (end-of-line 1))))))
5473 (defun org-convert-to-oddeven-levels ()
5474 "Convert an org-mode file with only odd levels to one with odd and even levels.
5475 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5476 section with an even level, conversion would destroy the structure of the file. An error
5477 is signaled in this case."
5478 (interactive)
5479 (goto-char (point-min))
5480 ;; First check if there are no even levels
5481 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5482 (org-show-context t)
5483 (error "Not all levels are odd in this file. Conversion not possible."))
5484 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5485 (let ((org-odd-levels-only nil) n)
5486 (save-excursion
5487 (goto-char (point-min))
5488 (while (re-search-forward "^\\*\\*+ " nil t)
5489 (setq n (/ (1- (length (match-string 0))) 2))
5490 (while (>= (setq n (1- n)) 0)
5491 (org-promote))
5492 (end-of-line 1))))))
5494 (defun org-tr-level (n)
5495 "Make N odd if required."
5496 (if org-odd-levels-only (1+ (/ n 2)) n))
5498 ;;; Vertical tree motion, cutting and pasting of subtrees
5500 (defun org-move-subtree-up (&optional arg)
5501 "Move the current subtree up past ARG headlines of the same level."
5502 (interactive "p")
5503 (org-move-subtree-down (- (prefix-numeric-value arg))))
5505 (defun org-move-subtree-down (&optional arg)
5506 "Move the current subtree down past ARG headlines of the same level."
5507 (interactive "p")
5508 (setq arg (prefix-numeric-value arg))
5509 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5510 'outline-get-last-sibling))
5511 (ins-point (make-marker))
5512 (cnt (abs arg))
5513 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5514 ;; Select the tree
5515 (org-back-to-heading)
5516 (setq beg0 (point))
5517 (save-excursion
5518 (setq ne-beg (org-back-over-empty-lines))
5519 (setq beg (point)))
5520 (save-match-data
5521 (save-excursion (outline-end-of-heading)
5522 (setq folded (org-invisible-p)))
5523 (outline-end-of-subtree))
5524 (outline-next-heading)
5525 (setq ne-end (org-back-over-empty-lines))
5526 (setq end (point))
5527 (goto-char beg0)
5528 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5529 ;; include less whitespace
5530 (save-excursion
5531 (goto-char beg)
5532 (forward-line (- ne-beg ne-end))
5533 (setq beg (point))))
5534 ;; Find insertion point, with error handling
5535 (while (> cnt 0)
5536 (or (and (funcall movfunc) (looking-at outline-regexp))
5537 (progn (goto-char beg0)
5538 (error "Cannot move past superior level or buffer limit")))
5539 (setq cnt (1- cnt)))
5540 (if (> arg 0)
5541 ;; Moving forward - still need to move over subtree
5542 (progn (org-end-of-subtree t t)
5543 (save-excursion
5544 (org-back-over-empty-lines)
5545 (or (bolp) (newline)))))
5546 (setq ne-ins (org-back-over-empty-lines))
5547 (move-marker ins-point (point))
5548 (setq txt (buffer-substring beg end))
5549 (org-save-markers-in-region beg end)
5550 (delete-region beg end)
5551 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5552 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5553 (let ((bbb (point)))
5554 (insert-before-markers txt)
5555 (org-reinstall-markers-in-region bbb)
5556 (move-marker ins-point bbb))
5557 (or (bolp) (insert "\n"))
5558 (setq ins-end (point))
5559 (goto-char ins-point)
5560 (org-skip-whitespace)
5561 (when (and (< arg 0)
5562 (org-first-sibling-p)
5563 (> ne-ins ne-beg))
5564 ;; Move whitespace back to beginning
5565 (save-excursion
5566 (goto-char ins-end)
5567 (let ((kill-whole-line t))
5568 (kill-line (- ne-ins ne-beg)) (point)))
5569 (insert (make-string (- ne-ins ne-beg) ?\n)))
5570 (move-marker ins-point nil)
5571 (org-compact-display-after-subtree-move)
5572 (org-show-empty-lines-in-parent)
5573 (unless folded
5574 (org-show-entry)
5575 (show-children)
5576 (org-cycle-hide-drawers 'children))))
5578 (defvar org-subtree-clip ""
5579 "Clipboard for cut and paste of subtrees.
5580 This is actually only a copy of the kill, because we use the normal kill
5581 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5583 (defvar org-subtree-clip-folded nil
5584 "Was the last copied subtree folded?
5585 This is used to fold the tree back after pasting.")
5587 (defun org-cut-subtree (&optional n)
5588 "Cut the current subtree into the clipboard.
5589 With prefix arg N, cut this many sequential subtrees.
5590 This is a short-hand for marking the subtree and then cutting it."
5591 (interactive "p")
5592 (org-copy-subtree n 'cut))
5594 (defun org-copy-subtree (&optional n cut force-store-markers)
5595 "Cut the current subtree into the clipboard.
5596 With prefix arg N, cut this many sequential subtrees.
5597 This is a short-hand for marking the subtree and then copying it.
5598 If CUT is non-nil, actually cut the subtree.
5599 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5600 of some markers in the region, even if CUT is non-nil. This is
5601 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5602 (interactive "p")
5603 (let (beg end folded (beg0 (point)))
5604 (if (interactive-p)
5605 (org-back-to-heading nil) ; take what looks like a subtree
5606 (org-back-to-heading t)) ; take what is really there
5607 (org-back-over-empty-lines)
5608 (setq beg (point))
5609 (skip-chars-forward " \t\r\n")
5610 (save-match-data
5611 (save-excursion (outline-end-of-heading)
5612 (setq folded (org-invisible-p)))
5613 (condition-case nil
5614 (outline-forward-same-level (1- n))
5615 (error nil))
5616 (org-end-of-subtree t t))
5617 (org-back-over-empty-lines)
5618 (setq end (point))
5619 (goto-char beg0)
5620 (when (> end beg)
5621 (setq org-subtree-clip-folded folded)
5622 (when (or cut force-store-markers)
5623 (org-save-markers-in-region beg end))
5624 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5625 (setq org-subtree-clip (current-kill 0))
5626 (message "%s: Subtree(s) with %d characters"
5627 (if cut "Cut" "Copied")
5628 (length org-subtree-clip)))))
5630 (defun org-paste-subtree (&optional level tree for-yank)
5631 "Paste the clipboard as a subtree, with modification of headline level.
5632 The entire subtree is promoted or demoted in order to match a new headline
5633 level.
5635 If the cursor is at the beginning of a headline, the same level as
5636 that headline is used to paste the tree
5638 If not, the new level is derived from the *visible* headings
5639 before and after the insertion point, and taken to be the inferior headline
5640 level of the two. So if the previous visible heading is level 3 and the
5641 next is level 4 (or vice versa), level 4 will be used for insertion.
5642 This makes sure that the subtree remains an independent subtree and does
5643 not swallow low level entries.
5645 You can also force a different level, either by using a numeric prefix
5646 argument, or by inserting the heading marker by hand. For example, if the
5647 cursor is after \"*****\", then the tree will be shifted to level 5.
5649 If optional TREE is given, use this text instead of the kill ring.
5651 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5652 move back over whitespace before inserting, and move point to the end of
5653 the inserted text when done."
5654 (interactive "P")
5655 (unless (org-kill-is-subtree-p tree)
5656 (error "%s"
5657 (substitute-command-keys
5658 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5659 (let* ((visp (not (org-invisible-p)))
5660 (txt (or tree (and kill-ring (current-kill 0))))
5661 (^re (concat "^\\(" outline-regexp "\\)"))
5662 (re (concat "\\(" outline-regexp "\\)"))
5663 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5665 (old-level (if (string-match ^re txt)
5666 (- (match-end 0) (match-beginning 0) 1)
5667 -1))
5668 (force-level (cond (level (prefix-numeric-value level))
5669 ((and (looking-at "[ \t]*$")
5670 (string-match
5671 ^re_ (buffer-substring
5672 (point-at-bol) (point))))
5673 (- (match-end 1) (match-beginning 1)))
5674 ((and (bolp)
5675 (looking-at org-outline-regexp))
5676 (- (match-end 0) (point) 1))
5677 (t nil)))
5678 (previous-level (save-excursion
5679 (condition-case nil
5680 (progn
5681 (outline-previous-visible-heading 1)
5682 (if (looking-at re)
5683 (- (match-end 0) (match-beginning 0) 1)
5685 (error 1))))
5686 (next-level (save-excursion
5687 (condition-case nil
5688 (progn
5689 (or (looking-at outline-regexp)
5690 (outline-next-visible-heading 1))
5691 (if (looking-at re)
5692 (- (match-end 0) (match-beginning 0) 1)
5694 (error 1))))
5695 (new-level (or force-level (max previous-level next-level)))
5696 (shift (if (or (= old-level -1)
5697 (= new-level -1)
5698 (= old-level new-level))
5700 (- new-level old-level)))
5701 (delta (if (> shift 0) -1 1))
5702 (func (if (> shift 0) 'org-demote 'org-promote))
5703 (org-odd-levels-only nil)
5704 beg end newend)
5705 ;; Remove the forced level indicator
5706 (if force-level
5707 (delete-region (point-at-bol) (point)))
5708 ;; Paste
5709 (beginning-of-line 1)
5710 (unless for-yank (org-back-over-empty-lines))
5711 (setq beg (point))
5712 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5713 (insert-before-markers txt)
5714 (unless (string-match "\n\\'" txt) (insert "\n"))
5715 (setq newend (point))
5716 (org-reinstall-markers-in-region beg)
5717 (setq end (point))
5718 (goto-char beg)
5719 (skip-chars-forward " \t\n\r")
5720 (setq beg (point))
5721 (if (and (org-invisible-p) visp)
5722 (save-excursion (outline-show-heading)))
5723 ;; Shift if necessary
5724 (unless (= shift 0)
5725 (save-restriction
5726 (narrow-to-region beg end)
5727 (while (not (= shift 0))
5728 (org-map-region func (point-min) (point-max))
5729 (setq shift (+ delta shift)))
5730 (goto-char (point-min))
5731 (setq newend (point-max))))
5732 (when (or (interactive-p) for-yank)
5733 (message "Clipboard pasted as level %d subtree" new-level))
5734 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5735 kill-ring
5736 (eq org-subtree-clip (current-kill 0))
5737 org-subtree-clip-folded)
5738 ;; The tree was folded before it was killed/copied
5739 (hide-subtree))
5740 (and for-yank (goto-char newend))))
5742 (defun org-kill-is-subtree-p (&optional txt)
5743 "Check if the current kill is an outline subtree, or a set of trees.
5744 Returns nil if kill does not start with a headline, or if the first
5745 headline level is not the largest headline level in the tree.
5746 So this will actually accept several entries of equal levels as well,
5747 which is OK for `org-paste-subtree'.
5748 If optional TXT is given, check this string instead of the current kill."
5749 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5750 (start-level (and kill
5751 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5752 org-outline-regexp "\\)")
5753 kill)
5754 (- (match-end 2) (match-beginning 2) 1)))
5755 (re (concat "^" org-outline-regexp))
5756 (start (1+ (or (match-beginning 2) -1))))
5757 (if (not start-level)
5758 (progn
5759 nil) ;; does not even start with a heading
5760 (catch 'exit
5761 (while (setq start (string-match re kill (1+ start)))
5762 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5763 (throw 'exit nil)))
5764 t))))
5766 (defvar org-markers-to-move nil
5767 "Markers that should be moved with a cut-and-paste operation.
5768 Those markers are stored together with their positions relative to
5769 the start of the region.")
5771 (defun org-save-markers-in-region (beg end)
5772 "Check markers in region.
5773 If these markers are between BEG and END, record their position relative
5774 to BEG, so that after moving the block of text, we can put the markers back
5775 into place.
5776 This function gets called just before an entry or tree gets cut from the
5777 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5778 called immediately, to move the markers with the entries."
5779 (setq org-markers-to-move nil)
5780 (when (featurep 'org-clock)
5781 (org-clock-save-markers-for-cut-and-paste beg end))
5782 (when (featurep 'org-agenda)
5783 (org-agenda-save-markers-for-cut-and-paste beg end)))
5785 (defun org-check-and-save-marker (marker beg end)
5786 "Check if MARKER is between BEG and END.
5787 If yes, remember the marker and the distance to BEG."
5788 (when (and (marker-buffer marker)
5789 (equal (marker-buffer marker) (current-buffer)))
5790 (if (and (>= marker beg) (< marker end))
5791 (push (cons marker (- marker beg)) org-markers-to-move))))
5793 (defun org-reinstall-markers-in-region (beg)
5794 "Move all remembered markers to their position relative to BEG."
5795 (mapc (lambda (x)
5796 (move-marker (car x) (+ beg (cdr x))))
5797 org-markers-to-move)
5798 (setq org-markers-to-move nil))
5800 (defun org-narrow-to-subtree ()
5801 "Narrow buffer to the current subtree."
5802 (interactive)
5803 (save-excursion
5804 (save-match-data
5805 (narrow-to-region
5806 (progn (org-back-to-heading) (point))
5807 (progn (org-end-of-subtree t) (point))))))
5810 ;;; Outline Sorting
5812 (defun org-sort (with-case)
5813 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5814 Optional argument WITH-CASE means sort case-sensitively.
5815 With a double prefix argument, also remove duplicate entries."
5816 (interactive "P")
5817 (if (org-at-table-p)
5818 (org-call-with-arg 'org-table-sort-lines with-case)
5819 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5821 (defun org-sort-remove-invisible (s)
5822 (remove-text-properties 0 (length s) org-rm-props s)
5823 (while (string-match org-bracket-link-regexp s)
5824 (setq s (replace-match (if (match-end 2)
5825 (match-string 3 s)
5826 (match-string 1 s)) t t s)))
5829 (defvar org-priority-regexp) ; defined later in the file
5831 (defun org-sort-entries-or-items
5832 (&optional with-case sorting-type getkey-func compare-func property)
5833 "Sort entries on a certain level of an outline tree.
5834 If there is an active region, the entries in the region are sorted.
5835 Else, if the cursor is before the first entry, sort the top-level items.
5836 Else, the children of the entry at point are sorted.
5838 Sorting can be alphabetically, numerically, and by date/time as given by
5839 the first time stamp in the entry. The command prompts for the sorting
5840 type unless it has been given to the function through the SORTING-TYPE
5841 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5842 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5843 called with point at the beginning of the record. It must return either
5844 a string or a number that should serve as the sorting key for that record.
5846 Comparing entries ignores case by default. However, with an optional argument
5847 WITH-CASE, the sorting considers case as well."
5848 (interactive "P")
5849 (let ((case-func (if with-case 'identity 'downcase))
5850 start beg end stars re re2
5851 txt what tmp plain-list-p)
5852 ;; Find beginning and end of region to sort
5853 (cond
5854 ((org-region-active-p)
5855 ;; we will sort the region
5856 (setq end (region-end)
5857 what "region")
5858 (goto-char (region-beginning))
5859 (if (not (org-on-heading-p)) (outline-next-heading))
5860 (setq start (point)))
5861 ((org-at-item-p)
5862 ;; we will sort this plain list
5863 (org-beginning-of-item-list) (setq start (point))
5864 (org-end-of-item-list) (setq end (point))
5865 (goto-char start)
5866 (setq plain-list-p t
5867 what "plain list"))
5868 ((or (org-on-heading-p)
5869 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5870 ;; we will sort the children of the current headline
5871 (org-back-to-heading)
5872 (setq start (point)
5873 end (progn (org-end-of-subtree t t)
5874 (org-back-over-empty-lines)
5875 (point))
5876 what "children")
5877 (goto-char start)
5878 (show-subtree)
5879 (outline-next-heading))
5881 ;; we will sort the top-level entries in this file
5882 (goto-char (point-min))
5883 (or (org-on-heading-p) (outline-next-heading))
5884 (setq start (point) end (point-max) what "top-level")
5885 (goto-char start)
5886 (show-all)))
5888 (setq beg (point))
5889 (if (>= beg end) (error "Nothing to sort"))
5891 (unless plain-list-p
5892 (looking-at "\\(\\*+\\)")
5893 (setq stars (match-string 1)
5894 re (concat "^" (regexp-quote stars) " +")
5895 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5896 txt (buffer-substring beg end))
5897 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5898 (if (and (not (equal stars "*")) (string-match re2 txt))
5899 (error "Region to sort contains a level above the first entry")))
5901 (unless sorting-type
5902 (message
5903 (if plain-list-p
5904 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5905 "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:")
5906 what)
5907 (setq sorting-type (read-char-exclusive))
5909 (and (= (downcase sorting-type) ?f)
5910 (setq getkey-func
5911 (org-ido-completing-read "Sort using function: "
5912 obarray 'fboundp t nil nil))
5913 (setq getkey-func (intern getkey-func)))
5915 (and (= (downcase sorting-type) ?r)
5916 (setq property
5917 (org-ido-completing-read "Property: "
5918 (mapcar 'list (org-buffer-property-keys t))
5919 nil t))))
5921 (message "Sorting entries...")
5923 (save-restriction
5924 (narrow-to-region start end)
5926 (let ((dcst (downcase sorting-type))
5927 (now (current-time)))
5928 (sort-subr
5929 (/= dcst sorting-type)
5930 ;; This function moves to the beginning character of the "record" to
5931 ;; be sorted.
5932 (if plain-list-p
5933 (lambda nil
5934 (if (org-at-item-p) t (goto-char (point-max))))
5935 (lambda nil
5936 (if (re-search-forward re nil t)
5937 (goto-char (match-beginning 0))
5938 (goto-char (point-max)))))
5939 ;; This function moves to the last character of the "record" being
5940 ;; sorted.
5941 (if plain-list-p
5942 'org-end-of-item
5943 (lambda nil
5944 (save-match-data
5945 (condition-case nil
5946 (outline-forward-same-level 1)
5947 (error
5948 (goto-char (point-max)))))))
5950 ;; This function returns the value that gets sorted against.
5951 (if plain-list-p
5952 (lambda nil
5953 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5954 (cond
5955 ((= dcst ?n)
5956 (string-to-number (buffer-substring (match-end 0)
5957 (point-at-eol))))
5958 ((= dcst ?a)
5959 (buffer-substring (match-end 0) (point-at-eol)))
5960 ((= dcst ?t)
5961 (if (re-search-forward org-ts-regexp
5962 (point-at-eol) t)
5963 (org-time-string-to-time (match-string 0))
5964 now))
5965 ((= dcst ?f)
5966 (if getkey-func
5967 (progn
5968 (setq tmp (funcall getkey-func))
5969 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5970 tmp)
5971 (error "Invalid key function `%s'" getkey-func)))
5972 (t (error "Invalid sorting type `%c'" sorting-type)))))
5973 (lambda nil
5974 (cond
5975 ((= dcst ?n)
5976 (if (looking-at org-complex-heading-regexp)
5977 (string-to-number (match-string 4))
5978 nil))
5979 ((= dcst ?a)
5980 (if (looking-at org-complex-heading-regexp)
5981 (funcall case-func (match-string 4))
5982 nil))
5983 ((= dcst ?t)
5984 (if (re-search-forward org-ts-regexp
5985 (save-excursion
5986 (forward-line 2)
5987 (point)) t)
5988 (org-time-string-to-time (match-string 0))
5989 now))
5990 ((= dcst ?p)
5991 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5992 (string-to-char (match-string 2))
5993 org-default-priority))
5994 ((= dcst ?r)
5995 (or (org-entry-get nil property) ""))
5996 ((= dcst ?o)
5997 (if (looking-at org-complex-heading-regexp)
5998 (- 9999 (length (member (match-string 2)
5999 org-todo-keywords-1)))))
6000 ((= dcst ?f)
6001 (if getkey-func
6002 (progn
6003 (setq tmp (funcall getkey-func))
6004 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6005 tmp)
6006 (error "Invalid key function `%s'" getkey-func)))
6007 (t (error "Invalid sorting type `%c'" sorting-type)))))
6009 (cond
6010 ((= dcst ?a) 'string<)
6011 ((= dcst ?t) 'time-less-p)
6012 ((= dcst ?f) compare-func)
6013 (t nil)))))
6014 (message "Sorting entries...done")))
6016 (defun org-do-sort (table what &optional with-case sorting-type)
6017 "Sort TABLE of WHAT according to SORTING-TYPE.
6018 The user will be prompted for the SORTING-TYPE if the call to this
6019 function does not specify it. WHAT is only for the prompt, to indicate
6020 what is being sorted. The sorting key will be extracted from
6021 the car of the elements of the table.
6022 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6023 (unless sorting-type
6024 (message
6025 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6026 what)
6027 (setq sorting-type (read-char-exclusive)))
6028 (let ((dcst (downcase sorting-type))
6029 extractfun comparefun)
6030 ;; Define the appropriate functions
6031 (cond
6032 ((= dcst ?n)
6033 (setq extractfun 'string-to-number
6034 comparefun (if (= dcst sorting-type) '< '>)))
6035 ((= dcst ?a)
6036 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6037 (lambda(x) (downcase (org-sort-remove-invisible x))))
6038 comparefun (if (= dcst sorting-type)
6039 'string<
6040 (lambda (a b) (and (not (string< a b))
6041 (not (string= a b)))))))
6042 ((= dcst ?t)
6043 (setq extractfun
6044 (lambda (x)
6045 (if (or (string-match org-ts-regexp x)
6046 (string-match org-ts-regexp-both x))
6047 (time-to-seconds
6048 (org-time-string-to-time (match-string 0 x)))
6050 comparefun (if (= dcst sorting-type) '< '>)))
6051 (t (error "Invalid sorting type `%c'" sorting-type)))
6053 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6054 table)
6055 (lambda (a b) (funcall comparefun (car a) (car b))))))
6057 ;;; Editing source examples
6059 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6060 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6061 (defvar org-edit-src-force-single-line nil)
6062 (defvar org-edit-src-from-org-mode nil)
6063 (defvar org-edit-src-picture nil)
6065 (define-minor-mode org-exit-edit-mode
6066 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6068 (defun org-edit-src-code ()
6069 "Edit the source code example at point.
6070 An indirect buffer is created, and that buffer is then narrowed to the
6071 example at point and switched to the correct language mode. When done,
6072 exit by killing the buffer with \\[org-edit-src-exit]."
6073 (interactive)
6074 (let ((line (org-current-line))
6075 (case-fold-search t)
6076 (msg (substitute-command-keys
6077 "Edit, then exit with C-c ' (C-c and single quote)"))
6078 (info (org-edit-src-find-region-and-lang))
6079 (org-mode-p (eq major-mode 'org-mode))
6080 beg end lang lang-f single lfmt)
6081 (if (not info)
6083 (setq beg (nth 0 info)
6084 end (nth 1 info)
6085 lang (nth 2 info)
6086 single (nth 3 info)
6087 lfmt (nth 4 info)
6088 lang-f (intern (concat lang "-mode")))
6089 (unless (functionp lang-f)
6090 (error "No such language mode: %s" lang-f))
6091 (goto-line line)
6092 (if (get-buffer "*Org Edit Src Example*")
6093 (kill-buffer "*Org Edit Src Example*"))
6094 (switch-to-buffer (make-indirect-buffer (current-buffer)
6095 "*Org Edit Src Example*"))
6096 (narrow-to-region beg end)
6097 (remove-text-properties beg end '(display nil invisible nil
6098 intangible nil))
6099 (let ((org-inhibit-startup t))
6100 (funcall lang-f))
6101 (set (make-local-variable 'org-edit-src-force-single-line) single)
6102 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6103 (when lfmt
6104 (set (make-local-variable 'org-coderef-label-format) lfmt))
6105 (when org-mode-p
6106 (goto-char (point-min))
6107 (while (re-search-forward "^," nil t)
6108 (replace-match "")))
6109 (goto-line line)
6110 (org-exit-edit-mode)
6111 (org-set-local 'header-line-format msg)
6112 (message "%s" msg)
6113 t)))
6115 (defun org-edit-fixed-width-region ()
6116 "Edit the fixed-width ascii drawing at point.
6117 This must be a region where each line starts with a colon followed by
6118 a space character.
6119 An indirect buffer is created, and that buffer is then narrowed to the
6120 example at point and switched to artist-mode. When done,
6121 exit by killing the buffer with \\[org-edit-src-exit]."
6122 (interactive)
6123 (let ((line (org-current-line))
6124 (case-fold-search t)
6125 (msg (substitute-command-keys
6126 "Edit, then exit with C-c ' (C-c and single quote)"))
6127 (org-mode-p (eq major-mode 'org-mode))
6128 beg end)
6129 (beginning-of-line 1)
6130 (if (looking-at "[ \t]*[^:\n \t]")
6132 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6133 (setq beg (point) end beg)
6134 (save-excursion
6135 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6136 (setq beg (point-at-bol 2))
6137 (setq beg (point))))
6138 (save-excursion
6139 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6140 (setq end (1- (match-beginning 0)))
6141 (setq end (point))))
6142 (goto-line line))
6143 (if (get-buffer "*Org Edit Picture*")
6144 (kill-buffer "*Org Edit Picture*"))
6145 (switch-to-buffer (make-indirect-buffer (current-buffer)
6146 "*Org Edit Picture*"))
6147 (narrow-to-region beg end)
6148 (remove-text-properties beg end '(display nil invisible nil
6149 intangible nil))
6150 (when (fboundp 'font-lock-unfontify-region)
6151 (font-lock-unfontify-region (point-min) (point-max)))
6152 (cond
6153 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6154 (fundamental-mode)
6155 (artist-mode 1))
6156 (t (funcall org-edit-fixed-width-region-mode)))
6157 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6158 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6159 (set (make-local-variable 'org-edit-src-picture) t)
6160 (goto-char (point-min))
6161 (while (re-search-forward "^[ \t]*: ?" nil t)
6162 (replace-match ""))
6163 (goto-line line)
6164 (org-exit-edit-mode)
6165 (org-set-local 'header-line-format msg)
6166 (message "%s" msg)
6167 t)))
6170 (defun org-edit-src-find-region-and-lang ()
6171 "Find the region and language for a local edit.
6172 Return a list with beginning and end of the region, a string representing
6173 the language, a switch telling of the content should be in a single line."
6174 (let ((re-list
6175 (append
6176 org-edit-src-region-extra
6178 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6179 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6180 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6181 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6182 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6183 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6184 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6185 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6186 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6187 ("^#\\+html:" "\n" "html" single-line)
6188 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6189 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6190 ("^#\\+latex:" "\n" "latex" single-line)
6191 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6192 ("^#\\+ascii:" "\n" "ascii" single-line)
6194 (pos (point))
6195 re1 re2 single beg end lang lfmt match-re1)
6196 (catch 'exit
6197 (while (setq entry (pop re-list))
6198 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6199 single (nth 3 entry))
6200 (save-excursion
6201 (if (or (looking-at re1)
6202 (re-search-backward re1 nil t))
6203 (progn
6204 (setq match-re1 (match-string 0))
6205 (setq beg (match-end 0)
6206 lang (org-edit-src-get-lang lang)
6207 lfmt (org-edit-src-get-label-format match-re1))
6208 (if (and (re-search-forward re2 nil t)
6209 (>= (match-end 0) pos))
6210 (throw 'exit (list beg (match-beginning 0)
6211 lang single lfmt))))
6212 (if (or (looking-at re2)
6213 (re-search-forward re2 nil t))
6214 (progn
6215 (setq end (match-beginning 0))
6216 (if (and (re-search-backward re1 nil t)
6217 (<= (match-beginning 0) pos))
6218 (progn
6219 (setq lfmt (org-edit-src-get-label-format
6220 (match-string 0)))
6221 (throw 'exit
6222 (list (match-end 0) end
6223 (org-edit-src-get-lang lang)
6224 single lfmt))))))))))))
6226 (defun org-edit-src-get-lang (lang)
6227 "Extract the src language."
6228 (let ((m (match-string 0)))
6229 (cond
6230 ((stringp lang) lang)
6231 ((integerp lang) (match-string lang))
6232 ((and (eq lang 'lang)
6233 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6234 (match-string 1 m))
6235 ((and (eq lang 'style)
6236 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6237 (match-string 1 m))
6238 (t "fundamental"))))
6240 (defun org-edit-src-get-label-format (s)
6241 "Extract the label format."
6242 (save-match-data
6243 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6244 (match-string 1 s))))
6246 (defun org-edit-src-exit ()
6247 "Exit special edit and protect problematic lines."
6248 (interactive)
6249 (unless (buffer-base-buffer (current-buffer))
6250 (error "This is not an indirect buffer, something is wrong..."))
6251 (unless (> (point-min) 1)
6252 (error "This buffer is not narrowed, something is wrong..."))
6253 (goto-char (point-min))
6254 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6255 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6256 (when (org-bound-and-true-p org-edit-src-force-single-line)
6257 (goto-char (point-min))
6258 (while (re-search-forward "\n" nil t)
6259 (replace-match " "))
6260 (goto-char (point-min))
6261 (if (looking-at "\\s-*") (replace-match " "))
6262 (if (re-search-forward "\\s-+\\'" nil t)
6263 (replace-match "")))
6264 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6265 (goto-char (point-min))
6266 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6267 (replace-match ",\\1"))
6268 (when font-lock-mode
6269 (font-lock-unfontify-region (point-min) (point-max)))
6270 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6271 (when (org-bound-and-true-p org-edit-src-picture)
6272 (untabify (point-min) (point-max))
6273 (goto-char (point-min))
6274 (while (re-search-forward "^" nil t)
6275 (replace-match ": "))
6276 (when font-lock-mode
6277 (font-lock-unfontify-region (point-min) (point-max)))
6278 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6279 (kill-buffer (current-buffer))
6280 (and (org-mode-p) (org-restart-font-lock)))
6283 ;;; The orgstruct minor mode
6285 ;; Define a minor mode which can be used in other modes in order to
6286 ;; integrate the org-mode structure editing commands.
6288 ;; This is really a hack, because the org-mode structure commands use
6289 ;; keys which normally belong to the major mode. Here is how it
6290 ;; works: The minor mode defines all the keys necessary to operate the
6291 ;; structure commands, but wraps the commands into a function which
6292 ;; tests if the cursor is currently at a headline or a plain list
6293 ;; item. If that is the case, the structure command is used,
6294 ;; temporarily setting many Org-mode variables like regular
6295 ;; expressions for filling etc. However, when any of those keys is
6296 ;; used at a different location, function uses `key-binding' to look
6297 ;; up if the key has an associated command in another currently active
6298 ;; keymap (minor modes, major mode, global), and executes that
6299 ;; command. There might be problems if any of the keys is otherwise
6300 ;; used as a prefix key.
6302 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6303 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6304 ;; addresses this by checking explicitly for both bindings.
6306 (defvar orgstruct-mode-map (make-sparse-keymap)
6307 "Keymap for the minor `orgstruct-mode'.")
6309 (defvar org-local-vars nil
6310 "List of local variables, for use by `orgstruct-mode'")
6312 ;;;###autoload
6313 (define-minor-mode orgstruct-mode
6314 "Toggle the minor more `orgstruct-mode'.
6315 This mode is for using Org-mode structure commands in other modes.
6316 The following key behave as if Org-mode was active, if the cursor
6317 is on a headline, or on a plain list item (both in the definition
6318 of Org-mode).
6320 M-up Move entry/item up
6321 M-down Move entry/item down
6322 M-left Promote
6323 M-right Demote
6324 M-S-up Move entry/item up
6325 M-S-down Move entry/item down
6326 M-S-left Promote subtree
6327 M-S-right Demote subtree
6328 M-q Fill paragraph and items like in Org-mode
6329 C-c ^ Sort entries
6330 C-c - Cycle list bullet
6331 TAB Cycle item visibility
6332 M-RET Insert new heading/item
6333 S-M-RET Insert new TODO heading / Checkbox item
6334 C-c C-c Set tags / toggle checkbox"
6335 nil " OrgStruct" nil
6336 (org-load-modules-maybe)
6337 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6339 ;;;###autoload
6340 (defun turn-on-orgstruct ()
6341 "Unconditionally turn on `orgstruct-mode'."
6342 (orgstruct-mode 1))
6344 (defun orgstruct++-mode (&optional arg)
6345 "Toggle `orgstruct-mode', the enhanced version of it.
6346 In addition to setting orgstruct-mode, this also exports all indentation and
6347 autofilling variables from org-mode into the buffer. It will also
6348 recognize item context in multiline items.
6349 Note that turning off orgstruct-mode will *not* remove the
6350 indentation/paragraph settings. This can only be done by refreshing the
6351 major mode, for example with \[normal-mode]."
6352 (interactive "P")
6353 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6354 (if (< arg 1)
6355 (orgstruct-mode -1)
6356 (orgstruct-mode 1)
6357 (let (var val)
6358 (mapc
6359 (lambda (x)
6360 (when (string-match
6361 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6362 (symbol-name (car x)))
6363 (setq var (car x) val (nth 1 x))
6364 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6365 org-local-vars)
6366 (org-set-local 'orgstruct-is-++ t))))
6368 (defvar orgstruct-is-++ nil
6369 "Is orgstruct-mode in ++ version in the current-buffer?")
6370 (make-variable-buffer-local 'orgstruct-is-++)
6372 ;;;###autoload
6373 (defun turn-on-orgstruct++ ()
6374 "Unconditionally turn on `orgstruct++-mode'."
6375 (orgstruct++-mode 1))
6377 (defun orgstruct-error ()
6378 "Error when there is no default binding for a structure key."
6379 (interactive)
6380 (error "This key has no function outside structure elements"))
6382 (defun orgstruct-setup ()
6383 "Setup orgstruct keymaps."
6384 (let ((nfunc 0)
6385 (bindings
6386 (list
6387 '([(meta up)] org-metaup)
6388 '([(meta down)] org-metadown)
6389 '([(meta left)] org-metaleft)
6390 '([(meta right)] org-metaright)
6391 '([(meta shift up)] org-shiftmetaup)
6392 '([(meta shift down)] org-shiftmetadown)
6393 '([(meta shift left)] org-shiftmetaleft)
6394 '([(meta shift right)] org-shiftmetaright)
6395 '([(shift up)] org-shiftup)
6396 '([(shift down)] org-shiftdown)
6397 '([(shift left)] org-shiftleft)
6398 '([(shift right)] org-shiftright)
6399 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6400 '("\M-q" fill-paragraph)
6401 '("\C-c^" org-sort)
6402 '("\C-c-" org-cycle-list-bullet)))
6403 elt key fun cmd)
6404 (while (setq elt (pop bindings))
6405 (setq nfunc (1+ nfunc))
6406 (setq key (org-key (car elt))
6407 fun (nth 1 elt)
6408 cmd (orgstruct-make-binding fun nfunc key))
6409 (org-defkey orgstruct-mode-map key cmd))
6411 ;; Special treatment needed for TAB and RET
6412 (org-defkey orgstruct-mode-map [(tab)]
6413 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6414 (org-defkey orgstruct-mode-map "\C-i"
6415 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6417 (org-defkey orgstruct-mode-map "\M-\C-m"
6418 (orgstruct-make-binding 'org-insert-heading 105
6419 "\M-\C-m" [(meta return)]))
6420 (org-defkey orgstruct-mode-map [(meta return)]
6421 (orgstruct-make-binding 'org-insert-heading 106
6422 [(meta return)] "\M-\C-m"))
6424 (org-defkey orgstruct-mode-map [(shift meta return)]
6425 (orgstruct-make-binding 'org-insert-todo-heading 107
6426 [(meta return)] "\M-\C-m"))
6428 (unless org-local-vars
6429 (setq org-local-vars (org-get-local-variables)))
6433 (defun orgstruct-make-binding (fun n &rest keys)
6434 "Create a function for binding in the structure minor mode.
6435 FUN is the command to call inside a table. N is used to create a unique
6436 command name. KEYS are keys that should be checked in for a command
6437 to execute outside of tables."
6438 (eval
6439 (list 'defun
6440 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6441 '(arg)
6442 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6443 "Outside of structure, run the binding of `"
6444 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6445 "'.")
6446 '(interactive "p")
6447 (list 'if
6448 `(org-context-p 'headline 'item
6449 (and orgstruct-is-++
6450 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6451 'item-body))
6452 (list 'org-run-like-in-org-mode (list 'quote fun))
6453 (list 'let '(orgstruct-mode)
6454 (list 'call-interactively
6455 (append '(or)
6456 (mapcar (lambda (k)
6457 (list 'key-binding k))
6458 keys)
6459 '('orgstruct-error))))))))
6461 (defun org-context-p (&rest contexts)
6462 "Check if local context is any of CONTEXTS.
6463 Possible values in the list of contexts are `table', `headline', and `item'."
6464 (let ((pos (point)))
6465 (goto-char (point-at-bol))
6466 (prog1 (or (and (memq 'table contexts)
6467 (looking-at "[ \t]*|"))
6468 (and (memq 'headline contexts)
6469 ;;????????? (looking-at "\\*+"))
6470 (looking-at outline-regexp))
6471 (and (memq 'item contexts)
6472 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6473 (and (memq 'item-body contexts)
6474 (org-in-item-p)))
6475 (goto-char pos))))
6477 (defun org-get-local-variables ()
6478 "Return a list of all local variables in an org-mode buffer."
6479 (let (varlist)
6480 (with-current-buffer (get-buffer-create "*Org tmp*")
6481 (erase-buffer)
6482 (org-mode)
6483 (setq varlist (buffer-local-variables)))
6484 (kill-buffer "*Org tmp*")
6485 (delq nil
6486 (mapcar
6487 (lambda (x)
6488 (setq x
6489 (if (symbolp x)
6490 (list x)
6491 (list (car x) (list 'quote (cdr x)))))
6492 (if (string-match
6493 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6494 (symbol-name (car x)))
6495 x nil))
6496 varlist))))
6498 ;;;###autoload
6499 (defun org-run-like-in-org-mode (cmd)
6500 "Run a command, pretending that the current buffer is in Org-mode.
6501 This will temporarily bind local variables that are typically bound in
6502 Org-mode to the values they have in Org-mode, and then interactively
6503 call CMD."
6504 (org-load-modules-maybe)
6505 (unless org-local-vars
6506 (setq org-local-vars (org-get-local-variables)))
6507 (eval (list 'let org-local-vars
6508 (list 'call-interactively (list 'quote cmd)))))
6510 ;;;; Archiving
6512 (defun org-get-category (&optional pos)
6513 "Get the category applying to position POS."
6514 (get-text-property (or pos (point)) 'org-category))
6516 (defun org-refresh-category-properties ()
6517 "Refresh category text properties in the buffer."
6518 (let ((def-cat (cond
6519 ((null org-category)
6520 (if buffer-file-name
6521 (file-name-sans-extension
6522 (file-name-nondirectory buffer-file-name))
6523 "???"))
6524 ((symbolp org-category) (symbol-name org-category))
6525 (t org-category)))
6526 beg end cat pos optionp)
6527 (org-unmodified
6528 (save-excursion
6529 (save-restriction
6530 (widen)
6531 (goto-char (point-min))
6532 (put-text-property (point) (point-max) 'org-category def-cat)
6533 (while (re-search-forward
6534 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6535 (setq pos (match-end 0)
6536 optionp (equal (char-after (match-beginning 0)) ?#)
6537 cat (org-trim (match-string 2)))
6538 (if optionp
6539 (setq beg (point-at-bol) end (point-max))
6540 (org-back-to-heading t)
6541 (setq beg (point) end (org-end-of-subtree t t)))
6542 (put-text-property beg end 'org-category cat)
6543 (goto-char pos)))))))
6546 ;;;; Link Stuff
6548 ;;; Link abbreviations
6550 (defun org-link-expand-abbrev (link)
6551 "Apply replacements as defined in `org-link-abbrev-alist."
6552 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6553 (let* ((key (match-string 1 link))
6554 (as (or (assoc key org-link-abbrev-alist-local)
6555 (assoc key org-link-abbrev-alist)))
6556 (tag (and (match-end 2) (match-string 3 link)))
6557 rpl)
6558 (if (not as)
6559 link
6560 (setq rpl (cdr as))
6561 (cond
6562 ((symbolp rpl) (funcall rpl tag))
6563 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6564 ((string-match "%h" rpl)
6565 (replace-match (url-hexify-string (or tag "")) t t rpl))
6566 (t (concat rpl tag)))))
6567 link))
6569 ;;; Storing and inserting links
6571 (defvar org-insert-link-history nil
6572 "Minibuffer history for links inserted with `org-insert-link'.")
6574 (defvar org-stored-links nil
6575 "Contains the links stored with `org-store-link'.")
6577 (defvar org-store-link-plist nil
6578 "Plist with info about the most recently link created with `org-store-link'.")
6580 (defvar org-link-protocols nil
6581 "Link protocols added to Org-mode using `org-add-link-type'.")
6583 (defvar org-store-link-functions nil
6584 "List of functions that are called to create and store a link.
6585 Each function will be called in turn until one returns a non-nil
6586 value. Each function should check if it is responsible for creating
6587 this link (for example by looking at the major mode).
6588 If not, it must exit and return nil.
6589 If yes, it should return a non-nil value after a calling
6590 `org-store-link-props' with a list of properties and values.
6591 Special properties are:
6593 :type The link prefix. like \"http\". This must be given.
6594 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6595 This is obligatory as well.
6596 :description Optional default description for the second pair
6597 of brackets in an Org-mode link. The user can still change
6598 this when inserting this link into an Org-mode buffer.
6600 In addition to these, any additional properties can be specified
6601 and then used in remember templates.")
6603 (defun org-add-link-type (type &optional follow export)
6604 "Add TYPE to the list of `org-link-types'.
6605 Re-compute all regular expressions depending on `org-link-types'
6607 FOLLOW and EXPORT are two functions.
6609 FOLLOW should take the link path as the single argument and do whatever
6610 is necessary to follow the link, for example find a file or display
6611 a mail message.
6613 EXPORT should format the link path for export to one of the export formats.
6614 It should be a function accepting three arguments:
6616 path the path of the link, the text after the prefix (like \"http:\")
6617 desc the description of the link, if any, nil if there was no description
6618 format the export format, a symbol like `html' or `latex'.
6620 The function may use the FORMAT information to return different values
6621 depending on the format. The return value will be put literally into
6622 the exported file.
6623 Org-mode has a built-in default for exporting links. If you are happy with
6624 this default, there is no need to define an export function for the link
6625 type. For a simple example of an export function, see `org-bbdb.el'."
6626 (add-to-list 'org-link-types type t)
6627 (org-make-link-regexps)
6628 (if (assoc type org-link-protocols)
6629 (setcdr (assoc type org-link-protocols) (list follow export))
6630 (push (list type follow export) org-link-protocols)))
6632 ;;;###autoload
6633 (defun org-store-link (arg)
6634 "\\<org-mode-map>Store an org-link to the current location.
6635 This link is added to `org-stored-links' and can later be inserted
6636 into an org-buffer with \\[org-insert-link].
6638 For some link types, a prefix arg is interpreted:
6639 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6640 For file links, arg negates `org-context-in-file-links'."
6641 (interactive "P")
6642 (org-load-modules-maybe)
6643 (setq org-store-link-plist nil) ; reset
6644 (let (link cpltxt desc description search txt)
6645 (cond
6647 ((run-hook-with-args-until-success 'org-store-link-functions)
6648 (setq link (plist-get org-store-link-plist :link)
6649 desc (or (plist-get org-store-link-plist :description) link)))
6651 ((equal (buffer-name) "*Org Edit Src Example*")
6652 (let (label gc)
6653 (while (or (not label)
6654 (save-excursion
6655 (save-restriction
6656 (widen)
6657 (goto-char (point-min))
6658 (re-search-forward
6659 (regexp-quote (format org-coderef-label-format label))
6660 nil t))))
6661 (when label (message "Label exists already") (sit-for 2))
6662 (setq label (read-string "Code line label: " label)))
6663 (end-of-line 1)
6664 (setq link (format org-coderef-label-format label))
6665 (setq gc (- 79 (length link)))
6666 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6667 (insert link)
6668 (setq link (concat "(" label ")") desc nil)))
6670 ((eq major-mode 'calendar-mode)
6671 (let ((cd (calendar-cursor-to-date)))
6672 (setq link
6673 (format-time-string
6674 (car org-time-stamp-formats)
6675 (apply 'encode-time
6676 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6677 nil nil nil))))
6678 (org-store-link-props :type "calendar" :date cd)))
6680 ((eq major-mode 'w3-mode)
6681 (setq cpltxt (url-view-url t)
6682 link (org-make-link cpltxt))
6683 (org-store-link-props :type "w3" :url (url-view-url t)))
6685 ((eq major-mode 'w3m-mode)
6686 (setq cpltxt (or w3m-current-title w3m-current-url)
6687 link (org-make-link w3m-current-url))
6688 (org-store-link-props :type "w3m" :url (url-view-url t)))
6690 ((setq search (run-hook-with-args-until-success
6691 'org-create-file-search-functions))
6692 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6693 "::" search))
6694 (setq cpltxt (or description link)))
6696 ((eq major-mode 'image-mode)
6697 (setq cpltxt (concat "file:"
6698 (abbreviate-file-name buffer-file-name))
6699 link (org-make-link cpltxt))
6700 (org-store-link-props :type "image" :file buffer-file-name))
6702 ((eq major-mode 'dired-mode)
6703 ;; link to the file in the current line
6704 (setq cpltxt (concat "file:"
6705 (abbreviate-file-name
6706 (expand-file-name
6707 (dired-get-filename nil t))))
6708 link (org-make-link cpltxt)))
6710 ((and buffer-file-name (org-mode-p))
6711 (cond
6712 ((org-in-regexp "<<\\(.*?\\)>>")
6713 (setq cpltxt
6714 (concat "file:"
6715 (abbreviate-file-name buffer-file-name)
6716 "::" (match-string 1))
6717 link (org-make-link cpltxt)))
6718 ((and (featurep 'org-id)
6719 (or (eq org-link-to-org-use-id t)
6720 (and (eq org-link-to-org-use-id 'create-if-interactive)
6721 (interactive-p))
6722 (and org-link-to-org-use-id
6723 (condition-case nil
6724 (org-entry-get nil "ID")
6725 (error nil)))))
6726 ;; We can make a link using the ID.
6727 (setq link (condition-case nil
6728 (prog1 (org-id-store-link)
6729 (setq desc (plist-get org-store-link-plist
6730 :description)))
6731 (error
6732 ;; probably before first headline, link to file only
6733 (concat "file:"
6734 (abbreviate-file-name buffer-file-name))))))
6736 ;; Just link to current headline
6737 (setq cpltxt (concat "file:"
6738 (abbreviate-file-name buffer-file-name)))
6739 ;; Add a context search string
6740 (when (org-xor org-context-in-file-links arg)
6741 (setq txt (cond
6742 ((org-on-heading-p) nil)
6743 ((org-region-active-p)
6744 (buffer-substring (region-beginning) (region-end)))
6745 (t nil)))
6746 (when (or (null txt) (string-match "\\S-" txt))
6747 (setq cpltxt
6748 (concat cpltxt "::"
6749 (condition-case nil
6750 (org-make-org-heading-search-string txt)
6751 (error "")))
6752 desc "NONE")))
6753 (if (string-match "::\\'" cpltxt)
6754 (setq cpltxt (substring cpltxt 0 -2)))
6755 (setq link (org-make-link cpltxt)))))
6757 ((buffer-file-name (buffer-base-buffer))
6758 ;; Just link to this file here.
6759 (setq cpltxt (concat "file:"
6760 (abbreviate-file-name
6761 (buffer-file-name (buffer-base-buffer)))))
6762 ;; Add a context string
6763 (when (org-xor org-context-in-file-links arg)
6764 (setq txt (if (org-region-active-p)
6765 (buffer-substring (region-beginning) (region-end))
6766 (buffer-substring (point-at-bol) (point-at-eol))))
6767 ;; Only use search option if there is some text.
6768 (when (string-match "\\S-" txt)
6769 (setq cpltxt
6770 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6771 desc "NONE")))
6772 (setq link (org-make-link cpltxt)))
6774 ((interactive-p)
6775 (error "Cannot link to a buffer which is not visiting a file"))
6777 (t (setq link nil)))
6779 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6780 (setq link (or link cpltxt)
6781 desc (or desc cpltxt))
6782 (if (equal desc "NONE") (setq desc nil))
6784 (if (and (interactive-p) link)
6785 (progn
6786 (setq org-stored-links
6787 (cons (list link desc) org-stored-links))
6788 (message "Stored: %s" (or desc link)))
6789 (and link (org-make-link-string link desc)))))
6791 (defun org-store-link-props (&rest plist)
6792 "Store link properties, extract names and addresses."
6793 (let (x adr)
6794 (when (setq x (plist-get plist :from))
6795 (setq adr (mail-extract-address-components x))
6796 (setq plist (plist-put plist :fromname (car adr)))
6797 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6798 (when (setq x (plist-get plist :to))
6799 (setq adr (mail-extract-address-components x))
6800 (setq plist (plist-put plist :toname (car adr)))
6801 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6802 (let ((from (plist-get plist :from))
6803 (to (plist-get plist :to)))
6804 (when (and from to org-from-is-user-regexp)
6805 (setq plist
6806 (plist-put plist :fromto
6807 (if (string-match org-from-is-user-regexp from)
6808 (concat "to %t")
6809 (concat "from %f"))))))
6810 (setq org-store-link-plist plist))
6812 (defun org-add-link-props (&rest plist)
6813 "Add these properties to the link property list."
6814 (let (key value)
6815 (while plist
6816 (setq key (pop plist) value (pop plist))
6817 (setq org-store-link-plist
6818 (plist-put org-store-link-plist key value)))))
6820 (defun org-email-link-description (&optional fmt)
6821 "Return the description part of an email link.
6822 This takes information from `org-store-link-plist' and formats it
6823 according to FMT (default from `org-email-link-description-format')."
6824 (setq fmt (or fmt org-email-link-description-format))
6825 (let* ((p org-store-link-plist)
6826 (to (plist-get p :toaddress))
6827 (from (plist-get p :fromaddress))
6828 (table
6829 (list
6830 (cons "%c" (plist-get p :fromto))
6831 (cons "%F" (plist-get p :from))
6832 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6833 (cons "%T" (plist-get p :to))
6834 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6835 (cons "%s" (plist-get p :subject))
6836 (cons "%m" (plist-get p :message-id)))))
6837 (when (string-match "%c" fmt)
6838 ;; Check if the user wrote this message
6839 (if (and org-from-is-user-regexp from to
6840 (save-match-data (string-match org-from-is-user-regexp from)))
6841 (setq fmt (replace-match "to %t" t t fmt))
6842 (setq fmt (replace-match "from %f" t t fmt))))
6843 (org-replace-escapes fmt table)))
6845 (defun org-make-org-heading-search-string (&optional string heading)
6846 "Make search string for STRING or current headline."
6847 (interactive)
6848 (let ((s (or string (org-get-heading))))
6849 (unless (and string (not heading))
6850 ;; We are using a headline, clean up garbage in there.
6851 (if (string-match org-todo-regexp s)
6852 (setq s (replace-match "" t t s)))
6853 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6854 (setq s (replace-match "" t t s)))
6855 (setq s (org-trim s))
6856 (if (string-match (concat "^\\(" org-quote-string "\\|"
6857 org-comment-string "\\)") s)
6858 (setq s (replace-match "" t t s)))
6859 (while (string-match org-ts-regexp s)
6860 (setq s (replace-match "" t t s))))
6861 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6862 (setq s (replace-match " " t t s)))
6863 (or string (setq s (concat "*" s))) ; Add * for headlines
6864 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6866 (defun org-make-link (&rest strings)
6867 "Concatenate STRINGS."
6868 (apply 'concat strings))
6870 (defun org-make-link-string (link &optional description)
6871 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6872 (unless (string-match "\\S-" link)
6873 (error "Empty link"))
6874 (when (stringp description)
6875 ;; Remove brackets from the description, they are fatal.
6876 (while (string-match "\\[" description)
6877 (setq description (replace-match "{" t t description)))
6878 (while (string-match "\\]" description)
6879 (setq description (replace-match "}" t t description))))
6880 (when (equal (org-link-escape link) description)
6881 ;; No description needed, it is identical
6882 (setq description nil))
6883 (when (and (not description)
6884 (not (equal link (org-link-escape link))))
6885 (setq description (org-extract-attributes link)))
6886 (concat "[[" (org-link-escape link) "]"
6887 (if description (concat "[" description "]") "")
6888 "]"))
6890 (defconst org-link-escape-chars
6891 '((?\ . "%20")
6892 (?\[ . "%5B")
6893 (?\] . "%5D")
6894 (?\340 . "%E0") ; `a
6895 (?\342 . "%E2") ; ^a
6896 (?\347 . "%E7") ; ,c
6897 (?\350 . "%E8") ; `e
6898 (?\351 . "%E9") ; 'e
6899 (?\352 . "%EA") ; ^e
6900 (?\356 . "%EE") ; ^i
6901 (?\364 . "%F4") ; ^o
6902 (?\371 . "%F9") ; `u
6903 (?\373 . "%FB") ; ^u
6904 (?\; . "%3B")
6905 (?? . "%3F")
6906 (?= . "%3D")
6907 (?+ . "%2B")
6909 "Association list of escapes for some characters problematic in links.
6910 This is the list that is used for internal purposes.")
6912 (defconst org-link-escape-chars-browser
6913 '((?\ . "%20")) ; 32 for the SPC char
6914 "Association list of escapes for some characters problematic in links.
6915 This is the list that is used before handing over to the browser.")
6917 (defun org-link-escape (text &optional table)
6918 "Escape characters in TEXT that are problematic for links."
6919 (setq table (or table org-link-escape-chars))
6920 (when text
6921 (let ((re (mapconcat (lambda (x) (regexp-quote
6922 (char-to-string (car x))))
6923 table "\\|")))
6924 (while (string-match re text)
6925 (setq text
6926 (replace-match
6927 (cdr (assoc (string-to-char (match-string 0 text))
6928 table))
6929 t t text)))
6930 text)))
6932 (defun org-link-unescape (text &optional table)
6933 "Reverse the action of `org-link-escape'."
6934 (setq table (or table org-link-escape-chars))
6935 (when text
6936 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6937 table "\\|")))
6938 (while (string-match re text)
6939 (setq text
6940 (replace-match
6941 (char-to-string (car (rassoc (match-string 0 text) table)))
6942 t t text)))
6943 text)))
6945 (defun org-xor (a b)
6946 "Exclusive or."
6947 (if a (not b) b))
6949 (defun org-fixup-message-id-for-http (s)
6950 "Replace special characters in a message id, so it can be used in an http query."
6951 (while (string-match "<" s)
6952 (setq s (replace-match "%3C" t t s)))
6953 (while (string-match ">" s)
6954 (setq s (replace-match "%3E" t t s)))
6955 (while (string-match "@" s)
6956 (setq s (replace-match "%40" t t s)))
6959 ;;;###autoload
6960 (defun org-insert-link-global ()
6961 "Insert a link like Org-mode does.
6962 This command can be called in any mode to insert a link in Org-mode syntax."
6963 (interactive)
6964 (org-load-modules-maybe)
6965 (org-run-like-in-org-mode 'org-insert-link))
6967 (defun org-insert-link (&optional complete-file link-location)
6968 "Insert a link. At the prompt, enter the link.
6970 Completion can be used to insert any of the link protocol prefixes like
6971 http or ftp in use.
6973 The history can be used to select a link previously stored with
6974 `org-store-link'. When the empty string is entered (i.e. if you just
6975 press RET at the prompt), the link defaults to the most recently
6976 stored link. As SPC triggers completion in the minibuffer, you need to
6977 use M-SPC or C-q SPC to force the insertion of a space character.
6979 You will also be prompted for a description, and if one is given, it will
6980 be displayed in the buffer instead of the link.
6982 If there is already a link at point, this command will allow you to edit link
6983 and description parts.
6985 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6986 be selected using completion. The path to the file will be relative to the
6987 current directory if the file is in the current directory or a subdirectory.
6988 Otherwise, the link will be the absolute path as completed in the minibuffer
6989 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6990 option `org-link-file-path-type'.
6992 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6993 the current directory or below.
6995 With three \\[universal-argument] prefixes, negate the meaning of
6996 `org-keep-stored-link-after-insertion'.
6998 If `org-make-link-description-function' is non-nil, this function will be
6999 called with the link target, and the result will be the default
7000 link description.
7002 If the LINK-LOCATION parameter is non-nil, this value will be
7003 used as the link location instead of reading one interactively."
7004 (interactive "P")
7005 (let* ((wcf (current-window-configuration))
7006 (region (if (org-region-active-p)
7007 (buffer-substring (region-beginning) (region-end))))
7008 (remove (and region (list (region-beginning) (region-end))))
7009 (desc region)
7010 tmphist ; byte-compile incorrectly complains about this
7011 (link link-location)
7012 entry file)
7013 (cond
7014 (link-location) ; specified by arg, just use it.
7015 ((org-in-regexp org-bracket-link-regexp 1)
7016 ;; We do have a link at point, and we are going to edit it.
7017 (setq remove (list (match-beginning 0) (match-end 0)))
7018 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7019 (setq link (read-string "Link: "
7020 (org-link-unescape
7021 (org-match-string-no-properties 1)))))
7022 ((or (org-in-regexp org-angle-link-re)
7023 (org-in-regexp org-plain-link-re))
7024 ;; Convert to bracket link
7025 (setq remove (list (match-beginning 0) (match-end 0))
7026 link (read-string "Link: "
7027 (org-remove-angle-brackets (match-string 0)))))
7028 ((member complete-file '((4) (16)))
7029 ;; Completing read for file names.
7030 (setq file (read-file-name "File: "))
7031 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7032 (pwd1 (file-name-as-directory (abbreviate-file-name
7033 (expand-file-name ".")))))
7034 (cond
7035 ((equal complete-file '(16))
7036 (setq link (org-make-link
7037 "file:"
7038 (abbreviate-file-name (expand-file-name file)))))
7039 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7040 (setq link (org-make-link "file:" (match-string 1 file))))
7041 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7042 (expand-file-name file))
7043 (setq link (org-make-link
7044 "file:" (match-string 1 (expand-file-name file)))))
7045 (t (setq link (org-make-link "file:" file))))))
7047 ;; Read link, with completion for stored links.
7048 (with-output-to-temp-buffer "*Org Links*"
7049 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7050 (when org-stored-links
7051 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7052 (princ (mapconcat
7053 (lambda (x)
7054 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7055 (reverse org-stored-links) "\n"))))
7056 (let ((cw (selected-window)))
7057 (select-window (get-buffer-window "*Org Links*"))
7058 (setq truncate-lines t)
7059 (org-fit-window-to-buffer)
7060 (select-window cw))
7061 ;; Fake a link history, containing the stored links.
7062 (setq tmphist (append (mapcar 'car org-stored-links)
7063 org-insert-link-history))
7064 (unwind-protect
7065 (setq link
7066 (let ((org-completion-use-ido nil))
7067 (org-completing-read
7068 "Link: "
7069 (append
7070 (mapcar (lambda (x) (list (concat (car x) ":")))
7071 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7072 (mapcar (lambda (x) (list (concat x ":")))
7073 org-link-types))
7074 nil nil nil
7075 'tmphist
7076 (or (car (car org-stored-links))))))
7077 (set-window-configuration wcf)
7078 (kill-buffer "*Org Links*"))
7079 (setq entry (assoc link org-stored-links))
7080 (or entry (push link org-insert-link-history))
7081 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7082 (not org-keep-stored-link-after-insertion))
7083 (setq org-stored-links (delq (assoc link org-stored-links)
7084 org-stored-links)))
7085 (setq desc (or desc (nth 1 entry)))))
7087 (if (string-match org-plain-link-re link)
7088 ;; URL-like link, normalize the use of angular brackets.
7089 (setq link (org-make-link (org-remove-angle-brackets link))))
7091 ;; Check if we are linking to the current file with a search option
7092 ;; If yes, simplify the link by using only the search option.
7093 (when (and buffer-file-name
7094 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7095 (let* ((path (match-string 1 link))
7096 (case-fold-search nil)
7097 (search (match-string 2 link)))
7098 (save-match-data
7099 (if (equal (file-truename buffer-file-name) (file-truename path))
7100 ;; We are linking to this same file, with a search option
7101 (setq link search)))))
7103 ;; Check if we can/should use a relative path. If yes, simplify the link
7104 (when (string-match "^file:\\(.*\\)" link)
7105 (let* ((path (match-string 1 link))
7106 (origpath path)
7107 (case-fold-search nil))
7108 (cond
7109 ((or (eq org-link-file-path-type 'absolute)
7110 (equal complete-file '(16)))
7111 (setq path (abbreviate-file-name (expand-file-name path))))
7112 ((eq org-link-file-path-type 'noabbrev)
7113 (setq path (expand-file-name path)))
7114 ((eq org-link-file-path-type 'relative)
7115 (setq path (file-relative-name path)))
7117 (save-match-data
7118 (if (string-match (concat "^" (regexp-quote
7119 (file-name-as-directory
7120 (expand-file-name "."))))
7121 (expand-file-name path))
7122 ;; We are linking a file with relative path name.
7123 (setq path (substring (expand-file-name path)
7124 (match-end 0)))
7125 (setq path (abbreviate-file-name (expand-file-name path)))))))
7126 (setq link (concat "file:" path))
7127 (if (equal desc origpath)
7128 (setq desc path))))
7130 (if org-make-link-description-function
7131 (setq desc (funcall org-make-link-description-function link desc)))
7133 (setq desc (read-string "Description: " desc))
7134 (unless (string-match "\\S-" desc) (setq desc nil))
7135 (if remove (apply 'delete-region remove))
7136 (insert (org-make-link-string link desc))))
7138 (defun org-completing-read (&rest args)
7139 "Completing-read with SPACE being a normal character."
7140 (let ((minibuffer-local-completion-map
7141 (copy-keymap minibuffer-local-completion-map)))
7142 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7143 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7144 (apply 'org-ido-completing-read args)))
7146 (defun org-completing-read-no-ido (&rest args)
7147 (let (org-completion-use-ido)
7148 (apply 'org-completing-read args)))
7150 (defun org-ido-completing-read (&rest args)
7151 "Completing-read using `ido-mode' speedups if available"
7152 (if (and org-completion-use-ido
7153 (fboundp 'ido-completing-read)
7154 (boundp 'ido-mode) ido-mode
7155 (listp (second args)))
7156 (let ((ido-enter-matching-directory nil))
7157 (apply 'ido-completing-read (concat (car args))
7158 (mapcar (lambda (x) (car x)) (nth 1 args))
7159 (cddr args)))
7160 (apply 'completing-read args)))
7163 (defun org-extract-attributes (s)
7164 "Extract the attributes cookie from a string and set as text property."
7165 (let (a attr (start 0) key value)
7166 (save-match-data
7167 (when (string-match "{{\\([^}]+\\)}}$" s)
7168 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7169 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7170 (setq key (match-string 1 a) value (match-string 2 a)
7171 start (match-end 0)
7172 attr (plist-put attr (intern key) value))))
7173 (org-add-props s nil 'org-attr attr))
7176 (defun org-attributes-to-string (plist)
7177 "Format a property list into an HTML attribute list."
7178 (let ((s "") key value)
7179 (while plist
7180 (setq key (pop plist) value (pop plist))
7181 (and value
7182 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7185 ;;; Opening/following a link
7187 (defvar org-link-search-failed nil)
7189 (defun org-next-link ()
7190 "Move forward to the next link.
7191 If the link is in hidden text, expose it."
7192 (interactive)
7193 (when (and org-link-search-failed (eq this-command last-command))
7194 (goto-char (point-min))
7195 (message "Link search wrapped back to beginning of buffer"))
7196 (setq org-link-search-failed nil)
7197 (let* ((pos (point))
7198 (ct (org-context))
7199 (a (assoc :link ct)))
7200 (if a (goto-char (nth 2 a)))
7201 (if (re-search-forward org-any-link-re nil t)
7202 (progn
7203 (goto-char (match-beginning 0))
7204 (if (org-invisible-p) (org-show-context)))
7205 (goto-char pos)
7206 (setq org-link-search-failed t)
7207 (error "No further link found"))))
7209 (defun org-previous-link ()
7210 "Move backward to the previous link.
7211 If the link is in hidden text, expose it."
7212 (interactive)
7213 (when (and org-link-search-failed (eq this-command last-command))
7214 (goto-char (point-max))
7215 (message "Link search wrapped back to end of buffer"))
7216 (setq org-link-search-failed nil)
7217 (let* ((pos (point))
7218 (ct (org-context))
7219 (a (assoc :link ct)))
7220 (if a (goto-char (nth 1 a)))
7221 (if (re-search-backward org-any-link-re nil t)
7222 (progn
7223 (goto-char (match-beginning 0))
7224 (if (org-invisible-p) (org-show-context)))
7225 (goto-char pos)
7226 (setq org-link-search-failed t)
7227 (error "No further link found"))))
7229 (defun org-translate-link (s)
7230 "Translate a link string if a translation function has been defined."
7231 (if (and org-link-translation-function
7232 (fboundp org-link-translation-function)
7233 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7234 (progn
7235 (setq s (funcall org-link-translation-function
7236 (match-string 1) (match-string 2)))
7237 (concat (car s) ":" (cdr s)))
7240 (defun org-translate-link-from-planner (type path)
7241 "Translate a link from Emacs Planner syntax so that Org can follow it.
7242 This is still an experimental function, your mileage may vary."
7243 (cond
7244 ((member type '("http" "https" "news" "ftp"))
7245 ;; standard Internet links are the same.
7246 nil)
7247 ((and (equal type "irc") (string-match "^//" path))
7248 ;; Planner has two / at the beginning of an irc link, we have 1.
7249 ;; We should have zero, actually....
7250 (setq path (substring path 1)))
7251 ((and (equal type "lisp") (string-match "^/" path))
7252 ;; Planner has a slash, we do not.
7253 (setq type "elisp" path (substring path 1)))
7254 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7255 ;; A typical message link. Planner has the id after the fina slash,
7256 ;; we separate it with a hash mark
7257 (setq path (concat (match-string 1 path) "#"
7258 (org-remove-angle-brackets (match-string 2 path)))))
7260 (cons type path))
7262 (defun org-find-file-at-mouse (ev)
7263 "Open file link or URL at mouse."
7264 (interactive "e")
7265 (mouse-set-point ev)
7266 (org-open-at-point 'in-emacs))
7268 (defun org-open-at-mouse (ev)
7269 "Open file link or URL at mouse."
7270 (interactive "e")
7271 (mouse-set-point ev)
7272 (if (eq major-mode 'org-agenda-mode)
7273 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7274 (org-open-at-point))
7276 (defvar org-window-config-before-follow-link nil
7277 "The window configuration before following a link.
7278 This is saved in case the need arises to restore it.")
7280 (defvar org-open-link-marker (make-marker)
7281 "Marker pointing to the location where `org-open-at-point; was called.")
7283 ;;;###autoload
7284 (defun org-open-at-point-global ()
7285 "Follow a link like Org-mode does.
7286 This command can be called in any mode to follow a link that has
7287 Org-mode syntax."
7288 (interactive)
7289 (org-run-like-in-org-mode 'org-open-at-point))
7291 ;;;###autoload
7292 (defun org-open-link-from-string (s &optional arg)
7293 "Open a link in the string S, as if it was in Org-mode."
7294 (interactive "sLink: \nP")
7295 (with-temp-buffer
7296 (let ((org-inhibit-startup t))
7297 (org-mode)
7298 (insert s)
7299 (goto-char (point-min))
7300 (org-open-at-point arg))))
7302 (defun org-open-at-point (&optional in-emacs)
7303 "Open link at or after point.
7304 If there is no link at point, this function will search forward up to
7305 the end of the current subtree.
7306 Normally, files will be opened by an appropriate application. If the
7307 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7308 With a double prefix argument, try to open outside of Emacs, in the
7309 application the system uses for this file type."
7310 (interactive "P")
7311 (org-load-modules-maybe)
7312 (move-marker org-open-link-marker (point))
7313 (setq org-window-config-before-follow-link (current-window-configuration))
7314 (org-remove-occur-highlights nil nil t)
7315 (cond
7316 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7317 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7318 (org-footnote-action))
7320 (let (type path link line search (pos (point)))
7321 (catch 'match
7322 (save-excursion
7323 (skip-chars-forward "^]\n\r")
7324 (when (org-in-regexp org-bracket-link-regexp)
7325 (setq link (org-extract-attributes
7326 (org-link-unescape (org-match-string-no-properties 1))))
7327 (while (string-match " *\n *" link)
7328 (setq link (replace-match " " t t link)))
7329 (setq link (org-link-expand-abbrev link))
7330 (cond
7331 ((or (file-name-absolute-p link)
7332 (string-match "^\\.\\.?/" link))
7333 (setq type "file" path link))
7334 ((string-match org-link-re-with-space3 link)
7335 (setq type (match-string 1 link) path (match-string 2 link)))
7336 (t (setq type "thisfile" path link)))
7337 (throw 'match t)))
7339 (when (get-text-property (point) 'org-linked-text)
7340 (setq type "thisfile"
7341 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7342 (1+ (point)) (point))
7343 path (buffer-substring
7344 (previous-single-property-change pos 'org-linked-text)
7345 (next-single-property-change pos 'org-linked-text)))
7346 (throw 'match t))
7348 (save-excursion
7349 (when (or (org-in-regexp org-angle-link-re)
7350 (org-in-regexp org-plain-link-re))
7351 (setq type (match-string 1) path (match-string 2))
7352 (throw 'match t)))
7353 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7354 (setq type "tree-match"
7355 path (match-string 1))
7356 (throw 'match t))
7357 (save-excursion
7358 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7359 (setq type "tags"
7360 path (match-string 1))
7361 (while (string-match ":" path)
7362 (setq path (replace-match "+" t t path)))
7363 (throw 'match t))))
7364 (unless path
7365 (error "No link found"))
7366 ;; Remove any trailing spaces in path
7367 (if (string-match " +\\'" path)
7368 (setq path (replace-match "" t t path)))
7369 (if (and org-link-translation-function
7370 (fboundp org-link-translation-function))
7371 ;; Check if we need to translate the link
7372 (let ((tmp (funcall org-link-translation-function type path)))
7373 (setq type (car tmp) path (cdr tmp))))
7375 (cond
7377 ((assoc type org-link-protocols)
7378 (funcall (nth 1 (assoc type org-link-protocols)) path))
7380 ((equal type "mailto")
7381 (let ((cmd (car org-link-mailto-program))
7382 (args (cdr org-link-mailto-program)) args1
7383 (address path) (subject "") a)
7384 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7385 (setq address (match-string 1 path)
7386 subject (org-link-escape (match-string 2 path))))
7387 (while args
7388 (cond
7389 ((not (stringp (car args))) (push (pop args) args1))
7390 (t (setq a (pop args))
7391 (if (string-match "%a" a)
7392 (setq a (replace-match address t t a)))
7393 (if (string-match "%s" a)
7394 (setq a (replace-match subject t t a)))
7395 (push a args1))))
7396 (apply cmd (nreverse args1))))
7398 ((member type '("http" "https" "ftp" "news"))
7399 (browse-url (concat type ":" (org-link-escape
7400 path org-link-escape-chars-browser))))
7402 ((member type '("message"))
7403 (browse-url (concat type ":" path)))
7405 ((string= type "tags")
7406 (org-tags-view in-emacs path))
7407 ((string= type "thisfile")
7408 (if in-emacs
7409 (switch-to-buffer-other-window
7410 (org-get-buffer-for-internal-link (current-buffer)))
7411 (org-mark-ring-push))
7412 (let ((cmd `(org-link-search
7413 ,path
7414 ,(cond ((equal in-emacs '(4)) 'occur)
7415 ((equal in-emacs '(16)) 'org-occur)
7416 (t nil))
7417 ,pos)))
7418 (condition-case nil (eval cmd)
7419 (error (progn (widen) (eval cmd))))))
7421 ((string= type "tree-match")
7422 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7424 ((string= type "file")
7425 (if (string-match "::\\([0-9]+\\)\\'" path)
7426 (setq line (string-to-number (match-string 1 path))
7427 path (substring path 0 (match-beginning 0)))
7428 (if (string-match "::\\(.+\\)\\'" path)
7429 (setq search (match-string 1 path)
7430 path (substring path 0 (match-beginning 0)))))
7431 (if (string-match "[*?{]" (file-name-nondirectory path))
7432 (dired path)
7433 (org-open-file path in-emacs line search)))
7435 ((string= type "news")
7436 (require 'org-gnus)
7437 (org-gnus-follow-link path))
7439 ((string= type "shell")
7440 (let ((cmd path))
7441 (if (or (not org-confirm-shell-link-function)
7442 (funcall org-confirm-shell-link-function
7443 (format "Execute \"%s\" in shell? "
7444 (org-add-props cmd nil
7445 'face 'org-warning))))
7446 (progn
7447 (message "Executing %s" cmd)
7448 (shell-command cmd))
7449 (error "Abort"))))
7451 ((string= type "elisp")
7452 (let ((cmd path))
7453 (if (or (not org-confirm-elisp-link-function)
7454 (funcall org-confirm-elisp-link-function
7455 (format "Execute \"%s\" as elisp? "
7456 (org-add-props cmd nil
7457 'face 'org-warning))))
7458 (message "%s => %s" cmd
7459 (if (equal (string-to-char cmd) ?\()
7460 (eval (read cmd))
7461 (call-interactively (read cmd))))
7462 (error "Abort"))))
7465 (browse-url-at-point))))))
7466 (move-marker org-open-link-marker nil)
7467 (run-hook-with-args 'org-follow-link-hook))
7469 ;;;; Time estimates
7471 (defun org-get-effort (&optional pom)
7472 "Get the effort estimate for the current entry."
7473 (org-entry-get pom org-effort-property))
7475 ;;; File search
7477 (defvar org-create-file-search-functions nil
7478 "List of functions to construct the right search string for a file link.
7479 These functions are called in turn with point at the location to
7480 which the link should point.
7482 A function in the hook should first test if it would like to
7483 handle this file type, for example by checking the major-mode or
7484 the file extension. If it decides not to handle this file, it
7485 should just return nil to give other functions a chance. If it
7486 does handle the file, it must return the search string to be used
7487 when following the link. The search string will be part of the
7488 file link, given after a double colon, and `org-open-at-point'
7489 will automatically search for it. If special measures must be
7490 taken to make the search successful, another function should be
7491 added to the companion hook `org-execute-file-search-functions',
7492 which see.
7494 A function in this hook may also use `setq' to set the variable
7495 `description' to provide a suggestion for the descriptive text to
7496 be used for this link when it gets inserted into an Org-mode
7497 buffer with \\[org-insert-link].")
7499 (defvar org-execute-file-search-functions nil
7500 "List of functions to execute a file search triggered by a link.
7502 Functions added to this hook must accept a single argument, the
7503 search string that was part of the file link, the part after the
7504 double colon. The function must first check if it would like to
7505 handle this search, for example by checking the major-mode or the
7506 file extension. If it decides not to handle this search, it
7507 should just return nil to give other functions a chance. If it
7508 does handle the search, it must return a non-nil value to keep
7509 other functions from trying.
7511 Each function can access the current prefix argument through the
7512 variable `current-prefix-argument'. Note that a single prefix is
7513 used to force opening a link in Emacs, so it may be good to only
7514 use a numeric or double prefix to guide the search function.
7516 In case this is needed, a function in this hook can also restore
7517 the window configuration before `org-open-at-point' was called using:
7519 (set-window-configuration org-window-config-before-follow-link)")
7521 (defun org-link-search (s &optional type avoid-pos)
7522 "Search for a link search option.
7523 If S is surrounded by forward slashes, it is interpreted as a
7524 regular expression. In org-mode files, this will create an `org-occur'
7525 sparse tree. In ordinary files, `occur' will be used to list matches.
7526 If the current buffer is in `dired-mode', grep will be used to search
7527 in all files. If AVOID-POS is given, ignore matches near that position."
7528 (let ((case-fold-search t)
7529 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7530 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7531 (append '(("") (" ") ("\t") ("\n"))
7532 org-emphasis-alist)
7533 "\\|") "\\)"))
7534 (pos (point))
7535 (pre nil) (post nil)
7536 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7537 (cond
7538 ;; First check if there are any special
7539 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7540 ;; Now try the builtin stuff
7541 ((save-excursion
7542 (goto-char (point-min))
7543 (and
7544 (re-search-forward
7545 (concat "<<" (regexp-quote s0) ">>") nil t)
7546 (setq type 'dedicated
7547 pos (match-beginning 0))))
7548 ;; There is an exact target for this
7549 (goto-char pos))
7550 ((and (string-match "^(\\(.*\\))$" s0)
7551 (save-excursion
7552 (goto-char (point-min))
7553 (and
7554 (re-search-forward
7555 (concat "[^[]" (regexp-quote
7556 (format org-coderef-label-format
7557 (match-string 1 s0))))
7558 nil t)
7559 (setq type 'dedicated
7560 pos (1+ (match-beginning 0))))))
7561 ;; There is a coderef target for this
7562 (goto-char pos))
7563 ((string-match "^/\\(.*\\)/$" s)
7564 ;; A regular expression
7565 (cond
7566 ((org-mode-p)
7567 (org-occur (match-string 1 s)))
7568 ;;((eq major-mode 'dired-mode)
7569 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7570 (t (org-do-occur (match-string 1 s)))))
7572 ;; A normal search strings
7573 (when (equal (string-to-char s) ?*)
7574 ;; Anchor on headlines, post may include tags.
7575 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7576 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7577 s (substring s 1)))
7578 (remove-text-properties
7579 0 (length s)
7580 '(face nil mouse-face nil keymap nil fontified nil) s)
7581 ;; Make a series of regular expressions to find a match
7582 (setq words (org-split-string s "[ \n\r\t]+")
7584 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7585 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7586 "\\)" markers)
7587 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7588 re2a (concat "[ \t\r\n]" re2a_)
7589 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7590 re4 (concat "[^a-zA-Z_]" re4_)
7592 re1 (concat pre re2 post)
7593 re3 (concat pre (if pre re4_ re4) post)
7594 re5 (concat pre ".*" re4)
7595 re2 (concat pre re2)
7596 re2a (concat pre (if pre re2a_ re2a))
7597 re4 (concat pre (if pre re4_ re4))
7598 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7599 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7600 re5 "\\)"
7602 (cond
7603 ((eq type 'org-occur) (org-occur reall))
7604 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7605 (t (goto-char (point-min))
7606 (setq type 'fuzzy)
7607 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7608 (org-search-not-self 1 re1 nil t)
7609 (org-search-not-self 1 re2 nil t)
7610 (org-search-not-self 1 re2a nil t)
7611 (org-search-not-self 1 re3 nil t)
7612 (org-search-not-self 1 re4 nil t)
7613 (org-search-not-self 1 re5 nil t)
7615 (goto-char (match-beginning 1))
7616 (goto-char pos)
7617 (error "No match")))))
7619 ;; Normal string-search
7620 (goto-char (point-min))
7621 (if (search-forward s nil t)
7622 (goto-char (match-beginning 0))
7623 (error "No match"))))
7624 (and (org-mode-p) (org-show-context 'link-search))
7625 type))
7627 (defun org-search-not-self (group &rest args)
7628 "Execute `re-search-forward', but only accept matches that do not
7629 enclose the position of `org-open-link-marker'."
7630 (let ((m org-open-link-marker))
7631 (catch 'exit
7632 (while (apply 're-search-forward args)
7633 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7634 (goto-char (match-end group))
7635 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7636 (> (match-beginning 0) (marker-position m))
7637 (< (match-end 0) (marker-position m)))
7638 (save-match-data
7639 (or (not (org-in-regexp
7640 org-bracket-link-analytic-regexp 1))
7641 (not (match-end 4)) ; no description
7642 (and (<= (match-beginning 4) (point))
7643 (>= (match-end 4) (point))))))
7644 (throw 'exit (point))))))))
7646 (defun org-get-buffer-for-internal-link (buffer)
7647 "Return a buffer to be used for displaying the link target of internal links."
7648 (cond
7649 ((not org-display-internal-link-with-indirect-buffer)
7650 buffer)
7651 ((string-match "(Clone)$" (buffer-name buffer))
7652 (message "Buffer is already a clone, not making another one")
7653 ;; we also do not modify visibility in this case
7654 buffer)
7655 (t ; make a new indirect buffer for displaying the link
7656 (let* ((bn (buffer-name buffer))
7657 (ibn (concat bn "(Clone)"))
7658 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7659 (with-current-buffer ib (org-overview))
7660 ib))))
7662 (defun org-do-occur (regexp &optional cleanup)
7663 "Call the Emacs command `occur'.
7664 If CLEANUP is non-nil, remove the printout of the regular expression
7665 in the *Occur* buffer. This is useful if the regex is long and not useful
7666 to read."
7667 (occur regexp)
7668 (when cleanup
7669 (let ((cwin (selected-window)) win beg end)
7670 (when (setq win (get-buffer-window "*Occur*"))
7671 (select-window win))
7672 (goto-char (point-min))
7673 (when (re-search-forward "match[a-z]+" nil t)
7674 (setq beg (match-end 0))
7675 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7676 (setq end (1- (match-beginning 0)))))
7677 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7678 (goto-char (point-min))
7679 (select-window cwin))))
7681 ;;; The mark ring for links jumps
7683 (defvar org-mark-ring nil
7684 "Mark ring for positions before jumps in Org-mode.")
7685 (defvar org-mark-ring-last-goto nil
7686 "Last position in the mark ring used to go back.")
7687 ;; Fill and close the ring
7688 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7689 (loop for i from 1 to org-mark-ring-length do
7690 (push (make-marker) org-mark-ring))
7691 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7692 org-mark-ring)
7694 (defun org-mark-ring-push (&optional pos buffer)
7695 "Put the current position or POS into the mark ring and rotate it."
7696 (interactive)
7697 (setq pos (or pos (point)))
7698 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7699 (move-marker (car org-mark-ring)
7700 (or pos (point))
7701 (or buffer (current-buffer)))
7702 (message "%s"
7703 (substitute-command-keys
7704 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7706 (defun org-mark-ring-goto (&optional n)
7707 "Jump to the previous position in the mark ring.
7708 With prefix arg N, jump back that many stored positions. When
7709 called several times in succession, walk through the entire ring.
7710 Org-mode commands jumping to a different position in the current file,
7711 or to another Org-mode file, automatically push the old position
7712 onto the ring."
7713 (interactive "p")
7714 (let (p m)
7715 (if (eq last-command this-command)
7716 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7717 (setq p org-mark-ring))
7718 (setq org-mark-ring-last-goto p)
7719 (setq m (car p))
7720 (switch-to-buffer (marker-buffer m))
7721 (goto-char m)
7722 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7724 (defun org-remove-angle-brackets (s)
7725 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7726 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7728 (defun org-add-angle-brackets (s)
7729 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7730 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7732 (defun org-remove-double-quotes (s)
7733 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7734 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7737 ;;; Following specific links
7739 (defun org-follow-timestamp-link ()
7740 (cond
7741 ((org-at-date-range-p t)
7742 (let ((org-agenda-start-on-weekday)
7743 (t1 (match-string 1))
7744 (t2 (match-string 2)))
7745 (setq t1 (time-to-days (org-time-string-to-time t1))
7746 t2 (time-to-days (org-time-string-to-time t2)))
7747 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7748 ((org-at-timestamp-p t)
7749 (org-agenda-list nil (time-to-days (org-time-string-to-time
7750 (substring (match-string 1) 0 10)))
7752 (t (error "This should not happen"))))
7755 ;;; Following file links
7756 (defvar org-wait nil)
7757 (defun org-open-file (path &optional in-emacs line search)
7758 "Open the file at PATH.
7759 First, this expands any special file name abbreviations. Then the
7760 configuration variable `org-file-apps' is checked if it contains an
7761 entry for this file type, and if yes, the corresponding command is launched.
7763 If no application is found, Emacs simply visits the file.
7765 With optional prefix argument IN-EMACS, Emacs will visit the file.
7766 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7767 and o use an external application to visit the file.
7769 Optional LINE specifies a line to go to, optional SEARCH a string to
7770 search for. If LINE or SEARCH is given, the file will always be
7771 opened in Emacs.
7772 If the file does not exist, an error is thrown."
7773 (setq in-emacs (or in-emacs line search))
7774 (let* ((file (if (equal path "")
7775 buffer-file-name
7776 (substitute-in-file-name (expand-file-name path))))
7777 (apps (append org-file-apps (org-default-apps)))
7778 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7779 (dirp (if remp nil (file-directory-p file)))
7780 (file (if (and dirp org-open-directory-means-index-dot-org)
7781 (concat (file-name-as-directory file) "index.org")
7782 file))
7783 (a-m-a-p (assq 'auto-mode apps))
7784 (dfile (downcase file))
7785 (old-buffer (current-buffer))
7786 (old-pos (point))
7787 (old-mode major-mode)
7788 ext cmd)
7789 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7790 (setq ext (match-string 1 dfile))
7791 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7792 (setq ext (match-string 1 dfile))))
7793 (cond
7794 ((equal in-emacs '(16))
7795 (setq cmd (cdr (assoc 'system apps))))
7796 (in-emacs (setq cmd 'emacs))
7798 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7799 (and dirp (cdr (assoc 'directory apps)))
7800 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7801 'string-match)
7802 (cdr (assoc ext apps))
7803 (cdr (assoc t apps))))))
7804 (when (eq cmd 'system)
7805 (setq cmd (cdr (assoc 'system apps))))
7806 (when (eq cmd 'default)
7807 (setq cmd (cdr (assoc t apps))))
7808 (when (eq cmd 'mailcap)
7809 (require 'mailcap)
7810 (mailcap-parse-mailcaps)
7811 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7812 (command (mailcap-mime-info mime-type)))
7813 (if (stringp command)
7814 (setq cmd command)
7815 (setq cmd 'emacs))))
7816 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7817 (not (file-exists-p file))
7818 (not org-open-non-existing-files))
7819 (error "No such file: %s" file))
7820 (cond
7821 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7822 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7823 (while (string-match "['\"]%s['\"]" cmd)
7824 (setq cmd (replace-match "%s" t t cmd)))
7825 (while (string-match "%s" cmd)
7826 (setq cmd (replace-match
7827 (save-match-data
7828 (shell-quote-argument
7829 (convert-standard-filename file)))
7830 t t cmd)))
7831 (save-window-excursion
7832 (start-process-shell-command cmd nil cmd)
7833 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7835 ((or (stringp cmd)
7836 (eq cmd 'emacs))
7837 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7838 (widen)
7839 (if line (goto-line line)
7840 (if search (org-link-search search))))
7841 ((consp cmd)
7842 (let ((file (convert-standard-filename file)))
7843 (eval cmd)))
7844 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7845 (and (org-mode-p) (eq old-mode 'org-mode)
7846 (or (not (equal old-buffer (current-buffer)))
7847 (not (equal old-pos (point))))
7848 (org-mark-ring-push old-pos old-buffer))))
7850 (defun org-default-apps ()
7851 "Return the default applications for this operating system."
7852 (cond
7853 ((eq system-type 'darwin)
7854 org-file-apps-defaults-macosx)
7855 ((eq system-type 'windows-nt)
7856 org-file-apps-defaults-windowsnt)
7857 (t org-file-apps-defaults-gnu)))
7859 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7860 "Convert extensions to regular expressions in the cars of LIST.
7861 Also, weed out any non-string entries, because the return value is used
7862 only for regexp matching.
7863 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7864 point to the symbol `emacs', indicating that the file should
7865 be opened in Emacs."
7866 (append
7867 (delq nil
7868 (mapcar (lambda (x)
7869 (if (not (stringp (car x)))
7871 (if (string-match "\\W" (car x))
7873 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7874 list))
7875 (if add-auto-mode
7876 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7878 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7879 (defun org-file-remote-p (file)
7880 "Test whether FILE specifies a location on a remote system.
7881 Return non-nil if the location is indeed remote.
7883 For example, the filename \"/user@host:/foo\" specifies a location
7884 on the system \"/user@host:\"."
7885 (cond ((fboundp 'file-remote-p)
7886 (file-remote-p file))
7887 ((fboundp 'tramp-handle-file-remote-p)
7888 (tramp-handle-file-remote-p file))
7889 ((and (boundp 'ange-ftp-name-format)
7890 (string-match (car ange-ftp-name-format) file))
7892 (t nil)))
7895 ;;;; Refiling
7897 (defun org-get-org-file ()
7898 "Read a filename, with default directory `org-directory'."
7899 (let ((default (or org-default-notes-file remember-data-file)))
7900 (read-file-name (format "File name [%s]: " default)
7901 (file-name-as-directory org-directory)
7902 default)))
7904 (defun org-notes-order-reversed-p ()
7905 "Check if the current file should receive notes in reversed order."
7906 (cond
7907 ((not org-reverse-note-order) nil)
7908 ((eq t org-reverse-note-order) t)
7909 ((not (listp org-reverse-note-order)) nil)
7910 (t (catch 'exit
7911 (let ((all org-reverse-note-order)
7912 entry)
7913 (while (setq entry (pop all))
7914 (if (string-match (car entry) buffer-file-name)
7915 (throw 'exit (cdr entry))))
7916 nil)))))
7918 (defvar org-refile-target-table nil
7919 "The list of refile targets, created by `org-refile'.")
7921 (defvar org-agenda-new-buffers nil
7922 "Buffers created to visit agenda files.")
7924 (defun org-get-refile-targets (&optional default-buffer)
7925 "Produce a table with refile targets."
7926 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7927 targets txt re files f desc descre fast-path-p level)
7928 (message "Getting targets...")
7929 (with-current-buffer (or default-buffer (current-buffer))
7930 (while (setq entry (pop entries))
7931 (setq files (car entry) desc (cdr entry))
7932 (setq fast-path-p nil)
7933 (cond
7934 ((null files) (setq files (list (current-buffer))))
7935 ((eq files 'org-agenda-files)
7936 (setq files (org-agenda-files 'unrestricted)))
7937 ((and (symbolp files) (fboundp files))
7938 (setq files (funcall files)))
7939 ((and (symbolp files) (boundp files))
7940 (setq files (symbol-value files))))
7941 (if (stringp files) (setq files (list files)))
7942 (cond
7943 ((eq (car desc) :tag)
7944 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7945 ((eq (car desc) :todo)
7946 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7947 ((eq (car desc) :regexp)
7948 (setq descre (cdr desc)))
7949 ((eq (car desc) :level)
7950 (setq descre (concat "^\\*\\{" (number-to-string
7951 (if org-odd-levels-only
7952 (1- (* 2 (cdr desc)))
7953 (cdr desc)))
7954 "\\}[ \t]")))
7955 ((eq (car desc) :maxlevel)
7956 (setq fast-path-p t)
7957 (setq descre (concat "^\\*\\{1," (number-to-string
7958 (if org-odd-levels-only
7959 (1- (* 2 (cdr desc)))
7960 (cdr desc)))
7961 "\\}[ \t]")))
7962 (t (error "Bad refiling target description %s" desc)))
7963 (while (setq f (pop files))
7964 (save-excursion
7965 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7966 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7967 (setq f (expand-file-name f))
7968 (save-excursion
7969 (save-restriction
7970 (widen)
7971 (goto-char (point-min))
7972 (while (re-search-forward descre nil t)
7973 (goto-char (point-at-bol))
7974 (when (looking-at org-complex-heading-regexp)
7975 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7976 txt (org-link-display-format (match-string 4))
7977 re (concat "^" (regexp-quote
7978 (buffer-substring (match-beginning 1)
7979 (match-end 4)))))
7980 (if (match-end 5) (setq re (concat re "[ \t]+"
7981 (regexp-quote
7982 (match-string 5)))))
7983 (setq re (concat re "[ \t]*$"))
7984 (when org-refile-use-outline-path
7985 (setq txt (mapconcat 'org-protect-slash
7986 (append
7987 (if (eq org-refile-use-outline-path 'file)
7988 (list (file-name-nondirectory
7989 (buffer-file-name (buffer-base-buffer))))
7990 (if (eq org-refile-use-outline-path 'full-file-path)
7991 (list (buffer-file-name (buffer-base-buffer)))))
7992 (org-get-outline-path fast-path-p level txt)
7993 (list txt))
7994 "/")))
7995 (push (list txt f re (point)) targets))
7996 (goto-char (point-at-eol))))))))
7997 (message "Getting targets...done")
7998 (nreverse targets))))
8000 (defun org-protect-slash (s)
8001 (while (string-match "/" s)
8002 (setq s (replace-match "\\" t t s)))
8005 (defvar org-olpa (make-vector 20 nil))
8007 (defun org-get-outline-path (&optional fastp level heading)
8008 "Return the outline path to the current entry, as a list."
8009 (if fastp
8010 (progn
8011 (if (> level 19)
8012 (error "Outline path failure, more than 19 levels."))
8013 (loop for i from level upto 19 do
8014 (aset org-olpa i nil))
8015 (prog1
8016 (delq nil (append org-olpa nil))
8017 (aset org-olpa level heading)))
8018 (let (rtn)
8019 (save-excursion
8020 (while (org-up-heading-safe)
8021 (when (looking-at org-complex-heading-regexp)
8022 (push (org-match-string-no-properties 4) rtn)))
8023 rtn))))
8025 (defvar org-refile-history nil
8026 "History for refiling operations.")
8028 (defun org-refile (&optional goto default-buffer)
8029 "Move the entry at point to another heading.
8030 The list of target headings is compiled using the information in
8031 `org-refile-targets', which see. This list is created before each use
8032 and will therefore always be up-to-date.
8034 At the target location, the entry is filed as a subitem of the target heading.
8035 Depending on `org-reverse-note-order', the new subitem will either be the
8036 first or the last subitem.
8038 If there is an active region, all entries in that region will be moved.
8039 However, the region must fulfil the requirement that the first heading
8040 is the first one sets the top-level of the moved text - at most siblings
8041 below it are allowed.
8043 With prefix arg GOTO, the command will only visit the target location,
8044 not actually move anything.
8045 With a double prefix `C-u C-u', go to the location where the last refiling
8046 operation has put the subtree."
8047 (interactive "P")
8048 (let* ((cbuf (current-buffer))
8049 (regionp (org-region-active-p))
8050 (region-start (and regionp (region-beginning)))
8051 (region-end (and regionp (region-end)))
8052 (region-length (and regionp (- region-end region-start)))
8053 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8054 pos it nbuf file re level reversed)
8055 (when regionp (goto-char region-start)
8056 (unless (org-kill-is-subtree-p
8057 (buffer-substring region-start region-end))
8058 (error "The region is not a (sequence of) subtree(s)")))
8059 (if (equal goto '(16))
8060 (org-refile-goto-last-stored)
8061 (when (setq it (org-refile-get-location
8062 (if goto "Goto: " "Refile to: ") default-buffer))
8063 (setq file (nth 1 it)
8064 re (nth 2 it)
8065 pos (nth 3 it))
8066 (if (and (equal (buffer-file-name) file)
8067 (if regionp
8068 (and (>= pos region-start)
8069 (<= pos region-end))
8070 (and (>= pos (point))
8071 (< pos (save-excursion
8072 (org-end-of-subtree t t))))))
8073 (error "Cannot refile to position inside the tree or region"))
8075 (setq nbuf (or (find-buffer-visiting file)
8076 (find-file-noselect file)))
8077 (if goto
8078 (progn
8079 (switch-to-buffer nbuf)
8080 (goto-char pos)
8081 (org-show-context 'org-goto))
8082 (if regionp
8083 (progn
8084 (kill-new (buffer-substring region-start region-end))
8085 (org-save-markers-in-region region-start region-end))
8086 (org-copy-subtree 1 nil t))
8087 (save-excursion
8088 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8089 (find-file-noselect file))))
8090 (setq reversed (org-notes-order-reversed-p))
8091 (save-excursion
8092 (save-restriction
8093 (widen)
8094 (goto-char pos)
8095 (looking-at outline-regexp)
8096 (setq level (org-get-valid-level (funcall outline-level) 1))
8097 (goto-char
8098 (if reversed
8099 (or (outline-next-heading) (point-max))
8100 (or (save-excursion (outline-get-next-sibling))
8101 (org-end-of-subtree t t)
8102 (point-max))))
8103 (if (not (bolp)) (newline))
8104 (bookmark-set "org-refile-last-stored")
8105 (org-paste-subtree level))))
8106 (if regionp
8107 (delete-region (point) (+ (point) region-length))
8108 (org-cut-subtree))
8109 (setq org-markers-to-move nil)
8110 (message "Refiled to \"%s\"" (car it)))))))
8112 (defun org-refile-goto-last-stored ()
8113 "Go to the location where the last refile was stored."
8114 (interactive)
8115 (bookmark-jump "org-refile-last-stored")
8116 (message "This is the location of the last refile"))
8118 (defun org-refile-get-location (&optional prompt default-buffer)
8119 "Prompt the user for a refile location, using PROMPT."
8120 (let ((org-refile-targets org-refile-targets)
8121 (org-refile-use-outline-path org-refile-use-outline-path))
8122 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8123 (unless org-refile-target-table
8124 (error "No refile targets"))
8125 (let* ((cbuf (current-buffer))
8126 (partial-completion-mode nil)
8127 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8128 (cfunc (if (and org-refile-use-outline-path
8129 org-outline-path-complete-in-steps)
8130 'org-olpath-completing-read
8131 'org-ido-completing-read))
8132 (extra (if org-refile-use-outline-path "/" ""))
8133 (filename (and cfn (expand-file-name cfn)))
8134 (tbl (mapcar
8135 (lambda (x)
8136 (if (not (equal filename (nth 1 x)))
8137 (cons (concat (car x) extra " ("
8138 (file-name-nondirectory (nth 1 x)) ")")
8139 (cdr x))
8140 (cons (concat (car x) extra) (cdr x))))
8141 org-refile-target-table))
8142 (completion-ignore-case t))
8143 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8144 tbl)))
8146 (defun org-olpath-completing-read (prompt collection &rest args)
8147 "Read an outline path like a file name."
8148 (let ((thetable collection)
8149 (org-completion-use-ido nil)) ; does not work with ido.
8150 (apply
8151 'org-ido-completing-read prompt
8152 (lambda (string predicate &optional flag)
8153 (let (rtn r f (l (length string)))
8154 (cond
8155 ((eq flag nil)
8156 ;; try completion
8157 (try-completion string thetable))
8158 ((eq flag t)
8159 ;; all-completions
8160 (setq rtn (all-completions string thetable predicate))
8161 (mapcar
8162 (lambda (x)
8163 (setq r (substring x l))
8164 (if (string-match " ([^)]*)$" x)
8165 (setq f (match-string 0 x))
8166 (setq f ""))
8167 (if (string-match "/" r)
8168 (concat string (substring r 0 (match-end 0)) f)
8170 rtn))
8171 ((eq flag 'lambda)
8172 ;; exact match?
8173 (assoc string thetable)))
8175 args)))
8177 ;;;; Dynamic blocks
8179 (defun org-find-dblock (name)
8180 "Find the first dynamic block with name NAME in the buffer.
8181 If not found, stay at current position and return nil."
8182 (let (pos)
8183 (save-excursion
8184 (goto-char (point-min))
8185 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8186 nil t)
8187 (match-beginning 0))))
8188 (if pos (goto-char pos))
8189 pos))
8191 (defconst org-dblock-start-re
8192 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8193 "Matches the startline of a dynamic block, with parameters.")
8195 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8196 "Matches the end of a dynamic block.")
8198 (defun org-create-dblock (plist)
8199 "Create a dynamic block section, with parameters taken from PLIST.
8200 PLIST must contain a :name entry which is used as name of the block."
8201 (unless (bolp) (newline))
8202 (let ((name (plist-get plist :name)))
8203 (insert "#+BEGIN: " name)
8204 (while plist
8205 (if (eq (car plist) :name)
8206 (setq plist (cddr plist))
8207 (insert " " (prin1-to-string (pop plist)))))
8208 (insert "\n\n#+END:\n")
8209 (beginning-of-line -2)))
8211 (defun org-prepare-dblock ()
8212 "Prepare dynamic block for refresh.
8213 This empties the block, puts the cursor at the insert position and returns
8214 the property list including an extra property :name with the block name."
8215 (unless (looking-at org-dblock-start-re)
8216 (error "Not at a dynamic block"))
8217 (let* ((begdel (1+ (match-end 0)))
8218 (name (org-no-properties (match-string 1)))
8219 (params (append (list :name name)
8220 (read (concat "(" (match-string 3) ")")))))
8221 (unless (re-search-forward org-dblock-end-re nil t)
8222 (error "Dynamic block not terminated"))
8223 (setq params
8224 (append params
8225 (list :content (buffer-substring
8226 begdel (match-beginning 0)))))
8227 (delete-region begdel (match-beginning 0))
8228 (goto-char begdel)
8229 (open-line 1)
8230 params))
8232 (defun org-map-dblocks (&optional command)
8233 "Apply COMMAND to all dynamic blocks in the current buffer.
8234 If COMMAND is not given, use `org-update-dblock'."
8235 (let ((cmd (or command 'org-update-dblock))
8236 pos)
8237 (save-excursion
8238 (goto-char (point-min))
8239 (while (re-search-forward org-dblock-start-re nil t)
8240 (goto-char (setq pos (match-beginning 0)))
8241 (condition-case nil
8242 (funcall cmd)
8243 (error (message "Error during update of dynamic block")))
8244 (goto-char pos)
8245 (unless (re-search-forward org-dblock-end-re nil t)
8246 (error "Dynamic block not terminated"))))))
8248 (defun org-dblock-update (&optional arg)
8249 "User command for updating dynamic blocks.
8250 Update the dynamic block at point. With prefix ARG, update all dynamic
8251 blocks in the buffer."
8252 (interactive "P")
8253 (if arg
8254 (org-update-all-dblocks)
8255 (or (looking-at org-dblock-start-re)
8256 (org-beginning-of-dblock))
8257 (org-update-dblock)))
8259 (defun org-update-dblock ()
8260 "Update the dynamic block at point
8261 This means to empty the block, parse for parameters and then call
8262 the correct writing function."
8263 (save-window-excursion
8264 (let* ((pos (point))
8265 (line (org-current-line))
8266 (params (org-prepare-dblock))
8267 (name (plist-get params :name))
8268 (cmd (intern (concat "org-dblock-write:" name))))
8269 (message "Updating dynamic block `%s' at line %d..." name line)
8270 (funcall cmd params)
8271 (message "Updating dynamic block `%s' at line %d...done" name line)
8272 (goto-char pos))))
8274 (defun org-beginning-of-dblock ()
8275 "Find the beginning of the dynamic block at point.
8276 Error if there is no such block at point."
8277 (let ((pos (point))
8278 beg)
8279 (end-of-line 1)
8280 (if (and (re-search-backward org-dblock-start-re nil t)
8281 (setq beg (match-beginning 0))
8282 (re-search-forward org-dblock-end-re nil t)
8283 (> (match-end 0) pos))
8284 (goto-char beg)
8285 (goto-char pos)
8286 (error "Not in a dynamic block"))))
8288 (defun org-update-all-dblocks ()
8289 "Update all dynamic blocks in the buffer.
8290 This function can be used in a hook."
8291 (when (org-mode-p)
8292 (org-map-dblocks 'org-update-dblock)))
8295 ;;;; Completion
8297 (defconst org-additional-option-like-keywords
8298 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8299 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8300 "BEGIN_EXAMPLE" "END_EXAMPLE"
8301 "BEGIN_QUOTE" "END_QUOTE"
8302 "BEGIN_VERSE" "END_VERSE"
8303 "BEGIN_SRC" "END_SRC"
8304 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8306 (defcustom org-structure-template-alist
8308 ("s" "#+begin_src ?\n\n#+end_src"
8309 "<src lang=\"?\">\n\n</src>")
8310 ("e" "#+begin_example\n?\n#+end_example"
8311 "<example>\n?\n</example>")
8312 ("q" "#+begin_quote\n?\n#+end_quote"
8313 "<quote>\n?\n</quote>")
8314 ("v" "#+begin_verse\n?\n#+end_verse"
8315 "<verse>\n?\n/verse>")
8316 ("l" "#+begin_latex\n?\n#+end_latex"
8317 "<literal style=\"latex\">\n?\n</literal>")
8318 ("L" "#+latex: "
8319 "<literal style=\"latex\">?</literal>")
8320 ("h" "#+begin_html\n?\n#+end_html"
8321 "<literal style=\"html\">\n?\n</literal>")
8322 ("H" "#+html: "
8323 "<literal style=\"html\">?</literal>")
8324 ("a" "#+begin_ascii\n?\n#+end_ascii")
8325 ("A" "#+ascii: ")
8326 ("i" "#+include %file ?"
8327 "<include file=%file markup=\"?\">")
8329 "Structure completion elements.
8330 This is a list of abbreviation keys and values. The value gets inserted
8331 it you type @samp{.} followed by the key and then the completion key,
8332 usually `M-TAB'. %file will be replaced by a file name after prompting
8333 for the file using completion.
8334 There are two templates for each key, the first uses the original Org syntax,
8335 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8336 the default when the /org-mtags.el/ module has been loaded. See also the
8337 variable `org-mtags-prefer-muse-templates'.
8338 This is an experimental feature, it is undecided if it is going to stay in."
8339 :group 'org-completion
8340 :type '(repeat
8341 (string :tag "Key")
8342 (string :tag "Template")
8343 (string :tag "Muse Template")))
8345 (defun org-try-structure-completion ()
8346 "Try to complete a structure template before point.
8347 This looks for strings like \"<e\" on an otherwise empty line and
8348 expands them."
8349 (let ((l (buffer-substring (point-at-bol) (point)))
8351 (when (and (looking-at "[ \t]*$")
8352 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8353 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8354 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8355 (match-beginning 1)) a)
8356 t)))
8358 (defun org-complete-expand-structure-template (start cell)
8359 "Expand a structure template."
8360 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8361 (rpl (nth (if musep 2 1) cell)))
8362 (delete-region start (point))
8363 (when (string-match "\\`#\\+" rpl)
8364 (cond
8365 ((bolp))
8366 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8367 (delete-region (point-at-bol) (point)))
8368 (t (newline))))
8369 (setq start (point))
8370 (if (string-match "%file" rpl)
8371 (setq rpl (replace-match
8372 (concat
8373 "\""
8374 (save-match-data
8375 (abbreviate-file-name (read-file-name "Include file: ")))
8376 "\"")
8377 t t rpl)))
8378 (insert rpl)
8379 (if (re-search-backward "\\?" start t) (delete-char 1))))
8382 (defun org-complete (&optional arg)
8383 "Perform completion on word at point.
8384 At the beginning of a headline, this completes TODO keywords as given in
8385 `org-todo-keywords'.
8386 If the current word is preceded by a backslash, completes the TeX symbols
8387 that are supported for HTML support.
8388 If the current word is preceded by \"#+\", completes special words for
8389 setting file options.
8390 In the line after \"#+STARTUP:, complete valid keywords.\"
8391 At all other locations, this simply calls the value of
8392 `org-completion-fallback-command'."
8393 (interactive "P")
8394 (org-without-partial-completion
8395 (catch 'exit
8396 (let* ((a nil)
8397 (end (point))
8398 (beg1 (save-excursion
8399 (skip-chars-backward (org-re "[:alnum:]_@"))
8400 (point)))
8401 (beg (save-excursion
8402 (skip-chars-backward "a-zA-Z0-9_:$")
8403 (point)))
8404 (confirm (lambda (x) (stringp (car x))))
8405 (searchhead (equal (char-before beg) ?*))
8406 (struct
8407 (when (and (member (char-before beg1) '(?. ?<))
8408 (setq a (assoc (buffer-substring beg1 (point))
8409 org-structure-template-alist)))
8410 (org-complete-expand-structure-template (1- beg1) a)
8411 (throw 'exit t)))
8412 (tag (and (equal (char-before beg1) ?:)
8413 (equal (char-after (point-at-bol)) ?*)))
8414 (prop (and (equal (char-before beg1) ?:)
8415 (not (equal (char-after (point-at-bol)) ?*))))
8416 (texp (equal (char-before beg) ?\\))
8417 (link (equal (char-before beg) ?\[))
8418 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8419 beg)
8420 "#+"))
8421 (startup (string-match "^#\\+STARTUP:.*"
8422 (buffer-substring (point-at-bol) (point))))
8423 (completion-ignore-case opt)
8424 (type nil)
8425 (tbl nil)
8426 (table (cond
8427 (opt
8428 (setq type :opt)
8429 (require 'org-exp)
8430 (append
8431 (mapcar
8432 (lambda (x)
8433 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8434 (cons (match-string 2 x) (match-string 1 x)))
8435 (org-split-string (org-get-current-options) "\n"))
8436 (mapcar 'list org-additional-option-like-keywords)))
8437 (startup
8438 (setq type :startup)
8439 org-startup-options)
8440 (link (append org-link-abbrev-alist-local
8441 org-link-abbrev-alist))
8442 (texp
8443 (setq type :tex)
8444 org-html-entities)
8445 ((string-match "\\`\\*+[ \t]+\\'"
8446 (buffer-substring (point-at-bol) beg))
8447 (setq type :todo)
8448 (mapcar 'list org-todo-keywords-1))
8449 (searchhead
8450 (setq type :searchhead)
8451 (save-excursion
8452 (goto-char (point-min))
8453 (while (re-search-forward org-todo-line-regexp nil t)
8454 (push (list
8455 (org-make-org-heading-search-string
8456 (match-string 3) t))
8457 tbl)))
8458 tbl)
8459 (tag (setq type :tag beg beg1)
8460 (or org-tag-alist (org-get-buffer-tags)))
8461 (prop (setq type :prop beg beg1)
8462 (mapcar 'list (org-buffer-property-keys nil t t)))
8463 (t (progn
8464 (call-interactively org-completion-fallback-command)
8465 (throw 'exit nil)))))
8466 (pattern (buffer-substring-no-properties beg end))
8467 (completion (try-completion pattern table confirm)))
8468 (cond ((eq completion t)
8469 (if (not (assoc (upcase pattern) table))
8470 (message "Already complete")
8471 (if (and (equal type :opt)
8472 (not (member (car (assoc (upcase pattern) table))
8473 org-additional-option-like-keywords)))
8474 (insert (substring (cdr (assoc (upcase pattern) table))
8475 (length pattern)))
8476 (if (memq type '(:tag :prop)) (insert ":")))))
8477 ((null completion)
8478 (message "Can't find completion for \"%s\"" pattern)
8479 (ding))
8480 ((not (string= pattern completion))
8481 (delete-region beg end)
8482 (if (string-match " +$" completion)
8483 (setq completion (replace-match "" t t completion)))
8484 (insert completion)
8485 (if (get-buffer-window "*Completions*")
8486 (delete-window (get-buffer-window "*Completions*")))
8487 (if (assoc completion table)
8488 (if (eq type :todo) (insert " ")
8489 (if (memq type '(:tag :prop)) (insert ":"))))
8490 (if (and (equal type :opt) (assoc completion table))
8491 (message "%s" (substitute-command-keys
8492 "Press \\[org-complete] again to insert example settings"))))
8494 (message "Making completion list...")
8495 (let ((list (sort (all-completions pattern table confirm)
8496 'string<)))
8497 (with-output-to-temp-buffer "*Completions*"
8498 (condition-case nil
8499 ;; Protection needed for XEmacs and emacs 21
8500 (display-completion-list list pattern)
8501 (error (display-completion-list list)))))
8502 (message "Making completion list...%s" "done")))))))
8504 ;;;; TODO, DEADLINE, Comments
8506 (defun org-toggle-comment ()
8507 "Change the COMMENT state of an entry."
8508 (interactive)
8509 (save-excursion
8510 (org-back-to-heading)
8511 (let (case-fold-search)
8512 (if (looking-at (concat outline-regexp
8513 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8514 (replace-match "" t t nil 1)
8515 (if (looking-at outline-regexp)
8516 (progn
8517 (goto-char (match-end 0))
8518 (insert org-comment-string " ")))))))
8520 (defvar org-last-todo-state-is-todo nil
8521 "This is non-nil when the last TODO state change led to a TODO state.
8522 If the last change removed the TODO tag or switched to DONE, then
8523 this is nil.")
8525 (defvar org-setting-tags nil) ; dynamically skipped
8527 (defun org-parse-local-options (string var)
8528 "Parse STRING for startup setting relevant for variable VAR."
8529 (let ((rtn (symbol-value var))
8530 e opts)
8531 (save-match-data
8532 (if (or (not string) (not (string-match "\\S-" string)))
8534 (setq opts (delq nil (mapcar (lambda (x)
8535 (setq e (assoc x org-startup-options))
8536 (if (eq (nth 1 e) var) e nil))
8537 (org-split-string string "[ \t]+"))))
8538 (if (not opts)
8540 (setq rtn nil)
8541 (while (setq e (pop opts))
8542 (if (not (nth 3 e))
8543 (setq rtn (nth 2 e))
8544 (if (not (listp rtn)) (setq rtn nil))
8545 (push (nth 2 e) rtn)))
8546 rtn)))))
8548 (defvar org-todo-setup-filter-hook nil
8549 "Hook for functions that pre-filter todo specs.
8551 Each function takes a todo spec and returns either `nil' or the spec
8552 transformed into canonical form." )
8554 (defvar org-todo-get-default-hook nil
8555 "Hook for functions that get a default item for todo.
8557 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8558 `nil' or a string to be used for the todo mark." )
8560 (defvar org-agenda-headline-snapshot-before-repeat)
8561 (defun org-todo (&optional arg)
8562 "Change the TODO state of an item.
8563 The state of an item is given by a keyword at the start of the heading,
8564 like
8565 *** TODO Write paper
8566 *** DONE Call mom
8568 The different keywords are specified in the variable `org-todo-keywords'.
8569 By default the available states are \"TODO\" and \"DONE\".
8570 So for this example: when the item starts with TODO, it is changed to DONE.
8571 When it starts with DONE, the DONE is removed. And when neither TODO nor
8572 DONE are present, add TODO at the beginning of the heading.
8574 With C-u prefix arg, use completion to determine the new state.
8575 With numeric prefix arg, switch to that state.
8576 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8577 With a tripple C-u prefix, circumvent any state blocking.
8579 For calling through lisp, arg is also interpreted in the following way:
8580 'none -> empty state
8581 \"\"(empty string) -> switch to empty state
8582 'done -> switch to DONE
8583 'nextset -> switch to the next set of keywords
8584 'previousset -> switch to the previous set of keywords
8585 \"WAITING\" -> switch to the specified keyword, but only if it
8586 really is a member of `org-todo-keywords'."
8587 (interactive "P")
8588 (if (equal arg '(16)) (setq arg 'nextset))
8589 (let ((org-blocker-hook org-blocker-hook))
8590 (when (equal arg '(64))
8591 (setq arg nil org-blocker-hook nil))
8592 (save-excursion
8593 (catch 'exit
8594 (org-back-to-heading)
8595 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8596 (or (looking-at (concat " +" org-todo-regexp " *"))
8597 (looking-at " *"))
8598 (let* ((match-data (match-data))
8599 (startpos (point-at-bol))
8600 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8601 (org-log-done org-log-done)
8602 (org-log-repeat org-log-repeat)
8603 (org-todo-log-states org-todo-log-states)
8604 (this (match-string 1))
8605 (hl-pos (match-beginning 0))
8606 (head (org-get-todo-sequence-head this))
8607 (ass (assoc head org-todo-kwd-alist))
8608 (interpret (nth 1 ass))
8609 (done-word (nth 3 ass))
8610 (final-done-word (nth 4 ass))
8611 (last-state (or this ""))
8612 (completion-ignore-case t)
8613 (member (member this org-todo-keywords-1))
8614 (tail (cdr member))
8615 (state (cond
8616 ((and org-todo-key-trigger
8617 (or (and (equal arg '(4))
8618 (eq org-use-fast-todo-selection 'prefix))
8619 (and (not arg) org-use-fast-todo-selection
8620 (not (eq org-use-fast-todo-selection
8621 'prefix)))))
8622 ;; Use fast selection
8623 (org-fast-todo-selection))
8624 ((and (equal arg '(4))
8625 (or (not org-use-fast-todo-selection)
8626 (not org-todo-key-trigger)))
8627 ;; Read a state with completion
8628 (org-ido-completing-read
8629 "State: " (mapcar (lambda(x) (list x))
8630 org-todo-keywords-1)
8631 nil t))
8632 ((eq arg 'right)
8633 (if this
8634 (if tail (car tail) nil)
8635 (car org-todo-keywords-1)))
8636 ((eq arg 'left)
8637 (if (equal member org-todo-keywords-1)
8639 (if this
8640 (nth (- (length org-todo-keywords-1)
8641 (length tail) 2)
8642 org-todo-keywords-1)
8643 (org-last org-todo-keywords-1))))
8644 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8645 (setq arg nil))) ; hack to fall back to cycling
8646 (arg
8647 ;; user or caller requests a specific state
8648 (cond
8649 ((equal arg "") nil)
8650 ((eq arg 'none) nil)
8651 ((eq arg 'done) (or done-word (car org-done-keywords)))
8652 ((eq arg 'nextset)
8653 (or (car (cdr (member head org-todo-heads)))
8654 (car org-todo-heads)))
8655 ((eq arg 'previousset)
8656 (let ((org-todo-heads (reverse org-todo-heads)))
8657 (or (car (cdr (member head org-todo-heads)))
8658 (car org-todo-heads))))
8659 ((car (member arg org-todo-keywords-1)))
8660 ((nth (1- (prefix-numeric-value arg))
8661 org-todo-keywords-1))))
8662 ((null member) (or head (car org-todo-keywords-1)))
8663 ((equal this final-done-word) nil) ;; -> make empty
8664 ((null tail) nil) ;; -> first entry
8665 ((memq interpret '(type priority))
8666 (if (eq this-command last-command)
8667 (car tail)
8668 (if (> (length tail) 0)
8669 (or done-word (car org-done-keywords))
8670 nil)))
8672 (car tail))))
8673 (state (or
8674 (run-hook-with-args-until-success
8675 'org-todo-get-default-hook state last-state)
8676 state))
8677 (next (if state (concat " " state " ") " "))
8678 (change-plist (list :type 'todo-state-change :from this :to state
8679 :position startpos))
8680 dolog now-done-p)
8681 (when org-blocker-hook
8682 (setq org-last-todo-state-is-todo
8683 (not (member this org-done-keywords)))
8684 (unless (save-excursion
8685 (save-match-data
8686 (run-hook-with-args-until-failure
8687 'org-blocker-hook change-plist)))
8688 (if (interactive-p)
8689 (error "TODO state change from %s to %s blocked" this state)
8690 ;; fail silently
8691 (message "TODO state change from %s to %s blocked" this state)
8692 (throw 'exit nil))))
8693 (store-match-data match-data)
8694 (replace-match next t t)
8695 (unless (pos-visible-in-window-p hl-pos)
8696 (message "TODO state changed to %s" (org-trim next)))
8697 (unless head
8698 (setq head (org-get-todo-sequence-head state)
8699 ass (assoc head org-todo-kwd-alist)
8700 interpret (nth 1 ass)
8701 done-word (nth 3 ass)
8702 final-done-word (nth 4 ass)))
8703 (when (memq arg '(nextset previousset))
8704 (message "Keyword-Set %d/%d: %s"
8705 (- (length org-todo-sets) -1
8706 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8707 (length org-todo-sets)
8708 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8709 (setq org-last-todo-state-is-todo
8710 (not (member state org-done-keywords)))
8711 (setq now-done-p (and (member state org-done-keywords)
8712 (not (member this org-done-keywords))))
8713 (and logging (org-local-logging logging))
8714 (when (and (or org-todo-log-states org-log-done)
8715 (not (memq arg '(nextset previousset))))
8716 ;; we need to look at recording a time and note
8717 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8718 (nth 2 (assoc this org-todo-log-states))))
8719 (when (and state
8720 (member state org-not-done-keywords)
8721 (not (member this org-not-done-keywords)))
8722 ;; This is now a todo state and was not one before
8723 ;; If there was a CLOSED time stamp, get rid of it.
8724 (org-add-planning-info nil nil 'closed))
8725 (when (and now-done-p org-log-done)
8726 ;; It is now done, and it was not done before
8727 (org-add-planning-info 'closed (org-current-time))
8728 (if (and (not dolog) (eq 'note org-log-done))
8729 (org-add-log-setup 'done state this 'findpos 'note)))
8730 (when (and state dolog)
8731 ;; This is a non-nil state, and we need to log it
8732 (org-add-log-setup 'state state this 'findpos dolog)))
8733 ;; Fixup tag positioning
8734 (org-todo-trigger-tag-changes state)
8735 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8736 (when org-provide-todo-statistics
8737 (org-update-parent-todo-statistics))
8738 (run-hooks 'org-after-todo-state-change-hook)
8739 (if (and arg (not (member state org-done-keywords)))
8740 (setq head (org-get-todo-sequence-head state)))
8741 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8742 ;; Do we need to trigger a repeat?
8743 (when now-done-p
8744 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8745 ;; This is for the agenda, take a snapshot of the headline.
8746 (save-match-data
8747 (setq org-agenda-headline-snapshot-before-repeat
8748 (org-get-heading))))
8749 (org-auto-repeat-maybe state))
8750 ;; Fixup cursor location if close to the keyword
8751 (if (and (outline-on-heading-p)
8752 (not (bolp))
8753 (save-excursion (beginning-of-line 1)
8754 (looking-at org-todo-line-regexp))
8755 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8756 (progn
8757 (goto-char (or (match-end 2) (match-end 1)))
8758 (just-one-space)))
8759 (when org-trigger-hook
8760 (save-excursion
8761 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8763 (defun org-block-todo-from-children-or-siblings (change-plist)
8764 "Block turning an entry into a TODO, using the hierarchy.
8765 This checks whether the current task should be blocked from state
8766 changes. Such blocking occurs when:
8768 1. The task has children which are not all in a completed state.
8770 2. A task has a parent with the property :ORDERED:, and there
8771 are siblings prior to the current task with incomplete
8772 status."
8773 (catch 'dont-block
8774 ;; If this is not a todo state change, or if this entry is already DONE,
8775 ;; do not block
8776 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8777 (member (plist-get change-plist :from)
8778 (cons 'done org-done-keywords))
8779 (member (plist-get change-plist :to)
8780 (cons 'todo org-not-done-keywords)))
8781 (throw 'dont-block t))
8782 ;; If this task has children, and any are undone, it's blocked
8783 (save-excursion
8784 (org-back-to-heading t)
8785 (let ((this-level (funcall outline-level)))
8786 (outline-next-heading)
8787 (let ((child-level (funcall outline-level)))
8788 (while (and (not (eobp))
8789 (> child-level this-level))
8790 ;; this todo has children, check whether they are all
8791 ;; completed
8792 (if (and (not (org-entry-is-done-p))
8793 (org-entry-is-todo-p))
8794 (throw 'dont-block nil))
8795 (outline-next-heading)
8796 (setq child-level (funcall outline-level))))))
8797 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8798 ;; any previous siblings are undone, it's blocked
8799 (save-excursion
8800 (org-back-to-heading t)
8801 (when (save-excursion
8802 (ignore-errors
8803 (org-up-heading-all 1)
8804 (org-entry-get (point) "ORDERED")))
8805 (let* ((this-level (funcall outline-level))
8806 (current-level this-level))
8807 (while (and (not (bobp))
8808 (= current-level this-level))
8809 (outline-previous-heading)
8810 (setq current-level (funcall outline-level))
8811 (if (= current-level this-level)
8812 ;; this todo has children, check whether they are all
8813 ;; completed
8814 (if (and (not (org-entry-is-done-p))
8815 (org-entry-is-todo-p))
8816 (throw 'dont-block nil)))))))
8817 t)) ; don't block
8819 (defcustom org-track-ordered-property-with-tag nil
8820 "Should the ORDERED property also be shown as a tag?
8821 The ORDERED property decides if an entry should require subtasks to be
8822 completed in sequence. Since a property is not very visible, setting
8823 this option means that toggling the ORDERED property with the command
8824 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
8825 not relevant for the behavior, but it makes things more visible.
8827 Note that toggling the tag with tags commands will not change the property
8828 and therefore not influence behavior!
8830 This can be t, meaning the tag ORDERED should be used, It can also be a
8831 string to select a different tag for this task."
8832 :group 'org-todo
8833 :type '(choice
8834 (const :tag "No tracking" nil)
8835 (const :tag "Track with ORDERED tag" t)
8836 (string :tag "Use other tag")))
8838 (defun org-toggle-ordered-property ()
8839 "Toggle the ORDERED property of the current entry.
8840 For better visibility, you can track the value of this property with a tag.
8841 See variable `org-track-ordered-property-with-tag'."
8842 (interactive)
8843 (let* ((t1 org-track-ordered-property-with-tag)
8844 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
8845 (save-excursion
8846 (org-back-to-heading)
8847 (if (org-entry-get nil "ORDERED")
8848 (progn
8849 (org-delete-property "ORDERED")
8850 (and tag (org-toggle-tag tag 'off))
8851 (message "Subtasks can be completed in arbitrary order"))
8852 (org-entry-put nil "ORDERED" "t")
8853 (and tag (org-toggle-tag tag 'on))
8854 (message "Subtasks must be completed in sequence")))))
8856 (defvar org-blocked-by-checkboxes) ; dynamically scoped
8857 (defun org-block-todo-from-checkboxes (change-plist)
8858 "Block turning an entry into a TODO, using checkboxes.
8859 This checks whether the current task should be blocked from state
8860 changes because there are uncheckd boxes in this entry."
8861 (catch 'dont-block
8862 ;; If this is not a todo state change, or if this entry is already DONE,
8863 ;; do not block
8864 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8865 (member (plist-get change-plist :from)
8866 (cons 'done org-done-keywords))
8867 (member (plist-get change-plist :to)
8868 (cons 'todo org-not-done-keywords)))
8869 (throw 'dont-block t))
8870 ;; If this task has checkboxes that are not checked, it's blocked
8871 (save-excursion
8872 (org-back-to-heading t)
8873 (let ((beg (point)) end)
8874 (outline-next-heading)
8875 (setq end (point))
8876 (goto-char beg)
8877 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8878 end t)
8879 (progn
8880 (if (boundp 'org-blocked-by-checkboxes)
8881 (setq org-blocked-by-checkboxes t))
8882 (throw 'dont-block nil)))))
8883 t)) ; do not block
8885 (defun org-update-parent-todo-statistics ()
8886 "Update any statistics cookie in the parent of the current headline."
8887 (interactive)
8888 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8889 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
8890 (catch 'exit
8891 (save-excursion
8892 (setq level (org-up-heading-safe))
8893 (unless level
8894 (throw 'exit nil))
8895 (while (re-search-forward box-re (point-at-eol) t)
8896 (setq cnt-all 0 cnt-done 0 cookie-present t)
8897 (setq is-percent (match-end 2))
8898 (save-match-data
8899 (unless (outline-next-heading) (throw 'exit nil))
8900 (while (looking-at org-todo-line-regexp)
8901 (setq kwd (match-string 2))
8902 (and kwd (setq cnt-all (1+ cnt-all)))
8903 (and (member kwd org-done-keywords)
8904 (setq cnt-done (1+ cnt-done)))
8905 (condition-case nil
8906 (org-forward-same-level 1)
8907 (error (end-of-line 1)))))
8908 (replace-match
8909 (if is-percent
8910 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8911 (format "[%d/%d]" cnt-done cnt-all))))
8912 (when cookie-present
8913 (run-hook-with-args 'org-after-todo-statistics-hook
8914 cnt-done (- cnt-all cnt-done)))))))
8916 (defvar org-after-todo-statistics-hook nil
8917 "Hook that is called after a TODO statistics cookie has been updated.
8918 Each function is called with two arguments: the number of not-done entries
8919 and the number of done entries.
8921 For example, the following function, when added to this hook, will switch
8922 an entry to DONE when all children are done, and back to TODO when new
8923 entries are set to a TODO status. Note that this hook is only called
8924 when there is a statistics cookie in the headline!
8926 (defun org-summary-todo (n-done n-not-done)
8927 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8928 (let (org-log-done org-log-states) ; turn off logging
8929 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8932 (defun org-todo-trigger-tag-changes (state)
8933 "Apply the changes defined in `org-todo-state-tags-triggers'."
8934 (let ((l org-todo-state-tags-triggers)
8935 changes)
8936 (when (or (not state) (equal state ""))
8937 (setq changes (append changes (cdr (assoc "" l)))))
8938 (when (and (stringp state) (> (length state) 0))
8939 (setq changes (append changes (cdr (assoc state l)))))
8940 (when (member state org-not-done-keywords)
8941 (setq changes (append changes (cdr (assoc 'todo l)))))
8942 (when (member state org-done-keywords)
8943 (setq changes (append changes (cdr (assoc 'done l)))))
8944 (dolist (c changes)
8945 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8947 (defun org-local-logging (value)
8948 "Get logging settings from a property VALUE."
8949 (let* (words w a)
8950 ;; directly set the variables, they are already local.
8951 (setq org-log-done nil
8952 org-log-repeat nil
8953 org-todo-log-states nil)
8954 (setq words (org-split-string value))
8955 (while (setq w (pop words))
8956 (cond
8957 ((setq a (assoc w org-startup-options))
8958 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8959 (set (nth 1 a) (nth 2 a))))
8960 ((setq a (org-extract-log-state-settings w))
8961 (and (member (car a) org-todo-keywords-1)
8962 (push a org-todo-log-states)))))))
8964 (defun org-get-todo-sequence-head (kwd)
8965 "Return the head of the TODO sequence to which KWD belongs.
8966 If KWD is not set, check if there is a text property remembering the
8967 right sequence."
8968 (let (p)
8969 (cond
8970 ((not kwd)
8971 (or (get-text-property (point-at-bol) 'org-todo-head)
8972 (progn
8973 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8974 nil (point-at-eol)))
8975 (get-text-property p 'org-todo-head))))
8976 ((not (member kwd org-todo-keywords-1))
8977 (car org-todo-keywords-1))
8978 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8980 (defun org-fast-todo-selection ()
8981 "Fast TODO keyword selection with single keys.
8982 Returns the new TODO keyword, or nil if no state change should occur."
8983 (let* ((fulltable org-todo-key-alist)
8984 (done-keywords org-done-keywords) ;; needed for the faces.
8985 (maxlen (apply 'max (mapcar
8986 (lambda (x)
8987 (if (stringp (car x)) (string-width (car x)) 0))
8988 fulltable)))
8989 (expert nil)
8990 (fwidth (+ maxlen 3 1 3))
8991 (ncol (/ (- (window-width) 4) fwidth))
8992 tg cnt e c tbl
8993 groups ingroup)
8994 (save-excursion
8995 (save-window-excursion
8996 (if expert
8997 (set-buffer (get-buffer-create " *Org todo*"))
8998 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8999 (erase-buffer)
9000 (org-set-local 'org-done-keywords done-keywords)
9001 (setq tbl fulltable cnt 0)
9002 (while (setq e (pop tbl))
9003 (cond
9004 ((equal e '(:startgroup))
9005 (push '() groups) (setq ingroup t)
9006 (when (not (= cnt 0))
9007 (setq cnt 0)
9008 (insert "\n"))
9009 (insert "{ "))
9010 ((equal e '(:endgroup))
9011 (setq ingroup nil cnt 0)
9012 (insert "}\n"))
9013 ((equal e '(:newline))
9014 (when (not (= cnt 0))
9015 (setq cnt 0)
9016 (insert "\n")
9017 (setq e (car tbl))
9018 (while (equal (car tbl) '(:newline))
9019 (insert "\n")
9020 (setq tbl (cdr tbl)))))
9022 (setq tg (car e) c (cdr e))
9023 (if ingroup (push tg (car groups)))
9024 (setq tg (org-add-props tg nil 'face
9025 (org-get-todo-face tg)))
9026 (if (and (= cnt 0) (not ingroup)) (insert " "))
9027 (insert "[" c "] " tg (make-string
9028 (- fwidth 4 (length tg)) ?\ ))
9029 (when (= (setq cnt (1+ cnt)) ncol)
9030 (insert "\n")
9031 (if ingroup (insert " "))
9032 (setq cnt 0)))))
9033 (insert "\n")
9034 (goto-char (point-min))
9035 (if (not expert) (org-fit-window-to-buffer))
9036 (message "[a-z..]:Set [SPC]:clear")
9037 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9038 (cond
9039 ((or (= c ?\C-g)
9040 (and (= c ?q) (not (rassoc c fulltable))))
9041 (setq quit-flag t))
9042 ((= c ?\ ) nil)
9043 ((setq e (rassoc c fulltable) tg (car e))
9045 (t (setq quit-flag t)))))))
9047 (defun org-entry-is-todo-p ()
9048 (member (org-get-todo-state) org-not-done-keywords))
9050 (defun org-entry-is-done-p ()
9051 (member (org-get-todo-state) org-done-keywords))
9053 (defun org-get-todo-state ()
9054 (save-excursion
9055 (org-back-to-heading t)
9056 (and (looking-at org-todo-line-regexp)
9057 (match-end 2)
9058 (match-string 2))))
9060 (defun org-at-date-range-p (&optional inactive-ok)
9061 "Is the cursor inside a date range?"
9062 (interactive)
9063 (save-excursion
9064 (catch 'exit
9065 (let ((pos (point)))
9066 (skip-chars-backward "^[<\r\n")
9067 (skip-chars-backward "<[")
9068 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9069 (>= (match-end 0) pos)
9070 (throw 'exit t))
9071 (skip-chars-backward "^<[\r\n")
9072 (skip-chars-backward "<[")
9073 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9074 (>= (match-end 0) pos)
9075 (throw 'exit t)))
9076 nil)))
9078 (defun org-get-repeat ()
9079 "Check if there is a deadline/schedule with repeater in this entry."
9080 (save-match-data
9081 (save-excursion
9082 (org-back-to-heading t)
9083 (if (re-search-forward
9084 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9085 (match-string 1)))))
9087 (defvar org-last-changed-timestamp)
9088 (defvar org-last-inserted-timestamp)
9089 (defvar org-log-post-message)
9090 (defvar org-log-note-purpose)
9091 (defvar org-log-note-how)
9092 (defvar org-log-note-extra)
9093 (defun org-auto-repeat-maybe (done-word)
9094 "Check if the current headline contains a repeated deadline/schedule.
9095 If yes, set TODO state back to what it was and change the base date
9096 of repeating deadline/scheduled time stamps to new date.
9097 This function is run automatically after each state change to a DONE state."
9098 ;; last-state is dynamically scoped into this function
9099 (let* ((repeat (org-get-repeat))
9100 (aa (assoc last-state org-todo-kwd-alist))
9101 (interpret (nth 1 aa))
9102 (head (nth 2 aa))
9103 (whata '(("d" . day) ("m" . month) ("y" . year)))
9104 (msg "Entry repeats: ")
9105 (org-log-done nil)
9106 (org-todo-log-states nil)
9107 (nshiftmax 10) (nshift 0)
9108 re type n what ts time)
9109 (when repeat
9110 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9111 (org-todo (if (eq interpret 'type) last-state head))
9112 (when org-log-repeat
9113 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9114 (memq 'org-add-log-note post-command-hook))
9115 ;; OK, we are already setup for some record
9116 (if (eq org-log-repeat 'note)
9117 ;; make sure we take a note, not only a time stamp
9118 (setq org-log-note-how 'note))
9119 ;; Set up for taking a record
9120 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9121 last-state
9122 'findpos org-log-repeat)))
9123 (org-back-to-heading t)
9124 (org-add-planning-info nil nil 'closed)
9125 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9126 org-deadline-time-regexp "\\)\\|\\("
9127 org-ts-regexp "\\)"))
9128 (while (re-search-forward
9129 re (save-excursion (outline-next-heading) (point)) t)
9130 (setq type (if (match-end 1) org-scheduled-string
9131 (if (match-end 3) org-deadline-string "Plain:"))
9132 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9133 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9134 (setq n (string-to-number (match-string 2 ts))
9135 what (match-string 3 ts))
9136 (if (equal what "w") (setq n (* n 7) what "d"))
9137 ;; Preparation, see if we need to modify the start date for the change
9138 (when (match-end 1)
9139 (setq time (save-match-data (org-time-string-to-time ts)))
9140 (cond
9141 ((equal (match-string 1 ts) ".")
9142 ;; Shift starting date to today
9143 (org-timestamp-change
9144 (- (time-to-days (current-time)) (time-to-days time))
9145 'day))
9146 ((equal (match-string 1 ts) "+")
9147 (while (or (= nshift 0)
9148 (<= (time-to-days time) (time-to-days (current-time))))
9149 (when (= (incf nshift) nshiftmax)
9150 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9151 (error "Abort")))
9152 (org-timestamp-change n (cdr (assoc what whata)))
9153 (org-at-timestamp-p t)
9154 (setq ts (match-string 1))
9155 (setq time (save-match-data (org-time-string-to-time ts))))
9156 (org-timestamp-change (- n) (cdr (assoc what whata)))
9157 ;; rematch, so that we have everything in place for the real shift
9158 (org-at-timestamp-p t)
9159 (setq ts (match-string 1))
9160 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9161 (org-timestamp-change n (cdr (assoc what whata)))
9162 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9163 (setq org-log-post-message msg)
9164 (message "%s" msg))))
9166 (defun org-show-todo-tree (arg)
9167 "Make a compact tree which shows all headlines marked with TODO.
9168 The tree will show the lines where the regexp matches, and all higher
9169 headlines above the match.
9170 With a \\[universal-argument] prefix, also show the DONE entries.
9171 With a numeric prefix N, construct a sparse tree for the Nth element
9172 of `org-todo-keywords-1'."
9173 (interactive "P")
9174 (let ((case-fold-search nil)
9175 (kwd-re
9176 (cond ((null arg) org-not-done-regexp)
9177 ((equal arg '(4))
9178 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9179 (mapcar 'list org-todo-keywords-1))))
9180 (concat "\\("
9181 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9182 "\\)\\>")))
9183 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9184 (regexp-quote (nth (1- (prefix-numeric-value arg))
9185 org-todo-keywords-1)))
9186 (t (error "Invalid prefix argument: %s" arg)))))
9187 (message "%d TODO entries found"
9188 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9190 (defun org-deadline (&optional remove time)
9191 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9192 With argument REMOVE, remove any deadline from the item.
9193 When TIME is set, it should be an internal time specification, and the
9194 scheduling will use the corresponding date."
9195 (interactive "P")
9196 (if remove
9197 (progn
9198 (org-remove-timestamp-with-keyword org-deadline-string)
9199 (message "Item no longer has a deadline."))
9200 (if (org-get-repeat)
9201 (error "Cannot change deadline on task with repeater, please do that by hand")
9202 (org-add-planning-info 'deadline time 'closed)
9203 (message "Deadline on %s" org-last-inserted-timestamp))))
9205 (defun org-schedule (&optional remove time)
9206 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9207 With argument REMOVE, remove any scheduling date from the item.
9208 When TIME is set, it should be an internal time specification, and the
9209 scheduling will use the corresponding date."
9210 (interactive "P")
9211 (if remove
9212 (progn
9213 (org-remove-timestamp-with-keyword org-scheduled-string)
9214 (message "Item is no longer scheduled."))
9215 (if (org-get-repeat)
9216 (error "Cannot reschedule task with repeater, please do that by hand")
9217 (org-add-planning-info 'scheduled time 'closed)
9218 (message "Scheduled to %s" org-last-inserted-timestamp))))
9220 (defun org-get-scheduled-time (pom &optional inherit)
9221 "Get the scheduled time as a time tuple, of a format suitable
9222 for calling org-schedule with, or if there is no scheduling,
9223 returns nil."
9224 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9225 (when time
9226 (apply 'encode-time (org-parse-time-string time)))))
9228 (defun org-get-deadline-time (pom &optional inherit)
9229 "Get the deadine as a time tuple, of a format suitable for
9230 calling org-deadlin with, or if there is no scheduling, returns
9231 nil."
9232 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9233 (when time
9234 (apply 'encode-time (org-parse-time-string time)))))
9236 (defun org-remove-timestamp-with-keyword (keyword)
9237 "Remove all time stamps with KEYWORD in the current entry."
9238 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9239 beg)
9240 (save-excursion
9241 (org-back-to-heading t)
9242 (setq beg (point))
9243 (org-end-of-subtree t t)
9244 (while (re-search-backward re beg t)
9245 (replace-match "")
9246 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9247 (equal (char-before) ?\ ))
9248 (backward-delete-char 1)
9249 (if (string-match "^[ \t]*$" (buffer-substring
9250 (point-at-bol) (point-at-eol)))
9251 (delete-region (point-at-bol)
9252 (min (point-max) (1+ (point-at-eol))))))))))
9254 (defun org-add-planning-info (what &optional time &rest remove)
9255 "Insert new timestamp with keyword in the line directly after the headline.
9256 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9257 If non is given, the user is prompted for a date.
9258 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9259 be removed."
9260 (interactive)
9261 (let (org-time-was-given org-end-time-was-given ts
9262 end default-time default-input)
9264 (catch 'exit
9265 (when (and (not time) (memq what '(scheduled deadline)))
9266 ;; Try to get a default date/time from existing timestamp
9267 (save-excursion
9268 (org-back-to-heading t)
9269 (setq end (save-excursion (outline-next-heading) (point)))
9270 (when (re-search-forward (if (eq what 'scheduled)
9271 org-scheduled-time-regexp
9272 org-deadline-time-regexp)
9273 end t)
9274 (setq ts (match-string 1)
9275 default-time
9276 (apply 'encode-time (org-parse-time-string ts))
9277 default-input (and ts (org-get-compact-tod ts))))))
9278 (when what
9279 ;; If necessary, get the time from the user
9280 (setq time (or time (org-read-date nil 'to-time nil nil
9281 default-time default-input))))
9283 (when (and org-insert-labeled-timestamps-at-point
9284 (member what '(scheduled deadline)))
9285 (insert
9286 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9287 (org-insert-time-stamp time org-time-was-given
9288 nil nil nil (list org-end-time-was-given))
9289 (setq what nil))
9290 (save-excursion
9291 (save-restriction
9292 (let (col list elt ts buffer-invisibility-spec)
9293 (org-back-to-heading t)
9294 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9295 (goto-char (match-end 1))
9296 (setq col (current-column))
9297 (goto-char (match-end 0))
9298 (if (eobp) (insert "\n") (forward-char 1))
9299 (when (and (not what)
9300 (not (looking-at
9301 (concat "[ \t]*"
9302 org-keyword-time-not-clock-regexp))))
9303 ;; Nothing to add, nothing to remove...... :-)
9304 (throw 'exit nil))
9305 (if (and (not (looking-at outline-regexp))
9306 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9307 "[^\r\n]*"))
9308 (not (equal (match-string 1) org-clock-string)))
9309 (narrow-to-region (match-beginning 0) (match-end 0))
9310 (insert-before-markers "\n")
9311 (backward-char 1)
9312 (narrow-to-region (point) (point))
9313 (and org-adapt-indentation (org-indent-to-column col)))
9314 ;; Check if we have to remove something.
9315 (setq list (cons what remove))
9316 (while list
9317 (setq elt (pop list))
9318 (goto-char (point-min))
9319 (when (or (and (eq elt 'scheduled)
9320 (re-search-forward org-scheduled-time-regexp nil t))
9321 (and (eq elt 'deadline)
9322 (re-search-forward org-deadline-time-regexp nil t))
9323 (and (eq elt 'closed)
9324 (re-search-forward org-closed-time-regexp nil t)))
9325 (replace-match "")
9326 (if (looking-at "--+<[^>]+>") (replace-match ""))
9327 (if (looking-at " +") (replace-match ""))))
9328 (goto-char (point-max))
9329 (when what
9330 (insert
9331 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9332 (cond ((eq what 'scheduled) org-scheduled-string)
9333 ((eq what 'deadline) org-deadline-string)
9334 ((eq what 'closed) org-closed-string))
9335 " ")
9336 (setq ts (org-insert-time-stamp
9337 time
9338 (or org-time-was-given
9339 (and (eq what 'closed) org-log-done-with-time))
9340 (eq what 'closed)
9341 nil nil (list org-end-time-was-given)))
9342 (end-of-line 1))
9343 (goto-char (point-min))
9344 (widen)
9345 (if (and (looking-at "[ \t]+\n")
9346 (equal (char-before) ?\n))
9347 (delete-region (1- (point)) (point-at-eol)))
9348 ts))))))
9350 (defvar org-log-note-marker (make-marker))
9351 (defvar org-log-note-purpose nil)
9352 (defvar org-log-note-state nil)
9353 (defvar org-log-note-previous-state nil)
9354 (defvar org-log-note-how nil)
9355 (defvar org-log-note-extra nil)
9356 (defvar org-log-note-window-configuration nil)
9357 (defvar org-log-note-return-to (make-marker))
9358 (defvar org-log-post-message nil
9359 "Message to be displayed after a log note has been stored.
9360 The auto-repeater uses this.")
9362 (defun org-add-note ()
9363 "Add a note to the current entry.
9364 This is done in the same way as adding a state change note."
9365 (interactive)
9366 (org-add-log-setup 'note nil nil 'findpos nil))
9368 (defvar org-property-end-re)
9369 (defun org-add-log-setup (&optional purpose state prev-state
9370 findpos how &optional extra)
9371 "Set up the post command hook to take a note.
9372 If this is about to TODO state change, the new state is expected in STATE.
9373 When FINDPOS is non-nil, find the correct position for the note in
9374 the current entry. If not, assume that it can be inserted at point.
9375 HOW is an indicator what kind of note should be created.
9376 EXTRA is additional text that will be inserted into the notes buffer."
9377 (let ((drawer (cond ((stringp org-log-into-drawer)
9378 org-log-into-drawer)
9379 (org-log-into-drawer "LOGBOOK")
9380 (t nil))))
9381 (save-restriction
9382 (save-excursion
9383 (when findpos
9384 (org-back-to-heading t)
9385 (narrow-to-region (point) (save-excursion
9386 (outline-next-heading) (point)))
9387 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9388 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9389 "[^\r\n]*\\)?"))
9390 (goto-char (match-end 0))
9391 (cond
9392 (drawer
9393 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9394 nil t)
9395 (progn
9396 (goto-char (match-end 0))
9397 (or org-log-states-order-reversed
9398 (and (re-search-forward org-property-end-re nil t)
9399 (goto-char (1- (match-beginning 0))))))
9400 (insert "\n:" drawer ":\n:END:")
9401 (beginning-of-line 0)
9402 (org-indent-line-function)
9403 (beginning-of-line 2)
9404 (org-indent-line-function)
9405 (end-of-line 0)))
9406 ((and org-log-state-notes-insert-after-drawers
9407 (save-excursion
9408 (forward-line) (looking-at org-drawer-regexp)))
9409 (forward-line)
9410 (while (looking-at org-drawer-regexp)
9411 (goto-char (match-end 0))
9412 (re-search-forward org-property-end-re (point-max) t)
9413 (forward-line))
9414 (forward-line -1)))
9415 (unless org-log-states-order-reversed
9416 (and (= (char-after) ?\n) (forward-char 1))
9417 (org-skip-over-state-notes)
9418 (skip-chars-backward " \t\n\r")))
9419 (move-marker org-log-note-marker (point))
9420 (setq org-log-note-purpose purpose
9421 org-log-note-state state
9422 org-log-note-previous-state prev-state
9423 org-log-note-how how
9424 org-log-note-extra extra)
9425 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9427 (defun org-skip-over-state-notes ()
9428 "Skip past the list of State notes in an entry."
9429 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9430 (while (looking-at "[ \t]*- State")
9431 (condition-case nil
9432 (org-next-item)
9433 (error (org-end-of-item)))))
9435 (defun org-add-log-note (&optional purpose)
9436 "Pop up a window for taking a note, and add this note later at point."
9437 (remove-hook 'post-command-hook 'org-add-log-note)
9438 (setq org-log-note-window-configuration (current-window-configuration))
9439 (delete-other-windows)
9440 (move-marker org-log-note-return-to (point))
9441 (switch-to-buffer (marker-buffer org-log-note-marker))
9442 (goto-char org-log-note-marker)
9443 (org-switch-to-buffer-other-window "*Org Note*")
9444 (erase-buffer)
9445 (if (memq org-log-note-how '(time state))
9446 (let (current-prefix-arg) (org-store-log-note))
9447 (let ((org-inhibit-startup t)) (org-mode))
9448 (insert (format "# Insert note for %s.
9449 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9450 (cond
9451 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9452 ((eq org-log-note-purpose 'done) "closed todo item")
9453 ((eq org-log-note-purpose 'state)
9454 (format "state change from \"%s\" to \"%s\""
9455 (or org-log-note-previous-state "")
9456 (or org-log-note-state "")))
9457 ((eq org-log-note-purpose 'note)
9458 "this entry")
9459 (t (error "This should not happen")))))
9460 (if org-log-note-extra (insert org-log-note-extra))
9461 (org-set-local 'org-finish-function 'org-store-log-note)))
9463 (defvar org-note-abort nil) ; dynamically scoped
9464 (defun org-store-log-note ()
9465 "Finish taking a log note, and insert it to where it belongs."
9466 (let ((txt (buffer-string))
9467 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9468 lines ind)
9469 (kill-buffer (current-buffer))
9470 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9471 (setq txt (replace-match "" t t txt)))
9472 (if (string-match "\\s-+\\'" txt)
9473 (setq txt (replace-match "" t t txt)))
9474 (setq lines (org-split-string txt "\n"))
9475 (when (and note (string-match "\\S-" note))
9476 (setq note
9477 (org-replace-escapes
9478 note
9479 (list (cons "%u" (user-login-name))
9480 (cons "%U" user-full-name)
9481 (cons "%t" (format-time-string
9482 (org-time-stamp-format 'long 'inactive)
9483 (current-time)))
9484 (cons "%s" (if org-log-note-state
9485 (concat "\"" org-log-note-state "\"")
9486 ""))
9487 (cons "%S" (if org-log-note-previous-state
9488 (concat "\"" org-log-note-previous-state "\"")
9489 "\"\"")))))
9490 (if lines (setq note (concat note " \\\\")))
9491 (push note lines))
9492 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9493 (when lines
9494 (save-excursion
9495 (set-buffer (marker-buffer org-log-note-marker))
9496 (save-excursion
9497 (goto-char org-log-note-marker)
9498 (move-marker org-log-note-marker nil)
9499 (end-of-line 1)
9500 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9501 (insert "- " (pop lines))
9502 (org-indent-line-function)
9503 (beginning-of-line 1)
9504 (looking-at "[ \t]*")
9505 (setq ind (concat (match-string 0) " "))
9506 (end-of-line 1)
9507 (while lines (insert "\n" ind (pop lines)))
9508 (message "Note stored")
9509 (org-back-to-heading t)
9510 (org-cycle-hide-drawers 'children)))))
9511 (set-window-configuration org-log-note-window-configuration)
9512 (with-current-buffer (marker-buffer org-log-note-return-to)
9513 (goto-char org-log-note-return-to))
9514 (move-marker org-log-note-return-to nil)
9515 (and org-log-post-message (message "%s" org-log-post-message)))
9517 (defun org-sparse-tree (&optional arg)
9518 "Create a sparse tree, prompt for the details.
9519 This command can create sparse trees. You first need to select the type
9520 of match used to create the tree:
9522 t Show entries with a specific TODO keyword.
9523 m Show entries selected by a tags/property match.
9524 p Enter a property name and its value (both with completion on existing
9525 names/values) and show entries with that property.
9526 r Show entries matching a regular expression
9527 d Show deadlines due within `org-deadline-warning-days'."
9528 (interactive "P")
9529 (let (ans kwd value)
9530 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date")
9531 (setq ans (read-char-exclusive))
9532 (cond
9533 ((equal ans ?d)
9534 (call-interactively 'org-check-deadlines))
9535 ((equal ans ?b)
9536 (call-interactively 'org-check-before-date))
9537 ((equal ans ?t)
9538 (org-show-todo-tree '(4)))
9539 ((member ans '(?T ?m))
9540 (call-interactively 'org-match-sparse-tree))
9541 ((member ans '(?p ?P))
9542 (setq kwd (org-ido-completing-read "Property: "
9543 (mapcar 'list (org-buffer-property-keys))))
9544 (setq value (org-ido-completing-read "Value: "
9545 (mapcar 'list (org-property-values kwd))))
9546 (unless (string-match "\\`{.*}\\'" value)
9547 (setq value (concat "\"" value "\"")))
9548 (org-match-sparse-tree arg (concat kwd "=" value)))
9549 ((member ans '(?r ?R ?/))
9550 (call-interactively 'org-occur))
9551 (t (error "No such sparse tree command \"%c\"" ans)))))
9553 (defvar org-occur-highlights nil
9554 "List of overlays used for occur matches.")
9555 (make-variable-buffer-local 'org-occur-highlights)
9556 (defvar org-occur-parameters nil
9557 "Parameters of the active org-occur calls.
9558 This is a list, each call to org-occur pushes as cons cell,
9559 containing the regular expression and the callback, onto the list.
9560 The list can contain several entries if `org-occur' has been called
9561 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9562 will only contain one set of parameters. When the highlights are
9563 removed (for example with `C-c C-c', or with the next edit (depending
9564 on `org-remove-highlights-with-change'), this variable is emptied
9565 as well.")
9566 (make-variable-buffer-local 'org-occur-parameters)
9568 (defun org-occur (regexp &optional keep-previous callback)
9569 "Make a compact tree which shows all matches of REGEXP.
9570 The tree will show the lines where the regexp matches, and all higher
9571 headlines above the match. It will also show the heading after the match,
9572 to make sure editing the matching entry is easy.
9573 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9574 call to `org-occur' will be kept, to allow stacking of calls to this
9575 command.
9576 If CALLBACK is non-nil, it is a function which is called to confirm
9577 that the match should indeed be shown."
9578 (interactive "sRegexp: \nP")
9579 (unless keep-previous
9580 (org-remove-occur-highlights nil nil t))
9581 (push (cons regexp callback) org-occur-parameters)
9582 (let ((cnt 0))
9583 (save-excursion
9584 (goto-char (point-min))
9585 (if (or (not keep-previous) ; do not want to keep
9586 (not org-occur-highlights)) ; no previous matches
9587 ;; hide everything
9588 (org-overview))
9589 (while (re-search-forward regexp nil t)
9590 (when (or (not callback)
9591 (save-match-data (funcall callback)))
9592 (setq cnt (1+ cnt))
9593 (when org-highlight-sparse-tree-matches
9594 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9595 (org-show-context 'occur-tree))))
9596 (when org-remove-highlights-with-change
9597 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9598 nil 'local))
9599 (unless org-sparse-tree-open-archived-trees
9600 (org-hide-archived-subtrees (point-min) (point-max)))
9601 (run-hooks 'org-occur-hook)
9602 (if (interactive-p)
9603 (message "%d match(es) for regexp %s" cnt regexp))
9604 cnt))
9606 (defun org-show-context (&optional key)
9607 "Make sure point and context and visible.
9608 How much context is shown depends upon the variables
9609 `org-show-hierarchy-above', `org-show-following-heading'. and
9610 `org-show-siblings'."
9611 (let ((heading-p (org-on-heading-p t))
9612 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9613 (following-p (org-get-alist-option org-show-following-heading key))
9614 (entry-p (org-get-alist-option org-show-entry-below key))
9615 (siblings-p (org-get-alist-option org-show-siblings key)))
9616 (catch 'exit
9617 ;; Show heading or entry text
9618 (if (and heading-p (not entry-p))
9619 (org-flag-heading nil) ; only show the heading
9620 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9621 (org-show-hidden-entry))) ; show entire entry
9622 (when following-p
9623 ;; Show next sibling, or heading below text
9624 (save-excursion
9625 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9626 (org-flag-heading nil))))
9627 (when siblings-p (org-show-siblings))
9628 (when hierarchy-p
9629 ;; show all higher headings, possibly with siblings
9630 (save-excursion
9631 (while (and (condition-case nil
9632 (progn (org-up-heading-all 1) t)
9633 (error nil))
9634 (not (bobp)))
9635 (org-flag-heading nil)
9636 (when siblings-p (org-show-siblings))))))))
9638 (defun org-reveal (&optional siblings)
9639 "Show current entry, hierarchy above it, and the following headline.
9640 This can be used to show a consistent set of context around locations
9641 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9642 not t for the search context.
9644 With optional argument SIBLINGS, on each level of the hierarchy all
9645 siblings are shown. This repairs the tree structure to what it would
9646 look like when opened with hierarchical calls to `org-cycle'."
9647 (interactive "P")
9648 (let ((org-show-hierarchy-above t)
9649 (org-show-following-heading t)
9650 (org-show-siblings (if siblings t org-show-siblings)))
9651 (org-show-context nil)))
9653 (defun org-highlight-new-match (beg end)
9654 "Highlight from BEG to END and mark the highlight is an occur headline."
9655 (let ((ov (org-make-overlay beg end)))
9656 (org-overlay-put ov 'face 'secondary-selection)
9657 (push ov org-occur-highlights)))
9659 (defun org-remove-occur-highlights (&optional beg end noremove)
9660 "Remove the occur highlights from the buffer.
9661 BEG and END are ignored. If NOREMOVE is nil, remove this function
9662 from the `before-change-functions' in the current buffer."
9663 (interactive)
9664 (unless org-inhibit-highlight-removal
9665 (mapc 'org-delete-overlay org-occur-highlights)
9666 (setq org-occur-highlights nil)
9667 (setq org-occur-parameters nil)
9668 (unless noremove
9669 (remove-hook 'before-change-functions
9670 'org-remove-occur-highlights 'local))))
9672 ;;;; Priorities
9674 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9675 "Regular expression matching the priority indicator.")
9677 (defvar org-remove-priority-next-time nil)
9679 (defun org-priority-up ()
9680 "Increase the priority of the current item."
9681 (interactive)
9682 (org-priority 'up))
9684 (defun org-priority-down ()
9685 "Decrease the priority of the current item."
9686 (interactive)
9687 (org-priority 'down))
9689 (defun org-priority (&optional action)
9690 "Change the priority of an item by ARG.
9691 ACTION can be `set', `up', `down', or a character."
9692 (interactive)
9693 (setq action (or action 'set))
9694 (let (current new news have remove)
9695 (save-excursion
9696 (org-back-to-heading t)
9697 (if (looking-at org-priority-regexp)
9698 (setq current (string-to-char (match-string 2))
9699 have t)
9700 (setq current org-default-priority))
9701 (cond
9702 ((or (eq action 'set)
9703 (if (featurep 'xemacs) (characterp action) (integerp action)))
9704 (if (not (eq action 'set))
9705 (setq new action)
9706 (message "Priority %c-%c, SPC to remove: "
9707 org-highest-priority org-lowest-priority)
9708 (setq new (read-char-exclusive)))
9709 (if (and (= (upcase org-highest-priority) org-highest-priority)
9710 (= (upcase org-lowest-priority) org-lowest-priority))
9711 (setq new (upcase new)))
9712 (cond ((equal new ?\ ) (setq remove t))
9713 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9714 (error "Priority must be between `%c' and `%c'"
9715 org-highest-priority org-lowest-priority))))
9716 ((eq action 'up)
9717 (if (and (not have) (eq last-command this-command))
9718 (setq new org-lowest-priority)
9719 (setq new (if (and org-priority-start-cycle-with-default (not have))
9720 org-default-priority (1- current)))))
9721 ((eq action 'down)
9722 (if (and (not have) (eq last-command this-command))
9723 (setq new org-highest-priority)
9724 (setq new (if (and org-priority-start-cycle-with-default (not have))
9725 org-default-priority (1+ current)))))
9726 (t (error "Invalid action")))
9727 (if (or (< (upcase new) org-highest-priority)
9728 (> (upcase new) org-lowest-priority))
9729 (setq remove t))
9730 (setq news (format "%c" new))
9731 (if have
9732 (if remove
9733 (replace-match "" t t nil 1)
9734 (replace-match news t t nil 2))
9735 (if remove
9736 (error "No priority cookie found in line")
9737 (looking-at org-todo-line-regexp)
9738 (if (match-end 2)
9739 (progn
9740 (goto-char (match-end 2))
9741 (insert " [#" news "]"))
9742 (goto-char (match-beginning 3))
9743 (insert "[#" news "] ")))))
9744 (org-preserve-lc (org-set-tags nil 'align))
9745 (if remove
9746 (message "Priority removed")
9747 (message "Priority of current item set to %s" news))))
9750 (defun org-get-priority (s)
9751 "Find priority cookie and return priority."
9752 (save-match-data
9753 (if (not (string-match org-priority-regexp s))
9754 (* 1000 (- org-lowest-priority org-default-priority))
9755 (* 1000 (- org-lowest-priority
9756 (string-to-char (match-string 2 s)))))))
9758 ;;;; Tags
9760 (defvar org-agenda-archives-mode)
9761 (defvar org-scanner-tags nil
9762 "The current tag list while the tags scanner is running.")
9763 (defvar org-trust-scanner-tags nil
9764 "Should `org-get-tags-at' use the tags fro the scanner.
9765 This is for internal dynamical scoping only.
9766 When this is non-nil, the function `org-get-tags-at' will return the value
9767 of `org-scanner-tags' instead of building the list by itself. This
9768 can lead to large speed-ups when the tags scanner is used in a file with
9769 many entries, and when the list of tags is retrieved, for example to
9770 obtain a list of properties. Building the tags list for each entry in such
9771 a file becomes an N^2 operation - but with this variable set, it scales
9772 as N.")
9774 (defun org-scan-tags (action matcher &optional todo-only)
9775 "Scan headline tags with inheritance and produce output ACTION.
9777 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9778 or `agenda' to produce an entry list for an agenda view. It can also be
9779 a Lisp form or a function that should be called at each matched headline, in
9780 this case the return value is a list of all return values from these calls.
9782 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9783 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9784 only lines with a TODO keyword are included in the output."
9785 (require 'org-agenda)
9786 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9787 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9788 (org-re
9789 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9790 (props (list 'face 'default
9791 'done-face 'org-done
9792 'undone-face 'default
9793 'mouse-face 'highlight
9794 'org-not-done-regexp org-not-done-regexp
9795 'org-todo-regexp org-todo-regexp
9796 'keymap org-agenda-keymap
9797 'help-echo
9798 (format "mouse-2 or RET jump to org file %s"
9799 (abbreviate-file-name
9800 (or (buffer-file-name (buffer-base-buffer))
9801 (buffer-name (buffer-base-buffer)))))))
9802 (case-fold-search nil)
9803 lspos tags tags-list
9804 (tags-alist (list (cons 0 org-file-tags)))
9805 (llast 0) rtn rtn1 level category i txt
9806 todo marker entry priority)
9807 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9808 (setq action (list 'lambda nil action)))
9809 (save-excursion
9810 (goto-char (point-min))
9811 (when (eq action 'sparse-tree)
9812 (org-overview)
9813 (org-remove-occur-highlights))
9814 (while (re-search-forward re nil t)
9815 (catch :skip
9816 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
9817 tags (if (match-end 4) (org-match-string-no-properties 4)))
9818 (goto-char (setq lspos (1+ (match-beginning 0))))
9819 (setq level (org-reduced-level (funcall outline-level))
9820 category (org-get-category))
9821 (setq i llast llast level)
9822 ;; remove tag lists from same and sublevels
9823 (while (>= i level)
9824 (when (setq entry (assoc i tags-alist))
9825 (setq tags-alist (delete entry tags-alist)))
9826 (setq i (1- i)))
9827 ;; add the next tags
9828 (when tags
9829 (setq tags (org-split-string tags ":")
9830 tags-alist
9831 (cons (cons level tags) tags-alist)))
9832 ;; compile tags for current headline
9833 (setq tags-list
9834 (if org-use-tag-inheritance
9835 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9836 tags)
9837 org-scanner-tags tags-list)
9838 (when org-use-tag-inheritance
9839 (setcdr (car tags-alist)
9840 (mapcar (lambda (x)
9841 (setq x (copy-sequence x))
9842 (org-add-prop-inherited x))
9843 (cdar tags-alist))))
9844 (when (and tags org-use-tag-inheritance
9845 (or (not (eq t org-use-tag-inheritance))
9846 org-tags-exclude-from-inheritance))
9847 ;; selective inheritance, remove uninherited ones
9848 (setcdr (car tags-alist)
9849 (org-remove-uniherited-tags (cdar tags-alist))))
9850 (when (and (or (not todo-only)
9851 (and (member todo org-not-done-keywords)
9852 (or (not org-agenda-tags-todo-honor-ignore-options)
9853 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9854 (let ((case-fold-search t)) (eval matcher))
9856 (not (member org-archive-tag tags-list))
9857 ;; we have an archive tag, should we use this anyway?
9858 (or (not org-agenda-skip-archived-trees)
9859 (and (eq action 'agenda) org-agenda-archives-mode))))
9860 (unless (eq action 'sparse-tree) (org-agenda-skip))
9862 ;; select this headline
9864 (cond
9865 ((eq action 'sparse-tree)
9866 (and org-highlight-sparse-tree-matches
9867 (org-get-heading) (match-end 0)
9868 (org-highlight-new-match
9869 (match-beginning 0) (match-beginning 1)))
9870 (org-show-context 'tags-tree))
9871 ((eq action 'agenda)
9872 (setq txt (org-format-agenda-item
9874 (concat
9875 (if org-tags-match-list-sublevels
9876 (make-string (1- level) ?.) "")
9877 (org-get-heading))
9878 category
9879 ;(org-get-tags-at)
9880 tags-list
9882 priority (org-get-priority txt))
9883 (goto-char lspos)
9884 (setq marker (org-agenda-new-marker))
9885 (org-add-props txt props
9886 'org-marker marker 'org-hd-marker marker 'org-category category
9887 'todo-state todo
9888 'priority priority 'type "tagsmatch")
9889 (push txt rtn))
9890 ((functionp action)
9891 (save-excursion
9892 (setq rtn1 (funcall action))
9893 (push rtn1 rtn))
9894 (goto-char (point-at-eol)))
9895 (t (error "Invalid action")))
9897 ;; if we are to skip sublevels, jump to end of subtree
9898 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9899 (when (and (eq action 'sparse-tree)
9900 (not org-sparse-tree-open-archived-trees))
9901 (org-hide-archived-subtrees (point-min) (point-max)))
9902 (nreverse rtn)))
9904 (defun org-remove-uniherited-tags (tags)
9905 "Remove all tags that are not inherited from the list TAGS."
9906 (cond
9907 ((eq org-use-tag-inheritance t)
9908 (if org-tags-exclude-from-inheritance
9909 (org-delete-all org-tags-exclude-from-inheritance tags)
9910 tags))
9911 ((not org-use-tag-inheritance) nil)
9912 ((stringp org-use-tag-inheritance)
9913 (delq nil (mapcar
9914 (lambda (x)
9915 (if (and (string-match org-use-tag-inheritance x)
9916 (not (member x org-tags-exclude-from-inheritance)))
9917 x nil))
9918 tags)))
9919 ((listp org-use-tag-inheritance)
9920 (delq nil (mapcar
9921 (lambda (x)
9922 (if (member x org-use-tag-inheritance) x nil))
9923 tags)))))
9925 (defvar todo-only) ;; dynamically scoped
9927 (defun org-match-sparse-tree (&optional todo-only match)
9928 "Create a sparse tree according to tags string MATCH.
9929 MATCH can contain positive and negative selection of tags, like
9930 \"+WORK+URGENT-WITHBOSS\".
9931 If optional argument TODO-ONLY is non-nil, only select lines that are
9932 also TODO lines."
9933 (interactive "P")
9934 (org-prepare-agenda-buffers (list (current-buffer)))
9935 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9937 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
9939 (defvar org-cached-props nil)
9940 (defun org-cached-entry-get (pom property)
9941 (if (or (eq t org-use-property-inheritance)
9942 (and (stringp org-use-property-inheritance)
9943 (string-match org-use-property-inheritance property))
9944 (and (listp org-use-property-inheritance)
9945 (member property org-use-property-inheritance)))
9946 ;; Caching is not possible, check it directly
9947 (org-entry-get pom property 'inherit)
9948 ;; Get all properties, so that we can do complicated checks easily
9949 (cdr (assoc property (or org-cached-props
9950 (setq org-cached-props
9951 (org-entry-properties pom)))))))
9953 (defun org-global-tags-completion-table (&optional files)
9954 "Return the list of all tags in all agenda buffer/files."
9955 (save-excursion
9956 (org-uniquify
9957 (delq nil
9958 (apply 'append
9959 (mapcar
9960 (lambda (file)
9961 (set-buffer (find-file-noselect file))
9962 (append (org-get-buffer-tags)
9963 (mapcar (lambda (x) (if (stringp (car-safe x))
9964 (list (car-safe x)) nil))
9965 org-tag-alist)))
9966 (if (and files (car files))
9967 files
9968 (org-agenda-files))))))))
9970 (defun org-make-tags-matcher (match)
9971 "Create the TAGS//TODO matcher form for the selection string MATCH."
9972 ;; todo-only is scoped dynamically into this function, and the function
9973 ;; may change it if the matcher asks for it.
9974 (unless match
9975 ;; Get a new match request, with completion
9976 (let ((org-last-tags-completion-table
9977 (org-global-tags-completion-table)))
9978 (setq match (org-completing-read-no-ido
9979 "Match: " 'org-tags-completion-function nil nil nil
9980 'org-tags-history))))
9982 ;; Parse the string and create a lisp form
9983 (let ((match0 match)
9984 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9985 minus tag mm
9986 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9987 orterms term orlist re-p str-p level-p level-op time-p
9988 prop-p pn pv po cat-p gv rest)
9989 (if (string-match "/+" match)
9990 ;; match contains also a todo-matching request
9991 (progn
9992 (setq tagsmatch (substring match 0 (match-beginning 0))
9993 todomatch (substring match (match-end 0)))
9994 (if (string-match "^!" todomatch)
9995 (setq todo-only t todomatch (substring todomatch 1)))
9996 (if (string-match "^\\s-*$" todomatch)
9997 (setq todomatch nil)))
9998 ;; only matching tags
9999 (setq tagsmatch match todomatch nil))
10001 ;; Make the tags matcher
10002 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10003 (setq tagsmatcher t)
10004 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10005 (while (setq term (pop orterms))
10006 (while (and (equal (substring term -1) "\\") orterms)
10007 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10008 (while (string-match re term)
10009 (setq rest (substring term (match-end 0))
10010 minus (and (match-end 1)
10011 (equal (match-string 1 term) "-"))
10012 tag (match-string 2 term)
10013 re-p (equal (string-to-char tag) ?{)
10014 level-p (match-end 4)
10015 prop-p (match-end 5)
10016 mm (cond
10017 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10018 (level-p
10019 (setq level-op (org-op-to-function (match-string 3 term)))
10020 `(,level-op level ,(string-to-number
10021 (match-string 4 term))))
10022 (prop-p
10023 (setq pn (match-string 5 term)
10024 po (match-string 6 term)
10025 pv (match-string 7 term)
10026 cat-p (equal pn "CATEGORY")
10027 re-p (equal (string-to-char pv) ?{)
10028 str-p (equal (string-to-char pv) ?\")
10029 time-p (save-match-data
10030 (string-match "^\"[[<].*[]>]\"$" pv))
10031 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10032 (if time-p (setq pv (org-matcher-time pv)))
10033 (setq po (org-op-to-function po (if time-p 'time str-p)))
10034 (cond
10035 ((equal pn "CATEGORY")
10036 (setq gv '(get-text-property (point) 'org-category)))
10037 ((equal pn "TODO")
10038 (setq gv 'todo))
10040 (setq gv `(org-cached-entry-get nil ,pn))))
10041 (if re-p
10042 (if (eq po 'org<>)
10043 `(not (string-match ,pv (or ,gv "")))
10044 `(string-match ,pv (or ,gv "")))
10045 (if str-p
10046 `(,po (or ,gv "") ,pv)
10047 `(,po (string-to-number (or ,gv ""))
10048 ,(string-to-number pv) ))))
10049 (t `(member ,tag tags-list)))
10050 mm (if minus (list 'not mm) mm)
10051 term rest)
10052 (push mm tagsmatcher))
10053 (push (if (> (length tagsmatcher) 1)
10054 (cons 'and tagsmatcher)
10055 (car tagsmatcher))
10056 orlist)
10057 (setq tagsmatcher nil))
10058 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10059 (setq tagsmatcher
10060 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10061 ;; Make the todo matcher
10062 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10063 (setq todomatcher t)
10064 (setq orterms (org-split-string todomatch "|") orlist nil)
10065 (while (setq term (pop orterms))
10066 (while (string-match re term)
10067 (setq minus (and (match-end 1)
10068 (equal (match-string 1 term) "-"))
10069 kwd (match-string 2 term)
10070 re-p (equal (string-to-char kwd) ?{)
10071 term (substring term (match-end 0))
10072 mm (if re-p
10073 `(string-match ,(substring kwd 1 -1) todo)
10074 (list 'equal 'todo kwd))
10075 mm (if minus (list 'not mm) mm))
10076 (push mm todomatcher))
10077 (push (if (> (length todomatcher) 1)
10078 (cons 'and todomatcher)
10079 (car todomatcher))
10080 orlist)
10081 (setq todomatcher nil))
10082 (setq todomatcher (if (> (length orlist) 1)
10083 (cons 'or orlist) (car orlist))))
10085 ;; Return the string and lisp forms of the matcher
10086 (setq matcher (if todomatcher
10087 (list 'and tagsmatcher todomatcher)
10088 tagsmatcher))
10089 (cons match0 matcher)))
10091 (defun org-op-to-function (op &optional stringp)
10092 "Turn an operator into the appropriate function."
10093 (setq op
10094 (cond
10095 ((equal op "<" ) '(< string< org-time<))
10096 ((equal op ">" ) '(> org-string> org-time>))
10097 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10098 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10099 ((member op '("=" "==")) '(= string= org-time=))
10100 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10101 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10103 (defun org<> (a b) (not (= a b)))
10104 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10105 (defun org-string>= (a b) (not (string< a b)))
10106 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10107 (defun org-string<> (a b) (not (string= a b)))
10108 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10109 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< 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) (org<> a b)))
10114 (defun org-2ft (s)
10115 "Convert S to a floating point time.
10116 If S is already a number, just return it. If it is a string, parse
10117 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10118 (cond
10119 ((numberp s) s)
10120 ((stringp s)
10121 (condition-case nil
10122 (float-time (apply 'encode-time (org-parse-time-string s)))
10123 (error 0.)))
10124 (t 0.)))
10126 (defun org-time-today ()
10127 "Time in seconds today at 0:00.
10128 Returns the float number of seconds since the beginning of the
10129 epoch to the beginning of today (00:00)."
10130 (float-time (apply 'encode-time
10131 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10133 (defun org-matcher-time (s)
10134 "Interpret a time comparison value."
10135 (save-match-data
10136 (cond
10137 ((string= s "<now>") (float-time))
10138 ((string= s "<today>") (org-time-today))
10139 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10140 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10141 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10142 (+ (org-time-today)
10143 (* (string-to-number (match-string 1 s))
10144 (cdr (assoc (match-string 2 s)
10145 '(("d" . 86400.0) ("w" . 604800.0)
10146 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10147 (t (org-2ft s)))))
10149 (defun org-match-any-p (re list)
10150 "Does re match any element of list?"
10151 (setq list (mapcar (lambda (x) (string-match re x)) list))
10152 (delq nil list))
10154 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10155 (defvar org-tags-overlay (org-make-overlay 1 1))
10156 (org-detach-overlay org-tags-overlay)
10158 (defun org-get-local-tags-at (&optional pos)
10159 "Get a list of tags defined in the current headline."
10160 (org-get-tags-at pos 'local))
10162 (defun org-get-local-tags ()
10163 "Get a list of tags defined in the current headline."
10164 (org-get-tags-at nil 'local))
10166 (defun org-get-tags-at (&optional pos local)
10167 "Get a list of all headline tags applicable at POS.
10168 POS defaults to point. If tags are inherited, the list contains
10169 the targets in the same sequence as the headlines appear, i.e.
10170 the tags of the current headline come last.
10171 When LOCAL is non-nil, only return tags from the current headline,
10172 ignore inherited ones."
10173 (interactive)
10174 (if (and org-trust-scanner-tags
10175 (or (not pos) (equal pos (point)))
10176 (not local))
10177 org-scanner-tags
10178 (let (tags ltags lastpos parent)
10179 (save-excursion
10180 (save-restriction
10181 (widen)
10182 (goto-char (or pos (point)))
10183 (save-match-data
10184 (catch 'done
10185 (condition-case nil
10186 (progn
10187 (org-back-to-heading t)
10188 (while (not (equal lastpos (point)))
10189 (setq lastpos (point))
10190 (when (looking-at
10191 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10192 (setq ltags (org-split-string
10193 (org-match-string-no-properties 1) ":"))
10194 (when parent
10195 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10196 (setq tags (append
10197 (if parent
10198 (org-remove-uniherited-tags ltags)
10199 ltags)
10200 tags)))
10201 (or org-use-tag-inheritance (throw 'done t))
10202 (if local (throw 'done t))
10203 (org-up-heading-all 1)
10204 (setq parent t)))
10205 (error nil)))))
10206 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10208 (defun org-add-prop-inherited (s)
10209 (add-text-properties 0 (length s) '(inherited t) s)
10212 (defun org-toggle-tag (tag &optional onoff)
10213 "Toggle the tag TAG for the current line.
10214 If ONOFF is `on' or `off', don't toggle but set to this state."
10215 (let (res current)
10216 (save-excursion
10217 (org-back-to-heading t)
10218 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10219 (point-at-eol) t)
10220 (progn
10221 (setq current (match-string 1))
10222 (replace-match ""))
10223 (setq current ""))
10224 (setq current (nreverse (org-split-string current ":")))
10225 (cond
10226 ((eq onoff 'on)
10227 (setq res t)
10228 (or (member tag current) (push tag current)))
10229 ((eq onoff 'off)
10230 (or (not (member tag current)) (setq current (delete tag current))))
10231 (t (if (member tag current)
10232 (setq current (delete tag current))
10233 (setq res t)
10234 (push tag current))))
10235 (end-of-line 1)
10236 (if current
10237 (progn
10238 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10239 (org-set-tags nil t))
10240 (delete-horizontal-space))
10241 (run-hooks 'org-after-tags-change-hook))
10242 res))
10244 (defun org-align-tags-here (to-col)
10245 ;; Assumes that this is a headline
10246 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10247 (beginning-of-line 1)
10248 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10249 (< pos (match-beginning 2)))
10250 (progn
10251 (setq tags-l (- (match-end 2) (match-beginning 2)))
10252 (goto-char (match-beginning 1))
10253 (insert " ")
10254 (delete-region (point) (1+ (match-beginning 2)))
10255 (setq ncol (max (1+ (current-column))
10256 (1+ col)
10257 (if (> to-col 0)
10258 to-col
10259 (- (abs to-col) tags-l))))
10260 (setq p (point))
10261 (insert (make-string (- ncol (current-column)) ?\ ))
10262 (setq ncol (current-column))
10263 (when indent-tabs-mode (tabify p (point-at-eol)))
10264 (org-move-to-column (min ncol col) t))
10265 (goto-char pos))))
10267 (defun org-set-tags-command (&optional arg just-align)
10268 "Call the set-tags command for the current entry."
10269 (interactive "P")
10270 (if (org-on-heading-p)
10271 (org-set-tags arg just-align)
10272 (save-excursion
10273 (org-back-to-heading t)
10274 (org-set-tags arg just-align))))
10276 (defun org-set-tags (&optional arg just-align)
10277 "Set the tags for the current headline.
10278 With prefix ARG, realign all tags in headings in the current buffer."
10279 (interactive "P")
10280 (let* ((re (concat "^" outline-regexp))
10281 (current (org-get-tags-string))
10282 (col (current-column))
10283 (org-setting-tags t)
10284 table current-tags inherited-tags ; computed below when needed
10285 tags p0 c0 c1 rpl)
10286 (if arg
10287 (save-excursion
10288 (goto-char (point-min))
10289 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10290 (while (re-search-forward re nil t)
10291 (org-set-tags nil t)
10292 (end-of-line 1)))
10293 (message "All tags realigned to column %d" org-tags-column))
10294 (if just-align
10295 (setq tags current)
10296 ;; Get a new set of tags from the user
10297 (save-excursion
10298 (setq table (append org-tag-persistent-alist
10299 (or org-tag-alist (org-get-buffer-tags)))
10300 org-last-tags-completion-table table
10301 current-tags (org-split-string current ":")
10302 inherited-tags (nreverse
10303 (nthcdr (length current-tags)
10304 (nreverse (org-get-tags-at))))
10305 tags
10306 (if (or (eq t org-use-fast-tag-selection)
10307 (and org-use-fast-tag-selection
10308 (delq nil (mapcar 'cdr table))))
10309 (org-fast-tag-selection
10310 current-tags inherited-tags table
10311 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10312 (let ((org-add-colon-after-tag-completion t))
10313 (org-trim
10314 (org-without-partial-completion
10315 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10316 nil nil current 'org-tags-history)))))))
10317 (while (string-match "[-+&]+" tags)
10318 ;; No boolean logic, just a list
10319 (setq tags (replace-match ":" t t tags))))
10321 (if (string-match "\\`[\t ]*\\'" tags)
10322 (setq tags "")
10323 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10324 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10326 ;; Insert new tags at the correct column
10327 (beginning-of-line 1)
10328 (cond
10329 ((and (equal current "") (equal tags "")))
10330 ((re-search-forward
10331 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10332 (point-at-eol) t)
10333 (if (equal tags "")
10334 (setq rpl "")
10335 (goto-char (match-beginning 0))
10336 (setq c0 (current-column) p0 (point)
10337 c1 (max (1+ c0) (if (> org-tags-column 0)
10338 org-tags-column
10339 (- (- org-tags-column) (length tags))))
10340 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10341 (replace-match rpl t t)
10342 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10343 tags)
10344 (t (error "Tags alignment failed")))
10345 (org-move-to-column col)
10346 (unless just-align
10347 (run-hooks 'org-after-tags-change-hook)))))
10349 (defun org-change-tag-in-region (beg end tag off)
10350 "Add or remove TAG for each entry in the region.
10351 This works in the agenda, and also in an org-mode buffer."
10352 (interactive
10353 (list (region-beginning) (region-end)
10354 (let ((org-last-tags-completion-table
10355 (if (org-mode-p)
10356 (org-get-buffer-tags)
10357 (org-global-tags-completion-table))))
10358 (org-ido-completing-read
10359 "Tag: " 'org-tags-completion-function nil nil nil
10360 'org-tags-history))
10361 (progn
10362 (message "[s]et or [r]emove? ")
10363 (equal (read-char-exclusive) ?r))))
10364 (if (fboundp 'deactivate-mark) (deactivate-mark))
10365 (let ((agendap (equal major-mode 'org-agenda-mode))
10366 l1 l2 m buf pos newhead (cnt 0))
10367 (goto-char end)
10368 (setq l2 (1- (org-current-line)))
10369 (goto-char beg)
10370 (setq l1 (org-current-line))
10371 (loop for l from l1 to l2 do
10372 (goto-line l)
10373 (setq m (get-text-property (point) 'org-hd-marker))
10374 (when (or (and (org-mode-p) (org-on-heading-p))
10375 (and agendap m))
10376 (setq buf (if agendap (marker-buffer m) (current-buffer))
10377 pos (if agendap m (point)))
10378 (with-current-buffer buf
10379 (save-excursion
10380 (save-restriction
10381 (goto-char pos)
10382 (setq cnt (1+ cnt))
10383 (org-toggle-tag tag (if off 'off 'on))
10384 (setq newhead (org-get-heading)))))
10385 (and agendap (org-agenda-change-all-lines newhead m))))
10386 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10388 (defun org-tags-completion-function (string predicate &optional flag)
10389 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10390 (confirm (lambda (x) (stringp (car x)))))
10391 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10392 (setq s1 (match-string 1 string)
10393 s2 (match-string 2 string))
10394 (setq s1 "" s2 string))
10395 (cond
10396 ((eq flag nil)
10397 ;; try completion
10398 (setq rtn (try-completion s2 ctable confirm))
10399 (if (stringp rtn)
10400 (setq rtn
10401 (concat s1 s2 (substring rtn (length s2))
10402 (if (and org-add-colon-after-tag-completion
10403 (assoc rtn ctable))
10404 ":" ""))))
10405 rtn)
10406 ((eq flag t)
10407 ;; all-completions
10408 (all-completions s2 ctable confirm)
10410 ((eq flag 'lambda)
10411 ;; exact match?
10412 (assoc s2 ctable)))
10415 (defun org-fast-tag-insert (kwd tags face &optional end)
10416 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10417 (insert (format "%-12s" (concat kwd ":"))
10418 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10419 (or end "")))
10421 (defun org-fast-tag-show-exit (flag)
10422 (save-excursion
10423 (goto-line 3)
10424 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10425 (replace-match ""))
10426 (when flag
10427 (end-of-line 1)
10428 (org-move-to-column (- (window-width) 19) t)
10429 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10431 (defun org-set-current-tags-overlay (current prefix)
10432 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10433 (if (featurep 'xemacs)
10434 (org-overlay-display org-tags-overlay (concat prefix s)
10435 'secondary-selection)
10436 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10437 (org-overlay-display org-tags-overlay (concat prefix s)))))
10439 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10440 "Fast tag selection with single keys.
10441 CURRENT is the current list of tags in the headline, INHERITED is the
10442 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10443 possibly with grouping information. TODO-TABLE is a similar table with
10444 TODO keywords, should these have keys assigned to them.
10445 If the keys are nil, a-z are automatically assigned.
10446 Returns the new tags string, or nil to not change the current settings."
10447 (let* ((fulltable (append table todo-table))
10448 (maxlen (apply 'max (mapcar
10449 (lambda (x)
10450 (if (stringp (car x)) (string-width (car x)) 0))
10451 fulltable)))
10452 (buf (current-buffer))
10453 (expert (eq org-fast-tag-selection-single-key 'expert))
10454 (buffer-tags nil)
10455 (fwidth (+ maxlen 3 1 3))
10456 (ncol (/ (- (window-width) 4) fwidth))
10457 (i-face 'org-done)
10458 (c-face 'org-todo)
10459 tg cnt e c char c1 c2 ntable tbl rtn
10460 ov-start ov-end ov-prefix
10461 (exit-after-next org-fast-tag-selection-single-key)
10462 (done-keywords org-done-keywords)
10463 groups ingroup)
10464 (save-excursion
10465 (beginning-of-line 1)
10466 (if (looking-at
10467 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10468 (setq ov-start (match-beginning 1)
10469 ov-end (match-end 1)
10470 ov-prefix "")
10471 (setq ov-start (1- (point-at-eol))
10472 ov-end (1+ ov-start))
10473 (skip-chars-forward "^\n\r")
10474 (setq ov-prefix
10475 (concat
10476 (buffer-substring (1- (point)) (point))
10477 (if (> (current-column) org-tags-column)
10479 (make-string (- org-tags-column (current-column)) ?\ ))))))
10480 (org-move-overlay org-tags-overlay ov-start ov-end)
10481 (save-window-excursion
10482 (if expert
10483 (set-buffer (get-buffer-create " *Org tags*"))
10484 (delete-other-windows)
10485 (split-window-vertically)
10486 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10487 (erase-buffer)
10488 (org-set-local 'org-done-keywords done-keywords)
10489 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10490 (org-fast-tag-insert "Current" current c-face "\n\n")
10491 (org-fast-tag-show-exit exit-after-next)
10492 (org-set-current-tags-overlay current ov-prefix)
10493 (setq tbl fulltable char ?a cnt 0)
10494 (while (setq e (pop tbl))
10495 (cond
10496 ((equal e '(:startgroup))
10497 (push '() groups) (setq ingroup t)
10498 (when (not (= cnt 0))
10499 (setq cnt 0)
10500 (insert "\n"))
10501 (insert "{ "))
10502 ((equal e '(:endgroup))
10503 (setq ingroup nil cnt 0)
10504 (insert "}\n"))
10505 ((equal e '(:newline))
10506 (when (not (= cnt 0))
10507 (setq cnt 0)
10508 (insert "\n")
10509 (setq e (car tbl))
10510 (while (equal (car tbl) '(:newline))
10511 (insert "\n")
10512 (setq tbl (cdr tbl)))))
10514 (setq tg (car e) c2 nil)
10515 (if (cdr e)
10516 (setq c (cdr e))
10517 ;; automatically assign a character.
10518 (setq c1 (string-to-char
10519 (downcase (substring
10520 tg (if (= (string-to-char tg) ?@) 1 0)))))
10521 (if (or (rassoc c1 ntable) (rassoc c1 table))
10522 (while (or (rassoc char ntable) (rassoc char table))
10523 (setq char (1+ char)))
10524 (setq c2 c1))
10525 (setq c (or c2 char)))
10526 (if ingroup (push tg (car groups)))
10527 (setq tg (org-add-props tg nil 'face
10528 (cond
10529 ((not (assoc tg table))
10530 (org-get-todo-face tg))
10531 ((member tg current) c-face)
10532 ((member tg inherited) i-face)
10533 (t nil))))
10534 (if (and (= cnt 0) (not ingroup)) (insert " "))
10535 (insert "[" c "] " tg (make-string
10536 (- fwidth 4 (length tg)) ?\ ))
10537 (push (cons tg c) ntable)
10538 (when (= (setq cnt (1+ cnt)) ncol)
10539 (insert "\n")
10540 (if ingroup (insert " "))
10541 (setq cnt 0)))))
10542 (setq ntable (nreverse ntable))
10543 (insert "\n")
10544 (goto-char (point-min))
10545 (if (not expert) (org-fit-window-to-buffer))
10546 (setq rtn
10547 (catch 'exit
10548 (while t
10549 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10550 (if groups " [!] no groups" " [!]groups")
10551 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10552 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10553 (cond
10554 ((= c ?\r) (throw 'exit t))
10555 ((= c ?!)
10556 (setq groups (not groups))
10557 (goto-char (point-min))
10558 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10559 ((= c ?\C-c)
10560 (if (not expert)
10561 (org-fast-tag-show-exit
10562 (setq exit-after-next (not exit-after-next)))
10563 (setq expert nil)
10564 (delete-other-windows)
10565 (split-window-vertically)
10566 (org-switch-to-buffer-other-window " *Org tags*")
10567 (org-fit-window-to-buffer)))
10568 ((or (= c ?\C-g)
10569 (and (= c ?q) (not (rassoc c ntable))))
10570 (org-detach-overlay org-tags-overlay)
10571 (setq quit-flag t))
10572 ((= c ?\ )
10573 (setq current nil)
10574 (if exit-after-next (setq exit-after-next 'now)))
10575 ((= c ?\t)
10576 (condition-case nil
10577 (setq tg (org-ido-completing-read
10578 "Tag: "
10579 (or buffer-tags
10580 (with-current-buffer buf
10581 (org-get-buffer-tags)))))
10582 (quit (setq tg "")))
10583 (when (string-match "\\S-" tg)
10584 (add-to-list 'buffer-tags (list tg))
10585 (if (member tg current)
10586 (setq current (delete tg current))
10587 (push tg current)))
10588 (if exit-after-next (setq exit-after-next 'now)))
10589 ((setq e (rassoc c todo-table) tg (car e))
10590 (with-current-buffer buf
10591 (save-excursion (org-todo tg)))
10592 (if exit-after-next (setq exit-after-next 'now)))
10593 ((setq e (rassoc c ntable) tg (car e))
10594 (if (member tg current)
10595 (setq current (delete tg current))
10596 (loop for g in groups do
10597 (if (member tg g)
10598 (mapc (lambda (x)
10599 (setq current (delete x current)))
10600 g)))
10601 (push tg current))
10602 (if exit-after-next (setq exit-after-next 'now))))
10604 ;; Create a sorted list
10605 (setq current
10606 (sort current
10607 (lambda (a b)
10608 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10609 (if (eq exit-after-next 'now) (throw 'exit t))
10610 (goto-char (point-min))
10611 (beginning-of-line 2)
10612 (delete-region (point) (point-at-eol))
10613 (org-fast-tag-insert "Current" current c-face)
10614 (org-set-current-tags-overlay current ov-prefix)
10615 (while (re-search-forward
10616 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10617 (setq tg (match-string 1))
10618 (add-text-properties
10619 (match-beginning 1) (match-end 1)
10620 (list 'face
10621 (cond
10622 ((member tg current) c-face)
10623 ((member tg inherited) i-face)
10624 (t (get-text-property (match-beginning 1) 'face))))))
10625 (goto-char (point-min)))))
10626 (org-detach-overlay org-tags-overlay)
10627 (if rtn
10628 (mapconcat 'identity current ":")
10629 nil))))
10631 (defun org-get-tags-string ()
10632 "Get the TAGS string in the current headline."
10633 (unless (org-on-heading-p t)
10634 (error "Not on a heading"))
10635 (save-excursion
10636 (beginning-of-line 1)
10637 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10638 (org-match-string-no-properties 1)
10639 "")))
10641 (defun org-get-tags ()
10642 "Get the list of tags specified in the current headline."
10643 (org-split-string (org-get-tags-string) ":"))
10645 (defun org-get-buffer-tags ()
10646 "Get a table of all tags used in the buffer, for completion."
10647 (let (tags)
10648 (save-excursion
10649 (goto-char (point-min))
10650 (while (re-search-forward
10651 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10652 (when (equal (char-after (point-at-bol 0)) ?*)
10653 (mapc (lambda (x) (add-to-list 'tags x))
10654 (org-split-string (org-match-string-no-properties 1) ":")))))
10655 (mapcar 'list tags)))
10657 ;;;; The mapping API
10659 ;;;###autoload
10660 (defun org-map-entries (func &optional match scope &rest skip)
10661 "Call FUNC at each headline selected by MATCH in SCOPE.
10663 FUNC is a function or a lisp form. The function will be called without
10664 arguments, with the cursor positioned at the beginning of the headline.
10665 The return values of all calls to the function will be collected and
10666 returned as a list.
10668 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10669 Only headlines that are matched by this query will be considered during
10670 the iteration. When MATCH is nil or t, all headlines will be
10671 visited by the iteration.
10673 SCOPE determines the scope of this command. It can be any of:
10675 nil The current buffer, respecting the restriction if any
10676 tree The subtree started with the entry at point
10677 file The current buffer, without restriction
10678 file-with-archives
10679 The current buffer, and any archives associated with it
10680 agenda All agenda files
10681 agenda-with-archives
10682 All agenda files with any archive files associated with them
10683 \(file1 file2 ...)
10684 If this is a list, all files in the list will be scanned
10686 The remaining args are treated as settings for the skipping facilities of
10687 the scanner. The following items can be given here:
10689 archive skip trees with the archive tag.
10690 comment skip trees with the COMMENT keyword
10691 function or Emacs Lisp form:
10692 will be used as value for `org-agenda-skip-function', so whenever
10693 the the function returns t, FUNC will not be called for that
10694 entry and search will continue from the point where the
10695 function leaves it.
10697 If your function needs to retrieve the tags including inherited tags
10698 at the *current* entry, you can use the value of the variable
10699 `org-scanner-tags' which will be much faster than getting the value
10700 with `org-get-tags-at'. If your function gets properties with
10701 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
10702 to t around the call to `org-entry-properties' to get the same speedup.
10703 Note that if your function moves around to retrieve tags and properties at
10704 a *different* entry, you cannot use these techniques."
10705 (let* ((org-agenda-archives-mode nil) ; just to make sure
10706 (org-agenda-skip-archived-trees (memq 'archive skip))
10707 (org-agenda-skip-comment-trees (memq 'comment skip))
10708 (org-agenda-skip-function
10709 (car (org-delete-all '(comment archive) skip)))
10710 (org-tags-match-list-sublevels t)
10711 matcher file res
10712 org-todo-keywords-for-agenda
10713 org-done-keywords-for-agenda
10714 org-todo-keyword-alist-for-agenda
10715 org-tag-alist-for-agenda)
10717 (cond
10718 ((eq match t) (setq matcher t))
10719 ((eq match nil) (setq matcher t))
10720 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10722 (save-excursion
10723 (save-restriction
10724 (when (eq scope 'tree)
10725 (org-back-to-heading t)
10726 (org-narrow-to-subtree)
10727 (setq scope nil))
10729 (if (not scope)
10730 (progn
10731 (org-prepare-agenda-buffers
10732 (list (buffer-file-name (current-buffer))))
10733 (setq res (org-scan-tags func matcher)))
10734 ;; Get the right scope
10735 (cond
10736 ((and scope (listp scope) (symbolp (car scope)))
10737 (setq scope (eval scope)))
10738 ((eq scope 'agenda)
10739 (setq scope (org-agenda-files t)))
10740 ((eq scope 'agenda-with-archives)
10741 (setq scope (org-agenda-files t))
10742 (setq scope (org-add-archive-files scope)))
10743 ((eq scope 'file)
10744 (setq scope (list (buffer-file-name))))
10745 ((eq scope 'file-with-archives)
10746 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10747 (org-prepare-agenda-buffers scope)
10748 (while (setq file (pop scope))
10749 (with-current-buffer (org-find-base-buffer-visiting file)
10750 (save-excursion
10751 (save-restriction
10752 (widen)
10753 (goto-char (point-min))
10754 (setq res (append res (org-scan-tags func matcher))))))))))
10755 res))
10757 ;;;; Properties
10759 ;;; Setting and retrieving properties
10761 (defconst org-special-properties
10762 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10763 "TIMESTAMP" "TIMESTAMP_IA")
10764 "The special properties valid in Org-mode.
10766 These are properties that are not defined in the property drawer,
10767 but in some other way.")
10769 (defconst org-default-properties
10770 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10771 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10772 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10773 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10774 "Some properties that are used by Org-mode for various purposes.
10775 Being in this list makes sure that they are offered for completion.")
10777 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10778 "Regular expression matching the first line of a property drawer.")
10780 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10781 "Regular expression matching the first line of a property drawer.")
10783 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10784 "Regular expression matching the first line of a property drawer.")
10786 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10787 "Regular expression matching the first line of a property drawer.")
10789 (defconst org-property-drawer-re
10790 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10791 org-property-end-re "\\)\n?")
10792 "Matches an entire property drawer.")
10794 (defconst org-clock-drawer-re
10795 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10796 org-property-end-re "\\)\n?")
10797 "Matches an entire clock drawer.")
10799 (defun org-property-action ()
10800 "Do an action on properties."
10801 (interactive)
10802 (let (c)
10803 (org-at-property-p)
10804 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10805 (setq c (read-char-exclusive))
10806 (cond
10807 ((equal c ?s)
10808 (call-interactively 'org-set-property))
10809 ((equal c ?d)
10810 (call-interactively 'org-delete-property))
10811 ((equal c ?D)
10812 (call-interactively 'org-delete-property-globally))
10813 ((equal c ?c)
10814 (call-interactively 'org-compute-property-at-point))
10815 (t (error "No such property action %c" c)))))
10817 (defun org-at-property-p ()
10818 "Is the cursor in a property line?"
10819 ;; FIXME: Does not check if we are actually in the drawer.
10820 ;; FIXME: also returns true on any drawers.....
10821 ;; This is used by C-c C-c for property action.
10822 (save-excursion
10823 (beginning-of-line 1)
10824 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10826 (defun org-get-property-block (&optional beg end force)
10827 "Return the (beg . end) range of the body of the property drawer.
10828 BEG and END can be beginning and end of subtree, if not given
10829 they will be found.
10830 If the drawer does not exist and FORCE is non-nil, create the drawer."
10831 (catch 'exit
10832 (save-excursion
10833 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10834 (end (or end (progn (outline-next-heading) (point)))))
10835 (goto-char beg)
10836 (if (re-search-forward org-property-start-re end t)
10837 (setq beg (1+ (match-end 0)))
10838 (if force
10839 (save-excursion
10840 (org-insert-property-drawer)
10841 (setq end (progn (outline-next-heading) (point))))
10842 (throw 'exit nil))
10843 (goto-char beg)
10844 (if (re-search-forward org-property-start-re end t)
10845 (setq beg (1+ (match-end 0)))))
10846 (if (re-search-forward org-property-end-re end t)
10847 (setq end (match-beginning 0))
10848 (or force (throw 'exit nil))
10849 (goto-char beg)
10850 (setq end beg)
10851 (org-indent-line-function)
10852 (insert ":END:\n"))
10853 (cons beg end)))))
10855 (defun org-entry-properties (&optional pom which)
10856 "Get all properties of the entry at point-or-marker POM.
10857 This includes the TODO keyword, the tags, time strings for deadline,
10858 scheduled, and clocking, and any additional properties defined in the
10859 entry. The return value is an alist, keys may occur multiple times
10860 if the property key was used several times.
10861 POM may also be nil, in which case the current entry is used.
10862 If WHICH is nil or `all', get all properties. If WHICH is
10863 `special' or `standard', only get that subclass."
10864 (setq which (or which 'all))
10865 (org-with-point-at pom
10866 (let ((clockstr (substring org-clock-string 0 -1))
10867 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10868 beg end range props sum-props key value string clocksum)
10869 (save-excursion
10870 (when (condition-case nil
10871 (and (org-mode-p) (org-back-to-heading t))
10872 (error nil))
10873 (setq beg (point))
10874 (setq sum-props (get-text-property (point) 'org-summaries))
10875 (setq clocksum (get-text-property (point) :org-clock-minutes))
10876 (outline-next-heading)
10877 (setq end (point))
10878 (when (memq which '(all special))
10879 ;; Get the special properties, like TODO and tags
10880 (goto-char beg)
10881 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10882 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10883 (when (looking-at org-priority-regexp)
10884 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10885 (when (and (setq value (org-get-tags-string))
10886 (string-match "\\S-" value))
10887 (push (cons "TAGS" value) props))
10888 (when (setq value (org-get-tags-at))
10889 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10890 props))
10891 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10892 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10893 string (if (equal key clockstr)
10894 (org-no-properties
10895 (org-trim
10896 (buffer-substring
10897 (match-beginning 3) (goto-char (point-at-eol)))))
10898 (substring (org-match-string-no-properties 3) 1 -1)))
10899 (unless key
10900 (if (= (char-after (match-beginning 3)) ?\[)
10901 (setq key "TIMESTAMP_IA")
10902 (setq key "TIMESTAMP")))
10903 (when (or (equal key clockstr) (not (assoc key props)))
10904 (push (cons key string) props)))
10908 (when (memq which '(all standard))
10909 ;; Get the standard properties, like :PROP: ...
10910 (setq range (org-get-property-block beg end))
10911 (when range
10912 (goto-char (car range))
10913 (while (re-search-forward
10914 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10915 (cdr range) t)
10916 (setq key (org-match-string-no-properties 1)
10917 value (org-trim (or (org-match-string-no-properties 2) "")))
10918 (unless (member key excluded)
10919 (push (cons key (or value "")) props)))))
10920 (if clocksum
10921 (push (cons "CLOCKSUM"
10922 (org-columns-number-to-string (/ (float clocksum) 60.)
10923 'add_times))
10924 props))
10925 (unless (assoc "CATEGORY" props)
10926 (setq value (or (org-get-category)
10927 (progn (org-refresh-category-properties)
10928 (org-get-category))))
10929 (push (cons "CATEGORY" value) props))
10930 (append sum-props (nreverse props)))))))
10932 (defun org-entry-get (pom property &optional inherit)
10933 "Get value of PROPERTY for entry at point-or-marker POM.
10934 If INHERIT is non-nil and the entry does not have the property,
10935 then also check higher levels of the hierarchy.
10936 If INHERIT is the symbol `selective', use inheritance only if the setting
10937 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10938 If the property is present but empty, the return value is the empty string.
10939 If the property is not present at all, nil is returned."
10940 (org-with-point-at pom
10941 (if (and inherit (if (eq inherit 'selective)
10942 (org-property-inherit-p property)
10944 (org-entry-get-with-inheritance property)
10945 (if (member property org-special-properties)
10946 ;; We need a special property. Use brute force, get all properties.
10947 (cdr (assoc property (org-entry-properties nil 'special)))
10948 (let ((range (org-get-property-block)))
10949 (if (and range
10950 (goto-char (car range))
10951 (re-search-forward
10952 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10953 (cdr range) t))
10954 ;; Found the property, return it.
10955 (if (match-end 1)
10956 (org-match-string-no-properties 1)
10957 "")))))))
10959 (defun org-property-or-variable-value (var &optional inherit)
10960 "Check if there is a property fixing the value of VAR.
10961 If yes, return this value. If not, return the current value of the variable."
10962 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10963 (if (and prop (stringp prop) (string-match "\\S-" prop))
10964 (read prop)
10965 (symbol-value var))))
10967 (defun org-entry-delete (pom property)
10968 "Delete the property PROPERTY from entry at point-or-marker POM."
10969 (org-with-point-at pom
10970 (if (member property org-special-properties)
10971 nil ; cannot delete these properties.
10972 (let ((range (org-get-property-block)))
10973 (if (and range
10974 (goto-char (car range))
10975 (re-search-forward
10976 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10977 (cdr range) t))
10978 (progn
10979 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10981 nil)))))
10983 ;; Multi-values properties are properties that contain multiple values
10984 ;; These values are assumed to be single words, separated by whitespace.
10985 (defun org-entry-add-to-multivalued-property (pom property value)
10986 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10987 (let* ((old (org-entry-get pom property))
10988 (values (and old (org-split-string old "[ \t]"))))
10989 (setq value (org-entry-protect-space value))
10990 (unless (member value values)
10991 (setq values (cons value values))
10992 (org-entry-put pom property
10993 (mapconcat 'identity values " ")))))
10995 (defun org-entry-remove-from-multivalued-property (pom property value)
10996 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10997 (let* ((old (org-entry-get pom property))
10998 (values (and old (org-split-string old "[ \t]"))))
10999 (setq value (org-entry-protect-space value))
11000 (when (member value values)
11001 (setq values (delete value values))
11002 (org-entry-put pom property
11003 (mapconcat 'identity values " ")))))
11005 (defun org-entry-member-in-multivalued-property (pom property value)
11006 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11007 (let* ((old (org-entry-get pom property))
11008 (values (and old (org-split-string old "[ \t]"))))
11009 (setq value (org-entry-protect-space value))
11010 (member value values)))
11012 (defun org-entry-get-multivalued-property (pom property)
11013 "Return a list of values in a multivalued property."
11014 (let* ((value (org-entry-get pom property))
11015 (values (and value (org-split-string value "[ \t]"))))
11016 (mapcar 'org-entry-restore-space values)))
11018 (defun org-entry-put-multivalued-property (pom property &rest values)
11019 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11020 VALUES should be a list of strings. Spaces will be protected."
11021 (org-entry-put pom property
11022 (mapconcat 'org-entry-protect-space values " "))
11023 (let* ((value (org-entry-get pom property))
11024 (values (and value (org-split-string value "[ \t]"))))
11025 (mapcar 'org-entry-restore-space values)))
11027 (defun org-entry-protect-space (s)
11028 "Protect spaces and newline in string S."
11029 (while (string-match " " s)
11030 (setq s (replace-match "%20" t t s)))
11031 (while (string-match "\n" s)
11032 (setq s (replace-match "%0A" t t s)))
11035 (defun org-entry-restore-space (s)
11036 "Restore spaces and newline in string S."
11037 (while (string-match "%20" s)
11038 (setq s (replace-match " " t t s)))
11039 (while (string-match "%0A" s)
11040 (setq s (replace-match "\n" t t s)))
11043 (defvar org-entry-property-inherited-from (make-marker)
11044 "Marker pointing to the entry from where a property was inherited.
11045 Each call to `org-entry-get-with-inheritance' will set this marker to the
11046 location of the entry where the inheritance search matched. If there was
11047 no match, the marker will point nowhere.
11048 Note that also `org-entry-get' calls this function, if the INHERIT flag
11049 is set.")
11051 (defun org-entry-get-with-inheritance (property)
11052 "Get entry property, and search higher levels if not present."
11053 (move-marker org-entry-property-inherited-from nil)
11054 (let (tmp)
11055 (save-excursion
11056 (save-restriction
11057 (widen)
11058 (catch 'ex
11059 (while t
11060 (when (setq tmp (org-entry-get nil property))
11061 (org-back-to-heading t)
11062 (move-marker org-entry-property-inherited-from (point))
11063 (throw 'ex tmp))
11064 (or (org-up-heading-safe) (throw 'ex nil)))))
11065 (or tmp
11066 (cdr (assoc property org-file-properties))
11067 (cdr (assoc property org-global-properties))
11068 (cdr (assoc property org-global-properties-fixed))))))
11070 (defun org-entry-put (pom property value)
11071 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11072 (org-with-point-at pom
11073 (org-back-to-heading t)
11074 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11075 range)
11076 (cond
11077 ((equal property "TODO")
11078 (when (and (stringp value) (string-match "\\S-" value)
11079 (not (member value org-todo-keywords-1)))
11080 (error "\"%s\" is not a valid TODO state" value))
11081 (if (or (not value)
11082 (not (string-match "\\S-" value)))
11083 (setq value 'none))
11084 (org-todo value)
11085 (org-set-tags nil 'align))
11086 ((equal property "PRIORITY")
11087 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11088 (string-to-char value) ?\ ))
11089 (org-set-tags nil 'align))
11090 ((equal property "SCHEDULED")
11091 (if (re-search-forward org-scheduled-time-regexp end t)
11092 (cond
11093 ((eq value 'earlier) (org-timestamp-change -1 'day))
11094 ((eq value 'later) (org-timestamp-change 1 'day))
11095 (t (call-interactively 'org-schedule)))
11096 (call-interactively 'org-schedule)))
11097 ((equal property "DEADLINE")
11098 (if (re-search-forward org-deadline-time-regexp end t)
11099 (cond
11100 ((eq value 'earlier) (org-timestamp-change -1 'day))
11101 ((eq value 'later) (org-timestamp-change 1 'day))
11102 (t (call-interactively 'org-deadline)))
11103 (call-interactively 'org-deadline)))
11104 ((member property org-special-properties)
11105 (error "The %s property can not yet be set with `org-entry-put'"
11106 property))
11107 (t ; a non-special property
11108 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11109 (setq range (org-get-property-block beg end 'force))
11110 (goto-char (car range))
11111 (if (re-search-forward
11112 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11113 (progn
11114 (delete-region (match-beginning 1) (match-end 1))
11115 (goto-char (match-beginning 1)))
11116 (goto-char (cdr range))
11117 (insert "\n")
11118 (backward-char 1)
11119 (org-indent-line-function)
11120 (insert ":" property ":"))
11121 (and value (insert " " value))
11122 (org-indent-line-function)))))))
11124 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11125 "Get all property keys in the current buffer.
11126 With INCLUDE-SPECIALS, also list the special properties that reflect things
11127 like tags and TODO state.
11128 With INCLUDE-DEFAULTS, also include properties that has special meaning
11129 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11130 With INCLUDE-COLUMNS, also include property names given in COLUMN
11131 formats in the current buffer."
11132 (let (rtn range cfmt s p)
11133 (save-excursion
11134 (save-restriction
11135 (widen)
11136 (goto-char (point-min))
11137 (while (re-search-forward org-property-start-re nil t)
11138 (setq range (org-get-property-block))
11139 (goto-char (car range))
11140 (while (re-search-forward
11141 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11142 (cdr range) t)
11143 (add-to-list 'rtn (org-match-string-no-properties 1)))
11144 (outline-next-heading))))
11146 (when include-specials
11147 (setq rtn (append org-special-properties rtn)))
11149 (when include-defaults
11150 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11152 (when include-columns
11153 (save-excursion
11154 (save-restriction
11155 (widen)
11156 (goto-char (point-min))
11157 (while (re-search-forward
11158 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11159 nil t)
11160 (setq cfmt (match-string 2) s 0)
11161 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11162 cfmt s)
11163 (setq s (match-end 0)
11164 p (match-string 1 cfmt))
11165 (unless (or (equal p "ITEM")
11166 (member p org-special-properties))
11167 (add-to-list 'rtn (match-string 1 cfmt))))))))
11169 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11171 (defun org-property-values (key)
11172 "Return a list of all values of property KEY."
11173 (save-excursion
11174 (save-restriction
11175 (widen)
11176 (goto-char (point-min))
11177 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11178 values)
11179 (while (re-search-forward re nil t)
11180 (add-to-list 'values (org-trim (match-string 1))))
11181 (delete "" values)))))
11183 (defun org-insert-property-drawer ()
11184 "Insert a property drawer into the current entry."
11185 (interactive)
11186 (org-back-to-heading t)
11187 (looking-at outline-regexp)
11188 (let ((indent (- (match-end 0)(match-beginning 0)))
11189 (beg (point))
11190 (re (concat "^[ \t]*" org-keyword-time-regexp))
11191 end hiddenp)
11192 (outline-next-heading)
11193 (setq end (point))
11194 (goto-char beg)
11195 (while (re-search-forward re end t))
11196 (setq hiddenp (org-invisible-p))
11197 (end-of-line 1)
11198 (and (equal (char-after) ?\n) (forward-char 1))
11199 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11200 (if (member (match-string 1) '("CLOCK:" ":END:"))
11201 ;; just skip this line
11202 (beginning-of-line 2)
11203 ;; Drawer start, find the end
11204 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11205 (beginning-of-line 1)))
11206 (org-skip-over-state-notes)
11207 (skip-chars-backward " \t\n\r")
11208 (if (eq (char-before) ?*) (forward-char 1))
11209 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11210 (beginning-of-line 0)
11211 (org-indent-to-column indent)
11212 (beginning-of-line 2)
11213 (org-indent-to-column indent)
11214 (beginning-of-line 0)
11215 (if hiddenp
11216 (save-excursion
11217 (org-back-to-heading t)
11218 (hide-entry))
11219 (org-flag-drawer t))))
11221 (defun org-set-property (property value)
11222 "In the current entry, set PROPERTY to VALUE.
11223 When called interactively, this will prompt for a property name, offering
11224 completion on existing and default properties. And then it will prompt
11225 for a value, offering completion either on allowed values (via an inherited
11226 xxx_ALL property) or on existing values in other instances of this property
11227 in the current file."
11228 (interactive
11229 (let* ((completion-ignore-case t)
11230 (keys (org-buffer-property-keys nil t t))
11231 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11232 (prop (if (member prop0 keys)
11233 prop0
11234 (or (cdr (assoc (downcase prop0)
11235 (mapcar (lambda (x) (cons (downcase x) x))
11236 keys)))
11237 prop0)))
11238 (cur (org-entry-get nil prop))
11239 (allowed (org-property-get-allowed-values nil prop 'table))
11240 (existing (mapcar 'list (org-property-values prop)))
11241 (val (if allowed
11242 (org-completing-read "Value: " allowed nil 'req-match)
11243 (let (org-completion-use-ido)
11244 (org-completing-read
11245 (concat "Value" (if (and cur (string-match "\\S-" cur))
11246 (concat "[" cur "]") "")
11247 ": ")
11248 existing nil nil "" nil cur)))))
11249 (list prop (if (equal val "") cur val))))
11250 (unless (equal (org-entry-get nil property) value)
11251 (org-entry-put nil property value)))
11253 (defun org-delete-property (property)
11254 "In the current entry, delete PROPERTY."
11255 (interactive
11256 (let* ((completion-ignore-case t)
11257 (prop (org-ido-completing-read
11258 "Property: " (org-entry-properties nil 'standard))))
11259 (list prop)))
11260 (message "Property %s %s" property
11261 (if (org-entry-delete nil property)
11262 "deleted"
11263 "was not present in the entry")))
11265 (defun org-delete-property-globally (property)
11266 "Remove PROPERTY globally, from all entries."
11267 (interactive
11268 (let* ((completion-ignore-case t)
11269 (prop (org-ido-completing-read
11270 "Globally remove property: "
11271 (mapcar 'list (org-buffer-property-keys)))))
11272 (list prop)))
11273 (save-excursion
11274 (save-restriction
11275 (widen)
11276 (goto-char (point-min))
11277 (let ((cnt 0))
11278 (while (re-search-forward
11279 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11280 nil t)
11281 (setq cnt (1+ cnt))
11282 (replace-match ""))
11283 (message "Property \"%s\" removed from %d entries" property cnt)))))
11285 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11287 (defun org-compute-property-at-point ()
11288 "Compute the property at point.
11289 This looks for an enclosing column format, extracts the operator and
11290 then applies it to the property in the column format's scope."
11291 (interactive)
11292 (unless (org-at-property-p)
11293 (error "Not at a property"))
11294 (let ((prop (org-match-string-no-properties 2)))
11295 (org-columns-get-format-and-top-level)
11296 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11297 (error "No operator defined for property %s" prop))
11298 (org-columns-compute prop)))
11300 (defun org-property-get-allowed-values (pom property &optional table)
11301 "Get allowed values for the property PROPERTY.
11302 When TABLE is non-nil, return an alist that can directly be used for
11303 completion."
11304 (let (vals)
11305 (cond
11306 ((equal property "TODO")
11307 (setq vals (org-with-point-at pom
11308 (append org-todo-keywords-1 '("")))))
11309 ((equal property "PRIORITY")
11310 (let ((n org-lowest-priority))
11311 (while (>= n org-highest-priority)
11312 (push (char-to-string n) vals)
11313 (setq n (1- n)))))
11314 ((member property org-special-properties))
11316 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11318 (when (and vals (string-match "\\S-" vals))
11319 (setq vals (car (read-from-string (concat "(" vals ")"))))
11320 (setq vals (mapcar (lambda (x)
11321 (cond ((stringp x) x)
11322 ((numberp x) (number-to-string x))
11323 ((symbolp x) (symbol-name x))
11324 (t "???")))
11325 vals)))))
11326 (if table (mapcar 'list vals) vals)))
11328 (defun org-property-previous-allowed-value (&optional previous)
11329 "Switch to the next allowed value for this property."
11330 (interactive)
11331 (org-property-next-allowed-value t))
11333 (defun org-property-next-allowed-value (&optional previous)
11334 "Switch to the next allowed value for this property."
11335 (interactive)
11336 (unless (org-at-property-p)
11337 (error "Not at a property"))
11338 (let* ((key (match-string 2))
11339 (value (match-string 3))
11340 (allowed (or (org-property-get-allowed-values (point) key)
11341 (and (member value '("[ ]" "[-]" "[X]"))
11342 '("[ ]" "[X]"))))
11343 nval)
11344 (unless allowed
11345 (error "Allowed values for this property have not been defined"))
11346 (if previous (setq allowed (reverse allowed)))
11347 (if (member value allowed)
11348 (setq nval (car (cdr (member value allowed)))))
11349 (setq nval (or nval (car allowed)))
11350 (if (equal nval value)
11351 (error "Only one allowed value for this property"))
11352 (org-at-property-p)
11353 (replace-match (concat " :" key ": " nval) t t)
11354 (org-indent-line-function)
11355 (beginning-of-line 1)
11356 (skip-chars-forward " \t")))
11358 (defun org-find-entry-with-id (ident)
11359 "Locate the entry that contains the ID property with exact value IDENT.
11360 IDENT can be a string, a symbol or a number, this function will search for
11361 the string representation of it.
11362 Return the position where this entry starts, or nil if there is no such entry."
11363 (interactive "sID: ")
11364 (let ((id (cond
11365 ((stringp ident) ident)
11366 ((symbol-name ident) (symbol-name ident))
11367 ((numberp ident) (number-to-string ident))
11368 (t (error "IDENT %s must be a string, symbol or number" ident))))
11369 (case-fold-search nil))
11370 (save-excursion
11371 (save-restriction
11372 (widen)
11373 (goto-char (point-min))
11374 (when (re-search-forward
11375 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11376 nil t)
11377 (org-back-to-heading)
11378 (point))))))
11380 ;;;; Timestamps
11382 (defvar org-last-changed-timestamp nil)
11383 (defvar org-last-inserted-timestamp nil
11384 "The last time stamp inserted with `org-insert-time-stamp'.")
11385 (defvar org-time-was-given) ; dynamically scoped parameter
11386 (defvar org-end-time-was-given) ; dynamically scoped parameter
11387 (defvar org-ts-what) ; dynamically scoped parameter
11389 (defun org-time-stamp (arg &optional inactive)
11390 "Prompt for a date/time and insert a time stamp.
11391 If the user specifies a time like HH:MM, or if this command is called
11392 with a prefix argument, the time stamp will contain date and time.
11393 Otherwise, only the date will be included. All parts of a date not
11394 specified by the user will be filled in from the current date/time.
11395 So if you press just return without typing anything, the time stamp
11396 will represent the current date/time. If there is already a timestamp
11397 at the cursor, it will be modified."
11398 (interactive "P")
11399 (let* ((ts nil)
11400 (default-time
11401 ;; Default time is either today, or, when entering a range,
11402 ;; the range start.
11403 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11404 (save-excursion
11405 (re-search-backward
11406 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11407 (- (point) 20) t)))
11408 (apply 'encode-time (org-parse-time-string (match-string 1)))
11409 (current-time)))
11410 (default-input (and ts (org-get-compact-tod ts)))
11411 org-time-was-given org-end-time-was-given time)
11412 (cond
11413 ((and (org-at-timestamp-p t)
11414 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11415 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11416 (insert "--")
11417 (setq time (let ((this-command this-command))
11418 (org-read-date arg 'totime nil nil
11419 default-time default-input)))
11420 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11421 ((org-at-timestamp-p t)
11422 (setq time (let ((this-command this-command))
11423 (org-read-date arg 'totime nil nil default-time default-input)))
11424 (when (org-at-timestamp-p t) ; just to get the match data
11425 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11426 (replace-match "")
11427 (setq org-last-changed-timestamp
11428 (org-insert-time-stamp
11429 time (or org-time-was-given arg)
11430 inactive nil nil (list org-end-time-was-given))))
11431 (message "Timestamp updated"))
11433 (setq time (let ((this-command this-command))
11434 (org-read-date arg 'totime nil nil default-time default-input)))
11435 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11436 nil nil (list org-end-time-was-given))))))
11438 ;; FIXME: can we use this for something else, like computing time differences?
11439 (defun org-get-compact-tod (s)
11440 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11441 (let* ((t1 (match-string 1 s))
11442 (h1 (string-to-number (match-string 2 s)))
11443 (m1 (string-to-number (match-string 3 s)))
11444 (t2 (and (match-end 4) (match-string 5 s)))
11445 (h2 (and t2 (string-to-number (match-string 6 s))))
11446 (m2 (and t2 (string-to-number (match-string 7 s))))
11447 dh dm)
11448 (if (not t2)
11450 (setq dh (- h2 h1) dm (- m2 m1))
11451 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11452 (concat t1 "+" (number-to-string dh)
11453 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11455 (defun org-time-stamp-inactive (&optional arg)
11456 "Insert an inactive time stamp.
11457 An inactive time stamp is enclosed in square brackets instead of angle
11458 brackets. It is inactive in the sense that it does not trigger agenda entries,
11459 does not link to the calendar and cannot be changed with the S-cursor keys.
11460 So these are more for recording a certain time/date."
11461 (interactive "P")
11462 (org-time-stamp arg 'inactive))
11464 (defvar org-date-ovl (org-make-overlay 1 1))
11465 (org-overlay-put org-date-ovl 'face 'org-warning)
11466 (org-detach-overlay org-date-ovl)
11468 (defvar org-ans1) ; dynamically scoped parameter
11469 (defvar org-ans2) ; dynamically scoped parameter
11471 (defvar org-plain-time-of-day-regexp) ; defined below
11473 (defvar org-overriding-default-time nil) ; dynamically scoped
11474 (defvar org-read-date-overlay nil)
11475 (defvar org-dcst nil) ; dynamically scoped
11477 (defun org-read-date (&optional with-time to-time from-string prompt
11478 default-time default-input)
11479 "Read a date, possibly a time, and make things smooth for the user.
11480 The prompt will suggest to enter an ISO date, but you can also enter anything
11481 which will at least partially be understood by `parse-time-string'.
11482 Unrecognized parts of the date will default to the current day, month, year,
11483 hour and minute. If this command is called to replace a timestamp at point,
11484 of to enter the second timestamp of a range, the default time is taken from the
11485 existing stamp. For example,
11486 3-2-5 --> 2003-02-05
11487 feb 15 --> currentyear-02-15
11488 sep 12 9 --> 2009-09-12
11489 12:45 --> today 12:45
11490 22 sept 0:34 --> currentyear-09-22 0:34
11491 12 --> currentyear-currentmonth-12
11492 Fri --> nearest Friday (today or later)
11493 etc.
11495 Furthermore you can specify a relative date by giving, as the *first* thing
11496 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11497 change in days weeks, months, years.
11498 With a single plus or minus, the date is relative to today. With a double
11499 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11500 +4d --> four days from today
11501 +4 --> same as above
11502 +2w --> two weeks from today
11503 ++5 --> five days from default date
11505 The function understands only English month and weekday abbreviations,
11506 but this can be configured with the variables `parse-time-months' and
11507 `parse-time-weekdays'.
11509 While prompting, a calendar is popped up - you can also select the
11510 date with the mouse (button 1). The calendar shows a period of three
11511 months. To scroll it to other months, use the keys `>' and `<'.
11512 If you don't like the calendar, turn it off with
11513 \(setq org-read-date-popup-calendar nil)
11515 With optional argument TO-TIME, the date will immediately be converted
11516 to an internal time.
11517 With an optional argument WITH-TIME, the prompt will suggest to also
11518 insert a time. Note that when WITH-TIME is not set, you can still
11519 enter a time, and this function will inform the calling routine about
11520 this change. The calling routine may then choose to change the format
11521 used to insert the time stamp into the buffer to include the time.
11522 With optional argument FROM-STRING, read from this string instead from
11523 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11524 the time/date that is used for everything that is not specified by the
11525 user."
11526 (require 'parse-time)
11527 (let* ((org-time-stamp-rounding-minutes
11528 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11529 (org-dcst org-display-custom-times)
11530 (ct (org-current-time))
11531 (def (or org-overriding-default-time default-time ct))
11532 (defdecode (decode-time def))
11533 (dummy (progn
11534 (when (< (nth 2 defdecode) org-extend-today-until)
11535 (setcar (nthcdr 2 defdecode) -1)
11536 (setcar (nthcdr 1 defdecode) 59)
11537 (setq def (apply 'encode-time defdecode)
11538 defdecode (decode-time def)))))
11539 (calendar-move-hook nil)
11540 (calendar-view-diary-initially-flag nil)
11541 (view-diary-entries-initially nil)
11542 (calendar-view-holidays-initially-flag nil)
11543 (view-calendar-holidays-initially nil)
11544 (timestr (format-time-string
11545 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11546 (prompt (concat (if prompt (concat prompt " ") "")
11547 (format "Date+time [%s]: " timestr)))
11548 ans (org-ans0 "") org-ans1 org-ans2 final)
11550 (cond
11551 (from-string (setq ans from-string))
11552 (org-read-date-popup-calendar
11553 (save-excursion
11554 (save-window-excursion
11555 (calendar)
11556 (calendar-forward-day (- (time-to-days def)
11557 (calendar-absolute-from-gregorian
11558 (calendar-current-date))))
11559 (org-eval-in-calendar nil t)
11560 (let* ((old-map (current-local-map))
11561 (map (copy-keymap calendar-mode-map))
11562 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11563 (org-defkey map (kbd "RET") 'org-calendar-select)
11564 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11565 'org-calendar-select-mouse)
11566 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11567 'org-calendar-select-mouse)
11568 (org-defkey minibuffer-local-map [(meta shift left)]
11569 (lambda () (interactive)
11570 (org-eval-in-calendar '(calendar-backward-month 1))))
11571 (org-defkey minibuffer-local-map [(meta shift right)]
11572 (lambda () (interactive)
11573 (org-eval-in-calendar '(calendar-forward-month 1))))
11574 (org-defkey minibuffer-local-map [(meta shift up)]
11575 (lambda () (interactive)
11576 (org-eval-in-calendar '(calendar-backward-year 1))))
11577 (org-defkey minibuffer-local-map [(meta shift down)]
11578 (lambda () (interactive)
11579 (org-eval-in-calendar '(calendar-forward-year 1))))
11580 (org-defkey minibuffer-local-map [(shift up)]
11581 (lambda () (interactive)
11582 (org-eval-in-calendar '(calendar-backward-week 1))))
11583 (org-defkey minibuffer-local-map [(shift down)]
11584 (lambda () (interactive)
11585 (org-eval-in-calendar '(calendar-forward-week 1))))
11586 (org-defkey minibuffer-local-map [(shift left)]
11587 (lambda () (interactive)
11588 (org-eval-in-calendar '(calendar-backward-day 1))))
11589 (org-defkey minibuffer-local-map [(shift right)]
11590 (lambda () (interactive)
11591 (org-eval-in-calendar '(calendar-forward-day 1))))
11592 (org-defkey minibuffer-local-map ">"
11593 (lambda () (interactive)
11594 (org-eval-in-calendar '(scroll-calendar-left 1))))
11595 (org-defkey minibuffer-local-map "<"
11596 (lambda () (interactive)
11597 (org-eval-in-calendar '(scroll-calendar-right 1))))
11598 (unwind-protect
11599 (progn
11600 (use-local-map map)
11601 (add-hook 'post-command-hook 'org-read-date-display)
11602 (setq org-ans0 (read-string prompt default-input nil nil))
11603 ;; org-ans0: from prompt
11604 ;; org-ans1: from mouse click
11605 ;; org-ans2: from calendar motion
11606 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11607 (remove-hook 'post-command-hook 'org-read-date-display)
11608 (use-local-map old-map)
11609 (when org-read-date-overlay
11610 (org-delete-overlay org-read-date-overlay)
11611 (setq org-read-date-overlay nil)))))))
11613 (t ; Naked prompt only
11614 (unwind-protect
11615 (setq ans (read-string prompt default-input nil timestr))
11616 (when org-read-date-overlay
11617 (org-delete-overlay org-read-date-overlay)
11618 (setq org-read-date-overlay nil)))))
11620 (setq final (org-read-date-analyze ans def defdecode))
11622 (if to-time
11623 (apply 'encode-time final)
11624 (if (and (boundp 'org-time-was-given) org-time-was-given)
11625 (format "%04d-%02d-%02d %02d:%02d"
11626 (nth 5 final) (nth 4 final) (nth 3 final)
11627 (nth 2 final) (nth 1 final))
11628 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11629 (defvar def)
11630 (defvar defdecode)
11631 (defvar with-time)
11632 (defun org-read-date-display ()
11633 "Display the current date prompt interpretation in the minibuffer."
11634 (when org-read-date-display-live
11635 (when org-read-date-overlay
11636 (org-delete-overlay org-read-date-overlay))
11637 (let ((p (point)))
11638 (end-of-line 1)
11639 (while (not (equal (buffer-substring
11640 (max (point-min) (- (point) 4)) (point))
11641 " "))
11642 (insert " "))
11643 (goto-char p))
11644 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11645 " " (or org-ans1 org-ans2)))
11646 (org-end-time-was-given nil)
11647 (f (org-read-date-analyze ans def defdecode))
11648 (fmts (if org-dcst
11649 org-time-stamp-custom-formats
11650 org-time-stamp-formats))
11651 (fmt (if (or with-time
11652 (and (boundp 'org-time-was-given) org-time-was-given))
11653 (cdr fmts)
11654 (car fmts)))
11655 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11656 (when (and org-end-time-was-given
11657 (string-match org-plain-time-of-day-regexp txt))
11658 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11659 org-end-time-was-given
11660 (substring txt (match-end 0)))))
11661 (setq org-read-date-overlay
11662 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11663 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11665 (defun org-read-date-analyze (ans def defdecode)
11666 "Analyse the combined answer of the date prompt."
11667 ;; FIXME: cleanup and comment
11668 (let (delta deltan deltaw deltadef year month day
11669 hour minute second wday pm h2 m2 tl wday1
11670 iso-year iso-weekday iso-week iso-year iso-date)
11672 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11673 (setq ans "+0"))
11675 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11676 (setq ans (replace-match "" t t ans)
11677 deltan (car delta)
11678 deltaw (nth 1 delta)
11679 deltadef (nth 2 delta)))
11681 ;; Check if there is an iso week date in there
11682 ;; If yes, sore the info and postpone interpreting it until the rest
11683 ;; of the parsing is done
11684 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11685 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11686 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11687 iso-week (string-to-number (match-string 2 ans)))
11688 (setq ans (replace-match "" t t ans)))
11690 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11691 (when (string-match
11692 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11693 (setq year (if (match-end 2)
11694 (string-to-number (match-string 2 ans))
11695 (string-to-number (format-time-string "%Y")))
11696 month (string-to-number (match-string 3 ans))
11697 day (string-to-number (match-string 4 ans)))
11698 (if (< year 100) (setq year (+ 2000 year)))
11699 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11700 t nil ans)))
11701 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11702 ;; If there is a time with am/pm, and *no* time without it, we convert
11703 ;; so that matching will be successful.
11704 (loop for i from 1 to 2 do ; twice, for end time as well
11705 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11706 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11707 (setq hour (string-to-number (match-string 1 ans))
11708 minute (if (match-end 3)
11709 (string-to-number (match-string 3 ans))
11711 pm (equal ?p
11712 (string-to-char (downcase (match-string 4 ans)))))
11713 (if (and (= hour 12) (not pm))
11714 (setq hour 0)
11715 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11716 (setq ans (replace-match (format "%02d:%02d" hour minute)
11717 t t ans))))
11719 ;; Check if a time range is given as a duration
11720 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11721 (setq hour (string-to-number (match-string 1 ans))
11722 h2 (+ hour (string-to-number (match-string 3 ans)))
11723 minute (string-to-number (match-string 2 ans))
11724 m2 (+ minute (if (match-end 5) (string-to-number
11725 (match-string 5 ans))0)))
11726 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11727 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11728 t t ans)))
11730 ;; Check if there is a time range
11731 (when (boundp 'org-end-time-was-given)
11732 (setq org-time-was-given nil)
11733 (when (and (string-match org-plain-time-of-day-regexp ans)
11734 (match-end 8))
11735 (setq org-end-time-was-given (match-string 8 ans))
11736 (setq ans (concat (substring ans 0 (match-beginning 7))
11737 (substring ans (match-end 7))))))
11739 (setq tl (parse-time-string ans)
11740 day (or (nth 3 tl) (nth 3 defdecode))
11741 month (or (nth 4 tl)
11742 (if (and org-read-date-prefer-future
11743 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11744 (1+ (nth 4 defdecode))
11745 (nth 4 defdecode)))
11746 year (or (nth 5 tl)
11747 (if (and org-read-date-prefer-future
11748 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11749 (1+ (nth 5 defdecode))
11750 (nth 5 defdecode)))
11751 hour (or (nth 2 tl) (nth 2 defdecode))
11752 minute (or (nth 1 tl) (nth 1 defdecode))
11753 second (or (nth 0 tl) 0)
11754 wday (nth 6 tl))
11756 ;; Special date definitions below
11757 (cond
11758 (iso-week
11759 ;; There was an iso week
11760 (setq year (or iso-year year)
11761 day (or iso-weekday wday 1)
11762 wday nil ; to make sure that the trigger below does not match
11763 iso-date (calendar-gregorian-from-absolute
11764 (calendar-absolute-from-iso
11765 (list iso-week day year))))
11766 ; FIXME: Should we also push ISO weeks into the future?
11767 ; (when (and org-read-date-prefer-future
11768 ; (not iso-year)
11769 ; (< (calendar-absolute-from-gregorian iso-date)
11770 ; (time-to-days (current-time))))
11771 ; (setq year (1+ year)
11772 ; iso-date (calendar-gregorian-from-absolute
11773 ; (calendar-absolute-from-iso
11774 ; (list iso-week day year)))))
11775 (setq month (car iso-date)
11776 year (nth 2 iso-date)
11777 day (nth 1 iso-date)))
11778 (deltan
11779 (unless deltadef
11780 (let ((now (decode-time (current-time))))
11781 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11782 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11783 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11784 ((equal deltaw "m") (setq month (+ month deltan)))
11785 ((equal deltaw "y") (setq year (+ year deltan)))))
11786 ((and wday (not (nth 3 tl)))
11787 ;; Weekday was given, but no day, so pick that day in the week
11788 ;; on or after the derived date.
11789 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11790 (unless (equal wday wday1)
11791 (setq day (+ day (% (- wday wday1 -7) 7))))))
11792 (if (and (boundp 'org-time-was-given)
11793 (nth 2 tl))
11794 (setq org-time-was-given t))
11795 (if (< year 100) (setq year (+ 2000 year)))
11796 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11797 (list second minute hour day month year)))
11799 (defvar parse-time-weekdays)
11801 (defun org-read-date-get-relative (s today default)
11802 "Check string S for special relative date string.
11803 TODAY and DEFAULT are internal times, for today and for a default.
11804 Return shift list (N what def-flag)
11805 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11806 N is the number of WHATs to shift.
11807 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11808 the DEFAULT date rather than TODAY."
11809 (when (and
11810 (string-match
11811 (concat
11812 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11813 "\\([0-9]+\\)?"
11814 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11815 "\\([ \t]\\|$\\)") s)
11816 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11817 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11818 (string-to-char (substring (match-string 1 s) -1))
11819 ?+))
11820 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11821 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11822 (what (if (match-end 3) (match-string 3 s) "d"))
11823 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11824 (date (if rel default today))
11825 (wday (nth 6 (decode-time date)))
11826 delta)
11827 (if wday1
11828 (progn
11829 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11830 (if (= dir ?-) (setq delta (- delta 7)))
11831 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11832 (list delta "d" rel))
11833 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11835 (defun org-eval-in-calendar (form &optional keepdate)
11836 "Eval FORM in the calendar window and return to current window.
11837 Also, store the cursor date in variable org-ans2."
11838 (let ((sw (selected-window)))
11839 (select-window (get-buffer-window "*Calendar*"))
11840 (eval form)
11841 (when (and (not keepdate) (calendar-cursor-to-date))
11842 (let* ((date (calendar-cursor-to-date))
11843 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11844 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11845 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11846 (select-window sw)))
11848 (defun org-calendar-select ()
11849 "Return to `org-read-date' with the date currently selected.
11850 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11851 (interactive)
11852 (when (calendar-cursor-to-date)
11853 (let* ((date (calendar-cursor-to-date))
11854 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11855 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11856 (if (active-minibuffer-window) (exit-minibuffer))))
11858 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11859 "Insert a date stamp for the date given by the internal TIME.
11860 WITH-HM means, use the stamp format that includes the time of the day.
11861 INACTIVE means use square brackets instead of angular ones, so that the
11862 stamp will not contribute to the agenda.
11863 PRE and POST are optional strings to be inserted before and after the
11864 stamp.
11865 The command returns the inserted time stamp."
11866 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11867 stamp)
11868 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11869 (insert-before-markers (or pre ""))
11870 (insert-before-markers (setq stamp (format-time-string fmt time)))
11871 (when (listp extra)
11872 (setq extra (car extra))
11873 (if (and (stringp extra)
11874 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11875 (setq extra (format "-%02d:%02d"
11876 (string-to-number (match-string 1 extra))
11877 (string-to-number (match-string 2 extra))))
11878 (setq extra nil)))
11879 (when extra
11880 (backward-char 1)
11881 (insert-before-markers extra)
11882 (forward-char 1))
11883 (insert-before-markers (or post ""))
11884 (setq org-last-inserted-timestamp stamp)))
11886 (defun org-toggle-time-stamp-overlays ()
11887 "Toggle the use of custom time stamp formats."
11888 (interactive)
11889 (setq org-display-custom-times (not org-display-custom-times))
11890 (unless org-display-custom-times
11891 (let ((p (point-min)) (bmp (buffer-modified-p)))
11892 (while (setq p (next-single-property-change p 'display))
11893 (if (and (get-text-property p 'display)
11894 (eq (get-text-property p 'face) 'org-date))
11895 (remove-text-properties
11896 p (setq p (next-single-property-change p 'display))
11897 '(display t))))
11898 (set-buffer-modified-p bmp)))
11899 (if (featurep 'xemacs)
11900 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11901 (org-restart-font-lock)
11902 (setq org-table-may-need-update t)
11903 (if org-display-custom-times
11904 (message "Time stamps are overlayed with custom format")
11905 (message "Time stamp overlays removed")))
11907 (defun org-display-custom-time (beg end)
11908 "Overlay modified time stamp format over timestamp between BEG and END."
11909 (let* ((ts (buffer-substring beg end))
11910 t1 w1 with-hm tf time str w2 (off 0))
11911 (save-match-data
11912 (setq t1 (org-parse-time-string ts t))
11913 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11914 (setq off (- (match-end 0) (match-beginning 0)))))
11915 (setq end (- end off))
11916 (setq w1 (- end beg)
11917 with-hm (and (nth 1 t1) (nth 2 t1))
11918 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11919 time (org-fix-decoded-time t1)
11920 str (org-add-props
11921 (format-time-string
11922 (substring tf 1 -1) (apply 'encode-time time))
11923 nil 'mouse-face 'highlight)
11924 w2 (length str))
11925 (if (not (= w2 w1))
11926 (add-text-properties (1+ beg) (+ 2 beg)
11927 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11928 (if (featurep 'xemacs)
11929 (progn
11930 (put-text-property beg end 'invisible t)
11931 (put-text-property beg end 'end-glyph (make-glyph str)))
11932 (put-text-property beg end 'display str))))
11934 (defun org-translate-time (string)
11935 "Translate all timestamps in STRING to custom format.
11936 But do this only if the variable `org-display-custom-times' is set."
11937 (when org-display-custom-times
11938 (save-match-data
11939 (let* ((start 0)
11940 (re org-ts-regexp-both)
11941 t1 with-hm inactive tf time str beg end)
11942 (while (setq start (string-match re string start))
11943 (setq beg (match-beginning 0)
11944 end (match-end 0)
11945 t1 (save-match-data
11946 (org-parse-time-string (substring string beg end) t))
11947 with-hm (and (nth 1 t1) (nth 2 t1))
11948 inactive (equal (substring string beg (1+ beg)) "[")
11949 tf (funcall (if with-hm 'cdr 'car)
11950 org-time-stamp-custom-formats)
11951 time (org-fix-decoded-time t1)
11952 str (format-time-string
11953 (concat
11954 (if inactive "[" "<") (substring tf 1 -1)
11955 (if inactive "]" ">"))
11956 (apply 'encode-time time))
11957 string (replace-match str t t string)
11958 start (+ start (length str)))))))
11959 string)
11961 (defun org-fix-decoded-time (time)
11962 "Set 0 instead of nil for the first 6 elements of time.
11963 Don't touch the rest."
11964 (let ((n 0))
11965 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11967 (defun org-days-to-time (timestamp-string)
11968 "Difference between TIMESTAMP-STRING and now in days."
11969 (- (time-to-days (org-time-string-to-time timestamp-string))
11970 (time-to-days (current-time))))
11972 (defun org-deadline-close (timestamp-string &optional ndays)
11973 "Is the time in TIMESTAMP-STRING close to the current date?"
11974 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11975 (and (< (org-days-to-time timestamp-string) ndays)
11976 (not (org-entry-is-done-p))))
11978 (defun org-get-wdays (ts)
11979 "Get the deadline lead time appropriate for timestring TS."
11980 (cond
11981 ((<= org-deadline-warning-days 0)
11982 ;; 0 or negative, enforce this value no matter what
11983 (- org-deadline-warning-days))
11984 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
11985 ;; lead time is specified.
11986 (floor (* (string-to-number (match-string 1 ts))
11987 (cdr (assoc (match-string 2 ts)
11988 '(("d" . 1) ("w" . 7)
11989 ("m" . 30.4) ("y" . 365.25)))))))
11990 ;; go for the default.
11991 (t org-deadline-warning-days)))
11993 (defun org-calendar-select-mouse (ev)
11994 "Return to `org-read-date' with the date currently selected.
11995 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11996 (interactive "e")
11997 (mouse-set-point ev)
11998 (when (calendar-cursor-to-date)
11999 (let* ((date (calendar-cursor-to-date))
12000 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12001 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12002 (if (active-minibuffer-window) (exit-minibuffer))))
12004 (defun org-check-deadlines (ndays)
12005 "Check if there are any deadlines due or past due.
12006 A deadline is considered due if it happens within `org-deadline-warning-days'
12007 days from today's date. If the deadline appears in an entry marked DONE,
12008 it is not shown. The prefix arg NDAYS can be used to test that many
12009 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12010 (interactive "P")
12011 (let* ((org-warn-days
12012 (cond
12013 ((equal ndays '(4)) 100000)
12014 (ndays (prefix-numeric-value ndays))
12015 (t (abs org-deadline-warning-days))))
12016 (case-fold-search nil)
12017 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12018 (callback
12019 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12021 (message "%d deadlines past-due or due within %d days"
12022 (org-occur regexp nil callback)
12023 org-warn-days)))
12025 (defun org-check-before-date (date)
12026 "Check if there are deadlines or scheduled entries before DATE."
12027 (interactive (list (org-read-date)))
12028 (let ((case-fold-search nil)
12029 (regexp (concat "\\<\\(" org-deadline-string
12030 "\\|" org-scheduled-string
12031 "\\) *<\\([^>]+\\)>"))
12032 (callback
12033 (lambda () (time-less-p
12034 (org-time-string-to-time (match-string 2))
12035 (org-time-string-to-time date)))))
12036 (message "%d entries before %s"
12037 (org-occur regexp nil callback) date)))
12039 (defun org-evaluate-time-range (&optional to-buffer)
12040 "Evaluate a time range by computing the difference between start and end.
12041 Normally the result is just printed in the echo area, but with prefix arg
12042 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12043 If the time range is actually in a table, the result is inserted into the
12044 next column.
12045 For time difference computation, a year is assumed to be exactly 365
12046 days in order to avoid rounding problems."
12047 (interactive "P")
12049 (org-clock-update-time-maybe)
12050 (save-excursion
12051 (unless (org-at-date-range-p t)
12052 (goto-char (point-at-bol))
12053 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12054 (if (not (org-at-date-range-p t))
12055 (error "Not at a time-stamp range, and none found in current line")))
12056 (let* ((ts1 (match-string 1))
12057 (ts2 (match-string 2))
12058 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12059 (match-end (match-end 0))
12060 (time1 (org-time-string-to-time ts1))
12061 (time2 (org-time-string-to-time ts2))
12062 (t1 (time-to-seconds time1))
12063 (t2 (time-to-seconds time2))
12064 (diff (abs (- t2 t1)))
12065 (negative (< (- t2 t1) 0))
12066 ;; (ys (floor (* 365 24 60 60)))
12067 (ds (* 24 60 60))
12068 (hs (* 60 60))
12069 (fy "%dy %dd %02d:%02d")
12070 (fy1 "%dy %dd")
12071 (fd "%dd %02d:%02d")
12072 (fd1 "%dd")
12073 (fh "%02d:%02d")
12074 y d h m align)
12075 (if havetime
12076 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12078 d (floor (/ diff ds)) diff (mod diff ds)
12079 h (floor (/ diff hs)) diff (mod diff hs)
12080 m (floor (/ diff 60)))
12081 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12083 d (floor (+ (/ diff ds) 0.5))
12084 h 0 m 0))
12085 (if (not to-buffer)
12086 (message "%s" (org-make-tdiff-string y d h m))
12087 (if (org-at-table-p)
12088 (progn
12089 (goto-char match-end)
12090 (setq align t)
12091 (and (looking-at " *|") (goto-char (match-end 0))))
12092 (goto-char match-end))
12093 (if (looking-at
12094 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12095 (replace-match ""))
12096 (if negative (insert " -"))
12097 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12098 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12099 (insert " " (format fh h m))))
12100 (if align (org-table-align))
12101 (message "Time difference inserted")))))
12103 (defun org-make-tdiff-string (y d h m)
12104 (let ((fmt "")
12105 (l nil))
12106 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12107 l (push y l)))
12108 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12109 l (push d l)))
12110 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12111 l (push h l)))
12112 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12113 l (push m l)))
12114 (apply 'format fmt (nreverse l))))
12116 (defun org-time-string-to-time (s)
12117 (apply 'encode-time (org-parse-time-string s)))
12119 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12120 "Convert a time stamp to an absolute day number.
12121 If there is a specifyer for a cyclic time stamp, get the closest date to
12122 DAYNR.
12123 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12124 (cond
12125 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12126 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12127 daynr
12128 (+ daynr 1000)))
12129 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12130 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12131 (time-to-days (current-time))) (match-string 0 s)
12132 prefer show-all))
12133 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12135 (defun org-days-to-iso-week (days)
12136 "Return the iso week number."
12137 (require 'cal-iso)
12138 (car (calendar-iso-from-absolute days)))
12140 (defun org-small-year-to-year (year)
12141 "Convert 2-digit years into 4-digit years.
12142 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12143 The year 2000 cannot be abbreviated. Any year larger than 99
12144 is returned unchanged."
12145 (if (< year 38)
12146 (setq year (+ 2000 year))
12147 (if (< year 100)
12148 (setq year (+ 1900 year))))
12149 year)
12151 (defun org-time-from-absolute (d)
12152 "Return the time corresponding to date D.
12153 D may be an absolute day number, or a calendar-type list (month day year)."
12154 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12155 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12157 (defun org-calendar-holiday ()
12158 "List of holidays, for Diary display in Org-mode."
12159 (require 'holidays)
12160 (let ((hl (funcall
12161 (if (fboundp 'calendar-check-holidays)
12162 'calendar-check-holidays 'check-calendar-holidays) date)))
12163 (if hl (mapconcat 'identity hl "; "))))
12165 (defun org-diary-sexp-entry (sexp entry date)
12166 "Process a SEXP diary ENTRY for DATE."
12167 (require 'diary-lib)
12168 (let ((result (if calendar-debug-sexp
12169 (let ((stack-trace-on-error t))
12170 (eval (car (read-from-string sexp))))
12171 (condition-case nil
12172 (eval (car (read-from-string sexp)))
12173 (error
12174 (beep)
12175 (message "Bad sexp at line %d in %s: %s"
12176 (org-current-line)
12177 (buffer-file-name) sexp)
12178 (sleep-for 2))))))
12179 (cond ((stringp result) result)
12180 ((and (consp result)
12181 (stringp (cdr result))) (cdr result))
12182 (result entry)
12183 (t nil))))
12185 (defun org-diary-to-ical-string (frombuf)
12186 "Get iCalendar entries from diary entries in buffer FROMBUF.
12187 This uses the icalendar.el library."
12188 (let* ((tmpdir (if (featurep 'xemacs)
12189 (temp-directory)
12190 temporary-file-directory))
12191 (tmpfile (make-temp-name
12192 (expand-file-name "orgics" tmpdir)))
12193 buf rtn b e)
12194 (save-excursion
12195 (set-buffer frombuf)
12196 (icalendar-export-region (point-min) (point-max) tmpfile)
12197 (setq buf (find-buffer-visiting tmpfile))
12198 (set-buffer buf)
12199 (goto-char (point-min))
12200 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12201 (setq b (match-beginning 0)))
12202 (goto-char (point-max))
12203 (if (re-search-backward "^END:VEVENT" nil t)
12204 (setq e (match-end 0)))
12205 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12206 (kill-buffer buf)
12207 (delete-file tmpfile)
12208 rtn))
12210 (defun org-closest-date (start current change prefer show-all)
12211 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12212 When PREFER is `past' return a date that is either CURRENT or past.
12213 When PREFER is `future', return a date that is either CURRENT or future.
12214 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12215 ;; Make the proper lists from the dates
12216 (catch 'exit
12217 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12218 dn dw sday cday n1 n2 n0
12219 d m y y1 y2 date1 date2 nmonths nm ny m2)
12221 (setq start (org-date-to-gregorian start)
12222 current (org-date-to-gregorian
12223 (if show-all
12224 current
12225 (time-to-days (current-time))))
12226 sday (calendar-absolute-from-gregorian start)
12227 cday (calendar-absolute-from-gregorian current))
12229 (if (<= cday sday) (throw 'exit sday))
12231 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12232 (setq dn (string-to-number (match-string 1 change))
12233 dw (cdr (assoc (match-string 2 change) a1)))
12234 (error "Invalid change specifyer: %s" change))
12235 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12236 (cond
12237 ((eq dw 'day)
12238 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12239 n2 (+ n1 dn)))
12240 ((eq dw 'year)
12241 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12242 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12243 (setq date1 (list m d y1)
12244 n1 (calendar-absolute-from-gregorian date1)
12245 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12246 n2 (calendar-absolute-from-gregorian date2)))
12247 ((eq dw 'month)
12248 ;; approx number of month between the two dates
12249 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12250 ;; How often does dn fit in there?
12251 (setq d (nth 1 start) m (car start) y (nth 2 start)
12252 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12253 m (+ m nm)
12254 ny (floor (/ m 12))
12255 y (+ y ny)
12256 m (- m (* ny 12)))
12257 (while (> m 12) (setq m (- m 12) y (1+ y)))
12258 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12259 (setq m2 (+ m dn) y2 y)
12260 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12261 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12262 (while (<= n2 cday)
12263 (setq n1 n2 m m2 y y2)
12264 (setq m2 (+ m dn) y2 y)
12265 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12266 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12267 ;; Make sure n1 is the earlier date
12268 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12269 (if show-all
12270 (cond
12271 ((eq prefer 'past) n1)
12272 ((eq prefer 'future) (if (= cday n1) n1 n2))
12273 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12274 (cond
12275 ((eq prefer 'past) n1)
12276 ((eq prefer 'future) (if (= cday n1) n1 n2))
12277 (t (if (= cday n1) n1 n2)))))))
12279 (defun org-date-to-gregorian (date)
12280 "Turn any specification of DATE into a gregorian date for the calendar."
12281 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12282 ((and (listp date) (= (length date) 3)) date)
12283 ((stringp date)
12284 (setq date (org-parse-time-string date))
12285 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12286 ((listp date)
12287 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12289 (defun org-parse-time-string (s &optional nodefault)
12290 "Parse the standard Org-mode time string.
12291 This should be a lot faster than the normal `parse-time-string'.
12292 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12293 hour and minute fields will be nil if not given."
12294 (if (string-match org-ts-regexp0 s)
12295 (list 0
12296 (if (or (match-beginning 8) (not nodefault))
12297 (string-to-number (or (match-string 8 s) "0")))
12298 (if (or (match-beginning 7) (not nodefault))
12299 (string-to-number (or (match-string 7 s) "0")))
12300 (string-to-number (match-string 4 s))
12301 (string-to-number (match-string 3 s))
12302 (string-to-number (match-string 2 s))
12303 nil nil nil)
12304 (make-list 9 0)))
12306 (defun org-timestamp-up (&optional arg)
12307 "Increase the date item at the cursor by one.
12308 If the cursor is on the year, change the year. If it is on the month or
12309 the day, change that.
12310 With prefix ARG, change by that many units."
12311 (interactive "p")
12312 (org-timestamp-change (prefix-numeric-value arg)))
12314 (defun org-timestamp-down (&optional arg)
12315 "Decrease the date item at the cursor by one.
12316 If the cursor is on the year, change the year. If it is on the month or
12317 the day, change that.
12318 With prefix ARG, change by that many units."
12319 (interactive "p")
12320 (org-timestamp-change (- (prefix-numeric-value arg))))
12322 (defun org-timestamp-up-day (&optional arg)
12323 "Increase the date in the time stamp by one day.
12324 With prefix ARG, change that many days."
12325 (interactive "p")
12326 (if (and (not (org-at-timestamp-p t))
12327 (org-on-heading-p))
12328 (org-todo 'up)
12329 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12331 (defun org-timestamp-down-day (&optional arg)
12332 "Decrease the date in the time stamp by one day.
12333 With prefix ARG, change that many days."
12334 (interactive "p")
12335 (if (and (not (org-at-timestamp-p t))
12336 (org-on-heading-p))
12337 (org-todo 'down)
12338 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12340 (defun org-at-timestamp-p (&optional inactive-ok)
12341 "Determine if the cursor is in or at a timestamp."
12342 (interactive)
12343 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12344 (pos (point))
12345 (ans (or (looking-at tsr)
12346 (save-excursion
12347 (skip-chars-backward "^[<\n\r\t")
12348 (if (> (point) (point-min)) (backward-char 1))
12349 (and (looking-at tsr)
12350 (> (- (match-end 0) pos) -1))))))
12351 (and ans
12352 (boundp 'org-ts-what)
12353 (setq org-ts-what
12354 (cond
12355 ((= pos (match-beginning 0)) 'bracket)
12356 ((= pos (1- (match-end 0))) 'bracket)
12357 ((org-pos-in-match-range pos 2) 'year)
12358 ((org-pos-in-match-range pos 3) 'month)
12359 ((org-pos-in-match-range pos 7) 'hour)
12360 ((org-pos-in-match-range pos 8) 'minute)
12361 ((or (org-pos-in-match-range pos 4)
12362 (org-pos-in-match-range pos 5)) 'day)
12363 ((and (> pos (or (match-end 8) (match-end 5)))
12364 (< pos (match-end 0)))
12365 (- pos (or (match-end 8) (match-end 5))))
12366 (t 'day))))
12367 ans))
12369 (defun org-toggle-timestamp-type ()
12370 "Toggle the type (<active> or [inactive]) of a time stamp."
12371 (interactive)
12372 (when (org-at-timestamp-p t)
12373 (let ((beg (match-beginning 0)) (end (match-end 0))
12374 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12375 (save-excursion
12376 (goto-char beg)
12377 (while (re-search-forward "[][<>]" end t)
12378 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12379 t t)))
12380 (message "Timestamp is now %sactive"
12381 (if (equal (char-after beg) ?<) "" "in")))))
12383 (defun org-timestamp-change (n &optional what)
12384 "Change the date in the time stamp at point.
12385 The date will be changed by N times WHAT. WHAT can be `day', `month',
12386 `year', `minute', `second'. If WHAT is not given, the cursor position
12387 in the timestamp determines what will be changed."
12388 (let ((pos (point))
12389 with-hm inactive
12390 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12391 org-ts-what
12392 extra rem
12393 ts time time0)
12394 (if (not (org-at-timestamp-p t))
12395 (error "Not at a timestamp"))
12396 (if (and (not what) (eq org-ts-what 'bracket))
12397 (org-toggle-timestamp-type)
12398 (if (and (not what) (not (eq org-ts-what 'day))
12399 org-display-custom-times
12400 (get-text-property (point) 'display)
12401 (not (get-text-property (1- (point)) 'display)))
12402 (setq org-ts-what 'day))
12403 (setq org-ts-what (or what org-ts-what)
12404 inactive (= (char-after (match-beginning 0)) ?\[)
12405 ts (match-string 0))
12406 (replace-match "")
12407 (if (string-match
12408 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12410 (setq extra (match-string 1 ts)))
12411 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12412 (setq with-hm t))
12413 (setq time0 (org-parse-time-string ts))
12414 (when (and (eq org-ts-what 'minute)
12415 (eq current-prefix-arg nil))
12416 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12417 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12418 (setcar (cdr time0) (+ (nth 1 time0)
12419 (if (> n 0) (- rem) (- dm rem))))))
12420 (setq time
12421 (encode-time (or (car time0) 0)
12422 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12423 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12424 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12425 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12426 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12427 (nthcdr 6 time0)))
12428 (when (integerp org-ts-what)
12429 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12430 (if (eq what 'calendar)
12431 (let ((cal-date (org-get-date-from-calendar)))
12432 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12433 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12434 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12435 (setcar time0 (or (car time0) 0))
12436 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12437 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12438 (setq time (apply 'encode-time time0))))
12439 (setq org-last-changed-timestamp
12440 (org-insert-time-stamp time with-hm inactive nil nil extra))
12441 (org-clock-update-time-maybe)
12442 (goto-char pos)
12443 ;; Try to recenter the calendar window, if any
12444 (if (and org-calendar-follow-timestamp-change
12445 (get-buffer-window "*Calendar*" t)
12446 (memq org-ts-what '(day month year)))
12447 (org-recenter-calendar (time-to-days time))))))
12449 (defun org-modify-ts-extra (s pos n dm)
12450 "Change the different parts of the lead-time and repeat fields in timestamp."
12451 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12452 ng h m new rem)
12453 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12454 (cond
12455 ((or (org-pos-in-match-range pos 2)
12456 (org-pos-in-match-range pos 3))
12457 (setq m (string-to-number (match-string 3 s))
12458 h (string-to-number (match-string 2 s)))
12459 (if (org-pos-in-match-range pos 2)
12460 (setq h (+ h n))
12461 (setq n (* dm (org-no-warnings (signum n))))
12462 (when (not (= 0 (setq rem (% m dm))))
12463 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12464 (setq m (+ m n)))
12465 (if (< m 0) (setq m (+ m 60) h (1- h)))
12466 (if (> m 59) (setq m (- m 60) h (1+ h)))
12467 (setq h (min 24 (max 0 h)))
12468 (setq ng 1 new (format "-%02d:%02d" h m)))
12469 ((org-pos-in-match-range pos 6)
12470 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12471 ((org-pos-in-match-range pos 5)
12472 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12474 ((org-pos-in-match-range pos 9)
12475 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12476 ((org-pos-in-match-range pos 8)
12477 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12479 (when ng
12480 (setq s (concat
12481 (substring s 0 (match-beginning ng))
12483 (substring s (match-end ng))))))
12486 (defun org-recenter-calendar (date)
12487 "If the calendar is visible, recenter it to DATE."
12488 (let* ((win (selected-window))
12489 (cwin (get-buffer-window "*Calendar*" t))
12490 (calendar-move-hook nil))
12491 (when cwin
12492 (select-window cwin)
12493 (calendar-goto-date (if (listp date) date
12494 (calendar-gregorian-from-absolute date)))
12495 (select-window win))))
12497 (defun org-goto-calendar (&optional arg)
12498 "Go to the Emacs calendar at the current date.
12499 If there is a time stamp in the current line, go to that date.
12500 A prefix ARG can be used to force the current date."
12501 (interactive "P")
12502 (let ((tsr org-ts-regexp) diff
12503 (calendar-move-hook nil)
12504 (calendar-view-holidays-initially-flag nil)
12505 (view-calendar-holidays-initially nil)
12506 (calendar-view-diary-initially-flag nil)
12507 (view-diary-entries-initially nil))
12508 (if (or (org-at-timestamp-p)
12509 (save-excursion
12510 (beginning-of-line 1)
12511 (looking-at (concat ".*" tsr))))
12512 (let ((d1 (time-to-days (current-time)))
12513 (d2 (time-to-days
12514 (org-time-string-to-time (match-string 1)))))
12515 (setq diff (- d2 d1))))
12516 (calendar)
12517 (calendar-goto-today)
12518 (if (and diff (not arg)) (calendar-forward-day diff))))
12520 (defun org-get-date-from-calendar ()
12521 "Return a list (month day year) of date at point in calendar."
12522 (with-current-buffer "*Calendar*"
12523 (save-match-data
12524 (calendar-cursor-to-date))))
12526 (defun org-date-from-calendar ()
12527 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12528 If there is already a time stamp at the cursor position, update it."
12529 (interactive)
12530 (if (org-at-timestamp-p t)
12531 (org-timestamp-change 0 'calendar)
12532 (let ((cal-date (org-get-date-from-calendar)))
12533 (org-insert-time-stamp
12534 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12536 (defun org-minutes-to-hh:mm-string (m)
12537 "Compute H:MM from a number of minutes."
12538 (let ((h (/ m 60)))
12539 (setq m (- m (* 60 h)))
12540 (format org-time-clocksum-format h m)))
12542 (defun org-hh:mm-string-to-minutes (s)
12543 "Convert a string H:MM to a number of minutes."
12544 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12545 (+ (* (string-to-number (match-string 1 s)) 60)
12546 (string-to-number (match-string 2 s)))
12549 ;;;; Files
12551 (defun org-save-all-org-buffers ()
12552 "Save all Org-mode buffers without user confirmation."
12553 (interactive)
12554 (message "Saving all Org-mode buffers...")
12555 (save-some-buffers t 'org-mode-p)
12556 (when (featurep 'org-id) (org-id-locations-save))
12557 (message "Saving all Org-mode buffers... done"))
12559 (defun org-revert-all-org-buffers ()
12560 "Revert all Org-mode buffers.
12561 Prompt for confirmation when there are unsaved changes.
12562 Be sure you know what you are doing before letting this function
12563 overwrite your changes.
12565 This function is useful in a setup where one tracks org files
12566 with a version control system, to revert on one machine after pulling
12567 changes from another. I believe the procedure must be like this:
12569 1. M-x org-save-all-org-buffers
12570 2. Pull changes from the other machine, resolve conflicts
12571 3. M-x org-revert-all-org-buffers"
12572 (interactive)
12573 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12574 (error "Abort"))
12575 (save-excursion
12576 (save-window-excursion
12577 (mapc
12578 (lambda (b)
12579 (when (and (with-current-buffer b (org-mode-p))
12580 (with-current-buffer b buffer-file-name))
12581 (switch-to-buffer b)
12582 (revert-buffer t 'no-confirm)))
12583 (buffer-list))
12584 (when (and (featurep 'org-id) org-id-track-globally)
12585 (org-id-locations-load)))))
12587 ;;;; Agenda files
12589 ;;;###autoload
12590 (defun org-iswitchb (&optional arg)
12591 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12592 With a prefix argument, restrict available to files.
12593 With two prefix arguments, restrict available buffers to agenda files.
12595 Due to some yet unresolved reason, the global function
12596 `iswitchb-mode' needs to be active for this function to work."
12597 (interactive "P")
12598 (require 'iswitchb)
12599 (let ((enabled iswitchb-mode) blist)
12600 (or enabled (iswitchb-mode 1))
12601 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12602 ((equal arg '(16)) (org-buffer-list 'agenda))
12603 (t (org-buffer-list))))
12604 (unwind-protect
12605 (let ((iswitchb-make-buflist-hook
12606 (lambda ()
12607 (setq iswitchb-temp-buflist
12608 (mapcar 'buffer-name blist)))))
12609 (switch-to-buffer
12610 (iswitchb-read-buffer
12611 "Switch-to: " nil t))
12612 (or enabled (iswitchb-mode -1))))))
12614 ;;;###autoload
12615 (defun org-ido-switchb (&optional arg)
12616 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12617 With a prefix argument, restrict available to files.
12618 With two prefix arguments, restrict available buffers to agenda files."
12619 (interactive "P")
12620 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12621 ((equal arg '(16)) (org-buffer-list 'agenda))
12622 (t (org-buffer-list)))))
12623 (switch-to-buffer
12624 (org-ido-completing-read "Org buffer: "
12625 (mapcar 'buffer-name blist)
12626 nil t))))
12628 (defun org-buffer-list (&optional predicate exclude-tmp)
12629 "Return a list of Org buffers.
12630 PREDICATE can be `export', `files' or `agenda'.
12632 export restrict the list to Export buffers.
12633 files restrict the list to buffers visiting Org files.
12634 agenda restrict the list to buffers visiting agenda files.
12636 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12637 (let* ((bfn nil)
12638 (agenda-files (and (eq predicate 'agenda)
12639 (mapcar 'file-truename (org-agenda-files t))))
12640 (filter
12641 (cond
12642 ((eq predicate 'files)
12643 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12644 ((eq predicate 'export)
12645 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12646 ((eq predicate 'agenda)
12647 (lambda (b)
12648 (with-current-buffer b
12649 (and (eq major-mode 'org-mode)
12650 (setq bfn (buffer-file-name b))
12651 (member (file-truename bfn) agenda-files)))))
12652 (t (lambda (b) (with-current-buffer b
12653 (or (eq major-mode 'org-mode)
12654 (string-match "\*Org .*Export"
12655 (buffer-name b)))))))))
12656 (delq nil
12657 (mapcar
12658 (lambda(b)
12659 (if (and (funcall filter b)
12660 (or (not exclude-tmp)
12661 (not (string-match "tmp" (buffer-name b)))))
12663 nil))
12664 (buffer-list)))))
12666 (defun org-agenda-files (&optional unrestricted archives)
12667 "Get the list of agenda files.
12668 Optional UNRESTRICTED means return the full list even if a restriction
12669 is currently in place.
12670 When ARCHIVES is t, include all archive files hat are really being
12671 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12672 `org-agenda-archives-mode' is t."
12673 (let ((files
12674 (cond
12675 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12676 ((stringp org-agenda-files) (org-read-agenda-file-list))
12677 ((listp org-agenda-files) org-agenda-files)
12678 (t (error "Invalid value of `org-agenda-files'")))))
12679 (setq files (apply 'append
12680 (mapcar (lambda (f)
12681 (if (file-directory-p f)
12682 (directory-files
12683 f t org-agenda-file-regexp)
12684 (list f)))
12685 files)))
12686 (when org-agenda-skip-unavailable-files
12687 (setq files (delq nil
12688 (mapcar (function
12689 (lambda (file)
12690 (and (file-readable-p file) file)))
12691 files))))
12692 (when (or (eq archives t)
12693 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12694 (setq files (org-add-archive-files files)))
12695 files))
12697 (defun org-edit-agenda-file-list ()
12698 "Edit the list of agenda files.
12699 Depending on setup, this either uses customize to edit the variable
12700 `org-agenda-files', or it visits the file that is holding the list. In the
12701 latter case, the buffer is set up in a way that saving it automatically kills
12702 the buffer and restores the previous window configuration."
12703 (interactive)
12704 (if (stringp org-agenda-files)
12705 (let ((cw (current-window-configuration)))
12706 (find-file org-agenda-files)
12707 (org-set-local 'org-window-configuration cw)
12708 (org-add-hook 'after-save-hook
12709 (lambda ()
12710 (set-window-configuration
12711 (prog1 org-window-configuration
12712 (kill-buffer (current-buffer))))
12713 (org-install-agenda-files-menu)
12714 (message "New agenda file list installed"))
12715 nil 'local)
12716 (message "%s" (substitute-command-keys
12717 "Edit list and finish with \\[save-buffer]")))
12718 (customize-variable 'org-agenda-files)))
12720 (defun org-store-new-agenda-file-list (list)
12721 "Set new value for the agenda file list and save it correctly."
12722 (if (stringp org-agenda-files)
12723 (let ((f org-agenda-files) b)
12724 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12725 (with-temp-file f
12726 (insert (mapconcat 'identity list "\n") "\n")))
12727 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12728 (setq org-agenda-files list)
12729 (customize-save-variable 'org-agenda-files org-agenda-files))))
12731 (defun org-read-agenda-file-list ()
12732 "Read the list of agenda files from a file."
12733 (when (file-directory-p org-agenda-files)
12734 (error "`org-agenda-files' cannot be a single directory"))
12735 (when (stringp org-agenda-files)
12736 (with-temp-buffer
12737 (insert-file-contents org-agenda-files)
12738 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12741 ;;;###autoload
12742 (defun org-cycle-agenda-files ()
12743 "Cycle through the files in `org-agenda-files'.
12744 If the current buffer visits an agenda file, find the next one in the list.
12745 If the current buffer does not, find the first agenda file."
12746 (interactive)
12747 (let* ((fs (org-agenda-files t))
12748 (files (append fs (list (car fs))))
12749 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12750 file)
12751 (unless files (error "No agenda files"))
12752 (catch 'exit
12753 (while (setq file (pop files))
12754 (if (equal (file-truename file) tcf)
12755 (when (car files)
12756 (find-file (car files))
12757 (throw 'exit t))))
12758 (find-file (car fs)))
12759 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12761 (defun org-agenda-file-to-front (&optional to-end)
12762 "Move/add the current file to the top of the agenda file list.
12763 If the file is not present in the list, it is added to the front. If it is
12764 present, it is moved there. With optional argument TO-END, add/move to the
12765 end of the list."
12766 (interactive "P")
12767 (let ((org-agenda-skip-unavailable-files nil)
12768 (file-alist (mapcar (lambda (x)
12769 (cons (file-truename x) x))
12770 (org-agenda-files t)))
12771 (ctf (file-truename buffer-file-name))
12772 x had)
12773 (setq x (assoc ctf file-alist) had x)
12775 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12776 (if to-end
12777 (setq file-alist (append (delq x file-alist) (list x)))
12778 (setq file-alist (cons x (delq x file-alist))))
12779 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12780 (org-install-agenda-files-menu)
12781 (message "File %s to %s of agenda file list"
12782 (if had "moved" "added") (if to-end "end" "front"))))
12784 (defun org-remove-file (&optional file)
12785 "Remove current file from the list of files in variable `org-agenda-files'.
12786 These are the files which are being checked for agenda entries.
12787 Optional argument FILE means, use this file instead of the current."
12788 (interactive)
12789 (let* ((org-agenda-skip-unavailable-files nil)
12790 (file (or file buffer-file-name))
12791 (true-file (file-truename file))
12792 (afile (abbreviate-file-name file))
12793 (files (delq nil (mapcar
12794 (lambda (x)
12795 (if (equal true-file
12796 (file-truename x))
12797 nil x))
12798 (org-agenda-files t)))))
12799 (if (not (= (length files) (length (org-agenda-files t))))
12800 (progn
12801 (org-store-new-agenda-file-list files)
12802 (org-install-agenda-files-menu)
12803 (message "Removed file: %s" afile))
12804 (message "File was not in list: %s (not removed)" afile))))
12806 (defun org-file-menu-entry (file)
12807 (vector file (list 'find-file file) t))
12809 (defun org-check-agenda-file (file)
12810 "Make sure FILE exists. If not, ask user what to do."
12811 (when (not (file-exists-p file))
12812 (message "non-existent file %s. [R]emove from list or [A]bort?"
12813 (abbreviate-file-name file))
12814 (let ((r (downcase (read-char-exclusive))))
12815 (cond
12816 ((equal r ?r)
12817 (org-remove-file file)
12818 (throw 'nextfile t))
12819 (t (error "Abort"))))))
12821 (defun org-get-agenda-file-buffer (file)
12822 "Get a buffer visiting FILE. If the buffer needs to be created, add
12823 it to the list of buffers which might be released later."
12824 (let ((buf (org-find-base-buffer-visiting file)))
12825 (if buf
12826 buf ; just return it
12827 ;; Make a new buffer and remember it
12828 (setq buf (find-file-noselect file))
12829 (if buf (push buf org-agenda-new-buffers))
12830 buf)))
12832 (defun org-release-buffers (blist)
12833 "Release all buffers in list, asking the user for confirmation when needed.
12834 When a buffer is unmodified, it is just killed. When modified, it is saved
12835 \(if the user agrees) and then killed."
12836 (let (buf file)
12837 (while (setq buf (pop blist))
12838 (setq file (buffer-file-name buf))
12839 (when (and (buffer-modified-p buf)
12840 file
12841 (y-or-n-p (format "Save file %s? " file)))
12842 (with-current-buffer buf (save-buffer)))
12843 (kill-buffer buf))))
12845 (defun org-prepare-agenda-buffers (files)
12846 "Create buffers for all agenda files, protect archived trees and comments."
12847 (interactive)
12848 (let ((pa '(:org-archived t))
12849 (pc '(:org-comment t))
12850 (pall '(:org-archived t :org-comment t))
12851 (inhibit-read-only t)
12852 (rea (concat ":" org-archive-tag ":"))
12853 bmp file re)
12854 (save-excursion
12855 (save-restriction
12856 (while (setq file (pop files))
12857 (if (bufferp file)
12858 (set-buffer file)
12859 (org-check-agenda-file file)
12860 (set-buffer (org-get-agenda-file-buffer file)))
12861 (widen)
12862 (setq bmp (buffer-modified-p))
12863 (org-refresh-category-properties)
12864 (setq org-todo-keywords-for-agenda
12865 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12866 (setq org-done-keywords-for-agenda
12867 (append org-done-keywords-for-agenda org-done-keywords))
12868 (setq org-todo-keyword-alist-for-agenda
12869 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12870 (setq org-tag-alist-for-agenda
12871 (append org-tag-alist-for-agenda org-tag-alist))
12873 (save-excursion
12874 (remove-text-properties (point-min) (point-max) pall)
12875 (when org-agenda-skip-archived-trees
12876 (goto-char (point-min))
12877 (while (re-search-forward rea nil t)
12878 (if (org-on-heading-p t)
12879 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12880 (goto-char (point-min))
12881 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12882 (while (re-search-forward re nil t)
12883 (add-text-properties
12884 (match-beginning 0) (org-end-of-subtree t) pc)))
12885 (set-buffer-modified-p bmp))))
12886 (setq org-todo-keyword-alist-for-agenda
12887 (org-uniquify org-todo-keyword-alist-for-agenda)
12888 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12890 ;;;; Embedded LaTeX
12892 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12893 "Keymap for the minor `org-cdlatex-mode'.")
12895 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12896 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12897 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12898 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12899 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12901 (defvar org-cdlatex-texmathp-advice-is-done nil
12902 "Flag remembering if we have applied the advice to texmathp already.")
12904 (define-minor-mode org-cdlatex-mode
12905 "Toggle the minor `org-cdlatex-mode'.
12906 This mode supports entering LaTeX environment and math in LaTeX fragments
12907 in Org-mode.
12908 \\{org-cdlatex-mode-map}"
12909 nil " OCDL" nil
12910 (when org-cdlatex-mode (require 'cdlatex))
12911 (unless org-cdlatex-texmathp-advice-is-done
12912 (setq org-cdlatex-texmathp-advice-is-done t)
12913 (defadvice texmathp (around org-math-always-on activate)
12914 "Always return t in org-mode buffers.
12915 This is because we want to insert math symbols without dollars even outside
12916 the LaTeX math segments. If Orgmode thinks that point is actually inside
12917 an embedded LaTeX fragment, let texmathp do its job.
12918 \\[org-cdlatex-mode-map]"
12919 (interactive)
12920 (let (p)
12921 (cond
12922 ((not (org-mode-p)) ad-do-it)
12923 ((eq this-command 'cdlatex-math-symbol)
12924 (setq ad-return-value t
12925 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12927 (let ((p (org-inside-LaTeX-fragment-p)))
12928 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12929 (setq ad-return-value t
12930 texmathp-why '("Org-mode embedded math" . 0))
12931 (if p ad-do-it)))))))))
12933 (defun turn-on-org-cdlatex ()
12934 "Unconditionally turn on `org-cdlatex-mode'."
12935 (org-cdlatex-mode 1))
12937 (defun org-inside-LaTeX-fragment-p ()
12938 "Test if point is inside a LaTeX fragment.
12939 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12940 sequence appearing also before point.
12941 Even though the matchers for math are configurable, this function assumes
12942 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12943 delimiters are skipped when they have been removed by customization.
12944 The return value is nil, or a cons cell with the delimiter and
12945 and the position of this delimiter.
12947 This function does a reasonably good job, but can locally be fooled by
12948 for example currency specifications. For example it will assume being in
12949 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12950 fragments that are properly closed, but during editing, we have to live
12951 with the uncertainty caused by missing closing delimiters. This function
12952 looks only before point, not after."
12953 (catch 'exit
12954 (let ((pos (point))
12955 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12956 (lim (progn
12957 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12958 (point)))
12959 dd-on str (start 0) m re)
12960 (goto-char pos)
12961 (when dodollar
12962 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12963 re (nth 1 (assoc "$" org-latex-regexps)))
12964 (while (string-match re str start)
12965 (cond
12966 ((= (match-end 0) (length str))
12967 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12968 ((= (match-end 0) (- (length str) 5))
12969 (throw 'exit nil))
12970 (t (setq start (match-end 0))))))
12971 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12972 (goto-char pos)
12973 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12974 (and (match-beginning 2) (throw 'exit nil))
12975 ;; count $$
12976 (while (re-search-backward "\\$\\$" lim t)
12977 (setq dd-on (not dd-on)))
12978 (goto-char pos)
12979 (if dd-on (cons "$$" m))))))
12982 (defun org-try-cdlatex-tab ()
12983 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12984 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12985 - inside a LaTeX fragment, or
12986 - after the first word in a line, where an abbreviation expansion could
12987 insert a LaTeX environment."
12988 (when org-cdlatex-mode
12989 (cond
12990 ((save-excursion
12991 (skip-chars-backward "a-zA-Z0-9*")
12992 (skip-chars-backward " \t")
12993 (bolp))
12994 (cdlatex-tab) t)
12995 ((org-inside-LaTeX-fragment-p)
12996 (cdlatex-tab) t)
12997 (t nil))))
12999 (defun org-cdlatex-underscore-caret (&optional arg)
13000 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13001 Revert to the normal definition outside of these fragments."
13002 (interactive "P")
13003 (if (org-inside-LaTeX-fragment-p)
13004 (call-interactively 'cdlatex-sub-superscript)
13005 (let (org-cdlatex-mode)
13006 (call-interactively (key-binding (vector last-input-event))))))
13008 (defun org-cdlatex-math-modify (&optional arg)
13009 "Execute `cdlatex-math-modify' in LaTeX fragments.
13010 Revert to the normal definition outside of these fragments."
13011 (interactive "P")
13012 (if (org-inside-LaTeX-fragment-p)
13013 (call-interactively 'cdlatex-math-modify)
13014 (let (org-cdlatex-mode)
13015 (call-interactively (key-binding (vector last-input-event))))))
13017 (defvar org-latex-fragment-image-overlays nil
13018 "List of overlays carrying the images of latex fragments.")
13019 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13021 (defun org-remove-latex-fragment-image-overlays ()
13022 "Remove all overlays with LaTeX fragment images in current buffer."
13023 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13024 (setq org-latex-fragment-image-overlays nil))
13026 (defun org-preview-latex-fragment (&optional subtree)
13027 "Preview the LaTeX fragment at point, or all locally or globally.
13028 If the cursor is in a LaTeX fragment, create the image and overlay
13029 it over the source code. If there is no fragment at point, display
13030 all fragments in the current text, from one headline to the next. With
13031 prefix SUBTREE, display all fragments in the current subtree. With a
13032 double prefix `C-u C-u', or when the cursor is before the first headline,
13033 display all fragments in the buffer.
13034 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13035 (interactive "P")
13036 (org-remove-latex-fragment-image-overlays)
13037 (save-excursion
13038 (save-restriction
13039 (let (beg end at msg)
13040 (cond
13041 ((or (equal subtree '(16))
13042 (not (save-excursion
13043 (re-search-backward (concat "^" outline-regexp) nil t))))
13044 (setq beg (point-min) end (point-max)
13045 msg "Creating images for buffer...%s"))
13046 ((equal subtree '(4))
13047 (org-back-to-heading)
13048 (setq beg (point) end (org-end-of-subtree t)
13049 msg "Creating images for subtree...%s"))
13051 (if (setq at (org-inside-LaTeX-fragment-p))
13052 (goto-char (max (point-min) (- (cdr at) 2)))
13053 (org-back-to-heading))
13054 (setq beg (point) end (progn (outline-next-heading) (point))
13055 msg (if at "Creating image...%s"
13056 "Creating images for entry...%s"))))
13057 (message msg "")
13058 (narrow-to-region beg end)
13059 (goto-char beg)
13060 (org-format-latex
13061 (concat "ltxpng/" (file-name-sans-extension
13062 (file-name-nondirectory
13063 buffer-file-name)))
13064 default-directory 'overlays msg at 'forbuffer)
13065 (message msg "done. Use `C-c C-c' to remove images.")))))
13067 (defvar org-latex-regexps
13068 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13069 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13070 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13071 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13072 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13073 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13074 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13075 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13076 "Regular expressions for matching embedded LaTeX.")
13078 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13079 "Replace LaTeX fragments with links to an image, and produce images."
13080 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13081 (let* ((prefixnodir (file-name-nondirectory prefix))
13082 (absprefix (expand-file-name prefix dir))
13083 (todir (file-name-directory absprefix))
13084 (opt org-format-latex-options)
13085 (matchers (plist-get opt :matchers))
13086 (re-list org-latex-regexps)
13087 (cnt 0) txt link beg end re e checkdir
13088 m n block linkfile movefile ov)
13089 ;; Check if there are old images files with this prefix, and remove them
13090 (when (file-directory-p todir)
13091 (mapc 'delete-file
13092 (directory-files
13093 todir 'full
13094 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13095 ;; Check the different regular expressions
13096 (while (setq e (pop re-list))
13097 (setq m (car e) re (nth 1 e) n (nth 2 e)
13098 block (if (nth 3 e) "\n\n" ""))
13099 (when (member m matchers)
13100 (goto-char (point-min))
13101 (while (re-search-forward re nil t)
13102 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13103 (not (get-text-property (match-beginning n)
13104 'org-protected)))
13105 (setq txt (match-string n)
13106 beg (match-beginning n) end (match-end n)
13107 cnt (1+ cnt)
13108 linkfile (format "%s_%04d.png" prefix cnt)
13109 movefile (format "%s_%04d.png" absprefix cnt)
13110 link (concat block "[[file:" linkfile "]]" block))
13111 (if msg (message msg cnt))
13112 (goto-char beg)
13113 (unless checkdir ; make sure the directory exists
13114 (setq checkdir t)
13115 (or (file-directory-p todir) (make-directory todir)))
13116 (org-create-formula-image
13117 txt movefile opt forbuffer)
13118 (if overlays
13119 (progn
13120 (setq ov (org-make-overlay beg end))
13121 (if (featurep 'xemacs)
13122 (progn
13123 (org-overlay-put ov 'invisible t)
13124 (org-overlay-put
13125 ov 'end-glyph
13126 (make-glyph (vector 'png :file movefile))))
13127 (org-overlay-put
13128 ov 'display
13129 (list 'image :type 'png :file movefile :ascent 'center)))
13130 (push ov org-latex-fragment-image-overlays)
13131 (goto-char end))
13132 (delete-region beg end)
13133 (insert link))))))))
13135 ;; This function borrows from Ganesh Swami's latex2png.el
13136 (defun org-create-formula-image (string tofile options buffer)
13137 (let* ((tmpdir (if (featurep 'xemacs)
13138 (temp-directory)
13139 temporary-file-directory))
13140 (texfilebase (make-temp-name
13141 (expand-file-name "orgtex" tmpdir)))
13142 (texfile (concat texfilebase ".tex"))
13143 (dvifile (concat texfilebase ".dvi"))
13144 (pngfile (concat texfilebase ".png"))
13145 (fnh (if (featurep 'xemacs)
13146 (font-height (get-face-font 'default))
13147 (face-attribute 'default :height nil)))
13148 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13149 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13150 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13151 "Black"))
13152 (bg (or (plist-get options (if buffer :background :html-background))
13153 "Transparent")))
13154 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13155 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13156 (with-temp-file texfile
13157 (insert org-format-latex-header
13158 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13159 (let ((dir default-directory))
13160 (condition-case nil
13161 (progn
13162 (cd tmpdir)
13163 (call-process "latex" nil nil nil texfile))
13164 (error nil))
13165 (cd dir))
13166 (if (not (file-exists-p dvifile))
13167 (progn (message "Failed to create dvi file from %s" texfile) nil)
13168 (condition-case nil
13169 (call-process "dvipng" nil nil nil
13170 "-E" "-fg" fg "-bg" bg
13171 "-D" dpi
13172 ;;"-x" scale "-y" scale
13173 "-T" "tight"
13174 "-o" pngfile
13175 dvifile)
13176 (error nil))
13177 (if (not (file-exists-p pngfile))
13178 (progn (message "Failed to create png file from %s" texfile) nil)
13179 ;; Use the requested file name and clean up
13180 (copy-file pngfile tofile 'replace)
13181 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13182 (delete-file (concat texfilebase e)))
13183 pngfile))))
13185 (defun org-dvipng-color (attr)
13186 "Return an rgb color specification for dvipng."
13187 (apply 'format "rgb %s %s %s"
13188 (mapcar 'org-normalize-color
13189 (color-values (face-attribute 'default attr nil)))))
13191 (defun org-normalize-color (value)
13192 "Return string to be used as color value for an RGB component."
13193 (format "%g" (/ value 65535.0)))
13195 ;;;; Key bindings
13197 ;; Make `C-c C-x' a prefix key
13198 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13200 ;; TAB key with modifiers
13201 (org-defkey org-mode-map "\C-i" 'org-cycle)
13202 (org-defkey org-mode-map [(tab)] 'org-cycle)
13203 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13204 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13205 (org-defkey org-mode-map "\M-\t" 'org-complete)
13206 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13207 ;; The following line is necessary under Suse GNU/Linux
13208 (unless (featurep 'xemacs)
13209 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13210 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13211 (define-key org-mode-map [backtab] 'org-shifttab)
13213 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13214 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13215 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13217 ;; Cursor keys with modifiers
13218 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13219 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13220 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13221 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13223 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13224 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13225 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13226 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13228 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13229 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13230 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13231 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13233 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13234 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13236 ;;; Extra keys for tty access.
13237 ;; We only set them when really needed because otherwise the
13238 ;; menus don't show the simple keys
13240 (when (or org-use-extra-keys
13241 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13242 (not window-system))
13243 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13244 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13245 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13246 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13247 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13248 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13249 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13250 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13251 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13252 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13253 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13254 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13255 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13256 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13257 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13258 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13259 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13260 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13261 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13262 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13263 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13264 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13266 ;; All the other keys
13268 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13269 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13270 (if (boundp 'narrow-map)
13271 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13272 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13273 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13274 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13275 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13276 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13277 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13278 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13279 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13280 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13281 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13282 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13283 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13284 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13285 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13286 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13287 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13288 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13289 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13290 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13291 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13292 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13293 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13294 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13295 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13296 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13297 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13298 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13299 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13300 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13301 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13302 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13303 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13304 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13305 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13306 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13307 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13308 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13309 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13310 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13311 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13312 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13313 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13314 (org-defkey org-mode-map "\C-c^" 'org-sort)
13315 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13316 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13317 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13318 (org-defkey org-mode-map "\C-m" 'org-return)
13319 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13320 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13321 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13322 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13323 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13324 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13325 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13326 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13327 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13328 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13329 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13330 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13331 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13332 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13333 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13334 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13335 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13337 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13338 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13339 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13340 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13342 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13343 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13344 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13345 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13346 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13347 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13348 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13349 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13350 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13351 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13352 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13353 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13354 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13356 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13357 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13358 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13359 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13361 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13363 (define-key org-mode-map "\C-c\C-xr" 'org-reload)
13365 (when (featurep 'xemacs)
13366 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13369 (defvar org-self-insert-command-undo-counter 0)
13371 (defvar org-table-auto-blank-field) ; defined in org-table.el
13372 (defun org-self-insert-command (N)
13373 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13374 If the cursor is in a table looking at whitespace, the whitespace is
13375 overwritten, and the table is not marked as requiring realignment."
13376 (interactive "p")
13377 (if (and
13378 (org-table-p)
13379 (progn
13380 ;; check if we blank the field, and if that triggers align
13381 (and (featurep 'org-table) org-table-auto-blank-field
13382 (member last-command
13383 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13384 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13385 ;; got extra space, this field does not determine column width
13386 (let (org-table-may-need-update) (org-table-blank-field))
13387 ;; no extra space, this field may determine column width
13388 (org-table-blank-field)))
13390 (eq N 1)
13391 (looking-at "[^|\n]* |"))
13392 (let (org-table-may-need-update)
13393 (goto-char (1- (match-end 0)))
13394 (delete-backward-char 1)
13395 (goto-char (match-beginning 0))
13396 (self-insert-command N))
13397 (setq org-table-may-need-update t)
13398 (self-insert-command N)
13399 (org-fix-tags-on-the-fly)
13400 (if org-self-insert-cluster-for-undo
13401 (if (not (eq last-command 'org-self-insert-command))
13402 (setq org-self-insert-command-undo-counter 1)
13403 (if (>= org-self-insert-command-undo-counter 20)
13404 (setq org-self-insert-command-undo-counter 1)
13405 (and (> org-self-insert-command-undo-counter 0)
13406 buffer-undo-list
13407 (not (cadr buffer-undo-list)) ; remove nil entry
13408 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13409 (setq org-self-insert-command-undo-counter
13410 (1+ org-self-insert-command-undo-counter)))))))
13412 (defun org-fix-tags-on-the-fly ()
13413 (when (and (equal (char-after (point-at-bol)) ?*)
13414 (org-on-heading-p))
13415 (org-align-tags-here org-tags-column)))
13417 (defun org-delete-backward-char (N)
13418 "Like `delete-backward-char', insert whitespace at field end in tables.
13419 When deleting backwards, in tables this function will insert whitespace in
13420 front of the next \"|\" separator, to keep the table aligned. The table will
13421 still be marked for re-alignment if the field did fill the entire column,
13422 because, in this case the deletion might narrow the column."
13423 (interactive "p")
13424 (if (and (org-table-p)
13425 (eq N 1)
13426 (string-match "|" (buffer-substring (point-at-bol) (point)))
13427 (looking-at ".*?|"))
13428 (let ((pos (point))
13429 (noalign (looking-at "[^|\n\r]* |"))
13430 (c org-table-may-need-update))
13431 (backward-delete-char N)
13432 (skip-chars-forward "^|")
13433 (insert " ")
13434 (goto-char (1- pos))
13435 ;; noalign: if there were two spaces at the end, this field
13436 ;; does not determine the width of the column.
13437 (if noalign (setq org-table-may-need-update c)))
13438 (backward-delete-char N)
13439 (org-fix-tags-on-the-fly)))
13441 (defun org-delete-char (N)
13442 "Like `delete-char', but insert whitespace at field end in tables.
13443 When deleting characters, in tables this function will insert whitespace in
13444 front of the next \"|\" separator, to keep the table aligned. The table will
13445 still be marked for re-alignment if the field did fill the entire column,
13446 because, in this case the deletion might narrow the column."
13447 (interactive "p")
13448 (if (and (org-table-p)
13449 (not (bolp))
13450 (not (= (char-after) ?|))
13451 (eq N 1))
13452 (if (looking-at ".*?|")
13453 (let ((pos (point))
13454 (noalign (looking-at "[^|\n\r]* |"))
13455 (c org-table-may-need-update))
13456 (replace-match (concat
13457 (substring (match-string 0) 1 -1)
13458 " |"))
13459 (goto-char pos)
13460 ;; noalign: if there were two spaces at the end, this field
13461 ;; does not determine the width of the column.
13462 (if noalign (setq org-table-may-need-update c)))
13463 (delete-char N))
13464 (delete-char N)
13465 (org-fix-tags-on-the-fly)))
13467 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13468 (put 'org-self-insert-command 'delete-selection t)
13469 (put 'orgtbl-self-insert-command 'delete-selection t)
13470 (put 'org-delete-char 'delete-selection 'supersede)
13471 (put 'org-delete-backward-char 'delete-selection 'supersede)
13472 (put 'org-yank 'delete-selection 'yank)
13474 ;; Make `flyspell-mode' delay after some commands
13475 (put 'org-self-insert-command 'flyspell-delayed t)
13476 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13477 (put 'org-delete-char 'flyspell-delayed t)
13478 (put 'org-delete-backward-char 'flyspell-delayed t)
13480 ;; Make pabbrev-mode expand after org-mode commands
13481 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13482 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13484 ;; How to do this: Measure non-white length of current string
13485 ;; If equal to column width, we should realign.
13487 (defun org-remap (map &rest commands)
13488 "In MAP, remap the functions given in COMMANDS.
13489 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13490 (let (new old)
13491 (while commands
13492 (setq old (pop commands) new (pop commands))
13493 (if (fboundp 'command-remapping)
13494 (org-defkey map (vector 'remap old) new)
13495 (substitute-key-definition old new map global-map)))))
13497 (when (eq org-enable-table-editor 'optimized)
13498 ;; If the user wants maximum table support, we need to hijack
13499 ;; some standard editing functions
13500 (org-remap org-mode-map
13501 'self-insert-command 'org-self-insert-command
13502 'delete-char 'org-delete-char
13503 'delete-backward-char 'org-delete-backward-char)
13504 (org-defkey org-mode-map "|" 'org-force-self-insert))
13506 (defvar org-ctrl-c-ctrl-c-hook nil
13507 "Hook for functions attaching themselves to `C-c C-c'.
13508 This can be used to add additional functionality to the C-c C-c key which
13509 executes context-dependent commands.
13510 Each function will be called with no arguments. The function must check
13511 if the context is appropriate for it to act. If yes, it should do its
13512 thing and then return a non-nil value. If the context is wrong,
13513 just do nothing.")
13515 (defvar org-metaleft-hook nil
13516 "Hook for functions attaching themselves to `M-left'.
13517 See `org-ctrl-c-ctrl-c-hook' for more information.")
13518 (defvar org-metaright-hook nil
13519 "Hook for functions attaching themselves to `M-right'.
13520 See `org-ctrl-c-ctrl-c-hook' for more information.")
13521 (defvar org-metaup-hook nil
13522 "Hook for functions attaching themselves to `M-up'.
13523 See `org-ctrl-c-ctrl-c-hook' for more information.")
13524 (defvar org-metadown-hook nil
13525 "Hook for functions attaching themselves to `M-down'.
13526 See `org-ctrl-c-ctrl-c-hook' for more information.")
13527 (defvar org-shiftmetaleft-hook nil
13528 "Hook for functions attaching themselves to `M-S-left'.
13529 See `org-ctrl-c-ctrl-c-hook' for more information.")
13530 (defvar org-shiftmetaright-hook nil
13531 "Hook for functions attaching themselves to `M-S-right'.
13532 See `org-ctrl-c-ctrl-c-hook' for more information.")
13533 (defvar org-shiftmetaup-hook nil
13534 "Hook for functions attaching themselves to `M-S-up'.
13535 See `org-ctrl-c-ctrl-c-hook' for more information.")
13536 (defvar org-shiftmetadown-hook nil
13537 "Hook for functions attaching themselves to `M-S-down'.
13538 See `org-ctrl-c-ctrl-c-hook' for more information.")
13539 (defvar org-metareturn-hook nil
13540 "Hook for functions attaching themselves to `M-RET'.
13541 See `org-ctrl-c-ctrl-c-hook' for more information.")
13543 (defun org-modifier-cursor-error ()
13544 "Throw an error, a modified cursor command was applied in wrong context."
13545 (error "This command is active in special context like tables, headlines or items"))
13547 (defun org-shiftselect-error ()
13548 "Throw an error because Shift-Cursor command was applied in wrong context."
13549 (if (and (boundp 'shift-select-mode) shift-select-mode)
13550 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13551 (error "This command works only in special context like headlines or timestamps.")))
13553 (defun org-call-for-shift-select (cmd)
13554 (let ((this-command-keys-shift-translated t))
13555 (call-interactively cmd)))
13557 (defun org-shifttab (&optional arg)
13558 "Global visibility cycling or move to previous table field.
13559 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13560 on context.
13561 See the individual commands for more information."
13562 (interactive "P")
13563 (cond
13564 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13565 ((integerp arg)
13566 (message "Content view to level: %d" arg)
13567 (org-content (prefix-numeric-value arg))
13568 (setq org-cycle-global-status 'overview))
13569 (t (call-interactively 'org-global-cycle))))
13571 (defun org-shiftmetaleft ()
13572 "Promote subtree or delete table column.
13573 Calls `org-promote-subtree', `org-outdent-item',
13574 or `org-table-delete-column', depending on context.
13575 See the individual commands for more information."
13576 (interactive)
13577 (cond
13578 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13579 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13580 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13581 ((org-at-item-p) (call-interactively 'org-outdent-item))
13582 (t (org-modifier-cursor-error))))
13584 (defun org-shiftmetaright ()
13585 "Demote subtree or insert table column.
13586 Calls `org-demote-subtree', `org-indent-item',
13587 or `org-table-insert-column', depending on context.
13588 See the individual commands for more information."
13589 (interactive)
13590 (cond
13591 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13592 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13593 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13594 ((org-at-item-p) (call-interactively 'org-indent-item))
13595 (t (org-modifier-cursor-error))))
13597 (defun org-shiftmetaup (&optional arg)
13598 "Move subtree up or kill table row.
13599 Calls `org-move-subtree-up' or `org-table-kill-row' or
13600 `org-move-item-up' depending on context. See the individual commands
13601 for more information."
13602 (interactive "P")
13603 (cond
13604 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13605 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13606 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13607 ((org-at-item-p) (call-interactively 'org-move-item-up))
13608 (t (org-modifier-cursor-error))))
13610 (defun org-shiftmetadown (&optional arg)
13611 "Move subtree down or insert table row.
13612 Calls `org-move-subtree-down' or `org-table-insert-row' or
13613 `org-move-item-down', depending on context. See the individual
13614 commands for more information."
13615 (interactive "P")
13616 (cond
13617 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13618 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13619 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13620 ((org-at-item-p) (call-interactively 'org-move-item-down))
13621 (t (org-modifier-cursor-error))))
13623 (defun org-metaleft (&optional arg)
13624 "Promote heading or move table column to left.
13625 Calls `org-do-promote' or `org-table-move-column', depending on context.
13626 With no specific context, calls the Emacs default `backward-word'.
13627 See the individual commands for more information."
13628 (interactive "P")
13629 (cond
13630 ((run-hook-with-args-until-success 'org-metaleft-hook))
13631 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13632 ((or (org-on-heading-p)
13633 (and (org-region-active-p)
13634 (save-excursion
13635 (goto-char (region-beginning))
13636 (org-on-heading-p))))
13637 (call-interactively 'org-do-promote))
13638 ((or (org-at-item-p)
13639 (and (org-region-active-p)
13640 (save-excursion
13641 (goto-char (region-beginning))
13642 (org-at-item-p))))
13643 (call-interactively 'org-outdent-item))
13644 (t (call-interactively 'backward-word))))
13646 (defun org-metaright (&optional arg)
13647 "Demote subtree or move table column to right.
13648 Calls `org-do-demote' or `org-table-move-column', depending on context.
13649 With no specific context, calls the Emacs default `forward-word'.
13650 See the individual commands for more information."
13651 (interactive "P")
13652 (cond
13653 ((run-hook-with-args-until-success 'org-metaright-hook))
13654 ((org-at-table-p) (call-interactively 'org-table-move-column))
13655 ((or (org-on-heading-p)
13656 (and (org-region-active-p)
13657 (save-excursion
13658 (goto-char (region-beginning))
13659 (org-on-heading-p))))
13660 (call-interactively 'org-do-demote))
13661 ((or (org-at-item-p)
13662 (and (org-region-active-p)
13663 (save-excursion
13664 (goto-char (region-beginning))
13665 (org-at-item-p))))
13666 (call-interactively 'org-indent-item))
13667 (t (call-interactively 'forward-word))))
13669 (defun org-metaup (&optional arg)
13670 "Move subtree up or move table row up.
13671 Calls `org-move-subtree-up' or `org-table-move-row' or
13672 `org-move-item-up', depending on context. See the individual commands
13673 for more information."
13674 (interactive "P")
13675 (cond
13676 ((run-hook-with-args-until-success 'org-metaup-hook))
13677 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13678 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13679 ((org-at-item-p) (call-interactively 'org-move-item-up))
13680 (t (transpose-lines 1) (beginning-of-line -1))))
13682 (defun org-metadown (&optional arg)
13683 "Move subtree down or move table row down.
13684 Calls `org-move-subtree-down' or `org-table-move-row' or
13685 `org-move-item-down', depending on context. See the individual
13686 commands for more information."
13687 (interactive "P")
13688 (cond
13689 ((run-hook-with-args-until-success 'org-metadown-hook))
13690 ((org-at-table-p) (call-interactively 'org-table-move-row))
13691 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13692 ((org-at-item-p) (call-interactively 'org-move-item-down))
13693 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13695 (defun org-shiftup (&optional arg)
13696 "Increase item in timestamp or increase priority of current headline.
13697 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13698 depending on context. See the individual commands for more information."
13699 (interactive "P")
13700 (cond
13701 ((and org-support-shift-select (org-region-active-p))
13702 (org-call-for-shift-select 'previous-line))
13703 ((org-at-timestamp-p t)
13704 (call-interactively (if org-edit-timestamp-down-means-later
13705 'org-timestamp-down 'org-timestamp-up)))
13706 ((and (not (eq org-support-shift-select 'always))
13707 (org-on-heading-p))
13708 (call-interactively 'org-priority-up))
13709 ((and (not org-support-shift-select) (org-at-item-p))
13710 (call-interactively 'org-previous-item))
13711 ((org-clocktable-try-shift 'up arg))
13712 (org-support-shift-select
13713 (org-call-for-shift-select 'previous-line))
13714 (t (org-shiftselect-error))))
13716 (defun org-shiftdown (&optional arg)
13717 "Decrease item in timestamp or decrease priority of current headline.
13718 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13719 depending on context. See the individual commands for more information."
13720 (interactive "P")
13721 (cond
13722 ((and org-support-shift-select (org-region-active-p))
13723 (org-call-for-shift-select 'next-line))
13724 ((org-at-timestamp-p t)
13725 (call-interactively (if org-edit-timestamp-down-means-later
13726 'org-timestamp-up 'org-timestamp-down)))
13727 ((and (not (eq org-support-shift-select 'always))
13728 (org-on-heading-p))
13729 (call-interactively 'org-priority-down))
13730 ((and (not org-support-shift-select) (org-at-item-p))
13731 (call-interactively 'org-next-item))
13732 ((org-clocktable-try-shift 'down arg))
13733 (org-support-shift-select
13734 (org-call-for-shift-select 'next-line))
13735 (t (org-shiftselect-error))))
13737 (defun org-shiftright (&optional arg)
13738 "Cycle the thing at point or in the current line, depending on context.
13739 Depending on context, this does one of the following:
13741 - switch a timestamp at point one day into the future
13742 - on a headline, switch to the next TODO keyword.
13743 - on an item, switch entire list to the next bullet type
13744 - on a property line, switch to the next allowed value
13745 - on a clocktable definition line, move time block into the future"
13746 (interactive "P")
13747 (cond
13748 ((and org-support-shift-select (org-region-active-p))
13749 (org-call-for-shift-select 'forward-char))
13750 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13751 ((and (not (eq org-support-shift-select 'always))
13752 (org-on-heading-p))
13753 (org-call-with-arg 'org-todo 'right))
13754 ((or (and org-support-shift-select
13755 (not (eq org-support-shift-select 'always))
13756 (org-at-item-bullet-p))
13757 (and (not org-support-shift-select) (org-at-item-p)))
13758 (org-call-with-arg 'org-cycle-list-bullet nil))
13759 ((and (not (eq org-support-shift-select 'always))
13760 (org-at-property-p))
13761 (call-interactively 'org-property-next-allowed-value))
13762 ((org-clocktable-try-shift 'right arg))
13763 (org-support-shift-select
13764 (org-call-for-shift-select 'forward-char))
13765 (t (org-shiftselect-error))))
13767 (defun org-shiftleft (&optional arg)
13768 "Cycle the thing at point or in the current line, depending on context.
13769 Depending on context, this does one of the following:
13771 - switch a timestamp at point one day into the past
13772 - on a headline, switch to the previous TODO keyword.
13773 - on an item, switch entire list to the previous bullet type
13774 - on a property line, switch to the previous allowed value
13775 - on a clocktable definition line, move time block into the past"
13776 (interactive "P")
13777 (cond
13778 ((and org-support-shift-select (org-region-active-p))
13779 (org-call-for-shift-select 'backward-char))
13780 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13781 ((and (not (eq org-support-shift-select 'always))
13782 (org-on-heading-p))
13783 (org-call-with-arg 'org-todo 'left))
13784 ((or (and org-support-shift-select
13785 (not (eq org-support-shift-select 'always))
13786 (org-at-item-bullet-p))
13787 (and (not org-support-shift-select) (org-at-item-p)))
13788 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13789 ((and (not (eq org-support-shift-select 'always))
13790 (org-at-property-p))
13791 (call-interactively 'org-property-previous-allowed-value))
13792 ((org-clocktable-try-shift 'left arg))
13793 (org-support-shift-select
13794 (org-call-for-shift-select 'backward-char))
13795 (t (org-shiftselect-error))))
13797 (defun org-shiftcontrolright ()
13798 "Switch to next TODO set."
13799 (interactive)
13800 (cond
13801 ((and org-support-shift-select (org-region-active-p))
13802 (org-call-for-shift-select 'forward-word))
13803 ((and (not (eq org-support-shift-select 'always))
13804 (org-on-heading-p))
13805 (org-call-with-arg 'org-todo 'nextset))
13806 (org-support-shift-select
13807 (org-call-for-shift-select 'forward-word))
13808 (t (org-shiftselect-error))))
13810 (defun org-shiftcontrolleft ()
13811 "Switch to previous TODO set."
13812 (interactive)
13813 (cond
13814 ((and org-support-shift-select (org-region-active-p))
13815 (org-call-for-shift-select 'backward-word))
13816 ((and (not (eq org-support-shift-select 'always))
13817 (org-on-heading-p))
13818 (org-call-with-arg 'org-todo 'previousset))
13819 (org-support-shift-select
13820 (org-call-for-shift-select 'backward-word))
13821 (t (org-shiftselect-error))))
13823 (defun org-ctrl-c-ret ()
13824 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13825 (interactive)
13826 (cond
13827 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13828 (t (call-interactively 'org-insert-heading))))
13830 (defun org-copy-special ()
13831 "Copy region in table or copy current subtree.
13832 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13833 See the individual commands for more information."
13834 (interactive)
13835 (call-interactively
13836 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13838 (defun org-cut-special ()
13839 "Cut region in table or cut current subtree.
13840 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13841 See the individual commands for more information."
13842 (interactive)
13843 (call-interactively
13844 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13846 (defun org-paste-special (arg)
13847 "Paste rectangular region into table, or past subtree relative to level.
13848 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13849 See the individual commands for more information."
13850 (interactive "P")
13851 (if (org-at-table-p)
13852 (org-table-paste-rectangle)
13853 (org-paste-subtree arg)))
13855 (defun org-edit-special ()
13856 "Call a special editor for the stuff at point.
13857 When at a table, call the formula editor with `org-table-edit-formulas'.
13858 When at the first line of an src example, call `org-edit-src-code'.
13859 When in an #+include line, visit the include file. Otherwise call
13860 `ffap' to visit the file at point."
13861 (interactive)
13862 (cond
13863 ((org-at-table-p)
13864 (call-interactively 'org-table-edit-formulas))
13865 ((save-excursion
13866 (beginning-of-line 1)
13867 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13868 (find-file (org-trim (match-string 1))))
13869 ((org-edit-src-code))
13870 ((org-edit-fixed-width-region))
13871 (t (call-interactively 'ffap))))
13874 (defun org-ctrl-c-ctrl-c (&optional arg)
13875 "Set tags in headline, or update according to changed information at point.
13877 This command does many different things, depending on context:
13879 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
13880 this is what we do.
13882 - If the cursor is in a headline, prompt for tags and insert them
13883 into the current line, aligned to `org-tags-column'. When called
13884 with prefix arg, realign all tags in the current buffer.
13886 - If the cursor is in one of the special #+KEYWORD lines, this
13887 triggers scanning the buffer for these lines and updating the
13888 information.
13890 - If the cursor is inside a table, realign the table. This command
13891 works even if the automatic table editor has been turned off.
13893 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13894 the entire table.
13896 - If the cursor is at a footnote reference or definition, jump to
13897 the corresponding definition or references, respectively.
13899 - If the cursor is a the beginning of a dynamic block, update it.
13901 - If the cursor is inside a table created by the table.el package,
13902 activate that table.
13904 - If the current buffer is a remember buffer, close note and file
13905 it. A prefix argument of 1 files to the default location
13906 without further interaction. A prefix argument of 2 files to
13907 the currently clocking task.
13909 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13910 links in this buffer.
13912 - If the cursor is on a numbered item in a plain list, renumber the
13913 ordered list.
13915 - If the cursor is on a checkbox, toggle it."
13916 (interactive "P")
13917 (let ((org-enable-table-editor t))
13918 (cond
13919 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13920 org-occur-highlights
13921 org-latex-fragment-image-overlays)
13922 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13923 (org-remove-occur-highlights)
13924 (org-remove-latex-fragment-image-overlays)
13925 (message "Temporary highlights/overlays removed from current buffer"))
13926 ((and (local-variable-p 'org-finish-function (current-buffer))
13927 (fboundp org-finish-function))
13928 (funcall org-finish-function))
13929 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
13930 ((org-at-property-p)
13931 (call-interactively 'org-property-action))
13932 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13933 ((org-on-heading-p) (call-interactively 'org-set-tags))
13934 ((org-at-table.el-p)
13935 (require 'table)
13936 (beginning-of-line 1)
13937 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13938 (call-interactively 'table-recognize-table))
13939 ((org-at-table-p)
13940 (org-table-maybe-eval-formula)
13941 (if arg
13942 (call-interactively 'org-table-recalculate)
13943 (org-table-maybe-recalculate-line))
13944 (call-interactively 'org-table-align))
13945 ((or (org-footnote-at-reference-p)
13946 (org-footnote-at-definition-p))
13947 (call-interactively 'org-footnote-action))
13948 ((org-at-item-checkbox-p)
13949 (call-interactively 'org-toggle-checkbox))
13950 ((org-at-item-p)
13951 (if arg
13952 (call-interactively 'org-toggle-checkbox)
13953 (call-interactively 'org-maybe-renumber-ordered-list)))
13954 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13955 ;; Dynamic block
13956 (beginning-of-line 1)
13957 (save-excursion (org-update-dblock)))
13958 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13959 (cond
13960 ((equal (match-string 1) "TBLFM")
13961 ;; Recalculate the table before this line
13962 (save-excursion
13963 (beginning-of-line 1)
13964 (skip-chars-backward " \r\n\t")
13965 (if (org-at-table-p)
13966 (org-call-with-arg 'org-table-recalculate t))))
13968 ; (org-set-regexps-and-options)
13969 ; (org-restart-font-lock)
13970 (let ((org-inhibit-startup t)) (org-mode-restart))
13971 (message "Local setup has been refreshed"))))
13972 (t (error "C-c C-c can do nothing useful at this location.")))))
13974 (defun org-mode-restart ()
13975 "Restart Org-mode, to scan again for special lines.
13976 Also updates the keyword regular expressions."
13977 (interactive)
13978 (org-mode)
13979 (message "Org-mode restarted"))
13981 (defun org-kill-note-or-show-branches ()
13982 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13983 (interactive)
13984 (if (not org-finish-function)
13985 (call-interactively 'show-branches)
13986 (let ((org-note-abort t))
13987 (funcall org-finish-function))))
13989 (defun org-return (&optional indent)
13990 "Goto next table row or insert a newline.
13991 Calls `org-table-next-row' or `newline', depending on context.
13992 See the individual commands for more information."
13993 (interactive)
13994 (cond
13995 ((bobp) (if indent (newline-and-indent) (newline)))
13996 ((org-at-table-p)
13997 (org-table-justify-field-maybe)
13998 (call-interactively 'org-table-next-row))
13999 ((and org-return-follows-link
14000 (eq (get-text-property (point) 'face) 'org-link))
14001 (call-interactively 'org-open-at-point))
14002 ((and (org-at-heading-p)
14003 (looking-at
14004 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14005 (org-show-entry)
14006 (end-of-line 1)
14007 (newline))
14008 (t (if indent (newline-and-indent) (newline)))))
14010 (defun org-return-indent ()
14011 "Goto next table row or insert a newline and indent.
14012 Calls `org-table-next-row' or `newline-and-indent', depending on
14013 context. See the individual commands for more information."
14014 (interactive)
14015 (org-return t))
14017 (defun org-ctrl-c-star ()
14018 "Compute table, or change heading status of lines.
14019 Calls `org-table-recalculate' or `org-toggle-heading',
14020 depending on context."
14021 (interactive)
14022 (cond
14023 ((org-at-table-p)
14024 (call-interactively 'org-table-recalculate))
14026 ;; Convert all lines in region to list items
14027 (call-interactively 'org-toggle-heading))))
14029 (defun org-ctrl-c-minus ()
14030 "Insert separator line in table or modify bullet status of line.
14031 Also turns a plain line or a region of lines into list items.
14032 Calls `org-table-insert-hline', `org-toggle-item', or
14033 `org-cycle-list-bullet', depending on context."
14034 (interactive)
14035 (cond
14036 ((org-at-table-p)
14037 (call-interactively 'org-table-insert-hline))
14038 ((org-region-active-p)
14039 (call-interactively 'org-toggle-item))
14040 ((org-in-item-p)
14041 (call-interactively 'org-cycle-list-bullet))
14043 (call-interactively 'org-toggle-item))))
14045 (defun org-toggle-item ()
14046 "Convert headings or normal lines to items, items to normal lines.
14047 If there is no active region, only the current line is considered.
14049 If the first line in the region is a headline, convert all headlines to items.
14051 If the first line in the region is an item, convert all items to normal lines.
14053 If the first line is normal text, add an item bullet to each line."
14054 (interactive)
14055 (let (l2 l beg end)
14056 (if (org-region-active-p)
14057 (setq beg (region-beginning) end (region-end))
14058 (setq beg (point-at-bol)
14059 end (min (1+ (point-at-eol)) (point-max))))
14060 (save-excursion
14061 (goto-char end)
14062 (setq l2 (org-current-line))
14063 (goto-char beg)
14064 (beginning-of-line 1)
14065 (setq l (1- (org-current-line)))
14066 (if (org-at-item-p)
14067 ;; We already have items, de-itemize
14068 (while (< (setq l (1+ l)) l2)
14069 (when (org-at-item-p)
14070 (goto-char (match-beginning 2))
14071 (delete-region (match-beginning 2) (match-end 2))
14072 (and (looking-at "[ \t]+") (replace-match "")))
14073 (beginning-of-line 2))
14074 (if (org-on-heading-p)
14075 ;; Headings, convert to items
14076 (while (< (setq l (1+ l)) l2)
14077 (if (looking-at org-outline-regexp)
14078 (replace-match "- " t t))
14079 (beginning-of-line 2))
14080 ;; normal lines, turn them into items
14081 (while (< (setq l (1+ l)) l2)
14082 (unless (org-at-item-p)
14083 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14084 (replace-match "\\1- \\2")))
14085 (beginning-of-line 2)))))))
14087 (defun org-toggle-heading (&optional nstars)
14088 "Convert headings to normal text, or items or text to headings.
14089 If there is no active region, only the current line is considered.
14091 If the first line is a heading, remove the stars from all headlines
14092 in the region.
14094 If the first line is a plain list item, turn all plain list items into
14095 headings.
14097 If the first line is a normal line, turn each and every line in the region
14098 into a heading.
14100 When converting a line into a heading, the number of stars is chosen
14101 such that the lines become children of the current entry. However, when
14102 a prefix argument is given, its value determines the number of stars to add."
14103 (interactive "P")
14104 (let (l2 l itemp beg end)
14105 (if (org-region-active-p)
14106 (setq beg (region-beginning) end (region-end))
14107 (setq beg (point-at-bol)
14108 end (min (1+ (point-at-eol)) (point-max))))
14109 (save-excursion
14110 (goto-char end)
14111 (setq l2 (org-current-line))
14112 (goto-char beg)
14113 (beginning-of-line 1)
14114 (setq l (1- (org-current-line)))
14115 (if (org-on-heading-p)
14116 ;; We already have headlines, de-star them
14117 (while (< (setq l (1+ l)) l2)
14118 (when (org-on-heading-p t)
14119 (and (looking-at outline-regexp) (replace-match "")))
14120 (beginning-of-line 2))
14121 (setq itemp (org-at-item-p))
14122 (let* ((stars
14123 (if nstars
14124 (make-string (prefix-numeric-value current-prefix-arg)
14126 (save-excursion
14127 (re-search-backward org-complex-heading-regexp nil t)
14128 (or (match-string 1) "*"))))
14129 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
14130 (rpl (concat stars add-stars " ")))
14131 (while (< (setq l (1+ l)) l2)
14132 (if itemp
14133 (and (org-at-item-p) (replace-match rpl t t))
14134 (unless (org-on-heading-p)
14135 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14136 (replace-match (concat rpl (match-string 2))))))
14137 (beginning-of-line 2)))))))
14139 (defun org-meta-return (&optional arg)
14140 "Insert a new heading or wrap a region in a table.
14141 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14142 See the individual commands for more information."
14143 (interactive "P")
14144 (cond
14145 ((run-hook-with-args-until-success 'org-metareturn-hook))
14146 ((org-at-table-p)
14147 (call-interactively 'org-table-wrap-region))
14148 (t (call-interactively 'org-insert-heading))))
14150 ;;; Menu entries
14152 ;; Define the Org-mode menus
14153 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14154 '("Tbl"
14155 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14156 ["Next Field" org-cycle (org-at-table-p)]
14157 ["Previous Field" org-shifttab (org-at-table-p)]
14158 ["Next Row" org-return (org-at-table-p)]
14159 "--"
14160 ["Blank Field" org-table-blank-field (org-at-table-p)]
14161 ["Edit Field" org-table-edit-field (org-at-table-p)]
14162 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14163 "--"
14164 ("Column"
14165 ["Move Column Left" org-metaleft (org-at-table-p)]
14166 ["Move Column Right" org-metaright (org-at-table-p)]
14167 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14168 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14169 ("Row"
14170 ["Move Row Up" org-metaup (org-at-table-p)]
14171 ["Move Row Down" org-metadown (org-at-table-p)]
14172 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14173 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14174 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14175 "--"
14176 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14177 ("Rectangle"
14178 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14179 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14180 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14181 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14182 "--"
14183 ("Calculate"
14184 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14185 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14186 ["Edit Formulas" org-edit-special (org-at-table-p)]
14187 "--"
14188 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14189 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14190 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14191 "--"
14192 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14193 "--"
14194 ["Sum Column/Rectangle" org-table-sum
14195 (or (org-at-table-p) (org-region-active-p))]
14196 ["Which Column?" org-table-current-column (org-at-table-p)])
14197 ["Debug Formulas"
14198 org-table-toggle-formula-debugger
14199 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14200 ["Show Col/Row Numbers"
14201 org-table-toggle-coordinate-overlays
14202 :style toggle
14203 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14204 "--"
14205 ["Create" org-table-create (and (not (org-at-table-p))
14206 org-enable-table-editor)]
14207 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14208 ["Import from File" org-table-import (not (org-at-table-p))]
14209 ["Export to File" org-table-export (org-at-table-p)]
14210 "--"
14211 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14213 (easy-menu-define org-org-menu org-mode-map "Org menu"
14214 '("Org"
14215 ("Show/Hide"
14216 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14217 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14218 ["Sparse Tree..." org-sparse-tree t]
14219 ["Reveal Context" org-reveal t]
14220 ["Show All" show-all t]
14221 "--"
14222 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14223 "--"
14224 ["New Heading" org-insert-heading t]
14225 ("Navigate Headings"
14226 ["Up" outline-up-heading t]
14227 ["Next" outline-next-visible-heading t]
14228 ["Previous" outline-previous-visible-heading t]
14229 ["Next Same Level" outline-forward-same-level t]
14230 ["Previous Same Level" outline-backward-same-level t]
14231 "--"
14232 ["Jump" org-goto t])
14233 ("Edit Structure"
14234 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14235 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14236 "--"
14237 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14238 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14239 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14240 "--"
14241 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14242 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14243 ["Demote Heading" org-metaright (not (org-at-table-p))]
14244 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14245 "--"
14246 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14247 "--"
14248 ["Convert to odd levels" org-convert-to-odd-levels t]
14249 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14250 ("Editing"
14251 ["Emphasis..." org-emphasize t]
14252 ["Edit Source Example" org-edit-special t]
14253 "--"
14254 ["Footnote new/jump" org-footnote-action t]
14255 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14256 ("Archive"
14257 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14258 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14259 ; :active t :keys "C-u C-c C-x C-a"]
14260 ["Sparse trees open ARCHIVE trees"
14261 (setq org-sparse-tree-open-archived-trees
14262 (not org-sparse-tree-open-archived-trees))
14263 :style toggle :selected org-sparse-tree-open-archived-trees]
14264 ["Cycling opens ARCHIVE trees"
14265 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14266 :style toggle :selected org-cycle-open-archived-trees]
14267 "--"
14268 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14269 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14270 ; ["Check and Move Children" (org-archive-subtree '(4))
14271 ; :active t :keys "C-u C-c C-x C-s"]
14273 "--"
14274 ("TODO Lists"
14275 ["TODO/DONE/-" org-todo t]
14276 ("Select keyword"
14277 ["Next keyword" org-shiftright (org-on-heading-p)]
14278 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14279 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14280 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14281 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14282 ["Show TODO Tree" org-show-todo-tree t]
14283 ["Global TODO list" org-todo-list t]
14284 "--"
14285 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14286 :selected org-enforce-todo-dependencies :style toggle :active t]
14287 "Settings for tree at point"
14288 ["Do Children sequentially" org-toggle-ordered-property :style radio
14289 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14290 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14291 ["Do Children parallel" org-toggle-ordered-property :style radio
14292 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14293 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14294 "--"
14295 ["Set Priority" org-priority t]
14296 ["Priority Up" org-shiftup t]
14297 ["Priority Down" org-shiftdown t])
14298 ("TAGS and Properties"
14299 ["Set Tags" org-set-tags-command t]
14300 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14301 "--"
14302 ["Set property" org-set-property t]
14303 ["Column view of properties" org-columns t]
14304 ["Insert Column View DBlock" org-insert-columns-dblock t])
14305 ("Dates and Scheduling"
14306 ["Timestamp" org-time-stamp t]
14307 ["Timestamp (inactive)" org-time-stamp-inactive t]
14308 ("Change Date"
14309 ["1 Day Later" org-shiftright t]
14310 ["1 Day Earlier" org-shiftleft t]
14311 ["1 ... Later" org-shiftup t]
14312 ["1 ... Earlier" org-shiftdown t])
14313 ["Compute Time Range" org-evaluate-time-range t]
14314 ["Schedule Item" org-schedule t]
14315 ["Deadline" org-deadline t]
14316 "--"
14317 ["Custom time format" org-toggle-time-stamp-overlays
14318 :style radio :selected org-display-custom-times]
14319 "--"
14320 ["Goto Calendar" org-goto-calendar t]
14321 ["Date from Calendar" org-date-from-calendar t]
14322 "--"
14323 ["Start/Restart Timer" org-timer-start t]
14324 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14325 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14326 ["Insert Timer String" org-timer t]
14327 ["Insert Timer Item" org-timer-item t])
14328 ("Logging work"
14329 ["Clock in" org-clock-in t]
14330 ["Clock out" org-clock-out t]
14331 ["Clock cancel" org-clock-cancel t]
14332 ["Goto running clock" org-clock-goto t]
14333 ["Display times" org-clock-display t]
14334 ["Create clock table" org-clock-report t]
14335 "--"
14336 ["Record DONE time"
14337 (progn (setq org-log-done (not org-log-done))
14338 (message "Switching to %s will %s record a timestamp"
14339 (car org-done-keywords)
14340 (if org-log-done "automatically" "not")))
14341 :style toggle :selected org-log-done])
14342 "--"
14343 ["Agenda Command..." org-agenda t]
14344 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14345 ("File List for Agenda")
14346 ("Special views current file"
14347 ["TODO Tree" org-show-todo-tree t]
14348 ["Check Deadlines" org-check-deadlines t]
14349 ["Timeline" org-timeline t]
14350 ["Tags/Property tree" org-match-sparse-tree t])
14351 "--"
14352 ("Hyperlinks"
14353 ["Store Link (Global)" org-store-link t]
14354 ["Insert Link" org-insert-link t]
14355 ["Follow Link" org-open-at-point t]
14356 "--"
14357 ["Next link" org-next-link t]
14358 ["Previous link" org-previous-link t]
14359 "--"
14360 ["Descriptive Links"
14361 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14362 :style radio
14363 :selected (member '(org-link) buffer-invisibility-spec)]
14364 ["Literal Links"
14365 (progn
14366 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14367 :style radio
14368 :selected (not (member '(org-link) buffer-invisibility-spec))])
14369 "--"
14370 ["Export/Publish..." org-export t]
14371 ("LaTeX"
14372 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14373 :selected org-cdlatex-mode]
14374 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14375 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14376 ["Modify math symbol" org-cdlatex-math-modify
14377 (org-inside-LaTeX-fragment-p)]
14378 ["Export LaTeX fragments as images"
14379 (if (featurep 'org-exp)
14380 (setq org-export-with-LaTeX-fragments
14381 (not org-export-with-LaTeX-fragments))
14382 (require 'org-exp))
14383 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14384 org-export-with-LaTeX-fragments)])
14385 "--"
14386 ("Documentation"
14387 ["Show Version" org-version t]
14388 ["Info Documentation" org-info t])
14389 ("Customize"
14390 ["Browse Org Group" org-customize t]
14391 "--"
14392 ["Expand This Menu" org-create-customize-menu
14393 (fboundp 'customize-menu-create)])
14394 "--"
14395 ("Refresh/Reload"
14396 ["Refresh setup current buffer" org-mode-restart t]
14397 ["Reload Org (after update)" org-reload t]
14398 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14401 (defun org-info (&optional node)
14402 "Read documentation for Org-mode in the info system.
14403 With optional NODE, go directly to that node."
14404 (interactive)
14405 (info (format "(org)%s" (or node ""))))
14407 (defun org-install-agenda-files-menu ()
14408 (let ((bl (buffer-list)))
14409 (save-excursion
14410 (while bl
14411 (set-buffer (pop bl))
14412 (if (org-mode-p) (setq bl nil)))
14413 (when (org-mode-p)
14414 (easy-menu-change
14415 '("Org") "File List for Agenda"
14416 (append
14417 (list
14418 ["Edit File List" (org-edit-agenda-file-list) t]
14419 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14420 ["Remove Current File from List" org-remove-file t]
14421 ["Cycle through agenda files" org-cycle-agenda-files t]
14422 ["Occur in all agenda files" org-occur-in-agenda-files t]
14423 "--")
14424 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14426 ;;;; Documentation
14428 ;;;###autoload
14429 (defun org-require-autoloaded-modules ()
14430 (interactive)
14431 (mapc 'require
14432 '(org-agenda org-archive org-attach org-clock org-colview
14433 org-exp org-id org-export-latex org-publish
14434 org-remember org-table org-timer)))
14436 ;;;###autoload
14437 (defun org-reload (&optional uncompiled)
14438 "Reload all org lisp files.
14439 With prefix arg UNCOMPILED, load the uncompiled versions."
14440 (interactive "P")
14441 (require 'find-func)
14442 (let* ((dir (file-name-directory (find-library-name "org")))
14443 (files (directory-files dir t "\\.el\\'"))
14444 (remove-re (concat (if (featurep 'xemacs)
14445 "org-colview" "org-colview-xemacs")
14446 "\\'")))
14447 (setq files (mapcar 'file-name-sans-extension files))
14448 (setq files (mapcar
14449 (lambda (x) (if (string-match remove-re x) nil x))
14450 files))
14451 (setq files (delq nil files))
14452 (mapc
14453 (lambda (f)
14454 (if (and (not uncompiled)
14455 (file-exists-p (concat f ".elc")))
14456 (load (concat f ".elc") nil nil t)
14457 (load (concat f ".el") nil nil t)))
14458 files)))
14460 ;;;###autoload
14461 (defun org-customize ()
14462 "Call the customize function with org as argument."
14463 (interactive)
14464 (org-load-modules-maybe)
14465 (org-require-autoloaded-modules)
14466 (customize-browse 'org))
14468 (defun org-create-customize-menu ()
14469 "Create a full customization menu for Org-mode, insert it into the menu."
14470 (interactive)
14471 (org-load-modules-maybe)
14472 (org-require-autoloaded-modules)
14473 (if (fboundp 'customize-menu-create)
14474 (progn
14475 (easy-menu-change
14476 '("Org") "Customize"
14477 `(["Browse Org group" org-customize t]
14478 "--"
14479 ,(customize-menu-create 'org)
14480 ["Set" Custom-set t]
14481 ["Save" Custom-save t]
14482 ["Reset to Current" Custom-reset-current t]
14483 ["Reset to Saved" Custom-reset-saved t]
14484 ["Reset to Standard Settings" Custom-reset-standard t]))
14485 (message "\"Org\"-menu now contains full customization menu"))
14486 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14488 ;;;; Miscellaneous stuff
14490 ;;; Generally useful functions
14492 (defun org-find-text-property-in-string (prop s)
14493 "Return the first non-nil value of property PROP in string S."
14494 (or (get-text-property 0 prop s)
14495 (get-text-property (or (next-single-property-change 0 prop s) 0)
14496 prop s)))
14498 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14499 "Display the given MESSAGE as a warning."
14500 (if (fboundp 'display-warning)
14501 (display-warning 'org message
14502 (if (featurep 'xemacs)
14503 'warning
14504 :warning))
14505 (let ((buf (get-buffer-create "*Org warnings*")))
14506 (with-current-buffer buf
14507 (goto-char (point-max))
14508 (insert "Warning (Org): " message)
14509 (unless (bolp)
14510 (newline)))
14511 (display-buffer buf)
14512 (sit-for 0))))
14514 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14515 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14516 (if (and marker (marker-buffer marker)
14517 (buffer-live-p (marker-buffer marker)))
14518 (progn
14519 (switch-to-buffer (marker-buffer marker))
14520 (if (or (> marker (point-max)) (< marker (point-min)))
14521 (widen))
14522 (goto-char marker)
14523 (org-show-context 'org-goto))
14524 (if bookmark
14525 (bookmark-jump bookmark)
14526 (error "Cannot find location"))))
14528 (defun org-quote-csv-field (s)
14529 "Quote field for inclusion in CSV material."
14530 (if (string-match "[\",]" s)
14531 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14534 (defun org-plist-delete (plist property)
14535 "Delete PROPERTY from PLIST.
14536 This is in contrast to merely setting it to 0."
14537 (let (p)
14538 (while plist
14539 (if (not (eq property (car plist)))
14540 (setq p (plist-put p (car plist) (nth 1 plist))))
14541 (setq plist (cddr plist)))
14544 (defun org-force-self-insert (N)
14545 "Needed to enforce self-insert under remapping."
14546 (interactive "p")
14547 (self-insert-command N))
14549 (defun org-string-width (s)
14550 "Compute width of string, ignoring invisible characters.
14551 This ignores character with invisibility property `org-link', and also
14552 characters with property `org-cwidth', because these will become invisible
14553 upon the next fontification round."
14554 (let (b l)
14555 (when (or (eq t buffer-invisibility-spec)
14556 (assq 'org-link buffer-invisibility-spec))
14557 (while (setq b (text-property-any 0 (length s)
14558 'invisible 'org-link s))
14559 (setq s (concat (substring s 0 b)
14560 (substring s (or (next-single-property-change
14561 b 'invisible s) (length s)))))))
14562 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14563 (setq s (concat (substring s 0 b)
14564 (substring s (or (next-single-property-change
14565 b 'org-cwidth s) (length s))))))
14566 (setq l (string-width s) b -1)
14567 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14568 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14571 (defun org-get-indentation (&optional line)
14572 "Get the indentation of the current line, interpreting tabs.
14573 When LINE is given, assume it represents a line and compute its indentation."
14574 (if line
14575 (if (string-match "^ *" (org-remove-tabs line))
14576 (match-end 0))
14577 (save-excursion
14578 (beginning-of-line 1)
14579 (skip-chars-forward " \t")
14580 (current-column))))
14582 (defun org-remove-tabs (s &optional width)
14583 "Replace tabulators in S with spaces.
14584 Assumes that s is a single line, starting in column 0."
14585 (setq width (or width tab-width))
14586 (while (string-match "\t" s)
14587 (setq s (replace-match
14588 (make-string
14589 (- (* width (/ (+ (match-beginning 0) width) width))
14590 (match-beginning 0)) ?\ )
14591 t t s)))
14594 (defun org-fix-indentation (line ind)
14595 "Fix indentation in LINE.
14596 IND is a cons cell with target and minimum indentation.
14597 If the current indentation in LINE is smaller than the minimum,
14598 leave it alone. If it is larger than ind, set it to the target."
14599 (let* ((l (org-remove-tabs line))
14600 (i (org-get-indentation l))
14601 (i1 (car ind)) (i2 (cdr ind)))
14602 (if (>= i i2) (setq l (substring line i2)))
14603 (if (> i1 0)
14604 (concat (make-string i1 ?\ ) l)
14605 l)))
14607 (defun org-base-buffer (buffer)
14608 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14609 (if (not buffer)
14610 buffer
14611 (or (buffer-base-buffer buffer)
14612 buffer)))
14614 (defun org-trim (s)
14615 "Remove whitespace at beginning and end of string."
14616 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14617 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14620 (defun org-wrap (string &optional width lines)
14621 "Wrap string to either a number of lines, or a width in characters.
14622 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14623 that costs. If there is a word longer than WIDTH, the text is actually
14624 wrapped to the length of that word.
14625 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14626 many lines, whatever width that takes.
14627 The return value is a list of lines, without newlines at the end."
14628 (let* ((words (org-split-string string "[ \t\n]+"))
14629 (maxword (apply 'max (mapcar 'org-string-width words)))
14630 w ll)
14631 (cond (width
14632 (org-do-wrap words (max maxword width)))
14633 (lines
14634 (setq w maxword)
14635 (setq ll (org-do-wrap words maxword))
14636 (if (<= (length ll) lines)
14638 (setq ll words)
14639 (while (> (length ll) lines)
14640 (setq w (1+ w))
14641 (setq ll (org-do-wrap words w)))
14642 ll))
14643 (t (error "Cannot wrap this")))))
14645 (defun org-do-wrap (words width)
14646 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14647 (let (lines line)
14648 (while words
14649 (setq line (pop words))
14650 (while (and words (< (+ (length line) (length (car words))) width))
14651 (setq line (concat line " " (pop words))))
14652 (setq lines (push line lines)))
14653 (nreverse lines)))
14655 (defun org-split-string (string &optional separators)
14656 "Splits STRING into substrings at SEPARATORS.
14657 No empty strings are returned if there are matches at the beginning
14658 and end of string."
14659 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14660 (start 0)
14661 notfirst
14662 (list nil))
14663 (while (and (string-match rexp string
14664 (if (and notfirst
14665 (= start (match-beginning 0))
14666 (< start (length string)))
14667 (1+ start) start))
14668 (< (match-beginning 0) (length string)))
14669 (setq notfirst t)
14670 (or (eq (match-beginning 0) 0)
14671 (and (eq (match-beginning 0) (match-end 0))
14672 (eq (match-beginning 0) start))
14673 (setq list
14674 (cons (substring string start (match-beginning 0))
14675 list)))
14676 (setq start (match-end 0)))
14677 (or (eq start (length string))
14678 (setq list
14679 (cons (substring string start)
14680 list)))
14681 (nreverse list)))
14683 (defun org-uuidgen-p (s)
14684 "Is S an ID created by UUIDGEN?"
14685 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
14687 (defun org-context ()
14688 "Return a list of contexts of the current cursor position.
14689 If several contexts apply, all are returned.
14690 Each context entry is a list with a symbol naming the context, and
14691 two positions indicating start and end of the context. Possible
14692 contexts are:
14694 :headline anywhere in a headline
14695 :headline-stars on the leading stars in a headline
14696 :todo-keyword on a TODO keyword (including DONE) in a headline
14697 :tags on the TAGS in a headline
14698 :priority on the priority cookie in a headline
14699 :item on the first line of a plain list item
14700 :item-bullet on the bullet/number of a plain list item
14701 :checkbox on the checkbox in a plain list item
14702 :table in an org-mode table
14703 :table-special on a special filed in a table
14704 :table-table in a table.el table
14705 :link on a hyperlink
14706 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14707 :target on a <<target>>
14708 :radio-target on a <<<radio-target>>>
14709 :latex-fragment on a LaTeX fragment
14710 :latex-preview on a LaTeX fragment with overlayed preview image
14712 This function expects the position to be visible because it uses font-lock
14713 faces as a help to recognize the following contexts: :table-special, :link,
14714 and :keyword."
14715 (let* ((f (get-text-property (point) 'face))
14716 (faces (if (listp f) f (list f)))
14717 (p (point)) clist o)
14718 ;; First the large context
14719 (cond
14720 ((org-on-heading-p t)
14721 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14722 (when (progn
14723 (beginning-of-line 1)
14724 (looking-at org-todo-line-tags-regexp))
14725 (push (org-point-in-group p 1 :headline-stars) clist)
14726 (push (org-point-in-group p 2 :todo-keyword) clist)
14727 (push (org-point-in-group p 4 :tags) clist))
14728 (goto-char p)
14729 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14730 (if (looking-at "\\[#[A-Z0-9]\\]")
14731 (push (org-point-in-group p 0 :priority) clist)))
14733 ((org-at-item-p)
14734 (push (org-point-in-group p 2 :item-bullet) clist)
14735 (push (list :item (point-at-bol)
14736 (save-excursion (org-end-of-item) (point)))
14737 clist)
14738 (and (org-at-item-checkbox-p)
14739 (push (org-point-in-group p 0 :checkbox) clist)))
14741 ((org-at-table-p)
14742 (push (list :table (org-table-begin) (org-table-end)) clist)
14743 (if (memq 'org-formula faces)
14744 (push (list :table-special
14745 (previous-single-property-change p 'face)
14746 (next-single-property-change p 'face)) clist)))
14747 ((org-at-table-p 'any)
14748 (push (list :table-table) clist)))
14749 (goto-char p)
14751 ;; Now the small context
14752 (cond
14753 ((org-at-timestamp-p)
14754 (push (org-point-in-group p 0 :timestamp) clist))
14755 ((memq 'org-link faces)
14756 (push (list :link
14757 (previous-single-property-change p 'face)
14758 (next-single-property-change p 'face)) clist))
14759 ((memq 'org-special-keyword faces)
14760 (push (list :keyword
14761 (previous-single-property-change p 'face)
14762 (next-single-property-change p 'face)) clist))
14763 ((org-on-target-p)
14764 (push (org-point-in-group p 0 :target) clist)
14765 (goto-char (1- (match-beginning 0)))
14766 (if (looking-at org-radio-target-regexp)
14767 (push (org-point-in-group p 0 :radio-target) clist))
14768 (goto-char p))
14769 ((setq o (car (delq nil
14770 (mapcar
14771 (lambda (x)
14772 (if (memq x org-latex-fragment-image-overlays) x))
14773 (org-overlays-at (point))))))
14774 (push (list :latex-fragment
14775 (org-overlay-start o) (org-overlay-end o)) clist)
14776 (push (list :latex-preview
14777 (org-overlay-start o) (org-overlay-end o)) clist))
14778 ((org-inside-LaTeX-fragment-p)
14779 ;; FIXME: positions wrong.
14780 (push (list :latex-fragment (point) (point)) clist)))
14782 (setq clist (nreverse (delq nil clist)))
14783 clist))
14785 ;; FIXME: Compare with at-regexp-p Do we need both?
14786 (defun org-in-regexp (re &optional nlines visually)
14787 "Check if point is inside a match of regexp.
14788 Normally only the current line is checked, but you can include NLINES extra
14789 lines both before and after point into the search.
14790 If VISUALLY is set, require that the cursor is not after the match but
14791 really on, so that the block visually is on the match."
14792 (catch 'exit
14793 (let ((pos (point))
14794 (eol (point-at-eol (+ 1 (or nlines 0))))
14795 (inc (if visually 1 0)))
14796 (save-excursion
14797 (beginning-of-line (- 1 (or nlines 0)))
14798 (while (re-search-forward re eol t)
14799 (if (and (<= (match-beginning 0) pos)
14800 (>= (+ inc (match-end 0)) pos))
14801 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14803 (defun org-at-regexp-p (regexp)
14804 "Is point inside a match of REGEXP in the current line?"
14805 (catch 'exit
14806 (save-excursion
14807 (let ((pos (point)) (end (point-at-eol)))
14808 (beginning-of-line 1)
14809 (while (re-search-forward regexp end t)
14810 (if (and (<= (match-beginning 0) pos)
14811 (>= (match-end 0) pos))
14812 (throw 'exit t)))
14813 nil))))
14815 (defun org-occur-in-agenda-files (regexp &optional nlines)
14816 "Call `multi-occur' with buffers for all agenda files."
14817 (interactive "sOrg-files matching: \np")
14818 (let* ((files (org-agenda-files))
14819 (tnames (mapcar 'file-truename files))
14820 (extra org-agenda-text-search-extra-files)
14822 (when (eq (car extra) 'agenda-archives)
14823 (setq extra (cdr extra))
14824 (setq files (org-add-archive-files files)))
14825 (while (setq f (pop extra))
14826 (unless (member (file-truename f) tnames)
14827 (add-to-list 'files f 'append)
14828 (add-to-list 'tnames (file-truename f) 'append)))
14829 (multi-occur
14830 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14831 regexp)))
14833 (if (boundp 'occur-mode-find-occurrence-hook)
14834 ;; Emacs 23
14835 (add-hook 'occur-mode-find-occurrence-hook
14836 (lambda ()
14837 (when (org-mode-p)
14838 (org-reveal))))
14839 ;; Emacs 22
14840 (defadvice occur-mode-goto-occurrence
14841 (after org-occur-reveal activate)
14842 (and (org-mode-p) (org-reveal)))
14843 (defadvice occur-mode-goto-occurrence-other-window
14844 (after org-occur-reveal activate)
14845 (and (org-mode-p) (org-reveal)))
14846 (defadvice occur-mode-display-occurrence
14847 (after org-occur-reveal activate)
14848 (when (org-mode-p)
14849 (let ((pos (occur-mode-find-occurrence)))
14850 (with-current-buffer (marker-buffer pos)
14851 (save-excursion
14852 (goto-char pos)
14853 (org-reveal)))))))
14855 (defun org-uniquify (list)
14856 "Remove duplicate elements from LIST."
14857 (let (res)
14858 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14859 res))
14861 (defun org-delete-all (elts list)
14862 "Remove all elements in ELTS from LIST."
14863 (while elts
14864 (setq list (delete (pop elts) list)))
14865 list)
14867 (defun org-back-over-empty-lines ()
14868 "Move backwards over whitespace, to the beginning of the first empty line.
14869 Returns the number of empty lines passed."
14870 (let ((pos (point)))
14871 (skip-chars-backward " \t\n\r")
14872 (beginning-of-line 2)
14873 (goto-char (min (point) pos))
14874 (count-lines (point) pos)))
14876 (defun org-skip-whitespace ()
14877 (skip-chars-forward " \t\n\r"))
14879 (defun org-point-in-group (point group &optional context)
14880 "Check if POINT is in match-group GROUP.
14881 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14882 match. If the match group does ot exist or point is not inside it,
14883 return nil."
14884 (and (match-beginning group)
14885 (>= point (match-beginning group))
14886 (<= point (match-end group))
14887 (if context
14888 (list context (match-beginning group) (match-end group))
14889 t)))
14891 (defun org-switch-to-buffer-other-window (&rest args)
14892 "Switch to buffer in a second window on the current frame.
14893 In particular, do not allow pop-up frames."
14894 (let (pop-up-frames special-display-buffer-names special-display-regexps
14895 special-display-function)
14896 (apply 'switch-to-buffer-other-window args)))
14898 (defun org-combine-plists (&rest plists)
14899 "Create a single property list from all plists in PLISTS.
14900 The process starts by copying the first list, and then setting properties
14901 from the other lists. Settings in the last list are the most significant
14902 ones and overrule settings in the other lists."
14903 (let ((rtn (copy-sequence (pop plists)))
14904 p v ls)
14905 (while plists
14906 (setq ls (pop plists))
14907 (while ls
14908 (setq p (pop ls) v (pop ls))
14909 (setq rtn (plist-put rtn p v))))
14910 rtn))
14912 (defun org-move-line-down (arg)
14913 "Move the current line down. With prefix argument, move it past ARG lines."
14914 (interactive "p")
14915 (let ((col (current-column))
14916 beg end pos)
14917 (beginning-of-line 1) (setq beg (point))
14918 (beginning-of-line 2) (setq end (point))
14919 (beginning-of-line (+ 1 arg))
14920 (setq pos (move-marker (make-marker) (point)))
14921 (insert (delete-and-extract-region beg end))
14922 (goto-char pos)
14923 (org-move-to-column col)))
14925 (defun org-move-line-up (arg)
14926 "Move the current line up. With prefix argument, move it past ARG lines."
14927 (interactive "p")
14928 (let ((col (current-column))
14929 beg end pos)
14930 (beginning-of-line 1) (setq beg (point))
14931 (beginning-of-line 2) (setq end (point))
14932 (beginning-of-line (- arg))
14933 (setq pos (move-marker (make-marker) (point)))
14934 (insert (delete-and-extract-region beg end))
14935 (goto-char pos)
14936 (org-move-to-column col)))
14938 (defun org-replace-escapes (string table)
14939 "Replace %-escapes in STRING with values in TABLE.
14940 TABLE is an association list with keys like \"%a\" and string values.
14941 The sequences in STRING may contain normal field width and padding information,
14942 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14943 so values can contain further %-escapes if they are define later in TABLE."
14944 (let ((case-fold-search nil)
14945 e re rpl)
14946 (while (setq e (pop table))
14947 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14948 (while (string-match re string)
14949 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14950 (cdr e)))
14951 (setq string (replace-match rpl t t string))))
14952 string))
14955 (defun org-sublist (list start end)
14956 "Return a section of LIST, from START to END.
14957 Counting starts at 1."
14958 (let (rtn (c start))
14959 (setq list (nthcdr (1- start) list))
14960 (while (and list (<= c end))
14961 (push (pop list) rtn)
14962 (setq c (1+ c)))
14963 (nreverse rtn)))
14965 (defun org-find-base-buffer-visiting (file)
14966 "Like `find-buffer-visiting' but alway return the base buffer and
14967 not an indirect buffer."
14968 (let ((buf (find-buffer-visiting file)))
14969 (if buf
14970 (or (buffer-base-buffer buf) buf)
14971 nil)))
14973 (defun org-image-file-name-regexp (&optional extensions)
14974 "Return regexp matching the file names of images.
14975 If EXTENSIONS is given, only match these."
14976 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14977 (image-file-name-regexp)
14978 (let ((image-file-name-extensions
14979 (or extensions
14980 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14981 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14982 (concat "\\."
14983 (regexp-opt (nconc (mapcar 'upcase
14984 image-file-name-extensions)
14985 image-file-name-extensions)
14987 "\\'"))))
14989 (defun org-file-image-p (file &optional extensions)
14990 "Return non-nil if FILE is an image."
14991 (save-match-data
14992 (string-match (org-image-file-name-regexp extensions) file)))
14994 (defun org-get-cursor-date ()
14995 "Return the date at cursor in as a time.
14996 This works in the calendar and in the agenda, anywhere else it just
14997 returns the current time."
14998 (let (date day defd)
14999 (cond
15000 ((eq major-mode 'calendar-mode)
15001 (setq date (calendar-cursor-to-date)
15002 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15003 ((eq major-mode 'org-agenda-mode)
15004 (setq day (get-text-property (point) 'day))
15005 (if day
15006 (setq date (calendar-gregorian-from-absolute day)
15007 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15008 (nth 2 date))))))
15009 (or defd (current-time))))
15011 (defvar org-agenda-action-marker (make-marker)
15012 "Marker pointing to the entry for the next agenda action.")
15014 (defun org-mark-entry-for-agenda-action ()
15015 "Mark the current entry as target of an agenda action.
15016 Agenda actions are actions executed from the agenda with the key `k',
15017 which make use of the date at the cursor."
15018 (interactive)
15019 (move-marker org-agenda-action-marker
15020 (save-excursion (org-back-to-heading t) (point))
15021 (current-buffer))
15022 (message
15023 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15025 ;;; Paragraph filling stuff.
15026 ;; We want this to be just right, so use the full arsenal.
15028 (defun org-indent-line-function ()
15029 "Indent line like previous, but further if previous was headline or item."
15030 (interactive)
15031 (let* ((pos (point))
15032 (itemp (org-at-item-p))
15033 (org-drawer-regexp (or org-drawer-regexp "\000"))
15034 column bpos bcol tpos tcol bullet btype bullet-type)
15035 ;; Find the previous relevant line
15036 (beginning-of-line 1)
15037 (cond
15038 ((looking-at "#") (setq column 0))
15039 ((looking-at "\\*+ ") (setq column 0))
15040 ((and (looking-at "[ \t]*:END:")
15041 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15042 (save-excursion
15043 (goto-char (1- (match-beginning 1)))
15044 (setq column (current-column))))
15046 (beginning-of-line 0)
15047 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15048 (not (looking-at "[ \t]*:END:"))
15049 (not (looking-at org-drawer-regexp)))
15050 (beginning-of-line 0))
15051 (cond
15052 ((looking-at "\\*+[ \t]+")
15053 (if (not org-adapt-indentation)
15054 (setq column 0)
15055 (goto-char (match-end 0))
15056 (setq column (current-column))))
15057 ((looking-at org-drawer-regexp)
15058 (goto-char (1- (match-beginning 1)))
15059 (setq column (current-column)))
15060 ((looking-at "\\([ \t]*\\):END:")
15061 (goto-char (match-end 1))
15062 (setq column (current-column)))
15063 ((org-in-item-p)
15064 (org-beginning-of-item)
15065 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15066 (setq bpos (match-beginning 1) tpos (match-end 0)
15067 bcol (progn (goto-char bpos) (current-column))
15068 tcol (progn (goto-char tpos) (current-column))
15069 bullet (match-string 1)
15070 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15071 (if (> tcol (+ bcol org-description-max-indent))
15072 (setq tcol (+ bcol 5)))
15073 (if (not itemp)
15074 (setq column tcol)
15075 (goto-char pos)
15076 (beginning-of-line 1)
15077 (if (looking-at "\\S-")
15078 (progn
15079 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15080 (setq bullet (match-string 1)
15081 btype (if (string-match "[0-9]" bullet) "n" bullet))
15082 (setq column (if (equal btype bullet-type) bcol tcol)))
15083 (setq column (org-get-indentation)))))
15084 (t (setq column (org-get-indentation))))))
15085 (goto-char pos)
15086 (if (<= (current-column) (current-indentation))
15087 (org-indent-line-to column)
15088 (save-excursion (org-indent-line-to column)))
15089 (setq column (current-column))
15090 (beginning-of-line 1)
15091 (if (looking-at
15092 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15093 (replace-match (concat "\\1" (format org-property-format
15094 (match-string 2) (match-string 3)))
15095 t nil))
15096 (org-move-to-column column)))
15098 (defun org-set-autofill-regexps ()
15099 (interactive)
15100 ;; In the paragraph separator we include headlines, because filling
15101 ;; text in a line directly attached to a headline would otherwise
15102 ;; fill the headline as well.
15103 (org-set-local 'comment-start-skip "^#+[ \t]*")
15104 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15105 ;; The paragraph starter includes hand-formatted lists.
15106 (org-set-local 'paragraph-start
15107 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15108 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15109 ;; But only if the user has not turned off tables or fixed-width regions
15110 (org-set-local
15111 'auto-fill-inhibit-regexp
15112 (concat "\\*+ \\|#\\+"
15113 "\\|[ \t]*" org-keyword-time-regexp
15114 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15115 (concat
15116 "\\|[ \t]*["
15117 (if org-enable-table-editor "|" "")
15118 (if org-enable-fixed-width-editor ":" "")
15119 "]"))))
15120 ;; We use our own fill-paragraph function, to make sure that tables
15121 ;; and fixed-width regions are not wrapped. That function will pass
15122 ;; through to `fill-paragraph' when appropriate.
15123 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15124 ; Adaptive filling: To get full control, first make sure that
15125 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15126 (org-set-local 'adaptive-fill-regexp "\000")
15127 (org-set-local 'adaptive-fill-function
15128 'org-adaptive-fill-function)
15129 (org-set-local
15130 'align-mode-rules-list
15131 '((org-in-buffer-settings
15132 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15133 (modes . '(org-mode))))))
15135 (defun org-fill-paragraph (&optional justify)
15136 "Re-align a table, pass through to fill-paragraph if no table."
15137 (let ((table-p (org-at-table-p))
15138 (table.el-p (org-at-table.el-p)))
15139 (cond ((and (equal (char-after (point-at-bol)) ?*)
15140 (save-excursion (goto-char (point-at-bol))
15141 (looking-at outline-regexp)))
15142 t) ; skip headlines
15143 (table.el-p t) ; skip table.el tables
15144 (table-p (org-table-align) t) ; align org-mode tables
15145 (t nil)))) ; call paragraph-fill
15147 ;; For reference, this is the default value of adaptive-fill-regexp
15148 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15150 (defun org-adaptive-fill-function ()
15151 "Return a fill prefix for org-mode files.
15152 In particular, this makes sure hanging paragraphs for hand-formatted lists
15153 work correctly."
15154 (cond ((looking-at "#[ \t]+")
15155 (match-string 0))
15156 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15157 (save-excursion
15158 (if (> (match-end 1) (+ (match-beginning 1)
15159 org-description-max-indent))
15160 (goto-char (+ (match-beginning 1) 5))
15161 (goto-char (match-end 0)))
15162 (make-string (current-column) ?\ )))
15163 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15164 (save-excursion
15165 (goto-char (match-end 0))
15166 (make-string (current-column) ?\ )))
15167 (t nil)))
15169 ;;; Other stuff.
15171 (defun org-toggle-fixed-width-section (arg)
15172 "Toggle the fixed-width export.
15173 If there is no active region, the QUOTE keyword at the current headline is
15174 inserted or removed. When present, it causes the text between this headline
15175 and the next to be exported as fixed-width text, and unmodified.
15176 If there is an active region, this command adds or removes a colon as the
15177 first character of this line. If the first character of a line is a colon,
15178 this line is also exported in fixed-width font."
15179 (interactive "P")
15180 (let* ((cc 0)
15181 (regionp (org-region-active-p))
15182 (beg (if regionp (region-beginning) (point)))
15183 (end (if regionp (region-end)))
15184 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15185 (case-fold-search nil)
15186 (re "[ \t]*\\(:\\)")
15187 off)
15188 (if regionp
15189 (save-excursion
15190 (goto-char beg)
15191 (setq cc (current-column))
15192 (beginning-of-line 1)
15193 (setq off (looking-at re))
15194 (while (> nlines 0)
15195 (setq nlines (1- nlines))
15196 (beginning-of-line 1)
15197 (cond
15198 (arg
15199 (org-move-to-column cc t)
15200 (insert ":\n")
15201 (forward-line -1))
15202 ((and off (looking-at re))
15203 (replace-match "" t t nil 1))
15204 ((not off) (org-move-to-column cc t) (insert ":")))
15205 (forward-line 1)))
15206 (save-excursion
15207 (org-back-to-heading)
15208 (if (looking-at (concat outline-regexp
15209 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15210 (replace-match "" t t nil 1)
15211 (if (looking-at outline-regexp)
15212 (progn
15213 (goto-char (match-end 0))
15214 (insert org-quote-string " "))))))))
15216 ;;;; Functions extending outline functionality
15218 (defun org-beginning-of-line (&optional arg)
15219 "Go to the beginning of the current line. If that is invisible, continue
15220 to a visible line beginning. This makes the function of C-a more intuitive.
15221 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15222 first attempt, and only move to after the tags when the cursor is already
15223 beyond the end of the headline."
15224 (interactive "P")
15225 (let ((pos (point))
15226 (special (if (consp org-special-ctrl-a/e)
15227 (car org-special-ctrl-a/e)
15228 org-special-ctrl-a/e))
15229 refpos)
15230 (beginning-of-line 1)
15231 (if (and arg (fboundp 'move-beginning-of-line))
15232 (call-interactively 'move-beginning-of-line)
15233 (if (bobp)
15235 (backward-char 1)
15236 (if (org-invisible-p)
15237 (while (and (not (bobp)) (org-invisible-p))
15238 (backward-char 1)
15239 (beginning-of-line 1))
15240 (forward-char 1))))
15241 (when special
15242 (cond
15243 ((and (looking-at org-complex-heading-regexp)
15244 (= (char-after (match-end 1)) ?\ ))
15245 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15246 (point-at-eol)))
15247 (goto-char
15248 (if (eq special t)
15249 (cond ((> pos refpos) refpos)
15250 ((= pos (point)) refpos)
15251 (t (point)))
15252 (cond ((> pos (point)) (point))
15253 ((not (eq last-command this-command)) (point))
15254 (t refpos)))))
15255 ((org-at-item-p)
15256 (goto-char
15257 (if (eq special t)
15258 (cond ((> pos (match-end 4)) (match-end 4))
15259 ((= pos (point)) (match-end 4))
15260 (t (point)))
15261 (cond ((> pos (point)) (point))
15262 ((not (eq last-command this-command)) (point))
15263 (t (match-end 4))))))))
15264 (org-no-warnings
15265 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15267 (defun org-end-of-line (&optional arg)
15268 "Go to the end of the line.
15269 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15270 first attempt, and only move to after the tags when the cursor is already
15271 beyond the end of the headline."
15272 (interactive "P")
15273 (let ((special (if (consp org-special-ctrl-a/e)
15274 (cdr org-special-ctrl-a/e)
15275 org-special-ctrl-a/e)))
15276 (if (or (not special)
15277 (not (org-on-heading-p))
15278 arg)
15279 (call-interactively (if (fboundp 'move-end-of-line)
15280 'move-end-of-line
15281 'end-of-line))
15282 (let ((pos (point)))
15283 (beginning-of-line 1)
15284 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15285 (if (eq special t)
15286 (if (or (< pos (match-beginning 1))
15287 (= pos (match-end 0)))
15288 (goto-char (match-beginning 1))
15289 (goto-char (match-end 0)))
15290 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15291 (goto-char (match-end 0))
15292 (goto-char (match-beginning 1))))
15293 (call-interactively (if (fboundp 'move-end-of-line)
15294 'move-end-of-line
15295 'end-of-line)))))
15296 (org-no-warnings
15297 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15299 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15300 (define-key org-mode-map "\C-e" 'org-end-of-line)
15302 (defun org-kill-line (&optional arg)
15303 "Kill line, to tags or end of line."
15304 (interactive "P")
15305 (cond
15306 ((or (not org-special-ctrl-k)
15307 (bolp)
15308 (not (org-on-heading-p)))
15309 (call-interactively 'kill-line))
15310 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15311 (kill-region (point) (match-beginning 1))
15312 (org-set-tags nil t))
15313 (t (kill-region (point) (point-at-eol)))))
15315 (define-key org-mode-map "\C-k" 'org-kill-line)
15317 (defun org-yank (&optional arg)
15318 "Yank. If the kill is a subtree, treat it specially.
15319 This command will look at the current kill and check if is a single
15320 subtree, or a series of subtrees[1]. If it passes the test, and if the
15321 cursor is at the beginning of a line or after the stars of a currently
15322 empty headline, then the yank is handled specially. How exactly depends
15323 on the value of the following variables, both set by default.
15325 org-yank-folded-subtrees
15326 When set, the subtree(s) will be folded after insertion, but only
15327 if doing so would now swallow text after the yanked text.
15329 org-yank-adjusted-subtrees
15330 When set, the subtree will be promoted or demoted in order to
15331 fit into the local outline tree structure, which means that the level
15332 will be adjusted so that it becomes the smaller one of the two
15333 *visible* surrounding headings.
15335 Any prefix to this command will cause `yank' to be called directly with
15336 no special treatment. In particular, a simple `C-u' prefix will just
15337 plainly yank the text as it is.
15339 \[1] Basically, the test checks if the first non-white line is a heading
15340 and if there are no other headings with fewer stars."
15341 (interactive "P")
15342 (setq this-command 'yank)
15343 (if arg
15344 (call-interactively 'yank)
15345 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15346 (and (org-kill-is-subtree-p)
15347 (or (bolp)
15348 (and (looking-at "[ \t]*$")
15349 (string-match
15350 "\\`\\*+\\'"
15351 (buffer-substring (point-at-bol) (point)))))))
15352 swallowp)
15353 (cond
15354 ((and subtreep org-yank-folded-subtrees)
15355 (let ((beg (point))
15356 end)
15357 (if (and subtreep org-yank-adjusted-subtrees)
15358 (org-paste-subtree nil nil 'for-yank)
15359 (call-interactively 'yank))
15360 (setq end (point))
15361 (goto-char beg)
15362 (when (and (bolp) subtreep
15363 (not (setq swallowp
15364 (org-yank-folding-would-swallow-text beg end))))
15365 (or (looking-at outline-regexp)
15366 (re-search-forward (concat "^" outline-regexp) end t))
15367 (while (and (< (point) end) (looking-at outline-regexp))
15368 (hide-subtree)
15369 (org-cycle-show-empty-lines 'folded)
15370 (condition-case nil
15371 (outline-forward-same-level 1)
15372 (error (goto-char end)))))
15373 (when swallowp
15374 (message
15375 "Yanked text not folded because that would swallow text"))
15376 (goto-char end)
15377 (skip-chars-forward " \t\n\r")
15378 (beginning-of-line 1)
15379 (push-mark beg 'nomsg)))
15380 ((and subtreep org-yank-adjusted-subtrees)
15381 (let ((beg (point-at-bol)))
15382 (org-paste-subtree nil nil 'for-yank)
15383 (push-mark beg 'nomsg)))
15385 (call-interactively 'yank))))))
15387 (defun org-yank-folding-would-swallow-text (beg end)
15388 "Would hide-subtree at BEG swallow any text after END?"
15389 (let (level)
15390 (save-excursion
15391 (goto-char beg)
15392 (when (or (looking-at outline-regexp)
15393 (re-search-forward (concat "^" outline-regexp) end t))
15394 (setq level (org-outline-level)))
15395 (goto-char end)
15396 (skip-chars-forward " \t\r\n\v\f")
15397 (if (or (eobp)
15398 (and (bolp) (looking-at org-outline-regexp)
15399 (<= (org-outline-level) level)))
15400 nil ; Nothing would be swallowed
15401 t)))) ; something would swallow
15403 (define-key org-mode-map "\C-y" 'org-yank)
15405 (defun org-invisible-p ()
15406 "Check if point is at a character currently not visible."
15407 ;; Early versions of noutline don't have `outline-invisible-p'.
15408 (if (fboundp 'outline-invisible-p)
15409 (outline-invisible-p)
15410 (get-char-property (point) 'invisible)))
15412 (defun org-invisible-p2 ()
15413 "Check if point is at a character currently not visible."
15414 (save-excursion
15415 (if (and (eolp) (not (bobp))) (backward-char 1))
15416 ;; Early versions of noutline don't have `outline-invisible-p'.
15417 (if (fboundp 'outline-invisible-p)
15418 (outline-invisible-p)
15419 (get-char-property (point) 'invisible))))
15421 (defun org-back-to-heading (&optional invisible-ok)
15422 "Call `outline-back-to-heading', but provide a better error message."
15423 (condition-case nil
15424 (outline-back-to-heading invisible-ok)
15425 (error (error "Before first headline at position %d in buffer %s"
15426 (point) (current-buffer)))))
15428 (defun org-before-first-heading-p ()
15429 "Before first heading?"
15430 (save-excursion
15431 (null (re-search-backward "^\\*+ " nil t))))
15433 (defalias 'org-on-heading-p 'outline-on-heading-p)
15434 (defalias 'org-at-heading-p 'outline-on-heading-p)
15435 (defun org-at-heading-or-item-p ()
15436 (or (org-on-heading-p) (org-at-item-p)))
15438 (defun org-on-target-p ()
15439 (or (org-in-regexp org-radio-target-regexp)
15440 (org-in-regexp org-target-regexp)))
15442 (defun org-up-heading-all (arg)
15443 "Move to the heading line of which the present line is a subheading.
15444 This function considers both visible and invisible heading lines.
15445 With argument, move up ARG levels."
15446 (if (fboundp 'outline-up-heading-all)
15447 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15448 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15450 (defun org-up-heading-safe ()
15451 "Move to the heading line of which the present line is a subheading.
15452 This version will not throw an error. It will return the level of the
15453 headline found, or nil if no higher level is found."
15454 (let (start-level re)
15455 (org-back-to-heading t)
15456 (setq start-level (funcall outline-level))
15457 (if (equal start-level 1)
15459 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15460 (if (re-search-backward re nil t)
15461 (funcall outline-level)))))
15463 (defun org-first-sibling-p ()
15464 "Is this heading the first child of its parents?"
15465 (interactive)
15466 (let ((re (concat "^" outline-regexp))
15467 level l)
15468 (unless (org-at-heading-p t)
15469 (error "Not at a heading"))
15470 (setq level (funcall outline-level))
15471 (save-excursion
15472 (if (not (re-search-backward re nil t))
15474 (setq l (funcall outline-level))
15475 (< l level)))))
15477 (defun org-goto-sibling (&optional previous)
15478 "Goto the next sibling, even if it is invisible.
15479 When PREVIOUS is set, go to the previous sibling instead. Returns t
15480 when a sibling was found. When none is found, return nil and don't
15481 move point."
15482 (let ((fun (if previous 're-search-backward 're-search-forward))
15483 (pos (point))
15484 (re (concat "^" outline-regexp))
15485 level l)
15486 (when (condition-case nil (org-back-to-heading t) (error nil))
15487 (setq level (funcall outline-level))
15488 (catch 'exit
15489 (or previous (forward-char 1))
15490 (while (funcall fun re nil t)
15491 (setq l (funcall outline-level))
15492 (when (< l level) (goto-char pos) (throw 'exit nil))
15493 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15494 (goto-char pos)
15495 nil))))
15497 (defun org-show-siblings ()
15498 "Show all siblings of the current headline."
15499 (save-excursion
15500 (while (org-goto-sibling) (org-flag-heading nil)))
15501 (save-excursion
15502 (while (org-goto-sibling 'previous)
15503 (org-flag-heading nil))))
15505 (defun org-show-hidden-entry ()
15506 "Show an entry where even the heading is hidden."
15507 (save-excursion
15508 (org-show-entry)))
15510 (defun org-flag-heading (flag &optional entry)
15511 "Flag the current heading. FLAG non-nil means make invisible.
15512 When ENTRY is non-nil, show the entire entry."
15513 (save-excursion
15514 (org-back-to-heading t)
15515 ;; Check if we should show the entire entry
15516 (if entry
15517 (progn
15518 (org-show-entry)
15519 (save-excursion
15520 (and (outline-next-heading)
15521 (org-flag-heading nil))))
15522 (outline-flag-region (max (point-min) (1- (point)))
15523 (save-excursion (outline-end-of-heading) (point))
15524 flag))))
15526 (defun org-forward-same-level (arg)
15527 "Move forward to the ARG'th subheading at same level as this one.
15528 Stop at the first and last subheadings of a superior heading.
15529 This is like outline-forward-same-level, but invisible headings are ok."
15530 (interactive "p")
15531 (org-back-to-heading t)
15532 (while (> arg 0)
15533 (let ((point-to-move-to (save-excursion
15534 (org-get-next-sibling))))
15535 (if point-to-move-to
15536 (progn
15537 (goto-char point-to-move-to)
15538 (setq arg (1- arg)))
15539 (progn
15540 (setq arg 0)
15541 (error "No following same-level heading"))))))
15543 (defun org-get-next-sibling ()
15544 "Move to next heading of the same level, and return point.
15545 If there is no such heading, return nil.
15546 This is like outline-next-sibling, but invisible headings are ok."
15547 (let ((level (funcall outline-level)))
15548 (outline-next-heading)
15549 (while (and (not (eobp)) (> (funcall outline-level) level))
15550 (outline-next-heading))
15551 (if (or (eobp) (< (funcall outline-level) level))
15553 (point))))
15555 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15556 ;; This is an exact copy of the original function, but it uses
15557 ;; `org-back-to-heading', to make it work also in invisible
15558 ;; trees. And is uses an invisible-OK argument.
15559 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15560 (org-back-to-heading invisible-OK)
15561 (let ((first t)
15562 (level (funcall outline-level)))
15563 (while (and (not (eobp))
15564 (or first (> (funcall outline-level) level)))
15565 (setq first nil)
15566 (outline-next-heading))
15567 (unless to-heading
15568 (if (memq (preceding-char) '(?\n ?\^M))
15569 (progn
15570 ;; Go to end of line before heading
15571 (forward-char -1)
15572 (if (memq (preceding-char) '(?\n ?\^M))
15573 ;; leave blank line before heading
15574 (forward-char -1))))))
15575 (point))
15577 (defun org-show-subtree ()
15578 "Show everything after this heading at deeper levels."
15579 (outline-flag-region
15580 (point)
15581 (save-excursion
15582 (outline-end-of-subtree) (outline-next-heading) (point))
15583 nil))
15585 (defun org-show-entry ()
15586 "Show the body directly following this heading.
15587 Show the heading too, if it is currently invisible."
15588 (interactive)
15589 (save-excursion
15590 (condition-case nil
15591 (progn
15592 (org-back-to-heading t)
15593 (outline-flag-region
15594 (max (point-min) (1- (point)))
15595 (save-excursion
15596 (if (re-search-forward
15597 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15598 (match-beginning 1)
15599 (point-max)))
15600 nil))
15601 (error nil))))
15603 (defun org-make-options-regexp (kwds &optional extra)
15604 "Make a regular expression for keyword lines."
15605 (concat
15607 "#?[ \t]*\\+\\("
15608 (mapconcat 'regexp-quote kwds "\\|")
15609 (if extra (concat "\\|" extra))
15610 "\\):[ \t]*"
15611 "\\(.+\\)"))
15613 ;; Make isearch reveal the necessary context
15614 (defun org-isearch-end ()
15615 "Reveal context after isearch exits."
15616 (when isearch-success ; only if search was successful
15617 (if (featurep 'xemacs)
15618 ;; Under XEmacs, the hook is run in the correct place,
15619 ;; we directly show the context.
15620 (org-show-context 'isearch)
15621 ;; In Emacs the hook runs *before* restoring the overlays.
15622 ;; So we have to use a one-time post-command-hook to do this.
15623 ;; (Emacs 22 has a special variable, see function `org-mode')
15624 (unless (and (boundp 'isearch-mode-end-hook-quit)
15625 isearch-mode-end-hook-quit)
15626 ;; Only when the isearch was not quitted.
15627 (org-add-hook 'post-command-hook 'org-isearch-post-command
15628 'append 'local)))))
15630 (defun org-isearch-post-command ()
15631 "Remove self from hook, and show context."
15632 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15633 (org-show-context 'isearch))
15636 ;;;; Integration with and fixes for other packages
15638 ;;; Imenu support
15640 (defvar org-imenu-markers nil
15641 "All markers currently used by Imenu.")
15642 (make-variable-buffer-local 'org-imenu-markers)
15644 (defun org-imenu-new-marker (&optional pos)
15645 "Return a new marker for use by Imenu, and remember the marker."
15646 (let ((m (make-marker)))
15647 (move-marker m (or pos (point)))
15648 (push m org-imenu-markers)
15651 (defun org-imenu-get-tree ()
15652 "Produce the index for Imenu."
15653 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15654 (setq org-imenu-markers nil)
15655 (let* ((n org-imenu-depth)
15656 (re (concat "^" outline-regexp))
15657 (subs (make-vector (1+ n) nil))
15658 (last-level 0)
15659 m level head)
15660 (save-excursion
15661 (save-restriction
15662 (widen)
15663 (goto-char (point-max))
15664 (while (re-search-backward re nil t)
15665 (setq level (org-reduced-level (funcall outline-level)))
15666 (when (<= level n)
15667 (looking-at org-complex-heading-regexp)
15668 (setq head (org-link-display-format
15669 (org-match-string-no-properties 4))
15670 m (org-imenu-new-marker))
15671 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15672 (if (>= level last-level)
15673 (push (cons head m) (aref subs level))
15674 (push (cons head (aref subs (1+ level))) (aref subs level))
15675 (loop for i from (1+ level) to n do (aset subs i nil)))
15676 (setq last-level level)))))
15677 (aref subs 1)))
15679 (eval-after-load "imenu"
15680 '(progn
15681 (add-hook 'imenu-after-jump-hook
15682 (lambda ()
15683 (if (eq major-mode 'org-mode)
15684 (org-show-context 'org-goto))))))
15686 (defun org-link-display-format (link)
15687 "Replace a link with either the description, or the link target
15688 if no description is present"
15689 (save-match-data
15690 (if (string-match org-bracket-link-analytic-regexp link)
15691 (replace-match (or (match-string 5 link)
15692 (concat (match-string 1 link)
15693 (match-string 3 link)))
15694 nil nil link)
15695 link)))
15697 ;; Speedbar support
15699 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15700 "Overlay marking the agenda restriction line in speedbar.")
15701 (org-overlay-put org-speedbar-restriction-lock-overlay
15702 'face 'org-agenda-restriction-lock)
15703 (org-overlay-put org-speedbar-restriction-lock-overlay
15704 'help-echo "Agendas are currently limited to this item.")
15705 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15707 (defun org-speedbar-set-agenda-restriction ()
15708 "Restrict future agenda commands to the location at point in speedbar.
15709 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15710 (interactive)
15711 (require 'org-agenda)
15712 (let (p m tp np dir txt)
15713 (cond
15714 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15715 'org-imenu t))
15716 (setq m (get-text-property p 'org-imenu-marker))
15717 (save-excursion
15718 (save-restriction
15719 (set-buffer (marker-buffer m))
15720 (goto-char m)
15721 (org-agenda-set-restriction-lock 'subtree))))
15722 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15723 'speedbar-function 'speedbar-find-file))
15724 (setq tp (previous-single-property-change
15725 (1+ p) 'speedbar-function)
15726 np (next-single-property-change
15727 tp 'speedbar-function)
15728 dir (speedbar-line-directory)
15729 txt (buffer-substring-no-properties (or tp (point-min))
15730 (or np (point-max))))
15731 (save-excursion
15732 (save-restriction
15733 (set-buffer (find-file-noselect
15734 (let ((default-directory dir))
15735 (expand-file-name txt))))
15736 (unless (org-mode-p)
15737 (error "Cannot restrict to non-Org-mode file"))
15738 (org-agenda-set-restriction-lock 'file))))
15739 (t (error "Don't know how to restrict Org-mode's agenda")))
15740 (org-move-overlay org-speedbar-restriction-lock-overlay
15741 (point-at-bol) (point-at-eol))
15742 (setq current-prefix-arg nil)
15743 (org-agenda-maybe-redo)))
15745 (eval-after-load "speedbar"
15746 '(progn
15747 (speedbar-add-supported-extension ".org")
15748 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15749 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15750 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15751 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15752 (add-hook 'speedbar-visiting-tag-hook
15753 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15756 ;;; Fixes and Hacks for problems with other packages
15758 ;; Make flyspell not check words in links, to not mess up our keymap
15759 (defun org-mode-flyspell-verify ()
15760 "Don't let flyspell put overlays at active buttons."
15761 (not (get-text-property (point) 'keymap)))
15763 ;; Make `bookmark-jump' show the jump location if it was hidden.
15764 (eval-after-load "bookmark"
15765 '(if (boundp 'bookmark-after-jump-hook)
15766 ;; We can use the hook
15767 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15768 ;; Hook not available, use advice
15769 (defadvice bookmark-jump (after org-make-visible activate)
15770 "Make the position visible."
15771 (org-bookmark-jump-unhide))))
15773 ;; Make sure saveplace show the location if it was hidden
15774 (eval-after-load "saveplace"
15775 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15776 "Make the position visible."
15777 (org-bookmark-jump-unhide)))
15779 (defun org-bookmark-jump-unhide ()
15780 "Unhide the current position, to show the bookmark location."
15781 (and (org-mode-p)
15782 (or (org-invisible-p)
15783 (save-excursion (goto-char (max (point-min) (1- (point))))
15784 (org-invisible-p)))
15785 (org-show-context 'bookmark-jump)))
15787 ;; Make session.el ignore our circular variable
15788 (eval-after-load "session"
15789 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15791 ;;;; Experimental code
15793 (defun org-closed-in-range ()
15794 "Sparse tree of items closed in a certain time range.
15795 Still experimental, may disappear in the future."
15796 (interactive)
15797 ;; Get the time interval from the user.
15798 (let* ((time1 (time-to-seconds
15799 (org-read-date nil 'to-time nil "Starting date: ")))
15800 (time2 (time-to-seconds
15801 (org-read-date nil 'to-time nil "End date:")))
15802 ;; callback function
15803 (callback (lambda ()
15804 (let ((time
15805 (time-to-seconds
15806 (apply 'encode-time
15807 (org-parse-time-string
15808 (match-string 1))))))
15809 ;; check if time in interval
15810 (and (>= time time1) (<= time time2))))))
15811 ;; make tree, check each match with the callback
15812 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15815 ;;;; Finish up
15817 (provide 'org)
15819 (run-hooks 'org-load-hook)
15821 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15823 ;;; org.el ends here