Bugfix: Swapping the last two subtrees in a file.
[org-mode.git] / lisp / org.el
blobaf700f623d2c10cef4a69b1900d09733628bf6e5
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.24trans
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.24trans"
98 "The version number of the file org.el.")
100 (defun org-version (&optional here)
101 "Show the org-mode version in the echo area.
102 With prefix arg HERE, insert it at point."
103 (interactive "P")
104 (let ((version (format "Org-mode version %s" org-version)))
105 (message version)
106 (if here
107 (insert version))))
109 ;;; Compatibility constants
111 ;;; The custom variables
113 (defgroup org nil
114 "Outline-based notes management and organizer."
115 :tag "Org"
116 :group 'outlines
117 :group 'hypermedia
118 :group 'calendar)
120 (defcustom org-load-hook nil
121 "Hook that is run after org.el has been loaded."
122 :group 'org
123 :type 'hook)
125 (defvar org-modules) ; defined below
126 (defvar org-modules-loaded nil
127 "Have the modules been loaded already?")
129 (defun org-load-modules-maybe (&optional force)
130 "Load all extensions listed in `org-modules'."
131 (when (or force (not org-modules-loaded))
132 (mapc (lambda (ext)
133 (condition-case nil (require ext)
134 (error (message "Problems while trying to load feature `%s'" ext))))
135 org-modules)
136 (setq org-modules-loaded t)))
138 (defun org-set-modules (var value)
139 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
140 (set var value)
141 (when (featurep 'org)
142 (org-load-modules-maybe 'force)))
144 (when (org-bound-and-true-p org-modules)
145 (let ((a (member 'org-infojs org-modules)))
146 (and a (setcar a 'org-jsinfo))))
148 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
149 "Modules that should always be loaded together with org.el.
150 If a description starts with <C>, the file is not part of Emacs
151 and loading it will require that you have downloaded and properly installed
152 the org-mode distribution.
154 You can also use this system to load external packages (i.e. neither Org
155 core modules, not modules from the CONTRIB directory). Just add symbols
156 to the end of the list. If the package is called org-xyz.el, then you need
157 to add the symbol `xyz', and the package must have a call to
159 (provide 'org-xyz)"
160 :group 'org
161 :set 'org-set-modules
162 :type
163 '(set :greedy t
164 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
165 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
166 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
167 (const :tag " id: Global IDs for identifying entries" org-id)
168 (const :tag " info: Links to Info nodes" org-info)
169 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
170 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
171 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
172 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
173 (const :tag " mew Links to Mew folders/messages" org-mew)
174 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
175 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
176 (const :tag " vm: Links to VM folders/messages" org-vm)
177 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
178 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
179 (const :tag " mouse: Additional mouse support" org-mouse)
181 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
182 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
183 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
184 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
185 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
186 (const :tag "C collector: Collect properties into tables" org-collector)
187 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
188 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
189 (const :tag "C eval: Include command output as text" org-eval)
190 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
191 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
192 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
193 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
194 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
195 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
196 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
197 (const :tag "C mtags: Support for muse-like tags" org-mtags)
198 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
199 (const :tag "C R: Computation using the R language" org-R)
200 (const :tag "C registry: A registry for Org links" org-registry)
201 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
202 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
203 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
204 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
205 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
207 (defcustom org-support-shift-select nil
208 "Non-nil means, make shift-cursor commands select text when possible.
210 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
211 selecting a region, or enlarge thusly regions started in this way.
212 In Org-mode, in special contexts, these same keys are used for other
213 purposes, important enough to compete with shift selection. Org tries
214 to balance these needs by supporting `shift-select-mode' outside these
215 special contexts, under control of this variable.
217 The default of this variable is nil, to avoid confusing behavior. Shifted
218 cursor keys will then execute Org commands in the following contexts:
219 - on a headline, changing TODO state (left/right) and priority (up/down)
220 - on a time stamp, changing the time
221 - in a plain list item, changing the bullet type
222 - in a property definition line, switching between allowed values
223 - in the BEGIN line of a clock table (changing the time block).
224 Outside these contexts, the commands will throw an error.
226 When this variable is t and the cursor is not in a special context,
227 Org-mode will support shift-selection for making and enlarging regions.
228 To make this more effective, the bullet cycling will no longer happen
229 anywhere in an item line, but only if the cursor is exactly on the bullet.
231 If you set this variable to the symbol `always', then the keys
232 will not be special in headlines, property lines, and item lines, to make
233 shift selection work there as well. If this is what you want, you can
234 use the following alternative commands: `C-c C-t' and `C-c ,' to
235 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
236 TODO sets, `C-c -' to cycle item bullet types, and properties can be
237 edited by hand or in column view.
239 However, when the cursor is on a timestamp, shift-cursor commands
240 will still edit the time stamp - this is just too good to give up.
242 XEmacs user should have this variable set to nil, because shift-select-mode
243 is Emacs 23 only."
244 :group 'org
245 :type '(choice
246 (const :tag "Never" nil)
247 (const :tag "When outside special context" t)
248 (const :tag "Everywhere except timestamps" always)))
250 (defgroup org-startup nil
251 "Options concerning startup of Org-mode."
252 :tag "Org Startup"
253 :group 'org)
255 (defcustom org-startup-folded t
256 "Non-nil means, entering Org-mode will switch to OVERVIEW.
257 This can also be configured on a per-file basis by adding one of
258 the following lines anywhere in the buffer:
260 #+STARTUP: fold
261 #+STARTUP: nofold
262 #+STARTUP: content"
263 :group 'org-startup
264 :type '(choice
265 (const :tag "nofold: show all" nil)
266 (const :tag "fold: overview" t)
267 (const :tag "content: all headlines" content)))
269 (defcustom org-startup-truncated t
270 "Non-nil means, entering Org-mode will set `truncate-lines'.
271 This is useful since some lines containing links can be very long and
272 uninteresting. Also tables look terrible when wrapped."
273 :group 'org-startup
274 :type 'boolean)
276 (defcustom org-startup-align-all-tables nil
277 "Non-nil means, align all tables when visiting a file.
278 This is useful when the column width in tables is forced with <N> cookies
279 in table fields. Such tables will look correct only after the first re-align.
280 This can also be configured on a per-file basis by adding one of
281 the following lines anywhere in the buffer:
282 #+STARTUP: align
283 #+STARTUP: noalign"
284 :group 'org-startup
285 :type 'boolean)
287 (defcustom org-insert-mode-line-in-empty-file nil
288 "Non-nil means insert the first line setting Org-mode in empty files.
289 When the function `org-mode' is called interactively in an empty file, this
290 normally means that the file name does not automatically trigger Org-mode.
291 To ensure that the file will always be in Org-mode in the future, a
292 line enforcing Org-mode will be inserted into the buffer, if this option
293 has been set."
294 :group 'org-startup
295 :type 'boolean)
297 (defcustom org-replace-disputed-keys nil
298 "Non-nil means use alternative key bindings for some keys.
299 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
300 These keys are also used by other packages like shift-selection-mode'
301 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
302 If you want to use Org-mode together with one of these other modes,
303 or more generally if you would like to move some Org-mode commands to
304 other keys, set this variable and configure the keys with the variable
305 `org-disputed-keys'.
307 This option is only relevant at load-time of Org-mode, and must be set
308 *before* org.el is loaded. Changing it requires a restart of Emacs to
309 become effective."
310 :group 'org-startup
311 :type 'boolean)
313 (defcustom org-use-extra-keys nil
314 "Non-nil means use extra key sequence definitions for certain
315 commands. This happens automatically if you run XEmacs or if
316 window-system is nil. This variable lets you do the same
317 manually. You must set it before loading org.
319 Example: on Carbon Emacs 22 running graphically, with an external
320 keyboard on a Powerbook, the default way of setting M-left might
321 not work for either Alt or ESC. Setting this variable will make
322 it work for ESC."
323 :group 'org-startup
324 :type 'boolean)
326 (if (fboundp 'defvaralias)
327 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
329 (defcustom org-disputed-keys
330 '(([(shift up)] . [(meta p)])
331 ([(shift down)] . [(meta n)])
332 ([(shift left)] . [(meta -)])
333 ([(shift right)] . [(meta +)])
334 ([(control shift right)] . [(meta shift +)])
335 ([(control shift left)] . [(meta shift -)]))
336 "Keys for which Org-mode and other modes compete.
337 This is an alist, cars are the default keys, second element specifies
338 the alternative to use when `org-replace-disputed-keys' is t.
340 Keys can be specified in any syntax supported by `define-key'.
341 The value of this option takes effect only at Org-mode's startup,
342 therefore you'll have to restart Emacs to apply it after changing."
343 :group 'org-startup
344 :type 'alist)
346 (defun org-key (key)
347 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
348 Or return the original if not disputed."
349 (if org-replace-disputed-keys
350 (let* ((nkey (key-description key))
351 (x (org-find-if (lambda (x)
352 (equal (key-description (car x)) nkey))
353 org-disputed-keys)))
354 (if x (cdr x) key))
355 key))
357 (defun org-find-if (predicate seq)
358 (catch 'exit
359 (while seq
360 (if (funcall predicate (car seq))
361 (throw 'exit (car seq))
362 (pop seq)))))
364 (defun org-defkey (keymap key def)
365 "Define a key, possibly translated, as returned by `org-key'."
366 (define-key keymap (org-key key) def))
368 (defcustom org-ellipsis nil
369 "The ellipsis to use in the Org-mode outline.
370 When nil, just use the standard three dots. When a string, use that instead,
371 When a face, use the standard 3 dots, but with the specified face.
372 The change affects only Org-mode (which will then use its own display table).
373 Changing this requires executing `M-x org-mode' in a buffer to become
374 effective."
375 :group 'org-startup
376 :type '(choice (const :tag "Default" nil)
377 (face :tag "Face" :value org-warning)
378 (string :tag "String" :value "...#")))
380 (defvar org-display-table nil
381 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
383 (defgroup org-keywords nil
384 "Keywords in Org-mode."
385 :tag "Org Keywords"
386 :group 'org)
388 (defcustom org-deadline-string "DEADLINE:"
389 "String to mark deadline entries.
390 A deadline is this string, followed by a time stamp. Should be a word,
391 terminated by a colon. You can insert a schedule keyword and
392 a timestamp with \\[org-deadline].
393 Changes become only effective after restarting Emacs."
394 :group 'org-keywords
395 :type 'string)
397 (defcustom org-scheduled-string "SCHEDULED:"
398 "String to mark scheduled TODO entries.
399 A schedule is this string, followed by a time stamp. Should be a word,
400 terminated by a colon. You can insert a schedule keyword and
401 a timestamp with \\[org-schedule].
402 Changes become only effective after restarting Emacs."
403 :group 'org-keywords
404 :type 'string)
406 (defcustom org-closed-string "CLOSED:"
407 "String used as the prefix for timestamps logging closing a TODO entry."
408 :group 'org-keywords
409 :type 'string)
411 (defcustom org-clock-string "CLOCK:"
412 "String used as prefix for timestamps clocking work hours on an item."
413 :group 'org-keywords
414 :type 'string)
416 (defcustom org-comment-string "COMMENT"
417 "Entries starting with this keyword will never be exported.
418 An entry can be toggled between COMMENT and normal with
419 \\[org-toggle-comment].
420 Changes become only effective after restarting Emacs."
421 :group 'org-keywords
422 :type 'string)
424 (defcustom org-quote-string "QUOTE"
425 "Entries starting with this keyword will be exported in fixed-width font.
426 Quoting applies only to the text in the entry following the headline, and does
427 not extend beyond the next headline, even if that is lower level.
428 An entry can be toggled between QUOTE and normal with
429 \\[org-toggle-fixed-width-section]."
430 :group 'org-keywords
431 :type 'string)
433 (defconst org-repeat-re
434 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
435 "Regular expression for specifying repeated events.
436 After a match, group 1 contains the repeat expression.")
438 (defgroup org-structure nil
439 "Options concerning the general structure of Org-mode files."
440 :tag "Org Structure"
441 :group 'org)
443 (defgroup org-reveal-location nil
444 "Options about how to make context of a location visible."
445 :tag "Org Reveal Location"
446 :group 'org-structure)
448 (defconst org-context-choice
449 '(choice
450 (const :tag "Always" t)
451 (const :tag "Never" nil)
452 (repeat :greedy t :tag "Individual contexts"
453 (cons
454 (choice :tag "Context"
455 (const agenda)
456 (const org-goto)
457 (const occur-tree)
458 (const tags-tree)
459 (const link-search)
460 (const mark-goto)
461 (const bookmark-jump)
462 (const isearch)
463 (const default))
464 (boolean))))
465 "Contexts for the reveal options.")
467 (defcustom org-show-hierarchy-above '((default . t))
468 "Non-nil means, show full hierarchy when revealing a location.
469 Org-mode often shows locations in an org-mode file which might have
470 been invisible before. When this is set, the hierarchy of headings
471 above the exposed location is shown.
472 Turning this off for example for sparse trees makes them very compact.
473 Instead of t, this can also be an alist specifying this option for different
474 contexts. Valid contexts are
475 agenda when exposing an entry from the agenda
476 org-goto when using the command `org-goto' on key C-c C-j
477 occur-tree when using the command `org-occur' on key C-c /
478 tags-tree when constructing a sparse tree based on tags matches
479 link-search when exposing search matches associated with a link
480 mark-goto when exposing the jump goal of a mark
481 bookmark-jump when exposing a bookmark location
482 isearch when exiting from an incremental search
483 default default for all contexts not set explicitly"
484 :group 'org-reveal-location
485 :type org-context-choice)
487 (defcustom org-show-following-heading '((default . nil))
488 "Non-nil means, show following heading when revealing a location.
489 Org-mode often shows locations in an org-mode file which might have
490 been invisible before. When this is set, the heading following the
491 match is shown.
492 Turning this off for example for sparse trees makes them very compact,
493 but makes it harder to edit the location of the match. In such a case,
494 use the command \\[org-reveal] to show more context.
495 Instead of t, this can also be an alist specifying this option for different
496 contexts. See `org-show-hierarchy-above' for valid contexts."
497 :group 'org-reveal-location
498 :type org-context-choice)
500 (defcustom org-show-siblings '((default . nil) (isearch t))
501 "Non-nil means, show all sibling heading when revealing a location.
502 Org-mode often shows locations in an org-mode file which might have
503 been invisible before. When this is set, the sibling of the current entry
504 heading are all made visible. If `org-show-hierarchy-above' is t,
505 the same happens on each level of the hierarchy above the current entry.
507 By default this is on for the isearch context, off for all other contexts.
508 Turning this off for example for sparse trees makes them very compact,
509 but makes it harder to edit the location of the match. In such a case,
510 use the command \\[org-reveal] to show more context.
511 Instead of t, this can also be an alist specifying this option for different
512 contexts. See `org-show-hierarchy-above' for valid contexts."
513 :group 'org-reveal-location
514 :type org-context-choice)
516 (defcustom org-show-entry-below '((default . nil))
517 "Non-nil means, show the entry below a headline when revealing a location.
518 Org-mode often shows locations in an org-mode file which might have
519 been invisible before. When this is set, the text below the headline that is
520 exposed is also shown.
522 By default this is off for all contexts.
523 Instead of t, this can also be an alist specifying this option for different
524 contexts. See `org-show-hierarchy-above' for valid contexts."
525 :group 'org-reveal-location
526 :type org-context-choice)
528 (defcustom org-indirect-buffer-display 'other-window
529 "How should indirect tree buffers be displayed?
530 This applies to indirect buffers created with the commands
531 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
532 Valid values are:
533 current-window Display in the current window
534 other-window Just display in another window.
535 dedicated-frame Create one new frame, and re-use it each time.
536 new-frame Make a new frame each time. Note that in this case
537 previously-made indirect buffers are kept, and you need to
538 kill these buffers yourself."
539 :group 'org-structure
540 :group 'org-agenda-windows
541 :type '(choice
542 (const :tag "In current window" current-window)
543 (const :tag "In current frame, other window" other-window)
544 (const :tag "Each time a new frame" new-frame)
545 (const :tag "One dedicated frame" dedicated-frame)))
547 (defgroup org-cycle nil
548 "Options concerning visibility cycling in Org-mode."
549 :tag "Org Cycle"
550 :group 'org-structure)
552 (defcustom org-cycle-max-level nil
553 "Maximum level which should still be subject to visibility cycling.
554 Levels higher than this will, for cycling, be treated as text, not a headline.
555 When `org-odd-levels-only' is set, a value of N in this variable actually
556 means 2N-1 stars as the limiting headline.
557 When nil, cycle all levels.
558 Note that the limiting level of cycling is also influenced by
559 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
560 `org-inlinetask-min-level' is, cycling will be limited to levels one less
561 than its value."
562 :group 'org-cycle
563 :type '(choice
564 (const :tag "No limit" nil)
565 (integer :tag "Maximum level")))
567 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
568 "Names of drawers. Drawers are not opened by cycling on the headline above.
569 Drawers only open with a TAB on the drawer line itself. A drawer looks like
570 this:
571 :DRAWERNAME:
572 .....
573 :END:
574 The drawer \"PROPERTIES\" is special for capturing properties through
575 the property API.
577 Drawers can be defined on the per-file basis with a line like:
579 #+DRAWERS: HIDDEN STATE PROPERTIES"
580 :group 'org-structure
581 :group 'org-cycle
582 :type '(repeat (string :tag "Drawer Name")))
584 (defcustom org-cycle-global-at-bob nil
585 "Cycle globally if cursor is at beginning of buffer and not at a headline.
586 This makes it possible to do global cycling without having to use S-TAB or
587 C-u TAB. For this special case to work, the first line of the buffer
588 must not be a headline - it may be empty or some other text. When used in
589 this way, `org-cycle-hook' is disables temporarily, to make sure the
590 cursor stays at the beginning of the buffer.
591 When this option is nil, don't do anything special at the beginning
592 of the buffer."
593 :group 'org-cycle
594 :type 'boolean)
596 (defcustom org-cycle-emulate-tab t
597 "Where should `org-cycle' emulate TAB.
598 nil Never
599 white Only in completely white lines
600 whitestart Only at the beginning of lines, before the first non-white char
601 t Everywhere except in headlines
602 exc-hl-bol Everywhere except at the start of a headline
603 If TAB is used in a place where it does not emulate TAB, the current subtree
604 visibility is cycled."
605 :group 'org-cycle
606 :type '(choice (const :tag "Never" nil)
607 (const :tag "Only in completely white lines" white)
608 (const :tag "Before first char in a line" whitestart)
609 (const :tag "Everywhere except in headlines" t)
610 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
613 (defcustom org-cycle-separator-lines 2
614 "Number of empty lines needed to keep an empty line between collapsed trees.
615 If you leave an empty line between the end of a subtree and the following
616 headline, this empty line is hidden when the subtree is folded.
617 Org-mode will leave (exactly) one empty line visible if the number of
618 empty lines is equal or larger to the number given in this variable.
619 So the default 2 means, at least 2 empty lines after the end of a subtree
620 are needed to produce free space between a collapsed subtree and the
621 following headline.
623 Special case: when 0, never leave empty lines in collapsed view."
624 :group 'org-cycle
625 :type 'integer)
626 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
628 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
629 org-cycle-hide-drawers
630 org-cycle-show-empty-lines
631 org-optimize-window-after-visibility-change)
632 "Hook that is run after `org-cycle' has changed the buffer visibility.
633 The function(s) in this hook must accept a single argument which indicates
634 the new state that was set by the most recent `org-cycle' command. The
635 argument is a symbol. After a global state change, it can have the values
636 `overview', `content', or `all'. After a local state change, it can have
637 the values `folded', `children', or `subtree'."
638 :group 'org-cycle
639 :type 'hook)
641 (defgroup org-edit-structure nil
642 "Options concerning structure editing in Org-mode."
643 :tag "Org Edit Structure"
644 :group 'org-structure)
646 (defcustom org-odd-levels-only nil
647 "Non-nil means, skip even levels and only use odd levels for the outline.
648 This has the effect that two stars are being added/taken away in
649 promotion/demotion commands. It also influences how levels are
650 handled by the exporters.
651 Changing it requires restart of `font-lock-mode' to become effective
652 for fontification also in regions already fontified.
653 You may also set this on a per-file basis by adding one of the following
654 lines to the buffer:
656 #+STARTUP: odd
657 #+STARTUP: oddeven"
658 :group 'org-edit-structure
659 :group 'org-font-lock
660 :type 'boolean)
662 (defcustom org-adapt-indentation t
663 "Non-nil means, adapt indentation when promoting and demoting.
664 When this is set and the *entire* text in an entry is indented, the
665 indentation is increased by one space in a demotion command, and
666 decreased by one in a promotion command. If any line in the entry
667 body starts at column 0, indentation is not changed at all."
668 :group 'org-edit-structure
669 :type 'boolean)
671 (defcustom org-special-ctrl-a/e nil
672 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
674 When t, `C-a' will bring back the cursor to the beginning of the
675 headline text, i.e. after the stars and after a possible TODO keyword.
676 In an item, this will be the position after the bullet.
677 When the cursor is already at that position, another `C-a' will bring
678 it to the beginning of the line.
680 `C-e' will jump to the end of the headline, ignoring the presence of tags
681 in the headline. A second `C-e' will then jump to the true end of the
682 line, after any tags.
684 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
685 and only a directly following, identical keypress will bring the cursor
686 to the special positions.
688 This may also be a cons cell where the behavior for `C-a' and `C-e' is
689 set separately."
690 :group 'org-edit-structure
691 :type '(choice
692 (const :tag "off" nil)
693 (const :tag "after stars/bullet and before tags first" t)
694 (const :tag "true line boundary first" reversed)
695 (cons :tag "Set C-a and C-e separately"
696 (choice :tag "Special C-a"
697 (const :tag "off" nil)
698 (const :tag "after stars/bullet first" t)
699 (const :tag "before stars/bullet first" reversed))
700 (choice :tag "Special C-e"
701 (const :tag "off" nil)
702 (const :tag "before tags first" t)
703 (const :tag "after tags first" reversed)))))
704 (if (fboundp 'defvaralias)
705 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
707 (defcustom org-special-ctrl-k nil
708 "Non-nil means `C-k' will behave specially in headlines.
709 When nil, `C-k' will call the default `kill-line' command.
710 When t, the following will happen while the cursor is in the headline:
712 - When the cursor is at the beginning of a headline, kill the entire
713 line and possible the folded subtree below the line.
714 - When in the middle of the headline text, kill the headline up to the tags.
715 - When after the headline text, kill the tags."
716 :group 'org-edit-structure
717 :type 'boolean)
719 (defcustom org-yank-folded-subtrees t
720 "Non-nil means, when yanking subtrees, fold them.
721 If the kill is a single subtree, or a sequence of subtrees, i.e. if
722 it starts with a heading and all other headings in it are either children
723 or siblings, then fold all the subtrees. However, do this only if no
724 text after the yank would be swallowed into a folded tree by this action."
725 :group 'org-edit-structure
726 :type 'boolean)
728 (defcustom org-yank-adjusted-subtrees nil
729 "Non-nil means, when yanking subtrees, adjust the level.
730 With this setting, `org-paste-subtree' is used to insert the subtree, see
731 this function for details."
732 :group 'org-edit-structure
733 :type 'boolean)
735 (defcustom org-M-RET-may-split-line '((default . t))
736 "Non-nil means, M-RET will split the line at the cursor position.
737 When nil, it will go to the end of the line before making a
738 new line.
739 You may also set this option in a different way for different
740 contexts. Valid contexts are:
742 headline when creating a new headline
743 item when creating a new item
744 table in a table field
745 default the value to be used for all contexts not explicitly
746 customized"
747 :group 'org-structure
748 :group 'org-table
749 :type '(choice
750 (const :tag "Always" t)
751 (const :tag "Never" nil)
752 (repeat :greedy t :tag "Individual contexts"
753 (cons
754 (choice :tag "Context"
755 (const headline)
756 (const item)
757 (const table)
758 (const default))
759 (boolean)))))
762 (defcustom org-insert-heading-respect-content nil
763 "Non-nil means, insert new headings after the current subtree.
764 When nil, the new heading is created directly after the current line.
765 The commands \\[org-insert-heading-respect-content] and
766 \\[org-insert-todo-heading-respect-content] turn this variable on
767 for the duration of the command."
768 :group 'org-structure
769 :type 'boolean)
771 (defcustom org-blank-before-new-entry '((heading . auto)
772 (plain-list-item . auto))
773 "Should `org-insert-heading' leave a blank line before new heading/item?
774 The value is an alist, with `heading' and `plain-list-item' as car,
775 and a boolean flag as cdr. For plain lists, if the variable
776 `org-empty-line-terminates-plain-lists' is set, the setting here
777 is ignored and no empty line is inserted, to keep the list in tact."
778 :group 'org-edit-structure
779 :type '(list
780 (cons (const heading)
781 (choice (const :tag "Never" nil)
782 (const :tag "Always" t)
783 (const :tag "Auto" auto)))
784 (cons (const plain-list-item)
785 (choice (const :tag "Never" nil)
786 (const :tag "Always" t)
787 (const :tag "Auto" auto)))))
789 (defcustom org-insert-heading-hook nil
790 "Hook being run after inserting a new heading."
791 :group 'org-edit-structure
792 :type 'hook)
794 (defcustom org-enable-fixed-width-editor t
795 "Non-nil means, lines starting with \":\" are treated as fixed-width.
796 This currently only means, they are never auto-wrapped.
797 When nil, such lines will be treated like ordinary lines.
798 See also the QUOTE keyword."
799 :group 'org-edit-structure
800 :type 'boolean)
802 (defcustom org-edit-src-region-extra nil
803 "Additional regexps to identify regions for editing with `org-edit-src-code'.
804 For examples see the function `org-edit-src-find-region-and-lang'.
805 The regular expression identifying the begin marker should end with a newline,
806 and the regexp marking the end line should start with a newline, to make sure
807 there are kept outside the narrowed region."
808 :group 'org-edit-structure
809 :type '(repeat
810 (list
811 (regexp :tag "begin regexp")
812 (regexp :tag "end regexp")
813 (choice :tag "language"
814 (string :tag "specify")
815 (integer :tag "from match group")
816 (const :tag "from `lang' element")
817 (const :tag "from `style' element")))))
819 (defcustom org-coderef-label-format "(ref:%s)"
820 "The default coderef format.
821 This format string will be used to search for coderef labels in literal
822 examples (EXAMPLE and SRC blocks). The format can be overwritten
823 an individual literal example with the -f option, like
825 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
827 #+END_SRC
829 If you want to use this for HTML export, make sure that the format does
830 not introduce special font-locking, and avoid the HTML special
831 characters `<', `>', and `&'. The reason for this restriction is that
832 the labels are searched for only after htmlize has done its job."
833 :group 'org-edit-structure ; FIXME this is not in the right group
834 :type 'string)
836 (defcustom org-edit-fixed-width-region-mode 'artist-mode
837 "The mode that should be used to edit fixed-width regions.
838 These are the regions where each line starts with a colon."
839 :group 'org-edit-structure
840 :type '(choice
841 (const artist-mode)
842 (const picture-mode)
843 (const fundamental-mode)
844 (function :tag "Other (specify)")))
846 (defcustom org-goto-auto-isearch t
847 "Non-nil means, typing characters in org-goto starts incremental search."
848 :group 'org-edit-structure
849 :type 'boolean)
851 (defgroup org-sparse-trees nil
852 "Options concerning sparse trees in Org-mode."
853 :tag "Org Sparse Trees"
854 :group 'org-structure)
856 (defcustom org-highlight-sparse-tree-matches t
857 "Non-nil means, highlight all matches that define a sparse tree.
858 The highlights will automatically disappear the next time the buffer is
859 changed by an edit command."
860 :group 'org-sparse-trees
861 :type 'boolean)
863 (defcustom org-remove-highlights-with-change t
864 "Non-nil means, any change to the buffer will remove temporary highlights.
865 Such highlights are created by `org-occur' and `org-clock-display'.
866 When nil, `C-c C-c needs to be used to get rid of the highlights.
867 The highlights created by `org-preview-latex-fragment' always need
868 `C-c C-c' to be removed."
869 :group 'org-sparse-trees
870 :group 'org-time
871 :type 'boolean)
874 (defcustom org-occur-hook '(org-first-headline-recenter)
875 "Hook that is run after `org-occur' has constructed a sparse tree.
876 This can be used to recenter the window to show as much of the structure
877 as possible."
878 :group 'org-sparse-trees
879 :type 'hook)
881 (defgroup org-imenu-and-speedbar nil
882 "Options concerning imenu and speedbar in Org-mode."
883 :tag "Org Imenu and Speedbar"
884 :group 'org-structure)
886 (defcustom org-imenu-depth 2
887 "The maximum level for Imenu access to Org-mode headlines.
888 This also applied for speedbar access."
889 :group 'org-imenu-and-speedbar
890 :type 'number)
892 (defgroup org-table nil
893 "Options concerning tables in Org-mode."
894 :tag "Org Table"
895 :group 'org)
897 (defcustom org-enable-table-editor 'optimized
898 "Non-nil means, lines starting with \"|\" are handled by the table editor.
899 When nil, such lines will be treated like ordinary lines.
901 When equal to the symbol `optimized', the table editor will be optimized to
902 do the following:
903 - Automatic overwrite mode in front of whitespace in table fields.
904 This makes the structure of the table stay in tact as long as the edited
905 field does not exceed the column width.
906 - Minimize the number of realigns. Normally, the table is aligned each time
907 TAB or RET are pressed to move to another field. With optimization this
908 happens only if changes to a field might have changed the column width.
909 Optimization requires replacing the functions `self-insert-command',
910 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
911 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
912 very good at guessing when a re-align will be necessary, but you can always
913 force one with \\[org-ctrl-c-ctrl-c].
915 If you would like to use the optimized version in Org-mode, but the
916 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
918 This variable can be used to turn on and off the table editor during a session,
919 but in order to toggle optimization, a restart is required.
921 See also the variable `org-table-auto-blank-field'."
922 :group 'org-table
923 :type '(choice
924 (const :tag "off" nil)
925 (const :tag "on" t)
926 (const :tag "on, optimized" optimized)))
928 (defcustom org-self-insert-cluster-for-undo t
929 "Non-nil means cluster self-insert commands for undo when possible.
930 If this is set, then, like in the Emacs command loop, 20 consequtive
931 characters will be undone together.
932 This is configurable, because there is some impact on typing performance."
933 :group 'org-table
934 :type 'boolean)
936 (defcustom org-table-tab-recognizes-table.el t
937 "Non-nil means, TAB will automatically notice a table.el table.
938 When it sees such a table, it moves point into it and - if necessary -
939 calls `table-recognize-table'."
940 :group 'org-table-editing
941 :type 'boolean)
943 (defgroup org-link nil
944 "Options concerning links in Org-mode."
945 :tag "Org Link"
946 :group 'org)
948 (defvar org-link-abbrev-alist-local nil
949 "Buffer-local version of `org-link-abbrev-alist', which see.
950 The value of this is taken from the #+LINK lines.")
951 (make-variable-buffer-local 'org-link-abbrev-alist-local)
953 (defcustom org-link-abbrev-alist nil
954 "Alist of link abbreviations.
955 The car of each element is a string, to be replaced at the start of a link.
956 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
957 links in Org-mode buffers can have an optional tag after a double colon, e.g.
959 [[linkkey:tag][description]]
961 The 'linkkey' must be a word word, starting with a letter, followed
962 by letters, numbers, '-' or '_'.
964 If REPLACE is a string, the tag will simply be appended to create the link.
965 If the string contains \"%s\", the tag will be inserted there. Alternatively,
966 the placeholder \"%h\" will cause a url-encoded version of the tag to
967 be inserted at that point (see the function `url-hexify-string').
969 REPLACE may also be a function that will be called with the tag as the
970 only argument to create the link, which should be returned as a string.
972 See the manual for examples."
973 :group 'org-link
974 :type '(repeat
975 (cons
976 (string :tag "Protocol")
977 (choice
978 (string :tag "Format")
979 (function)))))
981 (defcustom org-descriptive-links t
982 "Non-nil means, hide link part and only show description of bracket links.
983 Bracket links are like [[link][description]]. This variable sets the initial
984 state in new org-mode buffers. The setting can then be toggled on a
985 per-buffer basis from the Org->Hyperlinks menu."
986 :group 'org-link
987 :type 'boolean)
989 (defcustom org-link-file-path-type 'adaptive
990 "How the path name in file links should be stored.
991 Valid values are:
993 relative Relative to the current directory, i.e. the directory of the file
994 into which the link is being inserted.
995 absolute Absolute path, if possible with ~ for home directory.
996 noabbrev Absolute path, no abbreviation of home directory.
997 adaptive Use relative path for files in the current directory and sub-
998 directories of it. For other files, use an absolute path."
999 :group 'org-link
1000 :type '(choice
1001 (const relative)
1002 (const absolute)
1003 (const noabbrev)
1004 (const adaptive)))
1006 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1007 "Types of links that should be activated in Org-mode files.
1008 This is a list of symbols, each leading to the activation of a certain link
1009 type. In principle, it does not hurt to turn on most link types - there may
1010 be a small gain when turning off unused link types. The types are:
1012 bracket The recommended [[link][description]] or [[link]] links with hiding.
1013 angular Links in angular brackets that may contain whitespace like
1014 <bbdb:Carsten Dominik>.
1015 plain Plain links in normal text, no whitespace, like http://google.com.
1016 radio Text that is matched by a radio target, see manual for details.
1017 tag Tag settings in a headline (link to tag search).
1018 date Time stamps (link to calendar).
1019 footnote Footnote labels.
1021 Changing this variable requires a restart of Emacs to become effective."
1022 :group 'org-link
1023 :type '(set :greedy t
1024 (const :tag "Double bracket links (new style)" bracket)
1025 (const :tag "Angular bracket links (old style)" angular)
1026 (const :tag "Plain text links" plain)
1027 (const :tag "Radio target matches" radio)
1028 (const :tag "Tags" tag)
1029 (const :tag "Timestamps" date)
1030 (const :tag "Footnotes" footnote)))
1032 (defcustom org-make-link-description-function nil
1033 "Function to use to generate link descriptions from links. If
1034 nil the link location will be used. This function must take two
1035 parameters; the first is the link and the second the description
1036 org-insert-link has generated, and should return the description
1037 to use."
1038 :group 'org-link
1039 :type 'function)
1041 (defgroup org-link-store nil
1042 "Options concerning storing links in Org-mode."
1043 :tag "Org Store Link"
1044 :group 'org-link)
1046 (defcustom org-email-link-description-format "Email %c: %.30s"
1047 "Format of the description part of a link to an email or usenet message.
1048 The following %-escapes will be replaced by corresponding information:
1050 %F full \"From\" field
1051 %f name, taken from \"From\" field, address if no name
1052 %T full \"To\" field
1053 %t first name in \"To\" field, address if no name
1054 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1055 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1056 %s subject
1057 %m message-id.
1059 You may use normal field width specification between the % and the letter.
1060 This is for example useful to limit the length of the subject.
1062 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1063 :group 'org-link-store
1064 :type 'string)
1066 (defcustom org-from-is-user-regexp
1067 (let (r1 r2)
1068 (when (and user-mail-address (not (string= user-mail-address "")))
1069 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1070 (when (and user-full-name (not (string= user-full-name "")))
1071 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1072 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1073 "Regexp matched against the \"From:\" header of an email or usenet message.
1074 It should match if the message is from the user him/herself."
1075 :group 'org-link-store
1076 :type 'regexp)
1078 (defcustom org-link-to-org-use-id 'create-if-interactive
1079 "Non-nil means, storing a link to an Org file will use entry IDs.
1081 Note that before this variable is even considered, org-id must be loaded,
1082 to please customize `org-modules' and turn it on.
1084 The variable can have the following values:
1086 t Create an ID if needed to make a link to the current entry.
1088 create-if-interactive
1089 If `org-store-link' is called directly (interactively, as a user
1090 command), do create an ID to support the link. But when doing the
1091 job for remember, only use the ID if it already exists. The
1092 purpose of this setting is to avoid proliferation of unwanted
1093 IDs, just because you happen to be in an Org file when you
1094 call `org-remember' that automatically and preemptively
1095 creates a link. If you do want to get an ID link in a remember
1096 template to an entry not having an ID, create it first by
1097 explicitly creating a link to it, using `C-c C-l' first.
1099 use-existing
1100 Use existing ID, do not create one.
1102 nil Never use an ID to make a link, instead link using a text search for
1103 the headline text."
1104 :group 'org-link-store
1105 :type '(choice
1106 (const :tag "Create ID to make link" t)
1107 (const :tag "Create if string link interactively"
1108 'create-if-interactive)
1109 (const :tag "Only use existing" 'use-existing)
1110 (const :tag "Do not use ID to create link" nil)))
1112 (defcustom org-context-in-file-links t
1113 "Non-nil means, file links from `org-store-link' contain context.
1114 A search string will be added to the file name with :: as separator and
1115 used to find the context when the link is activated by the command
1116 `org-open-at-point'.
1117 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1118 negates this setting for the duration of the command."
1119 :group 'org-link-store
1120 :type 'boolean)
1122 (defcustom org-keep-stored-link-after-insertion nil
1123 "Non-nil means, keep link in list for entire session.
1125 The command `org-store-link' adds a link pointing to the current
1126 location to an internal list. These links accumulate during a session.
1127 The command `org-insert-link' can be used to insert links into any
1128 Org-mode file (offering completion for all stored links). When this
1129 option is nil, every link which has been inserted once using \\[org-insert-link]
1130 will be removed from the list, to make completing the unused links
1131 more efficient."
1132 :group 'org-link-store
1133 :type 'boolean)
1135 (defgroup org-link-follow nil
1136 "Options concerning following links in Org-mode."
1137 :tag "Org Follow Link"
1138 :group 'org-link)
1140 (defcustom org-link-translation-function nil
1141 "Function to translate links with different syntax to Org syntax.
1142 This can be used to translate links created for example by the Planner
1143 or emacs-wiki packages to Org syntax.
1144 The function must accept two parameters, a TYPE containing the link
1145 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1146 which is everything after the link protocol. It should return a cons
1147 with possibly modified values of type and path.
1148 Org contains a function for this, so if you set this variable to
1149 `org-translate-link-from-planner', you should be able follow many
1150 links created by planner."
1151 :group 'org-link-follow
1152 :type 'function)
1154 (defcustom org-follow-link-hook nil
1155 "Hook that is run after a link has been followed."
1156 :group 'org-link-follow
1157 :type 'hook)
1159 (defcustom org-tab-follows-link nil
1160 "Non-nil means, on links TAB will follow the link.
1161 Needs to be set before org.el is loaded.
1162 This really should not be used, it does not make sense, and the
1163 implementation is bad."
1164 :group 'org-link-follow
1165 :type 'boolean)
1167 (defcustom org-return-follows-link nil
1168 "Non-nil means, on links RET will follow the link.
1169 Needs to be set before org.el is loaded."
1170 :group 'org-link-follow
1171 :type 'boolean)
1173 (defcustom org-mouse-1-follows-link
1174 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1175 "Non-nil means, mouse-1 on a link will follow the link.
1176 A longer mouse click will still set point. Does not work on XEmacs.
1177 Needs to be set before org.el is loaded."
1178 :group 'org-link-follow
1179 :type 'boolean)
1181 (defcustom org-mark-ring-length 4
1182 "Number of different positions to be recorded in the ring
1183 Changing this requires a restart of Emacs to work correctly."
1184 :group 'org-link-follow
1185 :type 'integer)
1187 (defcustom org-link-frame-setup
1188 '((vm . vm-visit-folder-other-frame)
1189 (gnus . gnus-other-frame)
1190 (file . find-file-other-window))
1191 "Setup the frame configuration for following links.
1192 When following a link with Emacs, it may often be useful to display
1193 this link in another window or frame. This variable can be used to
1194 set this up for the different types of links.
1195 For VM, use any of
1196 `vm-visit-folder'
1197 `vm-visit-folder-other-frame'
1198 For Gnus, use any of
1199 `gnus'
1200 `gnus-other-frame'
1201 `org-gnus-no-new-news'
1202 For FILE, use any of
1203 `find-file'
1204 `find-file-other-window'
1205 `find-file-other-frame'
1206 For the calendar, use the variable `calendar-setup'.
1207 For BBDB, it is currently only possible to display the matches in
1208 another window."
1209 :group 'org-link-follow
1210 :type '(list
1211 (cons (const vm)
1212 (choice
1213 (const vm-visit-folder)
1214 (const vm-visit-folder-other-window)
1215 (const vm-visit-folder-other-frame)))
1216 (cons (const gnus)
1217 (choice
1218 (const gnus)
1219 (const gnus-other-frame)
1220 (const org-gnus-no-new-news)))
1221 (cons (const file)
1222 (choice
1223 (const find-file)
1224 (const find-file-other-window)
1225 (const find-file-other-frame)))))
1227 (defcustom org-display-internal-link-with-indirect-buffer nil
1228 "Non-nil means, use indirect buffer to display infile links.
1229 Activating internal links (from one location in a file to another location
1230 in the same file) normally just jumps to the location. When the link is
1231 activated with a C-u prefix (or with mouse-3), the link is displayed in
1232 another window. When this option is set, the other window actually displays
1233 an indirect buffer clone of the current buffer, to avoid any visibility
1234 changes to the current buffer."
1235 :group 'org-link-follow
1236 :type 'boolean)
1238 (defcustom org-open-non-existing-files nil
1239 "Non-nil means, `org-open-file' will open non-existing files.
1240 When nil, an error will be generated."
1241 :group 'org-link-follow
1242 :type 'boolean)
1244 (defcustom org-open-directory-means-index-dot-org nil
1245 "Non-nil means, a link to a directory really means to index.org.
1246 When nil, following a directory link will run dired or open a finder/explorer
1247 window on that directory."
1248 :group 'org-link-follow
1249 :type 'boolean)
1251 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1252 "Function and arguments to call for following mailto links.
1253 This is a list with the first element being a lisp function, and the
1254 remaining elements being arguments to the function. In string arguments,
1255 %a will be replaced by the address, and %s will be replaced by the subject
1256 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1257 :group 'org-link-follow
1258 :type '(choice
1259 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1260 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1261 (const :tag "message-mail" (message-mail "%a" "%s"))
1262 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1264 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1265 "Non-nil means, ask for confirmation before executing shell links.
1266 Shell links can be dangerous: just think about a link
1268 [[shell:rm -rf ~/*][Google Search]]
1270 This link would show up in your Org-mode document as \"Google Search\",
1271 but really it would remove your entire home directory.
1272 Therefore we advise against setting this variable to nil.
1273 Just change it to `y-or-n-p' if you want to confirm with a
1274 single keystroke rather than having to type \"yes\"."
1275 :group 'org-link-follow
1276 :type '(choice
1277 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1278 (const :tag "with y-or-n (faster)" y-or-n-p)
1279 (const :tag "no confirmation (dangerous)" nil)))
1281 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1282 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1283 Elisp links can be dangerous: just think about a link
1285 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1287 This link would show up in your Org-mode document as \"Google Search\",
1288 but really it would remove your entire home directory.
1289 Therefore we advise against setting this variable to nil.
1290 Just change it to `y-or-n-p' if you want to confirm with a
1291 single keystroke rather than having to type \"yes\"."
1292 :group 'org-link-follow
1293 :type '(choice
1294 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1295 (const :tag "with y-or-n (faster)" y-or-n-p)
1296 (const :tag "no confirmation (dangerous)" nil)))
1298 (defconst org-file-apps-defaults-gnu
1299 '((remote . emacs)
1300 (system . mailcap)
1301 (t . mailcap))
1302 "Default file applications on a UNIX or GNU/Linux system.
1303 See `org-file-apps'.")
1305 (defconst org-file-apps-defaults-macosx
1306 '((remote . emacs)
1307 (t . "open %s")
1308 (system . "open %s")
1309 ("ps.gz" . "gv %s")
1310 ("eps.gz" . "gv %s")
1311 ("dvi" . "xdvi %s")
1312 ("fig" . "xfig %s"))
1313 "Default file applications on a MacOS X system.
1314 The system \"open\" is known as a default, but we use X11 applications
1315 for some files for which the OS does not have a good default.
1316 See `org-file-apps'.")
1318 (defconst org-file-apps-defaults-windowsnt
1319 (list
1320 '(remote . emacs)
1321 (cons t
1322 (list (if (featurep 'xemacs)
1323 'mswindows-shell-execute
1324 'w32-shell-execute)
1325 "open" 'file))
1326 (cons 'system
1327 (list (if (featurep 'xemacs)
1328 'mswindows-shell-execute
1329 'w32-shell-execute)
1330 "open" 'file)))
1331 "Default file applications on a Windows NT system.
1332 The system \"open\" is used for most files.
1333 See `org-file-apps'.")
1335 (defcustom org-file-apps
1337 (auto-mode . emacs)
1338 ("\\.x?html?\\'" . default)
1339 ("\\.pdf\\'" . default)
1341 "External applications for opening `file:path' items in a document.
1342 Org-mode uses system defaults for different file types, but
1343 you can use this variable to set the application for a given file
1344 extension. The entries in this list are cons cells where the car identifies
1345 files and the cdr the corresponding command. Possible values for the
1346 file identifier are
1347 \"regex\" Regular expression matched against the file name. For backward
1348 compatibility, this can also be a string with only alphanumeric
1349 characters, which is then interpreted as an extension.
1350 `directory' Matches a directory
1351 `remote' Matches a remote file, accessible through tramp or efs.
1352 Remote files most likely should be visited through Emacs
1353 because external applications cannot handle such paths.
1354 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1355 so all files Emacs knows how to handle. Using this with
1356 command `emacs' will open most files in Emacs. Beware that this
1357 will also open html files inside Emacs, unless you add
1358 (\"html\" . default) to the list as well.
1359 t Default for files not matched by any of the other options.
1360 `system' The system command to open files, like `open' on Windows
1361 and Mac OS X, and mailcap under GNU/Linux. This is the command
1362 that will be selected if you call `C-c C-o' with a double
1363 `C-u C-u' prefix.
1365 Possible values for the command are:
1366 `emacs' The file will be visited by the current Emacs process.
1367 `default' Use the default application for this file type, which is the
1368 association for t in the list, most likely in the system-specific
1369 part.
1370 This can be used to overrule an unwanted setting in the
1371 system-specific variable.
1372 `system' Use the system command for opening files, like \"open\".
1373 This command is specified by the entry whose car is `system'.
1374 Most likely, the system-specific version of this variable
1375 does define this command, but you can overrule/replace it
1376 here.
1377 string A command to be executed by a shell; %s will be replaced
1378 by the path to the file.
1379 sexp A Lisp form which will be evaluated. The file path will
1380 be available in the Lisp variable `file'.
1381 For more examples, see the system specific constants
1382 `org-file-apps-defaults-macosx'
1383 `org-file-apps-defaults-windowsnt'
1384 `org-file-apps-defaults-gnu'."
1385 :group 'org-link-follow
1386 :type '(repeat
1387 (cons (choice :value ""
1388 (string :tag "Extension")
1389 (const :tag "System command to open files" system)
1390 (const :tag "Default for unrecognized files" t)
1391 (const :tag "Remote file" remote)
1392 (const :tag "Links to a directory" directory)
1393 (const :tag "Any files that have Emacs modes"
1394 auto-mode))
1395 (choice :value ""
1396 (const :tag "Visit with Emacs" emacs)
1397 (const :tag "Use default" default)
1398 (const :tag "Use the system command" system)
1399 (string :tag "Command")
1400 (sexp :tag "Lisp form")))))
1402 (defgroup org-refile nil
1403 "Options concerning refiling entries in Org-mode."
1404 :tag "Org Refile"
1405 :group 'org)
1407 (defcustom org-directory "~/org"
1408 "Directory with org files.
1409 This is just a default location to look for Org files. There is no need
1410 at all to put your files into this directory. It is only used in the
1411 following situations:
1413 1. When a remember template specifies a target file that is not an
1414 absolute path. The path will then be interpreted relative to
1415 `org-directory'
1416 2. When a remember note is filed away in an interactive way (when exiting the
1417 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1418 with `org-directory' as the default path."
1419 :group 'org-refile
1420 :group 'org-remember
1421 :type 'directory)
1423 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1424 "Default target for storing notes.
1425 Used by the hooks for remember.el. This can be a string, or nil to mean
1426 the value of `remember-data-file'.
1427 You can set this on a per-template basis with the variable
1428 `org-remember-templates'."
1429 :group 'org-refile
1430 :group 'org-remember
1431 :type '(choice
1432 (const :tag "Default from remember-data-file" nil)
1433 file))
1435 (defcustom org-goto-interface 'outline
1436 "The default interface to be used for `org-goto'.
1437 Allowed values are:
1438 outline The interface shows an outline of the relevant file
1439 and the correct heading is found by moving through
1440 the outline or by searching with incremental search.
1441 outline-path-completion Headlines in the current buffer are offered via
1442 completion. This is the interface also used by
1443 the refile command."
1444 :group 'org-refile
1445 :type '(choice
1446 (const :tag "Outline" outline)
1447 (const :tag "Outline-path-completion" outline-path-completion)))
1449 (defcustom org-goto-max-level 5
1450 "Maximum level to be considered when running org-goto with refile interface."
1451 :group 'org-refile
1452 :type 'number)
1454 (defcustom org-reverse-note-order nil
1455 "Non-nil means, store new notes at the beginning of a file or entry.
1456 When nil, new notes will be filed to the end of a file or entry.
1457 This can also be a list with cons cells of regular expressions that
1458 are matched against file names, and values."
1459 :group 'org-remember
1460 :group 'org-refile
1461 :type '(choice
1462 (const :tag "Reverse always" t)
1463 (const :tag "Reverse never" nil)
1464 (repeat :tag "By file name regexp"
1465 (cons regexp boolean))))
1467 (defcustom org-refile-targets nil
1468 "Targets for refiling entries with \\[org-refile].
1469 This is list of cons cells. Each cell contains:
1470 - a specification of the files to be considered, either a list of files,
1471 or a symbol whose function or variable value will be used to retrieve
1472 a file name or a list of file names. If you use `org-agenda-files' for
1473 that, all agenda files will be scanned for targets. Nil means, consider
1474 headings in the current buffer.
1475 - A specification of how to find candidate refile targets. This may be
1476 any of:
1477 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1478 This tag has to be present in all target headlines, inheritance will
1479 not be considered.
1480 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1481 todo keyword.
1482 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1483 headlines that are refiling targets.
1484 - a cons cell (:level . N). Any headline of level N is considered a target.
1485 Note that, when `org-odd-levels-only' is set, level corresponds to
1486 order in hierarchy, not to the number of stars.
1487 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1488 Note that, when `org-odd-levels-only' is set, level corresponds to
1489 order in hierarchy, not to the number of stars.
1491 When this variable is nil, all top-level headlines in the current buffer
1492 are used, equivalent to the value `((nil . (:level . 1))'."
1493 :group 'org-refile
1494 :type '(repeat
1495 (cons
1496 (choice :value org-agenda-files
1497 (const :tag "All agenda files" org-agenda-files)
1498 (const :tag "Current buffer" nil)
1499 (function) (variable) (file))
1500 (choice :tag "Identify target headline by"
1501 (cons :tag "Specific tag" (const :value :tag) (string))
1502 (cons :tag "TODO keyword" (const :value :todo) (string))
1503 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1504 (cons :tag "Level number" (const :value :level) (integer))
1505 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1507 (defcustom org-refile-use-outline-path nil
1508 "Non-nil means, provide refile targets as paths.
1509 So a level 3 headline will be available as level1/level2/level3.
1510 When the value is `file', also include the file name (without directory)
1511 into the path. When `full-file-path', include the full file path."
1512 :group 'org-refile
1513 :type '(choice
1514 (const :tag "Not" nil)
1515 (const :tag "Yes" t)
1516 (const :tag "Start with file name" file)
1517 (const :tag "Start with full file path" full-file-path)))
1519 (defcustom org-outline-path-complete-in-steps t
1520 "Non-nil means, complete the outline path in hierarchical steps.
1521 When Org-mode uses the refile interface to select an outline path
1522 \(see variable `org-refile-use-outline-path'), the completion of
1523 the path can be done is a single go, or if can be done in steps down
1524 the headline hierarchy. Going in steps is probably the best if you
1525 do not use a special completion package like `ido' or `icicles'.
1526 However, when using these packages, going in one step can be very
1527 fast, while still showing the whole path to the entry."
1528 :group 'org-refile
1529 :type 'boolean)
1531 (defgroup org-todo nil
1532 "Options concerning TODO items in Org-mode."
1533 :tag "Org TODO"
1534 :group 'org)
1536 (defgroup org-progress nil
1537 "Options concerning Progress logging in Org-mode."
1538 :tag "Org Progress"
1539 :group 'org-time)
1541 (defvar org-todo-interpretation-widgets
1543 (:tag "Sequence (cycling hits every state)" sequence)
1544 (:tag "Type (cycling directly to DONE)" type))
1545 "The available interpretation symbols for customizing
1546 `org-todo-keywords'.
1547 Interested libraries should add to this list.")
1549 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1550 "List of TODO entry keyword sequences and their interpretation.
1551 \\<org-mode-map>This is a list of sequences.
1553 Each sequence starts with a symbol, either `sequence' or `type',
1554 indicating if the keywords should be interpreted as a sequence of
1555 action steps, or as different types of TODO items. The first
1556 keywords are states requiring action - these states will select a headline
1557 for inclusion into the global TODO list Org-mode produces. If one of
1558 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1559 signify that no further action is necessary. If \"|\" is not found,
1560 the last keyword is treated as the only DONE state of the sequence.
1562 The command \\[org-todo] cycles an entry through these states, and one
1563 additional state where no keyword is present. For details about this
1564 cycling, see the manual.
1566 TODO keywords and interpretation can also be set on a per-file basis with
1567 the special #+SEQ_TODO and #+TYP_TODO lines.
1569 Each keyword can optionally specify a character for fast state selection
1570 \(in combination with the variable `org-use-fast-todo-selection')
1571 and specifiers for state change logging, using the same syntax
1572 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1573 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1574 indicates to record a time stamp each time this state is selected.
1576 Each keyword may also specify if a timestamp or a note should be
1577 recorded when entering or leaving the state, by adding additional
1578 characters in the parenthesis after the keyword. This looks like this:
1579 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1580 record only the time of the state change. With X and Y being either
1581 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1582 Y when leaving the state if and only if the *target* state does not
1583 define X. You may omit any of the fast-selection key or X or /Y,
1584 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1586 For backward compatibility, this variable may also be just a list
1587 of keywords - in this case the interpretation (sequence or type) will be
1588 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1589 :group 'org-todo
1590 :group 'org-keywords
1591 :type '(choice
1592 (repeat :tag "Old syntax, just keywords"
1593 (string :tag "Keyword"))
1594 (repeat :tag "New syntax"
1595 (cons
1596 (choice
1597 :tag "Interpretation"
1598 ;;Quick and dirty way to see
1599 ;;`org-todo-interpretations'. This takes the
1600 ;;place of item arguments
1601 :convert-widget
1602 (lambda (widget)
1603 (widget-put widget
1604 :args (mapcar
1605 #'(lambda (x)
1606 (widget-convert
1607 (cons 'const x)))
1608 org-todo-interpretation-widgets))
1609 widget))
1610 (repeat
1611 (string :tag "Keyword"))))))
1613 (defvar org-todo-keywords-1 nil
1614 "All TODO and DONE keywords active in a buffer.")
1615 (make-variable-buffer-local 'org-todo-keywords-1)
1616 (defvar org-todo-keywords-for-agenda nil)
1617 (defvar org-done-keywords-for-agenda nil)
1618 (defvar org-todo-keyword-alist-for-agenda nil)
1619 (defvar org-tag-alist-for-agenda nil)
1620 (defvar org-agenda-contributing-files nil)
1621 (defvar org-not-done-keywords nil)
1622 (make-variable-buffer-local 'org-not-done-keywords)
1623 (defvar org-done-keywords nil)
1624 (make-variable-buffer-local 'org-done-keywords)
1625 (defvar org-todo-heads nil)
1626 (make-variable-buffer-local 'org-todo-heads)
1627 (defvar org-todo-sets nil)
1628 (make-variable-buffer-local 'org-todo-sets)
1629 (defvar org-todo-log-states nil)
1630 (make-variable-buffer-local 'org-todo-log-states)
1631 (defvar org-todo-kwd-alist nil)
1632 (make-variable-buffer-local 'org-todo-kwd-alist)
1633 (defvar org-todo-key-alist nil)
1634 (make-variable-buffer-local 'org-todo-key-alist)
1635 (defvar org-todo-key-trigger nil)
1636 (make-variable-buffer-local 'org-todo-key-trigger)
1638 (defcustom org-todo-interpretation 'sequence
1639 "Controls how TODO keywords are interpreted.
1640 This variable is in principle obsolete and is only used for
1641 backward compatibility, if the interpretation of todo keywords is
1642 not given already in `org-todo-keywords'. See that variable for
1643 more information."
1644 :group 'org-todo
1645 :group 'org-keywords
1646 :type '(choice (const sequence)
1647 (const type)))
1649 (defcustom org-use-fast-todo-selection t
1650 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1651 This variable describes if and under what circumstances the cycling
1652 mechanism for TODO keywords will be replaced by a single-key, direct
1653 selection scheme.
1655 When nil, fast selection is never used.
1657 When the symbol `prefix', it will be used when `org-todo' is called with
1658 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1659 in an agenda buffer.
1661 When t, fast selection is used by default. In this case, the prefix
1662 argument forces cycling instead.
1664 In all cases, the special interface is only used if access keys have actually
1665 been assigned by the user, i.e. if keywords in the configuration are followed
1666 by a letter in parenthesis, like TODO(t)."
1667 :group 'org-todo
1668 :type '(choice
1669 (const :tag "Never" nil)
1670 (const :tag "By default" t)
1671 (const :tag "Only with C-u C-c C-t" prefix)))
1673 (defcustom org-provide-todo-statistics t
1674 "Non-nil means, update todo statistics after insert and toggle.
1675 When this is set, todo statistics is updated in the parent of the current
1676 entry each time a todo state is changed."
1677 :group 'org-todo
1678 :type 'boolean)
1680 (defcustom org-after-todo-state-change-hook nil
1681 "Hook which is run after the state of a TODO item was changed.
1682 The new state (a string with a TODO keyword, or nil) is available in the
1683 Lisp variable `state'."
1684 :group 'org-todo
1685 :type 'hook)
1687 (defvar org-blocker-hook nil
1688 "Hook for functions that are allowed to block a state change.
1690 Each function gets as its single argument a property list, see
1691 `org-trigger-hook' for more information about this list.
1693 If any of the functions in this hook returns nil, the state change
1694 is blocked.")
1696 (defvar org-trigger-hook nil
1697 "Hook for functions that are triggered by a state change.
1699 Each function gets as its single argument a property list with at least
1700 the following elements:
1702 (:type type-of-change :position pos-at-entry-start
1703 :from old-state :to new-state)
1705 Depending on the type, more properties may be present.
1707 This mechanism is currently implemented for:
1709 TODO state changes
1710 ------------------
1711 :type todo-state-change
1712 :from previous state (keyword as a string), or nil, or a symbol
1713 'todo' or 'done', to indicate the general type of state.
1714 :to new state, like in :from")
1716 (defcustom org-enforce-todo-dependencies nil
1717 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1718 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1719 be blocked if any prior sibling is not yet done.
1720 This variable needs to be set before org.el is loaded, and you need to
1721 restart Emacs after a change to make the change effective. The only way
1722 to change is while Emacs is running is through the customize interface."
1723 :set (lambda (var val)
1724 (set var val)
1725 (if val
1726 (add-hook 'org-blocker-hook
1727 'org-block-todo-from-children-or-siblings)
1728 (remove-hook 'org-blocker-hook
1729 'org-block-todo-from-children-or-siblings)))
1730 :group 'org-todo
1731 :type 'boolean)
1733 (defcustom org-enforce-todo-checkbox-dependencies nil
1734 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1735 When this is nil, checkboxes have no influence on switching TODO states.
1736 When non-nil, you first need to check off all check boxes before the TODO
1737 entry can be switched to DONE.
1738 This variable needs to be set before org.el is loaded, and you need to
1739 restart Emacs after a change to make the change effective. The only way
1740 to change is while Emacs is running is through the customize interface."
1741 :set (lambda (var val)
1742 (set var val)
1743 (if val
1744 (add-hook 'org-blocker-hook
1745 'org-block-todo-from-checkboxes)
1746 (remove-hook 'org-blocker-hook
1747 'org-block-todo-from-checkboxes)))
1748 :group 'org-todo
1749 :type 'boolean)
1751 (defcustom org-todo-state-tags-triggers nil
1752 "Tag changes that should be triggered by TODO state changes.
1753 This is a list. Each entry is
1755 (state-change (tag . flag) .......)
1757 State-change can be a string with a state, and empty string to indicate the
1758 state that has no TODO keyword, or it can be one of the symbols `todo'
1759 or `done', meaning any not-done or done state, respectively."
1760 :group 'org-todo
1761 :group 'org-tags
1762 :type '(repeat
1763 (cons (choice :tag "When changing to"
1764 (const :tag "Not-done state" todo)
1765 (const :tag "Done state" done)
1766 (string :tag "State"))
1767 (repeat
1768 (cons :tag "Tag action"
1769 (string :tag "Tag")
1770 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1772 (defcustom org-log-done nil
1773 "Information to record when a task moves to the DONE state.
1775 Possible values are:
1777 nil Don't add anything, just change the keyword
1778 time Add a time stamp to the task
1779 note Prompt a closing note and add it with template `org-log-note-headings'
1781 This option can also be set with on a per-file-basis with
1783 #+STARTUP: nologdone
1784 #+STARTUP: logdone
1785 #+STARTUP: lognotedone
1787 You can have local logging settings for a subtree by setting the LOGGING
1788 property to one or more of these keywords."
1789 :group 'org-todo
1790 :group 'org-progress
1791 :type '(choice
1792 (const :tag "No logging" nil)
1793 (const :tag "Record CLOSED timestamp" time)
1794 (const :tag "Record CLOSED timestamp with closing note." note)))
1796 ;; Normalize old uses of org-log-done.
1797 (cond
1798 ((eq org-log-done t) (setq org-log-done 'time))
1799 ((and (listp org-log-done) (memq 'done org-log-done))
1800 (setq org-log-done 'note)))
1802 (defcustom org-log-note-clock-out nil
1803 "Non-nil means, record a note when clocking out of an item.
1804 This can also be configured on a per-file basis by adding one of
1805 the following lines anywhere in the buffer:
1807 #+STARTUP: lognoteclock-out
1808 #+STARTUP: nolognoteclock-out"
1809 :group 'org-todo
1810 :group 'org-progress
1811 :type 'boolean)
1813 (defcustom org-log-done-with-time t
1814 "Non-nil means, the CLOSED time stamp will contain date and time.
1815 When nil, only the date will be recorded."
1816 :group 'org-progress
1817 :type 'boolean)
1819 (defcustom org-log-note-headings
1820 '((done . "CLOSING NOTE %t")
1821 (state . "State %-12s from %-12S %t")
1822 (note . "Note taken on %t")
1823 (clock-out . ""))
1824 "Headings for notes added to entries.
1825 The value is an alist, with the car being a symbol indicating the note
1826 context, and the cdr is the heading to be used. The heading may also be the
1827 empty string.
1828 %t in the heading will be replaced by a time stamp.
1829 %s will be replaced by the new TODO state, in double quotes.
1830 %S will be replaced by the old TODO state, in double quotes.
1831 %u will be replaced by the user name.
1832 %U will be replaced by the full user name."
1833 :group 'org-todo
1834 :group 'org-progress
1835 :type '(list :greedy t
1836 (cons (const :tag "Heading when closing an item" done) string)
1837 (cons (const :tag
1838 "Heading when changing todo state (todo sequence only)"
1839 state) string)
1840 (cons (const :tag "Heading when just taking a note" note) string)
1841 (cons (const :tag "Heading when clocking out" clock-out) string)))
1843 (unless (assq 'note org-log-note-headings)
1844 (push '(note . "%t") org-log-note-headings))
1846 (defcustom org-log-into-drawer nil
1847 "Non-nil means, insert state change notes and time stamps into a drawer.
1848 When nil, state changes notes will be inserted after the headline and
1849 any scheduling and clock lines, but not inside a drawer.
1851 The value of this variable should be the name of the drawer to use.
1852 LOGBOOK is proposed at the default drawer for this purpose, you can
1853 also set this to a string to define the drawer of your choice.
1855 A value of t is also allowed, representing \"LOGBOOK\".
1857 If this variable is set, `org-log-state-notes-insert-after-drawers'
1858 will be ignored."
1859 :group 'org-todo
1860 :group 'org-progress
1861 :type '(choice
1862 (const :tag "Not into a drawer" nil)
1863 (const :tag "LOGBOOK" t)
1864 (string :tag "Other")))
1866 (if (fboundp 'defvaralias)
1867 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1869 (defcustom org-log-state-notes-insert-after-drawers nil
1870 "Non-nil means, insert state change notes after any drawers in entry.
1871 Only the drawers that *immediately* follow the headline and the
1872 deadline/scheduled line are skipped.
1873 When nil, insert notes right after the heading and perhaps the line
1874 with deadline/scheduling if present.
1876 This variable will have no effect if `org-log-into-drawer' is
1877 set."
1878 :group 'org-todo
1879 :group 'org-progress
1880 :type 'boolean)
1882 (defcustom org-log-states-order-reversed t
1883 "Non-nil means, the latest state change note will be directly after heading.
1884 When nil, the notes will be orderer according to time."
1885 :group 'org-todo
1886 :group 'org-progress
1887 :type 'boolean)
1889 (defcustom org-log-repeat 'time
1890 "Non-nil means, record moving through the DONE state when triggering repeat.
1891 An auto-repeating tasks is immediately switched back to TODO when marked
1892 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1893 the TODO keyword definition, or recording a closing note by setting
1894 `org-log-done', there will be no record of the task moving through DONE.
1895 This variable forces taking a note anyway. Possible values are:
1897 nil Don't force a record
1898 time Record a time stamp
1899 note Record a note
1901 This option can also be set with on a per-file-basis with
1903 #+STARTUP: logrepeat
1904 #+STARTUP: lognoterepeat
1905 #+STARTUP: nologrepeat
1907 You can have local logging settings for a subtree by setting the LOGGING
1908 property to one or more of these keywords."
1909 :group 'org-todo
1910 :group 'org-progress
1911 :type '(choice
1912 (const :tag "Don't force a record" nil)
1913 (const :tag "Force recording the DONE state" time)
1914 (const :tag "Force recording a note with the DONE state" note)))
1917 (defgroup org-priorities nil
1918 "Priorities in Org-mode."
1919 :tag "Org Priorities"
1920 :group 'org-todo)
1922 (defcustom org-highest-priority ?A
1923 "The highest priority of TODO items. A character like ?A, ?B etc.
1924 Must have a smaller ASCII number than `org-lowest-priority'."
1925 :group 'org-priorities
1926 :type 'character)
1928 (defcustom org-lowest-priority ?C
1929 "The lowest priority of TODO items. A character like ?A, ?B etc.
1930 Must have a larger ASCII number than `org-highest-priority'."
1931 :group 'org-priorities
1932 :type 'character)
1934 (defcustom org-default-priority ?B
1935 "The default priority of TODO items.
1936 This is the priority an item get if no explicit priority is given."
1937 :group 'org-priorities
1938 :type 'character)
1940 (defcustom org-priority-start-cycle-with-default t
1941 "Non-nil means, start with default priority when starting to cycle.
1942 When this is nil, the first step in the cycle will be (depending on the
1943 command used) one higher or lower that the default priority."
1944 :group 'org-priorities
1945 :type 'boolean)
1947 (defgroup org-time nil
1948 "Options concerning time stamps and deadlines in Org-mode."
1949 :tag "Org Time"
1950 :group 'org)
1952 (defcustom org-insert-labeled-timestamps-at-point nil
1953 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1954 When nil, these labeled time stamps are forces into the second line of an
1955 entry, just after the headline. When scheduling from the global TODO list,
1956 the time stamp will always be forced into the second line."
1957 :group 'org-time
1958 :type 'boolean)
1960 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1961 "Formats for `format-time-string' which are used for time stamps.
1962 It is not recommended to change this constant.")
1964 (defcustom org-time-stamp-rounding-minutes '(0 5)
1965 "Number of minutes to round time stamps to.
1966 These are two values, the first applies when first creating a time stamp.
1967 The second applies when changing it with the commands `S-up' and `S-down'.
1968 When changing the time stamp, this means that it will change in steps
1969 of N minutes, as given by the second value.
1971 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1972 numbers should be factors of 60, so for example 5, 10, 15.
1974 When this is larger than 1, you can still force an exact time-stamp by using
1975 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1976 and by using a prefix arg to `S-up/down' to specify the exact number
1977 of minutes to shift."
1978 :group 'org-time
1979 :get '(lambda (var) ; Make sure all entries have 5 elements
1980 (if (integerp (default-value var))
1981 (list (default-value var) 5)
1982 (default-value var)))
1983 :type '(list
1984 (integer :tag "when inserting times")
1985 (integer :tag "when modifying times")))
1987 ;; Normalize old customizations of this variable.
1988 (when (integerp org-time-stamp-rounding-minutes)
1989 (setq org-time-stamp-rounding-minutes
1990 (list org-time-stamp-rounding-minutes
1991 org-time-stamp-rounding-minutes)))
1993 (defcustom org-display-custom-times nil
1994 "Non-nil means, overlay custom formats over all time stamps.
1995 The formats are defined through the variable `org-time-stamp-custom-formats'.
1996 To turn this on on a per-file basis, insert anywhere in the file:
1997 #+STARTUP: customtime"
1998 :group 'org-time
1999 :set 'set-default
2000 :type 'sexp)
2001 (make-variable-buffer-local 'org-display-custom-times)
2003 (defcustom org-time-stamp-custom-formats
2004 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2005 "Custom formats for time stamps. See `format-time-string' for the syntax.
2006 These are overlayed over the default ISO format if the variable
2007 `org-display-custom-times' is set. Time like %H:%M should be at the
2008 end of the second format."
2009 :group 'org-time
2010 :type 'sexp)
2012 (defun org-time-stamp-format (&optional long inactive)
2013 "Get the right format for a time string."
2014 (let ((f (if long (cdr org-time-stamp-formats)
2015 (car org-time-stamp-formats))))
2016 (if inactive
2017 (concat "[" (substring f 1 -1) "]")
2018 f)))
2020 (defcustom org-time-clocksum-format "%d:%02d"
2021 "The format string used when creating CLOCKSUM lines, or when
2022 org-mode generates a time duration."
2023 :group 'org-time
2024 :type 'string)
2026 (defcustom org-deadline-warning-days 14
2027 "No. of days before expiration during which a deadline becomes active.
2028 This variable governs the display in sparse trees and in the agenda.
2029 When 0 or negative, it means use this number (the absolute value of it)
2030 even if a deadline has a different individual lead time specified.
2032 Custom commands can set this variable in the options section."
2033 :group 'org-time
2034 :group 'org-agenda-daily/weekly
2035 :type 'number)
2037 (defcustom org-read-date-prefer-future t
2038 "Non-nil means, assume future for incomplete date input from user.
2039 This affects the following situations:
2040 1. The user gives a day, but no month.
2041 For example, if today is the 15th, and you enter \"3\", Org-mode will
2042 read this as the third of *next* month. However, if you enter \"17\",
2043 it will be considered as *this* month.
2044 2. The user gives a month but not a year.
2045 For example, if it is april and you enter \"feb 2\", this will be read
2046 as feb 2, *next* year. \"May 5\", however, will be this year.
2048 Currently this does not work for ISO week specifications.
2050 When this option is nil, the current month and year will always be used
2051 as defaults."
2052 :group 'org-time
2053 :type 'boolean)
2055 (defcustom org-read-date-display-live t
2056 "Non-nil means, display current interpretation of date prompt live.
2057 This display will be in an overlay, in the minibuffer."
2058 :group 'org-time
2059 :type 'boolean)
2061 (defcustom org-read-date-popup-calendar t
2062 "Non-nil means, pop up a calendar when prompting for a date.
2063 In the calendar, the date can be selected with mouse-1. However, the
2064 minibuffer will also be active, and you can simply enter the date as well.
2065 When nil, only the minibuffer will be available."
2066 :group 'org-time
2067 :type 'boolean)
2068 (if (fboundp 'defvaralias)
2069 (defvaralias 'org-popup-calendar-for-date-prompt
2070 'org-read-date-popup-calendar))
2072 (defcustom org-read-date-minibuffer-setup-hook nil
2073 "Hook to be used to set up keys for the date/time interface.
2074 Add key definitions to `minibuffer-local-map', which will be a temporary
2075 copy."
2076 :group 'org-time
2077 :type 'hook)
2079 (defcustom org-extend-today-until 0
2080 "The hour when your day really ends. Must be an integer.
2081 This has influence for the following applications:
2082 - When switching the agenda to \"today\". It it is still earlier than
2083 the time given here, the day recognized as TODAY is actually yesterday.
2084 - When a date is read from the user and it is still before the time given
2085 here, the current date and time will be assumed to be yesterday, 23:59.
2086 Also, timestamps inserted in remember templates follow this rule.
2088 IMPORTANT: This is a feature whose implementation is and likely will
2089 remain incomplete. Really, it is only here because past midnight seems to
2090 be the favorite working time of John Wiegley :-)"
2091 :group 'org-time
2092 :type 'number)
2094 (defcustom org-edit-timestamp-down-means-later nil
2095 "Non-nil means, S-down will increase the time in a time stamp.
2096 When nil, S-up will increase."
2097 :group 'org-time
2098 :type 'boolean)
2100 (defcustom org-calendar-follow-timestamp-change t
2101 "Non-nil means, make the calendar window follow timestamp changes.
2102 When a timestamp is modified and the calendar window is visible, it will be
2103 moved to the new date."
2104 :group 'org-time
2105 :type 'boolean)
2107 (defgroup org-tags nil
2108 "Options concerning tags in Org-mode."
2109 :tag "Org Tags"
2110 :group 'org)
2112 (defcustom org-tag-alist nil
2113 "List of tags allowed in Org-mode files.
2114 When this list is nil, Org-mode will base TAG input on what is already in the
2115 buffer.
2116 The value of this variable is an alist, the car of each entry must be a
2117 keyword as a string, the cdr may be a character that is used to select
2118 that tag through the fast-tag-selection interface.
2119 See the manual for details."
2120 :group 'org-tags
2121 :type '(repeat
2122 (choice
2123 (cons (string :tag "Tag name")
2124 (character :tag "Access char"))
2125 (const :tag "Start radio group" (:startgroup))
2126 (const :tag "End radio group" (:endgroup))
2127 (const :tag "New line" (:newline)))))
2129 (defcustom org-tag-persistent-alist nil
2130 "List of tags that will always appear in all Org-mode files.
2131 This is in addition to any in buffer settings or customizations
2132 of `org-tag-alist'.
2133 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2134 The value of this variable is an alist, the car of each entry must be a
2135 keyword as a string, the cdr may be a character that is used to select
2136 that tag through the fast-tag-selection interface.
2137 See the manual for details.
2138 To disable these tags on a per-file basis, insert anywhere in the file:
2139 #+STARTUP: noptag"
2140 :group 'org-tags
2141 :type '(repeat
2142 (choice
2143 (cons (string :tag "Tag name")
2144 (character :tag "Access char"))
2145 (const :tag "Start radio group" (:startgroup))
2146 (const :tag "End radio group" (:endgroup))
2147 (const :tag "New line" (:newline)))))
2149 (defvar org-file-tags nil
2150 "List of tags that can be inherited by all entries in the file.
2151 The tags will be inherited if the variable `org-use-tag-inheritance'
2152 says they should be.
2153 This variable is populated from #+TAG lines.")
2155 (defcustom org-use-fast-tag-selection 'auto
2156 "Non-nil means, use fast tag selection scheme.
2157 This is a special interface to select and deselect tags with single keys.
2158 When nil, fast selection is never used.
2159 When the symbol `auto', fast selection is used if and only if selection
2160 characters for tags have been configured, either through the variable
2161 `org-tag-alist' or through a #+TAGS line in the buffer.
2162 When t, fast selection is always used and selection keys are assigned
2163 automatically if necessary."
2164 :group 'org-tags
2165 :type '(choice
2166 (const :tag "Always" t)
2167 (const :tag "Never" nil)
2168 (const :tag "When selection characters are configured" 'auto)))
2170 (defcustom org-fast-tag-selection-single-key nil
2171 "Non-nil means, fast tag selection exits after first change.
2172 When nil, you have to press RET to exit it.
2173 During fast tag selection, you can toggle this flag with `C-c'.
2174 This variable can also have the value `expert'. In this case, the window
2175 displaying the tags menu is not even shown, until you press C-c again."
2176 :group 'org-tags
2177 :type '(choice
2178 (const :tag "No" nil)
2179 (const :tag "Yes" t)
2180 (const :tag "Expert" expert)))
2182 (defvar org-fast-tag-selection-include-todo nil
2183 "Non-nil means, fast tags selection interface will also offer TODO states.
2184 This is an undocumented feature, you should not rely on it.")
2186 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2187 "The column to which tags should be indented in a headline.
2188 If this number is positive, it specifies the column. If it is negative,
2189 it means that the tags should be flushright to that column. For example,
2190 -80 works well for a normal 80 character screen."
2191 :group 'org-tags
2192 :type 'integer)
2194 (defcustom org-auto-align-tags t
2195 "Non-nil means, realign tags after pro/demotion of TODO state change.
2196 These operations change the length of a headline and therefore shift
2197 the tags around. With this options turned on, after each such operation
2198 the tags are again aligned to `org-tags-column'."
2199 :group 'org-tags
2200 :type 'boolean)
2202 (defcustom org-use-tag-inheritance t
2203 "Non-nil means, tags in levels apply also for sublevels.
2204 When nil, only the tags directly given in a specific line apply there.
2205 This may also be a list of tags that should be inherited, or a regexp that
2206 matches tags that should be inherited. Additional control is possible
2207 with the variable `org-tags-exclude-from-inheritance' which gives an
2208 explicit list of tags to be excluded from inheritance., even if the value of
2209 `org-use-tag-inheritance' would select it for inheritance.
2211 If this option is t, a match early-on in a tree can lead to a large
2212 number of matches in the subtree when constructing the agenda or creating
2213 a sparse tree. If you only want to see the first match in a tree during
2214 a search, check out the variable `org-tags-match-list-sublevels'."
2215 :group 'org-tags
2216 :type '(choice
2217 (const :tag "Not" nil)
2218 (const :tag "Always" t)
2219 (repeat :tag "Specific tags" (string :tag "Tag"))
2220 (regexp :tag "Tags matched by regexp")))
2222 (defcustom org-tags-exclude-from-inheritance nil
2223 "List of tags that should never be inherited.
2224 This is a way to exclude a few tags from inheritance. For way to do
2225 the opposite, to actively allow inheritance for selected tags,
2226 see the variable `org-use-tag-inheritance'."
2227 :group 'org-tags
2228 :type '(repeat (string :tag "Tag")))
2230 (defun org-tag-inherit-p (tag)
2231 "Check if TAG is one that should be inherited."
2232 (cond
2233 ((member tag org-tags-exclude-from-inheritance) nil)
2234 ((eq org-use-tag-inheritance t) t)
2235 ((not org-use-tag-inheritance) nil)
2236 ((stringp org-use-tag-inheritance)
2237 (string-match org-use-tag-inheritance tag))
2238 ((listp org-use-tag-inheritance)
2239 (member tag org-use-tag-inheritance))
2240 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2242 (defcustom org-tags-match-list-sublevels t
2243 "Non-nil means list also sublevels of headlines matching a search.
2244 This variable applies to tags/property searches, and also to stuck
2245 projects because this search is based on a tags match as well.
2247 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2248 the sublevels of a headline matching a tag search often also match
2249 the same search. Listing all of them can create very long lists.
2250 Setting this variable to nil causes subtrees of a match to be skipped.
2252 As a special case, if the tag search is restricted to TODO items, the
2253 value of this variable is ignored and sublevels are always checked, to
2254 make sure all corresponding TODO items find their way into the list.
2256 This variable is semi-obsolete and probably should always be true. It
2257 is better to limit inheritance to certain tags using the variables
2258 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2259 :group 'org-tags
2260 :type '(choice
2261 (const :tag "No, don't list them" nil)
2262 (const :tag "Yes, do list them" t)
2263 (const :tag "List them, indented with leading dots" indented)))
2265 (defvar org-tags-history nil
2266 "History of minibuffer reads for tags.")
2267 (defvar org-last-tags-completion-table nil
2268 "The last used completion table for tags.")
2269 (defvar org-after-tags-change-hook nil
2270 "Hook that is run after the tags in a line have changed.")
2272 (defgroup org-properties nil
2273 "Options concerning properties in Org-mode."
2274 :tag "Org Properties"
2275 :group 'org)
2277 (defcustom org-property-format "%-10s %s"
2278 "How property key/value pairs should be formatted by `indent-line'.
2279 When `indent-line' hits a property definition, it will format the line
2280 according to this format, mainly to make sure that the values are
2281 lined-up with respect to each other."
2282 :group 'org-properties
2283 :type 'string)
2285 (defcustom org-use-property-inheritance nil
2286 "Non-nil means, properties apply also for sublevels.
2288 This setting is chiefly used during property searches. Turning it on can
2289 cause significant overhead when doing a search, which is why it is not
2290 on by default.
2292 When nil, only the properties directly given in the current entry count.
2293 When t, every property is inherited. The value may also be a list of
2294 properties that should have inheritance, or a regular expression matching
2295 properties that should be inherited.
2297 However, note that some special properties use inheritance under special
2298 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2299 and the properties ending in \"_ALL\" when they are used as descriptor
2300 for valid values of a property.
2302 Note for programmers:
2303 When querying an entry with `org-entry-get', you can control if inheritance
2304 should be used. By default, `org-entry-get' looks only at the local
2305 properties. You can request inheritance by setting the inherit argument
2306 to t (to force inheritance) or to `selective' (to respect the setting
2307 in this variable)."
2308 :group 'org-properties
2309 :type '(choice
2310 (const :tag "Not" nil)
2311 (const :tag "Always" t)
2312 (repeat :tag "Specific properties" (string :tag "Property"))
2313 (regexp :tag "Properties matched by regexp")))
2315 (defun org-property-inherit-p (property)
2316 "Check if PROPERTY is one that should be inherited."
2317 (cond
2318 ((eq org-use-property-inheritance t) t)
2319 ((not org-use-property-inheritance) nil)
2320 ((stringp org-use-property-inheritance)
2321 (string-match org-use-property-inheritance property))
2322 ((listp org-use-property-inheritance)
2323 (member property org-use-property-inheritance))
2324 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2326 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2327 "The default column format, if no other format has been defined.
2328 This variable can be set on the per-file basis by inserting a line
2330 #+COLUMNS: %25ITEM ....."
2331 :group 'org-properties
2332 :type 'string)
2334 (defcustom org-columns-ellipses ".."
2335 "The ellipses to be used when a field in column view is truncated.
2336 When this is the empty string, as many characters as possible are shown,
2337 but then there will be no visual indication that the field has been truncated.
2338 When this is a string of length N, the last N characters of a truncated
2339 field are replaced by this string. If the column is narrower than the
2340 ellipses string, only part of the ellipses string will be shown."
2341 :group 'org-properties
2342 :type 'string)
2344 (defcustom org-columns-modify-value-for-display-function nil
2345 "Function that modifies values for display in column view.
2346 For example, it can be used to cut out a certain part from a time stamp.
2347 The function must take 2 arguments:
2349 column-title The title of the column (*not* the property name)
2350 value The value that should be modified.
2352 The function should return the value that should be displayed,
2353 or nil if the normal value should be used."
2354 :group 'org-properties
2355 :type 'function)
2357 (defcustom org-effort-property "Effort"
2358 "The property that is being used to keep track of effort estimates.
2359 Effort estimates given in this property need to have the format H:MM."
2360 :group 'org-properties
2361 :group 'org-progress
2362 :type '(string :tag "Property"))
2364 (defconst org-global-properties-fixed
2365 '(("VISIBILITY_ALL" . "folded children content all"))
2366 "List of property/value pairs that can be inherited by any entry.
2368 These are fixed values, for the preset properties. The user variable
2369 that can be used to add to this list is `org-global-properties'.
2371 The entries in this list are cons cells where the car is a property
2372 name and cdr is a string with the value. If the value represents
2373 multiple items like an \"_ALL\" property, separate the items by
2374 spaces.")
2376 (defcustom org-global-properties nil
2377 "List of property/value pairs that can be inherited by any entry.
2379 This list will be combined with the constant `org-global-properties-fixed'.
2381 The entries in this list are cons cells where the car is a property
2382 name and cdr is a string with the value.
2384 You can set buffer-local values for the same purpose in the variable
2385 `org-file-properties' this by adding lines like
2387 #+PROPERTY: NAME VALUE"
2388 :group 'org-properties
2389 :type '(repeat
2390 (cons (string :tag "Property")
2391 (string :tag "Value"))))
2393 (defvar org-file-properties nil
2394 "List of property/value pairs that can be inherited by any entry.
2395 Valid for the current buffer.
2396 This variable is populated from #+PROPERTY lines.")
2397 (make-variable-buffer-local 'org-file-properties)
2399 (defgroup org-agenda nil
2400 "Options concerning agenda views in Org-mode."
2401 :tag "Org Agenda"
2402 :group 'org)
2404 (defvar org-category nil
2405 "Variable used by org files to set a category for agenda display.
2406 Such files should use a file variable to set it, for example
2408 # -*- mode: org; org-category: \"ELisp\"
2410 or contain a special line
2412 #+CATEGORY: ELisp
2414 If the file does not specify a category, then file's base name
2415 is used instead.")
2416 (make-variable-buffer-local 'org-category)
2417 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2419 (defcustom org-agenda-files nil
2420 "The files to be used for agenda display.
2421 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2422 \\[org-remove-file]. You can also use customize to edit the list.
2424 If an entry is a directory, all files in that directory that are matched by
2425 `org-agenda-file-regexp' will be part of the file list.
2427 If the value of the variable is not a list but a single file name, then
2428 the list of agenda files is actually stored and maintained in that file, one
2429 agenda file per line."
2430 :group 'org-agenda
2431 :type '(choice
2432 (repeat :tag "List of files and directories" file)
2433 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2435 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2436 "Regular expression to match files for `org-agenda-files'.
2437 If any element in the list in that variable contains a directory instead
2438 of a normal file, all files in that directory that are matched by this
2439 regular expression will be included."
2440 :group 'org-agenda
2441 :type 'regexp)
2443 (defcustom org-agenda-text-search-extra-files nil
2444 "List of extra files to be searched by text search commands.
2445 These files will be search in addition to the agenda files by the
2446 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2447 Note that these files will only be searched for text search commands,
2448 not for the other agenda views like todo lists, tag searches or the weekly
2449 agenda. This variable is intended to list notes and possibly archive files
2450 that should also be searched by these two commands.
2451 In fact, if the first element in the list is the symbol `agenda-archives',
2452 than all archive files of all agenda files will be added to the search
2453 scope."
2454 :group 'org-agenda
2455 :type '(set :greedy t
2456 (const :tag "Agenda Archives" agenda-archives)
2457 (repeat :inline t (file))))
2459 (if (fboundp 'defvaralias)
2460 (defvaralias 'org-agenda-multi-occur-extra-files
2461 'org-agenda-text-search-extra-files))
2463 (defcustom org-agenda-skip-unavailable-files nil
2464 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2465 A nil value means to remove them, after a query, from the list."
2466 :group 'org-agenda
2467 :type 'boolean)
2469 (defcustom org-calendar-to-agenda-key [?c]
2470 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2471 The command `org-calendar-goto-agenda' will be bound to this key. The
2472 default is the character `c' because then `c' can be used to switch back and
2473 forth between agenda and calendar."
2474 :group 'org-agenda
2475 :type 'sexp)
2477 (defcustom org-calendar-agenda-action-key [?k]
2478 "The key to be installed in `calendar-mode-map' for agenda-action.
2479 The command `org-agenda-action' will be bound to this key. The
2480 default is the character `k' because we use the same key in the agenda."
2481 :group 'org-agenda
2482 :type 'sexp)
2484 (eval-after-load "calendar"
2485 '(progn
2486 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2487 'org-calendar-goto-agenda)
2488 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2489 'org-agenda-action)))
2491 (defgroup org-latex nil
2492 "Options for embedding LaTeX code into Org-mode."
2493 :tag "Org LaTeX"
2494 :group 'org)
2496 (defcustom org-format-latex-options
2497 '(:foreground default :background default :scale 1.0
2498 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2499 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2500 "Options for creating images from LaTeX fragments.
2501 This is a property list with the following properties:
2502 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2503 `default' means use the foreground of the default face.
2504 :background the background color, or \"Transparent\".
2505 `default' means use the background of the default face.
2506 :scale a scaling factor for the size of the images.
2507 :html-foreground, :html-background, :html-scale
2508 the same numbers for HTML export.
2509 :matchers a list indicating which matchers should be used to
2510 find LaTeX fragments. Valid members of this list are:
2511 \"begin\" find environments
2512 \"$1\" find single characters surrounded by $.$
2513 \"$\" find math expressions surrounded by $...$
2514 \"$$\" find math expressions surrounded by $$....$$
2515 \"\\(\" find math expressions surrounded by \\(...\\)
2516 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2517 :group 'org-latex
2518 :type 'plist)
2520 (defcustom org-format-latex-header "\\documentclass{article}
2521 \\usepackage{fullpage} % do not remove
2522 \\usepackage{amssymb}
2523 \\usepackage[usenames]{color}
2524 \\usepackage{amsmath}
2525 \\usepackage{latexsym}
2526 \\usepackage[mathscr]{eucal}
2527 \\pagestyle{empty} % do not remove"
2528 "The document header used for processing LaTeX fragments."
2529 :group 'org-latex
2530 :type 'string)
2533 (defgroup org-font-lock nil
2534 "Font-lock settings for highlighting in Org-mode."
2535 :tag "Org Font Lock"
2536 :group 'org)
2538 (defcustom org-level-color-stars-only nil
2539 "Non-nil means fontify only the stars in each headline.
2540 When nil, the entire headline is fontified.
2541 Changing it requires restart of `font-lock-mode' to become effective
2542 also in regions already fontified."
2543 :group 'org-font-lock
2544 :type 'boolean)
2546 (defcustom org-hide-leading-stars nil
2547 "Non-nil means, hide the first N-1 stars in a headline.
2548 This works by using the face `org-hide' for these stars. This
2549 face is white for a light background, and black for a dark
2550 background. You may have to customize the face `org-hide' to
2551 make this work.
2552 Changing it requires restart of `font-lock-mode' to become effective
2553 also in regions already fontified.
2554 You may also set this on a per-file basis by adding one of the following
2555 lines to the buffer:
2557 #+STARTUP: hidestars
2558 #+STARTUP: showstars"
2559 :group 'org-font-lock
2560 :type 'boolean)
2562 (defcustom org-fontify-done-headline nil
2563 "Non-nil means, change the face of a headline if it is marked DONE.
2564 Normally, only the TODO/DONE keyword indicates the state of a headline.
2565 When this is non-nil, the headline after the keyword is set to the
2566 `org-headline-done' as an additional indication."
2567 :group 'org-font-lock
2568 :type 'boolean)
2570 (defcustom org-fontify-emphasized-text t
2571 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2572 Changing this variable requires a restart of Emacs to take effect."
2573 :group 'org-font-lock
2574 :type 'boolean)
2576 (defcustom org-highlight-latex-fragments-and-specials nil
2577 "Non-nil means, fontify what is treated specially by the exporters."
2578 :group 'org-font-lock
2579 :type 'boolean)
2581 (defcustom org-hide-emphasis-markers nil
2582 "Non-nil mean font-lock should hide the emphasis marker characters."
2583 :group 'org-font-lock
2584 :type 'boolean)
2586 (defvar org-emph-re nil
2587 "Regular expression for matching emphasis.")
2588 (defvar org-verbatim-re nil
2589 "Regular expression for matching verbatim text.")
2590 (defvar org-emphasis-regexp-components) ; defined just below
2591 (defvar org-emphasis-alist) ; defined just below
2592 (defun org-set-emph-re (var val)
2593 "Set variable and compute the emphasis regular expression."
2594 (set var val)
2595 (when (and (boundp 'org-emphasis-alist)
2596 (boundp 'org-emphasis-regexp-components)
2597 org-emphasis-alist org-emphasis-regexp-components)
2598 (let* ((e org-emphasis-regexp-components)
2599 (pre (car e))
2600 (post (nth 1 e))
2601 (border (nth 2 e))
2602 (body (nth 3 e))
2603 (nl (nth 4 e))
2604 (body1 (concat body "*?"))
2605 (markers (mapconcat 'car org-emphasis-alist ""))
2606 (vmarkers (mapconcat
2607 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2608 org-emphasis-alist "")))
2609 ;; make sure special characters appear at the right position in the class
2610 (if (string-match "\\^" markers)
2611 (setq markers (concat (replace-match "" t t markers) "^")))
2612 (if (string-match "-" markers)
2613 (setq markers (concat (replace-match "" t t markers) "-")))
2614 (if (string-match "\\^" vmarkers)
2615 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2616 (if (string-match "-" vmarkers)
2617 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2618 (if (> nl 0)
2619 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2620 (int-to-string nl) "\\}")))
2621 ;; Make the regexp
2622 (setq org-emph-re
2623 (concat "\\([" pre "]\\|^\\)"
2624 "\\("
2625 "\\([" markers "]\\)"
2626 "\\("
2627 "[^" border "]\\|"
2628 "[^" border "]"
2629 body1
2630 "[^" border "]"
2631 "\\)"
2632 "\\3\\)"
2633 "\\([" post "]\\|$\\)"))
2634 (setq org-verbatim-re
2635 (concat "\\([" pre "]\\|^\\)"
2636 "\\("
2637 "\\([" vmarkers "]\\)"
2638 "\\("
2639 "[^" border "]\\|"
2640 "[^" border "]"
2641 body1
2642 "[^" border "]"
2643 "\\)"
2644 "\\3\\)"
2645 "\\([" post "]\\|$\\)")))))
2647 (defcustom org-emphasis-regexp-components
2648 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2649 "Components used to build the regular expression for emphasis.
2650 This is a list with 6 entries. Terminology: In an emphasis string
2651 like \" *strong word* \", we call the initial space PREMATCH, the final
2652 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2653 and \"trong wor\" is the body. The different components in this variable
2654 specify what is allowed/forbidden in each part:
2656 pre Chars allowed as prematch. Beginning of line will be allowed too.
2657 post Chars allowed as postmatch. End of line will be allowed too.
2658 border The chars *forbidden* as border characters.
2659 body-regexp A regexp like \".\" to match a body character. Don't use
2660 non-shy groups here, and don't allow newline here.
2661 newline The maximum number of newlines allowed in an emphasis exp.
2663 Use customize to modify this, or restart Emacs after changing it."
2664 :group 'org-font-lock
2665 :set 'org-set-emph-re
2666 :type '(list
2667 (sexp :tag "Allowed chars in pre ")
2668 (sexp :tag "Allowed chars in post ")
2669 (sexp :tag "Forbidden chars in border ")
2670 (sexp :tag "Regexp for body ")
2671 (integer :tag "number of newlines allowed")
2672 (option (boolean :tag "Please ignore this button"))))
2674 (defcustom org-emphasis-alist
2675 `(("*" bold "<b>" "</b>")
2676 ("/" italic "<i>" "</i>")
2677 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2678 ("=" org-code "<code>" "</code>" verbatim)
2679 ("~" org-verbatim "<code>" "</code>" verbatim)
2680 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2681 "<del>" "</del>")
2683 "Special syntax for emphasized text.
2684 Text starting and ending with a special character will be emphasized, for
2685 example *bold*, _underlined_ and /italic/. This variable sets the marker
2686 characters, the face to be used by font-lock for highlighting in Org-mode
2687 Emacs buffers, and the HTML tags to be used for this.
2688 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2689 Use customize to modify this, or restart Emacs after changing it."
2690 :group 'org-font-lock
2691 :set 'org-set-emph-re
2692 :type '(repeat
2693 (list
2694 (string :tag "Marker character")
2695 (choice
2696 (face :tag "Font-lock-face")
2697 (plist :tag "Face property list"))
2698 (string :tag "HTML start tag")
2699 (string :tag "HTML end tag")
2700 (option (const verbatim)))))
2702 ;;; Miscellaneous options
2704 (defgroup org-completion nil
2705 "Completion in Org-mode."
2706 :tag "Org Completion"
2707 :group 'org)
2709 (defcustom org-completion-use-ido nil
2710 "Non-nil means, use ido completion wherever possible.
2711 Note that `ido-mode' must be active for this variable to be relevant.
2712 If you decide to turn this variable on, you might well want to turn off
2713 `org-outline-path-complete-in-steps'."
2714 :group 'org-completion
2715 :type 'boolean)
2717 (defcustom org-completion-fallback-command 'hippie-expand
2718 "The expansion command called by \\[org-complete] in normal context.
2719 Normal means, no org-mode-specific context."
2720 :group 'org-completion
2721 :type 'function)
2723 ;;; Functions and variables from ther packages
2724 ;; Declared here to avoid compiler warnings
2726 ;; XEmacs only
2727 (defvar outline-mode-menu-heading)
2728 (defvar outline-mode-menu-show)
2729 (defvar outline-mode-menu-hide)
2730 (defvar zmacs-regions) ; XEmacs regions
2732 ;; Emacs only
2733 (defvar mark-active)
2735 ;; Various packages
2736 (declare-function find-library-name "find-func" (library))
2737 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2738 (declare-function calendar-forward-day "cal-move" (arg))
2739 (declare-function calendar-goto-date "cal-move" (date))
2740 (declare-function calendar-goto-today "cal-move" ())
2741 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2742 (defvar calc-embedded-close-formula)
2743 (defvar calc-embedded-open-formula)
2744 (declare-function cdlatex-tab "ext:cdlatex" ())
2745 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2746 (defvar font-lock-unfontify-region-function)
2747 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2748 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2749 (defvar iswitchb-temp-buflist)
2750 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2751 (defvar org-agenda-tags-todo-honor-ignore-options)
2752 (declare-function org-agenda-skip "org-agenda" ())
2753 (declare-function org-format-agenda-item "org-agenda"
2754 (extra txt &optional category tags dotime noprefix remove-re))
2755 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2756 (declare-function org-agenda-change-all-lines "org-agenda"
2757 (newhead hdmarker &optional fixface just-this))
2758 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2759 (declare-function org-agenda-maybe-redo "org-agenda" ())
2760 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2761 (beg end))
2762 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2763 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2764 "org-agenda" (&optional end))
2766 (declare-function parse-time-string "parse-time" (string))
2767 (declare-function remember "remember" (&optional initial))
2768 (declare-function remember-buffer-desc "remember" ())
2769 (declare-function remember-finalize "remember" ())
2770 (defvar remember-save-after-remembering)
2771 (defvar remember-data-file)
2772 (defvar remember-register)
2773 (defvar remember-buffer)
2774 (defvar remember-handler-functions)
2775 (defvar remember-annotation-functions)
2776 (defvar texmathp-why)
2777 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2778 (declare-function table--at-cell-p "table" (position &optional object at-column))
2780 (defvar w3m-current-url)
2781 (defvar w3m-current-title)
2783 (defvar org-latex-regexps)
2785 ;;; Autoload and prepare some org modules
2787 ;; Some table stuff that needs to be defined here, because it is used
2788 ;; by the functions setting up org-mode or checking for table context.
2790 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2791 "Detects an org-type or table-type table.")
2792 (defconst org-table-line-regexp "^[ \t]*|"
2793 "Detects an org-type table line.")
2794 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2795 "Detects an org-type table line.")
2796 (defconst org-table-hline-regexp "^[ \t]*|-"
2797 "Detects an org-type table hline.")
2798 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2799 "Detects a table-type table hline.")
2800 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2801 "Searching from within a table (any type) this finds the first line
2802 outside the table.")
2804 ;; Autoload the functions in org-table.el that are needed by functions here.
2806 (eval-and-compile
2807 (org-autoload "org-table"
2808 '(org-table-align org-table-begin org-table-blank-field
2809 org-table-convert org-table-convert-region org-table-copy-down
2810 org-table-copy-region org-table-create
2811 org-table-create-or-convert-from-region
2812 org-table-create-with-table.el org-table-current-dline
2813 org-table-cut-region org-table-delete-column org-table-edit-field
2814 org-table-edit-formulas org-table-end org-table-eval-formula
2815 org-table-export org-table-field-info
2816 org-table-get-stored-formulas org-table-goto-column
2817 org-table-hline-and-move org-table-import org-table-insert-column
2818 org-table-insert-hline org-table-insert-row org-table-iterate
2819 org-table-justify-field-maybe org-table-kill-row
2820 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2821 org-table-move-column org-table-move-column-left
2822 org-table-move-column-right org-table-move-row
2823 org-table-move-row-down org-table-move-row-up
2824 org-table-next-field org-table-next-row org-table-paste-rectangle
2825 org-table-previous-field org-table-recalculate
2826 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2827 org-table-toggle-coordinate-overlays
2828 org-table-toggle-formula-debugger org-table-wrap-region
2829 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2831 (defun org-at-table-p (&optional table-type)
2832 "Return t if the cursor is inside an org-type table.
2833 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2834 (if org-enable-table-editor
2835 (save-excursion
2836 (beginning-of-line 1)
2837 (looking-at (if table-type org-table-any-line-regexp
2838 org-table-line-regexp)))
2839 nil))
2840 (defsubst org-table-p () (org-at-table-p))
2842 (defun org-at-table.el-p ()
2843 "Return t if and only if we are at a table.el table."
2844 (and (org-at-table-p 'any)
2845 (save-excursion
2846 (goto-char (org-table-begin 'any))
2847 (looking-at org-table1-hline-regexp))))
2848 (defun org-table-recognize-table.el ()
2849 "If there is a table.el table nearby, recognize it and move into it."
2850 (if org-table-tab-recognizes-table.el
2851 (if (org-at-table.el-p)
2852 (progn
2853 (beginning-of-line 1)
2854 (if (looking-at org-table-dataline-regexp)
2856 (if (looking-at org-table1-hline-regexp)
2857 (progn
2858 (beginning-of-line 2)
2859 (if (looking-at org-table-any-border-regexp)
2860 (beginning-of-line -1)))))
2861 (if (re-search-forward "|" (org-table-end t) t)
2862 (progn
2863 (require 'table)
2864 (if (table--at-cell-p (point))
2866 (message "recognizing table.el table...")
2867 (table-recognize-table)
2868 (message "recognizing table.el table...done")))
2869 (error "This should not happen..."))
2871 nil)
2872 nil))
2874 (defun org-at-table-hline-p ()
2875 "Return t if the cursor is inside a hline in a table."
2876 (if org-enable-table-editor
2877 (save-excursion
2878 (beginning-of-line 1)
2879 (looking-at org-table-hline-regexp))
2880 nil))
2882 (defvar org-table-clean-did-remove-column nil)
2884 (defun org-table-map-tables (function)
2885 "Apply FUNCTION to the start of all tables in the buffer."
2886 (save-excursion
2887 (save-restriction
2888 (widen)
2889 (goto-char (point-min))
2890 (while (re-search-forward org-table-any-line-regexp nil t)
2891 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2892 (beginning-of-line 1)
2893 (if (looking-at org-table-line-regexp)
2894 (save-excursion (funcall function)))
2895 (re-search-forward org-table-any-border-regexp nil 1))))
2896 (message "Mapping tables: done"))
2898 ;; Declare and autoload functions from org-exp.el
2900 (declare-function org-default-export-plist "org-exp")
2901 (declare-function org-infile-export-plist "org-exp")
2902 (declare-function org-get-current-options "org-exp")
2903 (eval-and-compile
2904 (org-autoload "org-exp"
2905 '(org-export org-export-as-ascii org-export-visible
2906 org-insert-export-options-template org-export-as-html-and-open
2907 org-export-as-html-batch org-export-as-html-to-buffer
2908 org-replace-region-by-html org-export-region-as-html
2909 org-export-as-html org-export-icalendar-this-file
2910 org-export-icalendar-all-agenda-files
2911 org-table-clean-before-export
2912 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2914 ;; Declare and autoload functions from org-agenda.el
2916 (eval-and-compile
2917 (org-autoload "org-agenda"
2918 '(org-agenda org-agenda-list org-search-view
2919 org-todo-list org-tags-view org-agenda-list-stuck-projects
2920 org-diary org-agenda-to-appt
2921 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2923 ;; Autoload org-remember
2925 (eval-and-compile
2926 (org-autoload "org-remember"
2927 '(org-remember-insinuate org-remember-annotation
2928 org-remember-apply-template org-remember org-remember-handler)))
2930 ;; Autoload org-clock.el
2933 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2934 (beg end))
2935 (declare-function org-clock-update-mode-line "org-clock" ())
2936 (defvar org-clock-start-time)
2937 (defvar org-clock-marker (make-marker)
2938 "Marker recording the last clock-in.")
2940 (eval-and-compile
2941 (org-autoload
2942 "org-clock"
2943 '(org-clock-in org-clock-out org-clock-cancel
2944 org-clock-goto org-clock-sum org-clock-display
2945 org-clock-remove-overlays org-clock-report
2946 org-clocktable-shift org-dblock-write:clocktable
2947 org-get-clocktable)))
2949 (defun org-clock-update-time-maybe ()
2950 "If this is a CLOCK line, update it and return t.
2951 Otherwise, return nil."
2952 (interactive)
2953 (save-excursion
2954 (beginning-of-line 1)
2955 (skip-chars-forward " \t")
2956 (when (looking-at org-clock-string)
2957 (let ((re (concat "[ \t]*" org-clock-string
2958 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2959 "\\([ \t]*=>.*\\)?\\)?"))
2960 ts te h m s neg)
2961 (cond
2962 ((not (looking-at re))
2963 nil)
2964 ((not (match-end 2))
2965 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2966 (> org-clock-marker (point))
2967 (<= org-clock-marker (point-at-eol)))
2968 ;; The clock is running here
2969 (setq org-clock-start-time
2970 (apply 'encode-time
2971 (org-parse-time-string (match-string 1))))
2972 (org-clock-update-mode-line)))
2974 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2975 (end-of-line 1)
2976 (setq ts (match-string 1)
2977 te (match-string 3))
2978 (setq s (- (time-to-seconds
2979 (apply 'encode-time (org-parse-time-string te)))
2980 (time-to-seconds
2981 (apply 'encode-time (org-parse-time-string ts))))
2982 neg (< s 0)
2983 s (abs s)
2984 h (floor (/ s 3600))
2985 s (- s (* 3600 h))
2986 m (floor (/ s 60))
2987 s (- s (* 60 s)))
2988 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2989 t))))))
2991 (defun org-check-running-clock ()
2992 "Check if the current buffer contains the running clock.
2993 If yes, offer to stop it and to save the buffer with the changes."
2994 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2995 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2996 (buffer-name))))
2997 (org-clock-out)
2998 (when (y-or-n-p "Save changed buffer?")
2999 (save-buffer))))
3001 (defun org-clocktable-try-shift (dir n)
3002 "Check if this line starts a clock table, if yes, shift the time block."
3003 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3004 (org-clocktable-shift dir n)))
3006 ;; Autoload org-timer.el
3008 (eval-and-compile
3009 (org-autoload
3010 "org-timer"
3011 '(org-timer-start org-timer org-timer-item
3012 org-timer-change-times-in-region)))
3014 ;; Autoload org-feed.el
3016 (eval-and-compile
3017 (org-autoload
3018 "org-feed"
3019 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3022 ;; Autoload archiving code
3023 ;; The stuff that is needed for cycling and tags has to be defined here.
3025 (defgroup org-archive nil
3026 "Options concerning archiving in Org-mode."
3027 :tag "Org Archive"
3028 :group 'org-structure)
3030 (defcustom org-archive-location "%s_archive::"
3031 "The location where subtrees should be archived.
3033 The value of this variable is a string, consisting of two parts,
3034 separated by a double-colon. The first part is a filename and
3035 the second part is a headline.
3037 When the filename is omitted, archiving happens in the same file.
3038 %s in the filename will be replaced by the current file
3039 name (without the directory part). Archiving to a different file
3040 is useful to keep archived entries from contributing to the
3041 Org-mode Agenda.
3043 The archived entries will be filed as subtrees of the specified
3044 headline. When the headline is omitted, the subtrees are simply
3045 filed away at the end of the file, as top-level entries. Also in
3046 the heading you can use %s to represent the file name, this can be
3047 useful when using the same archive for a number of different files.
3049 Here are a few examples:
3050 \"%s_archive::\"
3051 If the current file is Projects.org, archive in file
3052 Projects.org_archive, as top-level trees. This is the default.
3054 \"::* Archived Tasks\"
3055 Archive in the current file, under the top-level headline
3056 \"* Archived Tasks\".
3058 \"~/org/archive.org::\"
3059 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3061 \"~/org/archive.org::From %s\"
3062 Archive in file ~/org/archive.org (absolute path), und headlines
3063 \"From FILENAME\" where file name is the current file name.
3065 \"basement::** Finished Tasks\"
3066 Archive in file ./basement (relative path), as level 3 trees
3067 below the level 2 heading \"** Finished Tasks\".
3069 You may set this option on a per-file basis by adding to the buffer a
3070 line like
3072 #+ARCHIVE: basement::** Finished Tasks
3074 You may also define it locally for a subtree by setting an ARCHIVE property
3075 in the entry. If such a property is found in an entry, or anywhere up
3076 the hierarchy, it will be used."
3077 :group 'org-archive
3078 :type 'string)
3080 (defcustom org-archive-tag "ARCHIVE"
3081 "The tag that marks a subtree as archived.
3082 An archived subtree does not open during visibility cycling, and does
3083 not contribute to the agenda listings.
3084 After changing this, font-lock must be restarted in the relevant buffers to
3085 get the proper fontification."
3086 :group 'org-archive
3087 :group 'org-keywords
3088 :type 'string)
3090 (defcustom org-agenda-skip-archived-trees t
3091 "Non-nil means, the agenda will skip any items located in archived trees.
3092 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3093 variable is no longer recommended, you should leave it at the value t.
3094 Instead, use the key `v' to cycle the archives-mode in the agenda."
3095 :group 'org-archive
3096 :group 'org-agenda-skip
3097 :type 'boolean)
3099 (defcustom org-columns-skip-arrchived-trees t
3100 "Non-nil means, irgnore archived trees when creating column view."
3101 :group 'org-archive
3102 :group 'org-properties
3103 :type 'boolean)
3105 (defcustom org-cycle-open-archived-trees nil
3106 "Non-nil means, `org-cycle' will open archived trees.
3107 An archived tree is a tree marked with the tag ARCHIVE.
3108 When nil, archived trees will stay folded. You can still open them with
3109 normal outline commands like `show-all', but not with the cycling commands."
3110 :group 'org-archive
3111 :group 'org-cycle
3112 :type 'boolean)
3114 (defcustom org-sparse-tree-open-archived-trees nil
3115 "Non-nil means sparse tree construction shows matches in archived trees.
3116 When nil, matches in these trees are highlighted, but the trees are kept in
3117 collapsed state."
3118 :group 'org-archive
3119 :group 'org-sparse-trees
3120 :type 'boolean)
3122 (defun org-cycle-hide-archived-subtrees (state)
3123 "Re-hide all archived subtrees after a visibility state change."
3124 (when (and (not org-cycle-open-archived-trees)
3125 (not (memq state '(overview folded))))
3126 (save-excursion
3127 (let* ((globalp (memq state '(contents all)))
3128 (beg (if globalp (point-min) (point)))
3129 (end (if globalp (point-max) (org-end-of-subtree t))))
3130 (org-hide-archived-subtrees beg end)
3131 (goto-char beg)
3132 (if (looking-at (concat ".*:" org-archive-tag ":"))
3133 (message "%s" (substitute-command-keys
3134 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3136 (defun org-force-cycle-archived ()
3137 "Cycle subtree even if it is archived."
3138 (interactive)
3139 (setq this-command 'org-cycle)
3140 (let ((org-cycle-open-archived-trees t))
3141 (call-interactively 'org-cycle)))
3143 (defun org-hide-archived-subtrees (beg end)
3144 "Re-hide all archived subtrees after a visibility state change."
3145 (save-excursion
3146 (let* ((re (concat ":" org-archive-tag ":")))
3147 (goto-char beg)
3148 (while (re-search-forward re end t)
3149 (and (org-on-heading-p) (hide-subtree))
3150 (org-end-of-subtree t)))))
3152 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3154 (eval-and-compile
3155 (org-autoload "org-archive"
3156 '(org-add-archive-files org-archive-subtree
3157 org-archive-to-archive-sibling org-toggle-archive-tag)))
3159 ;; Autoload Column View Code
3161 (declare-function org-columns-number-to-string "org-colview")
3162 (declare-function org-columns-get-format-and-top-level "org-colview")
3163 (declare-function org-columns-compute "org-colview")
3165 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3166 '(org-columns-number-to-string org-columns-get-format-and-top-level
3167 org-columns-compute org-agenda-columns org-columns-remove-overlays
3168 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3170 ;; Autoload ID code
3172 (declare-function org-id-store-link "org-id")
3173 (declare-function org-id-locations-load "org-id")
3174 (declare-function org-id-locations-save "org-id")
3175 (defvar org-id-track-globally)
3176 (org-autoload "org-id"
3177 '(org-id-get-create org-id-new org-id-copy org-id-get
3178 org-id-get-with-outline-path-completion
3179 org-id-get-with-outline-drilling
3180 org-id-goto org-id-find org-id-store-link))
3182 ;; Autoload Plotting Code
3184 (org-autoload "org-plot"
3185 '(org-plot/gnuplot))
3187 ;;; Variables for pre-computed regular expressions, all buffer local
3189 (defvar org-drawer-regexp nil
3190 "Matches first line of a hidden block.")
3191 (make-variable-buffer-local 'org-drawer-regexp)
3192 (defvar org-todo-regexp nil
3193 "Matches any of the TODO state keywords.")
3194 (make-variable-buffer-local 'org-todo-regexp)
3195 (defvar org-not-done-regexp nil
3196 "Matches any of the TODO state keywords except the last one.")
3197 (make-variable-buffer-local 'org-not-done-regexp)
3198 (defvar org-todo-line-regexp nil
3199 "Matches a headline and puts TODO state into group 2 if present.")
3200 (make-variable-buffer-local 'org-todo-line-regexp)
3201 (defvar org-complex-heading-regexp nil
3202 "Matches a headline and puts everything into groups:
3203 group 1: the stars
3204 group 2: The todo keyword, maybe
3205 group 3: Priority cookie
3206 group 4: True headline
3207 group 5: Tags")
3208 (make-variable-buffer-local 'org-complex-heading-regexp)
3209 (defvar org-todo-line-tags-regexp nil
3210 "Matches a headline and puts TODO state into group 2 if present.
3211 Also put tags into group 4 if tags are present.")
3212 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3213 (defvar org-nl-done-regexp nil
3214 "Matches newline followed by a headline with the DONE keyword.")
3215 (make-variable-buffer-local 'org-nl-done-regexp)
3216 (defvar org-looking-at-done-regexp nil
3217 "Matches the DONE keyword a point.")
3218 (make-variable-buffer-local 'org-looking-at-done-regexp)
3219 (defvar org-ds-keyword-length 12
3220 "Maximum length of the Deadline and SCHEDULED keywords.")
3221 (make-variable-buffer-local 'org-ds-keyword-length)
3222 (defvar org-deadline-regexp nil
3223 "Matches the DEADLINE keyword.")
3224 (make-variable-buffer-local 'org-deadline-regexp)
3225 (defvar org-deadline-time-regexp nil
3226 "Matches the DEADLINE keyword together with a time stamp.")
3227 (make-variable-buffer-local 'org-deadline-time-regexp)
3228 (defvar org-deadline-line-regexp nil
3229 "Matches the DEADLINE keyword and the rest of the line.")
3230 (make-variable-buffer-local 'org-deadline-line-regexp)
3231 (defvar org-scheduled-regexp nil
3232 "Matches the SCHEDULED keyword.")
3233 (make-variable-buffer-local 'org-scheduled-regexp)
3234 (defvar org-scheduled-time-regexp nil
3235 "Matches the SCHEDULED keyword together with a time stamp.")
3236 (make-variable-buffer-local 'org-scheduled-time-regexp)
3237 (defvar org-closed-time-regexp nil
3238 "Matches the CLOSED keyword together with a time stamp.")
3239 (make-variable-buffer-local 'org-closed-time-regexp)
3241 (defvar org-keyword-time-regexp nil
3242 "Matches any of the 4 keywords, together with the time stamp.")
3243 (make-variable-buffer-local 'org-keyword-time-regexp)
3244 (defvar org-keyword-time-not-clock-regexp nil
3245 "Matches any of the 3 keywords, together with the time stamp.")
3246 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3247 (defvar org-maybe-keyword-time-regexp nil
3248 "Matches a timestamp, possibly preceeded by a keyword.")
3249 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3250 (defvar org-planning-or-clock-line-re nil
3251 "Matches a line with planning or clock info.")
3252 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3254 (defconst org-plain-time-of-day-regexp
3255 (concat
3256 "\\(\\<[012]?[0-9]"
3257 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3258 "\\(--?"
3259 "\\(\\<[012]?[0-9]"
3260 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3261 "\\)?")
3262 "Regular expression to match a plain time or time range.
3263 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3264 groups carry important information:
3265 0 the full match
3266 1 the first time, range or not
3267 8 the second time, if it is a range.")
3269 (defconst org-plain-time-extension-regexp
3270 (concat
3271 "\\(\\<[012]?[0-9]"
3272 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3273 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3274 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3275 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3276 groups carry important information:
3277 0 the full match
3278 7 hours of duration
3279 9 minutes of duration")
3281 (defconst org-stamp-time-of-day-regexp
3282 (concat
3283 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3284 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3285 "\\(--?"
3286 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3287 "Regular expression to match a timestamp time or time range.
3288 After a match, the following groups carry important information:
3289 0 the full match
3290 1 date plus weekday, for backreferencing to make sure both times on same day
3291 2 the first time, range or not
3292 4 the second time, if it is a range.")
3294 (defconst org-startup-options
3295 '(("fold" org-startup-folded t)
3296 ("overview" org-startup-folded t)
3297 ("nofold" org-startup-folded nil)
3298 ("showall" org-startup-folded nil)
3299 ("content" org-startup-folded content)
3300 ("hidestars" org-hide-leading-stars t)
3301 ("showstars" org-hide-leading-stars nil)
3302 ("odd" org-odd-levels-only t)
3303 ("oddeven" org-odd-levels-only nil)
3304 ("align" org-startup-align-all-tables t)
3305 ("noalign" org-startup-align-all-tables nil)
3306 ("customtime" org-display-custom-times t)
3307 ("logdone" org-log-done time)
3308 ("lognotedone" org-log-done note)
3309 ("nologdone" org-log-done nil)
3310 ("lognoteclock-out" org-log-note-clock-out t)
3311 ("nolognoteclock-out" org-log-note-clock-out nil)
3312 ("logrepeat" org-log-repeat state)
3313 ("lognoterepeat" org-log-repeat note)
3314 ("nologrepeat" org-log-repeat nil)
3315 ("fninline" org-footnote-define-inline t)
3316 ("nofninline" org-footnote-define-inline nil)
3317 ("fnlocal" org-footnote-section nil)
3318 ("fnauto" org-footnote-auto-label t)
3319 ("fnprompt" org-footnote-auto-label nil)
3320 ("fnconfirm" org-footnote-auto-label confirm)
3321 ("fnplain" org-footnote-auto-label plain)
3322 ("constcgs" constants-unit-system cgs)
3323 ("constSI" constants-unit-system SI)
3324 ("noptag" org-tag-persistent-alist nil))
3325 "Variable associated with STARTUP options for org-mode.
3326 Each element is a list of three items: The startup options as written
3327 in the #+STARTUP line, the corresponding variable, and the value to
3328 set this variable to if the option is found. An optional forth element PUSH
3329 means to push this value onto the list in the variable.")
3331 (defun org-set-regexps-and-options ()
3332 "Precompute regular expressions for current buffer."
3333 (when (org-mode-p)
3334 (org-set-local 'org-todo-kwd-alist nil)
3335 (org-set-local 'org-todo-key-alist nil)
3336 (org-set-local 'org-todo-key-trigger nil)
3337 (org-set-local 'org-todo-keywords-1 nil)
3338 (org-set-local 'org-done-keywords nil)
3339 (org-set-local 'org-todo-heads nil)
3340 (org-set-local 'org-todo-sets nil)
3341 (org-set-local 'org-todo-log-states nil)
3342 (org-set-local 'org-file-properties nil)
3343 (org-set-local 'org-file-tags nil)
3344 (let ((re (org-make-options-regexp
3345 '("CATEGORY" "TODO" "COLUMNS"
3346 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3347 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3348 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3349 (splitre "[ \t]+")
3350 kwds kws0 kwsa key log value cat arch tags const links hw dws
3351 tail sep kws1 prio props ftags drawers
3352 ext-setup-or-nil setup-contents (start 0))
3353 (save-excursion
3354 (save-restriction
3355 (widen)
3356 (goto-char (point-min))
3357 (while (or (and ext-setup-or-nil
3358 (string-match re ext-setup-or-nil start)
3359 (setq start (match-end 0)))
3360 (and (setq ext-setup-or-nil nil start 0)
3361 (re-search-forward re nil t)))
3362 (setq key (upcase (match-string 1 ext-setup-or-nil))
3363 value (org-match-string-no-properties 2 ext-setup-or-nil))
3364 (cond
3365 ((equal key "CATEGORY")
3366 (if (string-match "[ \t]+$" value)
3367 (setq value (replace-match "" t t value)))
3368 (setq cat value))
3369 ((member key '("SEQ_TODO" "TODO"))
3370 (push (cons 'sequence (org-split-string value splitre)) kwds))
3371 ((equal key "TYP_TODO")
3372 (push (cons 'type (org-split-string value splitre)) kwds))
3373 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3374 ;; general TODO-like setup
3375 (push (cons (intern (downcase (match-string 1 key)))
3376 (org-split-string value splitre)) kwds))
3377 ((equal key "TAGS")
3378 (setq tags (append tags (if tags '("\\n") nil)
3379 (org-split-string value splitre))))
3380 ((equal key "COLUMNS")
3381 (org-set-local 'org-columns-default-format value))
3382 ((equal key "LINK")
3383 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3384 (push (cons (match-string 1 value)
3385 (org-trim (match-string 2 value)))
3386 links)))
3387 ((equal key "PRIORITIES")
3388 (setq prio (org-split-string value " +")))
3389 ((equal key "PROPERTY")
3390 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3391 (push (cons (match-string 1 value) (match-string 2 value))
3392 props)))
3393 ((equal key "FILETAGS")
3394 (when (string-match "\\S-" value)
3395 (setq ftags
3396 (append
3397 ftags
3398 (apply 'append
3399 (mapcar (lambda (x) (org-split-string x ":"))
3400 (org-split-string value)))))))
3401 ((equal key "DRAWERS")
3402 (setq drawers (org-split-string value splitre)))
3403 ((equal key "CONSTANTS")
3404 (setq const (append const (org-split-string value splitre))))
3405 ((equal key "STARTUP")
3406 (let ((opts (org-split-string value splitre))
3407 l var val)
3408 (while (setq l (pop opts))
3409 (when (setq l (assoc l org-startup-options))
3410 (setq var (nth 1 l) val (nth 2 l))
3411 (if (not (nth 3 l))
3412 (set (make-local-variable var) val)
3413 (if (not (listp (symbol-value var)))
3414 (set (make-local-variable var) nil))
3415 (set (make-local-variable var) (symbol-value var))
3416 (add-to-list var val))))))
3417 ((equal key "ARCHIVE")
3418 (string-match " *$" value)
3419 (setq arch (replace-match "" t t value))
3420 (remove-text-properties 0 (length arch)
3421 '(face t fontified t) arch))
3422 ((equal key "SETUPFILE")
3423 (setq setup-contents (org-file-contents
3424 (expand-file-name
3425 (org-remove-double-quotes value))
3426 'noerror))
3427 (if (not ext-setup-or-nil)
3428 (setq ext-setup-or-nil setup-contents start 0)
3429 (setq ext-setup-or-nil
3430 (concat (substring ext-setup-or-nil 0 start)
3431 "\n" setup-contents "\n"
3432 (substring ext-setup-or-nil start)))))
3433 ))))
3434 (when cat
3435 (org-set-local 'org-category (intern cat))
3436 (push (cons "CATEGORY" cat) props))
3437 (when prio
3438 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3439 (setq prio (mapcar 'string-to-char prio))
3440 (org-set-local 'org-highest-priority (nth 0 prio))
3441 (org-set-local 'org-lowest-priority (nth 1 prio))
3442 (org-set-local 'org-default-priority (nth 2 prio)))
3443 (and props (org-set-local 'org-file-properties (nreverse props)))
3444 (and ftags (org-set-local 'org-file-tags
3445 (mapcar 'org-add-prop-inherited ftags)))
3446 (and drawers (org-set-local 'org-drawers drawers))
3447 (and arch (org-set-local 'org-archive-location arch))
3448 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3449 ;; Process the TODO keywords
3450 (unless kwds
3451 ;; Use the global values as if they had been given locally.
3452 (setq kwds (default-value 'org-todo-keywords))
3453 (if (stringp (car kwds))
3454 (setq kwds (list (cons org-todo-interpretation
3455 (default-value 'org-todo-keywords)))))
3456 (setq kwds (reverse kwds)))
3457 (setq kwds (nreverse kwds))
3458 (let (inter kws kw)
3459 (while (setq kws (pop kwds))
3460 (let ((kws (or
3461 (run-hook-with-args-until-success
3462 'org-todo-setup-filter-hook kws)
3463 kws)))
3464 (setq inter (pop kws) sep (member "|" kws)
3465 kws0 (delete "|" (copy-sequence kws))
3466 kwsa nil
3467 kws1 (mapcar
3468 (lambda (x)
3469 ;; 1 2
3470 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3471 (progn
3472 (setq kw (match-string 1 x)
3473 key (and (match-end 2) (match-string 2 x))
3474 log (org-extract-log-state-settings x))
3475 (push (cons kw (and key (string-to-char key))) kwsa)
3476 (and log (push log org-todo-log-states))
3478 (error "Invalid TODO keyword %s" x)))
3479 kws0)
3480 kwsa (if kwsa (append '((:startgroup))
3481 (nreverse kwsa)
3482 '((:endgroup))))
3483 hw (car kws1)
3484 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3485 tail (list inter hw (car dws) (org-last dws))))
3486 (add-to-list 'org-todo-heads hw 'append)
3487 (push kws1 org-todo-sets)
3488 (setq org-done-keywords (append org-done-keywords dws nil))
3489 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3490 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3491 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3492 (setq org-todo-sets (nreverse org-todo-sets)
3493 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3494 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3495 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3496 ;; Process the constants
3497 (when const
3498 (let (e cst)
3499 (while (setq e (pop const))
3500 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3501 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3502 (setq org-table-formula-constants-local cst)))
3504 ;; Process the tags.
3505 (when tags
3506 (let (e tgs)
3507 (while (setq e (pop tags))
3508 (cond
3509 ((equal e "{") (push '(:startgroup) tgs))
3510 ((equal e "}") (push '(:endgroup) tgs))
3511 ((equal e "\\n") (push '(:newline) tgs))
3512 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3513 (push (cons (match-string 1 e)
3514 (string-to-char (match-string 2 e)))
3515 tgs))
3516 (t (push (list e) tgs))))
3517 (org-set-local 'org-tag-alist nil)
3518 (while (setq e (pop tgs))
3519 (or (and (stringp (car e))
3520 (assoc (car e) org-tag-alist))
3521 (push e org-tag-alist)))))
3523 ;; Compute the regular expressions and other local variables
3524 (if (not org-done-keywords)
3525 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3526 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3527 (length org-scheduled-string)
3528 (length org-clock-string)
3529 (length org-closed-string)))
3530 org-drawer-regexp
3531 (concat "^[ \t]*:\\("
3532 (mapconcat 'regexp-quote org-drawers "\\|")
3533 "\\):[ \t]*$")
3534 org-not-done-keywords
3535 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3536 org-todo-regexp
3537 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3538 "\\|") "\\)\\>")
3539 org-not-done-regexp
3540 (concat "\\<\\("
3541 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3542 "\\)\\>")
3543 org-todo-line-regexp
3544 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3545 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3546 "\\)\\>\\)?[ \t]*\\(.*\\)")
3547 org-complex-heading-regexp
3548 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3549 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3550 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3551 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3552 org-nl-done-regexp
3553 (concat "\n\\*+[ \t]+"
3554 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3555 "\\)" "\\>")
3556 org-todo-line-tags-regexp
3557 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3558 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3559 (org-re
3560 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3561 org-looking-at-done-regexp
3562 (concat "^" "\\(?:"
3563 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3564 "\\>")
3565 org-deadline-regexp (concat "\\<" org-deadline-string)
3566 org-deadline-time-regexp
3567 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3568 org-deadline-line-regexp
3569 (concat "\\<\\(" org-deadline-string "\\).*")
3570 org-scheduled-regexp
3571 (concat "\\<" org-scheduled-string)
3572 org-scheduled-time-regexp
3573 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3574 org-closed-time-regexp
3575 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3576 org-keyword-time-regexp
3577 (concat "\\<\\(" org-scheduled-string
3578 "\\|" org-deadline-string
3579 "\\|" org-closed-string
3580 "\\|" org-clock-string "\\)"
3581 " *[[<]\\([^]>]+\\)[]>]")
3582 org-keyword-time-not-clock-regexp
3583 (concat "\\<\\(" org-scheduled-string
3584 "\\|" org-deadline-string
3585 "\\|" org-closed-string
3586 "\\)"
3587 " *[[<]\\([^]>]+\\)[]>]")
3588 org-maybe-keyword-time-regexp
3589 (concat "\\(\\<\\(" org-scheduled-string
3590 "\\|" org-deadline-string
3591 "\\|" org-closed-string
3592 "\\|" org-clock-string "\\)\\)?"
3593 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3594 org-planning-or-clock-line-re
3595 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3596 "\\|" org-deadline-string
3597 "\\|" org-closed-string "\\|" org-clock-string
3598 "\\)\\>\\)")
3600 (org-compute-latex-and-specials-regexp)
3601 (org-set-font-lock-defaults))))
3603 (defun org-file-contents (file &optional noerror)
3604 "Return the contents of FILE, as a string."
3605 (if (or (not file)
3606 (not (file-readable-p file)))
3607 (if noerror
3608 (progn
3609 (message "Cannot read file %s" file)
3610 (ding) (sit-for 2)
3612 (error "Cannot read file %s" file))
3613 (with-temp-buffer
3614 (insert-file-contents file)
3615 (buffer-string))))
3617 (defun org-extract-log-state-settings (x)
3618 "Extract the log state setting from a TODO keyword string.
3619 This will extract info from a string like \"WAIT(w@/!)\"."
3620 (let (kw key log1 log2)
3621 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3622 (setq kw (match-string 1 x)
3623 key (and (match-end 2) (match-string 2 x))
3624 log1 (and (match-end 3) (match-string 3 x))
3625 log2 (and (match-end 4) (match-string 4 x)))
3626 (and (or log1 log2)
3627 (list kw
3628 (and log1 (if (equal log1 "!") 'time 'note))
3629 (and log2 (if (equal log2 "!") 'time 'note)))))))
3631 (defun org-remove-keyword-keys (list)
3632 "Remove a pair of parenthesis at the end of each string in LIST."
3633 (mapcar (lambda (x)
3634 (if (string-match "(.*)$" x)
3635 (substring x 0 (match-beginning 0))
3637 list))
3639 ;; FIXME: this could be done much better, using second characters etc.
3640 (defun org-assign-fast-keys (alist)
3641 "Assign fast keys to a keyword-key alist.
3642 Respect keys that are already there."
3643 (let (new e k c c1 c2 (char ?a))
3644 (while (setq e (pop alist))
3645 (cond
3646 ((equal e '(:startgroup)) (push e new))
3647 ((equal e '(:endgroup)) (push e new))
3648 ((equal e '(:newline)) (push e new))
3650 (setq k (car e) c2 nil)
3651 (if (cdr e)
3652 (setq c (cdr e))
3653 ;; automatically assign a character.
3654 (setq c1 (string-to-char
3655 (downcase (substring
3656 k (if (= (string-to-char k) ?@) 1 0)))))
3657 (if (or (rassoc c1 new) (rassoc c1 alist))
3658 (while (or (rassoc char new) (rassoc char alist))
3659 (setq char (1+ char)))
3660 (setq c2 c1))
3661 (setq c (or c2 char)))
3662 (push (cons k c) new))))
3663 (nreverse new)))
3665 ;;; Some variables used in various places
3667 (defvar org-window-configuration nil
3668 "Used in various places to store a window configuration.")
3669 (defvar org-finish-function nil
3670 "Function to be called when `C-c C-c' is used.
3671 This is for getting out of special buffers like remember.")
3674 ;; FIXME: Occasionally check by commenting these, to make sure
3675 ;; no other functions uses these, forgetting to let-bind them.
3676 (defvar entry)
3677 (defvar state)
3678 (defvar last-state)
3679 (defvar date)
3680 (defvar description)
3682 ;; Defined somewhere in this file, but used before definition.
3683 (defvar org-html-entities)
3684 (defvar org-struct-menu)
3685 (defvar org-org-menu)
3686 (defvar org-tbl-menu)
3687 (defvar org-agenda-keymap)
3689 ;;;; Define the Org-mode
3691 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3692 (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."))
3695 ;; We use a before-change function to check if a table might need
3696 ;; an update.
3697 (defvar org-table-may-need-update t
3698 "Indicates that a table might need an update.
3699 This variable is set by `org-before-change-function'.
3700 `org-table-align' sets it back to nil.")
3701 (defun org-before-change-function (beg end)
3702 "Every change indicates that a table might need an update."
3703 (setq org-table-may-need-update t))
3704 (defvar org-mode-map)
3705 (defvar org-mode-hook nil
3706 "Mode hook for Org-mode, run after the mode was turned on.")
3707 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3708 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3709 (defvar org-table-buffer-is-an nil)
3710 (defconst org-outline-regexp "\\*+ ")
3712 ;;;###autoload
3713 (define-derived-mode org-mode outline-mode "Org"
3714 "Outline-based notes management and organizer, alias
3715 \"Carsten's outline-mode for keeping track of everything.\"
3717 Org-mode develops organizational tasks around a NOTES file which
3718 contains information about projects as plain text. Org-mode is
3719 implemented on top of outline-mode, which is ideal to keep the content
3720 of large files well structured. It supports ToDo items, deadlines and
3721 time stamps, which magically appear in the diary listing of the Emacs
3722 calendar. Tables are easily created with a built-in table editor.
3723 Plain text URL-like links connect to websites, emails (VM), Usenet
3724 messages (Gnus), BBDB entries, and any files related to the project.
3725 For printing and sharing of notes, an Org-mode file (or a part of it)
3726 can be exported as a structured ASCII or HTML file.
3728 The following commands are available:
3730 \\{org-mode-map}"
3732 ;; Get rid of Outline menus, they are not needed
3733 ;; Need to do this here because define-derived-mode sets up
3734 ;; the keymap so late. Still, it is a waste to call this each time
3735 ;; we switch another buffer into org-mode.
3736 (if (featurep 'xemacs)
3737 (when (boundp 'outline-mode-menu-heading)
3738 ;; Assume this is Greg's port, it used easymenu
3739 (easy-menu-remove outline-mode-menu-heading)
3740 (easy-menu-remove outline-mode-menu-show)
3741 (easy-menu-remove outline-mode-menu-hide))
3742 (define-key org-mode-map [menu-bar headings] 'undefined)
3743 (define-key org-mode-map [menu-bar hide] 'undefined)
3744 (define-key org-mode-map [menu-bar show] 'undefined))
3746 (org-load-modules-maybe)
3747 (easy-menu-add org-org-menu)
3748 (easy-menu-add org-tbl-menu)
3749 (org-install-agenda-files-menu)
3750 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3751 (org-add-to-invisibility-spec '(org-cwidth))
3752 (when (featurep 'xemacs)
3753 (org-set-local 'line-move-ignore-invisible t))
3754 (org-set-local 'outline-regexp org-outline-regexp)
3755 (org-set-local 'outline-level 'org-outline-level)
3756 (when (and org-ellipsis
3757 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3758 (fboundp 'make-glyph-code))
3759 (unless org-display-table
3760 (setq org-display-table (make-display-table)))
3761 (set-display-table-slot
3762 org-display-table 4
3763 (vconcat (mapcar
3764 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3765 org-ellipsis)))
3766 (if (stringp org-ellipsis) org-ellipsis "..."))))
3767 (setq buffer-display-table org-display-table))
3768 (org-set-regexps-and-options)
3769 (when (and org-tag-faces (not org-tags-special-faces-re))
3770 ;; tag faces set outside customize.... force initialization.
3771 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3772 ;; Calc embedded
3773 (org-set-local 'calc-embedded-open-mode "# ")
3774 (modify-syntax-entry ?# "<")
3775 (modify-syntax-entry ?@ "w")
3776 (if org-startup-truncated (setq truncate-lines t))
3777 (org-set-local 'font-lock-unfontify-region-function
3778 'org-unfontify-region)
3779 ;; Activate before-change-function
3780 (org-set-local 'org-table-may-need-update t)
3781 (org-add-hook 'before-change-functions 'org-before-change-function nil
3782 'local)
3783 ;; Check for running clock before killing a buffer
3784 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3785 ;; Paragraphs and auto-filling
3786 (org-set-autofill-regexps)
3787 (setq indent-line-function 'org-indent-line-function)
3788 (org-update-radio-target-regexp)
3789 ;; Make sure dependence stuff works reliably, even for users who set it
3790 ;; too late :-(
3791 (if org-enforce-todo-dependencies
3792 (add-hook 'org-blocker-hook
3793 'org-block-todo-from-children-or-siblings)
3794 (remove-hook 'org-blocker-hook
3795 'org-block-todo-from-children-or-siblings))
3796 (if org-enforce-todo-checkbox-dependencies
3797 (add-hook 'org-blocker-hook
3798 'org-block-todo-from-checkboxes)
3799 (remove-hook 'org-blocker-hook
3800 'org-block-todo-from-checkboxes))
3802 ;; Comment characters
3803 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3804 (org-set-local 'comment-padding " ")
3806 ;; Align options lines
3807 (org-set-local
3808 'align-mode-rules-list
3809 '((org-in-buffer-settings
3810 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3811 (modes . '(org-mode)))))
3813 ;; Imenu
3814 (org-set-local 'imenu-create-index-function
3815 'org-imenu-get-tree)
3817 ;; Make isearch reveal context
3818 (if (or (featurep 'xemacs)
3819 (not (boundp 'outline-isearch-open-invisible-function)))
3820 ;; Emacs 21 and XEmacs make use of the hook
3821 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3822 ;; Emacs 22 deals with this through a special variable
3823 (org-set-local 'outline-isearch-open-invisible-function
3824 (lambda (&rest ignore) (org-show-context 'isearch))))
3826 ;; If empty file that did not turn on org-mode automatically, make it to.
3827 (if (and org-insert-mode-line-in-empty-file
3828 (interactive-p)
3829 (= (point-min) (point-max)))
3830 (insert "# -*- mode: org -*-\n\n"))
3832 (unless org-inhibit-startup
3833 (when org-startup-align-all-tables
3834 (let ((bmp (buffer-modified-p)))
3835 (org-table-map-tables 'org-table-align)
3836 (set-buffer-modified-p bmp)))
3837 (org-set-startup-visibility)))
3839 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3841 (defun org-current-time ()
3842 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3843 (if (> (car org-time-stamp-rounding-minutes) 1)
3844 (let ((r (car org-time-stamp-rounding-minutes))
3845 (time (decode-time)))
3846 (apply 'encode-time
3847 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3848 (nthcdr 2 time))))
3849 (current-time)))
3851 ;;;; Font-Lock stuff, including the activators
3853 (defvar org-mouse-map (make-sparse-keymap))
3854 (org-defkey org-mouse-map
3855 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3856 (org-defkey org-mouse-map
3857 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3858 (when org-mouse-1-follows-link
3859 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3860 (when org-tab-follows-link
3861 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3862 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3864 (require 'font-lock)
3866 (defconst org-non-link-chars "]\t\n\r<>")
3867 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3868 "shell" "elisp"))
3869 (defvar org-link-types-re nil
3870 "Matches a link that has a url-like prefix like \"http:\"")
3871 (defvar org-link-re-with-space nil
3872 "Matches a link with spaces, optional angular brackets around it.")
3873 (defvar org-link-re-with-space2 nil
3874 "Matches a link with spaces, optional angular brackets around it.")
3875 (defvar org-link-re-with-space3 nil
3876 "Matches a link with spaces, only for internal part in bracket links.")
3877 (defvar org-angle-link-re nil
3878 "Matches link with angular brackets, spaces are allowed.")
3879 (defvar org-plain-link-re nil
3880 "Matches plain link, without spaces.")
3881 (defvar org-bracket-link-regexp nil
3882 "Matches a link in double brackets.")
3883 (defvar org-bracket-link-analytic-regexp nil
3884 "Regular expression used to analyze links.
3885 Here is what the match groups contain after a match:
3886 1: http:
3887 2: http
3888 3: path
3889 4: [desc]
3890 5: desc")
3891 (defvar org-bracket-link-analytic-regexp++ nil
3892 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3893 (defvar org-any-link-re nil
3894 "Regular expression matching any link.")
3896 (defun org-make-link-regexps ()
3897 "Update the link regular expressions.
3898 This should be called after the variable `org-link-types' has changed."
3899 (setq org-link-types-re
3900 (concat
3901 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3902 org-link-re-with-space
3903 (concat
3904 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3905 "\\([^" org-non-link-chars " ]"
3906 "[^" org-non-link-chars "]*"
3907 "[^" org-non-link-chars " ]\\)>?")
3908 org-link-re-with-space2
3909 (concat
3910 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3911 "\\([^" org-non-link-chars " ]"
3912 "[^\t\n\r]*"
3913 "[^" org-non-link-chars " ]\\)>?")
3914 org-link-re-with-space3
3915 (concat
3916 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3917 "\\([^" org-non-link-chars " ]"
3918 "[^\t\n\r]*\\)")
3919 org-angle-link-re
3920 (concat
3921 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3922 "\\([^" org-non-link-chars " ]"
3923 "[^" org-non-link-chars "]*"
3924 "\\)>")
3925 org-plain-link-re
3926 (concat
3927 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3928 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3929 org-bracket-link-regexp
3930 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3931 org-bracket-link-analytic-regexp
3932 (concat
3933 "\\[\\["
3934 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3935 "\\([^]]+\\)"
3936 "\\]"
3937 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3938 "\\]")
3939 org-bracket-link-analytic-regexp++
3940 (concat
3941 "\\[\\["
3942 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3943 "\\([^]]+\\)"
3944 "\\]"
3945 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3946 "\\]")
3947 org-any-link-re
3948 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3949 org-angle-link-re "\\)\\|\\("
3950 org-plain-link-re "\\)")))
3952 (org-make-link-regexps)
3954 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3955 "Regular expression for fast time stamp matching.")
3956 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3957 "Regular expression for fast time stamp matching.")
3958 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3959 "Regular expression matching time strings for analysis.
3960 This one does not require the space after the date, so it can be used
3961 on a string that terminates immediately after the date.")
3962 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3963 "Regular expression matching time strings for analysis.")
3964 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3965 "Regular expression matching time stamps, with groups.")
3966 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3967 "Regular expression matching time stamps (also [..]), with groups.")
3968 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3969 "Regular expression matching a time stamp range.")
3970 (defconst org-tr-regexp-both
3971 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3972 "Regular expression matching a time stamp range.")
3973 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3974 org-ts-regexp "\\)?")
3975 "Regular expression matching a time stamp or time stamp range.")
3976 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3977 org-ts-regexp-both "\\)?")
3978 "Regular expression matching a time stamp or time stamp range.
3979 The time stamps may be either active or inactive.")
3981 (defvar org-emph-face nil)
3983 (defun org-do-emphasis-faces (limit)
3984 "Run through the buffer and add overlays to links."
3985 (let (rtn)
3986 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3987 (if (not (= (char-after (match-beginning 3))
3988 (char-after (match-beginning 4))))
3989 (progn
3990 (setq rtn t)
3991 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3992 'face
3993 (nth 1 (assoc (match-string 3)
3994 org-emphasis-alist)))
3995 (add-text-properties (match-beginning 2) (match-end 2)
3996 '(font-lock-multiline t))
3997 (when org-hide-emphasis-markers
3998 (add-text-properties (match-end 4) (match-beginning 5)
3999 '(invisible org-link))
4000 (add-text-properties (match-beginning 3) (match-end 3)
4001 '(invisible org-link)))))
4002 (backward-char 1))
4003 rtn))
4005 (defun org-emphasize (&optional char)
4006 "Insert or change an emphasis, i.e. a font like bold or italic.
4007 If there is an active region, change that region to a new emphasis.
4008 If there is no region, just insert the marker characters and position
4009 the cursor between them.
4010 CHAR should be either the marker character, or the first character of the
4011 HTML tag associated with that emphasis. If CHAR is a space, the means
4012 to remove the emphasis of the selected region.
4013 If char is not given (for example in an interactive call) it
4014 will be prompted for."
4015 (interactive)
4016 (let ((eal org-emphasis-alist) e det
4017 (erc org-emphasis-regexp-components)
4018 (prompt "")
4019 (string "") beg end move tag c s)
4020 (if (org-region-active-p)
4021 (setq beg (region-beginning) end (region-end)
4022 string (buffer-substring beg end))
4023 (setq move t))
4025 (while (setq e (pop eal))
4026 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4027 c (aref tag 0))
4028 (push (cons c (string-to-char (car e))) det)
4029 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4030 (substring tag 1)))))
4031 (setq det (nreverse det))
4032 (unless char
4033 (message "%s" (concat "Emphasis marker or tag:" prompt))
4034 (setq char (read-char-exclusive)))
4035 (setq char (or (cdr (assoc char det)) char))
4036 (if (equal char ?\ )
4037 (setq s "" move nil)
4038 (unless (assoc (char-to-string char) org-emphasis-alist)
4039 (error "No such emphasis marker: \"%c\"" char))
4040 (setq s (char-to-string char)))
4041 (while (and (> (length string) 1)
4042 (equal (substring string 0 1) (substring string -1))
4043 (assoc (substring string 0 1) org-emphasis-alist))
4044 (setq string (substring string 1 -1)))
4045 (setq string (concat s string s))
4046 (if beg (delete-region beg end))
4047 (unless (or (bolp)
4048 (string-match (concat "[" (nth 0 erc) "\n]")
4049 (char-to-string (char-before (point)))))
4050 (insert " "))
4051 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4052 (char-to-string (char-after (point))))
4053 (insert " ") (backward-char 1))
4054 (insert string)
4055 (and move (backward-char 1))))
4057 (defconst org-nonsticky-props
4058 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4061 (defun org-activate-plain-links (limit)
4062 "Run through the buffer and add overlays to links."
4063 (catch 'exit
4064 (let (f)
4065 (while (re-search-forward org-plain-link-re limit t)
4066 (setq f (get-text-property (match-beginning 0) 'face))
4067 (if (or (eq f 'org-tag)
4068 (and (listp f) (memq 'org-tag f)))
4070 (add-text-properties (match-beginning 0) (match-end 0)
4071 (list 'mouse-face 'highlight
4072 'rear-nonsticky org-nonsticky-props
4073 'keymap org-mouse-map
4075 (throw 'exit t))))))
4077 (defun org-activate-code (limit)
4078 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4079 (progn
4080 (remove-text-properties (match-beginning 0) (match-end 0)
4081 '(display t invisible t intangible t))
4082 t)))
4084 (defun org-activate-angle-links (limit)
4085 "Run through the buffer and add overlays to links."
4086 (if (re-search-forward org-angle-link-re limit t)
4087 (progn
4088 (add-text-properties (match-beginning 0) (match-end 0)
4089 (list 'mouse-face 'highlight
4090 'rear-nonsticky org-nonsticky-props
4091 'keymap org-mouse-map
4093 t)))
4095 (defun org-activate-footnote-links (limit)
4096 "Run through the buffer and add overlays to links."
4097 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4098 limit t)
4099 (progn
4100 (add-text-properties (match-beginning 2) (match-end 2)
4101 (list 'mouse-face 'highlight
4102 'rear-nonsticky org-nonsticky-props
4103 'keymap org-mouse-map
4104 'help-echo
4105 (if (= (point-at-bol) (match-beginning 2))
4106 "Footnote definition"
4107 "Footnote reference")
4109 t)))
4111 (defun org-activate-bracket-links (limit)
4112 "Run through the buffer and add overlays to bracketed links."
4113 (if (re-search-forward org-bracket-link-regexp limit t)
4114 (let* ((help (concat "LINK: "
4115 (org-match-string-no-properties 1)))
4116 ;; FIXME: above we should remove the escapes.
4117 ;; but that requires another match, protecting match data,
4118 ;; a lot of overhead for font-lock.
4119 (ip (org-maybe-intangible
4120 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4121 'keymap org-mouse-map 'mouse-face 'highlight
4122 'font-lock-multiline t 'help-echo help)))
4123 (vp (list 'rear-nonsticky org-nonsticky-props
4124 'keymap org-mouse-map 'mouse-face 'highlight
4125 'font-lock-multiline t 'help-echo help)))
4126 ;; We need to remove the invisible property here. Table narrowing
4127 ;; may have made some of this invisible.
4128 (remove-text-properties (match-beginning 0) (match-end 0)
4129 '(invisible nil))
4130 (if (match-end 3)
4131 (progn
4132 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4133 (add-text-properties (match-beginning 3) (match-end 3) vp)
4134 (add-text-properties (match-end 3) (match-end 0) ip))
4135 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4136 (add-text-properties (match-beginning 1) (match-end 1) vp)
4137 (add-text-properties (match-end 1) (match-end 0) ip))
4138 t)))
4140 (defun org-activate-dates (limit)
4141 "Run through the buffer and add overlays to dates."
4142 (if (re-search-forward org-tsr-regexp-both limit t)
4143 (progn
4144 (add-text-properties (match-beginning 0) (match-end 0)
4145 (list 'mouse-face 'highlight
4146 'rear-nonsticky org-nonsticky-props
4147 'keymap org-mouse-map))
4148 (when org-display-custom-times
4149 (if (match-end 3)
4150 (org-display-custom-time (match-beginning 3) (match-end 3)))
4151 (org-display-custom-time (match-beginning 1) (match-end 1)))
4152 t)))
4154 (defvar org-target-link-regexp nil
4155 "Regular expression matching radio targets in plain text.")
4156 (make-variable-buffer-local 'org-target-link-regexp)
4157 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4158 "Regular expression matching a link target.")
4159 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4160 "Regular expression matching a radio target.")
4161 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4162 "Regular expression matching any target.")
4164 (defun org-activate-target-links (limit)
4165 "Run through the buffer and add overlays to target matches."
4166 (when org-target-link-regexp
4167 (let ((case-fold-search t))
4168 (if (re-search-forward org-target-link-regexp limit t)
4169 (progn
4170 (add-text-properties (match-beginning 0) (match-end 0)
4171 (list 'mouse-face 'highlight
4172 'rear-nonsticky org-nonsticky-props
4173 'keymap org-mouse-map
4174 'help-echo "Radio target link"
4175 'org-linked-text t))
4176 t)))))
4178 (defun org-update-radio-target-regexp ()
4179 "Find all radio targets in this file and update the regular expression."
4180 (interactive)
4181 (when (memq 'radio org-activate-links)
4182 (setq org-target-link-regexp
4183 (org-make-target-link-regexp (org-all-targets 'radio)))
4184 (org-restart-font-lock)))
4186 (defun org-hide-wide-columns (limit)
4187 (let (s e)
4188 (setq s (text-property-any (point) (or limit (point-max))
4189 'org-cwidth t))
4190 (when s
4191 (setq e (next-single-property-change s 'org-cwidth))
4192 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4193 (goto-char e)
4194 t)))
4196 (defvar org-latex-and-specials-regexp nil
4197 "Regular expression for highlighting export special stuff.")
4198 (defvar org-match-substring-regexp)
4199 (defvar org-match-substring-with-braces-regexp)
4200 (defvar org-export-html-special-string-regexps)
4202 (defun org-compute-latex-and-specials-regexp ()
4203 "Compute regular expression for stuff treated specially by exporters."
4204 (if (not org-highlight-latex-fragments-and-specials)
4205 (org-set-local 'org-latex-and-specials-regexp nil)
4206 (require 'org-exp)
4207 (let*
4208 ((matchers (plist-get org-format-latex-options :matchers))
4209 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4210 org-latex-regexps)))
4211 (options (org-combine-plists (org-default-export-plist)
4212 (org-infile-export-plist)))
4213 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4214 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4215 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4216 (org-export-html-expand (plist-get options :expand-quoted-html))
4217 (org-export-with-special-strings (plist-get options :special-strings))
4218 (re-sub
4219 (cond
4220 ((equal org-export-with-sub-superscripts '{})
4221 (list org-match-substring-with-braces-regexp))
4222 (org-export-with-sub-superscripts
4223 (list org-match-substring-regexp))
4224 (t nil)))
4225 (re-latex
4226 (if org-export-with-LaTeX-fragments
4227 (mapcar (lambda (x) (nth 1 x)) latexs)))
4228 (re-macros
4229 (if org-export-with-TeX-macros
4230 (list (concat "\\\\"
4231 (regexp-opt
4232 (append (mapcar 'car org-html-entities)
4233 (if (boundp 'org-latex-entities)
4234 org-latex-entities nil))
4235 'words))) ; FIXME
4237 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4238 (re-special (if org-export-with-special-strings
4239 (mapcar (lambda (x) (car x))
4240 org-export-html-special-string-regexps)))
4241 (re-rest
4242 (delq nil
4243 (list
4244 (if org-export-html-expand "@<[^>\n]+>")
4245 ))))
4246 (org-set-local
4247 'org-latex-and-specials-regexp
4248 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4249 re-rest) "\\|")))))
4251 (defun org-do-latex-and-special-faces (limit)
4252 "Run through the buffer and add overlays to links."
4253 (when org-latex-and-specials-regexp
4254 (let (rtn d)
4255 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4256 limit t))
4257 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4258 'face))
4259 '(org-code org-verbatim underline)))
4260 (progn
4261 (setq rtn t
4262 d (cond ((member (char-after (1+ (match-beginning 0)))
4263 '(?_ ?^)) 1)
4264 (t 0)))
4265 (font-lock-prepend-text-property
4266 (+ d (match-beginning 0)) (match-end 0)
4267 'face 'org-latex-and-export-specials)
4268 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4269 '(font-lock-multiline t)))))
4270 rtn)))
4272 (defun org-restart-font-lock ()
4273 "Restart font-lock-mode, to force refontification."
4274 (when (and (boundp 'font-lock-mode) font-lock-mode)
4275 (font-lock-mode -1)
4276 (font-lock-mode 1)))
4278 (defun org-all-targets (&optional radio)
4279 "Return a list of all targets in this file.
4280 With optional argument RADIO, only find radio targets."
4281 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4282 rtn)
4283 (save-excursion
4284 (goto-char (point-min))
4285 (while (re-search-forward re nil t)
4286 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4287 rtn)))
4289 (defun org-make-target-link-regexp (targets)
4290 "Make regular expression matching all strings in TARGETS.
4291 The regular expression finds the targets also if there is a line break
4292 between words."
4293 (and targets
4294 (concat
4295 "\\<\\("
4296 (mapconcat
4297 (lambda (x)
4298 (while (string-match " +" x)
4299 (setq x (replace-match "\\s-+" t t x)))
4301 targets
4302 "\\|")
4303 "\\)\\>")))
4305 (defun org-activate-tags (limit)
4306 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4307 (progn
4308 (add-text-properties (match-beginning 1) (match-end 1)
4309 (list 'mouse-face 'highlight
4310 'rear-nonsticky org-nonsticky-props
4311 'keymap org-mouse-map))
4312 t)))
4314 (defun org-outline-level ()
4315 (save-excursion
4316 (looking-at outline-regexp)
4317 (if (match-beginning 1)
4318 (+ (org-get-string-indentation (match-string 1)) 1000)
4319 (1- (- (match-end 0) (match-beginning 0))))))
4321 (defvar org-font-lock-keywords nil)
4323 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4324 "Regular expression matching a property line.")
4326 (defvar org-font-lock-hook nil
4327 "Functions to be called for special font lock stuff.")
4329 (defun org-font-lock-hook (limit)
4330 (run-hook-with-args 'org-font-lock-hook limit))
4332 (defun org-set-font-lock-defaults ()
4333 (let* ((em org-fontify-emphasized-text)
4334 (lk org-activate-links)
4335 (org-font-lock-extra-keywords
4336 (list
4337 ;; Call the hook
4338 '(org-font-lock-hook)
4339 ;; Headlines
4340 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4341 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4342 ;; Table lines
4343 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4344 (1 'org-table t))
4345 ;; Table internals
4346 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4347 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4348 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4349 ;; Drawers
4350 (list org-drawer-regexp '(0 'org-special-keyword t))
4351 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4352 ;; Properties
4353 (list org-property-re
4354 '(1 'org-special-keyword t)
4355 '(3 'org-property-value t))
4356 (if org-format-transports-properties-p
4357 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4358 ;; Links
4359 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4360 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4361 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4362 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4363 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4364 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4365 (if (memq 'footnote lk) '(org-activate-footnote-links
4366 (2 'org-footnote t)))
4367 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4368 '(org-hide-wide-columns (0 nil append))
4369 ;; TODO lines
4370 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4371 '(1 (org-get-todo-face 1) t))
4372 ;; DONE
4373 (if org-fontify-done-headline
4374 (list (concat "^[*]+ +\\<\\("
4375 (mapconcat 'regexp-quote org-done-keywords "\\|")
4376 "\\)\\(.*\\)")
4377 '(2 'org-headline-done t))
4378 nil)
4379 ;; Priorities
4380 '(org-font-lock-add-priority-faces)
4381 ;; Tags
4382 '(org-font-lock-add-tag-faces)
4383 ;; Special keywords
4384 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4385 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4386 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4387 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4388 ;; Emphasis
4389 (if em
4390 (if (featurep 'xemacs)
4391 '(org-do-emphasis-faces (0 nil append))
4392 '(org-do-emphasis-faces)))
4393 ;; Checkboxes
4394 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4395 2 'org-checkbox prepend)
4396 (if org-provide-checkbox-statistics
4397 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4398 (0 (org-get-checkbox-statistics-face) t)))
4399 ;; Description list items
4400 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4401 2 'bold prepend)
4402 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4403 '(1 'org-archived prepend))
4404 ;; Specials
4405 '(org-do-latex-and-special-faces)
4406 ;; Code
4407 '(org-activate-code (1 'org-code t))
4408 ;; COMMENT
4409 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4410 "\\|" org-quote-string "\\)\\>")
4411 '(1 'org-special-keyword t))
4412 '("^#.*" (0 'font-lock-comment-face t))
4414 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4415 ;; Now set the full font-lock-keywords
4416 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4417 (org-set-local 'font-lock-defaults
4418 '(org-font-lock-keywords t nil nil backward-paragraph))
4419 (kill-local-variable 'font-lock-keywords) nil))
4421 (defvar org-m nil)
4422 (defvar org-l nil)
4423 (defvar org-f nil)
4424 (defun org-get-level-face (n)
4425 "Get the right face for match N in font-lock matching of headlines."
4426 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4427 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4428 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4429 (cond
4430 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4431 ((eq n 2) org-f)
4432 (t (if org-level-color-stars-only nil org-f))))
4434 (defun org-get-todo-face (kwd)
4435 "Get the right face for a TODO keyword KWD.
4436 If KWD is a number, get the corresponding match group."
4437 (if (numberp kwd) (setq kwd (match-string kwd)))
4438 (or (cdr (assoc kwd org-todo-keyword-faces))
4439 (and (member kwd org-done-keywords) 'org-done)
4440 'org-todo))
4442 (defun org-font-lock-add-tag-faces (limit)
4443 "Add the special tag faces."
4444 (when (and org-tag-faces org-tags-special-faces-re)
4445 (while (re-search-forward org-tags-special-faces-re limit t)
4446 (add-text-properties (match-beginning 1) (match-end 1)
4447 (list 'face (org-get-tag-face 1)
4448 'font-lock-fontified t))
4449 (backward-char 1))))
4451 (defun org-font-lock-add-priority-faces (limit)
4452 "Add the special priority faces."
4453 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4454 (add-text-properties
4455 (match-beginning 0) (match-end 0)
4456 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4457 org-priority-faces))
4458 'org-special-keyword)
4459 'font-lock-fontified t))))
4461 (defun org-get-tag-face (kwd)
4462 "Get the right face for a TODO keyword KWD.
4463 If KWD is a number, get the corresponding match group."
4464 (if (numberp kwd) (setq kwd (match-string kwd)))
4465 (or (cdr (assoc kwd org-tag-faces))
4466 'org-tag))
4468 (defun org-unfontify-region (beg end &optional maybe_loudly)
4469 "Remove fontification and activation overlays from links."
4470 (font-lock-default-unfontify-region beg end)
4471 (let* ((buffer-undo-list t)
4472 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4473 (inhibit-modification-hooks t)
4474 deactivate-mark buffer-file-name buffer-file-truename)
4475 (remove-text-properties beg end
4476 '(mouse-face t keymap t org-linked-text t
4477 invisible t intangible t))))
4479 ;;;; Visibility cycling, including org-goto and indirect buffer
4481 ;;; Cycling
4483 (defvar org-cycle-global-status nil)
4484 (make-variable-buffer-local 'org-cycle-global-status)
4485 (defvar org-cycle-subtree-status nil)
4486 (make-variable-buffer-local 'org-cycle-subtree-status)
4488 ;;;###autoload
4490 (defvar org-inlinetask-min-level)
4491 (defun org-cycle (&optional arg)
4492 "Visibility cycling for Org-mode.
4494 - When this function is called with a prefix argument, rotate the entire
4495 buffer through 3 states (global cycling)
4496 1. OVERVIEW: Show only top-level headlines.
4497 2. CONTENTS: Show all headlines of all levels, but no body text.
4498 3. SHOW ALL: Show everything.
4499 When called with two C-u C-u prefixes, switch to the startup visibility,
4500 determined by the variable `org-startup-folded', and by any VISIBILITY
4501 properties in the buffer.
4502 When called with three C-u C-u C-u prefixed, show the entire buffer,
4503 including drawers.
4505 - When point is at the beginning of a headline, rotate the subtree started
4506 by this line through 3 different states (local cycling)
4507 1. FOLDED: Only the main headline is shown.
4508 2. CHILDREN: The main headline and the direct children are shown.
4509 From this state, you can move to one of the children
4510 and zoom in further.
4511 3. SUBTREE: Show the entire subtree, including body text.
4513 - When there is a numeric prefix, go up to a heading with level ARG, do
4514 a `show-subtree' and return to the previous cursor position. If ARG
4515 is negative, go up that many levels.
4517 - When point is not at the beginning of a headline, execute the global
4518 binding for TAB, which is re-indenting the line. See the option
4519 `org-cycle-emulate-tab' for details.
4521 - Special case: if point is at the beginning of the buffer and there is
4522 no headline in line 1, this function will act as if called with prefix arg.
4523 But only if also the variable `org-cycle-global-at-bob' is t."
4524 (interactive "P")
4525 (org-load-modules-maybe)
4526 (let* ((limit-level
4527 (or org-cycle-max-level
4528 (and (boundp 'org-inlinetask-min-level)
4529 org-inlinetask-min-level
4530 (1- org-inlinetask-min-level))))
4531 (nstars (and limit-level
4532 (if org-odd-levels-only
4533 (and limit-level (1- (* limit 2)))
4534 limit-level)))
4535 (outline-regexp
4536 (cond
4537 ((not (org-mode-p)) outline-regexp)
4538 (org-cycle-include-plain-lists
4539 (concat "\\(?:\\*"
4540 (if nstars (format "\\{1,%d\\} " nstars) "+")
4541 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4542 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4543 (bob-special (and org-cycle-global-at-bob (bobp)
4544 (not (looking-at outline-regexp))))
4545 (org-cycle-hook
4546 (if bob-special
4547 (delq 'org-optimize-window-after-visibility-change
4548 (copy-sequence org-cycle-hook))
4549 org-cycle-hook))
4550 (pos (point)))
4552 (if (or bob-special (equal arg '(4)))
4553 ;; special case: use global cycling
4554 (setq arg t))
4556 (cond
4558 ((equal arg '(16))
4559 (org-set-startup-visibility)
4560 (message "Startup visibility, plus VISIBILITY properties"))
4562 ((equal arg '(64))
4563 (show-all)
4564 (message "Entire buffer visible, including drawers"))
4566 ((org-at-table-p 'any)
4567 ;; Enter the table or move to the next field in the table
4568 (or (org-table-recognize-table.el)
4569 (progn
4570 (if arg (org-table-edit-field t)
4571 (org-table-justify-field-maybe)
4572 (call-interactively 'org-table-next-field)))))
4574 ((eq arg t) ;; Global cycling
4576 (cond
4577 ((and (eq last-command this-command)
4578 (eq org-cycle-global-status 'overview))
4579 ;; We just created the overview - now do table of contents
4580 ;; This can be slow in very large buffers, so indicate action
4581 (message "CONTENTS...")
4582 (org-content)
4583 (message "CONTENTS...done")
4584 (setq org-cycle-global-status 'contents)
4585 (run-hook-with-args 'org-cycle-hook 'contents))
4587 ((and (eq last-command this-command)
4588 (eq org-cycle-global-status 'contents))
4589 ;; We just showed the table of contents - now show everything
4590 (show-all)
4591 (message "SHOW ALL")
4592 (setq org-cycle-global-status 'all)
4593 (run-hook-with-args 'org-cycle-hook 'all))
4596 ;; Default action: go to overview
4597 (org-overview)
4598 (message "OVERVIEW")
4599 (setq org-cycle-global-status 'overview)
4600 (run-hook-with-args 'org-cycle-hook 'overview))))
4602 ((and org-drawers org-drawer-regexp
4603 (save-excursion
4604 (beginning-of-line 1)
4605 (looking-at org-drawer-regexp)))
4606 ;; Toggle block visibility
4607 (org-flag-drawer
4608 (not (get-char-property (match-end 0) 'invisible))))
4610 ((integerp arg)
4611 ;; Show-subtree, ARG levels up from here.
4612 (save-excursion
4613 (org-back-to-heading)
4614 (outline-up-heading (if (< arg 0) (- arg)
4615 (- (funcall outline-level) arg)))
4616 (org-show-subtree)))
4618 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4619 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4620 ;; At a heading: rotate between three different views
4621 (org-back-to-heading)
4622 (let ((goal-column 0) eoh eol eos)
4623 ;; First, some boundaries
4624 (save-excursion
4625 (org-back-to-heading)
4626 (save-excursion
4627 (beginning-of-line 2)
4628 (while (and (not (eobp)) ;; this is like `next-line'
4629 (get-char-property (1- (point)) 'invisible))
4630 (beginning-of-line 2)) (setq eol (point)))
4631 (outline-end-of-heading) (setq eoh (point))
4632 (org-end-of-subtree t)
4633 (unless (eobp)
4634 (skip-chars-forward " \t\n")
4635 (beginning-of-line 1) ; in case this is an item
4637 (setq eos (1- (point))))
4638 ;; Find out what to do next and set `this-command'
4639 (cond
4640 ((= eos eoh)
4641 ;; Nothing is hidden behind this heading
4642 (message "EMPTY ENTRY")
4643 (setq org-cycle-subtree-status nil)
4644 (save-excursion
4645 (goto-char eos)
4646 (outline-next-heading)
4647 (if (org-invisible-p) (org-flag-heading nil))))
4648 ((or (>= eol eos)
4649 (not (string-match "\\S-" (buffer-substring eol eos))))
4650 ;; Entire subtree is hidden in one line: open it
4651 (org-show-entry)
4652 (show-children)
4653 (message "CHILDREN")
4654 (save-excursion
4655 (goto-char eos)
4656 (outline-next-heading)
4657 (if (org-invisible-p) (org-flag-heading nil)))
4658 (setq org-cycle-subtree-status 'children)
4659 (run-hook-with-args 'org-cycle-hook 'children))
4660 ((and (eq last-command this-command)
4661 (eq org-cycle-subtree-status 'children))
4662 ;; We just showed the children, now show everything.
4663 (org-show-subtree)
4664 (message "SUBTREE")
4665 (setq org-cycle-subtree-status 'subtree)
4666 (run-hook-with-args 'org-cycle-hook 'subtree))
4668 ;; Default action: hide the subtree.
4669 (hide-subtree)
4670 (message "FOLDED")
4671 (setq org-cycle-subtree-status 'folded)
4672 (run-hook-with-args 'org-cycle-hook 'folded)))))
4674 ;; TAB emulation and template completion
4675 (buffer-read-only (org-back-to-heading))
4677 ((org-try-structure-completion))
4679 ((org-try-cdlatex-tab))
4681 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4682 (or (not (bolp))
4683 (not (looking-at outline-regexp))))
4684 (call-interactively (global-key-binding "\t")))
4686 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4687 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4688 (or (and (eq org-cycle-emulate-tab 'white)
4689 (= (match-end 0) (point-at-eol)))
4690 (and (eq org-cycle-emulate-tab 'whitestart)
4691 (>= (match-end 0) pos))))
4693 (eq org-cycle-emulate-tab t))
4694 (call-interactively (global-key-binding "\t")))
4696 (t (save-excursion
4697 (org-back-to-heading)
4698 (org-cycle))))))
4700 ;;;###autoload
4701 (defun org-global-cycle (&optional arg)
4702 "Cycle the global visibility. For details see `org-cycle'.
4703 With C-u prefix arg, switch to startup visibility.
4704 With a numeric prefix, show all headlines up to that level."
4705 (interactive "P")
4706 (let ((org-cycle-include-plain-lists
4707 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4708 (cond
4709 ((integerp arg)
4710 (show-all)
4711 (hide-sublevels arg)
4712 (setq org-cycle-global-status 'contents))
4713 ((equal arg '(4))
4714 (org-set-startup-visibility)
4715 (message "Startup visibility, plus VISIBILITY properties."))
4717 (org-cycle '(4))))))
4719 (defun org-set-startup-visibility ()
4720 "Set the visibility required by startup options and properties."
4721 (cond
4722 ((eq org-startup-folded t)
4723 (org-cycle '(4)))
4724 ((eq org-startup-folded 'content)
4725 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4726 (org-cycle '(4)) (org-cycle '(4)))))
4727 (org-set-visibility-according-to-property 'no-cleanup)
4728 (org-cycle-hide-archived-subtrees 'all)
4729 (org-cycle-hide-drawers 'all)
4730 (org-cycle-show-empty-lines 'all))
4732 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4733 "Switch subtree visibilities according to :VISIBILITY: property."
4734 (interactive)
4735 (let (org-show-entry-below state)
4736 (save-excursion
4737 (goto-char (point-min))
4738 (while (re-search-forward
4739 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4740 nil t)
4741 (setq state (match-string 1))
4742 (save-excursion
4743 (org-back-to-heading t)
4744 (hide-subtree)
4745 (org-reveal)
4746 (cond
4747 ((equal state '("fold" "folded"))
4748 (hide-subtree))
4749 ((equal state "children")
4750 (org-show-hidden-entry)
4751 (show-children))
4752 ((equal state "content")
4753 (save-excursion
4754 (save-restriction
4755 (org-narrow-to-subtree)
4756 (org-content))))
4757 ((member state '("all" "showall"))
4758 (show-subtree)))))
4759 (unless no-cleanup
4760 (org-cycle-hide-archived-subtrees 'all)
4761 (org-cycle-hide-drawers 'all)
4762 (org-cycle-show-empty-lines 'all)))))
4764 (defun org-overview ()
4765 "Switch to overview mode, showing only top-level headlines.
4766 Really, this shows all headlines with level equal or greater than the level
4767 of the first headline in the buffer. This is important, because if the
4768 first headline is not level one, then (hide-sublevels 1) gives confusing
4769 results."
4770 (interactive)
4771 (let ((level (save-excursion
4772 (goto-char (point-min))
4773 (if (re-search-forward (concat "^" outline-regexp) nil t)
4774 (progn
4775 (goto-char (match-beginning 0))
4776 (funcall outline-level))))))
4777 (and level (hide-sublevels level))))
4779 (defun org-content (&optional arg)
4780 "Show all headlines in the buffer, like a table of contents.
4781 With numerical argument N, show content up to level N."
4782 (interactive "P")
4783 (save-excursion
4784 ;; Visit all headings and show their offspring
4785 (and (integerp arg) (org-overview))
4786 (goto-char (point-max))
4787 (catch 'exit
4788 (while (and (progn (condition-case nil
4789 (outline-previous-visible-heading 1)
4790 (error (goto-char (point-min))))
4792 (looking-at outline-regexp))
4793 (if (integerp arg)
4794 (show-children (1- arg))
4795 (show-branches))
4796 (if (bobp) (throw 'exit nil))))))
4799 (defun org-optimize-window-after-visibility-change (state)
4800 "Adjust the window after a change in outline visibility.
4801 This function is the default value of the hook `org-cycle-hook'."
4802 (when (get-buffer-window (current-buffer))
4803 (cond
4804 ((eq state 'content) nil)
4805 ((eq state 'all) nil)
4806 ((eq state 'folded) nil)
4807 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4808 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4810 (defun org-compact-display-after-subtree-move ()
4811 "Show a compacter version of the tree of the entry's parent."
4812 (save-excursion
4813 (if (org-up-heading-safe)
4814 (progn
4815 (hide-subtree)
4816 (show-entry)
4817 (show-children)
4818 (org-cycle-show-empty-lines 'children)
4819 (org-cycle-hide-drawers 'children))
4820 (org-overview))))
4822 (defun org-cycle-show-empty-lines (state)
4823 "Show empty lines above all visible headlines.
4824 The region to be covered depends on STATE when called through
4825 `org-cycle-hook'. Lisp program can use t for STATE to get the
4826 entire buffer covered. Note that an empty line is only shown if there
4827 are at least `org-cycle-separator-lines' empty lines before the headline."
4828 (when (> org-cycle-separator-lines 0)
4829 (save-excursion
4830 (let* ((n org-cycle-separator-lines)
4831 (re (cond
4832 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4833 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4834 (t (let ((ns (number-to-string (- n 2))))
4835 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4836 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4837 beg end)
4838 (cond
4839 ((memq state '(overview contents t))
4840 (setq beg (point-min) end (point-max)))
4841 ((memq state '(children folded))
4842 (setq beg (point) end (progn (org-end-of-subtree t t)
4843 (beginning-of-line 2)
4844 (point)))))
4845 (when beg
4846 (goto-char beg)
4847 (while (re-search-forward re end t)
4848 (if (not (get-char-property (match-end 1) 'invisible))
4849 (outline-flag-region
4850 (match-beginning 1) (match-end 1) nil)))))))
4851 ;; Never hide empty lines at the end of the file.
4852 (save-excursion
4853 (goto-char (point-max))
4854 (outline-previous-heading)
4855 (outline-end-of-heading)
4856 (if (and (looking-at "[ \t\n]+")
4857 (= (match-end 0) (point-max)))
4858 (outline-flag-region (point) (match-end 0) nil))))
4860 (defun org-show-empty-lines-in-parent ()
4861 "Move to the parent and re-show empty lines before visible headlines."
4862 (save-excursion
4863 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4864 (org-cycle-show-empty-lines context))))
4866 (defun org-cycle-hide-drawers (state)
4867 "Re-hide all drawers after a visibility state change."
4868 (when (and (org-mode-p)
4869 (not (memq state '(overview folded))))
4870 (save-excursion
4871 (let* ((globalp (memq state '(contents all)))
4872 (beg (if globalp (point-min) (point)))
4873 (end (if globalp (point-max) (org-end-of-subtree t))))
4874 (goto-char beg)
4875 (while (re-search-forward org-drawer-regexp end t)
4876 (org-flag-drawer t))))))
4878 (defun org-flag-drawer (flag)
4879 (save-excursion
4880 (beginning-of-line 1)
4881 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4882 (let ((b (match-end 0))
4883 (outline-regexp org-outline-regexp))
4884 (if (re-search-forward
4885 "^[ \t]*:END:"
4886 (save-excursion (outline-next-heading) (point)) t)
4887 (outline-flag-region b (point-at-eol) flag)
4888 (error ":END: line missing"))))))
4890 (defun org-subtree-end-visible-p ()
4891 "Is the end of the current subtree visible?"
4892 (pos-visible-in-window-p
4893 (save-excursion (org-end-of-subtree t) (point))))
4895 (defun org-first-headline-recenter (&optional N)
4896 "Move cursor to the first headline and recenter the headline.
4897 Optional argument N means, put the headline into the Nth line of the window."
4898 (goto-char (point-min))
4899 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4900 (beginning-of-line)
4901 (recenter (prefix-numeric-value N))))
4903 ;;; Org-goto
4905 (defvar org-goto-window-configuration nil)
4906 (defvar org-goto-marker nil)
4907 (defvar org-goto-map
4908 (let ((map (make-sparse-keymap)))
4909 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4910 (while (setq cmd (pop cmds))
4911 (substitute-key-definition cmd cmd map global-map)))
4912 (suppress-keymap map)
4913 (org-defkey map "\C-m" 'org-goto-ret)
4914 (org-defkey map [(return)] 'org-goto-ret)
4915 (org-defkey map [(left)] 'org-goto-left)
4916 (org-defkey map [(right)] 'org-goto-right)
4917 (org-defkey map [(control ?g)] 'org-goto-quit)
4918 (org-defkey map "\C-i" 'org-cycle)
4919 (org-defkey map [(tab)] 'org-cycle)
4920 (org-defkey map [(down)] 'outline-next-visible-heading)
4921 (org-defkey map [(up)] 'outline-previous-visible-heading)
4922 (if org-goto-auto-isearch
4923 (if (fboundp 'define-key-after)
4924 (define-key-after map [t] 'org-goto-local-auto-isearch)
4925 nil)
4926 (org-defkey map "q" 'org-goto-quit)
4927 (org-defkey map "n" 'outline-next-visible-heading)
4928 (org-defkey map "p" 'outline-previous-visible-heading)
4929 (org-defkey map "f" 'outline-forward-same-level)
4930 (org-defkey map "b" 'outline-backward-same-level)
4931 (org-defkey map "u" 'outline-up-heading))
4932 (org-defkey map "/" 'org-occur)
4933 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4934 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4935 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4936 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4937 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4938 map))
4940 (defconst org-goto-help
4941 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4942 RET=jump to location [Q]uit and return to previous location
4943 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4945 (defvar org-goto-start-pos) ; dynamically scoped parameter
4947 ;; FIXME: Docstring doe not mention both interfaces
4948 (defun org-goto (&optional alternative-interface)
4949 "Look up a different location in the current file, keeping current visibility.
4951 When you want look-up or go to a different location in a document, the
4952 fastest way is often to fold the entire buffer and then dive into the tree.
4953 This method has the disadvantage, that the previous location will be folded,
4954 which may not be what you want.
4956 This command works around this by showing a copy of the current buffer
4957 in an indirect buffer, in overview mode. You can dive into the tree in
4958 that copy, use org-occur and incremental search to find a location.
4959 When pressing RET or `Q', the command returns to the original buffer in
4960 which the visibility is still unchanged. After RET is will also jump to
4961 the location selected in the indirect buffer and expose the
4962 the headline hierarchy above."
4963 (interactive "P")
4964 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4965 (org-refile-use-outline-path t)
4966 (interface
4967 (if (not alternative-interface)
4968 org-goto-interface
4969 (if (eq org-goto-interface 'outline)
4970 'outline-path-completion
4971 'outline)))
4972 (org-goto-start-pos (point))
4973 (selected-point
4974 (if (eq interface 'outline)
4975 (car (org-get-location (current-buffer) org-goto-help))
4976 (nth 3 (org-refile-get-location "Goto: ")))))
4977 (if selected-point
4978 (progn
4979 (org-mark-ring-push org-goto-start-pos)
4980 (goto-char selected-point)
4981 (if (or (org-invisible-p) (org-invisible-p2))
4982 (org-show-context 'org-goto)))
4983 (message "Quit"))))
4985 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4986 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4987 (defvar org-goto-local-auto-isearch-map) ; defined below
4989 (defun org-get-location (buf help)
4990 "Let the user select a location in the Org-mode buffer BUF.
4991 This function uses a recursive edit. It returns the selected position
4992 or nil."
4993 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4994 (isearch-hide-immediately nil)
4995 (isearch-search-fun-function
4996 (lambda () 'org-goto-local-search-headings))
4997 (org-goto-selected-point org-goto-exit-command))
4998 (save-excursion
4999 (save-window-excursion
5000 (delete-other-windows)
5001 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5002 (switch-to-buffer
5003 (condition-case nil
5004 (make-indirect-buffer (current-buffer) "*org-goto*")
5005 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5006 (with-output-to-temp-buffer "*Help*"
5007 (princ help))
5008 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5009 (setq buffer-read-only nil)
5010 (let ((org-startup-truncated t)
5011 (org-startup-folded nil)
5012 (org-startup-align-all-tables nil))
5013 (org-mode)
5014 (org-overview))
5015 (setq buffer-read-only t)
5016 (if (and (boundp 'org-goto-start-pos)
5017 (integer-or-marker-p org-goto-start-pos))
5018 (let ((org-show-hierarchy-above t)
5019 (org-show-siblings t)
5020 (org-show-following-heading t))
5021 (goto-char org-goto-start-pos)
5022 (and (org-invisible-p) (org-show-context)))
5023 (goto-char (point-min)))
5024 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5025 (message "Select location and press RET")
5026 (use-local-map org-goto-map)
5027 (recursive-edit)
5029 (kill-buffer "*org-goto*")
5030 (cons org-goto-selected-point org-goto-exit-command)))
5032 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5033 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5034 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5035 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5037 (defun org-goto-local-search-headings (string bound noerror)
5038 "Search and make sure that any matches are in headlines."
5039 (catch 'return
5040 (while (if isearch-forward
5041 (search-forward string bound noerror)
5042 (search-backward string bound noerror))
5043 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5044 (and (member :headline context)
5045 (not (member :tags context))))
5046 (throw 'return (point))))))
5048 (defun org-goto-local-auto-isearch ()
5049 "Start isearch."
5050 (interactive)
5051 (goto-char (point-min))
5052 (let ((keys (this-command-keys)))
5053 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5054 (isearch-mode t)
5055 (isearch-process-search-char (string-to-char keys)))))
5057 (defun org-goto-ret (&optional arg)
5058 "Finish `org-goto' by going to the new location."
5059 (interactive "P")
5060 (setq org-goto-selected-point (point)
5061 org-goto-exit-command 'return)
5062 (throw 'exit nil))
5064 (defun org-goto-left ()
5065 "Finish `org-goto' by going to the new location."
5066 (interactive)
5067 (if (org-on-heading-p)
5068 (progn
5069 (beginning-of-line 1)
5070 (setq org-goto-selected-point (point)
5071 org-goto-exit-command 'left)
5072 (throw 'exit nil))
5073 (error "Not on a heading")))
5075 (defun org-goto-right ()
5076 "Finish `org-goto' by going to the new location."
5077 (interactive)
5078 (if (org-on-heading-p)
5079 (progn
5080 (setq org-goto-selected-point (point)
5081 org-goto-exit-command 'right)
5082 (throw 'exit nil))
5083 (error "Not on a heading")))
5085 (defun org-goto-quit ()
5086 "Finish `org-goto' without cursor motion."
5087 (interactive)
5088 (setq org-goto-selected-point nil)
5089 (setq org-goto-exit-command 'quit)
5090 (throw 'exit nil))
5092 ;;; Indirect buffer display of subtrees
5094 (defvar org-indirect-dedicated-frame nil
5095 "This is the frame being used for indirect tree display.")
5096 (defvar org-last-indirect-buffer nil)
5098 (defun org-tree-to-indirect-buffer (&optional arg)
5099 "Create indirect buffer and narrow it to current subtree.
5100 With numerical prefix ARG, go up to this level and then take that tree.
5101 If ARG is negative, go up that many levels.
5102 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5103 indirect buffer previously made with this command, to avoid proliferation of
5104 indirect buffers. However, when you call the command with a `C-u' prefix, or
5105 when `org-indirect-buffer-display' is `new-frame', the last buffer
5106 is kept so that you can work with several indirect buffers at the same time.
5107 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5108 requests that a new frame be made for the new buffer, so that the dedicated
5109 frame is not changed."
5110 (interactive "P")
5111 (let ((cbuf (current-buffer))
5112 (cwin (selected-window))
5113 (pos (point))
5114 beg end level heading ibuf)
5115 (save-excursion
5116 (org-back-to-heading t)
5117 (when (numberp arg)
5118 (setq level (org-outline-level))
5119 (if (< arg 0) (setq arg (+ level arg)))
5120 (while (> (setq level (org-outline-level)) arg)
5121 (outline-up-heading 1 t)))
5122 (setq beg (point)
5123 heading (org-get-heading))
5124 (org-end-of-subtree t) (setq end (point)))
5125 (if (and (buffer-live-p org-last-indirect-buffer)
5126 (not (eq org-indirect-buffer-display 'new-frame))
5127 (not arg))
5128 (kill-buffer org-last-indirect-buffer))
5129 (setq ibuf (org-get-indirect-buffer cbuf)
5130 org-last-indirect-buffer ibuf)
5131 (cond
5132 ((or (eq org-indirect-buffer-display 'new-frame)
5133 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5134 (select-frame (make-frame))
5135 (delete-other-windows)
5136 (switch-to-buffer ibuf)
5137 (org-set-frame-title heading))
5138 ((eq org-indirect-buffer-display 'dedicated-frame)
5139 (raise-frame
5140 (select-frame (or (and org-indirect-dedicated-frame
5141 (frame-live-p org-indirect-dedicated-frame)
5142 org-indirect-dedicated-frame)
5143 (setq org-indirect-dedicated-frame (make-frame)))))
5144 (delete-other-windows)
5145 (switch-to-buffer ibuf)
5146 (org-set-frame-title (concat "Indirect: " heading)))
5147 ((eq org-indirect-buffer-display 'current-window)
5148 (switch-to-buffer ibuf))
5149 ((eq org-indirect-buffer-display 'other-window)
5150 (pop-to-buffer ibuf))
5151 (t (error "Invalid value.")))
5152 (if (featurep 'xemacs)
5153 (save-excursion (org-mode) (turn-on-font-lock)))
5154 (narrow-to-region beg end)
5155 (show-all)
5156 (goto-char pos)
5157 (and (window-live-p cwin) (select-window cwin))))
5159 (defun org-get-indirect-buffer (&optional buffer)
5160 (setq buffer (or buffer (current-buffer)))
5161 (let ((n 1) (base (buffer-name buffer)) bname)
5162 (while (buffer-live-p
5163 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5164 (setq n (1+ n)))
5165 (condition-case nil
5166 (make-indirect-buffer buffer bname 'clone)
5167 (error (make-indirect-buffer buffer bname)))))
5169 (defun org-set-frame-title (title)
5170 "Set the title of the current frame to the string TITLE."
5171 ;; FIXME: how to name a single frame in XEmacs???
5172 (unless (featurep 'xemacs)
5173 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5175 ;;;; Structure editing
5177 ;;; Inserting headlines
5179 (defun org-previous-line-empty-p ()
5180 (save-excursion
5181 (and (not (bobp))
5182 (or (beginning-of-line 0) t)
5183 (save-match-data
5184 (looking-at "[ \t]*$")))))
5186 (defun org-insert-heading (&optional force-heading)
5187 "Insert a new heading or item with same depth at point.
5188 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5189 If point is at the beginning of a headline, insert a sibling before the
5190 current headline. If point is not at the beginning, do not split the line,
5191 but create the new headline after the current line."
5192 (interactive "P")
5193 (if (= (buffer-size) 0)
5194 (insert "\n* ")
5195 (when (or force-heading (not (org-insert-item)))
5196 (let* ((empty-line-p nil)
5197 (head (save-excursion
5198 (condition-case nil
5199 (progn
5200 (org-back-to-heading)
5201 (setq empty-line-p (org-previous-line-empty-p))
5202 (match-string 0))
5203 (error "*"))))
5204 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5205 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5206 pos hide-previous previous-pos)
5207 (cond
5208 ((and (org-on-heading-p) (bolp)
5209 (or (bobp)
5210 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5211 ;; insert before the current line
5212 (open-line (if blank 2 1)))
5213 ((and (bolp)
5214 (or (bobp)
5215 (save-excursion
5216 (backward-char 1) (not (org-invisible-p)))))
5217 ;; insert right here
5218 nil)
5220 ;; somewhere in the line
5221 (save-excursion
5222 (setq previous-pos (point-at-bol))
5223 (end-of-line)
5224 (setq hide-previous (org-invisible-p)))
5225 (and org-insert-heading-respect-content (org-show-subtree))
5226 (let ((split
5227 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5228 (save-excursion
5229 (let ((p (point)))
5230 (goto-char (point-at-bol))
5231 (and (looking-at org-complex-heading-regexp)
5232 (> p (match-beginning 4)))))))
5233 tags pos)
5234 (cond
5235 (org-insert-heading-respect-content
5236 (org-end-of-subtree nil t)
5237 (or (bolp) (newline))
5238 (or (org-previous-line-empty-p)
5239 (and blank (newline)))
5240 (open-line 1))
5241 ((org-on-heading-p)
5242 (when hide-previous
5243 (show-children)
5244 (org-show-entry))
5245 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5246 (setq tags (and (match-end 2) (match-string 2)))
5247 (and (match-end 1)
5248 (delete-region (match-beginning 1) (match-end 1)))
5249 (setq pos (point-at-bol))
5250 (or split (end-of-line 1))
5251 (delete-horizontal-space)
5252 (newline (if blank 2 1))
5253 (when tags
5254 (save-excursion
5255 (goto-char pos)
5256 (end-of-line 1)
5257 (insert " " tags)
5258 (org-set-tags nil 'align))))
5260 (or split (end-of-line 1))
5261 (newline (if blank 2 1)))))))
5262 (insert head) (just-one-space)
5263 (setq pos (point))
5264 (end-of-line 1)
5265 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5266 (when (and org-insert-heading-respect-content hide-previous)
5267 (save-excursion
5268 (goto-char previous-pos)
5269 (hide-subtree)))
5270 (run-hooks 'org-insert-heading-hook)))))
5272 (defun org-get-heading (&optional no-tags)
5273 "Return the heading of the current entry, without the stars."
5274 (save-excursion
5275 (org-back-to-heading t)
5276 (if (looking-at
5277 (if no-tags
5278 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5279 "\\*+[ \t]+\\([^\r\n]*\\)"))
5280 (match-string 1) "")))
5282 (defun org-heading-components ()
5283 "Return the components of the current heading.
5284 This is a list with the following elements:
5285 - the level as an integer
5286 - the reduced level, different if `org-odd-levels-only' is set.
5287 - the TODO keyword, or nil
5288 - the priority character, like ?A, or nil if no priority is given
5289 - the headline text itself, or the tags string if no headline text
5290 - the tags string, or nil."
5291 (save-excursion
5292 (org-back-to-heading t)
5293 (if (looking-at org-complex-heading-regexp)
5294 (list (length (match-string 1))
5295 (org-reduced-level (length (match-string 1)))
5296 (org-match-string-no-properties 2)
5297 (and (match-end 3) (aref (match-string 3) 2))
5298 (org-match-string-no-properties 4)
5299 (org-match-string-no-properties 5)))))
5301 (defun org-insert-heading-after-current ()
5302 "Insert a new heading with same level as current, after current subtree."
5303 (interactive)
5304 (org-back-to-heading)
5305 (org-insert-heading)
5306 (org-move-subtree-down)
5307 (end-of-line 1))
5309 (defun org-insert-heading-respect-content ()
5310 (interactive)
5311 (let ((org-insert-heading-respect-content t))
5312 (org-insert-heading t)))
5314 (defun org-insert-todo-heading-respect-content (&optional force-state)
5315 (interactive "P")
5316 (let ((org-insert-heading-respect-content t))
5317 (org-insert-todo-heading force-state t)))
5319 (defun org-insert-todo-heading (arg &optional force-heading)
5320 "Insert a new heading with the same level and TODO state as current heading.
5321 If the heading has no TODO state, or if the state is DONE, use the first
5322 state (TODO by default). Also with prefix arg, force first state."
5323 (interactive "P")
5324 (when (or force-heading (not (org-insert-item 'checkbox)))
5325 (org-insert-heading force-heading)
5326 (save-excursion
5327 (org-back-to-heading)
5328 (outline-previous-heading)
5329 (looking-at org-todo-line-regexp))
5330 (let*
5331 ((new-mark-x
5332 (if (or arg
5333 (not (match-beginning 2))
5334 (member (match-string 2) org-done-keywords))
5335 (car org-todo-keywords-1)
5336 (match-string 2)))
5337 (new-mark
5339 (run-hook-with-args-until-success
5340 'org-todo-get-default-hook new-mark-x nil)
5341 new-mark-x)))
5342 (beginning-of-line 1)
5343 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5344 (insert new-mark " ")))
5345 (when org-provide-todo-statistics
5346 (org-update-parent-todo-statistics))))
5348 (defun org-insert-subheading (arg)
5349 "Insert a new subheading and demote it.
5350 Works for outline headings and for plain lists alike."
5351 (interactive "P")
5352 (org-insert-heading arg)
5353 (cond
5354 ((org-on-heading-p) (org-do-demote))
5355 ((org-at-item-p) (org-indent-item 1))))
5357 (defun org-insert-todo-subheading (arg)
5358 "Insert a new subheading with TODO keyword or checkbox and demote it.
5359 Works for outline headings and for plain lists alike."
5360 (interactive "P")
5361 (org-insert-todo-heading arg)
5362 (cond
5363 ((org-on-heading-p) (org-do-demote))
5364 ((org-at-item-p) (org-indent-item 1))))
5366 ;;; Promotion and Demotion
5368 (defun org-promote-subtree ()
5369 "Promote the entire subtree.
5370 See also `org-promote'."
5371 (interactive)
5372 (save-excursion
5373 (org-map-tree 'org-promote))
5374 (org-fix-position-after-promote))
5376 (defun org-demote-subtree ()
5377 "Demote the entire subtree. See `org-demote'.
5378 See also `org-promote'."
5379 (interactive)
5380 (save-excursion
5381 (org-map-tree 'org-demote))
5382 (org-fix-position-after-promote))
5385 (defun org-do-promote ()
5386 "Promote the current heading higher up the tree.
5387 If the region is active in `transient-mark-mode', promote all headings
5388 in the region."
5389 (interactive)
5390 (save-excursion
5391 (if (org-region-active-p)
5392 (org-map-region 'org-promote (region-beginning) (region-end))
5393 (org-promote)))
5394 (org-fix-position-after-promote))
5396 (defun org-do-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 (interactive)
5401 (save-excursion
5402 (if (org-region-active-p)
5403 (org-map-region 'org-demote (region-beginning) (region-end))
5404 (org-demote)))
5405 (org-fix-position-after-promote))
5407 (defun org-fix-position-after-promote ()
5408 "Make sure that after pro/demotion cursor position is right."
5409 (let ((pos (point)))
5410 (when (save-excursion
5411 (beginning-of-line 1)
5412 (looking-at org-todo-line-regexp)
5413 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5414 (cond ((eobp) (insert " "))
5415 ((eolp) (insert " "))
5416 ((equal (char-after) ?\ ) (forward-char 1))))))
5418 (defun org-reduced-level (l)
5419 "Compute the effective level of a heading.
5420 This takes into account the setting of `org-odd-levels-only'."
5421 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5423 (defun org-get-valid-level (level &optional change)
5424 "Rectify a level change under the influence of `org-odd-levels-only'
5425 LEVEL is a current level, CHANGE is by how much the level should be
5426 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5427 even level numbers will become the next higher odd number."
5428 (if org-odd-levels-only
5429 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5430 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5431 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5432 (max 1 (+ level (or change 0)))))
5434 (if (boundp 'define-obsolete-function-alias)
5435 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5436 (define-obsolete-function-alias 'org-get-legal-level
5437 'org-get-valid-level)
5438 (define-obsolete-function-alias 'org-get-legal-level
5439 'org-get-valid-level "23.1")))
5441 (defun org-promote ()
5442 "Promote the current heading higher up the tree.
5443 If the region is active in `transient-mark-mode', promote all headings
5444 in the region."
5445 (org-back-to-heading t)
5446 (let* ((level (save-match-data (funcall outline-level)))
5447 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5448 (diff (abs (- level (length up-head) -1))))
5449 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5450 (replace-match up-head nil t)
5451 ;; Fixup tag positioning
5452 (and org-auto-align-tags (org-set-tags nil t))
5453 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5455 (defun org-demote ()
5456 "Demote the current heading lower down the tree.
5457 If the region is active in `transient-mark-mode', demote all headings
5458 in the region."
5459 (org-back-to-heading t)
5460 (let* ((level (save-match-data (funcall outline-level)))
5461 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5462 (diff (abs (- level (length down-head) -1))))
5463 (replace-match down-head nil t)
5464 ;; Fixup tag positioning
5465 (and org-auto-align-tags (org-set-tags nil t))
5466 (if org-adapt-indentation (org-fixup-indentation diff))))
5468 (defun org-map-tree (fun)
5469 "Call FUN for every heading underneath the current one."
5470 (org-back-to-heading)
5471 (let ((level (funcall outline-level)))
5472 (save-excursion
5473 (funcall fun)
5474 (while (and (progn
5475 (outline-next-heading)
5476 (> (funcall outline-level) level))
5477 (not (eobp)))
5478 (funcall fun)))))
5480 (defun org-map-region (fun beg end)
5481 "Call FUN for every heading between BEG and END."
5482 (let ((org-ignore-region t))
5483 (save-excursion
5484 (setq end (copy-marker end))
5485 (goto-char beg)
5486 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5487 (< (point) end))
5488 (funcall fun))
5489 (while (and (progn
5490 (outline-next-heading)
5491 (< (point) end))
5492 (not (eobp)))
5493 (funcall fun)))))
5495 (defun org-fixup-indentation (diff)
5496 "Change the indentation in the current entry by DIFF
5497 However, if any line in the current entry has no indentation, or if it
5498 would end up with no indentation after the change, nothing at all is done."
5499 (save-excursion
5500 (let ((end (save-excursion (outline-next-heading)
5501 (point-marker)))
5502 (prohibit (if (> diff 0)
5503 "^\\S-"
5504 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5505 col)
5506 (unless (save-excursion (end-of-line 1)
5507 (re-search-forward prohibit end t))
5508 (while (and (< (point) end)
5509 (re-search-forward "^[ \t]+" end t))
5510 (goto-char (match-end 0))
5511 (setq col (current-column))
5512 (if (< diff 0) (replace-match ""))
5513 (org-indent-to-column (+ diff col))))
5514 (move-marker end nil))))
5516 (defun org-convert-to-odd-levels ()
5517 "Convert an org-mode file with all levels allowed to one with odd levels.
5518 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5519 level 5 etc."
5520 (interactive)
5521 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5522 (let ((org-odd-levels-only nil) n)
5523 (save-excursion
5524 (goto-char (point-min))
5525 (while (re-search-forward "^\\*\\*+ " nil t)
5526 (setq n (- (length (match-string 0)) 2))
5527 (while (>= (setq n (1- n)) 0)
5528 (org-demote))
5529 (end-of-line 1))))))
5532 (defun org-convert-to-oddeven-levels ()
5533 "Convert an org-mode file with only odd levels to one with odd and even levels.
5534 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5535 section with an even level, conversion would destroy the structure of the file. An error
5536 is signaled in this case."
5537 (interactive)
5538 (goto-char (point-min))
5539 ;; First check if there are no even levels
5540 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5541 (org-show-context t)
5542 (error "Not all levels are odd in this file. Conversion not possible."))
5543 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5544 (let ((org-odd-levels-only nil) n)
5545 (save-excursion
5546 (goto-char (point-min))
5547 (while (re-search-forward "^\\*\\*+ " nil t)
5548 (setq n (/ (1- (length (match-string 0))) 2))
5549 (while (>= (setq n (1- n)) 0)
5550 (org-promote))
5551 (end-of-line 1))))))
5553 (defun org-tr-level (n)
5554 "Make N odd if required."
5555 (if org-odd-levels-only (1+ (/ n 2)) n))
5557 ;;; Vertical tree motion, cutting and pasting of subtrees
5559 (defun org-move-subtree-up (&optional arg)
5560 "Move the current subtree up past ARG headlines of the same level."
5561 (interactive "p")
5562 (org-move-subtree-down (- (prefix-numeric-value arg))))
5564 (defun org-move-subtree-down (&optional arg)
5565 "Move the current subtree down past ARG headlines of the same level."
5566 (interactive "p")
5567 (setq arg (prefix-numeric-value arg))
5568 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5569 'outline-get-last-sibling))
5570 (ins-point (make-marker))
5571 (cnt (abs arg))
5572 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5573 ;; Select the tree
5574 (org-back-to-heading)
5575 (setq beg0 (point))
5576 (save-excursion
5577 (setq ne-beg (org-back-over-empty-lines))
5578 (setq beg (point)))
5579 (save-match-data
5580 (save-excursion (outline-end-of-heading)
5581 (setq folded (org-invisible-p)))
5582 (outline-end-of-subtree))
5583 (outline-next-heading)
5584 (setq ne-end (org-back-over-empty-lines))
5585 (setq end (point))
5586 (goto-char beg0)
5587 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5588 ;; include less whitespace
5589 (save-excursion
5590 (goto-char beg)
5591 (forward-line (- ne-beg ne-end))
5592 (setq beg (point))))
5593 ;; Find insertion point, with error handling
5594 (while (> cnt 0)
5595 (or (and (funcall movfunc) (looking-at outline-regexp))
5596 (progn (goto-char beg0)
5597 (error "Cannot move past superior level or buffer limit")))
5598 (setq cnt (1- cnt)))
5599 (if (> arg 0)
5600 ;; Moving forward - still need to move over subtree
5601 (progn (org-end-of-subtree t t)
5602 (save-excursion
5603 (org-back-over-empty-lines)
5604 (or (bolp) (newline)))))
5605 (setq ne-ins (org-back-over-empty-lines))
5606 (move-marker ins-point (point))
5607 (setq txt (buffer-substring beg end))
5608 (org-save-markers-in-region beg end)
5609 (delete-region beg end)
5610 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5611 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5612 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5613 (let ((bbb (point)))
5614 (insert-before-markers txt)
5615 (org-reinstall-markers-in-region bbb)
5616 (move-marker ins-point bbb))
5617 (or (bolp) (insert "\n"))
5618 (setq ins-end (point))
5619 (goto-char ins-point)
5620 (org-skip-whitespace)
5621 (when (and (< arg 0)
5622 (org-first-sibling-p)
5623 (> ne-ins ne-beg))
5624 ;; Move whitespace back to beginning
5625 (save-excursion
5626 (goto-char ins-end)
5627 (let ((kill-whole-line t))
5628 (kill-line (- ne-ins ne-beg)) (point)))
5629 (insert (make-string (- ne-ins ne-beg) ?\n)))
5630 (move-marker ins-point nil)
5631 (org-compact-display-after-subtree-move)
5632 (org-show-empty-lines-in-parent)
5633 (unless folded
5634 (org-show-entry)
5635 (show-children)
5636 (org-cycle-hide-drawers 'children))))
5638 (defvar org-subtree-clip ""
5639 "Clipboard for cut and paste of subtrees.
5640 This is actually only a copy of the kill, because we use the normal kill
5641 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5643 (defvar org-subtree-clip-folded nil
5644 "Was the last copied subtree folded?
5645 This is used to fold the tree back after pasting.")
5647 (defun org-cut-subtree (&optional n)
5648 "Cut the current subtree into the clipboard.
5649 With prefix arg N, cut this many sequential subtrees.
5650 This is a short-hand for marking the subtree and then cutting it."
5651 (interactive "p")
5652 (org-copy-subtree n 'cut))
5654 (defun org-copy-subtree (&optional n cut force-store-markers)
5655 "Cut the current subtree into the clipboard.
5656 With prefix arg N, cut this many sequential subtrees.
5657 This is a short-hand for marking the subtree and then copying it.
5658 If CUT is non-nil, actually cut the subtree.
5659 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5660 of some markers in the region, even if CUT is non-nil. This is
5661 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5662 (interactive "p")
5663 (let (beg end folded (beg0 (point)))
5664 (if (interactive-p)
5665 (org-back-to-heading nil) ; take what looks like a subtree
5666 (org-back-to-heading t)) ; take what is really there
5667 (org-back-over-empty-lines)
5668 (setq beg (point))
5669 (skip-chars-forward " \t\r\n")
5670 (save-match-data
5671 (save-excursion (outline-end-of-heading)
5672 (setq folded (org-invisible-p)))
5673 (condition-case nil
5674 (outline-forward-same-level (1- n))
5675 (error nil))
5676 (org-end-of-subtree t t))
5677 (org-back-over-empty-lines)
5678 (setq end (point))
5679 (goto-char beg0)
5680 (when (> end beg)
5681 (setq org-subtree-clip-folded folded)
5682 (when (or cut force-store-markers)
5683 (org-save-markers-in-region beg end))
5684 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5685 (setq org-subtree-clip (current-kill 0))
5686 (message "%s: Subtree(s) with %d characters"
5687 (if cut "Cut" "Copied")
5688 (length org-subtree-clip)))))
5690 (defun org-paste-subtree (&optional level tree for-yank)
5691 "Paste the clipboard as a subtree, with modification of headline level.
5692 The entire subtree is promoted or demoted in order to match a new headline
5693 level.
5695 If the cursor is at the beginning of a headline, the same level as
5696 that headline is used to paste the tree
5698 If not, the new level is derived from the *visible* headings
5699 before and after the insertion point, and taken to be the inferior headline
5700 level of the two. So if the previous visible heading is level 3 and the
5701 next is level 4 (or vice versa), level 4 will be used for insertion.
5702 This makes sure that the subtree remains an independent subtree and does
5703 not swallow low level entries.
5705 You can also force a different level, either by using a numeric prefix
5706 argument, or by inserting the heading marker by hand. For example, if the
5707 cursor is after \"*****\", then the tree will be shifted to level 5.
5709 If optional TREE is given, use this text instead of the kill ring.
5711 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5712 move back over whitespace before inserting, and move point to the end of
5713 the inserted text when done."
5714 (interactive "P")
5715 (unless (org-kill-is-subtree-p tree)
5716 (error "%s"
5717 (substitute-command-keys
5718 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5719 (let* ((visp (not (org-invisible-p)))
5720 (txt (or tree (and kill-ring (current-kill 0))))
5721 (^re (concat "^\\(" outline-regexp "\\)"))
5722 (re (concat "\\(" outline-regexp "\\)"))
5723 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5725 (old-level (if (string-match ^re txt)
5726 (- (match-end 0) (match-beginning 0) 1)
5727 -1))
5728 (force-level (cond (level (prefix-numeric-value level))
5729 ((and (looking-at "[ \t]*$")
5730 (string-match
5731 ^re_ (buffer-substring
5732 (point-at-bol) (point))))
5733 (- (match-end 1) (match-beginning 1)))
5734 ((and (bolp)
5735 (looking-at org-outline-regexp))
5736 (- (match-end 0) (point) 1))
5737 (t nil)))
5738 (previous-level (save-excursion
5739 (condition-case nil
5740 (progn
5741 (outline-previous-visible-heading 1)
5742 (if (looking-at re)
5743 (- (match-end 0) (match-beginning 0) 1)
5745 (error 1))))
5746 (next-level (save-excursion
5747 (condition-case nil
5748 (progn
5749 (or (looking-at outline-regexp)
5750 (outline-next-visible-heading 1))
5751 (if (looking-at re)
5752 (- (match-end 0) (match-beginning 0) 1)
5754 (error 1))))
5755 (new-level (or force-level (max previous-level next-level)))
5756 (shift (if (or (= old-level -1)
5757 (= new-level -1)
5758 (= old-level new-level))
5760 (- new-level old-level)))
5761 (delta (if (> shift 0) -1 1))
5762 (func (if (> shift 0) 'org-demote 'org-promote))
5763 (org-odd-levels-only nil)
5764 beg end newend)
5765 ;; Remove the forced level indicator
5766 (if force-level
5767 (delete-region (point-at-bol) (point)))
5768 ;; Paste
5769 (beginning-of-line 1)
5770 (unless for-yank (org-back-over-empty-lines))
5771 (setq beg (point))
5772 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5773 (insert-before-markers txt)
5774 (unless (string-match "\n\\'" txt) (insert "\n"))
5775 (setq newend (point))
5776 (org-reinstall-markers-in-region beg)
5777 (setq end (point))
5778 (goto-char beg)
5779 (skip-chars-forward " \t\n\r")
5780 (setq beg (point))
5781 (if (and (org-invisible-p) visp)
5782 (save-excursion (outline-show-heading)))
5783 ;; Shift if necessary
5784 (unless (= shift 0)
5785 (save-restriction
5786 (narrow-to-region beg end)
5787 (while (not (= shift 0))
5788 (org-map-region func (point-min) (point-max))
5789 (setq shift (+ delta shift)))
5790 (goto-char (point-min))
5791 (setq newend (point-max))))
5792 (when (or (interactive-p) for-yank)
5793 (message "Clipboard pasted as level %d subtree" new-level))
5794 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5795 kill-ring
5796 (eq org-subtree-clip (current-kill 0))
5797 org-subtree-clip-folded)
5798 ;; The tree was folded before it was killed/copied
5799 (hide-subtree))
5800 (and for-yank (goto-char newend))))
5802 (defun org-kill-is-subtree-p (&optional txt)
5803 "Check if the current kill is an outline subtree, or a set of trees.
5804 Returns nil if kill does not start with a headline, or if the first
5805 headline level is not the largest headline level in the tree.
5806 So this will actually accept several entries of equal levels as well,
5807 which is OK for `org-paste-subtree'.
5808 If optional TXT is given, check this string instead of the current kill."
5809 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5810 (start-level (and kill
5811 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5812 org-outline-regexp "\\)")
5813 kill)
5814 (- (match-end 2) (match-beginning 2) 1)))
5815 (re (concat "^" org-outline-regexp))
5816 (start (1+ (or (match-beginning 2) -1))))
5817 (if (not start-level)
5818 (progn
5819 nil) ;; does not even start with a heading
5820 (catch 'exit
5821 (while (setq start (string-match re kill (1+ start)))
5822 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5823 (throw 'exit nil)))
5824 t))))
5826 (defvar org-markers-to-move nil
5827 "Markers that should be moved with a cut-and-paste operation.
5828 Those markers are stored together with their positions relative to
5829 the start of the region.")
5831 (defun org-save-markers-in-region (beg end)
5832 "Check markers in region.
5833 If these markers are between BEG and END, record their position relative
5834 to BEG, so that after moving the block of text, we can put the markers back
5835 into place.
5836 This function gets called just before an entry or tree gets cut from the
5837 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5838 called immediately, to move the markers with the entries."
5839 (setq org-markers-to-move nil)
5840 (when (featurep 'org-clock)
5841 (org-clock-save-markers-for-cut-and-paste beg end))
5842 (when (featurep 'org-agenda)
5843 (org-agenda-save-markers-for-cut-and-paste beg end)))
5845 (defun org-check-and-save-marker (marker beg end)
5846 "Check if MARKER is between BEG and END.
5847 If yes, remember the marker and the distance to BEG."
5848 (when (and (marker-buffer marker)
5849 (equal (marker-buffer marker) (current-buffer)))
5850 (if (and (>= marker beg) (< marker end))
5851 (push (cons marker (- marker beg)) org-markers-to-move))))
5853 (defun org-reinstall-markers-in-region (beg)
5854 "Move all remembered markers to their position relative to BEG."
5855 (mapc (lambda (x)
5856 (move-marker (car x) (+ beg (cdr x))))
5857 org-markers-to-move)
5858 (setq org-markers-to-move nil))
5860 (defun org-narrow-to-subtree ()
5861 "Narrow buffer to the current subtree."
5862 (interactive)
5863 (save-excursion
5864 (save-match-data
5865 (narrow-to-region
5866 (progn (org-back-to-heading) (point))
5867 (progn (org-end-of-subtree t) (point))))))
5869 (defun org-clone-subtree-with-time-shift (n &optional shift)
5870 "Clone the task (subtree) at point N times.
5871 The clones will be inserted as siblings.
5873 In interactive use, the user will be prompted for the number of clones
5874 to be produced, and for a time SHIFT, which may be a repeater as used
5875 in time stamps, for example `+3d'.
5877 When a valid repeater is given and the entry contains any time stamps,
5878 the clones will become a sequence in time, with time stamps in the
5879 subtree shifted for each clone produced. If SHIFT is nil or the
5880 empty string, time stamps will be left alone.
5882 If the original subtree did contain time stamps with a repeater,
5883 the following will happen:
5884 - the repeater will be removed in each clone
5885 - an additional clone will be produced, with the current, unshifted
5886 date(s) in the entry.
5887 - the original entry will be placed *after* all the clones, with
5888 repeater intact.
5889 - the start days in the repeater in the original entry will be shifted
5890 to past the last clone.
5891 I this way you can spell out a number of instances of a repeating task,
5892 and still retain the repeater to cover future instances of the task."
5893 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
5894 (let (beg end template task
5895 shift-n shift-what doshift nmin nmax (n-no-remove -1))
5896 (if (not (and (integerp n) (> n 0)))
5897 (error "Invalid number of replications %s" n))
5898 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
5899 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
5900 shift)))
5901 (error "Invalid shift specification %s" shift))
5902 (when doshift
5903 (setq shift-n (string-to-number (match-string 1 shift))
5904 shift-what (cdr (assoc (match-string 2 shift)
5905 '(("d" . day) ("w" . week)
5906 ("m" . month) ("y" . year))))))
5907 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
5908 (setq nmin 1 nmax n)
5909 (org-back-to-heading t)
5910 (setq beg (point))
5911 (org-end-of-subtree t t)
5912 (setq end (point))
5913 (setq template (buffer-substring beg end))
5914 (when (and doshift
5915 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
5916 (delete-region beg end)
5917 (setq end beg)
5918 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
5919 (goto-char end)
5920 (loop for n from nmin to nmax do
5921 (if (not doshift)
5922 (setq task template)
5923 (with-temp-buffer
5924 (insert template)
5925 (org-mode)
5926 (goto-char (point-min))
5927 (while (re-search-forward org-ts-regexp nil t)
5928 (org-timestamp-change (* n shift-n) shift-what))
5929 (unless (= n n-no-remove)
5930 (goto-char (point-min))
5931 (while (re-search-forward org-ts-regexp nil t)
5932 (save-excursion
5933 (goto-char (match-beginning 0))
5934 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
5935 (delete-region (match-beginning 1) (match-end 1))))))
5936 (setq task (buffer-string))))
5937 (insert task))
5938 (goto-char beg)))
5940 ;;; Outline Sorting
5942 (defun org-sort (with-case)
5943 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5944 Optional argument WITH-CASE means sort case-sensitively.
5945 With a double prefix argument, also remove duplicate entries."
5946 (interactive "P")
5947 (if (org-at-table-p)
5948 (org-call-with-arg 'org-table-sort-lines with-case)
5949 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5951 (defun org-sort-remove-invisible (s)
5952 (remove-text-properties 0 (length s) org-rm-props s)
5953 (while (string-match org-bracket-link-regexp s)
5954 (setq s (replace-match (if (match-end 2)
5955 (match-string 3 s)
5956 (match-string 1 s)) t t s)))
5959 (defvar org-priority-regexp) ; defined later in the file
5961 (defun org-sort-entries-or-items
5962 (&optional with-case sorting-type getkey-func compare-func property)
5963 "Sort entries on a certain level of an outline tree.
5964 If there is an active region, the entries in the region are sorted.
5965 Else, if the cursor is before the first entry, sort the top-level items.
5966 Else, the children of the entry at point are sorted.
5968 Sorting can be alphabetically, numerically, and by date/time as given by
5969 the first time stamp in the entry. The command prompts for the sorting
5970 type unless it has been given to the function through the SORTING-TYPE
5971 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5972 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5973 called with point at the beginning of the record. It must return either
5974 a string or a number that should serve as the sorting key for that record.
5976 Comparing entries ignores case by default. However, with an optional argument
5977 WITH-CASE, the sorting considers case as well."
5978 (interactive "P")
5979 (let ((case-func (if with-case 'identity 'downcase))
5980 start beg end stars re re2
5981 txt what tmp plain-list-p)
5982 ;; Find beginning and end of region to sort
5983 (cond
5984 ((org-region-active-p)
5985 ;; we will sort the region
5986 (setq end (region-end)
5987 what "region")
5988 (goto-char (region-beginning))
5989 (if (not (org-on-heading-p)) (outline-next-heading))
5990 (setq start (point)))
5991 ((org-at-item-p)
5992 ;; we will sort this plain list
5993 (org-beginning-of-item-list) (setq start (point))
5994 (org-end-of-item-list) (setq end (point))
5995 (goto-char start)
5996 (setq plain-list-p t
5997 what "plain list"))
5998 ((or (org-on-heading-p)
5999 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6000 ;; we will sort the children of the current headline
6001 (org-back-to-heading)
6002 (setq start (point)
6003 end (progn (org-end-of-subtree t t)
6004 (org-back-over-empty-lines)
6005 (point))
6006 what "children")
6007 (goto-char start)
6008 (show-subtree)
6009 (outline-next-heading))
6011 ;; we will sort the top-level entries in this file
6012 (goto-char (point-min))
6013 (or (org-on-heading-p) (outline-next-heading))
6014 (setq start (point) end (point-max) what "top-level")
6015 (goto-char start)
6016 (show-all)))
6018 (setq beg (point))
6019 (if (>= beg end) (error "Nothing to sort"))
6021 (unless plain-list-p
6022 (looking-at "\\(\\*+\\)")
6023 (setq stars (match-string 1)
6024 re (concat "^" (regexp-quote stars) " +")
6025 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6026 txt (buffer-substring beg end))
6027 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6028 (if (and (not (equal stars "*")) (string-match re2 txt))
6029 (error "Region to sort contains a level above the first entry")))
6031 (unless sorting-type
6032 (message
6033 (if plain-list-p
6034 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6035 "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:")
6036 what)
6037 (setq sorting-type (read-char-exclusive))
6039 (and (= (downcase sorting-type) ?f)
6040 (setq getkey-func
6041 (org-ido-completing-read "Sort using function: "
6042 obarray 'fboundp t nil nil))
6043 (setq getkey-func (intern getkey-func)))
6045 (and (= (downcase sorting-type) ?r)
6046 (setq property
6047 (org-ido-completing-read "Property: "
6048 (mapcar 'list (org-buffer-property-keys t))
6049 nil t))))
6051 (message "Sorting entries...")
6053 (save-restriction
6054 (narrow-to-region start end)
6056 (let ((dcst (downcase sorting-type))
6057 (now (current-time)))
6058 (sort-subr
6059 (/= dcst sorting-type)
6060 ;; This function moves to the beginning character of the "record" to
6061 ;; be sorted.
6062 (if plain-list-p
6063 (lambda nil
6064 (if (org-at-item-p) t (goto-char (point-max))))
6065 (lambda nil
6066 (if (re-search-forward re nil t)
6067 (goto-char (match-beginning 0))
6068 (goto-char (point-max)))))
6069 ;; This function moves to the last character of the "record" being
6070 ;; sorted.
6071 (if plain-list-p
6072 'org-end-of-item
6073 (lambda nil
6074 (save-match-data
6075 (condition-case nil
6076 (outline-forward-same-level 1)
6077 (error
6078 (goto-char (point-max)))))))
6080 ;; This function returns the value that gets sorted against.
6081 (if plain-list-p
6082 (lambda nil
6083 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6084 (cond
6085 ((= dcst ?n)
6086 (string-to-number (buffer-substring (match-end 0)
6087 (point-at-eol))))
6088 ((= dcst ?a)
6089 (buffer-substring (match-end 0) (point-at-eol)))
6090 ((= dcst ?t)
6091 (if (re-search-forward org-ts-regexp
6092 (point-at-eol) t)
6093 (org-time-string-to-time (match-string 0))
6094 now))
6095 ((= dcst ?f)
6096 (if getkey-func
6097 (progn
6098 (setq tmp (funcall getkey-func))
6099 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6100 tmp)
6101 (error "Invalid key function `%s'" getkey-func)))
6102 (t (error "Invalid sorting type `%c'" sorting-type)))))
6103 (lambda nil
6104 (cond
6105 ((= dcst ?n)
6106 (if (looking-at org-complex-heading-regexp)
6107 (string-to-number (match-string 4))
6108 nil))
6109 ((= dcst ?a)
6110 (if (looking-at org-complex-heading-regexp)
6111 (funcall case-func (match-string 4))
6112 nil))
6113 ((= dcst ?t)
6114 (if (re-search-forward org-ts-regexp
6115 (save-excursion
6116 (forward-line 2)
6117 (point)) t)
6118 (org-time-string-to-time (match-string 0))
6119 now))
6120 ((= dcst ?p)
6121 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6122 (string-to-char (match-string 2))
6123 org-default-priority))
6124 ((= dcst ?r)
6125 (or (org-entry-get nil property) ""))
6126 ((= dcst ?o)
6127 (if (looking-at org-complex-heading-regexp)
6128 (- 9999 (length (member (match-string 2)
6129 org-todo-keywords-1)))))
6130 ((= dcst ?f)
6131 (if getkey-func
6132 (progn
6133 (setq tmp (funcall getkey-func))
6134 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6135 tmp)
6136 (error "Invalid key function `%s'" getkey-func)))
6137 (t (error "Invalid sorting type `%c'" sorting-type)))))
6139 (cond
6140 ((= dcst ?a) 'string<)
6141 ((= dcst ?t) 'time-less-p)
6142 ((= dcst ?f) compare-func)
6143 (t nil)))))
6144 (message "Sorting entries...done")))
6146 (defun org-do-sort (table what &optional with-case sorting-type)
6147 "Sort TABLE of WHAT according to SORTING-TYPE.
6148 The user will be prompted for the SORTING-TYPE if the call to this
6149 function does not specify it. WHAT is only for the prompt, to indicate
6150 what is being sorted. The sorting key will be extracted from
6151 the car of the elements of the table.
6152 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6153 (unless sorting-type
6154 (message
6155 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6156 what)
6157 (setq sorting-type (read-char-exclusive)))
6158 (let ((dcst (downcase sorting-type))
6159 extractfun comparefun)
6160 ;; Define the appropriate functions
6161 (cond
6162 ((= dcst ?n)
6163 (setq extractfun 'string-to-number
6164 comparefun (if (= dcst sorting-type) '< '>)))
6165 ((= dcst ?a)
6166 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6167 (lambda(x) (downcase (org-sort-remove-invisible x))))
6168 comparefun (if (= dcst sorting-type)
6169 'string<
6170 (lambda (a b) (and (not (string< a b))
6171 (not (string= a b)))))))
6172 ((= dcst ?t)
6173 (setq extractfun
6174 (lambda (x)
6175 (if (or (string-match org-ts-regexp x)
6176 (string-match org-ts-regexp-both x))
6177 (time-to-seconds
6178 (org-time-string-to-time (match-string 0 x)))
6180 comparefun (if (= dcst sorting-type) '< '>)))
6181 (t (error "Invalid sorting type `%c'" sorting-type)))
6183 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6184 table)
6185 (lambda (a b) (funcall comparefun (car a) (car b))))))
6187 ;;; Editing source examples
6189 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6190 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6191 (defvar org-edit-src-force-single-line nil)
6192 (defvar org-edit-src-from-org-mode nil)
6193 (defvar org-edit-src-picture nil)
6195 (define-minor-mode org-exit-edit-mode
6196 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6198 (defun org-edit-src-code ()
6199 "Edit the source code example at point.
6200 An indirect buffer is created, and that buffer is then narrowed to the
6201 example at point and switched to the correct language mode. When done,
6202 exit by killing the buffer with \\[org-edit-src-exit]."
6203 (interactive)
6204 (let ((line (org-current-line))
6205 (case-fold-search t)
6206 (msg (substitute-command-keys
6207 "Edit, then exit with C-c ' (C-c and single quote)"))
6208 (info (org-edit-src-find-region-and-lang))
6209 (org-mode-p (eq major-mode 'org-mode))
6210 beg end lang lang-f single lfmt)
6211 (if (not info)
6213 (setq beg (nth 0 info)
6214 end (nth 1 info)
6215 lang (nth 2 info)
6216 single (nth 3 info)
6217 lfmt (nth 4 info)
6218 lang-f (intern (concat lang "-mode")))
6219 (unless (functionp lang-f)
6220 (error "No such language mode: %s" lang-f))
6221 (goto-line line)
6222 (if (get-buffer "*Org Edit Src Example*")
6223 (kill-buffer "*Org Edit Src Example*"))
6224 (switch-to-buffer (make-indirect-buffer (current-buffer)
6225 "*Org Edit Src Example*"))
6226 (narrow-to-region beg end)
6227 (remove-text-properties beg end '(display nil invisible nil
6228 intangible nil))
6229 (let ((org-inhibit-startup t))
6230 (funcall lang-f))
6231 (set (make-local-variable 'org-edit-src-force-single-line) single)
6232 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6233 (when lfmt
6234 (set (make-local-variable 'org-coderef-label-format) lfmt))
6235 (when org-mode-p
6236 (goto-char (point-min))
6237 (while (re-search-forward "^," nil t)
6238 (replace-match "")))
6239 (goto-line line)
6240 (org-exit-edit-mode)
6241 (org-set-local 'header-line-format msg)
6242 (message "%s" msg)
6243 t)))
6245 (defun org-edit-fixed-width-region ()
6246 "Edit the fixed-width ascii drawing at point.
6247 This must be a region where each line starts with a colon followed by
6248 a space character.
6249 An indirect buffer is created, and that buffer is then narrowed to the
6250 example at point and switched to artist-mode. When done,
6251 exit by killing the buffer with \\[org-edit-src-exit]."
6252 (interactive)
6253 (let ((line (org-current-line))
6254 (case-fold-search t)
6255 (msg (substitute-command-keys
6256 "Edit, then exit with C-c ' (C-c and single quote)"))
6257 (org-mode-p (eq major-mode 'org-mode))
6258 beg end)
6259 (beginning-of-line 1)
6260 (if (looking-at "[ \t]*[^:\n \t]")
6262 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6263 (setq beg (point) end beg)
6264 (save-excursion
6265 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6266 (setq beg (point-at-bol 2))
6267 (setq beg (point))))
6268 (save-excursion
6269 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6270 (setq end (1- (match-beginning 0)))
6271 (setq end (point))))
6272 (goto-line line))
6273 (if (get-buffer "*Org Edit Picture*")
6274 (kill-buffer "*Org Edit Picture*"))
6275 (switch-to-buffer (make-indirect-buffer (current-buffer)
6276 "*Org Edit Picture*"))
6277 (narrow-to-region beg end)
6278 (remove-text-properties beg end '(display nil invisible nil
6279 intangible nil))
6280 (when (fboundp 'font-lock-unfontify-region)
6281 (font-lock-unfontify-region (point-min) (point-max)))
6282 (cond
6283 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6284 (fundamental-mode)
6285 (artist-mode 1))
6286 (t (funcall org-edit-fixed-width-region-mode)))
6287 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6288 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6289 (set (make-local-variable 'org-edit-src-picture) t)
6290 (goto-char (point-min))
6291 (while (re-search-forward "^[ \t]*: ?" nil t)
6292 (replace-match ""))
6293 (goto-line line)
6294 (org-exit-edit-mode)
6295 (org-set-local 'header-line-format msg)
6296 (message "%s" msg)
6297 t)))
6300 (defun org-edit-src-find-region-and-lang ()
6301 "Find the region and language for a local edit.
6302 Return a list with beginning and end of the region, a string representing
6303 the language, a switch telling of the content should be in a single line."
6304 (let ((re-list
6305 (append
6306 org-edit-src-region-extra
6308 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6309 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6310 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6311 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6312 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6313 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6314 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6315 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6316 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6317 ("^#\\+html:" "\n" "html" single-line)
6318 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6319 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6320 ("^#\\+latex:" "\n" "latex" single-line)
6321 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6322 ("^#\\+ascii:" "\n" "ascii" single-line)
6324 (pos (point))
6325 re1 re2 single beg end lang lfmt match-re1)
6326 (catch 'exit
6327 (while (setq entry (pop re-list))
6328 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6329 single (nth 3 entry))
6330 (save-excursion
6331 (if (or (looking-at re1)
6332 (re-search-backward re1 nil t))
6333 (progn
6334 (setq match-re1 (match-string 0))
6335 (setq beg (match-end 0)
6336 lang (org-edit-src-get-lang lang)
6337 lfmt (org-edit-src-get-label-format match-re1))
6338 (if (and (re-search-forward re2 nil t)
6339 (>= (match-end 0) pos))
6340 (throw 'exit (list beg (match-beginning 0)
6341 lang single lfmt))))
6342 (if (or (looking-at re2)
6343 (re-search-forward re2 nil t))
6344 (progn
6345 (setq end (match-beginning 0))
6346 (if (and (re-search-backward re1 nil t)
6347 (<= (match-beginning 0) pos))
6348 (progn
6349 (setq lfmt (org-edit-src-get-label-format
6350 (match-string 0)))
6351 (throw 'exit
6352 (list (match-end 0) end
6353 (org-edit-src-get-lang lang)
6354 single lfmt))))))))))))
6356 (defun org-edit-src-get-lang (lang)
6357 "Extract the src language."
6358 (let ((m (match-string 0)))
6359 (cond
6360 ((stringp lang) lang)
6361 ((integerp lang) (match-string lang))
6362 ((and (eq lang 'lang)
6363 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6364 (match-string 1 m))
6365 ((and (eq lang 'style)
6366 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6367 (match-string 1 m))
6368 (t "fundamental"))))
6370 (defun org-edit-src-get-label-format (s)
6371 "Extract the label format."
6372 (save-match-data
6373 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6374 (match-string 1 s))))
6376 (defun org-edit-src-exit ()
6377 "Exit special edit and protect problematic lines."
6378 (interactive)
6379 (unless (buffer-base-buffer (current-buffer))
6380 (error "This is not an indirect buffer, something is wrong..."))
6381 (unless (> (point-min) 1)
6382 (error "This buffer is not narrowed, something is wrong..."))
6383 (goto-char (point-min))
6384 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6385 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6386 (when (org-bound-and-true-p org-edit-src-force-single-line)
6387 (goto-char (point-min))
6388 (while (re-search-forward "\n" nil t)
6389 (replace-match " "))
6390 (goto-char (point-min))
6391 (if (looking-at "\\s-*") (replace-match " "))
6392 (if (re-search-forward "\\s-+\\'" nil t)
6393 (replace-match "")))
6394 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6395 (goto-char (point-min))
6396 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6397 (replace-match ",\\1"))
6398 (when font-lock-mode
6399 (font-lock-unfontify-region (point-min) (point-max)))
6400 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6401 (when (org-bound-and-true-p org-edit-src-picture)
6402 (untabify (point-min) (point-max))
6403 (goto-char (point-min))
6404 (while (re-search-forward "^" nil t)
6405 (replace-match ": "))
6406 (when font-lock-mode
6407 (font-lock-unfontify-region (point-min) (point-max)))
6408 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6409 (kill-buffer (current-buffer))
6410 (and (org-mode-p) (org-restart-font-lock)))
6413 ;;; The orgstruct minor mode
6415 ;; Define a minor mode which can be used in other modes in order to
6416 ;; integrate the org-mode structure editing commands.
6418 ;; This is really a hack, because the org-mode structure commands use
6419 ;; keys which normally belong to the major mode. Here is how it
6420 ;; works: The minor mode defines all the keys necessary to operate the
6421 ;; structure commands, but wraps the commands into a function which
6422 ;; tests if the cursor is currently at a headline or a plain list
6423 ;; item. If that is the case, the structure command is used,
6424 ;; temporarily setting many Org-mode variables like regular
6425 ;; expressions for filling etc. However, when any of those keys is
6426 ;; used at a different location, function uses `key-binding' to look
6427 ;; up if the key has an associated command in another currently active
6428 ;; keymap (minor modes, major mode, global), and executes that
6429 ;; command. There might be problems if any of the keys is otherwise
6430 ;; used as a prefix key.
6432 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6433 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6434 ;; addresses this by checking explicitly for both bindings.
6436 (defvar orgstruct-mode-map (make-sparse-keymap)
6437 "Keymap for the minor `orgstruct-mode'.")
6439 (defvar org-local-vars nil
6440 "List of local variables, for use by `orgstruct-mode'")
6442 ;;;###autoload
6443 (define-minor-mode orgstruct-mode
6444 "Toggle the minor more `orgstruct-mode'.
6445 This mode is for using Org-mode structure commands in other modes.
6446 The following key behave as if Org-mode was active, if the cursor
6447 is on a headline, or on a plain list item (both in the definition
6448 of Org-mode).
6450 M-up Move entry/item up
6451 M-down Move entry/item down
6452 M-left Promote
6453 M-right Demote
6454 M-S-up Move entry/item up
6455 M-S-down Move entry/item down
6456 M-S-left Promote subtree
6457 M-S-right Demote subtree
6458 M-q Fill paragraph and items like in Org-mode
6459 C-c ^ Sort entries
6460 C-c - Cycle list bullet
6461 TAB Cycle item visibility
6462 M-RET Insert new heading/item
6463 S-M-RET Insert new TODO heading / Checkbox item
6464 C-c C-c Set tags / toggle checkbox"
6465 nil " OrgStruct" nil
6466 (org-load-modules-maybe)
6467 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6469 ;;;###autoload
6470 (defun turn-on-orgstruct ()
6471 "Unconditionally turn on `orgstruct-mode'."
6472 (orgstruct-mode 1))
6474 (defun orgstruct++-mode (&optional arg)
6475 "Toggle `orgstruct-mode', the enhanced version of it.
6476 In addition to setting orgstruct-mode, this also exports all indentation and
6477 autofilling variables from org-mode into the buffer. It will also
6478 recognize item context in multiline items.
6479 Note that turning off orgstruct-mode will *not* remove the
6480 indentation/paragraph settings. This can only be done by refreshing the
6481 major mode, for example with \[normal-mode]."
6482 (interactive "P")
6483 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6484 (if (< arg 1)
6485 (orgstruct-mode -1)
6486 (orgstruct-mode 1)
6487 (let (var val)
6488 (mapc
6489 (lambda (x)
6490 (when (string-match
6491 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6492 (symbol-name (car x)))
6493 (setq var (car x) val (nth 1 x))
6494 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6495 org-local-vars)
6496 (org-set-local 'orgstruct-is-++ t))))
6498 (defvar orgstruct-is-++ nil
6499 "Is orgstruct-mode in ++ version in the current-buffer?")
6500 (make-variable-buffer-local 'orgstruct-is-++)
6502 ;;;###autoload
6503 (defun turn-on-orgstruct++ ()
6504 "Unconditionally turn on `orgstruct++-mode'."
6505 (orgstruct++-mode 1))
6507 (defun orgstruct-error ()
6508 "Error when there is no default binding for a structure key."
6509 (interactive)
6510 (error "This key has no function outside structure elements"))
6512 (defun orgstruct-setup ()
6513 "Setup orgstruct keymaps."
6514 (let ((nfunc 0)
6515 (bindings
6516 (list
6517 '([(meta up)] org-metaup)
6518 '([(meta down)] org-metadown)
6519 '([(meta left)] org-metaleft)
6520 '([(meta right)] org-metaright)
6521 '([(meta shift up)] org-shiftmetaup)
6522 '([(meta shift down)] org-shiftmetadown)
6523 '([(meta shift left)] org-shiftmetaleft)
6524 '([(meta shift right)] org-shiftmetaright)
6525 '([(shift up)] org-shiftup)
6526 '([(shift down)] org-shiftdown)
6527 '([(shift left)] org-shiftleft)
6528 '([(shift right)] org-shiftright)
6529 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6530 '("\M-q" fill-paragraph)
6531 '("\C-c^" org-sort)
6532 '("\C-c-" org-cycle-list-bullet)))
6533 elt key fun cmd)
6534 (while (setq elt (pop bindings))
6535 (setq nfunc (1+ nfunc))
6536 (setq key (org-key (car elt))
6537 fun (nth 1 elt)
6538 cmd (orgstruct-make-binding fun nfunc key))
6539 (org-defkey orgstruct-mode-map key cmd))
6541 ;; Special treatment needed for TAB and RET
6542 (org-defkey orgstruct-mode-map [(tab)]
6543 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6544 (org-defkey orgstruct-mode-map "\C-i"
6545 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6547 (org-defkey orgstruct-mode-map "\M-\C-m"
6548 (orgstruct-make-binding 'org-insert-heading 105
6549 "\M-\C-m" [(meta return)]))
6550 (org-defkey orgstruct-mode-map [(meta return)]
6551 (orgstruct-make-binding 'org-insert-heading 106
6552 [(meta return)] "\M-\C-m"))
6554 (org-defkey orgstruct-mode-map [(shift meta return)]
6555 (orgstruct-make-binding 'org-insert-todo-heading 107
6556 [(meta return)] "\M-\C-m"))
6558 (unless org-local-vars
6559 (setq org-local-vars (org-get-local-variables)))
6563 (defun orgstruct-make-binding (fun n &rest keys)
6564 "Create a function for binding in the structure minor mode.
6565 FUN is the command to call inside a table. N is used to create a unique
6566 command name. KEYS are keys that should be checked in for a command
6567 to execute outside of tables."
6568 (eval
6569 (list 'defun
6570 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6571 '(arg)
6572 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6573 "Outside of structure, run the binding of `"
6574 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6575 "'.")
6576 '(interactive "p")
6577 (list 'if
6578 `(org-context-p 'headline 'item
6579 (and orgstruct-is-++
6580 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6581 'item-body))
6582 (list 'org-run-like-in-org-mode (list 'quote fun))
6583 (list 'let '(orgstruct-mode)
6584 (list 'call-interactively
6585 (append '(or)
6586 (mapcar (lambda (k)
6587 (list 'key-binding k))
6588 keys)
6589 '('orgstruct-error))))))))
6591 (defun org-context-p (&rest contexts)
6592 "Check if local context is any of CONTEXTS.
6593 Possible values in the list of contexts are `table', `headline', and `item'."
6594 (let ((pos (point)))
6595 (goto-char (point-at-bol))
6596 (prog1 (or (and (memq 'table contexts)
6597 (looking-at "[ \t]*|"))
6598 (and (memq 'headline contexts)
6599 ;;????????? (looking-at "\\*+"))
6600 (looking-at outline-regexp))
6601 (and (memq 'item contexts)
6602 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6603 (and (memq 'item-body contexts)
6604 (org-in-item-p)))
6605 (goto-char pos))))
6607 (defun org-get-local-variables ()
6608 "Return a list of all local variables in an org-mode buffer."
6609 (let (varlist)
6610 (with-current-buffer (get-buffer-create "*Org tmp*")
6611 (erase-buffer)
6612 (org-mode)
6613 (setq varlist (buffer-local-variables)))
6614 (kill-buffer "*Org tmp*")
6615 (delq nil
6616 (mapcar
6617 (lambda (x)
6618 (setq x
6619 (if (symbolp x)
6620 (list x)
6621 (list (car x) (list 'quote (cdr x)))))
6622 (if (string-match
6623 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6624 (symbol-name (car x)))
6625 x nil))
6626 varlist))))
6628 ;;;###autoload
6629 (defun org-run-like-in-org-mode (cmd)
6630 "Run a command, pretending that the current buffer is in Org-mode.
6631 This will temporarily bind local variables that are typically bound in
6632 Org-mode to the values they have in Org-mode, and then interactively
6633 call CMD."
6634 (org-load-modules-maybe)
6635 (unless org-local-vars
6636 (setq org-local-vars (org-get-local-variables)))
6637 (eval (list 'let org-local-vars
6638 (list 'call-interactively (list 'quote cmd)))))
6640 ;;;; Archiving
6642 (defun org-get-category (&optional pos)
6643 "Get the category applying to position POS."
6644 (get-text-property (or pos (point)) 'org-category))
6646 (defun org-refresh-category-properties ()
6647 "Refresh category text properties in the buffer."
6648 (let ((def-cat (cond
6649 ((null org-category)
6650 (if buffer-file-name
6651 (file-name-sans-extension
6652 (file-name-nondirectory buffer-file-name))
6653 "???"))
6654 ((symbolp org-category) (symbol-name org-category))
6655 (t org-category)))
6656 beg end cat pos optionp)
6657 (org-unmodified
6658 (save-excursion
6659 (save-restriction
6660 (widen)
6661 (goto-char (point-min))
6662 (put-text-property (point) (point-max) 'org-category def-cat)
6663 (while (re-search-forward
6664 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6665 (setq pos (match-end 0)
6666 optionp (equal (char-after (match-beginning 0)) ?#)
6667 cat (org-trim (match-string 2)))
6668 (if optionp
6669 (setq beg (point-at-bol) end (point-max))
6670 (org-back-to-heading t)
6671 (setq beg (point) end (org-end-of-subtree t t)))
6672 (put-text-property beg end 'org-category cat)
6673 (goto-char pos)))))))
6676 ;;;; Link Stuff
6678 ;;; Link abbreviations
6680 (defun org-link-expand-abbrev (link)
6681 "Apply replacements as defined in `org-link-abbrev-alist."
6682 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6683 (let* ((key (match-string 1 link))
6684 (as (or (assoc key org-link-abbrev-alist-local)
6685 (assoc key org-link-abbrev-alist)))
6686 (tag (and (match-end 2) (match-string 3 link)))
6687 rpl)
6688 (if (not as)
6689 link
6690 (setq rpl (cdr as))
6691 (cond
6692 ((symbolp rpl) (funcall rpl tag))
6693 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6694 ((string-match "%h" rpl)
6695 (replace-match (url-hexify-string (or tag "")) t t rpl))
6696 (t (concat rpl tag)))))
6697 link))
6699 ;;; Storing and inserting links
6701 (defvar org-insert-link-history nil
6702 "Minibuffer history for links inserted with `org-insert-link'.")
6704 (defvar org-stored-links nil
6705 "Contains the links stored with `org-store-link'.")
6707 (defvar org-store-link-plist nil
6708 "Plist with info about the most recently link created with `org-store-link'.")
6710 (defvar org-link-protocols nil
6711 "Link protocols added to Org-mode using `org-add-link-type'.")
6713 (defvar org-store-link-functions nil
6714 "List of functions that are called to create and store a link.
6715 Each function will be called in turn until one returns a non-nil
6716 value. Each function should check if it is responsible for creating
6717 this link (for example by looking at the major mode).
6718 If not, it must exit and return nil.
6719 If yes, it should return a non-nil value after a calling
6720 `org-store-link-props' with a list of properties and values.
6721 Special properties are:
6723 :type The link prefix. like \"http\". This must be given.
6724 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6725 This is obligatory as well.
6726 :description Optional default description for the second pair
6727 of brackets in an Org-mode link. The user can still change
6728 this when inserting this link into an Org-mode buffer.
6730 In addition to these, any additional properties can be specified
6731 and then used in remember templates.")
6733 (defun org-add-link-type (type &optional follow export)
6734 "Add TYPE to the list of `org-link-types'.
6735 Re-compute all regular expressions depending on `org-link-types'
6737 FOLLOW and EXPORT are two functions.
6739 FOLLOW should take the link path as the single argument and do whatever
6740 is necessary to follow the link, for example find a file or display
6741 a mail message.
6743 EXPORT should format the link path for export to one of the export formats.
6744 It should be a function accepting three arguments:
6746 path the path of the link, the text after the prefix (like \"http:\")
6747 desc the description of the link, if any, nil if there was no description
6748 format the export format, a symbol like `html' or `latex'.
6750 The function may use the FORMAT information to return different values
6751 depending on the format. The return value will be put literally into
6752 the exported file.
6753 Org-mode has a built-in default for exporting links. If you are happy with
6754 this default, there is no need to define an export function for the link
6755 type. For a simple example of an export function, see `org-bbdb.el'."
6756 (add-to-list 'org-link-types type t)
6757 (org-make-link-regexps)
6758 (if (assoc type org-link-protocols)
6759 (setcdr (assoc type org-link-protocols) (list follow export))
6760 (push (list type follow export) org-link-protocols)))
6762 ;;;###autoload
6763 (defun org-store-link (arg)
6764 "\\<org-mode-map>Store an org-link to the current location.
6765 This link is added to `org-stored-links' and can later be inserted
6766 into an org-buffer with \\[org-insert-link].
6768 For some link types, a prefix arg is interpreted:
6769 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6770 For file links, arg negates `org-context-in-file-links'."
6771 (interactive "P")
6772 (org-load-modules-maybe)
6773 (setq org-store-link-plist nil) ; reset
6774 (let (link cpltxt desc description search txt)
6775 (cond
6777 ((run-hook-with-args-until-success 'org-store-link-functions)
6778 (setq link (plist-get org-store-link-plist :link)
6779 desc (or (plist-get org-store-link-plist :description) link)))
6781 ((equal (buffer-name) "*Org Edit Src Example*")
6782 (let (label gc)
6783 (while (or (not label)
6784 (save-excursion
6785 (save-restriction
6786 (widen)
6787 (goto-char (point-min))
6788 (re-search-forward
6789 (regexp-quote (format org-coderef-label-format label))
6790 nil t))))
6791 (when label (message "Label exists already") (sit-for 2))
6792 (setq label (read-string "Code line label: " label)))
6793 (end-of-line 1)
6794 (setq link (format org-coderef-label-format label))
6795 (setq gc (- 79 (length link)))
6796 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6797 (insert link)
6798 (setq link (concat "(" label ")") desc nil)))
6800 ((eq major-mode 'calendar-mode)
6801 (let ((cd (calendar-cursor-to-date)))
6802 (setq link
6803 (format-time-string
6804 (car org-time-stamp-formats)
6805 (apply 'encode-time
6806 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6807 nil nil nil))))
6808 (org-store-link-props :type "calendar" :date cd)))
6810 ((eq major-mode 'w3-mode)
6811 (setq cpltxt (if (and (buffer-name)
6812 (not (string-match "Untitled" (buffer-name))))
6813 (buffer-name)
6814 (url-view-url t))
6815 link (org-make-link (url-view-url t)))
6816 (org-store-link-props :type "w3" :url (url-view-url t)))
6818 ((eq major-mode 'w3m-mode)
6819 (setq cpltxt (or w3m-current-title w3m-current-url)
6820 link (org-make-link w3m-current-url))
6821 (org-store-link-props :type "w3m" :url (url-view-url t)))
6823 ((setq search (run-hook-with-args-until-success
6824 'org-create-file-search-functions))
6825 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6826 "::" search))
6827 (setq cpltxt (or description link)))
6829 ((eq major-mode 'image-mode)
6830 (setq cpltxt (concat "file:"
6831 (abbreviate-file-name buffer-file-name))
6832 link (org-make-link cpltxt))
6833 (org-store-link-props :type "image" :file buffer-file-name))
6835 ((eq major-mode 'dired-mode)
6836 ;; link to the file in the current line
6837 (setq cpltxt (concat "file:"
6838 (abbreviate-file-name
6839 (expand-file-name
6840 (dired-get-filename nil t))))
6841 link (org-make-link cpltxt)))
6843 ((and buffer-file-name (org-mode-p))
6844 (cond
6845 ((org-in-regexp "<<\\(.*?\\)>>")
6846 (setq cpltxt
6847 (concat "file:"
6848 (abbreviate-file-name buffer-file-name)
6849 "::" (match-string 1))
6850 link (org-make-link cpltxt)))
6851 ((and (featurep 'org-id)
6852 (or (eq org-link-to-org-use-id t)
6853 (and (eq org-link-to-org-use-id 'create-if-interactive)
6854 (interactive-p))
6855 (and org-link-to-org-use-id
6856 (condition-case nil
6857 (org-entry-get nil "ID")
6858 (error nil)))))
6859 ;; We can make a link using the ID.
6860 (setq link (condition-case nil
6861 (prog1 (org-id-store-link)
6862 (setq desc (plist-get org-store-link-plist
6863 :description)))
6864 (error
6865 ;; probably before first headline, link to file only
6866 (concat "file:"
6867 (abbreviate-file-name buffer-file-name))))))
6869 ;; Just link to current headline
6870 (setq cpltxt (concat "file:"
6871 (abbreviate-file-name buffer-file-name)))
6872 ;; Add a context search string
6873 (when (org-xor org-context-in-file-links arg)
6874 (setq txt (cond
6875 ((org-on-heading-p) nil)
6876 ((org-region-active-p)
6877 (buffer-substring (region-beginning) (region-end)))
6878 (t nil)))
6879 (when (or (null txt) (string-match "\\S-" txt))
6880 (setq cpltxt
6881 (concat cpltxt "::"
6882 (condition-case nil
6883 (org-make-org-heading-search-string txt)
6884 (error "")))
6885 desc "NONE")))
6886 (if (string-match "::\\'" cpltxt)
6887 (setq cpltxt (substring cpltxt 0 -2)))
6888 (setq link (org-make-link cpltxt)))))
6890 ((buffer-file-name (buffer-base-buffer))
6891 ;; Just link to this file here.
6892 (setq cpltxt (concat "file:"
6893 (abbreviate-file-name
6894 (buffer-file-name (buffer-base-buffer)))))
6895 ;; Add a context string
6896 (when (org-xor org-context-in-file-links arg)
6897 (setq txt (if (org-region-active-p)
6898 (buffer-substring (region-beginning) (region-end))
6899 (buffer-substring (point-at-bol) (point-at-eol))))
6900 ;; Only use search option if there is some text.
6901 (when (string-match "\\S-" txt)
6902 (setq cpltxt
6903 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6904 desc "NONE")))
6905 (setq link (org-make-link cpltxt)))
6907 ((interactive-p)
6908 (error "Cannot link to a buffer which is not visiting a file"))
6910 (t (setq link nil)))
6912 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6913 (setq link (or link cpltxt)
6914 desc (or desc cpltxt))
6915 (if (equal desc "NONE") (setq desc nil))
6917 (if (and (interactive-p) link)
6918 (progn
6919 (setq org-stored-links
6920 (cons (list link desc) org-stored-links))
6921 (message "Stored: %s" (or desc link)))
6922 (and link (org-make-link-string link desc)))))
6924 (defun org-store-link-props (&rest plist)
6925 "Store link properties, extract names and addresses."
6926 (let (x adr)
6927 (when (setq x (plist-get plist :from))
6928 (setq adr (mail-extract-address-components x))
6929 (setq plist (plist-put plist :fromname (car adr)))
6930 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6931 (when (setq x (plist-get plist :to))
6932 (setq adr (mail-extract-address-components x))
6933 (setq plist (plist-put plist :toname (car adr)))
6934 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6935 (let ((from (plist-get plist :from))
6936 (to (plist-get plist :to)))
6937 (when (and from to org-from-is-user-regexp)
6938 (setq plist
6939 (plist-put plist :fromto
6940 (if (string-match org-from-is-user-regexp from)
6941 (concat "to %t")
6942 (concat "from %f"))))))
6943 (setq org-store-link-plist plist))
6945 (defun org-add-link-props (&rest plist)
6946 "Add these properties to the link property list."
6947 (let (key value)
6948 (while plist
6949 (setq key (pop plist) value (pop plist))
6950 (setq org-store-link-plist
6951 (plist-put org-store-link-plist key value)))))
6953 (defun org-email-link-description (&optional fmt)
6954 "Return the description part of an email link.
6955 This takes information from `org-store-link-plist' and formats it
6956 according to FMT (default from `org-email-link-description-format')."
6957 (setq fmt (or fmt org-email-link-description-format))
6958 (let* ((p org-store-link-plist)
6959 (to (plist-get p :toaddress))
6960 (from (plist-get p :fromaddress))
6961 (table
6962 (list
6963 (cons "%c" (plist-get p :fromto))
6964 (cons "%F" (plist-get p :from))
6965 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6966 (cons "%T" (plist-get p :to))
6967 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6968 (cons "%s" (plist-get p :subject))
6969 (cons "%m" (plist-get p :message-id)))))
6970 (when (string-match "%c" fmt)
6971 ;; Check if the user wrote this message
6972 (if (and org-from-is-user-regexp from to
6973 (save-match-data (string-match org-from-is-user-regexp from)))
6974 (setq fmt (replace-match "to %t" t t fmt))
6975 (setq fmt (replace-match "from %f" t t fmt))))
6976 (org-replace-escapes fmt table)))
6978 (defun org-make-org-heading-search-string (&optional string heading)
6979 "Make search string for STRING or current headline."
6980 (interactive)
6981 (let ((s (or string (org-get-heading))))
6982 (unless (and string (not heading))
6983 ;; We are using a headline, clean up garbage in there.
6984 (if (string-match org-todo-regexp s)
6985 (setq s (replace-match "" t t s)))
6986 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6987 (setq s (replace-match "" t t s)))
6988 (setq s (org-trim s))
6989 (if (string-match (concat "^\\(" org-quote-string "\\|"
6990 org-comment-string "\\)") s)
6991 (setq s (replace-match "" t t s)))
6992 (while (string-match org-ts-regexp s)
6993 (setq s (replace-match "" t t s))))
6994 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6995 (setq s (replace-match " " t t s)))
6996 (or string (setq s (concat "*" s))) ; Add * for headlines
6997 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6999 (defun org-make-link (&rest strings)
7000 "Concatenate STRINGS."
7001 (apply 'concat strings))
7003 (defun org-make-link-string (link &optional description)
7004 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7005 (unless (string-match "\\S-" link)
7006 (error "Empty link"))
7007 (when (stringp description)
7008 ;; Remove brackets from the description, they are fatal.
7009 (while (string-match "\\[" description)
7010 (setq description (replace-match "{" t t description)))
7011 (while (string-match "\\]" description)
7012 (setq description (replace-match "}" t t description))))
7013 (when (equal (org-link-escape link) description)
7014 ;; No description needed, it is identical
7015 (setq description nil))
7016 (when (and (not description)
7017 (not (equal link (org-link-escape link))))
7018 (setq description (org-extract-attributes link)))
7019 (concat "[[" (org-link-escape link) "]"
7020 (if description (concat "[" description "]") "")
7021 "]"))
7023 (defconst org-link-escape-chars
7024 '((?\ . "%20")
7025 (?\[ . "%5B")
7026 (?\] . "%5D")
7027 (?\340 . "%E0") ; `a
7028 (?\342 . "%E2") ; ^a
7029 (?\347 . "%E7") ; ,c
7030 (?\350 . "%E8") ; `e
7031 (?\351 . "%E9") ; 'e
7032 (?\352 . "%EA") ; ^e
7033 (?\356 . "%EE") ; ^i
7034 (?\364 . "%F4") ; ^o
7035 (?\371 . "%F9") ; `u
7036 (?\373 . "%FB") ; ^u
7037 (?\; . "%3B")
7038 (?? . "%3F")
7039 (?= . "%3D")
7040 (?+ . "%2B")
7042 "Association list of escapes for some characters problematic in links.
7043 This is the list that is used for internal purposes.")
7045 (defconst org-link-escape-chars-browser
7046 '((?\ . "%20")) ; 32 for the SPC char
7047 "Association list of escapes for some characters problematic in links.
7048 This is the list that is used before handing over to the browser.")
7050 (defun org-link-escape (text &optional table)
7051 "Escape characters in TEXT that are problematic for links."
7052 (setq table (or table org-link-escape-chars))
7053 (when text
7054 (let ((re (mapconcat (lambda (x) (regexp-quote
7055 (char-to-string (car x))))
7056 table "\\|")))
7057 (while (string-match re text)
7058 (setq text
7059 (replace-match
7060 (cdr (assoc (string-to-char (match-string 0 text))
7061 table))
7062 t t text)))
7063 text)))
7065 (defun org-link-unescape (text &optional table)
7066 "Reverse the action of `org-link-escape'."
7067 (setq table (or table org-link-escape-chars))
7068 (when text
7069 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7070 table "\\|")))
7071 (while (string-match re text)
7072 (setq text
7073 (replace-match
7074 (char-to-string (car (rassoc (match-string 0 text) table)))
7075 t t text)))
7076 text)))
7078 (defun org-xor (a b)
7079 "Exclusive or."
7080 (if a (not b) b))
7082 (defun org-fixup-message-id-for-http (s)
7083 "Replace special characters in a message id, so it can be used in an http query."
7084 (while (string-match "<" s)
7085 (setq s (replace-match "%3C" t t s)))
7086 (while (string-match ">" s)
7087 (setq s (replace-match "%3E" t t s)))
7088 (while (string-match "@" s)
7089 (setq s (replace-match "%40" t t s)))
7092 ;;;###autoload
7093 (defun org-insert-link-global ()
7094 "Insert a link like Org-mode does.
7095 This command can be called in any mode to insert a link in Org-mode syntax."
7096 (interactive)
7097 (org-load-modules-maybe)
7098 (org-run-like-in-org-mode 'org-insert-link))
7100 (defun org-insert-link (&optional complete-file link-location)
7101 "Insert a link. At the prompt, enter the link.
7103 Completion can be used to insert any of the link protocol prefixes like
7104 http or ftp in use.
7106 The history can be used to select a link previously stored with
7107 `org-store-link'. When the empty string is entered (i.e. if you just
7108 press RET at the prompt), the link defaults to the most recently
7109 stored link. As SPC triggers completion in the minibuffer, you need to
7110 use M-SPC or C-q SPC to force the insertion of a space character.
7112 You will also be prompted for a description, and if one is given, it will
7113 be displayed in the buffer instead of the link.
7115 If there is already a link at point, this command will allow you to edit link
7116 and description parts.
7118 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7119 be selected using completion. The path to the file will be relative to the
7120 current directory if the file is in the current directory or a subdirectory.
7121 Otherwise, the link will be the absolute path as completed in the minibuffer
7122 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7123 option `org-link-file-path-type'.
7125 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7126 the current directory or below.
7128 With three \\[universal-argument] prefixes, negate the meaning of
7129 `org-keep-stored-link-after-insertion'.
7131 If `org-make-link-description-function' is non-nil, this function will be
7132 called with the link target, and the result will be the default
7133 link description.
7135 If the LINK-LOCATION parameter is non-nil, this value will be
7136 used as the link location instead of reading one interactively."
7137 (interactive "P")
7138 (let* ((wcf (current-window-configuration))
7139 (region (if (org-region-active-p)
7140 (buffer-substring (region-beginning) (region-end))))
7141 (remove (and region (list (region-beginning) (region-end))))
7142 (desc region)
7143 tmphist ; byte-compile incorrectly complains about this
7144 (link link-location)
7145 entry file)
7146 (cond
7147 (link-location) ; specified by arg, just use it.
7148 ((org-in-regexp org-bracket-link-regexp 1)
7149 ;; We do have a link at point, and we are going to edit it.
7150 (setq remove (list (match-beginning 0) (match-end 0)))
7151 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7152 (setq link (read-string "Link: "
7153 (org-link-unescape
7154 (org-match-string-no-properties 1)))))
7155 ((or (org-in-regexp org-angle-link-re)
7156 (org-in-regexp org-plain-link-re))
7157 ;; Convert to bracket link
7158 (setq remove (list (match-beginning 0) (match-end 0))
7159 link (read-string "Link: "
7160 (org-remove-angle-brackets (match-string 0)))))
7161 ((member complete-file '((4) (16)))
7162 ;; Completing read for file names.
7163 (setq file (read-file-name "File: "))
7164 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7165 (pwd1 (file-name-as-directory (abbreviate-file-name
7166 (expand-file-name ".")))))
7167 (cond
7168 ((equal complete-file '(16))
7169 (setq link (org-make-link
7170 "file:"
7171 (abbreviate-file-name (expand-file-name file)))))
7172 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7173 (setq link (org-make-link "file:" (match-string 1 file))))
7174 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7175 (expand-file-name file))
7176 (setq link (org-make-link
7177 "file:" (match-string 1 (expand-file-name file)))))
7178 (t (setq link (org-make-link "file:" file))))))
7180 ;; Read link, with completion for stored links.
7181 (with-output-to-temp-buffer "*Org Links*"
7182 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7183 (when org-stored-links
7184 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7185 (princ (mapconcat
7186 (lambda (x)
7187 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7188 (reverse org-stored-links) "\n"))))
7189 (let ((cw (selected-window)))
7190 (select-window (get-buffer-window "*Org Links*"))
7191 (setq truncate-lines t)
7192 (org-fit-window-to-buffer)
7193 (select-window cw))
7194 ;; Fake a link history, containing the stored links.
7195 (setq tmphist (append (mapcar 'car org-stored-links)
7196 org-insert-link-history))
7197 (unwind-protect
7198 (setq link
7199 (let ((org-completion-use-ido nil))
7200 (org-completing-read
7201 "Link: "
7202 (append
7203 (mapcar (lambda (x) (list (concat (car x) ":")))
7204 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7205 (mapcar (lambda (x) (list (concat x ":")))
7206 org-link-types))
7207 nil nil nil
7208 'tmphist
7209 (or (car (car org-stored-links))))))
7210 (set-window-configuration wcf)
7211 (kill-buffer "*Org Links*"))
7212 (setq entry (assoc link org-stored-links))
7213 (or entry (push link org-insert-link-history))
7214 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7215 (not org-keep-stored-link-after-insertion))
7216 (setq org-stored-links (delq (assoc link org-stored-links)
7217 org-stored-links)))
7218 (setq desc (or desc (nth 1 entry)))))
7220 (if (string-match org-plain-link-re link)
7221 ;; URL-like link, normalize the use of angular brackets.
7222 (setq link (org-make-link (org-remove-angle-brackets link))))
7224 ;; Check if we are linking to the current file with a search option
7225 ;; If yes, simplify the link by using only the search option.
7226 (when (and buffer-file-name
7227 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7228 (let* ((path (match-string 1 link))
7229 (case-fold-search nil)
7230 (search (match-string 2 link)))
7231 (save-match-data
7232 (if (equal (file-truename buffer-file-name) (file-truename path))
7233 ;; We are linking to this same file, with a search option
7234 (setq link search)))))
7236 ;; Check if we can/should use a relative path. If yes, simplify the link
7237 (when (string-match "^file:\\(.*\\)" link)
7238 (let* ((path (match-string 1 link))
7239 (origpath path)
7240 (case-fold-search nil))
7241 (cond
7242 ((or (eq org-link-file-path-type 'absolute)
7243 (equal complete-file '(16)))
7244 (setq path (abbreviate-file-name (expand-file-name path))))
7245 ((eq org-link-file-path-type 'noabbrev)
7246 (setq path (expand-file-name path)))
7247 ((eq org-link-file-path-type 'relative)
7248 (setq path (file-relative-name path)))
7250 (save-match-data
7251 (if (string-match (concat "^" (regexp-quote
7252 (file-name-as-directory
7253 (expand-file-name "."))))
7254 (expand-file-name path))
7255 ;; We are linking a file with relative path name.
7256 (setq path (substring (expand-file-name path)
7257 (match-end 0)))
7258 (setq path (abbreviate-file-name (expand-file-name path)))))))
7259 (setq link (concat "file:" path))
7260 (if (equal desc origpath)
7261 (setq desc path))))
7263 (if org-make-link-description-function
7264 (setq desc (funcall org-make-link-description-function link desc)))
7266 (setq desc (read-string "Description: " desc))
7267 (unless (string-match "\\S-" desc) (setq desc nil))
7268 (if remove (apply 'delete-region remove))
7269 (insert (org-make-link-string link desc))))
7271 (defun org-completing-read (&rest args)
7272 "Completing-read with SPACE being a normal character."
7273 (let ((minibuffer-local-completion-map
7274 (copy-keymap minibuffer-local-completion-map)))
7275 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7276 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7277 (apply 'org-ido-completing-read args)))
7279 (defun org-completing-read-no-ido (&rest args)
7280 (let (org-completion-use-ido)
7281 (apply 'org-completing-read args)))
7283 (defun org-ido-completing-read (&rest args)
7284 "Completing-read using `ido-mode' speedups if available"
7285 (if (and org-completion-use-ido
7286 (fboundp 'ido-completing-read)
7287 (boundp 'ido-mode) ido-mode
7288 (listp (second args)))
7289 (let ((ido-enter-matching-directory nil))
7290 (apply 'ido-completing-read (concat (car args))
7291 (mapcar (lambda (x) (car x)) (nth 1 args))
7292 (cddr args)))
7293 (apply 'completing-read args)))
7296 (defun org-extract-attributes (s)
7297 "Extract the attributes cookie from a string and set as text property."
7298 (let (a attr (start 0) key value)
7299 (save-match-data
7300 (when (string-match "{{\\([^}]+\\)}}$" s)
7301 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7302 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7303 (setq key (match-string 1 a) value (match-string 2 a)
7304 start (match-end 0)
7305 attr (plist-put attr (intern key) value))))
7306 (org-add-props s nil 'org-attr attr))
7309 (defun org-attributes-to-string (plist)
7310 "Format a property list into an HTML attribute list."
7311 (let ((s "") key value)
7312 (while plist
7313 (setq key (pop plist) value (pop plist))
7314 (and value
7315 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7318 ;;; Opening/following a link
7320 (defvar org-link-search-failed nil)
7322 (defun org-next-link ()
7323 "Move forward to the next link.
7324 If the link is in hidden text, expose it."
7325 (interactive)
7326 (when (and org-link-search-failed (eq this-command last-command))
7327 (goto-char (point-min))
7328 (message "Link search wrapped back to beginning of buffer"))
7329 (setq org-link-search-failed nil)
7330 (let* ((pos (point))
7331 (ct (org-context))
7332 (a (assoc :link ct)))
7333 (if a (goto-char (nth 2 a)))
7334 (if (re-search-forward org-any-link-re nil t)
7335 (progn
7336 (goto-char (match-beginning 0))
7337 (if (org-invisible-p) (org-show-context)))
7338 (goto-char pos)
7339 (setq org-link-search-failed t)
7340 (error "No further link found"))))
7342 (defun org-previous-link ()
7343 "Move backward to the previous link.
7344 If the link is in hidden text, expose it."
7345 (interactive)
7346 (when (and org-link-search-failed (eq this-command last-command))
7347 (goto-char (point-max))
7348 (message "Link search wrapped back to end of buffer"))
7349 (setq org-link-search-failed nil)
7350 (let* ((pos (point))
7351 (ct (org-context))
7352 (a (assoc :link ct)))
7353 (if a (goto-char (nth 1 a)))
7354 (if (re-search-backward org-any-link-re nil t)
7355 (progn
7356 (goto-char (match-beginning 0))
7357 (if (org-invisible-p) (org-show-context)))
7358 (goto-char pos)
7359 (setq org-link-search-failed t)
7360 (error "No further link found"))))
7362 (defun org-translate-link (s)
7363 "Translate a link string if a translation function has been defined."
7364 (if (and org-link-translation-function
7365 (fboundp org-link-translation-function)
7366 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7367 (progn
7368 (setq s (funcall org-link-translation-function
7369 (match-string 1) (match-string 2)))
7370 (concat (car s) ":" (cdr s)))
7373 (defun org-translate-link-from-planner (type path)
7374 "Translate a link from Emacs Planner syntax so that Org can follow it.
7375 This is still an experimental function, your mileage may vary."
7376 (cond
7377 ((member type '("http" "https" "news" "ftp"))
7378 ;; standard Internet links are the same.
7379 nil)
7380 ((and (equal type "irc") (string-match "^//" path))
7381 ;; Planner has two / at the beginning of an irc link, we have 1.
7382 ;; We should have zero, actually....
7383 (setq path (substring path 1)))
7384 ((and (equal type "lisp") (string-match "^/" path))
7385 ;; Planner has a slash, we do not.
7386 (setq type "elisp" path (substring path 1)))
7387 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7388 ;; A typical message link. Planner has the id after the fina slash,
7389 ;; we separate it with a hash mark
7390 (setq path (concat (match-string 1 path) "#"
7391 (org-remove-angle-brackets (match-string 2 path)))))
7393 (cons type path))
7395 (defun org-find-file-at-mouse (ev)
7396 "Open file link or URL at mouse."
7397 (interactive "e")
7398 (mouse-set-point ev)
7399 (org-open-at-point 'in-emacs))
7401 (defun org-open-at-mouse (ev)
7402 "Open file link or URL at mouse."
7403 (interactive "e")
7404 (mouse-set-point ev)
7405 (if (eq major-mode 'org-agenda-mode)
7406 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7407 (org-open-at-point))
7409 (defvar org-window-config-before-follow-link nil
7410 "The window configuration before following a link.
7411 This is saved in case the need arises to restore it.")
7413 (defvar org-open-link-marker (make-marker)
7414 "Marker pointing to the location where `org-open-at-point; was called.")
7416 ;;;###autoload
7417 (defun org-open-at-point-global ()
7418 "Follow a link like Org-mode does.
7419 This command can be called in any mode to follow a link that has
7420 Org-mode syntax."
7421 (interactive)
7422 (org-run-like-in-org-mode 'org-open-at-point))
7424 ;;;###autoload
7425 (defun org-open-link-from-string (s &optional arg)
7426 "Open a link in the string S, as if it was in Org-mode."
7427 (interactive "sLink: \nP")
7428 (with-temp-buffer
7429 (let ((org-inhibit-startup t))
7430 (org-mode)
7431 (insert s)
7432 (goto-char (point-min))
7433 (org-open-at-point arg))))
7435 (defun org-open-at-point (&optional in-emacs)
7436 "Open link at or after point.
7437 If there is no link at point, this function will search forward up to
7438 the end of the current subtree.
7439 Normally, files will be opened by an appropriate application. If the
7440 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7441 With a double prefix argument, try to open outside of Emacs, in the
7442 application the system uses for this file type."
7443 (interactive "P")
7444 (org-load-modules-maybe)
7445 (move-marker org-open-link-marker (point))
7446 (setq org-window-config-before-follow-link (current-window-configuration))
7447 (org-remove-occur-highlights nil nil t)
7448 (cond
7449 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7450 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7451 (org-footnote-action))
7453 (let (type path link line search (pos (point)))
7454 (catch 'match
7455 (save-excursion
7456 (skip-chars-forward "^]\n\r")
7457 (when (org-in-regexp org-bracket-link-regexp)
7458 (setq link (org-extract-attributes
7459 (org-link-unescape (org-match-string-no-properties 1))))
7460 (while (string-match " *\n *" link)
7461 (setq link (replace-match " " t t link)))
7462 (setq link (org-link-expand-abbrev link))
7463 (cond
7464 ((or (file-name-absolute-p link)
7465 (string-match "^\\.\\.?/" link))
7466 (setq type "file" path link))
7467 ((string-match org-link-re-with-space3 link)
7468 (setq type (match-string 1 link) path (match-string 2 link)))
7469 (t (setq type "thisfile" path link)))
7470 (throw 'match t)))
7472 (when (get-text-property (point) 'org-linked-text)
7473 (setq type "thisfile"
7474 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7475 (1+ (point)) (point))
7476 path (buffer-substring
7477 (previous-single-property-change pos 'org-linked-text)
7478 (next-single-property-change pos 'org-linked-text)))
7479 (throw 'match t))
7481 (save-excursion
7482 (when (or (org-in-regexp org-angle-link-re)
7483 (org-in-regexp org-plain-link-re))
7484 (setq type (match-string 1) path (match-string 2))
7485 (throw 'match t)))
7486 (save-excursion
7487 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7488 (setq type "tags"
7489 path (match-string 1))
7490 (while (string-match ":" path)
7491 (setq path (replace-match "+" t t path)))
7492 (throw 'match t)))
7493 (when (org-in-regexp "<\\([^><\n]+\\)>")
7494 (setq type "tree-match"
7495 path (match-string 1))
7496 (throw 'match t)))
7497 (unless path
7498 (error "No link found"))
7499 ;; Remove any trailing spaces in path
7500 (if (string-match " +\\'" path)
7501 (setq path (replace-match "" t t path)))
7502 (if (and org-link-translation-function
7503 (fboundp org-link-translation-function))
7504 ;; Check if we need to translate the link
7505 (let ((tmp (funcall org-link-translation-function type path)))
7506 (setq type (car tmp) path (cdr tmp))))
7508 (cond
7510 ((assoc type org-link-protocols)
7511 (funcall (nth 1 (assoc type org-link-protocols)) path))
7513 ((equal type "mailto")
7514 (let ((cmd (car org-link-mailto-program))
7515 (args (cdr org-link-mailto-program)) args1
7516 (address path) (subject "") a)
7517 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7518 (setq address (match-string 1 path)
7519 subject (org-link-escape (match-string 2 path))))
7520 (while args
7521 (cond
7522 ((not (stringp (car args))) (push (pop args) args1))
7523 (t (setq a (pop args))
7524 (if (string-match "%a" a)
7525 (setq a (replace-match address t t a)))
7526 (if (string-match "%s" a)
7527 (setq a (replace-match subject t t a)))
7528 (push a args1))))
7529 (apply cmd (nreverse args1))))
7531 ((member type '("http" "https" "ftp" "news"))
7532 (browse-url (concat type ":" (org-link-escape
7533 path org-link-escape-chars-browser))))
7535 ((member type '("message"))
7536 (browse-url (concat type ":" path)))
7538 ((string= type "tags")
7539 (org-tags-view in-emacs path))
7540 ((string= type "thisfile")
7541 (if in-emacs
7542 (switch-to-buffer-other-window
7543 (org-get-buffer-for-internal-link (current-buffer)))
7544 (org-mark-ring-push))
7545 (let ((cmd `(org-link-search
7546 ,path
7547 ,(cond ((equal in-emacs '(4)) 'occur)
7548 ((equal in-emacs '(16)) 'org-occur)
7549 (t nil))
7550 ,pos)))
7551 (condition-case nil (eval cmd)
7552 (error (progn (widen) (eval cmd))))))
7554 ((string= type "tree-match")
7555 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7557 ((string= type "file")
7558 (if (string-match "::\\([0-9]+\\)\\'" path)
7559 (setq line (string-to-number (match-string 1 path))
7560 path (substring path 0 (match-beginning 0)))
7561 (if (string-match "::\\(.+\\)\\'" path)
7562 (setq search (match-string 1 path)
7563 path (substring path 0 (match-beginning 0)))))
7564 (if (string-match "[*?{]" (file-name-nondirectory path))
7565 (dired path)
7566 (org-open-file path in-emacs line search)))
7568 ((string= type "news")
7569 (require 'org-gnus)
7570 (org-gnus-follow-link path))
7572 ((string= type "shell")
7573 (let ((cmd path))
7574 (if (or (not org-confirm-shell-link-function)
7575 (funcall org-confirm-shell-link-function
7576 (format "Execute \"%s\" in shell? "
7577 (org-add-props cmd nil
7578 'face 'org-warning))))
7579 (progn
7580 (message "Executing %s" cmd)
7581 (shell-command cmd))
7582 (error "Abort"))))
7584 ((string= type "elisp")
7585 (let ((cmd path))
7586 (if (or (not org-confirm-elisp-link-function)
7587 (funcall org-confirm-elisp-link-function
7588 (format "Execute \"%s\" as elisp? "
7589 (org-add-props cmd nil
7590 'face 'org-warning))))
7591 (message "%s => %s" cmd
7592 (if (equal (string-to-char cmd) ?\()
7593 (eval (read cmd))
7594 (call-interactively (read cmd))))
7595 (error "Abort"))))
7598 (browse-url-at-point))))))
7599 (move-marker org-open-link-marker nil)
7600 (run-hook-with-args 'org-follow-link-hook))
7602 ;;;; Time estimates
7604 (defun org-get-effort (&optional pom)
7605 "Get the effort estimate for the current entry."
7606 (org-entry-get pom org-effort-property))
7608 ;;; File search
7610 (defvar org-create-file-search-functions nil
7611 "List of functions to construct the right search string for a file link.
7612 These functions are called in turn with point at the location to
7613 which the link should point.
7615 A function in the hook should first test if it would like to
7616 handle this file type, for example by checking the major-mode or
7617 the file extension. If it decides not to handle this file, it
7618 should just return nil to give other functions a chance. If it
7619 does handle the file, it must return the search string to be used
7620 when following the link. The search string will be part of the
7621 file link, given after a double colon, and `org-open-at-point'
7622 will automatically search for it. If special measures must be
7623 taken to make the search successful, another function should be
7624 added to the companion hook `org-execute-file-search-functions',
7625 which see.
7627 A function in this hook may also use `setq' to set the variable
7628 `description' to provide a suggestion for the descriptive text to
7629 be used for this link when it gets inserted into an Org-mode
7630 buffer with \\[org-insert-link].")
7632 (defvar org-execute-file-search-functions nil
7633 "List of functions to execute a file search triggered by a link.
7635 Functions added to this hook must accept a single argument, the
7636 search string that was part of the file link, the part after the
7637 double colon. The function must first check if it would like to
7638 handle this search, for example by checking the major-mode or the
7639 file extension. If it decides not to handle this search, it
7640 should just return nil to give other functions a chance. If it
7641 does handle the search, it must return a non-nil value to keep
7642 other functions from trying.
7644 Each function can access the current prefix argument through the
7645 variable `current-prefix-argument'. Note that a single prefix is
7646 used to force opening a link in Emacs, so it may be good to only
7647 use a numeric or double prefix to guide the search function.
7649 In case this is needed, a function in this hook can also restore
7650 the window configuration before `org-open-at-point' was called using:
7652 (set-window-configuration org-window-config-before-follow-link)")
7654 (defun org-link-search (s &optional type avoid-pos)
7655 "Search for a link search option.
7656 If S is surrounded by forward slashes, it is interpreted as a
7657 regular expression. In org-mode files, this will create an `org-occur'
7658 sparse tree. In ordinary files, `occur' will be used to list matches.
7659 If the current buffer is in `dired-mode', grep will be used to search
7660 in all files. If AVOID-POS is given, ignore matches near that position."
7661 (let ((case-fold-search t)
7662 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7663 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7664 (append '(("") (" ") ("\t") ("\n"))
7665 org-emphasis-alist)
7666 "\\|") "\\)"))
7667 (pos (point))
7668 (pre nil) (post nil)
7669 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7670 (cond
7671 ;; First check if there are any special
7672 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7673 ;; Now try the builtin stuff
7674 ((save-excursion
7675 (goto-char (point-min))
7676 (and
7677 (re-search-forward
7678 (concat "<<" (regexp-quote s0) ">>") nil t)
7679 (setq type 'dedicated
7680 pos (match-beginning 0))))
7681 ;; There is an exact target for this
7682 (goto-char pos))
7683 ((and (string-match "^(\\(.*\\))$" s0)
7684 (save-excursion
7685 (goto-char (point-min))
7686 (and
7687 (re-search-forward
7688 (concat "[^[]" (regexp-quote
7689 (format org-coderef-label-format
7690 (match-string 1 s0))))
7691 nil t)
7692 (setq type 'dedicated
7693 pos (1+ (match-beginning 0))))))
7694 ;; There is a coderef target for this
7695 (goto-char pos))
7696 ((string-match "^/\\(.*\\)/$" s)
7697 ;; A regular expression
7698 (cond
7699 ((org-mode-p)
7700 (org-occur (match-string 1 s)))
7701 ;;((eq major-mode 'dired-mode)
7702 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7703 (t (org-do-occur (match-string 1 s)))))
7705 ;; A normal search strings
7706 (when (equal (string-to-char s) ?*)
7707 ;; Anchor on headlines, post may include tags.
7708 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7709 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7710 s (substring s 1)))
7711 (remove-text-properties
7712 0 (length s)
7713 '(face nil mouse-face nil keymap nil fontified nil) s)
7714 ;; Make a series of regular expressions to find a match
7715 (setq words (org-split-string s "[ \n\r\t]+")
7717 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7718 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7719 "\\)" markers)
7720 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7721 re2a (concat "[ \t\r\n]" re2a_)
7722 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7723 re4 (concat "[^a-zA-Z_]" re4_)
7725 re1 (concat pre re2 post)
7726 re3 (concat pre (if pre re4_ re4) post)
7727 re5 (concat pre ".*" re4)
7728 re2 (concat pre re2)
7729 re2a (concat pre (if pre re2a_ re2a))
7730 re4 (concat pre (if pre re4_ re4))
7731 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7732 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7733 re5 "\\)"
7735 (cond
7736 ((eq type 'org-occur) (org-occur reall))
7737 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7738 (t (goto-char (point-min))
7739 (setq type 'fuzzy)
7740 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7741 (org-search-not-self 1 re1 nil t)
7742 (org-search-not-self 1 re2 nil t)
7743 (org-search-not-self 1 re2a nil t)
7744 (org-search-not-self 1 re3 nil t)
7745 (org-search-not-self 1 re4 nil t)
7746 (org-search-not-self 1 re5 nil t)
7748 (goto-char (match-beginning 1))
7749 (goto-char pos)
7750 (error "No match")))))
7752 ;; Normal string-search
7753 (goto-char (point-min))
7754 (if (search-forward s nil t)
7755 (goto-char (match-beginning 0))
7756 (error "No match"))))
7757 (and (org-mode-p) (org-show-context 'link-search))
7758 type))
7760 (defun org-search-not-self (group &rest args)
7761 "Execute `re-search-forward', but only accept matches that do not
7762 enclose the position of `org-open-link-marker'."
7763 (let ((m org-open-link-marker))
7764 (catch 'exit
7765 (while (apply 're-search-forward args)
7766 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7767 (goto-char (match-end group))
7768 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7769 (> (match-beginning 0) (marker-position m))
7770 (< (match-end 0) (marker-position m)))
7771 (save-match-data
7772 (or (not (org-in-regexp
7773 org-bracket-link-analytic-regexp 1))
7774 (not (match-end 4)) ; no description
7775 (and (<= (match-beginning 4) (point))
7776 (>= (match-end 4) (point))))))
7777 (throw 'exit (point))))))))
7779 (defun org-get-buffer-for-internal-link (buffer)
7780 "Return a buffer to be used for displaying the link target of internal links."
7781 (cond
7782 ((not org-display-internal-link-with-indirect-buffer)
7783 buffer)
7784 ((string-match "(Clone)$" (buffer-name buffer))
7785 (message "Buffer is already a clone, not making another one")
7786 ;; we also do not modify visibility in this case
7787 buffer)
7788 (t ; make a new indirect buffer for displaying the link
7789 (let* ((bn (buffer-name buffer))
7790 (ibn (concat bn "(Clone)"))
7791 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7792 (with-current-buffer ib (org-overview))
7793 ib))))
7795 (defun org-do-occur (regexp &optional cleanup)
7796 "Call the Emacs command `occur'.
7797 If CLEANUP is non-nil, remove the printout of the regular expression
7798 in the *Occur* buffer. This is useful if the regex is long and not useful
7799 to read."
7800 (occur regexp)
7801 (when cleanup
7802 (let ((cwin (selected-window)) win beg end)
7803 (when (setq win (get-buffer-window "*Occur*"))
7804 (select-window win))
7805 (goto-char (point-min))
7806 (when (re-search-forward "match[a-z]+" nil t)
7807 (setq beg (match-end 0))
7808 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7809 (setq end (1- (match-beginning 0)))))
7810 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7811 (goto-char (point-min))
7812 (select-window cwin))))
7814 ;;; The mark ring for links jumps
7816 (defvar org-mark-ring nil
7817 "Mark ring for positions before jumps in Org-mode.")
7818 (defvar org-mark-ring-last-goto nil
7819 "Last position in the mark ring used to go back.")
7820 ;; Fill and close the ring
7821 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7822 (loop for i from 1 to org-mark-ring-length do
7823 (push (make-marker) org-mark-ring))
7824 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7825 org-mark-ring)
7827 (defun org-mark-ring-push (&optional pos buffer)
7828 "Put the current position or POS into the mark ring and rotate it."
7829 (interactive)
7830 (setq pos (or pos (point)))
7831 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7832 (move-marker (car org-mark-ring)
7833 (or pos (point))
7834 (or buffer (current-buffer)))
7835 (message "%s"
7836 (substitute-command-keys
7837 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7839 (defun org-mark-ring-goto (&optional n)
7840 "Jump to the previous position in the mark ring.
7841 With prefix arg N, jump back that many stored positions. When
7842 called several times in succession, walk through the entire ring.
7843 Org-mode commands jumping to a different position in the current file,
7844 or to another Org-mode file, automatically push the old position
7845 onto the ring."
7846 (interactive "p")
7847 (let (p m)
7848 (if (eq last-command this-command)
7849 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7850 (setq p org-mark-ring))
7851 (setq org-mark-ring-last-goto p)
7852 (setq m (car p))
7853 (switch-to-buffer (marker-buffer m))
7854 (goto-char m)
7855 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7857 (defun org-remove-angle-brackets (s)
7858 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7859 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7861 (defun org-add-angle-brackets (s)
7862 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7863 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7865 (defun org-remove-double-quotes (s)
7866 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7867 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7870 ;;; Following specific links
7872 (defun org-follow-timestamp-link ()
7873 (cond
7874 ((org-at-date-range-p t)
7875 (let ((org-agenda-start-on-weekday)
7876 (t1 (match-string 1))
7877 (t2 (match-string 2)))
7878 (setq t1 (time-to-days (org-time-string-to-time t1))
7879 t2 (time-to-days (org-time-string-to-time t2)))
7880 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7881 ((org-at-timestamp-p t)
7882 (org-agenda-list nil (time-to-days (org-time-string-to-time
7883 (substring (match-string 1) 0 10)))
7885 (t (error "This should not happen"))))
7888 ;;; Following file links
7889 (defvar org-wait nil)
7890 (defun org-open-file (path &optional in-emacs line search)
7891 "Open the file at PATH.
7892 First, this expands any special file name abbreviations. Then the
7893 configuration variable `org-file-apps' is checked if it contains an
7894 entry for this file type, and if yes, the corresponding command is launched.
7896 If no application is found, Emacs simply visits the file.
7898 With optional prefix argument IN-EMACS, Emacs will visit the file.
7899 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7900 and o use an external application to visit the file.
7902 Optional LINE specifies a line to go to, optional SEARCH a string to
7903 search for. If LINE or SEARCH is given, the file will always be
7904 opened in Emacs.
7905 If the file does not exist, an error is thrown."
7906 (setq in-emacs (or in-emacs line search))
7907 (let* ((file (if (equal path "")
7908 buffer-file-name
7909 (substitute-in-file-name (expand-file-name path))))
7910 (apps (append org-file-apps (org-default-apps)))
7911 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7912 (dirp (if remp nil (file-directory-p file)))
7913 (file (if (and dirp org-open-directory-means-index-dot-org)
7914 (concat (file-name-as-directory file) "index.org")
7915 file))
7916 (a-m-a-p (assq 'auto-mode apps))
7917 (dfile (downcase file))
7918 (old-buffer (current-buffer))
7919 (old-pos (point))
7920 (old-mode major-mode)
7921 ext cmd)
7922 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7923 (setq ext (match-string 1 dfile))
7924 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7925 (setq ext (match-string 1 dfile))))
7926 (cond
7927 ((equal in-emacs '(16))
7928 (setq cmd (cdr (assoc 'system apps))))
7929 (in-emacs (setq cmd 'emacs))
7931 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7932 (and dirp (cdr (assoc 'directory apps)))
7933 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7934 'string-match)
7935 (cdr (assoc ext apps))
7936 (cdr (assoc t apps))))))
7937 (when (eq cmd 'system)
7938 (setq cmd (cdr (assoc 'system apps))))
7939 (when (eq cmd 'default)
7940 (setq cmd (cdr (assoc t apps))))
7941 (when (eq cmd 'mailcap)
7942 (require 'mailcap)
7943 (mailcap-parse-mailcaps)
7944 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7945 (command (mailcap-mime-info mime-type)))
7946 (if (stringp command)
7947 (setq cmd command)
7948 (setq cmd 'emacs))))
7949 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7950 (not (file-exists-p file))
7951 (not org-open-non-existing-files))
7952 (error "No such file: %s" file))
7953 (cond
7954 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7955 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7956 (while (string-match "['\"]%s['\"]" cmd)
7957 (setq cmd (replace-match "%s" t t cmd)))
7958 (while (string-match "%s" cmd)
7959 (setq cmd (replace-match
7960 (save-match-data
7961 (shell-quote-argument
7962 (convert-standard-filename file)))
7963 t t cmd)))
7964 (save-window-excursion
7965 (start-process-shell-command cmd nil cmd)
7966 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7968 ((or (stringp cmd)
7969 (eq cmd 'emacs))
7970 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7971 (widen)
7972 (if line (goto-line line)
7973 (if search (org-link-search search))))
7974 ((consp cmd)
7975 (let ((file (convert-standard-filename file)))
7976 (eval cmd)))
7977 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7978 (and (org-mode-p) (eq old-mode 'org-mode)
7979 (or (not (equal old-buffer (current-buffer)))
7980 (not (equal old-pos (point))))
7981 (org-mark-ring-push old-pos old-buffer))))
7983 (defun org-default-apps ()
7984 "Return the default applications for this operating system."
7985 (cond
7986 ((eq system-type 'darwin)
7987 org-file-apps-defaults-macosx)
7988 ((eq system-type 'windows-nt)
7989 org-file-apps-defaults-windowsnt)
7990 (t org-file-apps-defaults-gnu)))
7992 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7993 "Convert extensions to regular expressions in the cars of LIST.
7994 Also, weed out any non-string entries, because the return value is used
7995 only for regexp matching.
7996 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7997 point to the symbol `emacs', indicating that the file should
7998 be opened in Emacs."
7999 (append
8000 (delq nil
8001 (mapcar (lambda (x)
8002 (if (not (stringp (car x)))
8004 (if (string-match "\\W" (car x))
8006 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8007 list))
8008 (if add-auto-mode
8009 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8011 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8012 (defun org-file-remote-p (file)
8013 "Test whether FILE specifies a location on a remote system.
8014 Return non-nil if the location is indeed remote.
8016 For example, the filename \"/user@host:/foo\" specifies a location
8017 on the system \"/user@host:\"."
8018 (cond ((fboundp 'file-remote-p)
8019 (file-remote-p file))
8020 ((fboundp 'tramp-handle-file-remote-p)
8021 (tramp-handle-file-remote-p file))
8022 ((and (boundp 'ange-ftp-name-format)
8023 (string-match (car ange-ftp-name-format) file))
8025 (t nil)))
8028 ;;;; Refiling
8030 (defun org-get-org-file ()
8031 "Read a filename, with default directory `org-directory'."
8032 (let ((default (or org-default-notes-file remember-data-file)))
8033 (read-file-name (format "File name [%s]: " default)
8034 (file-name-as-directory org-directory)
8035 default)))
8037 (defun org-notes-order-reversed-p ()
8038 "Check if the current file should receive notes in reversed order."
8039 (cond
8040 ((not org-reverse-note-order) nil)
8041 ((eq t org-reverse-note-order) t)
8042 ((not (listp org-reverse-note-order)) nil)
8043 (t (catch 'exit
8044 (let ((all org-reverse-note-order)
8045 entry)
8046 (while (setq entry (pop all))
8047 (if (string-match (car entry) buffer-file-name)
8048 (throw 'exit (cdr entry))))
8049 nil)))))
8051 (defvar org-refile-target-table nil
8052 "The list of refile targets, created by `org-refile'.")
8054 (defvar org-agenda-new-buffers nil
8055 "Buffers created to visit agenda files.")
8057 (defun org-get-refile-targets (&optional default-buffer)
8058 "Produce a table with refile targets."
8059 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8060 targets txt re files f desc descre fast-path-p level)
8061 (message "Getting targets...")
8062 (with-current-buffer (or default-buffer (current-buffer))
8063 (while (setq entry (pop entries))
8064 (setq files (car entry) desc (cdr entry))
8065 (setq fast-path-p nil)
8066 (cond
8067 ((null files) (setq files (list (current-buffer))))
8068 ((eq files 'org-agenda-files)
8069 (setq files (org-agenda-files 'unrestricted)))
8070 ((and (symbolp files) (fboundp files))
8071 (setq files (funcall files)))
8072 ((and (symbolp files) (boundp files))
8073 (setq files (symbol-value files))))
8074 (if (stringp files) (setq files (list files)))
8075 (cond
8076 ((eq (car desc) :tag)
8077 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8078 ((eq (car desc) :todo)
8079 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8080 ((eq (car desc) :regexp)
8081 (setq descre (cdr desc)))
8082 ((eq (car desc) :level)
8083 (setq descre (concat "^\\*\\{" (number-to-string
8084 (if org-odd-levels-only
8085 (1- (* 2 (cdr desc)))
8086 (cdr desc)))
8087 "\\}[ \t]")))
8088 ((eq (car desc) :maxlevel)
8089 (setq fast-path-p t)
8090 (setq descre (concat "^\\*\\{1," (number-to-string
8091 (if org-odd-levels-only
8092 (1- (* 2 (cdr desc)))
8093 (cdr desc)))
8094 "\\}[ \t]")))
8095 (t (error "Bad refiling target description %s" desc)))
8096 (while (setq f (pop files))
8097 (save-excursion
8098 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8099 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8100 (setq f (expand-file-name f))
8101 (save-excursion
8102 (save-restriction
8103 (widen)
8104 (goto-char (point-min))
8105 (while (re-search-forward descre nil t)
8106 (goto-char (point-at-bol))
8107 (when (looking-at org-complex-heading-regexp)
8108 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8109 txt (org-link-display-format (match-string 4))
8110 re (concat "^" (regexp-quote
8111 (buffer-substring (match-beginning 1)
8112 (match-end 4)))))
8113 (if (match-end 5) (setq re (concat re "[ \t]+"
8114 (regexp-quote
8115 (match-string 5)))))
8116 (setq re (concat re "[ \t]*$"))
8117 (when org-refile-use-outline-path
8118 (setq txt (mapconcat 'org-protect-slash
8119 (append
8120 (if (eq org-refile-use-outline-path 'file)
8121 (list (file-name-nondirectory
8122 (buffer-file-name (buffer-base-buffer))))
8123 (if (eq org-refile-use-outline-path 'full-file-path)
8124 (list (buffer-file-name (buffer-base-buffer)))))
8125 (org-get-outline-path fast-path-p level txt)
8126 (list txt))
8127 "/")))
8128 (push (list txt f re (point)) targets))
8129 (goto-char (point-at-eol))))))))
8130 (message "Getting targets...done")
8131 (nreverse targets))))
8133 (defun org-protect-slash (s)
8134 (while (string-match "/" s)
8135 (setq s (replace-match "\\" t t s)))
8138 (defvar org-olpa (make-vector 20 nil))
8140 (defun org-get-outline-path (&optional fastp level heading)
8141 "Return the outline path to the current entry, as a list."
8142 (if fastp
8143 (progn
8144 (if (> level 19)
8145 (error "Outline path failure, more than 19 levels."))
8146 (loop for i from level upto 19 do
8147 (aset org-olpa i nil))
8148 (prog1
8149 (delq nil (append org-olpa nil))
8150 (aset org-olpa level heading)))
8151 (let (rtn)
8152 (save-excursion
8153 (while (org-up-heading-safe)
8154 (when (looking-at org-complex-heading-regexp)
8155 (push (org-match-string-no-properties 4) rtn)))
8156 rtn))))
8158 (defvar org-refile-history nil
8159 "History for refiling operations.")
8161 (defun org-refile (&optional goto default-buffer)
8162 "Move the entry at point to another heading.
8163 The list of target headings is compiled using the information in
8164 `org-refile-targets', which see. This list is created before each use
8165 and will therefore always be up-to-date.
8167 At the target location, the entry is filed as a subitem of the target heading.
8168 Depending on `org-reverse-note-order', the new subitem will either be the
8169 first or the last subitem.
8171 If there is an active region, all entries in that region will be moved.
8172 However, the region must fulfil the requirement that the first heading
8173 is the first one sets the top-level of the moved text - at most siblings
8174 below it are allowed.
8176 With prefix arg GOTO, the command will only visit the target location,
8177 not actually move anything.
8178 With a double prefix `C-u C-u', go to the location where the last refiling
8179 operation has put the subtree."
8180 (interactive "P")
8181 (let* ((cbuf (current-buffer))
8182 (regionp (org-region-active-p))
8183 (region-start (and regionp (region-beginning)))
8184 (region-end (and regionp (region-end)))
8185 (region-length (and regionp (- region-end region-start)))
8186 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8187 pos it nbuf file re level reversed)
8188 (when regionp (goto-char region-start)
8189 (unless (org-kill-is-subtree-p
8190 (buffer-substring region-start region-end))
8191 (error "The region is not a (sequence of) subtree(s)")))
8192 (if (equal goto '(16))
8193 (org-refile-goto-last-stored)
8194 (when (setq it (org-refile-get-location
8195 (if goto "Goto: " "Refile to: ") default-buffer))
8196 (setq file (nth 1 it)
8197 re (nth 2 it)
8198 pos (nth 3 it))
8199 (if (and (not goto)
8200 (equal (buffer-file-name) file)
8201 (if regionp
8202 (and (>= pos region-start)
8203 (<= pos region-end))
8204 (and (>= pos (point))
8205 (< pos (save-excursion
8206 (org-end-of-subtree t t))))))
8207 (error "Cannot refile to position inside the tree or region"))
8209 (setq nbuf (or (find-buffer-visiting file)
8210 (find-file-noselect file)))
8211 (if goto
8212 (progn
8213 (switch-to-buffer nbuf)
8214 (goto-char pos)
8215 (org-show-context 'org-goto))
8216 (if regionp
8217 (progn
8218 (kill-new (buffer-substring region-start region-end))
8219 (org-save-markers-in-region region-start region-end))
8220 (org-copy-subtree 1 nil t))
8221 (save-excursion
8222 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8223 (find-file-noselect file))))
8224 (setq reversed (org-notes-order-reversed-p))
8225 (save-excursion
8226 (save-restriction
8227 (widen)
8228 (goto-char pos)
8229 (looking-at outline-regexp)
8230 (setq level (org-get-valid-level (funcall outline-level) 1))
8231 (goto-char
8232 (if reversed
8233 (or (outline-next-heading) (point-max))
8234 (or (save-excursion (outline-get-next-sibling))
8235 (org-end-of-subtree t t)
8236 (point-max))))
8237 (if (not (bolp)) (newline))
8238 (bookmark-set "org-refile-last-stored")
8239 (org-paste-subtree level))))
8240 (if regionp
8241 (delete-region (point) (+ (point) region-length))
8242 (org-cut-subtree))
8243 (setq org-markers-to-move nil)
8244 (message "Refiled to \"%s\"" (car it)))))))
8246 (defun org-refile-goto-last-stored ()
8247 "Go to the location where the last refile was stored."
8248 (interactive)
8249 (bookmark-jump "org-refile-last-stored")
8250 (message "This is the location of the last refile"))
8252 (defun org-refile-get-location (&optional prompt default-buffer)
8253 "Prompt the user for a refile location, using PROMPT."
8254 (let ((org-refile-targets org-refile-targets)
8255 (org-refile-use-outline-path org-refile-use-outline-path))
8256 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8257 (unless org-refile-target-table
8258 (error "No refile targets"))
8259 (let* ((cbuf (current-buffer))
8260 (partial-completion-mode nil)
8261 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8262 (cfunc (if (and org-refile-use-outline-path
8263 org-outline-path-complete-in-steps)
8264 'org-olpath-completing-read
8265 'org-ido-completing-read))
8266 (extra (if org-refile-use-outline-path "/" ""))
8267 (filename (and cfn (expand-file-name cfn)))
8268 (tbl (mapcar
8269 (lambda (x)
8270 (if (not (equal filename (nth 1 x)))
8271 (cons (concat (car x) extra " ("
8272 (file-name-nondirectory (nth 1 x)) ")")
8273 (cdr x))
8274 (cons (concat (car x) extra) (cdr x))))
8275 org-refile-target-table))
8276 (completion-ignore-case t))
8277 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8278 tbl)))
8280 (defun org-olpath-completing-read (prompt collection &rest args)
8281 "Read an outline path like a file name."
8282 (let ((thetable collection)
8283 (org-completion-use-ido nil)) ; does not work with ido.
8284 (apply
8285 'org-ido-completing-read prompt
8286 (lambda (string predicate &optional flag)
8287 (let (rtn r f (l (length string)))
8288 (cond
8289 ((eq flag nil)
8290 ;; try completion
8291 (try-completion string thetable))
8292 ((eq flag t)
8293 ;; all-completions
8294 (setq rtn (all-completions string thetable predicate))
8295 (mapcar
8296 (lambda (x)
8297 (setq r (substring x l))
8298 (if (string-match " ([^)]*)$" x)
8299 (setq f (match-string 0 x))
8300 (setq f ""))
8301 (if (string-match "/" r)
8302 (concat string (substring r 0 (match-end 0)) f)
8304 rtn))
8305 ((eq flag 'lambda)
8306 ;; exact match?
8307 (assoc string thetable)))
8309 args)))
8311 ;;;; Dynamic blocks
8313 (defun org-find-dblock (name)
8314 "Find the first dynamic block with name NAME in the buffer.
8315 If not found, stay at current position and return nil."
8316 (let (pos)
8317 (save-excursion
8318 (goto-char (point-min))
8319 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8320 nil t)
8321 (match-beginning 0))))
8322 (if pos (goto-char pos))
8323 pos))
8325 (defconst org-dblock-start-re
8326 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8327 "Matches the startline of a dynamic block, with parameters.")
8329 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8330 "Matches the end of a dynamic block.")
8332 (defun org-create-dblock (plist)
8333 "Create a dynamic block section, with parameters taken from PLIST.
8334 PLIST must contain a :name entry which is used as name of the block."
8335 (unless (bolp) (newline))
8336 (let ((name (plist-get plist :name)))
8337 (insert "#+BEGIN: " name)
8338 (while plist
8339 (if (eq (car plist) :name)
8340 (setq plist (cddr plist))
8341 (insert " " (prin1-to-string (pop plist)))))
8342 (insert "\n\n#+END:\n")
8343 (beginning-of-line -2)))
8345 (defun org-prepare-dblock ()
8346 "Prepare dynamic block for refresh.
8347 This empties the block, puts the cursor at the insert position and returns
8348 the property list including an extra property :name with the block name."
8349 (unless (looking-at org-dblock-start-re)
8350 (error "Not at a dynamic block"))
8351 (let* ((begdel (1+ (match-end 0)))
8352 (name (org-no-properties (match-string 1)))
8353 (params (append (list :name name)
8354 (read (concat "(" (match-string 3) ")")))))
8355 (unless (re-search-forward org-dblock-end-re nil t)
8356 (error "Dynamic block not terminated"))
8357 (setq params
8358 (append params
8359 (list :content (buffer-substring
8360 begdel (match-beginning 0)))))
8361 (delete-region begdel (match-beginning 0))
8362 (goto-char begdel)
8363 (open-line 1)
8364 params))
8366 (defun org-map-dblocks (&optional command)
8367 "Apply COMMAND to all dynamic blocks in the current buffer.
8368 If COMMAND is not given, use `org-update-dblock'."
8369 (let ((cmd (or command 'org-update-dblock))
8370 pos)
8371 (save-excursion
8372 (goto-char (point-min))
8373 (while (re-search-forward org-dblock-start-re nil t)
8374 (goto-char (setq pos (match-beginning 0)))
8375 (condition-case nil
8376 (funcall cmd)
8377 (error (message "Error during update of dynamic block")))
8378 (goto-char pos)
8379 (unless (re-search-forward org-dblock-end-re nil t)
8380 (error "Dynamic block not terminated"))))))
8382 (defun org-dblock-update (&optional arg)
8383 "User command for updating dynamic blocks.
8384 Update the dynamic block at point. With prefix ARG, update all dynamic
8385 blocks in the buffer."
8386 (interactive "P")
8387 (if arg
8388 (org-update-all-dblocks)
8389 (or (looking-at org-dblock-start-re)
8390 (org-beginning-of-dblock))
8391 (org-update-dblock)))
8393 (defun org-update-dblock ()
8394 "Update the dynamic block at point
8395 This means to empty the block, parse for parameters and then call
8396 the correct writing function."
8397 (save-window-excursion
8398 (let* ((pos (point))
8399 (line (org-current-line))
8400 (params (org-prepare-dblock))
8401 (name (plist-get params :name))
8402 (cmd (intern (concat "org-dblock-write:" name))))
8403 (message "Updating dynamic block `%s' at line %d..." name line)
8404 (funcall cmd params)
8405 (message "Updating dynamic block `%s' at line %d...done" name line)
8406 (goto-char pos))))
8408 (defun org-beginning-of-dblock ()
8409 "Find the beginning of the dynamic block at point.
8410 Error if there is no such block at point."
8411 (let ((pos (point))
8412 beg)
8413 (end-of-line 1)
8414 (if (and (re-search-backward org-dblock-start-re nil t)
8415 (setq beg (match-beginning 0))
8416 (re-search-forward org-dblock-end-re nil t)
8417 (> (match-end 0) pos))
8418 (goto-char beg)
8419 (goto-char pos)
8420 (error "Not in a dynamic block"))))
8422 (defun org-update-all-dblocks ()
8423 "Update all dynamic blocks in the buffer.
8424 This function can be used in a hook."
8425 (when (org-mode-p)
8426 (org-map-dblocks 'org-update-dblock)))
8429 ;;;; Completion
8431 (defconst org-additional-option-like-keywords
8432 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8433 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8434 "BEGIN_EXAMPLE" "END_EXAMPLE"
8435 "BEGIN_QUOTE" "END_QUOTE"
8436 "BEGIN_VERSE" "END_VERSE"
8437 "BEGIN_CENTER" "END_CENTER"
8438 "BEGIN_SRC" "END_SRC"
8439 "CATEGORY" "COLUMNS"
8440 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8442 (defcustom org-structure-template-alist
8444 ("s" "#+begin_src ?\n\n#+end_src"
8445 "<src lang=\"?\">\n\n</src>")
8446 ("e" "#+begin_example\n?\n#+end_example"
8447 "<example>\n?\n</example>")
8448 ("q" "#+begin_quote\n?\n#+end_quote"
8449 "<quote>\n?\n</quote>")
8450 ("v" "#+begin_verse\n?\n#+end_verse"
8451 "<verse>\n?\n/verse>")
8452 ("c" "#+begin_center\n?\n#+end_center"
8453 "<center>\n?\n/center>")
8454 ("l" "#+begin_latex\n?\n#+end_latex"
8455 "<literal style=\"latex\">\n?\n</literal>")
8456 ("L" "#+latex: "
8457 "<literal style=\"latex\">?</literal>")
8458 ("h" "#+begin_html\n?\n#+end_html"
8459 "<literal style=\"html\">\n?\n</literal>")
8460 ("H" "#+html: "
8461 "<literal style=\"html\">?</literal>")
8462 ("a" "#+begin_ascii\n?\n#+end_ascii")
8463 ("A" "#+ascii: ")
8464 ("i" "#+include %file ?"
8465 "<include file=%file markup=\"?\">")
8467 "Structure completion elements.
8468 This is a list of abbreviation keys and values. The value gets inserted
8469 it you type @samp{.} followed by the key and then the completion key,
8470 usually `M-TAB'. %file will be replaced by a file name after prompting
8471 for the file using completion.
8472 There are two templates for each key, the first uses the original Org syntax,
8473 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8474 the default when the /org-mtags.el/ module has been loaded. See also the
8475 variable `org-mtags-prefer-muse-templates'.
8476 This is an experimental feature, it is undecided if it is going to stay in."
8477 :group 'org-completion
8478 :type '(repeat
8479 (string :tag "Key")
8480 (string :tag "Template")
8481 (string :tag "Muse Template")))
8483 (defun org-try-structure-completion ()
8484 "Try to complete a structure template before point.
8485 This looks for strings like \"<e\" on an otherwise empty line and
8486 expands them."
8487 (let ((l (buffer-substring (point-at-bol) (point)))
8489 (when (and (looking-at "[ \t]*$")
8490 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8491 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8492 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8493 (match-beginning 1)) a)
8494 t)))
8496 (defun org-complete-expand-structure-template (start cell)
8497 "Expand a structure template."
8498 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8499 (rpl (nth (if musep 2 1) cell)))
8500 (delete-region start (point))
8501 (when (string-match "\\`#\\+" rpl)
8502 (cond
8503 ((bolp))
8504 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8505 (delete-region (point-at-bol) (point)))
8506 (t (newline))))
8507 (setq start (point))
8508 (if (string-match "%file" rpl)
8509 (setq rpl (replace-match
8510 (concat
8511 "\""
8512 (save-match-data
8513 (abbreviate-file-name (read-file-name "Include file: ")))
8514 "\"")
8515 t t rpl)))
8516 (insert rpl)
8517 (if (re-search-backward "\\?" start t) (delete-char 1))))
8520 (defun org-complete (&optional arg)
8521 "Perform completion on word at point.
8522 At the beginning of a headline, this completes TODO keywords as given in
8523 `org-todo-keywords'.
8524 If the current word is preceded by a backslash, completes the TeX symbols
8525 that are supported for HTML support.
8526 If the current word is preceded by \"#+\", completes special words for
8527 setting file options.
8528 In the line after \"#+STARTUP:, complete valid keywords.\"
8529 At all other locations, this simply calls the value of
8530 `org-completion-fallback-command'."
8531 (interactive "P")
8532 (org-without-partial-completion
8533 (catch 'exit
8534 (let* ((a nil)
8535 (end (point))
8536 (beg1 (save-excursion
8537 (skip-chars-backward (org-re "[:alnum:]_@"))
8538 (point)))
8539 (beg (save-excursion
8540 (skip-chars-backward "a-zA-Z0-9_:$")
8541 (point)))
8542 (confirm (lambda (x) (stringp (car x))))
8543 (searchhead (equal (char-before beg) ?*))
8544 (struct
8545 (when (and (member (char-before beg1) '(?. ?<))
8546 (setq a (assoc (buffer-substring beg1 (point))
8547 org-structure-template-alist)))
8548 (org-complete-expand-structure-template (1- beg1) a)
8549 (throw 'exit t)))
8550 (tag (and (equal (char-before beg1) ?:)
8551 (equal (char-after (point-at-bol)) ?*)))
8552 (prop (and (equal (char-before beg1) ?:)
8553 (not (equal (char-after (point-at-bol)) ?*))))
8554 (texp (equal (char-before beg) ?\\))
8555 (link (equal (char-before beg) ?\[))
8556 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8557 beg)
8558 "#+"))
8559 (startup (string-match "^#\\+STARTUP:.*"
8560 (buffer-substring (point-at-bol) (point))))
8561 (completion-ignore-case opt)
8562 (type nil)
8563 (tbl nil)
8564 (table (cond
8565 (opt
8566 (setq type :opt)
8567 (require 'org-exp)
8568 (append
8569 (mapcar
8570 (lambda (x)
8571 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8572 (cons (match-string 2 x) (match-string 1 x)))
8573 (org-split-string (org-get-current-options) "\n"))
8574 (mapcar 'list org-additional-option-like-keywords)))
8575 (startup
8576 (setq type :startup)
8577 org-startup-options)
8578 (link (append org-link-abbrev-alist-local
8579 org-link-abbrev-alist))
8580 (texp
8581 (setq type :tex)
8582 org-html-entities)
8583 ((string-match "\\`\\*+[ \t]+\\'"
8584 (buffer-substring (point-at-bol) beg))
8585 (setq type :todo)
8586 (mapcar 'list org-todo-keywords-1))
8587 (searchhead
8588 (setq type :searchhead)
8589 (save-excursion
8590 (goto-char (point-min))
8591 (while (re-search-forward org-todo-line-regexp nil t)
8592 (push (list
8593 (org-make-org-heading-search-string
8594 (match-string 3) t))
8595 tbl)))
8596 tbl)
8597 (tag (setq type :tag beg beg1)
8598 (or org-tag-alist (org-get-buffer-tags)))
8599 (prop (setq type :prop beg beg1)
8600 (mapcar 'list (org-buffer-property-keys nil t t)))
8601 (t (progn
8602 (call-interactively org-completion-fallback-command)
8603 (throw 'exit nil)))))
8604 (pattern (buffer-substring-no-properties beg end))
8605 (completion (try-completion pattern table confirm)))
8606 (cond ((eq completion t)
8607 (if (not (assoc (upcase pattern) table))
8608 (message "Already complete")
8609 (if (and (equal type :opt)
8610 (not (member (car (assoc (upcase pattern) table))
8611 org-additional-option-like-keywords)))
8612 (insert (substring (cdr (assoc (upcase pattern) table))
8613 (length pattern)))
8614 (if (memq type '(:tag :prop)) (insert ":")))))
8615 ((null completion)
8616 (message "Can't find completion for \"%s\"" pattern)
8617 (ding))
8618 ((not (string= pattern completion))
8619 (delete-region beg end)
8620 (if (string-match " +$" completion)
8621 (setq completion (replace-match "" t t completion)))
8622 (insert completion)
8623 (if (get-buffer-window "*Completions*")
8624 (delete-window (get-buffer-window "*Completions*")))
8625 (if (assoc completion table)
8626 (if (eq type :todo) (insert " ")
8627 (if (memq type '(:tag :prop)) (insert ":"))))
8628 (if (and (equal type :opt) (assoc completion table))
8629 (message "%s" (substitute-command-keys
8630 "Press \\[org-complete] again to insert example settings"))))
8632 (message "Making completion list...")
8633 (let ((list (sort (all-completions pattern table confirm)
8634 'string<)))
8635 (with-output-to-temp-buffer "*Completions*"
8636 (condition-case nil
8637 ;; Protection needed for XEmacs and emacs 21
8638 (display-completion-list list pattern)
8639 (error (display-completion-list list)))))
8640 (message "Making completion list...%s" "done")))))))
8642 ;;;; TODO, DEADLINE, Comments
8644 (defun org-toggle-comment ()
8645 "Change the COMMENT state of an entry."
8646 (interactive)
8647 (save-excursion
8648 (org-back-to-heading)
8649 (let (case-fold-search)
8650 (if (looking-at (concat outline-regexp
8651 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8652 (replace-match "" t t nil 1)
8653 (if (looking-at outline-regexp)
8654 (progn
8655 (goto-char (match-end 0))
8656 (insert org-comment-string " ")))))))
8658 (defvar org-last-todo-state-is-todo nil
8659 "This is non-nil when the last TODO state change led to a TODO state.
8660 If the last change removed the TODO tag or switched to DONE, then
8661 this is nil.")
8663 (defvar org-setting-tags nil) ; dynamically skipped
8665 (defun org-parse-local-options (string var)
8666 "Parse STRING for startup setting relevant for variable VAR."
8667 (let ((rtn (symbol-value var))
8668 e opts)
8669 (save-match-data
8670 (if (or (not string) (not (string-match "\\S-" string)))
8672 (setq opts (delq nil (mapcar (lambda (x)
8673 (setq e (assoc x org-startup-options))
8674 (if (eq (nth 1 e) var) e nil))
8675 (org-split-string string "[ \t]+"))))
8676 (if (not opts)
8678 (setq rtn nil)
8679 (while (setq e (pop opts))
8680 (if (not (nth 3 e))
8681 (setq rtn (nth 2 e))
8682 (if (not (listp rtn)) (setq rtn nil))
8683 (push (nth 2 e) rtn)))
8684 rtn)))))
8686 (defvar org-todo-setup-filter-hook nil
8687 "Hook for functions that pre-filter todo specs.
8689 Each function takes a todo spec and returns either `nil' or the spec
8690 transformed into canonical form." )
8692 (defvar org-todo-get-default-hook nil
8693 "Hook for functions that get a default item for todo.
8695 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8696 `nil' or a string to be used for the todo mark." )
8698 (defvar org-agenda-headline-snapshot-before-repeat)
8699 (defun org-todo (&optional arg)
8700 "Change the TODO state of an item.
8701 The state of an item is given by a keyword at the start of the heading,
8702 like
8703 *** TODO Write paper
8704 *** DONE Call mom
8706 The different keywords are specified in the variable `org-todo-keywords'.
8707 By default the available states are \"TODO\" and \"DONE\".
8708 So for this example: when the item starts with TODO, it is changed to DONE.
8709 When it starts with DONE, the DONE is removed. And when neither TODO nor
8710 DONE are present, add TODO at the beginning of the heading.
8712 With C-u prefix arg, use completion to determine the new state.
8713 With numeric prefix arg, switch to that state.
8714 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8715 With a tripple C-u prefix, circumvent any state blocking.
8717 For calling through lisp, arg is also interpreted in the following way:
8718 'none -> empty state
8719 \"\"(empty string) -> switch to empty state
8720 'done -> switch to DONE
8721 'nextset -> switch to the next set of keywords
8722 'previousset -> switch to the previous set of keywords
8723 \"WAITING\" -> switch to the specified keyword, but only if it
8724 really is a member of `org-todo-keywords'."
8725 (interactive "P")
8726 (if (equal arg '(16)) (setq arg 'nextset))
8727 (let ((org-blocker-hook org-blocker-hook))
8728 (when (equal arg '(64))
8729 (setq arg nil org-blocker-hook nil))
8730 (save-excursion
8731 (catch 'exit
8732 (org-back-to-heading)
8733 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8734 (or (looking-at (concat " +" org-todo-regexp " *"))
8735 (looking-at " *"))
8736 (let* ((match-data (match-data))
8737 (startpos (point-at-bol))
8738 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8739 (org-log-done org-log-done)
8740 (org-log-repeat org-log-repeat)
8741 (org-todo-log-states org-todo-log-states)
8742 (this (match-string 1))
8743 (hl-pos (match-beginning 0))
8744 (head (org-get-todo-sequence-head this))
8745 (ass (assoc head org-todo-kwd-alist))
8746 (interpret (nth 1 ass))
8747 (done-word (nth 3 ass))
8748 (final-done-word (nth 4 ass))
8749 (last-state (or this ""))
8750 (completion-ignore-case t)
8751 (member (member this org-todo-keywords-1))
8752 (tail (cdr member))
8753 (state (cond
8754 ((and org-todo-key-trigger
8755 (or (and (equal arg '(4))
8756 (eq org-use-fast-todo-selection 'prefix))
8757 (and (not arg) org-use-fast-todo-selection
8758 (not (eq org-use-fast-todo-selection
8759 'prefix)))))
8760 ;; Use fast selection
8761 (org-fast-todo-selection))
8762 ((and (equal arg '(4))
8763 (or (not org-use-fast-todo-selection)
8764 (not org-todo-key-trigger)))
8765 ;; Read a state with completion
8766 (org-ido-completing-read
8767 "State: " (mapcar (lambda(x) (list x))
8768 org-todo-keywords-1)
8769 nil t))
8770 ((eq arg 'right)
8771 (if this
8772 (if tail (car tail) nil)
8773 (car org-todo-keywords-1)))
8774 ((eq arg 'left)
8775 (if (equal member org-todo-keywords-1)
8777 (if this
8778 (nth (- (length org-todo-keywords-1)
8779 (length tail) 2)
8780 org-todo-keywords-1)
8781 (org-last org-todo-keywords-1))))
8782 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8783 (setq arg nil))) ; hack to fall back to cycling
8784 (arg
8785 ;; user or caller requests a specific state
8786 (cond
8787 ((equal arg "") nil)
8788 ((eq arg 'none) nil)
8789 ((eq arg 'done) (or done-word (car org-done-keywords)))
8790 ((eq arg 'nextset)
8791 (or (car (cdr (member head org-todo-heads)))
8792 (car org-todo-heads)))
8793 ((eq arg 'previousset)
8794 (let ((org-todo-heads (reverse org-todo-heads)))
8795 (or (car (cdr (member head org-todo-heads)))
8796 (car org-todo-heads))))
8797 ((car (member arg org-todo-keywords-1)))
8798 ((nth (1- (prefix-numeric-value arg))
8799 org-todo-keywords-1))))
8800 ((null member) (or head (car org-todo-keywords-1)))
8801 ((equal this final-done-word) nil) ;; -> make empty
8802 ((null tail) nil) ;; -> first entry
8803 ((memq interpret '(type priority))
8804 (if (eq this-command last-command)
8805 (car tail)
8806 (if (> (length tail) 0)
8807 (or done-word (car org-done-keywords))
8808 nil)))
8810 (car tail))))
8811 (state (or
8812 (run-hook-with-args-until-success
8813 'org-todo-get-default-hook state last-state)
8814 state))
8815 (next (if state (concat " " state " ") " "))
8816 (change-plist (list :type 'todo-state-change :from this :to state
8817 :position startpos))
8818 dolog now-done-p)
8819 (when org-blocker-hook
8820 (setq org-last-todo-state-is-todo
8821 (not (member this org-done-keywords)))
8822 (unless (save-excursion
8823 (save-match-data
8824 (run-hook-with-args-until-failure
8825 'org-blocker-hook change-plist)))
8826 (if (interactive-p)
8827 (error "TODO state change from %s to %s blocked" this state)
8828 ;; fail silently
8829 (message "TODO state change from %s to %s blocked" this state)
8830 (throw 'exit nil))))
8831 (store-match-data match-data)
8832 (replace-match next t t)
8833 (unless (pos-visible-in-window-p hl-pos)
8834 (message "TODO state changed to %s" (org-trim next)))
8835 (unless head
8836 (setq head (org-get-todo-sequence-head state)
8837 ass (assoc head org-todo-kwd-alist)
8838 interpret (nth 1 ass)
8839 done-word (nth 3 ass)
8840 final-done-word (nth 4 ass)))
8841 (when (memq arg '(nextset previousset))
8842 (message "Keyword-Set %d/%d: %s"
8843 (- (length org-todo-sets) -1
8844 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8845 (length org-todo-sets)
8846 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8847 (setq org-last-todo-state-is-todo
8848 (not (member state org-done-keywords)))
8849 (setq now-done-p (and (member state org-done-keywords)
8850 (not (member this org-done-keywords))))
8851 (and logging (org-local-logging logging))
8852 (when (and (or org-todo-log-states org-log-done)
8853 (not (memq arg '(nextset previousset))))
8854 ;; we need to look at recording a time and note
8855 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8856 (nth 2 (assoc this org-todo-log-states))))
8857 (when (and state
8858 (member state org-not-done-keywords)
8859 (not (member this org-not-done-keywords)))
8860 ;; This is now a todo state and was not one before
8861 ;; If there was a CLOSED time stamp, get rid of it.
8862 (org-add-planning-info nil nil 'closed))
8863 (when (and now-done-p org-log-done)
8864 ;; It is now done, and it was not done before
8865 (org-add-planning-info 'closed (org-current-time))
8866 (if (and (not dolog) (eq 'note org-log-done))
8867 (org-add-log-setup 'done state this 'findpos 'note)))
8868 (when (and state dolog)
8869 ;; This is a non-nil state, and we need to log it
8870 (org-add-log-setup 'state state this 'findpos dolog)))
8871 ;; Fixup tag positioning
8872 (org-todo-trigger-tag-changes state)
8873 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8874 (when org-provide-todo-statistics
8875 (org-update-parent-todo-statistics))
8876 (run-hooks 'org-after-todo-state-change-hook)
8877 (if (and arg (not (member state org-done-keywords)))
8878 (setq head (org-get-todo-sequence-head state)))
8879 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8880 ;; Do we need to trigger a repeat?
8881 (when now-done-p
8882 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8883 ;; This is for the agenda, take a snapshot of the headline.
8884 (save-match-data
8885 (setq org-agenda-headline-snapshot-before-repeat
8886 (org-get-heading))))
8887 (org-auto-repeat-maybe state))
8888 ;; Fixup cursor location if close to the keyword
8889 (if (and (outline-on-heading-p)
8890 (not (bolp))
8891 (save-excursion (beginning-of-line 1)
8892 (looking-at org-todo-line-regexp))
8893 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8894 (progn
8895 (goto-char (or (match-end 2) (match-end 1)))
8896 (just-one-space)))
8897 (when org-trigger-hook
8898 (save-excursion
8899 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8901 (defun org-block-todo-from-children-or-siblings (change-plist)
8902 "Block turning an entry into a TODO, using the hierarchy.
8903 This checks whether the current task should be blocked from state
8904 changes. Such blocking occurs when:
8906 1. The task has children which are not all in a completed state.
8908 2. A task has a parent with the property :ORDERED:, and there
8909 are siblings prior to the current task with incomplete
8910 status."
8911 (catch 'dont-block
8912 ;; If this is not a todo state change, or if this entry is already DONE,
8913 ;; do not block
8914 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8915 (member (plist-get change-plist :from)
8916 (cons 'done org-done-keywords))
8917 (member (plist-get change-plist :to)
8918 (cons 'todo org-not-done-keywords)))
8919 (throw 'dont-block t))
8920 ;; If this task has children, and any are undone, it's blocked
8921 (save-excursion
8922 (org-back-to-heading t)
8923 (let ((this-level (funcall outline-level)))
8924 (outline-next-heading)
8925 (let ((child-level (funcall outline-level)))
8926 (while (and (not (eobp))
8927 (> child-level this-level))
8928 ;; this todo has children, check whether they are all
8929 ;; completed
8930 (if (and (not (org-entry-is-done-p))
8931 (org-entry-is-todo-p))
8932 (throw 'dont-block nil))
8933 (outline-next-heading)
8934 (setq child-level (funcall outline-level))))))
8935 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8936 ;; any previous siblings are undone, it's blocked
8937 (save-excursion
8938 (org-back-to-heading t)
8939 (when (save-excursion
8940 (ignore-errors
8941 (org-up-heading-all 1)
8942 (org-entry-get (point) "ORDERED")))
8943 (let* ((this-level (funcall outline-level))
8944 (current-level this-level))
8945 (while (and (not (bobp))
8946 (>= current-level this-level))
8947 (outline-previous-heading)
8948 (setq current-level (funcall outline-level))
8949 (if (= current-level this-level)
8950 ;; This is a younger sibling, check if it is completed
8951 (if (and (not (org-entry-is-done-p))
8952 (org-entry-is-todo-p))
8953 (throw 'dont-block nil)))))))
8954 t)) ; don't block
8956 (defcustom org-track-ordered-property-with-tag nil
8957 "Should the ORDERED property also be shown as a tag?
8958 The ORDERED property decides if an entry should require subtasks to be
8959 completed in sequence. Since a property is not very visible, setting
8960 this option means that toggling the ORDERED property with the command
8961 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
8962 not relevant for the behavior, but it makes things more visible.
8964 Note that toggling the tag with tags commands will not change the property
8965 and therefore not influence behavior!
8967 This can be t, meaning the tag ORDERED should be used, It can also be a
8968 string to select a different tag for this task."
8969 :group 'org-todo
8970 :type '(choice
8971 (const :tag "No tracking" nil)
8972 (const :tag "Track with ORDERED tag" t)
8973 (string :tag "Use other tag")))
8975 (defun org-toggle-ordered-property ()
8976 "Toggle the ORDERED property of the current entry.
8977 For better visibility, you can track the value of this property with a tag.
8978 See variable `org-track-ordered-property-with-tag'."
8979 (interactive)
8980 (let* ((t1 org-track-ordered-property-with-tag)
8981 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
8982 (save-excursion
8983 (org-back-to-heading)
8984 (if (org-entry-get nil "ORDERED")
8985 (progn
8986 (org-delete-property "ORDERED")
8987 (and tag (org-toggle-tag tag 'off))
8988 (message "Subtasks can be completed in arbitrary order"))
8989 (org-entry-put nil "ORDERED" "t")
8990 (and tag (org-toggle-tag tag 'on))
8991 (message "Subtasks must be completed in sequence")))))
8993 (defvar org-blocked-by-checkboxes) ; dynamically scoped
8994 (defun org-block-todo-from-checkboxes (change-plist)
8995 "Block turning an entry into a TODO, using checkboxes.
8996 This checks whether the current task should be blocked from state
8997 changes because there are uncheckd boxes in this entry."
8998 (catch 'dont-block
8999 ;; If this is not a todo state change, or if this entry is already DONE,
9000 ;; do not block
9001 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9002 (member (plist-get change-plist :from)
9003 (cons 'done org-done-keywords))
9004 (member (plist-get change-plist :to)
9005 (cons 'todo org-not-done-keywords)))
9006 (throw 'dont-block t))
9007 ;; If this task has checkboxes that are not checked, it's blocked
9008 (save-excursion
9009 (org-back-to-heading t)
9010 (let ((beg (point)) end)
9011 (outline-next-heading)
9012 (setq end (point))
9013 (goto-char beg)
9014 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9015 end t)
9016 (progn
9017 (if (boundp 'org-blocked-by-checkboxes)
9018 (setq org-blocked-by-checkboxes t))
9019 (throw 'dont-block nil)))))
9020 t)) ; do not block
9022 (defun org-update-parent-todo-statistics ()
9023 "Update any statistics cookie in the parent of the current headline."
9024 (interactive)
9025 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9026 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9027 (catch 'exit
9028 (save-excursion
9029 (setq level (org-up-heading-safe))
9030 (unless level
9031 (throw 'exit nil))
9032 (while (re-search-forward box-re (point-at-eol) t)
9033 (setq cnt-all 0 cnt-done 0 cookie-present t)
9034 (setq is-percent (match-end 2))
9035 (save-match-data
9036 (unless (outline-next-heading) (throw 'exit nil))
9037 (while (looking-at org-todo-line-regexp)
9038 (setq kwd (match-string 2))
9039 (and kwd (setq cnt-all (1+ cnt-all)))
9040 (and (member kwd org-done-keywords)
9041 (setq cnt-done (1+ cnt-done)))
9042 (condition-case nil
9043 (org-forward-same-level 1)
9044 (error (end-of-line 1)))))
9045 (replace-match
9046 (if is-percent
9047 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9048 (format "[%d/%d]" cnt-done cnt-all))))
9049 (when cookie-present
9050 (run-hook-with-args 'org-after-todo-statistics-hook
9051 cnt-done (- cnt-all cnt-done)))))))
9053 (defvar org-after-todo-statistics-hook nil
9054 "Hook that is called after a TODO statistics cookie has been updated.
9055 Each function is called with two arguments: the number of not-done entries
9056 and the number of done entries.
9058 For example, the following function, when added to this hook, will switch
9059 an entry to DONE when all children are done, and back to TODO when new
9060 entries are set to a TODO status. Note that this hook is only called
9061 when there is a statistics cookie in the headline!
9063 (defun org-summary-todo (n-done n-not-done)
9064 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9065 (let (org-log-done org-log-states) ; turn off logging
9066 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9069 (defun org-todo-trigger-tag-changes (state)
9070 "Apply the changes defined in `org-todo-state-tags-triggers'."
9071 (let ((l org-todo-state-tags-triggers)
9072 changes)
9073 (when (or (not state) (equal state ""))
9074 (setq changes (append changes (cdr (assoc "" l)))))
9075 (when (and (stringp state) (> (length state) 0))
9076 (setq changes (append changes (cdr (assoc state l)))))
9077 (when (member state org-not-done-keywords)
9078 (setq changes (append changes (cdr (assoc 'todo l)))))
9079 (when (member state org-done-keywords)
9080 (setq changes (append changes (cdr (assoc 'done l)))))
9081 (dolist (c changes)
9082 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9084 (defun org-local-logging (value)
9085 "Get logging settings from a property VALUE."
9086 (let* (words w a)
9087 ;; directly set the variables, they are already local.
9088 (setq org-log-done nil
9089 org-log-repeat nil
9090 org-todo-log-states nil)
9091 (setq words (org-split-string value))
9092 (while (setq w (pop words))
9093 (cond
9094 ((setq a (assoc w org-startup-options))
9095 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9096 (set (nth 1 a) (nth 2 a))))
9097 ((setq a (org-extract-log-state-settings w))
9098 (and (member (car a) org-todo-keywords-1)
9099 (push a org-todo-log-states)))))))
9101 (defun org-get-todo-sequence-head (kwd)
9102 "Return the head of the TODO sequence to which KWD belongs.
9103 If KWD is not set, check if there is a text property remembering the
9104 right sequence."
9105 (let (p)
9106 (cond
9107 ((not kwd)
9108 (or (get-text-property (point-at-bol) 'org-todo-head)
9109 (progn
9110 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9111 nil (point-at-eol)))
9112 (get-text-property p 'org-todo-head))))
9113 ((not (member kwd org-todo-keywords-1))
9114 (car org-todo-keywords-1))
9115 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9117 (defun org-fast-todo-selection ()
9118 "Fast TODO keyword selection with single keys.
9119 Returns the new TODO keyword, or nil if no state change should occur."
9120 (let* ((fulltable org-todo-key-alist)
9121 (done-keywords org-done-keywords) ;; needed for the faces.
9122 (maxlen (apply 'max (mapcar
9123 (lambda (x)
9124 (if (stringp (car x)) (string-width (car x)) 0))
9125 fulltable)))
9126 (expert nil)
9127 (fwidth (+ maxlen 3 1 3))
9128 (ncol (/ (- (window-width) 4) fwidth))
9129 tg cnt e c tbl
9130 groups ingroup)
9131 (save-excursion
9132 (save-window-excursion
9133 (if expert
9134 (set-buffer (get-buffer-create " *Org todo*"))
9135 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9136 (erase-buffer)
9137 (org-set-local 'org-done-keywords done-keywords)
9138 (setq tbl fulltable cnt 0)
9139 (while (setq e (pop tbl))
9140 (cond
9141 ((equal e '(:startgroup))
9142 (push '() groups) (setq ingroup t)
9143 (when (not (= cnt 0))
9144 (setq cnt 0)
9145 (insert "\n"))
9146 (insert "{ "))
9147 ((equal e '(:endgroup))
9148 (setq ingroup nil cnt 0)
9149 (insert "}\n"))
9150 ((equal e '(:newline))
9151 (when (not (= cnt 0))
9152 (setq cnt 0)
9153 (insert "\n")
9154 (setq e (car tbl))
9155 (while (equal (car tbl) '(:newline))
9156 (insert "\n")
9157 (setq tbl (cdr tbl)))))
9159 (setq tg (car e) c (cdr e))
9160 (if ingroup (push tg (car groups)))
9161 (setq tg (org-add-props tg nil 'face
9162 (org-get-todo-face tg)))
9163 (if (and (= cnt 0) (not ingroup)) (insert " "))
9164 (insert "[" c "] " tg (make-string
9165 (- fwidth 4 (length tg)) ?\ ))
9166 (when (= (setq cnt (1+ cnt)) ncol)
9167 (insert "\n")
9168 (if ingroup (insert " "))
9169 (setq cnt 0)))))
9170 (insert "\n")
9171 (goto-char (point-min))
9172 (if (not expert) (org-fit-window-to-buffer))
9173 (message "[a-z..]:Set [SPC]:clear")
9174 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9175 (cond
9176 ((or (= c ?\C-g)
9177 (and (= c ?q) (not (rassoc c fulltable))))
9178 (setq quit-flag t))
9179 ((= c ?\ ) nil)
9180 ((setq e (rassoc c fulltable) tg (car e))
9182 (t (setq quit-flag t)))))))
9184 (defun org-entry-is-todo-p ()
9185 (member (org-get-todo-state) org-not-done-keywords))
9187 (defun org-entry-is-done-p ()
9188 (member (org-get-todo-state) org-done-keywords))
9190 (defun org-get-todo-state ()
9191 (save-excursion
9192 (org-back-to-heading t)
9193 (and (looking-at org-todo-line-regexp)
9194 (match-end 2)
9195 (match-string 2))))
9197 (defun org-at-date-range-p (&optional inactive-ok)
9198 "Is the cursor inside a date range?"
9199 (interactive)
9200 (save-excursion
9201 (catch 'exit
9202 (let ((pos (point)))
9203 (skip-chars-backward "^[<\r\n")
9204 (skip-chars-backward "<[")
9205 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9206 (>= (match-end 0) pos)
9207 (throw 'exit t))
9208 (skip-chars-backward "^<[\r\n")
9209 (skip-chars-backward "<[")
9210 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9211 (>= (match-end 0) pos)
9212 (throw 'exit t)))
9213 nil)))
9215 (defun org-get-repeat ()
9216 "Check if there is a deadline/schedule with repeater in this entry."
9217 (save-match-data
9218 (save-excursion
9219 (org-back-to-heading t)
9220 (if (re-search-forward
9221 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9222 (match-string 1)))))
9224 (defvar org-last-changed-timestamp)
9225 (defvar org-last-inserted-timestamp)
9226 (defvar org-log-post-message)
9227 (defvar org-log-note-purpose)
9228 (defvar org-log-note-how)
9229 (defvar org-log-note-extra)
9230 (defun org-auto-repeat-maybe (done-word)
9231 "Check if the current headline contains a repeated deadline/schedule.
9232 If yes, set TODO state back to what it was and change the base date
9233 of repeating deadline/scheduled time stamps to new date.
9234 This function is run automatically after each state change to a DONE state."
9235 ;; last-state is dynamically scoped into this function
9236 (let* ((repeat (org-get-repeat))
9237 (aa (assoc last-state org-todo-kwd-alist))
9238 (interpret (nth 1 aa))
9239 (head (nth 2 aa))
9240 (whata '(("d" . day) ("m" . month) ("y" . year)))
9241 (msg "Entry repeats: ")
9242 (org-log-done nil)
9243 (org-todo-log-states nil)
9244 (nshiftmax 10) (nshift 0)
9245 re type n what ts time)
9246 (when repeat
9247 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9248 (org-todo (if (eq interpret 'type) last-state head))
9249 (when org-log-repeat
9250 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9251 (memq 'org-add-log-note post-command-hook))
9252 ;; OK, we are already setup for some record
9253 (if (eq org-log-repeat 'note)
9254 ;; make sure we take a note, not only a time stamp
9255 (setq org-log-note-how 'note))
9256 ;; Set up for taking a record
9257 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9258 last-state
9259 'findpos org-log-repeat)))
9260 (org-back-to-heading t)
9261 (org-add-planning-info nil nil 'closed)
9262 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9263 org-deadline-time-regexp "\\)\\|\\("
9264 org-ts-regexp "\\)"))
9265 (while (re-search-forward
9266 re (save-excursion (outline-next-heading) (point)) t)
9267 (setq type (if (match-end 1) org-scheduled-string
9268 (if (match-end 3) org-deadline-string "Plain:"))
9269 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9270 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9271 (setq n (string-to-number (match-string 2 ts))
9272 what (match-string 3 ts))
9273 (if (equal what "w") (setq n (* n 7) what "d"))
9274 ;; Preparation, see if we need to modify the start date for the change
9275 (when (match-end 1)
9276 (setq time (save-match-data (org-time-string-to-time ts)))
9277 (cond
9278 ((equal (match-string 1 ts) ".")
9279 ;; Shift starting date to today
9280 (org-timestamp-change
9281 (- (time-to-days (current-time)) (time-to-days time))
9282 'day))
9283 ((equal (match-string 1 ts) "+")
9284 (while (or (= nshift 0)
9285 (<= (time-to-days time) (time-to-days (current-time))))
9286 (when (= (incf nshift) nshiftmax)
9287 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9288 (error "Abort")))
9289 (org-timestamp-change n (cdr (assoc what whata)))
9290 (org-at-timestamp-p t)
9291 (setq ts (match-string 1))
9292 (setq time (save-match-data (org-time-string-to-time ts))))
9293 (org-timestamp-change (- n) (cdr (assoc what whata)))
9294 ;; rematch, so that we have everything in place for the real shift
9295 (org-at-timestamp-p t)
9296 (setq ts (match-string 1))
9297 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9298 (org-timestamp-change n (cdr (assoc what whata)))
9299 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9300 (setq org-log-post-message msg)
9301 (message "%s" msg))))
9303 (defun org-show-todo-tree (arg)
9304 "Make a compact tree which shows all headlines marked with TODO.
9305 The tree will show the lines where the regexp matches, and all higher
9306 headlines above the match.
9307 With a \\[universal-argument] prefix, also show the DONE entries.
9308 With a numeric prefix N, construct a sparse tree for the Nth element
9309 of `org-todo-keywords-1'."
9310 (interactive "P")
9311 (let ((case-fold-search nil)
9312 (kwd-re
9313 (cond ((null arg) org-not-done-regexp)
9314 ((equal arg '(4))
9315 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9316 (mapcar 'list org-todo-keywords-1))))
9317 (concat "\\("
9318 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9319 "\\)\\>")))
9320 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9321 (regexp-quote (nth (1- (prefix-numeric-value arg))
9322 org-todo-keywords-1)))
9323 (t (error "Invalid prefix argument: %s" arg)))))
9324 (message "%d TODO entries found"
9325 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9327 (defun org-deadline (&optional remove time)
9328 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9329 With argument REMOVE, remove any deadline from the item.
9330 When TIME is set, it should be an internal time specification, and the
9331 scheduling will use the corresponding date."
9332 (interactive "P")
9333 (if remove
9334 (progn
9335 (org-remove-timestamp-with-keyword org-deadline-string)
9336 (message "Item no longer has a deadline."))
9337 (if (org-get-repeat)
9338 (error "Cannot change deadline on task with repeater, please do that by hand")
9339 (org-add-planning-info 'deadline time 'closed)
9340 (message "Deadline on %s" org-last-inserted-timestamp))))
9342 (defun org-schedule (&optional remove time)
9343 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9344 With argument REMOVE, remove any scheduling date from the item.
9345 When TIME is set, it should be an internal time specification, and the
9346 scheduling will use the corresponding date."
9347 (interactive "P")
9348 (if remove
9349 (progn
9350 (org-remove-timestamp-with-keyword org-scheduled-string)
9351 (message "Item is no longer scheduled."))
9352 (if (org-get-repeat)
9353 (error "Cannot reschedule task with repeater, please do that by hand")
9354 (org-add-planning-info 'scheduled time 'closed)
9355 (message "Scheduled to %s" org-last-inserted-timestamp))))
9357 (defun org-get-scheduled-time (pom &optional inherit)
9358 "Get the scheduled time as a time tuple, of a format suitable
9359 for calling org-schedule with, or if there is no scheduling,
9360 returns nil."
9361 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9362 (when time
9363 (apply 'encode-time (org-parse-time-string time)))))
9365 (defun org-get-deadline-time (pom &optional inherit)
9366 "Get the deadine as a time tuple, of a format suitable for
9367 calling org-deadlin with, or if there is no scheduling, returns
9368 nil."
9369 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9370 (when time
9371 (apply 'encode-time (org-parse-time-string time)))))
9373 (defun org-remove-timestamp-with-keyword (keyword)
9374 "Remove all time stamps with KEYWORD in the current entry."
9375 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9376 beg)
9377 (save-excursion
9378 (org-back-to-heading t)
9379 (setq beg (point))
9380 (org-end-of-subtree t t)
9381 (while (re-search-backward re beg t)
9382 (replace-match "")
9383 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9384 (equal (char-before) ?\ ))
9385 (backward-delete-char 1)
9386 (if (string-match "^[ \t]*$" (buffer-substring
9387 (point-at-bol) (point-at-eol)))
9388 (delete-region (point-at-bol)
9389 (min (point-max) (1+ (point-at-eol))))))))))
9391 (defun org-add-planning-info (what &optional time &rest remove)
9392 "Insert new timestamp with keyword in the line directly after the headline.
9393 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9394 If non is given, the user is prompted for a date.
9395 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9396 be removed."
9397 (interactive)
9398 (let (org-time-was-given org-end-time-was-given ts
9399 end default-time default-input)
9401 (catch 'exit
9402 (when (and (not time) (memq what '(scheduled deadline)))
9403 ;; Try to get a default date/time from existing timestamp
9404 (save-excursion
9405 (org-back-to-heading t)
9406 (setq end (save-excursion (outline-next-heading) (point)))
9407 (when (re-search-forward (if (eq what 'scheduled)
9408 org-scheduled-time-regexp
9409 org-deadline-time-regexp)
9410 end t)
9411 (setq ts (match-string 1)
9412 default-time
9413 (apply 'encode-time (org-parse-time-string ts))
9414 default-input (and ts (org-get-compact-tod ts))))))
9415 (when what
9416 ;; If necessary, get the time from the user
9417 (setq time (or time (org-read-date nil 'to-time nil nil
9418 default-time default-input))))
9420 (when (and org-insert-labeled-timestamps-at-point
9421 (member what '(scheduled deadline)))
9422 (insert
9423 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9424 (org-insert-time-stamp time org-time-was-given
9425 nil nil nil (list org-end-time-was-given))
9426 (setq what nil))
9427 (save-excursion
9428 (save-restriction
9429 (let (col list elt ts buffer-invisibility-spec)
9430 (org-back-to-heading t)
9431 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9432 (goto-char (match-end 1))
9433 (setq col (current-column))
9434 (goto-char (match-end 0))
9435 (if (eobp) (insert "\n") (forward-char 1))
9436 (when (and (not what)
9437 (not (looking-at
9438 (concat "[ \t]*"
9439 org-keyword-time-not-clock-regexp))))
9440 ;; Nothing to add, nothing to remove...... :-)
9441 (throw 'exit nil))
9442 (if (and (not (looking-at outline-regexp))
9443 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9444 "[^\r\n]*"))
9445 (not (equal (match-string 1) org-clock-string)))
9446 (narrow-to-region (match-beginning 0) (match-end 0))
9447 (insert-before-markers "\n")
9448 (backward-char 1)
9449 (narrow-to-region (point) (point))
9450 (and org-adapt-indentation (org-indent-to-column col)))
9451 ;; Check if we have to remove something.
9452 (setq list (cons what remove))
9453 (while list
9454 (setq elt (pop list))
9455 (goto-char (point-min))
9456 (when (or (and (eq elt 'scheduled)
9457 (re-search-forward org-scheduled-time-regexp nil t))
9458 (and (eq elt 'deadline)
9459 (re-search-forward org-deadline-time-regexp nil t))
9460 (and (eq elt 'closed)
9461 (re-search-forward org-closed-time-regexp nil t)))
9462 (replace-match "")
9463 (if (looking-at "--+<[^>]+>") (replace-match ""))
9464 (if (looking-at " +") (replace-match ""))))
9465 (goto-char (point-max))
9466 (when what
9467 (insert
9468 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9469 (cond ((eq what 'scheduled) org-scheduled-string)
9470 ((eq what 'deadline) org-deadline-string)
9471 ((eq what 'closed) org-closed-string))
9472 " ")
9473 (setq ts (org-insert-time-stamp
9474 time
9475 (or org-time-was-given
9476 (and (eq what 'closed) org-log-done-with-time))
9477 (eq what 'closed)
9478 nil nil (list org-end-time-was-given)))
9479 (end-of-line 1))
9480 (goto-char (point-min))
9481 (widen)
9482 (if (and (looking-at "[ \t]+\n")
9483 (equal (char-before) ?\n))
9484 (delete-region (1- (point)) (point-at-eol)))
9485 ts))))))
9487 (defvar org-log-note-marker (make-marker))
9488 (defvar org-log-note-purpose nil)
9489 (defvar org-log-note-state nil)
9490 (defvar org-log-note-previous-state nil)
9491 (defvar org-log-note-how nil)
9492 (defvar org-log-note-extra nil)
9493 (defvar org-log-note-window-configuration nil)
9494 (defvar org-log-note-return-to (make-marker))
9495 (defvar org-log-post-message nil
9496 "Message to be displayed after a log note has been stored.
9497 The auto-repeater uses this.")
9499 (defun org-add-note ()
9500 "Add a note to the current entry.
9501 This is done in the same way as adding a state change note."
9502 (interactive)
9503 (org-add-log-setup 'note nil nil 'findpos nil))
9505 (defvar org-property-end-re)
9506 (defun org-add-log-setup (&optional purpose state prev-state
9507 findpos how &optional extra)
9508 "Set up the post command hook to take a note.
9509 If this is about to TODO state change, the new state is expected in STATE.
9510 When FINDPOS is non-nil, find the correct position for the note in
9511 the current entry. If not, assume that it can be inserted at point.
9512 HOW is an indicator what kind of note should be created.
9513 EXTRA is additional text that will be inserted into the notes buffer."
9514 (let ((drawer (cond ((stringp org-log-into-drawer)
9515 org-log-into-drawer)
9516 (org-log-into-drawer "LOGBOOK")
9517 (t nil))))
9518 (save-restriction
9519 (save-excursion
9520 (when findpos
9521 (org-back-to-heading t)
9522 (narrow-to-region (point) (save-excursion
9523 (outline-next-heading) (point)))
9524 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9525 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9526 "[^\r\n]*\\)?"))
9527 (goto-char (match-end 0))
9528 (cond
9529 (drawer
9530 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9531 nil t)
9532 (progn
9533 (goto-char (match-end 0))
9534 (or org-log-states-order-reversed
9535 (and (re-search-forward org-property-end-re nil t)
9536 (goto-char (1- (match-beginning 0))))))
9537 (insert "\n:" drawer ":\n:END:")
9538 (beginning-of-line 0)
9539 (org-indent-line-function)
9540 (beginning-of-line 2)
9541 (org-indent-line-function)
9542 (end-of-line 0)))
9543 ((and org-log-state-notes-insert-after-drawers
9544 (save-excursion
9545 (forward-line) (looking-at org-drawer-regexp)))
9546 (forward-line)
9547 (while (looking-at org-drawer-regexp)
9548 (goto-char (match-end 0))
9549 (re-search-forward org-property-end-re (point-max) t)
9550 (forward-line))
9551 (forward-line -1)))
9552 (unless org-log-states-order-reversed
9553 (and (= (char-after) ?\n) (forward-char 1))
9554 (org-skip-over-state-notes)
9555 (skip-chars-backward " \t\n\r")))
9556 (move-marker org-log-note-marker (point))
9557 (setq org-log-note-purpose purpose
9558 org-log-note-state state
9559 org-log-note-previous-state prev-state
9560 org-log-note-how how
9561 org-log-note-extra extra)
9562 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9564 (defun org-skip-over-state-notes ()
9565 "Skip past the list of State notes in an entry."
9566 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9567 (while (looking-at "[ \t]*- State")
9568 (condition-case nil
9569 (org-next-item)
9570 (error (org-end-of-item)))))
9572 (defun org-add-log-note (&optional purpose)
9573 "Pop up a window for taking a note, and add this note later at point."
9574 (remove-hook 'post-command-hook 'org-add-log-note)
9575 (setq org-log-note-window-configuration (current-window-configuration))
9576 (delete-other-windows)
9577 (move-marker org-log-note-return-to (point))
9578 (switch-to-buffer (marker-buffer org-log-note-marker))
9579 (goto-char org-log-note-marker)
9580 (org-switch-to-buffer-other-window "*Org Note*")
9581 (erase-buffer)
9582 (if (memq org-log-note-how '(time state))
9583 (let (current-prefix-arg) (org-store-log-note))
9584 (let ((org-inhibit-startup t)) (org-mode))
9585 (insert (format "# Insert note for %s.
9586 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9587 (cond
9588 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9589 ((eq org-log-note-purpose 'done) "closed todo item")
9590 ((eq org-log-note-purpose 'state)
9591 (format "state change from \"%s\" to \"%s\""
9592 (or org-log-note-previous-state "")
9593 (or org-log-note-state "")))
9594 ((eq org-log-note-purpose 'note)
9595 "this entry")
9596 (t (error "This should not happen")))))
9597 (if org-log-note-extra (insert org-log-note-extra))
9598 (org-set-local 'org-finish-function 'org-store-log-note)))
9600 (defvar org-note-abort nil) ; dynamically scoped
9601 (defun org-store-log-note ()
9602 "Finish taking a log note, and insert it to where it belongs."
9603 (let ((txt (buffer-string))
9604 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9605 lines ind)
9606 (kill-buffer (current-buffer))
9607 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9608 (setq txt (replace-match "" t t txt)))
9609 (if (string-match "\\s-+\\'" txt)
9610 (setq txt (replace-match "" t t txt)))
9611 (setq lines (org-split-string txt "\n"))
9612 (when (and note (string-match "\\S-" note))
9613 (setq note
9614 (org-replace-escapes
9615 note
9616 (list (cons "%u" (user-login-name))
9617 (cons "%U" user-full-name)
9618 (cons "%t" (format-time-string
9619 (org-time-stamp-format 'long 'inactive)
9620 (current-time)))
9621 (cons "%s" (if org-log-note-state
9622 (concat "\"" org-log-note-state "\"")
9623 ""))
9624 (cons "%S" (if org-log-note-previous-state
9625 (concat "\"" org-log-note-previous-state "\"")
9626 "\"\"")))))
9627 (if lines (setq note (concat note " \\\\")))
9628 (push note lines))
9629 (when (or current-prefix-arg org-note-abort)
9630 (when org-log-into-drawer
9631 (org-remove-empty-drawer-at
9632 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
9633 org-log-note-marker))
9634 (setq lines nil))
9635 (when lines
9636 (save-excursion
9637 (set-buffer (marker-buffer org-log-note-marker))
9638 (save-excursion
9639 (goto-char org-log-note-marker)
9640 (move-marker org-log-note-marker nil)
9641 (end-of-line 1)
9642 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9643 (insert "- " (pop lines))
9644 (org-indent-line-function)
9645 (beginning-of-line 1)
9646 (looking-at "[ \t]*")
9647 (setq ind (concat (match-string 0) " "))
9648 (end-of-line 1)
9649 (while lines (insert "\n" ind (pop lines)))
9650 (message "Note stored")
9651 (org-back-to-heading t)
9652 (org-cycle-hide-drawers 'children)))))
9653 (set-window-configuration org-log-note-window-configuration)
9654 (with-current-buffer (marker-buffer org-log-note-return-to)
9655 (goto-char org-log-note-return-to))
9656 (move-marker org-log-note-return-to nil)
9657 (and org-log-post-message (message "%s" org-log-post-message)))
9659 (defun org-remove-empty-drawer-at (drawer pos)
9660 "Remove an emptyr DARWER drawer at position POS.
9661 POS may also be a marker."
9662 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
9663 (save-excursion
9664 (save-restriction
9665 (widen)
9666 (goto-char pos)
9667 (if (org-in-regexp
9668 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
9669 (replace-match ""))))))
9671 (defun org-sparse-tree (&optional arg)
9672 "Create a sparse tree, prompt for the details.
9673 This command can create sparse trees. You first need to select the type
9674 of match used to create the tree:
9676 t Show entries with a specific TODO keyword.
9677 m Show entries selected by a tags/property match.
9678 p Enter a property name and its value (both with completion on existing
9679 names/values) and show entries with that property.
9680 r Show entries matching a regular expression.
9681 d Show deadlines due within `org-deadline-warning-days'.
9682 b Show deadlines and scheduled items before a date.
9683 a Show deadlines and scheduled items after a date."
9684 (interactive "P")
9685 (let (ans kwd value)
9686 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
9687 (setq ans (read-char-exclusive))
9688 (cond
9689 ((equal ans ?d)
9690 (call-interactively 'org-check-deadlines))
9691 ((equal ans ?b)
9692 (call-interactively 'org-check-before-date))
9693 ((equal ans ?a)
9694 (call-interactively 'org-check-after-date))
9695 ((equal ans ?t)
9696 (org-show-todo-tree '(4)))
9697 ((member ans '(?T ?m))
9698 (call-interactively 'org-match-sparse-tree))
9699 ((member ans '(?p ?P))
9700 (setq kwd (org-ido-completing-read "Property: "
9701 (mapcar 'list (org-buffer-property-keys))))
9702 (setq value (org-ido-completing-read "Value: "
9703 (mapcar 'list (org-property-values kwd))))
9704 (unless (string-match "\\`{.*}\\'" value)
9705 (setq value (concat "\"" value "\"")))
9706 (org-match-sparse-tree arg (concat kwd "=" value)))
9707 ((member ans '(?r ?R ?/))
9708 (call-interactively 'org-occur))
9709 (t (error "No such sparse tree command \"%c\"" ans)))))
9711 (defvar org-occur-highlights nil
9712 "List of overlays used for occur matches.")
9713 (make-variable-buffer-local 'org-occur-highlights)
9714 (defvar org-occur-parameters nil
9715 "Parameters of the active org-occur calls.
9716 This is a list, each call to org-occur pushes as cons cell,
9717 containing the regular expression and the callback, onto the list.
9718 The list can contain several entries if `org-occur' has been called
9719 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9720 will only contain one set of parameters. When the highlights are
9721 removed (for example with `C-c C-c', or with the next edit (depending
9722 on `org-remove-highlights-with-change'), this variable is emptied
9723 as well.")
9724 (make-variable-buffer-local 'org-occur-parameters)
9726 (defun org-occur (regexp &optional keep-previous callback)
9727 "Make a compact tree which shows all matches of REGEXP.
9728 The tree will show the lines where the regexp matches, and all higher
9729 headlines above the match. It will also show the heading after the match,
9730 to make sure editing the matching entry is easy.
9731 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9732 call to `org-occur' will be kept, to allow stacking of calls to this
9733 command.
9734 If CALLBACK is non-nil, it is a function which is called to confirm
9735 that the match should indeed be shown."
9736 (interactive "sRegexp: \nP")
9737 (unless keep-previous
9738 (org-remove-occur-highlights nil nil t))
9739 (push (cons regexp callback) org-occur-parameters)
9740 (let ((cnt 0))
9741 (save-excursion
9742 (goto-char (point-min))
9743 (if (or (not keep-previous) ; do not want to keep
9744 (not org-occur-highlights)) ; no previous matches
9745 ;; hide everything
9746 (org-overview))
9747 (while (re-search-forward regexp nil t)
9748 (when (or (not callback)
9749 (save-match-data (funcall callback)))
9750 (setq cnt (1+ cnt))
9751 (when org-highlight-sparse-tree-matches
9752 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9753 (org-show-context 'occur-tree))))
9754 (when org-remove-highlights-with-change
9755 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9756 nil 'local))
9757 (unless org-sparse-tree-open-archived-trees
9758 (org-hide-archived-subtrees (point-min) (point-max)))
9759 (run-hooks 'org-occur-hook)
9760 (if (interactive-p)
9761 (message "%d match(es) for regexp %s" cnt regexp))
9762 cnt))
9764 (defun org-show-context (&optional key)
9765 "Make sure point and context and visible.
9766 How much context is shown depends upon the variables
9767 `org-show-hierarchy-above', `org-show-following-heading'. and
9768 `org-show-siblings'."
9769 (let ((heading-p (org-on-heading-p t))
9770 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9771 (following-p (org-get-alist-option org-show-following-heading key))
9772 (entry-p (org-get-alist-option org-show-entry-below key))
9773 (siblings-p (org-get-alist-option org-show-siblings key)))
9774 (catch 'exit
9775 ;; Show heading or entry text
9776 (if (and heading-p (not entry-p))
9777 (org-flag-heading nil) ; only show the heading
9778 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9779 (org-show-hidden-entry))) ; show entire entry
9780 (when following-p
9781 ;; Show next sibling, or heading below text
9782 (save-excursion
9783 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9784 (org-flag-heading nil))))
9785 (when siblings-p (org-show-siblings))
9786 (when hierarchy-p
9787 ;; show all higher headings, possibly with siblings
9788 (save-excursion
9789 (while (and (condition-case nil
9790 (progn (org-up-heading-all 1) t)
9791 (error nil))
9792 (not (bobp)))
9793 (org-flag-heading nil)
9794 (when siblings-p (org-show-siblings))))))))
9796 (defun org-reveal (&optional siblings)
9797 "Show current entry, hierarchy above it, and the following headline.
9798 This can be used to show a consistent set of context around locations
9799 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9800 not t for the search context.
9802 With optional argument SIBLINGS, on each level of the hierarchy all
9803 siblings are shown. This repairs the tree structure to what it would
9804 look like when opened with hierarchical calls to `org-cycle'."
9805 (interactive "P")
9806 (let ((org-show-hierarchy-above t)
9807 (org-show-following-heading t)
9808 (org-show-siblings (if siblings t org-show-siblings)))
9809 (org-show-context nil)))
9811 (defun org-highlight-new-match (beg end)
9812 "Highlight from BEG to END and mark the highlight is an occur headline."
9813 (let ((ov (org-make-overlay beg end)))
9814 (org-overlay-put ov 'face 'secondary-selection)
9815 (push ov org-occur-highlights)))
9817 (defun org-remove-occur-highlights (&optional beg end noremove)
9818 "Remove the occur highlights from the buffer.
9819 BEG and END are ignored. If NOREMOVE is nil, remove this function
9820 from the `before-change-functions' in the current buffer."
9821 (interactive)
9822 (unless org-inhibit-highlight-removal
9823 (mapc 'org-delete-overlay org-occur-highlights)
9824 (setq org-occur-highlights nil)
9825 (setq org-occur-parameters nil)
9826 (unless noremove
9827 (remove-hook 'before-change-functions
9828 'org-remove-occur-highlights 'local))))
9830 ;;;; Priorities
9832 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9833 "Regular expression matching the priority indicator.")
9835 (defvar org-remove-priority-next-time nil)
9837 (defun org-priority-up ()
9838 "Increase the priority of the current item."
9839 (interactive)
9840 (org-priority 'up))
9842 (defun org-priority-down ()
9843 "Decrease the priority of the current item."
9844 (interactive)
9845 (org-priority 'down))
9847 (defun org-priority (&optional action)
9848 "Change the priority of an item by ARG.
9849 ACTION can be `set', `up', `down', or a character."
9850 (interactive)
9851 (setq action (or action 'set))
9852 (let (current new news have remove)
9853 (save-excursion
9854 (org-back-to-heading t)
9855 (if (looking-at org-priority-regexp)
9856 (setq current (string-to-char (match-string 2))
9857 have t)
9858 (setq current org-default-priority))
9859 (cond
9860 ((or (eq action 'set)
9861 (if (featurep 'xemacs) (characterp action) (integerp action)))
9862 (if (not (eq action 'set))
9863 (setq new action)
9864 (message "Priority %c-%c, SPC to remove: "
9865 org-highest-priority org-lowest-priority)
9866 (setq new (read-char-exclusive)))
9867 (if (and (= (upcase org-highest-priority) org-highest-priority)
9868 (= (upcase org-lowest-priority) org-lowest-priority))
9869 (setq new (upcase new)))
9870 (cond ((equal new ?\ ) (setq remove t))
9871 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9872 (error "Priority must be between `%c' and `%c'"
9873 org-highest-priority org-lowest-priority))))
9874 ((eq action 'up)
9875 (if (and (not have) (eq last-command this-command))
9876 (setq new org-lowest-priority)
9877 (setq new (if (and org-priority-start-cycle-with-default (not have))
9878 org-default-priority (1- current)))))
9879 ((eq action 'down)
9880 (if (and (not have) (eq last-command this-command))
9881 (setq new org-highest-priority)
9882 (setq new (if (and org-priority-start-cycle-with-default (not have))
9883 org-default-priority (1+ current)))))
9884 (t (error "Invalid action")))
9885 (if (or (< (upcase new) org-highest-priority)
9886 (> (upcase new) org-lowest-priority))
9887 (setq remove t))
9888 (setq news (format "%c" new))
9889 (if have
9890 (if remove
9891 (replace-match "" t t nil 1)
9892 (replace-match news t t nil 2))
9893 (if remove
9894 (error "No priority cookie found in line")
9895 (looking-at org-todo-line-regexp)
9896 (if (match-end 2)
9897 (progn
9898 (goto-char (match-end 2))
9899 (insert " [#" news "]"))
9900 (goto-char (match-beginning 3))
9901 (insert "[#" news "] ")))))
9902 (org-preserve-lc (org-set-tags nil 'align))
9903 (if remove
9904 (message "Priority removed")
9905 (message "Priority of current item set to %s" news))))
9908 (defun org-get-priority (s)
9909 "Find priority cookie and return priority."
9910 (save-match-data
9911 (if (not (string-match org-priority-regexp s))
9912 (* 1000 (- org-lowest-priority org-default-priority))
9913 (* 1000 (- org-lowest-priority
9914 (string-to-char (match-string 2 s)))))))
9916 ;;;; Tags
9918 (defvar org-agenda-archives-mode)
9919 (defvar org-scanner-tags nil
9920 "The current tag list while the tags scanner is running.")
9921 (defvar org-trust-scanner-tags nil
9922 "Should `org-get-tags-at' use the tags fro the scanner.
9923 This is for internal dynamical scoping only.
9924 When this is non-nil, the function `org-get-tags-at' will return the value
9925 of `org-scanner-tags' instead of building the list by itself. This
9926 can lead to large speed-ups when the tags scanner is used in a file with
9927 many entries, and when the list of tags is retrieved, for example to
9928 obtain a list of properties. Building the tags list for each entry in such
9929 a file becomes an N^2 operation - but with this variable set, it scales
9930 as N.")
9932 (defun org-scan-tags (action matcher &optional todo-only)
9933 "Scan headline tags with inheritance and produce output ACTION.
9935 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9936 or `agenda' to produce an entry list for an agenda view. It can also be
9937 a Lisp form or a function that should be called at each matched headline, in
9938 this case the return value is a list of all return values from these calls.
9940 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9941 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9942 only lines with a TODO keyword are included in the output."
9943 (require 'org-agenda)
9944 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9945 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9946 (org-re
9947 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9948 (props (list 'face 'default
9949 'done-face 'org-agenda-done
9950 'undone-face 'default
9951 'mouse-face 'highlight
9952 'org-not-done-regexp org-not-done-regexp
9953 'org-todo-regexp org-todo-regexp
9954 'keymap org-agenda-keymap
9955 'help-echo
9956 (format "mouse-2 or RET jump to org file %s"
9957 (abbreviate-file-name
9958 (or (buffer-file-name (buffer-base-buffer))
9959 (buffer-name (buffer-base-buffer)))))))
9960 (case-fold-search nil)
9961 lspos tags tags-list
9962 (tags-alist (list (cons 0 org-file-tags)))
9963 (llast 0) rtn rtn1 level category i txt
9964 todo marker entry priority)
9965 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9966 (setq action (list 'lambda nil action)))
9967 (save-excursion
9968 (goto-char (point-min))
9969 (when (eq action 'sparse-tree)
9970 (org-overview)
9971 (org-remove-occur-highlights))
9972 (while (re-search-forward re nil t)
9973 (catch :skip
9974 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
9975 tags (if (match-end 4) (org-match-string-no-properties 4)))
9976 (goto-char (setq lspos (1+ (match-beginning 0))))
9977 (setq level (org-reduced-level (funcall outline-level))
9978 category (org-get-category))
9979 (setq i llast llast level)
9980 ;; remove tag lists from same and sublevels
9981 (while (>= i level)
9982 (when (setq entry (assoc i tags-alist))
9983 (setq tags-alist (delete entry tags-alist)))
9984 (setq i (1- i)))
9985 ;; add the next tags
9986 (when tags
9987 (setq tags (org-split-string tags ":")
9988 tags-alist
9989 (cons (cons level tags) tags-alist)))
9990 ;; compile tags for current headline
9991 (setq tags-list
9992 (if org-use-tag-inheritance
9993 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9994 tags)
9995 org-scanner-tags tags-list)
9996 (when org-use-tag-inheritance
9997 (setcdr (car tags-alist)
9998 (mapcar (lambda (x)
9999 (setq x (copy-sequence x))
10000 (org-add-prop-inherited x))
10001 (cdar tags-alist))))
10002 (when (and tags org-use-tag-inheritance
10003 (or (not (eq t org-use-tag-inheritance))
10004 org-tags-exclude-from-inheritance))
10005 ;; selective inheritance, remove uninherited ones
10006 (setcdr (car tags-alist)
10007 (org-remove-uniherited-tags (cdar tags-alist))))
10008 (when (and (or (not todo-only)
10009 (and (member todo org-not-done-keywords)
10010 (or (not org-agenda-tags-todo-honor-ignore-options)
10011 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10012 (let ((case-fold-search t)) (eval matcher))
10014 (not (member org-archive-tag tags-list))
10015 ;; we have an archive tag, should we use this anyway?
10016 (or (not org-agenda-skip-archived-trees)
10017 (and (eq action 'agenda) org-agenda-archives-mode))))
10018 (unless (eq action 'sparse-tree) (org-agenda-skip))
10020 ;; select this headline
10022 (cond
10023 ((eq action 'sparse-tree)
10024 (and org-highlight-sparse-tree-matches
10025 (org-get-heading) (match-end 0)
10026 (org-highlight-new-match
10027 (match-beginning 0) (match-beginning 1)))
10028 (org-show-context 'tags-tree))
10029 ((eq action 'agenda)
10030 (setq txt (org-format-agenda-item
10032 (concat
10033 (if (eq org-tags-match-list-sublevels 'indented)
10034 (make-string (1- level) ?.) "")
10035 (org-get-heading))
10036 category
10037 tags-list
10039 priority (org-get-priority txt))
10040 (goto-char lspos)
10041 (setq marker (org-agenda-new-marker))
10042 (org-add-props txt props
10043 'org-marker marker 'org-hd-marker marker 'org-category category
10044 'todo-state todo
10045 'priority priority 'type "tagsmatch")
10046 (push txt rtn))
10047 ((functionp action)
10048 (save-excursion
10049 (setq rtn1 (funcall action))
10050 (push rtn1 rtn))
10051 (goto-char (point-at-eol)))
10052 (t (error "Invalid action")))
10054 ;; if we are to skip sublevels, jump to end of subtree
10055 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
10056 (when (and (eq action 'sparse-tree)
10057 (not org-sparse-tree-open-archived-trees))
10058 (org-hide-archived-subtrees (point-min) (point-max)))
10059 (nreverse rtn)))
10061 (defun org-remove-uniherited-tags (tags)
10062 "Remove all tags that are not inherited from the list TAGS."
10063 (cond
10064 ((eq org-use-tag-inheritance t)
10065 (if org-tags-exclude-from-inheritance
10066 (org-delete-all org-tags-exclude-from-inheritance tags)
10067 tags))
10068 ((not org-use-tag-inheritance) nil)
10069 ((stringp org-use-tag-inheritance)
10070 (delq nil (mapcar
10071 (lambda (x)
10072 (if (and (string-match org-use-tag-inheritance x)
10073 (not (member x org-tags-exclude-from-inheritance)))
10074 x nil))
10075 tags)))
10076 ((listp org-use-tag-inheritance)
10077 (delq nil (mapcar
10078 (lambda (x)
10079 (if (member x org-use-tag-inheritance) x nil))
10080 tags)))))
10082 (defvar todo-only) ;; dynamically scoped
10084 (defun org-match-sparse-tree (&optional todo-only match)
10085 "Create a sparse tree according to tags string MATCH.
10086 MATCH can contain positive and negative selection of tags, like
10087 \"+WORK+URGENT-WITHBOSS\".
10088 If optional argument TODO-ONLY is non-nil, only select lines that are
10089 also TODO lines."
10090 (interactive "P")
10091 (org-prepare-agenda-buffers (list (current-buffer)))
10092 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10094 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10096 (defvar org-cached-props nil)
10097 (defun org-cached-entry-get (pom property)
10098 (if (or (eq t org-use-property-inheritance)
10099 (and (stringp org-use-property-inheritance)
10100 (string-match org-use-property-inheritance property))
10101 (and (listp org-use-property-inheritance)
10102 (member property org-use-property-inheritance)))
10103 ;; Caching is not possible, check it directly
10104 (org-entry-get pom property 'inherit)
10105 ;; Get all properties, so that we can do complicated checks easily
10106 (cdr (assoc property (or org-cached-props
10107 (setq org-cached-props
10108 (org-entry-properties pom)))))))
10110 (defun org-global-tags-completion-table (&optional files)
10111 "Return the list of all tags in all agenda buffer/files."
10112 (save-excursion
10113 (org-uniquify
10114 (delq nil
10115 (apply 'append
10116 (mapcar
10117 (lambda (file)
10118 (set-buffer (find-file-noselect file))
10119 (append (org-get-buffer-tags)
10120 (mapcar (lambda (x) (if (stringp (car-safe x))
10121 (list (car-safe x)) nil))
10122 org-tag-alist)))
10123 (if (and files (car files))
10124 files
10125 (org-agenda-files))))))))
10127 (defun org-make-tags-matcher (match)
10128 "Create the TAGS//TODO matcher form for the selection string MATCH."
10129 ;; todo-only is scoped dynamically into this function, and the function
10130 ;; may change it if the matcher asks for it.
10131 (unless match
10132 ;; Get a new match request, with completion
10133 (let ((org-last-tags-completion-table
10134 (org-global-tags-completion-table)))
10135 (setq match (org-completing-read-no-ido
10136 "Match: " 'org-tags-completion-function nil nil nil
10137 'org-tags-history))))
10139 ;; Parse the string and create a lisp form
10140 (let ((match0 match)
10141 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10142 minus tag mm
10143 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10144 orterms term orlist re-p str-p level-p level-op time-p
10145 prop-p pn pv po cat-p gv rest)
10146 (if (string-match "/+" match)
10147 ;; match contains also a todo-matching request
10148 (progn
10149 (setq tagsmatch (substring match 0 (match-beginning 0))
10150 todomatch (substring match (match-end 0)))
10151 (if (string-match "^!" todomatch)
10152 (setq todo-only t todomatch (substring todomatch 1)))
10153 (if (string-match "^\\s-*$" todomatch)
10154 (setq todomatch nil)))
10155 ;; only matching tags
10156 (setq tagsmatch match todomatch nil))
10158 ;; Make the tags matcher
10159 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10160 (setq tagsmatcher t)
10161 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10162 (while (setq term (pop orterms))
10163 (while (and (equal (substring term -1) "\\") orterms)
10164 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10165 (while (string-match re term)
10166 (setq rest (substring term (match-end 0))
10167 minus (and (match-end 1)
10168 (equal (match-string 1 term) "-"))
10169 tag (match-string 2 term)
10170 re-p (equal (string-to-char tag) ?{)
10171 level-p (match-end 4)
10172 prop-p (match-end 5)
10173 mm (cond
10174 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10175 (level-p
10176 (setq level-op (org-op-to-function (match-string 3 term)))
10177 `(,level-op level ,(string-to-number
10178 (match-string 4 term))))
10179 (prop-p
10180 (setq pn (match-string 5 term)
10181 po (match-string 6 term)
10182 pv (match-string 7 term)
10183 cat-p (equal pn "CATEGORY")
10184 re-p (equal (string-to-char pv) ?{)
10185 str-p (equal (string-to-char pv) ?\")
10186 time-p (save-match-data
10187 (string-match "^\"[[<].*[]>]\"$" pv))
10188 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10189 (if time-p (setq pv (org-matcher-time pv)))
10190 (setq po (org-op-to-function po (if time-p 'time str-p)))
10191 (cond
10192 ((equal pn "CATEGORY")
10193 (setq gv '(get-text-property (point) 'org-category)))
10194 ((equal pn "TODO")
10195 (setq gv 'todo))
10197 (setq gv `(org-cached-entry-get nil ,pn))))
10198 (if re-p
10199 (if (eq po 'org<>)
10200 `(not (string-match ,pv (or ,gv "")))
10201 `(string-match ,pv (or ,gv "")))
10202 (if str-p
10203 `(,po (or ,gv "") ,pv)
10204 `(,po (string-to-number (or ,gv ""))
10205 ,(string-to-number pv) ))))
10206 (t `(member ,tag tags-list)))
10207 mm (if minus (list 'not mm) mm)
10208 term rest)
10209 (push mm tagsmatcher))
10210 (push (if (> (length tagsmatcher) 1)
10211 (cons 'and tagsmatcher)
10212 (car tagsmatcher))
10213 orlist)
10214 (setq tagsmatcher nil))
10215 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10216 (setq tagsmatcher
10217 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10218 ;; Make the todo matcher
10219 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10220 (setq todomatcher t)
10221 (setq orterms (org-split-string todomatch "|") orlist nil)
10222 (while (setq term (pop orterms))
10223 (while (string-match re term)
10224 (setq minus (and (match-end 1)
10225 (equal (match-string 1 term) "-"))
10226 kwd (match-string 2 term)
10227 re-p (equal (string-to-char kwd) ?{)
10228 term (substring term (match-end 0))
10229 mm (if re-p
10230 `(string-match ,(substring kwd 1 -1) todo)
10231 (list 'equal 'todo kwd))
10232 mm (if minus (list 'not mm) mm))
10233 (push mm todomatcher))
10234 (push (if (> (length todomatcher) 1)
10235 (cons 'and todomatcher)
10236 (car todomatcher))
10237 orlist)
10238 (setq todomatcher nil))
10239 (setq todomatcher (if (> (length orlist) 1)
10240 (cons 'or orlist) (car orlist))))
10242 ;; Return the string and lisp forms of the matcher
10243 (setq matcher (if todomatcher
10244 (list 'and tagsmatcher todomatcher)
10245 tagsmatcher))
10246 (cons match0 matcher)))
10248 (defun org-op-to-function (op &optional stringp)
10249 "Turn an operator into the appropriate function."
10250 (setq op
10251 (cond
10252 ((equal op "<" ) '(< string< org-time<))
10253 ((equal op ">" ) '(> org-string> org-time>))
10254 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10255 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10256 ((member op '("=" "==")) '(= string= org-time=))
10257 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10258 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10260 (defun org<> (a b) (not (= a b)))
10261 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10262 (defun org-string>= (a b) (not (string< a b)))
10263 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10264 (defun org-string<> (a b) (not (string= a b)))
10265 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10266 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10267 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10268 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10269 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10270 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10271 (defun org-2ft (s)
10272 "Convert S to a floating point time.
10273 If S is already a number, just return it. If it is a string, parse
10274 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10275 (cond
10276 ((numberp s) s)
10277 ((stringp s)
10278 (condition-case nil
10279 (float-time (apply 'encode-time (org-parse-time-string s)))
10280 (error 0.)))
10281 (t 0.)))
10283 (defun org-time-today ()
10284 "Time in seconds today at 0:00.
10285 Returns the float number of seconds since the beginning of the
10286 epoch to the beginning of today (00:00)."
10287 (float-time (apply 'encode-time
10288 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10290 (defun org-matcher-time (s)
10291 "Interpret a time comparison value."
10292 (save-match-data
10293 (cond
10294 ((string= s "<now>") (float-time))
10295 ((string= s "<today>") (org-time-today))
10296 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10297 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10298 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10299 (+ (org-time-today)
10300 (* (string-to-number (match-string 1 s))
10301 (cdr (assoc (match-string 2 s)
10302 '(("d" . 86400.0) ("w" . 604800.0)
10303 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10304 (t (org-2ft s)))))
10306 (defun org-match-any-p (re list)
10307 "Does re match any element of list?"
10308 (setq list (mapcar (lambda (x) (string-match re x)) list))
10309 (delq nil list))
10311 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10312 (defvar org-tags-overlay (org-make-overlay 1 1))
10313 (org-detach-overlay org-tags-overlay)
10315 (defun org-get-local-tags-at (&optional pos)
10316 "Get a list of tags defined in the current headline."
10317 (org-get-tags-at pos 'local))
10319 (defun org-get-local-tags ()
10320 "Get a list of tags defined in the current headline."
10321 (org-get-tags-at nil 'local))
10323 (defun org-get-tags-at (&optional pos local)
10324 "Get a list of all headline tags applicable at POS.
10325 POS defaults to point. If tags are inherited, the list contains
10326 the targets in the same sequence as the headlines appear, i.e.
10327 the tags of the current headline come last.
10328 When LOCAL is non-nil, only return tags from the current headline,
10329 ignore inherited ones."
10330 (interactive)
10331 (if (and org-trust-scanner-tags
10332 (or (not pos) (equal pos (point)))
10333 (not local))
10334 org-scanner-tags
10335 (let (tags ltags lastpos parent)
10336 (save-excursion
10337 (save-restriction
10338 (widen)
10339 (goto-char (or pos (point)))
10340 (save-match-data
10341 (catch 'done
10342 (condition-case nil
10343 (progn
10344 (org-back-to-heading t)
10345 (while (not (equal lastpos (point)))
10346 (setq lastpos (point))
10347 (when (looking-at
10348 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10349 (setq ltags (org-split-string
10350 (org-match-string-no-properties 1) ":"))
10351 (when parent
10352 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10353 (setq tags (append
10354 (if parent
10355 (org-remove-uniherited-tags ltags)
10356 ltags)
10357 tags)))
10358 (or org-use-tag-inheritance (throw 'done t))
10359 (if local (throw 'done t))
10360 (org-up-heading-all 1)
10361 (setq parent t)))
10362 (error nil)))))
10363 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10365 (defun org-add-prop-inherited (s)
10366 (add-text-properties 0 (length s) '(inherited t) s)
10369 (defun org-toggle-tag (tag &optional onoff)
10370 "Toggle the tag TAG for the current line.
10371 If ONOFF is `on' or `off', don't toggle but set to this state."
10372 (let (res current)
10373 (save-excursion
10374 (org-back-to-heading t)
10375 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10376 (point-at-eol) t)
10377 (progn
10378 (setq current (match-string 1))
10379 (replace-match ""))
10380 (setq current ""))
10381 (setq current (nreverse (org-split-string current ":")))
10382 (cond
10383 ((eq onoff 'on)
10384 (setq res t)
10385 (or (member tag current) (push tag current)))
10386 ((eq onoff 'off)
10387 (or (not (member tag current)) (setq current (delete tag current))))
10388 (t (if (member tag current)
10389 (setq current (delete tag current))
10390 (setq res t)
10391 (push tag current))))
10392 (end-of-line 1)
10393 (if current
10394 (progn
10395 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10396 (org-set-tags nil t))
10397 (delete-horizontal-space))
10398 (run-hooks 'org-after-tags-change-hook))
10399 res))
10401 (defun org-align-tags-here (to-col)
10402 ;; Assumes that this is a headline
10403 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10404 (beginning-of-line 1)
10405 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10406 (< pos (match-beginning 2)))
10407 (progn
10408 (setq tags-l (- (match-end 2) (match-beginning 2)))
10409 (goto-char (match-beginning 1))
10410 (insert " ")
10411 (delete-region (point) (1+ (match-beginning 2)))
10412 (setq ncol (max (1+ (current-column))
10413 (1+ col)
10414 (if (> to-col 0)
10415 to-col
10416 (- (abs to-col) tags-l))))
10417 (setq p (point))
10418 (insert (make-string (- ncol (current-column)) ?\ ))
10419 (setq ncol (current-column))
10420 (when indent-tabs-mode (tabify p (point-at-eol)))
10421 (org-move-to-column (min ncol col) t))
10422 (goto-char pos))))
10424 (defun org-set-tags-command (&optional arg just-align)
10425 "Call the set-tags command for the current entry."
10426 (interactive "P")
10427 (if (org-on-heading-p)
10428 (org-set-tags arg just-align)
10429 (save-excursion
10430 (org-back-to-heading t)
10431 (org-set-tags arg just-align))))
10433 (defun org-set-tags (&optional arg just-align)
10434 "Set the tags for the current headline.
10435 With prefix ARG, realign all tags in headings in the current buffer."
10436 (interactive "P")
10437 (let* ((re (concat "^" outline-regexp))
10438 (current (org-get-tags-string))
10439 (col (current-column))
10440 (org-setting-tags t)
10441 table current-tags inherited-tags ; computed below when needed
10442 tags p0 c0 c1 rpl)
10443 (if arg
10444 (save-excursion
10445 (goto-char (point-min))
10446 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10447 (while (re-search-forward re nil t)
10448 (org-set-tags nil t)
10449 (end-of-line 1)))
10450 (message "All tags realigned to column %d" org-tags-column))
10451 (if just-align
10452 (setq tags current)
10453 ;; Get a new set of tags from the user
10454 (save-excursion
10455 (setq table (append org-tag-persistent-alist
10456 (or org-tag-alist (org-get-buffer-tags)))
10457 org-last-tags-completion-table table
10458 current-tags (org-split-string current ":")
10459 inherited-tags (nreverse
10460 (nthcdr (length current-tags)
10461 (nreverse (org-get-tags-at))))
10462 tags
10463 (if (or (eq t org-use-fast-tag-selection)
10464 (and org-use-fast-tag-selection
10465 (delq nil (mapcar 'cdr table))))
10466 (org-fast-tag-selection
10467 current-tags inherited-tags table
10468 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10469 (let ((org-add-colon-after-tag-completion t))
10470 (org-trim
10471 (org-without-partial-completion
10472 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10473 nil nil current 'org-tags-history)))))))
10474 (while (string-match "[-+&]+" tags)
10475 ;; No boolean logic, just a list
10476 (setq tags (replace-match ":" t t tags))))
10478 (if (string-match "\\`[\t ]*\\'" tags)
10479 (setq tags "")
10480 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10481 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10483 ;; Insert new tags at the correct column
10484 (beginning-of-line 1)
10485 (cond
10486 ((and (equal current "") (equal tags "")))
10487 ((re-search-forward
10488 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10489 (point-at-eol) t)
10490 (if (equal tags "")
10491 (setq rpl "")
10492 (goto-char (match-beginning 0))
10493 (setq c0 (current-column) p0 (point)
10494 c1 (max (1+ c0) (if (> org-tags-column 0)
10495 org-tags-column
10496 (- (- org-tags-column) (length tags))))
10497 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10498 (replace-match rpl t t)
10499 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10500 tags)
10501 (t (error "Tags alignment failed")))
10502 (org-move-to-column col)
10503 (unless just-align
10504 (run-hooks 'org-after-tags-change-hook)))))
10506 (defun org-change-tag-in-region (beg end tag off)
10507 "Add or remove TAG for each entry in the region.
10508 This works in the agenda, and also in an org-mode buffer."
10509 (interactive
10510 (list (region-beginning) (region-end)
10511 (let ((org-last-tags-completion-table
10512 (if (org-mode-p)
10513 (org-get-buffer-tags)
10514 (org-global-tags-completion-table))))
10515 (org-ido-completing-read
10516 "Tag: " 'org-tags-completion-function nil nil nil
10517 'org-tags-history))
10518 (progn
10519 (message "[s]et or [r]emove? ")
10520 (equal (read-char-exclusive) ?r))))
10521 (if (fboundp 'deactivate-mark) (deactivate-mark))
10522 (let ((agendap (equal major-mode 'org-agenda-mode))
10523 l1 l2 m buf pos newhead (cnt 0))
10524 (goto-char end)
10525 (setq l2 (1- (org-current-line)))
10526 (goto-char beg)
10527 (setq l1 (org-current-line))
10528 (loop for l from l1 to l2 do
10529 (goto-line l)
10530 (setq m (get-text-property (point) 'org-hd-marker))
10531 (when (or (and (org-mode-p) (org-on-heading-p))
10532 (and agendap m))
10533 (setq buf (if agendap (marker-buffer m) (current-buffer))
10534 pos (if agendap m (point)))
10535 (with-current-buffer buf
10536 (save-excursion
10537 (save-restriction
10538 (goto-char pos)
10539 (setq cnt (1+ cnt))
10540 (org-toggle-tag tag (if off 'off 'on))
10541 (setq newhead (org-get-heading)))))
10542 (and agendap (org-agenda-change-all-lines newhead m))))
10543 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10545 (defun org-tags-completion-function (string predicate &optional flag)
10546 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10547 (confirm (lambda (x) (stringp (car x)))))
10548 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10549 (setq s1 (match-string 1 string)
10550 s2 (match-string 2 string))
10551 (setq s1 "" s2 string))
10552 (cond
10553 ((eq flag nil)
10554 ;; try completion
10555 (setq rtn (try-completion s2 ctable confirm))
10556 (if (stringp rtn)
10557 (setq rtn
10558 (concat s1 s2 (substring rtn (length s2))
10559 (if (and org-add-colon-after-tag-completion
10560 (assoc rtn ctable))
10561 ":" ""))))
10562 rtn)
10563 ((eq flag t)
10564 ;; all-completions
10565 (all-completions s2 ctable confirm)
10567 ((eq flag 'lambda)
10568 ;; exact match?
10569 (assoc s2 ctable)))
10572 (defun org-fast-tag-insert (kwd tags face &optional end)
10573 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10574 (insert (format "%-12s" (concat kwd ":"))
10575 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10576 (or end "")))
10578 (defun org-fast-tag-show-exit (flag)
10579 (save-excursion
10580 (goto-line 3)
10581 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10582 (replace-match ""))
10583 (when flag
10584 (end-of-line 1)
10585 (org-move-to-column (- (window-width) 19) t)
10586 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10588 (defun org-set-current-tags-overlay (current prefix)
10589 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10590 (if (featurep 'xemacs)
10591 (org-overlay-display org-tags-overlay (concat prefix s)
10592 'secondary-selection)
10593 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10594 (org-overlay-display org-tags-overlay (concat prefix s)))))
10596 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10597 "Fast tag selection with single keys.
10598 CURRENT is the current list of tags in the headline, INHERITED is the
10599 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10600 possibly with grouping information. TODO-TABLE is a similar table with
10601 TODO keywords, should these have keys assigned to them.
10602 If the keys are nil, a-z are automatically assigned.
10603 Returns the new tags string, or nil to not change the current settings."
10604 (let* ((fulltable (append table todo-table))
10605 (maxlen (apply 'max (mapcar
10606 (lambda (x)
10607 (if (stringp (car x)) (string-width (car x)) 0))
10608 fulltable)))
10609 (buf (current-buffer))
10610 (expert (eq org-fast-tag-selection-single-key 'expert))
10611 (buffer-tags nil)
10612 (fwidth (+ maxlen 3 1 3))
10613 (ncol (/ (- (window-width) 4) fwidth))
10614 (i-face 'org-done)
10615 (c-face 'org-todo)
10616 tg cnt e c char c1 c2 ntable tbl rtn
10617 ov-start ov-end ov-prefix
10618 (exit-after-next org-fast-tag-selection-single-key)
10619 (done-keywords org-done-keywords)
10620 groups ingroup)
10621 (save-excursion
10622 (beginning-of-line 1)
10623 (if (looking-at
10624 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10625 (setq ov-start (match-beginning 1)
10626 ov-end (match-end 1)
10627 ov-prefix "")
10628 (setq ov-start (1- (point-at-eol))
10629 ov-end (1+ ov-start))
10630 (skip-chars-forward "^\n\r")
10631 (setq ov-prefix
10632 (concat
10633 (buffer-substring (1- (point)) (point))
10634 (if (> (current-column) org-tags-column)
10636 (make-string (- org-tags-column (current-column)) ?\ ))))))
10637 (org-move-overlay org-tags-overlay ov-start ov-end)
10638 (save-window-excursion
10639 (if expert
10640 (set-buffer (get-buffer-create " *Org tags*"))
10641 (delete-other-windows)
10642 (split-window-vertically)
10643 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10644 (erase-buffer)
10645 (org-set-local 'org-done-keywords done-keywords)
10646 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10647 (org-fast-tag-insert "Current" current c-face "\n\n")
10648 (org-fast-tag-show-exit exit-after-next)
10649 (org-set-current-tags-overlay current ov-prefix)
10650 (setq tbl fulltable char ?a cnt 0)
10651 (while (setq e (pop tbl))
10652 (cond
10653 ((equal e '(:startgroup))
10654 (push '() groups) (setq ingroup t)
10655 (when (not (= cnt 0))
10656 (setq cnt 0)
10657 (insert "\n"))
10658 (insert "{ "))
10659 ((equal e '(:endgroup))
10660 (setq ingroup nil cnt 0)
10661 (insert "}\n"))
10662 ((equal e '(:newline))
10663 (when (not (= cnt 0))
10664 (setq cnt 0)
10665 (insert "\n")
10666 (setq e (car tbl))
10667 (while (equal (car tbl) '(:newline))
10668 (insert "\n")
10669 (setq tbl (cdr tbl)))))
10671 (setq tg (car e) c2 nil)
10672 (if (cdr e)
10673 (setq c (cdr e))
10674 ;; automatically assign a character.
10675 (setq c1 (string-to-char
10676 (downcase (substring
10677 tg (if (= (string-to-char tg) ?@) 1 0)))))
10678 (if (or (rassoc c1 ntable) (rassoc c1 table))
10679 (while (or (rassoc char ntable) (rassoc char table))
10680 (setq char (1+ char)))
10681 (setq c2 c1))
10682 (setq c (or c2 char)))
10683 (if ingroup (push tg (car groups)))
10684 (setq tg (org-add-props tg nil 'face
10685 (cond
10686 ((not (assoc tg table))
10687 (org-get-todo-face tg))
10688 ((member tg current) c-face)
10689 ((member tg inherited) i-face)
10690 (t nil))))
10691 (if (and (= cnt 0) (not ingroup)) (insert " "))
10692 (insert "[" c "] " tg (make-string
10693 (- fwidth 4 (length tg)) ?\ ))
10694 (push (cons tg c) ntable)
10695 (when (= (setq cnt (1+ cnt)) ncol)
10696 (insert "\n")
10697 (if ingroup (insert " "))
10698 (setq cnt 0)))))
10699 (setq ntable (nreverse ntable))
10700 (insert "\n")
10701 (goto-char (point-min))
10702 (if (not expert) (org-fit-window-to-buffer))
10703 (setq rtn
10704 (catch 'exit
10705 (while t
10706 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10707 (if groups " [!] no groups" " [!]groups")
10708 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10709 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10710 (cond
10711 ((= c ?\r) (throw 'exit t))
10712 ((= c ?!)
10713 (setq groups (not groups))
10714 (goto-char (point-min))
10715 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10716 ((= c ?\C-c)
10717 (if (not expert)
10718 (org-fast-tag-show-exit
10719 (setq exit-after-next (not exit-after-next)))
10720 (setq expert nil)
10721 (delete-other-windows)
10722 (split-window-vertically)
10723 (org-switch-to-buffer-other-window " *Org tags*")
10724 (org-fit-window-to-buffer)))
10725 ((or (= c ?\C-g)
10726 (and (= c ?q) (not (rassoc c ntable))))
10727 (org-detach-overlay org-tags-overlay)
10728 (setq quit-flag t))
10729 ((= c ?\ )
10730 (setq current nil)
10731 (if exit-after-next (setq exit-after-next 'now)))
10732 ((= c ?\t)
10733 (condition-case nil
10734 (setq tg (org-ido-completing-read
10735 "Tag: "
10736 (or buffer-tags
10737 (with-current-buffer buf
10738 (org-get-buffer-tags)))))
10739 (quit (setq tg "")))
10740 (when (string-match "\\S-" tg)
10741 (add-to-list 'buffer-tags (list tg))
10742 (if (member tg current)
10743 (setq current (delete tg current))
10744 (push tg current)))
10745 (if exit-after-next (setq exit-after-next 'now)))
10746 ((setq e (rassoc c todo-table) tg (car e))
10747 (with-current-buffer buf
10748 (save-excursion (org-todo tg)))
10749 (if exit-after-next (setq exit-after-next 'now)))
10750 ((setq e (rassoc c ntable) tg (car e))
10751 (if (member tg current)
10752 (setq current (delete tg current))
10753 (loop for g in groups do
10754 (if (member tg g)
10755 (mapc (lambda (x)
10756 (setq current (delete x current)))
10757 g)))
10758 (push tg current))
10759 (if exit-after-next (setq exit-after-next 'now))))
10761 ;; Create a sorted list
10762 (setq current
10763 (sort current
10764 (lambda (a b)
10765 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10766 (if (eq exit-after-next 'now) (throw 'exit t))
10767 (goto-char (point-min))
10768 (beginning-of-line 2)
10769 (delete-region (point) (point-at-eol))
10770 (org-fast-tag-insert "Current" current c-face)
10771 (org-set-current-tags-overlay current ov-prefix)
10772 (while (re-search-forward
10773 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10774 (setq tg (match-string 1))
10775 (add-text-properties
10776 (match-beginning 1) (match-end 1)
10777 (list 'face
10778 (cond
10779 ((member tg current) c-face)
10780 ((member tg inherited) i-face)
10781 (t (get-text-property (match-beginning 1) 'face))))))
10782 (goto-char (point-min)))))
10783 (org-detach-overlay org-tags-overlay)
10784 (if rtn
10785 (mapconcat 'identity current ":")
10786 nil))))
10788 (defun org-get-tags-string ()
10789 "Get the TAGS string in the current headline."
10790 (unless (org-on-heading-p t)
10791 (error "Not on a heading"))
10792 (save-excursion
10793 (beginning-of-line 1)
10794 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10795 (org-match-string-no-properties 1)
10796 "")))
10798 (defun org-get-tags ()
10799 "Get the list of tags specified in the current headline."
10800 (org-split-string (org-get-tags-string) ":"))
10802 (defun org-get-buffer-tags ()
10803 "Get a table of all tags used in the buffer, for completion."
10804 (let (tags)
10805 (save-excursion
10806 (goto-char (point-min))
10807 (while (re-search-forward
10808 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10809 (when (equal (char-after (point-at-bol 0)) ?*)
10810 (mapc (lambda (x) (add-to-list 'tags x))
10811 (org-split-string (org-match-string-no-properties 1) ":")))))
10812 (mapcar 'list tags)))
10814 ;;;; The mapping API
10816 ;;;###autoload
10817 (defun org-map-entries (func &optional match scope &rest skip)
10818 "Call FUNC at each headline selected by MATCH in SCOPE.
10820 FUNC is a function or a lisp form. The function will be called without
10821 arguments, with the cursor positioned at the beginning of the headline.
10822 The return values of all calls to the function will be collected and
10823 returned as a list.
10825 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10826 Only headlines that are matched by this query will be considered during
10827 the iteration. When MATCH is nil or t, all headlines will be
10828 visited by the iteration.
10830 SCOPE determines the scope of this command. It can be any of:
10832 nil The current buffer, respecting the restriction if any
10833 tree The subtree started with the entry at point
10834 file The current buffer, without restriction
10835 file-with-archives
10836 The current buffer, and any archives associated with it
10837 agenda All agenda files
10838 agenda-with-archives
10839 All agenda files with any archive files associated with them
10840 \(file1 file2 ...)
10841 If this is a list, all files in the list will be scanned
10843 The remaining args are treated as settings for the skipping facilities of
10844 the scanner. The following items can be given here:
10846 archive skip trees with the archive tag.
10847 comment skip trees with the COMMENT keyword
10848 function or Emacs Lisp form:
10849 will be used as value for `org-agenda-skip-function', so whenever
10850 the the function returns t, FUNC will not be called for that
10851 entry and search will continue from the point where the
10852 function leaves it.
10854 If your function needs to retrieve the tags including inherited tags
10855 at the *current* entry, you can use the value of the variable
10856 `org-scanner-tags' which will be much faster than getting the value
10857 with `org-get-tags-at'. If your function gets properties with
10858 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
10859 to t around the call to `org-entry-properties' to get the same speedup.
10860 Note that if your function moves around to retrieve tags and properties at
10861 a *different* entry, you cannot use these techniques."
10862 (let* ((org-agenda-archives-mode nil) ; just to make sure
10863 (org-agenda-skip-archived-trees (memq 'archive skip))
10864 (org-agenda-skip-comment-trees (memq 'comment skip))
10865 (org-agenda-skip-function
10866 (car (org-delete-all '(comment archive) skip)))
10867 (org-tags-match-list-sublevels t)
10868 matcher file res
10869 org-todo-keywords-for-agenda
10870 org-done-keywords-for-agenda
10871 org-todo-keyword-alist-for-agenda
10872 org-tag-alist-for-agenda)
10874 (cond
10875 ((eq match t) (setq matcher t))
10876 ((eq match nil) (setq matcher t))
10877 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10879 (save-excursion
10880 (save-restriction
10881 (when (eq scope 'tree)
10882 (org-back-to-heading t)
10883 (org-narrow-to-subtree)
10884 (setq scope nil))
10886 (if (not scope)
10887 (progn
10888 (org-prepare-agenda-buffers
10889 (list (buffer-file-name (current-buffer))))
10890 (setq res (org-scan-tags func matcher)))
10891 ;; Get the right scope
10892 (cond
10893 ((and scope (listp scope) (symbolp (car scope)))
10894 (setq scope (eval scope)))
10895 ((eq scope 'agenda)
10896 (setq scope (org-agenda-files t)))
10897 ((eq scope 'agenda-with-archives)
10898 (setq scope (org-agenda-files t))
10899 (setq scope (org-add-archive-files scope)))
10900 ((eq scope 'file)
10901 (setq scope (list (buffer-file-name))))
10902 ((eq scope 'file-with-archives)
10903 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10904 (org-prepare-agenda-buffers scope)
10905 (while (setq file (pop scope))
10906 (with-current-buffer (org-find-base-buffer-visiting file)
10907 (save-excursion
10908 (save-restriction
10909 (widen)
10910 (goto-char (point-min))
10911 (setq res (append res (org-scan-tags func matcher))))))))))
10912 res))
10914 ;;;; Properties
10916 ;;; Setting and retrieving properties
10918 (defconst org-special-properties
10919 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10920 "TIMESTAMP" "TIMESTAMP_IA")
10921 "The special properties valid in Org-mode.
10923 These are properties that are not defined in the property drawer,
10924 but in some other way.")
10926 (defconst org-default-properties
10927 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10928 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10929 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10930 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10931 "Some properties that are used by Org-mode for various purposes.
10932 Being in this list makes sure that they are offered for completion.")
10934 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10935 "Regular expression matching the first line of a property drawer.")
10937 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10938 "Regular expression matching the first line of a property drawer.")
10940 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10941 "Regular expression matching the first line of a property drawer.")
10943 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10944 "Regular expression matching the first line of a property drawer.")
10946 (defconst org-property-drawer-re
10947 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10948 org-property-end-re "\\)\n?")
10949 "Matches an entire property drawer.")
10951 (defconst org-clock-drawer-re
10952 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10953 org-property-end-re "\\)\n?")
10954 "Matches an entire clock drawer.")
10956 (defun org-property-action ()
10957 "Do an action on properties."
10958 (interactive)
10959 (let (c)
10960 (org-at-property-p)
10961 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10962 (setq c (read-char-exclusive))
10963 (cond
10964 ((equal c ?s)
10965 (call-interactively 'org-set-property))
10966 ((equal c ?d)
10967 (call-interactively 'org-delete-property))
10968 ((equal c ?D)
10969 (call-interactively 'org-delete-property-globally))
10970 ((equal c ?c)
10971 (call-interactively 'org-compute-property-at-point))
10972 (t (error "No such property action %c" c)))))
10974 (defun org-at-property-p ()
10975 "Is the cursor in a property line?"
10976 ;; FIXME: Does not check if we are actually in the drawer.
10977 ;; FIXME: also returns true on any drawers.....
10978 ;; This is used by C-c C-c for property action.
10979 (save-excursion
10980 (beginning-of-line 1)
10981 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10983 (defun org-get-property-block (&optional beg end force)
10984 "Return the (beg . end) range of the body of the property drawer.
10985 BEG and END can be beginning and end of subtree, if not given
10986 they will be found.
10987 If the drawer does not exist and FORCE is non-nil, create the drawer."
10988 (catch 'exit
10989 (save-excursion
10990 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10991 (end (or end (progn (outline-next-heading) (point)))))
10992 (goto-char beg)
10993 (if (re-search-forward org-property-start-re end t)
10994 (setq beg (1+ (match-end 0)))
10995 (if force
10996 (save-excursion
10997 (org-insert-property-drawer)
10998 (setq end (progn (outline-next-heading) (point))))
10999 (throw 'exit nil))
11000 (goto-char beg)
11001 (if (re-search-forward org-property-start-re end t)
11002 (setq beg (1+ (match-end 0)))))
11003 (if (re-search-forward org-property-end-re end t)
11004 (setq end (match-beginning 0))
11005 (or force (throw 'exit nil))
11006 (goto-char beg)
11007 (setq end beg)
11008 (org-indent-line-function)
11009 (insert ":END:\n"))
11010 (cons beg end)))))
11012 (defun org-entry-properties (&optional pom which)
11013 "Get all properties of the entry at point-or-marker POM.
11014 This includes the TODO keyword, the tags, time strings for deadline,
11015 scheduled, and clocking, and any additional properties defined in the
11016 entry. The return value is an alist, keys may occur multiple times
11017 if the property key was used several times.
11018 POM may also be nil, in which case the current entry is used.
11019 If WHICH is nil or `all', get all properties. If WHICH is
11020 `special' or `standard', only get that subclass."
11021 (setq which (or which 'all))
11022 (org-with-point-at pom
11023 (let ((clockstr (substring org-clock-string 0 -1))
11024 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11025 beg end range props sum-props key value string clocksum)
11026 (save-excursion
11027 (when (condition-case nil
11028 (and (org-mode-p) (org-back-to-heading t))
11029 (error nil))
11030 (setq beg (point))
11031 (setq sum-props (get-text-property (point) 'org-summaries))
11032 (setq clocksum (get-text-property (point) :org-clock-minutes))
11033 (outline-next-heading)
11034 (setq end (point))
11035 (when (memq which '(all special))
11036 ;; Get the special properties, like TODO and tags
11037 (goto-char beg)
11038 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11039 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11040 (when (looking-at org-priority-regexp)
11041 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11042 (when (and (setq value (org-get-tags-string))
11043 (string-match "\\S-" value))
11044 (push (cons "TAGS" value) props))
11045 (when (setq value (org-get-tags-at))
11046 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11047 props))
11048 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11049 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11050 string (if (equal key clockstr)
11051 (org-no-properties
11052 (org-trim
11053 (buffer-substring
11054 (match-beginning 3) (goto-char (point-at-eol)))))
11055 (substring (org-match-string-no-properties 3) 1 -1)))
11056 (unless key
11057 (if (= (char-after (match-beginning 3)) ?\[)
11058 (setq key "TIMESTAMP_IA")
11059 (setq key "TIMESTAMP")))
11060 (when (or (equal key clockstr) (not (assoc key props)))
11061 (push (cons key string) props)))
11065 (when (memq which '(all standard))
11066 ;; Get the standard properties, like :PROP: ...
11067 (setq range (org-get-property-block beg end))
11068 (when range
11069 (goto-char (car range))
11070 (while (re-search-forward
11071 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11072 (cdr range) t)
11073 (setq key (org-match-string-no-properties 1)
11074 value (org-trim (or (org-match-string-no-properties 2) "")))
11075 (unless (member key excluded)
11076 (push (cons key (or value "")) props)))))
11077 (if clocksum
11078 (push (cons "CLOCKSUM"
11079 (org-columns-number-to-string (/ (float clocksum) 60.)
11080 'add_times))
11081 props))
11082 (unless (assoc "CATEGORY" props)
11083 (setq value (or (org-get-category)
11084 (progn (org-refresh-category-properties)
11085 (org-get-category))))
11086 (push (cons "CATEGORY" value) props))
11087 (append sum-props (nreverse props)))))))
11089 (defun org-entry-get (pom property &optional inherit)
11090 "Get value of PROPERTY for entry at point-or-marker POM.
11091 If INHERIT is non-nil and the entry does not have the property,
11092 then also check higher levels of the hierarchy.
11093 If INHERIT is the symbol `selective', use inheritance only if the setting
11094 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11095 If the property is present but empty, the return value is the empty string.
11096 If the property is not present at all, nil is returned."
11097 (org-with-point-at pom
11098 (if (and inherit (if (eq inherit 'selective)
11099 (org-property-inherit-p property)
11101 (org-entry-get-with-inheritance property)
11102 (if (member property org-special-properties)
11103 ;; We need a special property. Use brute force, get all properties.
11104 (cdr (assoc property (org-entry-properties nil 'special)))
11105 (let ((range (org-get-property-block)))
11106 (if (and range
11107 (goto-char (car range))
11108 (re-search-forward
11109 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11110 (cdr range) t))
11111 ;; Found the property, return it.
11112 (if (match-end 1)
11113 (org-match-string-no-properties 1)
11114 "")))))))
11116 (defun org-property-or-variable-value (var &optional inherit)
11117 "Check if there is a property fixing the value of VAR.
11118 If yes, return this value. If not, return the current value of the variable."
11119 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11120 (if (and prop (stringp prop) (string-match "\\S-" prop))
11121 (read prop)
11122 (symbol-value var))))
11124 (defun org-entry-delete (pom property)
11125 "Delete the property PROPERTY from entry at point-or-marker POM."
11126 (org-with-point-at pom
11127 (if (member property org-special-properties)
11128 nil ; cannot delete these properties.
11129 (let ((range (org-get-property-block)))
11130 (if (and range
11131 (goto-char (car range))
11132 (re-search-forward
11133 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11134 (cdr range) t))
11135 (progn
11136 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11138 nil)))))
11140 ;; Multi-values properties are properties that contain multiple values
11141 ;; These values are assumed to be single words, separated by whitespace.
11142 (defun org-entry-add-to-multivalued-property (pom property value)
11143 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11144 (let* ((old (org-entry-get pom property))
11145 (values (and old (org-split-string old "[ \t]"))))
11146 (setq value (org-entry-protect-space value))
11147 (unless (member value values)
11148 (setq values (cons value values))
11149 (org-entry-put pom property
11150 (mapconcat 'identity values " ")))))
11152 (defun org-entry-remove-from-multivalued-property (pom property value)
11153 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11154 (let* ((old (org-entry-get pom property))
11155 (values (and old (org-split-string old "[ \t]"))))
11156 (setq value (org-entry-protect-space value))
11157 (when (member value values)
11158 (setq values (delete value values))
11159 (org-entry-put pom property
11160 (mapconcat 'identity values " ")))))
11162 (defun org-entry-member-in-multivalued-property (pom property value)
11163 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11164 (let* ((old (org-entry-get pom property))
11165 (values (and old (org-split-string old "[ \t]"))))
11166 (setq value (org-entry-protect-space value))
11167 (member value values)))
11169 (defun org-entry-get-multivalued-property (pom property)
11170 "Return a list of values in a multivalued property."
11171 (let* ((value (org-entry-get pom property))
11172 (values (and value (org-split-string value "[ \t]"))))
11173 (mapcar 'org-entry-restore-space values)))
11175 (defun org-entry-put-multivalued-property (pom property &rest values)
11176 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11177 VALUES should be a list of strings. Spaces will be protected."
11178 (org-entry-put pom property
11179 (mapconcat 'org-entry-protect-space values " "))
11180 (let* ((value (org-entry-get pom property))
11181 (values (and value (org-split-string value "[ \t]"))))
11182 (mapcar 'org-entry-restore-space values)))
11184 (defun org-entry-protect-space (s)
11185 "Protect spaces and newline in string S."
11186 (while (string-match " " s)
11187 (setq s (replace-match "%20" t t s)))
11188 (while (string-match "\n" s)
11189 (setq s (replace-match "%0A" t t s)))
11192 (defun org-entry-restore-space (s)
11193 "Restore spaces and newline in string S."
11194 (while (string-match "%20" s)
11195 (setq s (replace-match " " t t s)))
11196 (while (string-match "%0A" s)
11197 (setq s (replace-match "\n" t t s)))
11200 (defvar org-entry-property-inherited-from (make-marker)
11201 "Marker pointing to the entry from where a property was inherited.
11202 Each call to `org-entry-get-with-inheritance' will set this marker to the
11203 location of the entry where the inheritance search matched. If there was
11204 no match, the marker will point nowhere.
11205 Note that also `org-entry-get' calls this function, if the INHERIT flag
11206 is set.")
11208 (defun org-entry-get-with-inheritance (property)
11209 "Get entry property, and search higher levels if not present."
11210 (move-marker org-entry-property-inherited-from nil)
11211 (let (tmp)
11212 (save-excursion
11213 (save-restriction
11214 (widen)
11215 (catch 'ex
11216 (while t
11217 (when (setq tmp (org-entry-get nil property))
11218 (org-back-to-heading t)
11219 (move-marker org-entry-property-inherited-from (point))
11220 (throw 'ex tmp))
11221 (or (org-up-heading-safe) (throw 'ex nil)))))
11222 (or tmp
11223 (cdr (assoc property org-file-properties))
11224 (cdr (assoc property org-global-properties))
11225 (cdr (assoc property org-global-properties-fixed))))))
11227 (defun org-entry-put (pom property value)
11228 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11229 (org-with-point-at pom
11230 (org-back-to-heading t)
11231 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11232 range)
11233 (cond
11234 ((equal property "TODO")
11235 (when (and (stringp value) (string-match "\\S-" value)
11236 (not (member value org-todo-keywords-1)))
11237 (error "\"%s\" is not a valid TODO state" value))
11238 (if (or (not value)
11239 (not (string-match "\\S-" value)))
11240 (setq value 'none))
11241 (org-todo value)
11242 (org-set-tags nil 'align))
11243 ((equal property "PRIORITY")
11244 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11245 (string-to-char value) ?\ ))
11246 (org-set-tags nil 'align))
11247 ((equal property "SCHEDULED")
11248 (if (re-search-forward org-scheduled-time-regexp end t)
11249 (cond
11250 ((eq value 'earlier) (org-timestamp-change -1 'day))
11251 ((eq value 'later) (org-timestamp-change 1 'day))
11252 (t (call-interactively 'org-schedule)))
11253 (call-interactively 'org-schedule)))
11254 ((equal property "DEADLINE")
11255 (if (re-search-forward org-deadline-time-regexp end t)
11256 (cond
11257 ((eq value 'earlier) (org-timestamp-change -1 'day))
11258 ((eq value 'later) (org-timestamp-change 1 'day))
11259 (t (call-interactively 'org-deadline)))
11260 (call-interactively 'org-deadline)))
11261 ((member property org-special-properties)
11262 (error "The %s property can not yet be set with `org-entry-put'"
11263 property))
11264 (t ; a non-special property
11265 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11266 (setq range (org-get-property-block beg end 'force))
11267 (goto-char (car range))
11268 (if (re-search-forward
11269 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11270 (progn
11271 (delete-region (match-beginning 1) (match-end 1))
11272 (goto-char (match-beginning 1)))
11273 (goto-char (cdr range))
11274 (insert "\n")
11275 (backward-char 1)
11276 (org-indent-line-function)
11277 (insert ":" property ":"))
11278 (and value (insert " " value))
11279 (org-indent-line-function)))))))
11281 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11282 "Get all property keys in the current buffer.
11283 With INCLUDE-SPECIALS, also list the special properties that reflect things
11284 like tags and TODO state.
11285 With INCLUDE-DEFAULTS, also include properties that has special meaning
11286 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11287 With INCLUDE-COLUMNS, also include property names given in COLUMN
11288 formats in the current buffer."
11289 (let (rtn range cfmt s p)
11290 (save-excursion
11291 (save-restriction
11292 (widen)
11293 (goto-char (point-min))
11294 (while (re-search-forward org-property-start-re nil t)
11295 (setq range (org-get-property-block))
11296 (goto-char (car range))
11297 (while (re-search-forward
11298 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11299 (cdr range) t)
11300 (add-to-list 'rtn (org-match-string-no-properties 1)))
11301 (outline-next-heading))))
11303 (when include-specials
11304 (setq rtn (append org-special-properties rtn)))
11306 (when include-defaults
11307 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11309 (when include-columns
11310 (save-excursion
11311 (save-restriction
11312 (widen)
11313 (goto-char (point-min))
11314 (while (re-search-forward
11315 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11316 nil t)
11317 (setq cfmt (match-string 2) s 0)
11318 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11319 cfmt s)
11320 (setq s (match-end 0)
11321 p (match-string 1 cfmt))
11322 (unless (or (equal p "ITEM")
11323 (member p org-special-properties))
11324 (add-to-list 'rtn (match-string 1 cfmt))))))))
11326 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11328 (defun org-property-values (key)
11329 "Return a list of all values of property KEY."
11330 (save-excursion
11331 (save-restriction
11332 (widen)
11333 (goto-char (point-min))
11334 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11335 values)
11336 (while (re-search-forward re nil t)
11337 (add-to-list 'values (org-trim (match-string 1))))
11338 (delete "" values)))))
11340 (defun org-insert-property-drawer ()
11341 "Insert a property drawer into the current entry."
11342 (interactive)
11343 (org-back-to-heading t)
11344 (looking-at outline-regexp)
11345 (let ((indent (- (match-end 0)(match-beginning 0)))
11346 (beg (point))
11347 (re (concat "^[ \t]*" org-keyword-time-regexp))
11348 end hiddenp)
11349 (outline-next-heading)
11350 (setq end (point))
11351 (goto-char beg)
11352 (while (re-search-forward re end t))
11353 (setq hiddenp (org-invisible-p))
11354 (end-of-line 1)
11355 (and (equal (char-after) ?\n) (forward-char 1))
11356 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11357 (if (member (match-string 1) '("CLOCK:" ":END:"))
11358 ;; just skip this line
11359 (beginning-of-line 2)
11360 ;; Drawer start, find the end
11361 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11362 (beginning-of-line 1)))
11363 (org-skip-over-state-notes)
11364 (skip-chars-backward " \t\n\r")
11365 (if (eq (char-before) ?*) (forward-char 1))
11366 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11367 (beginning-of-line 0)
11368 (org-indent-to-column indent)
11369 (beginning-of-line 2)
11370 (org-indent-to-column indent)
11371 (beginning-of-line 0)
11372 (if hiddenp
11373 (save-excursion
11374 (org-back-to-heading t)
11375 (hide-entry))
11376 (org-flag-drawer t))))
11378 (defun org-set-property (property value)
11379 "In the current entry, set PROPERTY to VALUE.
11380 When called interactively, this will prompt for a property name, offering
11381 completion on existing and default properties. And then it will prompt
11382 for a value, offering completion either on allowed values (via an inherited
11383 xxx_ALL property) or on existing values in other instances of this property
11384 in the current file."
11385 (interactive
11386 (let* ((completion-ignore-case t)
11387 (keys (org-buffer-property-keys nil t t))
11388 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11389 (prop (if (member prop0 keys)
11390 prop0
11391 (or (cdr (assoc (downcase prop0)
11392 (mapcar (lambda (x) (cons (downcase x) x))
11393 keys)))
11394 prop0)))
11395 (cur (org-entry-get nil prop))
11396 (allowed (org-property-get-allowed-values nil prop 'table))
11397 (existing (mapcar 'list (org-property-values prop)))
11398 (val (if allowed
11399 (org-completing-read "Value: " allowed nil 'req-match)
11400 (let (org-completion-use-ido)
11401 (org-completing-read
11402 (concat "Value" (if (and cur (string-match "\\S-" cur))
11403 (concat "[" cur "]") "")
11404 ": ")
11405 existing nil nil "" nil cur)))))
11406 (list prop (if (equal val "") cur val))))
11407 (unless (equal (org-entry-get nil property) value)
11408 (org-entry-put nil property value)))
11410 (defun org-delete-property (property)
11411 "In the current entry, delete PROPERTY."
11412 (interactive
11413 (let* ((completion-ignore-case t)
11414 (prop (org-ido-completing-read
11415 "Property: " (org-entry-properties nil 'standard))))
11416 (list prop)))
11417 (message "Property %s %s" property
11418 (if (org-entry-delete nil property)
11419 "deleted"
11420 "was not present in the entry")))
11422 (defun org-delete-property-globally (property)
11423 "Remove PROPERTY globally, from all entries."
11424 (interactive
11425 (let* ((completion-ignore-case t)
11426 (prop (org-ido-completing-read
11427 "Globally remove property: "
11428 (mapcar 'list (org-buffer-property-keys)))))
11429 (list prop)))
11430 (save-excursion
11431 (save-restriction
11432 (widen)
11433 (goto-char (point-min))
11434 (let ((cnt 0))
11435 (while (re-search-forward
11436 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11437 nil t)
11438 (setq cnt (1+ cnt))
11439 (replace-match ""))
11440 (message "Property \"%s\" removed from %d entries" property cnt)))))
11442 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11444 (defun org-compute-property-at-point ()
11445 "Compute the property at point.
11446 This looks for an enclosing column format, extracts the operator and
11447 then applies it to the property in the column format's scope."
11448 (interactive)
11449 (unless (org-at-property-p)
11450 (error "Not at a property"))
11451 (let ((prop (org-match-string-no-properties 2)))
11452 (org-columns-get-format-and-top-level)
11453 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11454 (error "No operator defined for property %s" prop))
11455 (org-columns-compute prop)))
11457 (defun org-property-get-allowed-values (pom property &optional table)
11458 "Get allowed values for the property PROPERTY.
11459 When TABLE is non-nil, return an alist that can directly be used for
11460 completion."
11461 (let (vals)
11462 (cond
11463 ((equal property "TODO")
11464 (setq vals (org-with-point-at pom
11465 (append org-todo-keywords-1 '("")))))
11466 ((equal property "PRIORITY")
11467 (let ((n org-lowest-priority))
11468 (while (>= n org-highest-priority)
11469 (push (char-to-string n) vals)
11470 (setq n (1- n)))))
11471 ((member property org-special-properties))
11473 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11475 (when (and vals (string-match "\\S-" vals))
11476 (setq vals (car (read-from-string (concat "(" vals ")"))))
11477 (setq vals (mapcar (lambda (x)
11478 (cond ((stringp x) x)
11479 ((numberp x) (number-to-string x))
11480 ((symbolp x) (symbol-name x))
11481 (t "???")))
11482 vals)))))
11483 (if table (mapcar 'list vals) vals)))
11485 (defun org-property-previous-allowed-value (&optional previous)
11486 "Switch to the next allowed value for this property."
11487 (interactive)
11488 (org-property-next-allowed-value t))
11490 (defun org-property-next-allowed-value (&optional previous)
11491 "Switch to the next allowed value for this property."
11492 (interactive)
11493 (unless (org-at-property-p)
11494 (error "Not at a property"))
11495 (let* ((key (match-string 2))
11496 (value (match-string 3))
11497 (allowed (or (org-property-get-allowed-values (point) key)
11498 (and (member value '("[ ]" "[-]" "[X]"))
11499 '("[ ]" "[X]"))))
11500 nval)
11501 (unless allowed
11502 (error "Allowed values for this property have not been defined"))
11503 (if previous (setq allowed (reverse allowed)))
11504 (if (member value allowed)
11505 (setq nval (car (cdr (member value allowed)))))
11506 (setq nval (or nval (car allowed)))
11507 (if (equal nval value)
11508 (error "Only one allowed value for this property"))
11509 (org-at-property-p)
11510 (replace-match (concat " :" key ": " nval) t t)
11511 (org-indent-line-function)
11512 (beginning-of-line 1)
11513 (skip-chars-forward " \t")))
11515 (defun org-find-entry-with-id (ident)
11516 "Locate the entry that contains the ID property with exact value IDENT.
11517 IDENT can be a string, a symbol or a number, this function will search for
11518 the string representation of it.
11519 Return the position where this entry starts, or nil if there is no such entry."
11520 (interactive "sID: ")
11521 (let ((id (cond
11522 ((stringp ident) ident)
11523 ((symbol-name ident) (symbol-name ident))
11524 ((numberp ident) (number-to-string ident))
11525 (t (error "IDENT %s must be a string, symbol or number" ident))))
11526 (case-fold-search nil))
11527 (save-excursion
11528 (save-restriction
11529 (widen)
11530 (goto-char (point-min))
11531 (when (re-search-forward
11532 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11533 nil t)
11534 (org-back-to-heading)
11535 (point))))))
11537 ;;;; Timestamps
11539 (defvar org-last-changed-timestamp nil)
11540 (defvar org-last-inserted-timestamp nil
11541 "The last time stamp inserted with `org-insert-time-stamp'.")
11542 (defvar org-time-was-given) ; dynamically scoped parameter
11543 (defvar org-end-time-was-given) ; dynamically scoped parameter
11544 (defvar org-ts-what) ; dynamically scoped parameter
11546 (defun org-time-stamp (arg &optional inactive)
11547 "Prompt for a date/time and insert a time stamp.
11548 If the user specifies a time like HH:MM, or if this command is called
11549 with a prefix argument, the time stamp will contain date and time.
11550 Otherwise, only the date will be included. All parts of a date not
11551 specified by the user will be filled in from the current date/time.
11552 So if you press just return without typing anything, the time stamp
11553 will represent the current date/time. If there is already a timestamp
11554 at the cursor, it will be modified."
11555 (interactive "P")
11556 (let* ((ts nil)
11557 (default-time
11558 ;; Default time is either today, or, when entering a range,
11559 ;; the range start.
11560 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11561 (save-excursion
11562 (re-search-backward
11563 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11564 (- (point) 20) t)))
11565 (apply 'encode-time (org-parse-time-string (match-string 1)))
11566 (current-time)))
11567 (default-input (and ts (org-get-compact-tod ts)))
11568 org-time-was-given org-end-time-was-given time)
11569 (cond
11570 ((and (org-at-timestamp-p t)
11571 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11572 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11573 (insert "--")
11574 (setq time (let ((this-command this-command))
11575 (org-read-date arg 'totime nil nil
11576 default-time default-input)))
11577 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11578 ((org-at-timestamp-p t)
11579 (setq time (let ((this-command this-command))
11580 (org-read-date arg 'totime nil nil default-time default-input)))
11581 (when (org-at-timestamp-p t) ; just to get the match data
11582 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11583 (replace-match "")
11584 (setq org-last-changed-timestamp
11585 (org-insert-time-stamp
11586 time (or org-time-was-given arg)
11587 inactive nil nil (list org-end-time-was-given))))
11588 (message "Timestamp updated"))
11590 (setq time (let ((this-command this-command))
11591 (org-read-date arg 'totime nil nil default-time default-input)))
11592 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11593 nil nil (list org-end-time-was-given))))))
11595 ;; FIXME: can we use this for something else, like computing time differences?
11596 (defun org-get-compact-tod (s)
11597 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11598 (let* ((t1 (match-string 1 s))
11599 (h1 (string-to-number (match-string 2 s)))
11600 (m1 (string-to-number (match-string 3 s)))
11601 (t2 (and (match-end 4) (match-string 5 s)))
11602 (h2 (and t2 (string-to-number (match-string 6 s))))
11603 (m2 (and t2 (string-to-number (match-string 7 s))))
11604 dh dm)
11605 (if (not t2)
11607 (setq dh (- h2 h1) dm (- m2 m1))
11608 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11609 (concat t1 "+" (number-to-string dh)
11610 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11612 (defun org-time-stamp-inactive (&optional arg)
11613 "Insert an inactive time stamp.
11614 An inactive time stamp is enclosed in square brackets instead of angle
11615 brackets. It is inactive in the sense that it does not trigger agenda entries,
11616 does not link to the calendar and cannot be changed with the S-cursor keys.
11617 So these are more for recording a certain time/date."
11618 (interactive "P")
11619 (org-time-stamp arg 'inactive))
11621 (defvar org-date-ovl (org-make-overlay 1 1))
11622 (org-overlay-put org-date-ovl 'face 'org-warning)
11623 (org-detach-overlay org-date-ovl)
11625 (defvar org-ans1) ; dynamically scoped parameter
11626 (defvar org-ans2) ; dynamically scoped parameter
11628 (defvar org-plain-time-of-day-regexp) ; defined below
11630 (defvar org-overriding-default-time nil) ; dynamically scoped
11631 (defvar org-read-date-overlay nil)
11632 (defvar org-dcst nil) ; dynamically scoped
11633 (defvar org-read-date-history nil)
11635 (defun org-read-date (&optional with-time to-time from-string prompt
11636 default-time default-input)
11637 "Read a date, possibly a time, and make things smooth for the user.
11638 The prompt will suggest to enter an ISO date, but you can also enter anything
11639 which will at least partially be understood by `parse-time-string'.
11640 Unrecognized parts of the date will default to the current day, month, year,
11641 hour and minute. If this command is called to replace a timestamp at point,
11642 of to enter the second timestamp of a range, the default time is taken from the
11643 existing stamp. For example,
11644 3-2-5 --> 2003-02-05
11645 feb 15 --> currentyear-02-15
11646 sep 12 9 --> 2009-09-12
11647 12:45 --> today 12:45
11648 22 sept 0:34 --> currentyear-09-22 0:34
11649 12 --> currentyear-currentmonth-12
11650 Fri --> nearest Friday (today or later)
11651 etc.
11653 Furthermore you can specify a relative date by giving, as the *first* thing
11654 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11655 change in days weeks, months, years.
11656 With a single plus or minus, the date is relative to today. With a double
11657 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11658 +4d --> four days from today
11659 +4 --> same as above
11660 +2w --> two weeks from today
11661 ++5 --> five days from default date
11663 The function understands only English month and weekday abbreviations,
11664 but this can be configured with the variables `parse-time-months' and
11665 `parse-time-weekdays'.
11667 While prompting, a calendar is popped up - you can also select the
11668 date with the mouse (button 1). The calendar shows a period of three
11669 months. To scroll it to other months, use the keys `>' and `<'.
11670 If you don't like the calendar, turn it off with
11671 \(setq org-read-date-popup-calendar nil)
11673 With optional argument TO-TIME, the date will immediately be converted
11674 to an internal time.
11675 With an optional argument WITH-TIME, the prompt will suggest to also
11676 insert a time. Note that when WITH-TIME is not set, you can still
11677 enter a time, and this function will inform the calling routine about
11678 this change. The calling routine may then choose to change the format
11679 used to insert the time stamp into the buffer to include the time.
11680 With optional argument FROM-STRING, read from this string instead from
11681 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11682 the time/date that is used for everything that is not specified by the
11683 user."
11684 (require 'parse-time)
11685 (let* ((org-time-stamp-rounding-minutes
11686 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11687 (org-dcst org-display-custom-times)
11688 (ct (org-current-time))
11689 (def (or org-overriding-default-time default-time ct))
11690 (defdecode (decode-time def))
11691 (dummy (progn
11692 (when (< (nth 2 defdecode) org-extend-today-until)
11693 (setcar (nthcdr 2 defdecode) -1)
11694 (setcar (nthcdr 1 defdecode) 59)
11695 (setq def (apply 'encode-time defdecode)
11696 defdecode (decode-time def)))))
11697 (calendar-move-hook nil)
11698 (calendar-view-diary-initially-flag nil)
11699 (view-diary-entries-initially nil)
11700 (calendar-view-holidays-initially-flag nil)
11701 (view-calendar-holidays-initially nil)
11702 (timestr (format-time-string
11703 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11704 (prompt (concat (if prompt (concat prompt " ") "")
11705 (format "Date+time [%s]: " timestr)))
11706 ans (org-ans0 "") org-ans1 org-ans2 final)
11708 (cond
11709 (from-string (setq ans from-string))
11710 (org-read-date-popup-calendar
11711 (save-excursion
11712 (save-window-excursion
11713 (calendar)
11714 (calendar-forward-day (- (time-to-days def)
11715 (calendar-absolute-from-gregorian
11716 (calendar-current-date))))
11717 (org-eval-in-calendar nil t)
11718 (let* ((old-map (current-local-map))
11719 (map (copy-keymap calendar-mode-map))
11720 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11721 (org-defkey map (kbd "RET") 'org-calendar-select)
11722 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11723 'org-calendar-select-mouse)
11724 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11725 'org-calendar-select-mouse)
11726 (org-defkey minibuffer-local-map [(meta shift left)]
11727 (lambda () (interactive)
11728 (org-eval-in-calendar '(calendar-backward-month 1))))
11729 (org-defkey minibuffer-local-map [(meta shift right)]
11730 (lambda () (interactive)
11731 (org-eval-in-calendar '(calendar-forward-month 1))))
11732 (org-defkey minibuffer-local-map [(meta shift up)]
11733 (lambda () (interactive)
11734 (org-eval-in-calendar '(calendar-backward-year 1))))
11735 (org-defkey minibuffer-local-map [(meta shift down)]
11736 (lambda () (interactive)
11737 (org-eval-in-calendar '(calendar-forward-year 1))))
11738 (org-defkey minibuffer-local-map [(shift up)]
11739 (lambda () (interactive)
11740 (org-eval-in-calendar '(calendar-backward-week 1))))
11741 (org-defkey minibuffer-local-map [(shift down)]
11742 (lambda () (interactive)
11743 (org-eval-in-calendar '(calendar-forward-week 1))))
11744 (org-defkey minibuffer-local-map [(shift left)]
11745 (lambda () (interactive)
11746 (org-eval-in-calendar '(calendar-backward-day 1))))
11747 (org-defkey minibuffer-local-map [(shift right)]
11748 (lambda () (interactive)
11749 (org-eval-in-calendar '(calendar-forward-day 1))))
11750 (org-defkey minibuffer-local-map ">"
11751 (lambda () (interactive)
11752 (org-eval-in-calendar '(scroll-calendar-left 1))))
11753 (org-defkey minibuffer-local-map "<"
11754 (lambda () (interactive)
11755 (org-eval-in-calendar '(scroll-calendar-right 1))))
11756 (run-hooks 'org-read-date-minibuffer-setup-hook)
11757 (unwind-protect
11758 (progn
11759 (use-local-map map)
11760 (add-hook 'post-command-hook 'org-read-date-display)
11761 (setq org-ans0 (read-string prompt default-input
11762 'org-read-date-history nil))
11763 ;; org-ans0: from prompt
11764 ;; org-ans1: from mouse click
11765 ;; org-ans2: from calendar motion
11766 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11767 (remove-hook 'post-command-hook 'org-read-date-display)
11768 (use-local-map old-map)
11769 (when org-read-date-overlay
11770 (org-delete-overlay org-read-date-overlay)
11771 (setq org-read-date-overlay nil)))))))
11773 (t ; Naked prompt only
11774 (unwind-protect
11775 (setq ans (read-string prompt default-input
11776 'org-read-date-history timestr))
11777 (when org-read-date-overlay
11778 (org-delete-overlay org-read-date-overlay)
11779 (setq org-read-date-overlay nil)))))
11781 (setq final (org-read-date-analyze ans def defdecode))
11783 (if to-time
11784 (apply 'encode-time final)
11785 (if (and (boundp 'org-time-was-given) org-time-was-given)
11786 (format "%04d-%02d-%02d %02d:%02d"
11787 (nth 5 final) (nth 4 final) (nth 3 final)
11788 (nth 2 final) (nth 1 final))
11789 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11790 (defvar def)
11791 (defvar defdecode)
11792 (defvar with-time)
11793 (defun org-read-date-display ()
11794 "Display the current date prompt interpretation in the minibuffer."
11795 (when org-read-date-display-live
11796 (when org-read-date-overlay
11797 (org-delete-overlay org-read-date-overlay))
11798 (let ((p (point)))
11799 (end-of-line 1)
11800 (while (not (equal (buffer-substring
11801 (max (point-min) (- (point) 4)) (point))
11802 " "))
11803 (insert " "))
11804 (goto-char p))
11805 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11806 " " (or org-ans1 org-ans2)))
11807 (org-end-time-was-given nil)
11808 (f (org-read-date-analyze ans def defdecode))
11809 (fmts (if org-dcst
11810 org-time-stamp-custom-formats
11811 org-time-stamp-formats))
11812 (fmt (if (or with-time
11813 (and (boundp 'org-time-was-given) org-time-was-given))
11814 (cdr fmts)
11815 (car fmts)))
11816 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11817 (when (and org-end-time-was-given
11818 (string-match org-plain-time-of-day-regexp txt))
11819 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11820 org-end-time-was-given
11821 (substring txt (match-end 0)))))
11822 (setq org-read-date-overlay
11823 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11824 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11826 (defun org-read-date-analyze (ans def defdecode)
11827 "Analyse the combined answer of the date prompt."
11828 ;; FIXME: cleanup and comment
11829 (let (delta deltan deltaw deltadef year month day
11830 hour minute second wday pm h2 m2 tl wday1
11831 iso-year iso-weekday iso-week iso-year iso-date)
11833 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11834 (setq ans "+0"))
11836 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11837 (setq ans (replace-match "" t t ans)
11838 deltan (car delta)
11839 deltaw (nth 1 delta)
11840 deltadef (nth 2 delta)))
11842 ;; Check if there is an iso week date in there
11843 ;; If yes, sore the info and postpone interpreting it until the rest
11844 ;; of the parsing is done
11845 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11846 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11847 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11848 iso-week (string-to-number (match-string 2 ans)))
11849 (setq ans (replace-match "" t t ans)))
11851 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11852 (when (string-match
11853 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11854 (setq year (if (match-end 2)
11855 (string-to-number (match-string 2 ans))
11856 (string-to-number (format-time-string "%Y")))
11857 month (string-to-number (match-string 3 ans))
11858 day (string-to-number (match-string 4 ans)))
11859 (if (< year 100) (setq year (+ 2000 year)))
11860 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11861 t nil ans)))
11862 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11863 ;; If there is a time with am/pm, and *no* time without it, we convert
11864 ;; so that matching will be successful.
11865 (loop for i from 1 to 2 do ; twice, for end time as well
11866 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11867 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11868 (setq hour (string-to-number (match-string 1 ans))
11869 minute (if (match-end 3)
11870 (string-to-number (match-string 3 ans))
11872 pm (equal ?p
11873 (string-to-char (downcase (match-string 4 ans)))))
11874 (if (and (= hour 12) (not pm))
11875 (setq hour 0)
11876 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11877 (setq ans (replace-match (format "%02d:%02d" hour minute)
11878 t t ans))))
11880 ;; Check if a time range is given as a duration
11881 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11882 (setq hour (string-to-number (match-string 1 ans))
11883 h2 (+ hour (string-to-number (match-string 3 ans)))
11884 minute (string-to-number (match-string 2 ans))
11885 m2 (+ minute (if (match-end 5) (string-to-number
11886 (match-string 5 ans))0)))
11887 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11888 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11889 t t ans)))
11891 ;; Check if there is a time range
11892 (when (boundp 'org-end-time-was-given)
11893 (setq org-time-was-given nil)
11894 (when (and (string-match org-plain-time-of-day-regexp ans)
11895 (match-end 8))
11896 (setq org-end-time-was-given (match-string 8 ans))
11897 (setq ans (concat (substring ans 0 (match-beginning 7))
11898 (substring ans (match-end 7))))))
11900 (setq tl (parse-time-string ans)
11901 day (or (nth 3 tl) (nth 3 defdecode))
11902 month (or (nth 4 tl)
11903 (if (and org-read-date-prefer-future
11904 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11905 (1+ (nth 4 defdecode))
11906 (nth 4 defdecode)))
11907 year (or (nth 5 tl)
11908 (if (and org-read-date-prefer-future
11909 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11910 (1+ (nth 5 defdecode))
11911 (nth 5 defdecode)))
11912 hour (or (nth 2 tl) (nth 2 defdecode))
11913 minute (or (nth 1 tl) (nth 1 defdecode))
11914 second (or (nth 0 tl) 0)
11915 wday (nth 6 tl))
11917 ;; Special date definitions below
11918 (cond
11919 (iso-week
11920 ;; There was an iso week
11921 (setq year (or iso-year year)
11922 day (or iso-weekday wday 1)
11923 wday nil ; to make sure that the trigger below does not match
11924 iso-date (calendar-gregorian-from-absolute
11925 (calendar-absolute-from-iso
11926 (list iso-week day year))))
11927 ; FIXME: Should we also push ISO weeks into the future?
11928 ; (when (and org-read-date-prefer-future
11929 ; (not iso-year)
11930 ; (< (calendar-absolute-from-gregorian iso-date)
11931 ; (time-to-days (current-time))))
11932 ; (setq year (1+ year)
11933 ; iso-date (calendar-gregorian-from-absolute
11934 ; (calendar-absolute-from-iso
11935 ; (list iso-week day year)))))
11936 (setq month (car iso-date)
11937 year (nth 2 iso-date)
11938 day (nth 1 iso-date)))
11939 (deltan
11940 (unless deltadef
11941 (let ((now (decode-time (current-time))))
11942 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11943 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11944 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11945 ((equal deltaw "m") (setq month (+ month deltan)))
11946 ((equal deltaw "y") (setq year (+ year deltan)))))
11947 ((and wday (not (nth 3 tl)))
11948 ;; Weekday was given, but no day, so pick that day in the week
11949 ;; on or after the derived date.
11950 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11951 (unless (equal wday wday1)
11952 (setq day (+ day (% (- wday wday1 -7) 7))))))
11953 (if (and (boundp 'org-time-was-given)
11954 (nth 2 tl))
11955 (setq org-time-was-given t))
11956 (if (< year 100) (setq year (+ 2000 year)))
11957 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11958 (list second minute hour day month year)))
11960 (defvar parse-time-weekdays)
11962 (defun org-read-date-get-relative (s today default)
11963 "Check string S for special relative date string.
11964 TODAY and DEFAULT are internal times, for today and for a default.
11965 Return shift list (N what def-flag)
11966 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11967 N is the number of WHATs to shift.
11968 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11969 the DEFAULT date rather than TODAY."
11970 (when (and
11971 (string-match
11972 (concat
11973 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11974 "\\([0-9]+\\)?"
11975 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11976 "\\([ \t]\\|$\\)") s)
11977 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11978 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11979 (string-to-char (substring (match-string 1 s) -1))
11980 ?+))
11981 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11982 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11983 (what (if (match-end 3) (match-string 3 s) "d"))
11984 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11985 (date (if rel default today))
11986 (wday (nth 6 (decode-time date)))
11987 delta)
11988 (if wday1
11989 (progn
11990 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11991 (if (= dir ?-) (setq delta (- delta 7)))
11992 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11993 (list delta "d" rel))
11994 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11996 (defun org-eval-in-calendar (form &optional keepdate)
11997 "Eval FORM in the calendar window and return to current window.
11998 Also, store the cursor date in variable org-ans2."
11999 (let ((sw (selected-window)))
12000 (select-window (get-buffer-window "*Calendar*"))
12001 (eval form)
12002 (when (and (not keepdate) (calendar-cursor-to-date))
12003 (let* ((date (calendar-cursor-to-date))
12004 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12005 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12006 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12007 (select-window sw)))
12009 (defun org-calendar-select ()
12010 "Return to `org-read-date' with the date currently selected.
12011 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12012 (interactive)
12013 (when (calendar-cursor-to-date)
12014 (let* ((date (calendar-cursor-to-date))
12015 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12016 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12017 (if (active-minibuffer-window) (exit-minibuffer))))
12019 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12020 "Insert a date stamp for the date given by the internal TIME.
12021 WITH-HM means, use the stamp format that includes the time of the day.
12022 INACTIVE means use square brackets instead of angular ones, so that the
12023 stamp will not contribute to the agenda.
12024 PRE and POST are optional strings to be inserted before and after the
12025 stamp.
12026 The command returns the inserted time stamp."
12027 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12028 stamp)
12029 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12030 (insert-before-markers (or pre ""))
12031 (insert-before-markers (setq stamp (format-time-string fmt time)))
12032 (when (listp extra)
12033 (setq extra (car extra))
12034 (if (and (stringp extra)
12035 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12036 (setq extra (format "-%02d:%02d"
12037 (string-to-number (match-string 1 extra))
12038 (string-to-number (match-string 2 extra))))
12039 (setq extra nil)))
12040 (when extra
12041 (backward-char 1)
12042 (insert-before-markers extra)
12043 (forward-char 1))
12044 (insert-before-markers (or post ""))
12045 (setq org-last-inserted-timestamp stamp)))
12047 (defun org-toggle-time-stamp-overlays ()
12048 "Toggle the use of custom time stamp formats."
12049 (interactive)
12050 (setq org-display-custom-times (not org-display-custom-times))
12051 (unless org-display-custom-times
12052 (let ((p (point-min)) (bmp (buffer-modified-p)))
12053 (while (setq p (next-single-property-change p 'display))
12054 (if (and (get-text-property p 'display)
12055 (eq (get-text-property p 'face) 'org-date))
12056 (remove-text-properties
12057 p (setq p (next-single-property-change p 'display))
12058 '(display t))))
12059 (set-buffer-modified-p bmp)))
12060 (if (featurep 'xemacs)
12061 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12062 (org-restart-font-lock)
12063 (setq org-table-may-need-update t)
12064 (if org-display-custom-times
12065 (message "Time stamps are overlayed with custom format")
12066 (message "Time stamp overlays removed")))
12068 (defun org-display-custom-time (beg end)
12069 "Overlay modified time stamp format over timestamp between BEG and END."
12070 (let* ((ts (buffer-substring beg end))
12071 t1 w1 with-hm tf time str w2 (off 0))
12072 (save-match-data
12073 (setq t1 (org-parse-time-string ts t))
12074 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12075 (setq off (- (match-end 0) (match-beginning 0)))))
12076 (setq end (- end off))
12077 (setq w1 (- end beg)
12078 with-hm (and (nth 1 t1) (nth 2 t1))
12079 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12080 time (org-fix-decoded-time t1)
12081 str (org-add-props
12082 (format-time-string
12083 (substring tf 1 -1) (apply 'encode-time time))
12084 nil 'mouse-face 'highlight)
12085 w2 (length str))
12086 (if (not (= w2 w1))
12087 (add-text-properties (1+ beg) (+ 2 beg)
12088 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12089 (if (featurep 'xemacs)
12090 (progn
12091 (put-text-property beg end 'invisible t)
12092 (put-text-property beg end 'end-glyph (make-glyph str)))
12093 (put-text-property beg end 'display str))))
12095 (defun org-translate-time (string)
12096 "Translate all timestamps in STRING to custom format.
12097 But do this only if the variable `org-display-custom-times' is set."
12098 (when org-display-custom-times
12099 (save-match-data
12100 (let* ((start 0)
12101 (re org-ts-regexp-both)
12102 t1 with-hm inactive tf time str beg end)
12103 (while (setq start (string-match re string start))
12104 (setq beg (match-beginning 0)
12105 end (match-end 0)
12106 t1 (save-match-data
12107 (org-parse-time-string (substring string beg end) t))
12108 with-hm (and (nth 1 t1) (nth 2 t1))
12109 inactive (equal (substring string beg (1+ beg)) "[")
12110 tf (funcall (if with-hm 'cdr 'car)
12111 org-time-stamp-custom-formats)
12112 time (org-fix-decoded-time t1)
12113 str (format-time-string
12114 (concat
12115 (if inactive "[" "<") (substring tf 1 -1)
12116 (if inactive "]" ">"))
12117 (apply 'encode-time time))
12118 string (replace-match str t t string)
12119 start (+ start (length str)))))))
12120 string)
12122 (defun org-fix-decoded-time (time)
12123 "Set 0 instead of nil for the first 6 elements of time.
12124 Don't touch the rest."
12125 (let ((n 0))
12126 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12128 (defun org-days-to-time (timestamp-string)
12129 "Difference between TIMESTAMP-STRING and now in days."
12130 (- (time-to-days (org-time-string-to-time timestamp-string))
12131 (time-to-days (current-time))))
12133 (defun org-deadline-close (timestamp-string &optional ndays)
12134 "Is the time in TIMESTAMP-STRING close to the current date?"
12135 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12136 (and (< (org-days-to-time timestamp-string) ndays)
12137 (not (org-entry-is-done-p))))
12139 (defun org-get-wdays (ts)
12140 "Get the deadline lead time appropriate for timestring TS."
12141 (cond
12142 ((<= org-deadline-warning-days 0)
12143 ;; 0 or negative, enforce this value no matter what
12144 (- org-deadline-warning-days))
12145 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12146 ;; lead time is specified.
12147 (floor (* (string-to-number (match-string 1 ts))
12148 (cdr (assoc (match-string 2 ts)
12149 '(("d" . 1) ("w" . 7)
12150 ("m" . 30.4) ("y" . 365.25)))))))
12151 ;; go for the default.
12152 (t org-deadline-warning-days)))
12154 (defun org-calendar-select-mouse (ev)
12155 "Return to `org-read-date' with the date currently selected.
12156 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12157 (interactive "e")
12158 (mouse-set-point ev)
12159 (when (calendar-cursor-to-date)
12160 (let* ((date (calendar-cursor-to-date))
12161 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12162 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12163 (if (active-minibuffer-window) (exit-minibuffer))))
12165 (defun org-check-deadlines (ndays)
12166 "Check if there are any deadlines due or past due.
12167 A deadline is considered due if it happens within `org-deadline-warning-days'
12168 days from today's date. If the deadline appears in an entry marked DONE,
12169 it is not shown. The prefix arg NDAYS can be used to test that many
12170 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12171 (interactive "P")
12172 (let* ((org-warn-days
12173 (cond
12174 ((equal ndays '(4)) 100000)
12175 (ndays (prefix-numeric-value ndays))
12176 (t (abs org-deadline-warning-days))))
12177 (case-fold-search nil)
12178 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12179 (callback
12180 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12182 (message "%d deadlines past-due or due within %d days"
12183 (org-occur regexp nil callback)
12184 org-warn-days)))
12186 (defun org-check-before-date (date)
12187 "Check if there are deadlines or scheduled entries before DATE."
12188 (interactive (list (org-read-date)))
12189 (let ((case-fold-search nil)
12190 (regexp (concat "\\<\\(" org-deadline-string
12191 "\\|" org-scheduled-string
12192 "\\) *<\\([^>]+\\)>"))
12193 (callback
12194 (lambda () (time-less-p
12195 (org-time-string-to-time (match-string 2))
12196 (org-time-string-to-time date)))))
12197 (message "%d entries before %s"
12198 (org-occur regexp nil callback) date)))
12200 (defun org-check-after-date (date)
12201 "Check if there are deadlines or scheduled entries after DATE."
12202 (interactive (list (org-read-date)))
12203 (let ((case-fold-search nil)
12204 (regexp (concat "\\<\\(" org-deadline-string
12205 "\\|" org-scheduled-string
12206 "\\) *<\\([^>]+\\)>"))
12207 (callback
12208 (lambda () (not
12209 (time-less-p
12210 (org-time-string-to-time (match-string 2))
12211 (org-time-string-to-time date))))))
12212 (message "%d entries after %s"
12213 (org-occur regexp nil callback) date)))
12215 (defun org-evaluate-time-range (&optional to-buffer)
12216 "Evaluate a time range by computing the difference between start and end.
12217 Normally the result is just printed in the echo area, but with prefix arg
12218 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12219 If the time range is actually in a table, the result is inserted into the
12220 next column.
12221 For time difference computation, a year is assumed to be exactly 365
12222 days in order to avoid rounding problems."
12223 (interactive "P")
12225 (org-clock-update-time-maybe)
12226 (save-excursion
12227 (unless (org-at-date-range-p t)
12228 (goto-char (point-at-bol))
12229 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12230 (if (not (org-at-date-range-p t))
12231 (error "Not at a time-stamp range, and none found in current line")))
12232 (let* ((ts1 (match-string 1))
12233 (ts2 (match-string 2))
12234 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12235 (match-end (match-end 0))
12236 (time1 (org-time-string-to-time ts1))
12237 (time2 (org-time-string-to-time ts2))
12238 (t1 (time-to-seconds time1))
12239 (t2 (time-to-seconds time2))
12240 (diff (abs (- t2 t1)))
12241 (negative (< (- t2 t1) 0))
12242 ;; (ys (floor (* 365 24 60 60)))
12243 (ds (* 24 60 60))
12244 (hs (* 60 60))
12245 (fy "%dy %dd %02d:%02d")
12246 (fy1 "%dy %dd")
12247 (fd "%dd %02d:%02d")
12248 (fd1 "%dd")
12249 (fh "%02d:%02d")
12250 y d h m align)
12251 (if havetime
12252 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12254 d (floor (/ diff ds)) diff (mod diff ds)
12255 h (floor (/ diff hs)) diff (mod diff hs)
12256 m (floor (/ diff 60)))
12257 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12259 d (floor (+ (/ diff ds) 0.5))
12260 h 0 m 0))
12261 (if (not to-buffer)
12262 (message "%s" (org-make-tdiff-string y d h m))
12263 (if (org-at-table-p)
12264 (progn
12265 (goto-char match-end)
12266 (setq align t)
12267 (and (looking-at " *|") (goto-char (match-end 0))))
12268 (goto-char match-end))
12269 (if (looking-at
12270 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12271 (replace-match ""))
12272 (if negative (insert " -"))
12273 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12274 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12275 (insert " " (format fh h m))))
12276 (if align (org-table-align))
12277 (message "Time difference inserted")))))
12279 (defun org-make-tdiff-string (y d h m)
12280 (let ((fmt "")
12281 (l nil))
12282 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12283 l (push y l)))
12284 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12285 l (push d l)))
12286 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12287 l (push h l)))
12288 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12289 l (push m l)))
12290 (apply 'format fmt (nreverse l))))
12292 (defun org-time-string-to-time (s)
12293 (apply 'encode-time (org-parse-time-string s)))
12295 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12296 "Convert a time stamp to an absolute day number.
12297 If there is a specifyer for a cyclic time stamp, get the closest date to
12298 DAYNR.
12299 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12300 (cond
12301 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12302 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12303 daynr
12304 (+ daynr 1000)))
12305 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12306 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12307 (time-to-days (current-time))) (match-string 0 s)
12308 prefer show-all))
12309 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12311 (defun org-days-to-iso-week (days)
12312 "Return the iso week number."
12313 (require 'cal-iso)
12314 (car (calendar-iso-from-absolute days)))
12316 (defun org-small-year-to-year (year)
12317 "Convert 2-digit years into 4-digit years.
12318 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12319 The year 2000 cannot be abbreviated. Any year larger than 99
12320 is returned unchanged."
12321 (if (< year 38)
12322 (setq year (+ 2000 year))
12323 (if (< year 100)
12324 (setq year (+ 1900 year))))
12325 year)
12327 (defun org-time-from-absolute (d)
12328 "Return the time corresponding to date D.
12329 D may be an absolute day number, or a calendar-type list (month day year)."
12330 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12331 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12333 (defun org-calendar-holiday ()
12334 "List of holidays, for Diary display in Org-mode."
12335 (require 'holidays)
12336 (let ((hl (funcall
12337 (if (fboundp 'calendar-check-holidays)
12338 'calendar-check-holidays 'check-calendar-holidays) date)))
12339 (if hl (mapconcat 'identity hl "; "))))
12341 (defun org-diary-sexp-entry (sexp entry date)
12342 "Process a SEXP diary ENTRY for DATE."
12343 (require 'diary-lib)
12344 (let ((result (if calendar-debug-sexp
12345 (let ((stack-trace-on-error t))
12346 (eval (car (read-from-string sexp))))
12347 (condition-case nil
12348 (eval (car (read-from-string sexp)))
12349 (error
12350 (beep)
12351 (message "Bad sexp at line %d in %s: %s"
12352 (org-current-line)
12353 (buffer-file-name) sexp)
12354 (sleep-for 2))))))
12355 (cond ((stringp result) result)
12356 ((and (consp result)
12357 (stringp (cdr result))) (cdr result))
12358 (result entry)
12359 (t nil))))
12361 (defun org-diary-to-ical-string (frombuf)
12362 "Get iCalendar entries from diary entries in buffer FROMBUF.
12363 This uses the icalendar.el library."
12364 (let* ((tmpdir (if (featurep 'xemacs)
12365 (temp-directory)
12366 temporary-file-directory))
12367 (tmpfile (make-temp-name
12368 (expand-file-name "orgics" tmpdir)))
12369 buf rtn b e)
12370 (save-excursion
12371 (set-buffer frombuf)
12372 (icalendar-export-region (point-min) (point-max) tmpfile)
12373 (setq buf (find-buffer-visiting tmpfile))
12374 (set-buffer buf)
12375 (goto-char (point-min))
12376 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12377 (setq b (match-beginning 0)))
12378 (goto-char (point-max))
12379 (if (re-search-backward "^END:VEVENT" nil t)
12380 (setq e (match-end 0)))
12381 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12382 (kill-buffer buf)
12383 (delete-file tmpfile)
12384 rtn))
12386 (defun org-closest-date (start current change prefer show-all)
12387 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12388 When PREFER is `past' return a date that is either CURRENT or past.
12389 When PREFER is `future', return a date that is either CURRENT or future.
12390 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12391 ;; Make the proper lists from the dates
12392 (catch 'exit
12393 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12394 dn dw sday cday n1 n2 n0
12395 d m y y1 y2 date1 date2 nmonths nm ny m2)
12397 (setq start (org-date-to-gregorian start)
12398 current (org-date-to-gregorian
12399 (if show-all
12400 current
12401 (time-to-days (current-time))))
12402 sday (calendar-absolute-from-gregorian start)
12403 cday (calendar-absolute-from-gregorian current))
12405 (if (<= cday sday) (throw 'exit sday))
12407 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12408 (setq dn (string-to-number (match-string 1 change))
12409 dw (cdr (assoc (match-string 2 change) a1)))
12410 (error "Invalid change specifyer: %s" change))
12411 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12412 (cond
12413 ((eq dw 'day)
12414 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12415 n2 (+ n1 dn)))
12416 ((eq dw 'year)
12417 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12418 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12419 (setq date1 (list m d y1)
12420 n1 (calendar-absolute-from-gregorian date1)
12421 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12422 n2 (calendar-absolute-from-gregorian date2)))
12423 ((eq dw 'month)
12424 ;; approx number of month between the two dates
12425 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12426 ;; How often does dn fit in there?
12427 (setq d (nth 1 start) m (car start) y (nth 2 start)
12428 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12429 m (+ m nm)
12430 ny (floor (/ m 12))
12431 y (+ y ny)
12432 m (- m (* ny 12)))
12433 (while (> m 12) (setq m (- m 12) y (1+ y)))
12434 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12435 (setq m2 (+ m dn) y2 y)
12436 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12437 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12438 (while (<= n2 cday)
12439 (setq n1 n2 m m2 y y2)
12440 (setq m2 (+ m dn) y2 y)
12441 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12442 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12443 ;; Make sure n1 is the earlier date
12444 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12445 (if show-all
12446 (cond
12447 ((eq prefer 'past) n1)
12448 ((eq prefer 'future) (if (= cday n1) n1 n2))
12449 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12450 (cond
12451 ((eq prefer 'past) n1)
12452 ((eq prefer 'future) (if (= cday n1) n1 n2))
12453 (t (if (= cday n1) n1 n2)))))))
12455 (defun org-date-to-gregorian (date)
12456 "Turn any specification of DATE into a gregorian date for the calendar."
12457 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12458 ((and (listp date) (= (length date) 3)) date)
12459 ((stringp date)
12460 (setq date (org-parse-time-string date))
12461 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12462 ((listp date)
12463 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12465 (defun org-parse-time-string (s &optional nodefault)
12466 "Parse the standard Org-mode time string.
12467 This should be a lot faster than the normal `parse-time-string'.
12468 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12469 hour and minute fields will be nil if not given."
12470 (if (string-match org-ts-regexp0 s)
12471 (list 0
12472 (if (or (match-beginning 8) (not nodefault))
12473 (string-to-number (or (match-string 8 s) "0")))
12474 (if (or (match-beginning 7) (not nodefault))
12475 (string-to-number (or (match-string 7 s) "0")))
12476 (string-to-number (match-string 4 s))
12477 (string-to-number (match-string 3 s))
12478 (string-to-number (match-string 2 s))
12479 nil nil nil)
12480 (make-list 9 0)))
12482 (defun org-timestamp-up (&optional arg)
12483 "Increase the date item at the cursor by one.
12484 If the cursor is on the year, change the year. If it is on the month or
12485 the day, change that.
12486 With prefix ARG, change by that many units."
12487 (interactive "p")
12488 (org-timestamp-change (prefix-numeric-value arg)))
12490 (defun org-timestamp-down (&optional arg)
12491 "Decrease the date item at the cursor by one.
12492 If the cursor is on the year, change the year. If it is on the month or
12493 the day, change that.
12494 With prefix ARG, change by that many units."
12495 (interactive "p")
12496 (org-timestamp-change (- (prefix-numeric-value arg))))
12498 (defun org-timestamp-up-day (&optional arg)
12499 "Increase the date in the time stamp by one day.
12500 With prefix ARG, change that many days."
12501 (interactive "p")
12502 (if (and (not (org-at-timestamp-p t))
12503 (org-on-heading-p))
12504 (org-todo 'up)
12505 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12507 (defun org-timestamp-down-day (&optional arg)
12508 "Decrease the date in the time stamp by one day.
12509 With prefix ARG, change that many days."
12510 (interactive "p")
12511 (if (and (not (org-at-timestamp-p t))
12512 (org-on-heading-p))
12513 (org-todo 'down)
12514 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12516 (defun org-at-timestamp-p (&optional inactive-ok)
12517 "Determine if the cursor is in or at a timestamp."
12518 (interactive)
12519 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12520 (pos (point))
12521 (ans (or (looking-at tsr)
12522 (save-excursion
12523 (skip-chars-backward "^[<\n\r\t")
12524 (if (> (point) (point-min)) (backward-char 1))
12525 (and (looking-at tsr)
12526 (> (- (match-end 0) pos) -1))))))
12527 (and ans
12528 (boundp 'org-ts-what)
12529 (setq org-ts-what
12530 (cond
12531 ((= pos (match-beginning 0)) 'bracket)
12532 ((= pos (1- (match-end 0))) 'bracket)
12533 ((org-pos-in-match-range pos 2) 'year)
12534 ((org-pos-in-match-range pos 3) 'month)
12535 ((org-pos-in-match-range pos 7) 'hour)
12536 ((org-pos-in-match-range pos 8) 'minute)
12537 ((or (org-pos-in-match-range pos 4)
12538 (org-pos-in-match-range pos 5)) 'day)
12539 ((and (> pos (or (match-end 8) (match-end 5)))
12540 (< pos (match-end 0)))
12541 (- pos (or (match-end 8) (match-end 5))))
12542 (t 'day))))
12543 ans))
12545 (defun org-toggle-timestamp-type ()
12546 "Toggle the type (<active> or [inactive]) of a time stamp."
12547 (interactive)
12548 (when (org-at-timestamp-p t)
12549 (let ((beg (match-beginning 0)) (end (match-end 0))
12550 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12551 (save-excursion
12552 (goto-char beg)
12553 (while (re-search-forward "[][<>]" end t)
12554 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12555 t t)))
12556 (message "Timestamp is now %sactive"
12557 (if (equal (char-after beg) ?<) "" "in")))))
12559 (defun org-timestamp-change (n &optional what)
12560 "Change the date in the time stamp at point.
12561 The date will be changed by N times WHAT. WHAT can be `day', `month',
12562 `year', `minute', `second'. If WHAT is not given, the cursor position
12563 in the timestamp determines what will be changed."
12564 (let ((pos (point))
12565 with-hm inactive
12566 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12567 org-ts-what
12568 extra rem
12569 ts time time0)
12570 (if (not (org-at-timestamp-p t))
12571 (error "Not at a timestamp"))
12572 (if (and (not what) (eq org-ts-what 'bracket))
12573 (org-toggle-timestamp-type)
12574 (if (and (not what) (not (eq org-ts-what 'day))
12575 org-display-custom-times
12576 (get-text-property (point) 'display)
12577 (not (get-text-property (1- (point)) 'display)))
12578 (setq org-ts-what 'day))
12579 (setq org-ts-what (or what org-ts-what)
12580 inactive (= (char-after (match-beginning 0)) ?\[)
12581 ts (match-string 0))
12582 (replace-match "")
12583 (if (string-match
12584 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12586 (setq extra (match-string 1 ts)))
12587 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12588 (setq with-hm t))
12589 (setq time0 (org-parse-time-string ts))
12590 (when (and (eq org-ts-what 'minute)
12591 (eq current-prefix-arg nil))
12592 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12593 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12594 (setcar (cdr time0) (+ (nth 1 time0)
12595 (if (> n 0) (- rem) (- dm rem))))))
12596 (setq time
12597 (encode-time (or (car time0) 0)
12598 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12599 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12600 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12601 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12602 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12603 (nthcdr 6 time0)))
12604 (when (and (member org-ts-what '(hour minute))
12605 extra
12606 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
12607 (setq extra (org-modify-ts-extra
12608 extra
12609 (if (eq org-ts-what 'hour) 2 5)
12610 n dm)))
12611 (when (integerp org-ts-what)
12612 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12613 (if (eq what 'calendar)
12614 (let ((cal-date (org-get-date-from-calendar)))
12615 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12616 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12617 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12618 (setcar time0 (or (car time0) 0))
12619 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12620 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12621 (setq time (apply 'encode-time time0))))
12622 (setq org-last-changed-timestamp
12623 (org-insert-time-stamp time with-hm inactive nil nil extra))
12624 (org-clock-update-time-maybe)
12625 (goto-char pos)
12626 ;; Try to recenter the calendar window, if any
12627 (if (and org-calendar-follow-timestamp-change
12628 (get-buffer-window "*Calendar*" t)
12629 (memq org-ts-what '(day month year)))
12630 (org-recenter-calendar (time-to-days time))))))
12632 (defun org-modify-ts-extra (s pos n dm)
12633 "Change the different parts of the lead-time and repeat fields in timestamp."
12634 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12635 ng h m new rem)
12636 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12637 (cond
12638 ((or (org-pos-in-match-range pos 2)
12639 (org-pos-in-match-range pos 3))
12640 (setq m (string-to-number (match-string 3 s))
12641 h (string-to-number (match-string 2 s)))
12642 (if (org-pos-in-match-range pos 2)
12643 (setq h (+ h n))
12644 (setq n (* dm (org-no-warnings (signum n))))
12645 (when (not (= 0 (setq rem (% m dm))))
12646 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12647 (setq m (+ m n)))
12648 (if (< m 0) (setq m (+ m 60) h (1- h)))
12649 (if (> m 59) (setq m (- m 60) h (1+ h)))
12650 (setq h (min 24 (max 0 h)))
12651 (setq ng 1 new (format "-%02d:%02d" h m)))
12652 ((org-pos-in-match-range pos 6)
12653 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12654 ((org-pos-in-match-range pos 5)
12655 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12657 ((org-pos-in-match-range pos 9)
12658 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12659 ((org-pos-in-match-range pos 8)
12660 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12662 (when ng
12663 (setq s (concat
12664 (substring s 0 (match-beginning ng))
12666 (substring s (match-end ng))))))
12669 (defun org-recenter-calendar (date)
12670 "If the calendar is visible, recenter it to DATE."
12671 (let* ((win (selected-window))
12672 (cwin (get-buffer-window "*Calendar*" t))
12673 (calendar-move-hook nil))
12674 (when cwin
12675 (select-window cwin)
12676 (calendar-goto-date (if (listp date) date
12677 (calendar-gregorian-from-absolute date)))
12678 (select-window win))))
12680 (defun org-goto-calendar (&optional arg)
12681 "Go to the Emacs calendar at the current date.
12682 If there is a time stamp in the current line, go to that date.
12683 A prefix ARG can be used to force the current date."
12684 (interactive "P")
12685 (let ((tsr org-ts-regexp) diff
12686 (calendar-move-hook nil)
12687 (calendar-view-holidays-initially-flag nil)
12688 (view-calendar-holidays-initially nil)
12689 (calendar-view-diary-initially-flag nil)
12690 (view-diary-entries-initially nil))
12691 (if (or (org-at-timestamp-p)
12692 (save-excursion
12693 (beginning-of-line 1)
12694 (looking-at (concat ".*" tsr))))
12695 (let ((d1 (time-to-days (current-time)))
12696 (d2 (time-to-days
12697 (org-time-string-to-time (match-string 1)))))
12698 (setq diff (- d2 d1))))
12699 (calendar)
12700 (calendar-goto-today)
12701 (if (and diff (not arg)) (calendar-forward-day diff))))
12703 (defun org-get-date-from-calendar ()
12704 "Return a list (month day year) of date at point in calendar."
12705 (with-current-buffer "*Calendar*"
12706 (save-match-data
12707 (calendar-cursor-to-date))))
12709 (defun org-date-from-calendar ()
12710 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12711 If there is already a time stamp at the cursor position, update it."
12712 (interactive)
12713 (if (org-at-timestamp-p t)
12714 (org-timestamp-change 0 'calendar)
12715 (let ((cal-date (org-get-date-from-calendar)))
12716 (org-insert-time-stamp
12717 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12719 (defun org-minutes-to-hh:mm-string (m)
12720 "Compute H:MM from a number of minutes."
12721 (let ((h (/ m 60)))
12722 (setq m (- m (* 60 h)))
12723 (format org-time-clocksum-format h m)))
12725 (defun org-hh:mm-string-to-minutes (s)
12726 "Convert a string H:MM to a number of minutes."
12727 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12728 (+ (* (string-to-number (match-string 1 s)) 60)
12729 (string-to-number (match-string 2 s)))
12732 ;;;; Files
12734 (defun org-save-all-org-buffers ()
12735 "Save all Org-mode buffers without user confirmation."
12736 (interactive)
12737 (message "Saving all Org-mode buffers...")
12738 (save-some-buffers t 'org-mode-p)
12739 (when (featurep 'org-id) (org-id-locations-save))
12740 (message "Saving all Org-mode buffers... done"))
12742 (defun org-revert-all-org-buffers ()
12743 "Revert all Org-mode buffers.
12744 Prompt for confirmation when there are unsaved changes.
12745 Be sure you know what you are doing before letting this function
12746 overwrite your changes.
12748 This function is useful in a setup where one tracks org files
12749 with a version control system, to revert on one machine after pulling
12750 changes from another. I believe the procedure must be like this:
12752 1. M-x org-save-all-org-buffers
12753 2. Pull changes from the other machine, resolve conflicts
12754 3. M-x org-revert-all-org-buffers"
12755 (interactive)
12756 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12757 (error "Abort"))
12758 (save-excursion
12759 (save-window-excursion
12760 (mapc
12761 (lambda (b)
12762 (when (and (with-current-buffer b (org-mode-p))
12763 (with-current-buffer b buffer-file-name))
12764 (switch-to-buffer b)
12765 (revert-buffer t 'no-confirm)))
12766 (buffer-list))
12767 (when (and (featurep 'org-id) org-id-track-globally)
12768 (org-id-locations-load)))))
12770 ;;;; Agenda files
12772 ;;;###autoload
12773 (defun org-iswitchb (&optional arg)
12774 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12775 With a prefix argument, restrict available to files.
12776 With two prefix arguments, restrict available buffers to agenda files.
12778 Due to some yet unresolved reason, the global function
12779 `iswitchb-mode' needs to be active for this function to work."
12780 (interactive "P")
12781 (require 'iswitchb)
12782 (let ((enabled iswitchb-mode) blist)
12783 (or enabled (iswitchb-mode 1))
12784 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12785 ((equal arg '(16)) (org-buffer-list 'agenda))
12786 (t (org-buffer-list))))
12787 (unwind-protect
12788 (let ((iswitchb-make-buflist-hook
12789 (lambda ()
12790 (setq iswitchb-temp-buflist
12791 (mapcar 'buffer-name blist)))))
12792 (switch-to-buffer
12793 (iswitchb-read-buffer
12794 "Switch-to: " nil t))
12795 (or enabled (iswitchb-mode -1))))))
12797 ;;;###autoload
12798 (defun org-ido-switchb (&optional arg)
12799 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12800 With a prefix argument, restrict available to files.
12801 With two prefix arguments, restrict available buffers to agenda files."
12802 (interactive "P")
12803 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12804 ((equal arg '(16)) (org-buffer-list 'agenda))
12805 (t (org-buffer-list)))))
12806 (switch-to-buffer
12807 (org-ido-completing-read "Org buffer: "
12808 (mapcar 'list (mapcar 'buffer-name blist))
12809 nil t))))
12811 (defun org-buffer-list (&optional predicate exclude-tmp)
12812 "Return a list of Org buffers.
12813 PREDICATE can be `export', `files' or `agenda'.
12815 export restrict the list to Export buffers.
12816 files restrict the list to buffers visiting Org files.
12817 agenda restrict the list to buffers visiting agenda files.
12819 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12820 (let* ((bfn nil)
12821 (agenda-files (and (eq predicate 'agenda)
12822 (mapcar 'file-truename (org-agenda-files t))))
12823 (filter
12824 (cond
12825 ((eq predicate 'files)
12826 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12827 ((eq predicate 'export)
12828 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12829 ((eq predicate 'agenda)
12830 (lambda (b)
12831 (with-current-buffer b
12832 (and (eq major-mode 'org-mode)
12833 (setq bfn (buffer-file-name b))
12834 (member (file-truename bfn) agenda-files)))))
12835 (t (lambda (b) (with-current-buffer b
12836 (or (eq major-mode 'org-mode)
12837 (string-match "\*Org .*Export"
12838 (buffer-name b)))))))))
12839 (delq nil
12840 (mapcar
12841 (lambda(b)
12842 (if (and (funcall filter b)
12843 (or (not exclude-tmp)
12844 (not (string-match "tmp" (buffer-name b)))))
12846 nil))
12847 (buffer-list)))))
12849 (defun org-agenda-files (&optional unrestricted archives)
12850 "Get the list of agenda files.
12851 Optional UNRESTRICTED means return the full list even if a restriction
12852 is currently in place.
12853 When ARCHIVES is t, include all archive files hat are really being
12854 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12855 `org-agenda-archives-mode' is t."
12856 (let ((files
12857 (cond
12858 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12859 ((stringp org-agenda-files) (org-read-agenda-file-list))
12860 ((listp org-agenda-files) org-agenda-files)
12861 (t (error "Invalid value of `org-agenda-files'")))))
12862 (setq files (apply 'append
12863 (mapcar (lambda (f)
12864 (if (file-directory-p f)
12865 (directory-files
12866 f t org-agenda-file-regexp)
12867 (list f)))
12868 files)))
12869 (when org-agenda-skip-unavailable-files
12870 (setq files (delq nil
12871 (mapcar (function
12872 (lambda (file)
12873 (and (file-readable-p file) file)))
12874 files))))
12875 (when (or (eq archives t)
12876 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12877 (setq files (org-add-archive-files files)))
12878 files))
12880 (defun org-edit-agenda-file-list ()
12881 "Edit the list of agenda files.
12882 Depending on setup, this either uses customize to edit the variable
12883 `org-agenda-files', or it visits the file that is holding the list. In the
12884 latter case, the buffer is set up in a way that saving it automatically kills
12885 the buffer and restores the previous window configuration."
12886 (interactive)
12887 (if (stringp org-agenda-files)
12888 (let ((cw (current-window-configuration)))
12889 (find-file org-agenda-files)
12890 (org-set-local 'org-window-configuration cw)
12891 (org-add-hook 'after-save-hook
12892 (lambda ()
12893 (set-window-configuration
12894 (prog1 org-window-configuration
12895 (kill-buffer (current-buffer))))
12896 (org-install-agenda-files-menu)
12897 (message "New agenda file list installed"))
12898 nil 'local)
12899 (message "%s" (substitute-command-keys
12900 "Edit list and finish with \\[save-buffer]")))
12901 (customize-variable 'org-agenda-files)))
12903 (defun org-store-new-agenda-file-list (list)
12904 "Set new value for the agenda file list and save it correctly."
12905 (if (stringp org-agenda-files)
12906 (let ((f org-agenda-files) b)
12907 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12908 (with-temp-file f
12909 (insert (mapconcat 'identity list "\n") "\n")))
12910 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12911 (setq org-agenda-files list)
12912 (customize-save-variable 'org-agenda-files org-agenda-files))))
12914 (defun org-read-agenda-file-list ()
12915 "Read the list of agenda files from a file."
12916 (when (file-directory-p org-agenda-files)
12917 (error "`org-agenda-files' cannot be a single directory"))
12918 (when (stringp org-agenda-files)
12919 (with-temp-buffer
12920 (insert-file-contents org-agenda-files)
12921 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12924 ;;;###autoload
12925 (defun org-cycle-agenda-files ()
12926 "Cycle through the files in `org-agenda-files'.
12927 If the current buffer visits an agenda file, find the next one in the list.
12928 If the current buffer does not, find the first agenda file."
12929 (interactive)
12930 (let* ((fs (org-agenda-files t))
12931 (files (append fs (list (car fs))))
12932 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12933 file)
12934 (unless files (error "No agenda files"))
12935 (catch 'exit
12936 (while (setq file (pop files))
12937 (if (equal (file-truename file) tcf)
12938 (when (car files)
12939 (find-file (car files))
12940 (throw 'exit t))))
12941 (find-file (car fs)))
12942 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12944 (defun org-agenda-file-to-front (&optional to-end)
12945 "Move/add the current file to the top of the agenda file list.
12946 If the file is not present in the list, it is added to the front. If it is
12947 present, it is moved there. With optional argument TO-END, add/move to the
12948 end of the list."
12949 (interactive "P")
12950 (let ((org-agenda-skip-unavailable-files nil)
12951 (file-alist (mapcar (lambda (x)
12952 (cons (file-truename x) x))
12953 (org-agenda-files t)))
12954 (ctf (file-truename buffer-file-name))
12955 x had)
12956 (setq x (assoc ctf file-alist) had x)
12958 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12959 (if to-end
12960 (setq file-alist (append (delq x file-alist) (list x)))
12961 (setq file-alist (cons x (delq x file-alist))))
12962 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12963 (org-install-agenda-files-menu)
12964 (message "File %s to %s of agenda file list"
12965 (if had "moved" "added") (if to-end "end" "front"))))
12967 (defun org-remove-file (&optional file)
12968 "Remove current file from the list of files in variable `org-agenda-files'.
12969 These are the files which are being checked for agenda entries.
12970 Optional argument FILE means, use this file instead of the current."
12971 (interactive)
12972 (let* ((org-agenda-skip-unavailable-files nil)
12973 (file (or file buffer-file-name))
12974 (true-file (file-truename file))
12975 (afile (abbreviate-file-name file))
12976 (files (delq nil (mapcar
12977 (lambda (x)
12978 (if (equal true-file
12979 (file-truename x))
12980 nil x))
12981 (org-agenda-files t)))))
12982 (if (not (= (length files) (length (org-agenda-files t))))
12983 (progn
12984 (org-store-new-agenda-file-list files)
12985 (org-install-agenda-files-menu)
12986 (message "Removed file: %s" afile))
12987 (message "File was not in list: %s (not removed)" afile))))
12989 (defun org-file-menu-entry (file)
12990 (vector file (list 'find-file file) t))
12992 (defun org-check-agenda-file (file)
12993 "Make sure FILE exists. If not, ask user what to do."
12994 (when (not (file-exists-p file))
12995 (message "non-existent file %s. [R]emove from list or [A]bort?"
12996 (abbreviate-file-name file))
12997 (let ((r (downcase (read-char-exclusive))))
12998 (cond
12999 ((equal r ?r)
13000 (org-remove-file file)
13001 (throw 'nextfile t))
13002 (t (error "Abort"))))))
13004 (defun org-get-agenda-file-buffer (file)
13005 "Get a buffer visiting FILE. If the buffer needs to be created, add
13006 it to the list of buffers which might be released later."
13007 (let ((buf (org-find-base-buffer-visiting file)))
13008 (if buf
13009 buf ; just return it
13010 ;; Make a new buffer and remember it
13011 (setq buf (find-file-noselect file))
13012 (if buf (push buf org-agenda-new-buffers))
13013 buf)))
13015 (defun org-release-buffers (blist)
13016 "Release all buffers in list, asking the user for confirmation when needed.
13017 When a buffer is unmodified, it is just killed. When modified, it is saved
13018 \(if the user agrees) and then killed."
13019 (let (buf file)
13020 (while (setq buf (pop blist))
13021 (setq file (buffer-file-name buf))
13022 (when (and (buffer-modified-p buf)
13023 file
13024 (y-or-n-p (format "Save file %s? " file)))
13025 (with-current-buffer buf (save-buffer)))
13026 (kill-buffer buf))))
13028 (defun org-prepare-agenda-buffers (files)
13029 "Create buffers for all agenda files, protect archived trees and comments."
13030 (interactive)
13031 (let ((pa '(:org-archived t))
13032 (pc '(:org-comment t))
13033 (pall '(:org-archived t :org-comment t))
13034 (inhibit-read-only t)
13035 (rea (concat ":" org-archive-tag ":"))
13036 bmp file re)
13037 (save-excursion
13038 (save-restriction
13039 (while (setq file (pop files))
13040 (if (bufferp file)
13041 (set-buffer file)
13042 (org-check-agenda-file file)
13043 (set-buffer (org-get-agenda-file-buffer file)))
13044 (widen)
13045 (setq bmp (buffer-modified-p))
13046 (org-refresh-category-properties)
13047 (setq org-todo-keywords-for-agenda
13048 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13049 (setq org-done-keywords-for-agenda
13050 (append org-done-keywords-for-agenda org-done-keywords))
13051 (setq org-todo-keyword-alist-for-agenda
13052 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13053 (setq org-tag-alist-for-agenda
13054 (append org-tag-alist-for-agenda org-tag-alist))
13056 (save-excursion
13057 (remove-text-properties (point-min) (point-max) pall)
13058 (when org-agenda-skip-archived-trees
13059 (goto-char (point-min))
13060 (while (re-search-forward rea nil t)
13061 (if (org-on-heading-p t)
13062 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13063 (goto-char (point-min))
13064 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13065 (while (re-search-forward re nil t)
13066 (add-text-properties
13067 (match-beginning 0) (org-end-of-subtree t) pc)))
13068 (set-buffer-modified-p bmp))))
13069 (setq org-todo-keyword-alist-for-agenda
13070 (org-uniquify org-todo-keyword-alist-for-agenda)
13071 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13073 ;;;; Embedded LaTeX
13075 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13076 "Keymap for the minor `org-cdlatex-mode'.")
13078 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13079 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13080 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13081 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13082 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13084 (defvar org-cdlatex-texmathp-advice-is-done nil
13085 "Flag remembering if we have applied the advice to texmathp already.")
13087 (define-minor-mode org-cdlatex-mode
13088 "Toggle the minor `org-cdlatex-mode'.
13089 This mode supports entering LaTeX environment and math in LaTeX fragments
13090 in Org-mode.
13091 \\{org-cdlatex-mode-map}"
13092 nil " OCDL" nil
13093 (when org-cdlatex-mode (require 'cdlatex))
13094 (unless org-cdlatex-texmathp-advice-is-done
13095 (setq org-cdlatex-texmathp-advice-is-done t)
13096 (defadvice texmathp (around org-math-always-on activate)
13097 "Always return t in org-mode buffers.
13098 This is because we want to insert math symbols without dollars even outside
13099 the LaTeX math segments. If Orgmode thinks that point is actually inside
13100 an embedded LaTeX fragment, let texmathp do its job.
13101 \\[org-cdlatex-mode-map]"
13102 (interactive)
13103 (let (p)
13104 (cond
13105 ((not (org-mode-p)) ad-do-it)
13106 ((eq this-command 'cdlatex-math-symbol)
13107 (setq ad-return-value t
13108 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13110 (let ((p (org-inside-LaTeX-fragment-p)))
13111 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13112 (setq ad-return-value t
13113 texmathp-why '("Org-mode embedded math" . 0))
13114 (if p ad-do-it)))))))))
13116 (defun turn-on-org-cdlatex ()
13117 "Unconditionally turn on `org-cdlatex-mode'."
13118 (org-cdlatex-mode 1))
13120 (defun org-inside-LaTeX-fragment-p ()
13121 "Test if point is inside a LaTeX fragment.
13122 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13123 sequence appearing also before point.
13124 Even though the matchers for math are configurable, this function assumes
13125 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13126 delimiters are skipped when they have been removed by customization.
13127 The return value is nil, or a cons cell with the delimiter and
13128 and the position of this delimiter.
13130 This function does a reasonably good job, but can locally be fooled by
13131 for example currency specifications. For example it will assume being in
13132 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13133 fragments that are properly closed, but during editing, we have to live
13134 with the uncertainty caused by missing closing delimiters. This function
13135 looks only before point, not after."
13136 (catch 'exit
13137 (let ((pos (point))
13138 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13139 (lim (progn
13140 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13141 (point)))
13142 dd-on str (start 0) m re)
13143 (goto-char pos)
13144 (when dodollar
13145 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13146 re (nth 1 (assoc "$" org-latex-regexps)))
13147 (while (string-match re str start)
13148 (cond
13149 ((= (match-end 0) (length str))
13150 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13151 ((= (match-end 0) (- (length str) 5))
13152 (throw 'exit nil))
13153 (t (setq start (match-end 0))))))
13154 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13155 (goto-char pos)
13156 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13157 (and (match-beginning 2) (throw 'exit nil))
13158 ;; count $$
13159 (while (re-search-backward "\\$\\$" lim t)
13160 (setq dd-on (not dd-on)))
13161 (goto-char pos)
13162 (if dd-on (cons "$$" m))))))
13165 (defun org-try-cdlatex-tab ()
13166 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13167 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13168 - inside a LaTeX fragment, or
13169 - after the first word in a line, where an abbreviation expansion could
13170 insert a LaTeX environment."
13171 (when org-cdlatex-mode
13172 (cond
13173 ((save-excursion
13174 (skip-chars-backward "a-zA-Z0-9*")
13175 (skip-chars-backward " \t")
13176 (bolp))
13177 (cdlatex-tab) t)
13178 ((org-inside-LaTeX-fragment-p)
13179 (cdlatex-tab) t)
13180 (t nil))))
13182 (defun org-cdlatex-underscore-caret (&optional arg)
13183 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13184 Revert to the normal definition outside of these fragments."
13185 (interactive "P")
13186 (if (org-inside-LaTeX-fragment-p)
13187 (call-interactively 'cdlatex-sub-superscript)
13188 (let (org-cdlatex-mode)
13189 (call-interactively (key-binding (vector last-input-event))))))
13191 (defun org-cdlatex-math-modify (&optional arg)
13192 "Execute `cdlatex-math-modify' in LaTeX fragments.
13193 Revert to the normal definition outside of these fragments."
13194 (interactive "P")
13195 (if (org-inside-LaTeX-fragment-p)
13196 (call-interactively 'cdlatex-math-modify)
13197 (let (org-cdlatex-mode)
13198 (call-interactively (key-binding (vector last-input-event))))))
13200 (defvar org-latex-fragment-image-overlays nil
13201 "List of overlays carrying the images of latex fragments.")
13202 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13204 (defun org-remove-latex-fragment-image-overlays ()
13205 "Remove all overlays with LaTeX fragment images in current buffer."
13206 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13207 (setq org-latex-fragment-image-overlays nil))
13209 (defun org-preview-latex-fragment (&optional subtree)
13210 "Preview the LaTeX fragment at point, or all locally or globally.
13211 If the cursor is in a LaTeX fragment, create the image and overlay
13212 it over the source code. If there is no fragment at point, display
13213 all fragments in the current text, from one headline to the next. With
13214 prefix SUBTREE, display all fragments in the current subtree. With a
13215 double prefix `C-u C-u', or when the cursor is before the first headline,
13216 display all fragments in the buffer.
13217 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13218 (interactive "P")
13219 (org-remove-latex-fragment-image-overlays)
13220 (save-excursion
13221 (save-restriction
13222 (let (beg end at msg)
13223 (cond
13224 ((or (equal subtree '(16))
13225 (not (save-excursion
13226 (re-search-backward (concat "^" outline-regexp) nil t))))
13227 (setq beg (point-min) end (point-max)
13228 msg "Creating images for buffer...%s"))
13229 ((equal subtree '(4))
13230 (org-back-to-heading)
13231 (setq beg (point) end (org-end-of-subtree t)
13232 msg "Creating images for subtree...%s"))
13234 (if (setq at (org-inside-LaTeX-fragment-p))
13235 (goto-char (max (point-min) (- (cdr at) 2)))
13236 (org-back-to-heading))
13237 (setq beg (point) end (progn (outline-next-heading) (point))
13238 msg (if at "Creating image...%s"
13239 "Creating images for entry...%s"))))
13240 (message msg "")
13241 (narrow-to-region beg end)
13242 (goto-char beg)
13243 (org-format-latex
13244 (concat "ltxpng/" (file-name-sans-extension
13245 (file-name-nondirectory
13246 buffer-file-name)))
13247 default-directory 'overlays msg at 'forbuffer)
13248 (message msg "done. Use `C-c C-c' to remove images.")))))
13250 (defvar org-latex-regexps
13251 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13252 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13253 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13254 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13255 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13256 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13257 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13258 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13259 "Regular expressions for matching embedded LaTeX.")
13261 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13262 "Replace LaTeX fragments with links to an image, and produce images."
13263 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13264 (let* ((prefixnodir (file-name-nondirectory prefix))
13265 (absprefix (expand-file-name prefix dir))
13266 (todir (file-name-directory absprefix))
13267 (opt org-format-latex-options)
13268 (matchers (plist-get opt :matchers))
13269 (re-list org-latex-regexps)
13270 (cnt 0) txt link beg end re e checkdir
13271 m n block linkfile movefile ov)
13272 ;; Check if there are old images files with this prefix, and remove them
13273 (when (file-directory-p todir)
13274 (mapc 'delete-file
13275 (directory-files
13276 todir 'full
13277 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13278 ;; Check the different regular expressions
13279 (while (setq e (pop re-list))
13280 (setq m (car e) re (nth 1 e) n (nth 2 e)
13281 block (if (nth 3 e) "\n\n" ""))
13282 (when (member m matchers)
13283 (goto-char (point-min))
13284 (while (re-search-forward re nil t)
13285 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13286 (not (get-text-property (match-beginning n)
13287 'org-protected)))
13288 (setq txt (match-string n)
13289 beg (match-beginning n) end (match-end n)
13290 cnt (1+ cnt)
13291 linkfile (format "%s_%04d.png" prefix cnt)
13292 movefile (format "%s_%04d.png" absprefix cnt)
13293 link (concat block "[[file:" linkfile "]]" block))
13294 (if msg (message msg cnt))
13295 (goto-char beg)
13296 (unless checkdir ; make sure the directory exists
13297 (setq checkdir t)
13298 (or (file-directory-p todir) (make-directory todir)))
13299 (org-create-formula-image
13300 txt movefile opt forbuffer)
13301 (if overlays
13302 (progn
13303 (setq ov (org-make-overlay beg end))
13304 (if (featurep 'xemacs)
13305 (progn
13306 (org-overlay-put ov 'invisible t)
13307 (org-overlay-put
13308 ov 'end-glyph
13309 (make-glyph (vector 'png :file movefile))))
13310 (org-overlay-put
13311 ov 'display
13312 (list 'image :type 'png :file movefile :ascent 'center)))
13313 (push ov org-latex-fragment-image-overlays)
13314 (goto-char end))
13315 (delete-region beg end)
13316 (insert link))))))))
13318 ;; This function borrows from Ganesh Swami's latex2png.el
13319 (defun org-create-formula-image (string tofile options buffer)
13320 (let* ((tmpdir (if (featurep 'xemacs)
13321 (temp-directory)
13322 temporary-file-directory))
13323 (texfilebase (make-temp-name
13324 (expand-file-name "orgtex" tmpdir)))
13325 (texfile (concat texfilebase ".tex"))
13326 (dvifile (concat texfilebase ".dvi"))
13327 (pngfile (concat texfilebase ".png"))
13328 (fnh (if (featurep 'xemacs)
13329 (font-height (get-face-font 'default))
13330 (face-attribute 'default :height nil)))
13331 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13332 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13333 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13334 "Black"))
13335 (bg (or (plist-get options (if buffer :background :html-background))
13336 "Transparent")))
13337 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13338 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13339 (with-temp-file texfile
13340 (insert org-format-latex-header
13341 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13342 (let ((dir default-directory))
13343 (condition-case nil
13344 (progn
13345 (cd tmpdir)
13346 (call-process "latex" nil nil nil texfile))
13347 (error nil))
13348 (cd dir))
13349 (if (not (file-exists-p dvifile))
13350 (progn (message "Failed to create dvi file from %s" texfile) nil)
13351 (condition-case nil
13352 (call-process "dvipng" nil nil nil
13353 "-E" "-fg" fg "-bg" bg
13354 "-D" dpi
13355 ;;"-x" scale "-y" scale
13356 "-T" "tight"
13357 "-o" pngfile
13358 dvifile)
13359 (error nil))
13360 (if (not (file-exists-p pngfile))
13361 (progn (message "Failed to create png file from %s" texfile) nil)
13362 ;; Use the requested file name and clean up
13363 (copy-file pngfile tofile 'replace)
13364 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13365 (delete-file (concat texfilebase e)))
13366 pngfile))))
13368 (defun org-dvipng-color (attr)
13369 "Return an rgb color specification for dvipng."
13370 (apply 'format "rgb %s %s %s"
13371 (mapcar 'org-normalize-color
13372 (color-values (face-attribute 'default attr nil)))))
13374 (defun org-normalize-color (value)
13375 "Return string to be used as color value for an RGB component."
13376 (format "%g" (/ value 65535.0)))
13378 ;;;; Key bindings
13380 ;; Make `C-c C-x' a prefix key
13381 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13383 ;; TAB key with modifiers
13384 (org-defkey org-mode-map "\C-i" 'org-cycle)
13385 (org-defkey org-mode-map [(tab)] 'org-cycle)
13386 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13387 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13388 (org-defkey org-mode-map "\M-\t" 'org-complete)
13389 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13390 ;; The following line is necessary under Suse GNU/Linux
13391 (unless (featurep 'xemacs)
13392 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13393 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13394 (define-key org-mode-map [backtab] 'org-shifttab)
13396 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13397 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13398 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13400 ;; Cursor keys with modifiers
13401 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13402 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13403 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13404 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13406 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13407 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13408 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13409 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13411 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13412 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13413 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13414 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13416 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13417 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13419 ;;; Extra keys for tty access.
13420 ;; We only set them when really needed because otherwise the
13421 ;; menus don't show the simple keys
13423 (when (or org-use-extra-keys
13424 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13425 (not window-system))
13426 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13427 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13428 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13429 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13430 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13431 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13432 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13433 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13434 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13435 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13436 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13437 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13438 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13439 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13440 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13441 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13442 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13443 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13444 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13445 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13446 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13447 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13449 ;; All the other keys
13451 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13452 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13453 (if (boundp 'narrow-map)
13454 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13455 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13456 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13457 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13458 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13459 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13460 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13461 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13462 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13463 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13464 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13465 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13466 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13467 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13468 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13469 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13470 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13471 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13472 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13473 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13474 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13475 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13476 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13477 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13478 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13479 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13480 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13481 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13482 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13483 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13484 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13485 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13486 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13487 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13488 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13489 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13490 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13491 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13492 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13493 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13494 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13495 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13496 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13497 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13498 (org-defkey org-mode-map "\C-c^" 'org-sort)
13499 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13500 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13501 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13502 (org-defkey org-mode-map "\C-m" 'org-return)
13503 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13504 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13505 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13506 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13507 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13508 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13509 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13510 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13511 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13512 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13513 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13514 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13515 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13516 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13517 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13518 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13519 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13521 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13522 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13523 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13524 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13526 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13527 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13528 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13529 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13530 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13531 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13532 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13533 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13534 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13535 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13536 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13537 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13538 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13540 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13541 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13542 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13543 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13545 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13547 (define-key org-mode-map "\C-c\C-xr" 'org-reload)
13549 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
13550 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
13552 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
13555 (when (featurep 'xemacs)
13556 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13559 (defvar org-self-insert-command-undo-counter 0)
13561 (defvar org-table-auto-blank-field) ; defined in org-table.el
13562 (defun org-self-insert-command (N)
13563 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13564 If the cursor is in a table looking at whitespace, the whitespace is
13565 overwritten, and the table is not marked as requiring realignment."
13566 (interactive "p")
13567 (if (and
13568 (org-table-p)
13569 (progn
13570 ;; check if we blank the field, and if that triggers align
13571 (and (featurep 'org-table) org-table-auto-blank-field
13572 (member last-command
13573 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13574 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13575 ;; got extra space, this field does not determine column width
13576 (let (org-table-may-need-update) (org-table-blank-field))
13577 ;; no extra space, this field may determine column width
13578 (org-table-blank-field)))
13580 (eq N 1)
13581 (looking-at "[^|\n]* |"))
13582 (let (org-table-may-need-update)
13583 (goto-char (1- (match-end 0)))
13584 (delete-backward-char 1)
13585 (goto-char (match-beginning 0))
13586 (self-insert-command N))
13587 (setq org-table-may-need-update t)
13588 (self-insert-command N)
13589 (org-fix-tags-on-the-fly)
13590 (if org-self-insert-cluster-for-undo
13591 (if (not (eq last-command 'org-self-insert-command))
13592 (setq org-self-insert-command-undo-counter 1)
13593 (if (>= org-self-insert-command-undo-counter 20)
13594 (setq org-self-insert-command-undo-counter 1)
13595 (and (> org-self-insert-command-undo-counter 0)
13596 buffer-undo-list
13597 (not (cadr buffer-undo-list)) ; remove nil entry
13598 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13599 (setq org-self-insert-command-undo-counter
13600 (1+ org-self-insert-command-undo-counter)))))))
13602 (defun org-fix-tags-on-the-fly ()
13603 (when (and (equal (char-after (point-at-bol)) ?*)
13604 (org-on-heading-p))
13605 (org-align-tags-here org-tags-column)))
13607 (defun org-delete-backward-char (N)
13608 "Like `delete-backward-char', insert whitespace at field end in tables.
13609 When deleting backwards, in tables this function will insert whitespace in
13610 front of the next \"|\" separator, to keep the table aligned. The table will
13611 still be marked for re-alignment if the field did fill the entire column,
13612 because, in this case the deletion might narrow the column."
13613 (interactive "p")
13614 (if (and (org-table-p)
13615 (eq N 1)
13616 (string-match "|" (buffer-substring (point-at-bol) (point)))
13617 (looking-at ".*?|"))
13618 (let ((pos (point))
13619 (noalign (looking-at "[^|\n\r]* |"))
13620 (c org-table-may-need-update))
13621 (backward-delete-char N)
13622 (skip-chars-forward "^|")
13623 (insert " ")
13624 (goto-char (1- pos))
13625 ;; noalign: if there were two spaces at the end, this field
13626 ;; does not determine the width of the column.
13627 (if noalign (setq org-table-may-need-update c)))
13628 (backward-delete-char N)
13629 (org-fix-tags-on-the-fly)))
13631 (defun org-delete-char (N)
13632 "Like `delete-char', but insert whitespace at field end in tables.
13633 When deleting characters, in tables this function will insert whitespace in
13634 front of the next \"|\" separator, to keep the table aligned. The table will
13635 still be marked for re-alignment if the field did fill the entire column,
13636 because, in this case the deletion might narrow the column."
13637 (interactive "p")
13638 (if (and (org-table-p)
13639 (not (bolp))
13640 (not (= (char-after) ?|))
13641 (eq N 1))
13642 (if (looking-at ".*?|")
13643 (let ((pos (point))
13644 (noalign (looking-at "[^|\n\r]* |"))
13645 (c org-table-may-need-update))
13646 (replace-match (concat
13647 (substring (match-string 0) 1 -1)
13648 " |"))
13649 (goto-char pos)
13650 ;; noalign: if there were two spaces at the end, this field
13651 ;; does not determine the width of the column.
13652 (if noalign (setq org-table-may-need-update c)))
13653 (delete-char N))
13654 (delete-char N)
13655 (org-fix-tags-on-the-fly)))
13657 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13658 (put 'org-self-insert-command 'delete-selection t)
13659 (put 'orgtbl-self-insert-command 'delete-selection t)
13660 (put 'org-delete-char 'delete-selection 'supersede)
13661 (put 'org-delete-backward-char 'delete-selection 'supersede)
13662 (put 'org-yank 'delete-selection 'yank)
13664 ;; Make `flyspell-mode' delay after some commands
13665 (put 'org-self-insert-command 'flyspell-delayed t)
13666 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13667 (put 'org-delete-char 'flyspell-delayed t)
13668 (put 'org-delete-backward-char 'flyspell-delayed t)
13670 ;; Make pabbrev-mode expand after org-mode commands
13671 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13672 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13674 ;; How to do this: Measure non-white length of current string
13675 ;; If equal to column width, we should realign.
13677 (defun org-remap (map &rest commands)
13678 "In MAP, remap the functions given in COMMANDS.
13679 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13680 (let (new old)
13681 (while commands
13682 (setq old (pop commands) new (pop commands))
13683 (if (fboundp 'command-remapping)
13684 (org-defkey map (vector 'remap old) new)
13685 (substitute-key-definition old new map global-map)))))
13687 (when (eq org-enable-table-editor 'optimized)
13688 ;; If the user wants maximum table support, we need to hijack
13689 ;; some standard editing functions
13690 (org-remap org-mode-map
13691 'self-insert-command 'org-self-insert-command
13692 'delete-char 'org-delete-char
13693 'delete-backward-char 'org-delete-backward-char)
13694 (org-defkey org-mode-map "|" 'org-force-self-insert))
13696 (defvar org-ctrl-c-ctrl-c-hook nil
13697 "Hook for functions attaching themselves to `C-c C-c'.
13698 This can be used to add additional functionality to the C-c C-c key which
13699 executes context-dependent commands.
13700 Each function will be called with no arguments. The function must check
13701 if the context is appropriate for it to act. If yes, it should do its
13702 thing and then return a non-nil value. If the context is wrong,
13703 just do nothing.")
13705 (defvar org-metaleft-hook nil
13706 "Hook for functions attaching themselves to `M-left'.
13707 See `org-ctrl-c-ctrl-c-hook' for more information.")
13708 (defvar org-metaright-hook nil
13709 "Hook for functions attaching themselves to `M-right'.
13710 See `org-ctrl-c-ctrl-c-hook' for more information.")
13711 (defvar org-metaup-hook nil
13712 "Hook for functions attaching themselves to `M-up'.
13713 See `org-ctrl-c-ctrl-c-hook' for more information.")
13714 (defvar org-metadown-hook nil
13715 "Hook for functions attaching themselves to `M-down'.
13716 See `org-ctrl-c-ctrl-c-hook' for more information.")
13717 (defvar org-shiftmetaleft-hook nil
13718 "Hook for functions attaching themselves to `M-S-left'.
13719 See `org-ctrl-c-ctrl-c-hook' for more information.")
13720 (defvar org-shiftmetaright-hook nil
13721 "Hook for functions attaching themselves to `M-S-right'.
13722 See `org-ctrl-c-ctrl-c-hook' for more information.")
13723 (defvar org-shiftmetaup-hook nil
13724 "Hook for functions attaching themselves to `M-S-up'.
13725 See `org-ctrl-c-ctrl-c-hook' for more information.")
13726 (defvar org-shiftmetadown-hook nil
13727 "Hook for functions attaching themselves to `M-S-down'.
13728 See `org-ctrl-c-ctrl-c-hook' for more information.")
13729 (defvar org-metareturn-hook nil
13730 "Hook for functions attaching themselves to `M-RET'.
13731 See `org-ctrl-c-ctrl-c-hook' for more information.")
13733 (defun org-modifier-cursor-error ()
13734 "Throw an error, a modified cursor command was applied in wrong context."
13735 (error "This command is active in special context like tables, headlines or items"))
13737 (defun org-shiftselect-error ()
13738 "Throw an error because Shift-Cursor command was applied in wrong context."
13739 (if (and (boundp 'shift-select-mode) shift-select-mode)
13740 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13741 (error "This command works only in special context like headlines or timestamps.")))
13743 (defun org-call-for-shift-select (cmd)
13744 (let ((this-command-keys-shift-translated t))
13745 (call-interactively cmd)))
13747 (defun org-shifttab (&optional arg)
13748 "Global visibility cycling or move to previous table field.
13749 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13750 on context.
13751 See the individual commands for more information."
13752 (interactive "P")
13753 (cond
13754 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13755 ((integerp arg)
13756 (message "Content view to level: %d" arg)
13757 (org-content (prefix-numeric-value arg))
13758 (setq org-cycle-global-status 'overview))
13759 (t (call-interactively 'org-global-cycle))))
13761 (defun org-shiftmetaleft ()
13762 "Promote subtree or delete table column.
13763 Calls `org-promote-subtree', `org-outdent-item',
13764 or `org-table-delete-column', depending on context.
13765 See the individual commands for more information."
13766 (interactive)
13767 (cond
13768 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13769 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13770 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13771 ((org-at-item-p) (call-interactively 'org-outdent-item))
13772 (t (org-modifier-cursor-error))))
13774 (defun org-shiftmetaright ()
13775 "Demote subtree or insert table column.
13776 Calls `org-demote-subtree', `org-indent-item',
13777 or `org-table-insert-column', depending on context.
13778 See the individual commands for more information."
13779 (interactive)
13780 (cond
13781 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13782 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13783 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13784 ((org-at-item-p) (call-interactively 'org-indent-item))
13785 (t (org-modifier-cursor-error))))
13787 (defun org-shiftmetaup (&optional arg)
13788 "Move subtree up or kill table row.
13789 Calls `org-move-subtree-up' or `org-table-kill-row' or
13790 `org-move-item-up' depending on context. See the individual commands
13791 for more information."
13792 (interactive "P")
13793 (cond
13794 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13795 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13796 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13797 ((org-at-item-p) (call-interactively 'org-move-item-up))
13798 (t (org-modifier-cursor-error))))
13800 (defun org-shiftmetadown (&optional arg)
13801 "Move subtree down or insert table row.
13802 Calls `org-move-subtree-down' or `org-table-insert-row' or
13803 `org-move-item-down', depending on context. See the individual
13804 commands for more information."
13805 (interactive "P")
13806 (cond
13807 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13808 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13809 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13810 ((org-at-item-p) (call-interactively 'org-move-item-down))
13811 (t (org-modifier-cursor-error))))
13813 (defun org-metaleft (&optional arg)
13814 "Promote heading or move table column to left.
13815 Calls `org-do-promote' or `org-table-move-column', depending on context.
13816 With no specific context, calls the Emacs default `backward-word'.
13817 See the individual commands for more information."
13818 (interactive "P")
13819 (cond
13820 ((run-hook-with-args-until-success 'org-metaleft-hook))
13821 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13822 ((or (org-on-heading-p)
13823 (and (org-region-active-p)
13824 (save-excursion
13825 (goto-char (region-beginning))
13826 (org-on-heading-p))))
13827 (call-interactively 'org-do-promote))
13828 ((or (org-at-item-p)
13829 (and (org-region-active-p)
13830 (save-excursion
13831 (goto-char (region-beginning))
13832 (org-at-item-p))))
13833 (call-interactively 'org-outdent-item))
13834 (t (call-interactively 'backward-word))))
13836 (defun org-metaright (&optional arg)
13837 "Demote subtree or move table column to right.
13838 Calls `org-do-demote' or `org-table-move-column', depending on context.
13839 With no specific context, calls the Emacs default `forward-word'.
13840 See the individual commands for more information."
13841 (interactive "P")
13842 (cond
13843 ((run-hook-with-args-until-success 'org-metaright-hook))
13844 ((org-at-table-p) (call-interactively 'org-table-move-column))
13845 ((or (org-on-heading-p)
13846 (and (org-region-active-p)
13847 (save-excursion
13848 (goto-char (region-beginning))
13849 (org-on-heading-p))))
13850 (call-interactively 'org-do-demote))
13851 ((or (org-at-item-p)
13852 (and (org-region-active-p)
13853 (save-excursion
13854 (goto-char (region-beginning))
13855 (org-at-item-p))))
13856 (call-interactively 'org-indent-item))
13857 (t (call-interactively 'forward-word))))
13859 (defun org-metaup (&optional arg)
13860 "Move subtree up or move table row up.
13861 Calls `org-move-subtree-up' or `org-table-move-row' or
13862 `org-move-item-up', depending on context. See the individual commands
13863 for more information."
13864 (interactive "P")
13865 (cond
13866 ((run-hook-with-args-until-success 'org-metaup-hook))
13867 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13868 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13869 ((org-at-item-p) (call-interactively 'org-move-item-up))
13870 (t (transpose-lines 1) (beginning-of-line -1))))
13872 (defun org-metadown (&optional arg)
13873 "Move subtree down or move table row down.
13874 Calls `org-move-subtree-down' or `org-table-move-row' or
13875 `org-move-item-down', depending on context. See the individual
13876 commands for more information."
13877 (interactive "P")
13878 (cond
13879 ((run-hook-with-args-until-success 'org-metadown-hook))
13880 ((org-at-table-p) (call-interactively 'org-table-move-row))
13881 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13882 ((org-at-item-p) (call-interactively 'org-move-item-down))
13883 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13885 (defun org-shiftup (&optional arg)
13886 "Increase item in timestamp or increase priority of current headline.
13887 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13888 depending on context. See the individual commands for more information."
13889 (interactive "P")
13890 (cond
13891 ((and org-support-shift-select (org-region-active-p))
13892 (org-call-for-shift-select 'previous-line))
13893 ((org-at-timestamp-p t)
13894 (call-interactively (if org-edit-timestamp-down-means-later
13895 'org-timestamp-down 'org-timestamp-up)))
13896 ((and (not (eq org-support-shift-select 'always))
13897 (org-on-heading-p))
13898 (call-interactively 'org-priority-up))
13899 ((and (not org-support-shift-select) (org-at-item-p))
13900 (call-interactively 'org-previous-item))
13901 ((org-clocktable-try-shift 'up arg))
13902 (org-support-shift-select
13903 (org-call-for-shift-select 'previous-line))
13904 (t (org-shiftselect-error))))
13906 (defun org-shiftdown (&optional arg)
13907 "Decrease item in timestamp or decrease priority of current headline.
13908 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13909 depending on context. See the individual commands for more information."
13910 (interactive "P")
13911 (cond
13912 ((and org-support-shift-select (org-region-active-p))
13913 (org-call-for-shift-select 'next-line))
13914 ((org-at-timestamp-p t)
13915 (call-interactively (if org-edit-timestamp-down-means-later
13916 'org-timestamp-up 'org-timestamp-down)))
13917 ((and (not (eq org-support-shift-select 'always))
13918 (org-on-heading-p))
13919 (call-interactively 'org-priority-down))
13920 ((and (not org-support-shift-select) (org-at-item-p))
13921 (call-interactively 'org-next-item))
13922 ((org-clocktable-try-shift 'down arg))
13923 (org-support-shift-select
13924 (org-call-for-shift-select 'next-line))
13925 (t (org-shiftselect-error))))
13927 (defun org-shiftright (&optional arg)
13928 "Cycle the thing at point or in the current line, depending on context.
13929 Depending on context, this does one of the following:
13931 - switch a timestamp at point one day into the future
13932 - on a headline, switch to the next TODO keyword.
13933 - on an item, switch entire list to the next bullet type
13934 - on a property line, switch to the next allowed value
13935 - on a clocktable definition line, move time block into the future"
13936 (interactive "P")
13937 (cond
13938 ((and org-support-shift-select (org-region-active-p))
13939 (org-call-for-shift-select 'forward-char))
13940 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13941 ((and (not (eq org-support-shift-select 'always))
13942 (org-on-heading-p))
13943 (org-call-with-arg 'org-todo 'right))
13944 ((or (and org-support-shift-select
13945 (not (eq org-support-shift-select 'always))
13946 (org-at-item-bullet-p))
13947 (and (not org-support-shift-select) (org-at-item-p)))
13948 (org-call-with-arg 'org-cycle-list-bullet nil))
13949 ((and (not (eq org-support-shift-select 'always))
13950 (org-at-property-p))
13951 (call-interactively 'org-property-next-allowed-value))
13952 ((org-clocktable-try-shift 'right arg))
13953 (org-support-shift-select
13954 (org-call-for-shift-select 'forward-char))
13955 (t (org-shiftselect-error))))
13957 (defun org-shiftleft (&optional arg)
13958 "Cycle the thing at point or in the current line, depending on context.
13959 Depending on context, this does one of the following:
13961 - switch a timestamp at point one day into the past
13962 - on a headline, switch to the previous TODO keyword.
13963 - on an item, switch entire list to the previous bullet type
13964 - on a property line, switch to the previous allowed value
13965 - on a clocktable definition line, move time block into the past"
13966 (interactive "P")
13967 (cond
13968 ((and org-support-shift-select (org-region-active-p))
13969 (org-call-for-shift-select 'backward-char))
13970 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13971 ((and (not (eq org-support-shift-select 'always))
13972 (org-on-heading-p))
13973 (org-call-with-arg 'org-todo 'left))
13974 ((or (and org-support-shift-select
13975 (not (eq org-support-shift-select 'always))
13976 (org-at-item-bullet-p))
13977 (and (not org-support-shift-select) (org-at-item-p)))
13978 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13979 ((and (not (eq org-support-shift-select 'always))
13980 (org-at-property-p))
13981 (call-interactively 'org-property-previous-allowed-value))
13982 ((org-clocktable-try-shift 'left arg))
13983 (org-support-shift-select
13984 (org-call-for-shift-select 'backward-char))
13985 (t (org-shiftselect-error))))
13987 (defun org-shiftcontrolright ()
13988 "Switch to next TODO set."
13989 (interactive)
13990 (cond
13991 ((and org-support-shift-select (org-region-active-p))
13992 (org-call-for-shift-select 'forward-word))
13993 ((and (not (eq org-support-shift-select 'always))
13994 (org-on-heading-p))
13995 (org-call-with-arg 'org-todo 'nextset))
13996 (org-support-shift-select
13997 (org-call-for-shift-select 'forward-word))
13998 (t (org-shiftselect-error))))
14000 (defun org-shiftcontrolleft ()
14001 "Switch to previous TODO set."
14002 (interactive)
14003 (cond
14004 ((and org-support-shift-select (org-region-active-p))
14005 (org-call-for-shift-select 'backward-word))
14006 ((and (not (eq org-support-shift-select 'always))
14007 (org-on-heading-p))
14008 (org-call-with-arg 'org-todo 'previousset))
14009 (org-support-shift-select
14010 (org-call-for-shift-select 'backward-word))
14011 (t (org-shiftselect-error))))
14013 (defun org-ctrl-c-ret ()
14014 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14015 (interactive)
14016 (cond
14017 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14018 (t (call-interactively 'org-insert-heading))))
14020 (defun org-copy-special ()
14021 "Copy region in table or copy current subtree.
14022 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14023 See the individual commands for more information."
14024 (interactive)
14025 (call-interactively
14026 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14028 (defun org-cut-special ()
14029 "Cut region in table or cut current subtree.
14030 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14031 See the individual commands for more information."
14032 (interactive)
14033 (call-interactively
14034 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14036 (defun org-paste-special (arg)
14037 "Paste rectangular region into table, or past subtree relative to level.
14038 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14039 See the individual commands for more information."
14040 (interactive "P")
14041 (if (org-at-table-p)
14042 (org-table-paste-rectangle)
14043 (org-paste-subtree arg)))
14045 (defun org-edit-special ()
14046 "Call a special editor for the stuff at point.
14047 When at a table, call the formula editor with `org-table-edit-formulas'.
14048 When at the first line of an src example, call `org-edit-src-code'.
14049 When in an #+include line, visit the include file. Otherwise call
14050 `ffap' to visit the file at point."
14051 (interactive)
14052 (cond
14053 ((org-at-table-p)
14054 (call-interactively 'org-table-edit-formulas))
14055 ((save-excursion
14056 (beginning-of-line 1)
14057 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14058 (find-file (org-trim (match-string 1))))
14059 ((org-edit-src-code))
14060 ((org-edit-fixed-width-region))
14061 (t (call-interactively 'ffap))))
14064 (defun org-ctrl-c-ctrl-c (&optional arg)
14065 "Set tags in headline, or update according to changed information at point.
14067 This command does many different things, depending on context:
14069 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14070 this is what we do.
14072 - If the cursor is in a headline, prompt for tags and insert them
14073 into the current line, aligned to `org-tags-column'. When called
14074 with prefix arg, realign all tags in the current buffer.
14076 - If the cursor is in one of the special #+KEYWORD lines, this
14077 triggers scanning the buffer for these lines and updating the
14078 information.
14080 - If the cursor is inside a table, realign the table. This command
14081 works even if the automatic table editor has been turned off.
14083 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14084 the entire table.
14086 - If the cursor is at a footnote reference or definition, jump to
14087 the corresponding definition or references, respectively.
14089 - If the cursor is a the beginning of a dynamic block, update it.
14091 - If the cursor is inside a table created by the table.el package,
14092 activate that table.
14094 - If the current buffer is a remember buffer, close note and file
14095 it. A prefix argument of 1 files to the default location
14096 without further interaction. A prefix argument of 2 files to
14097 the currently clocking task.
14099 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14100 links in this buffer.
14102 - If the cursor is on a numbered item in a plain list, renumber the
14103 ordered list.
14105 - If the cursor is on a checkbox, toggle it."
14106 (interactive "P")
14107 (let ((org-enable-table-editor t))
14108 (cond
14109 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14110 org-occur-highlights
14111 org-latex-fragment-image-overlays)
14112 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14113 (org-remove-occur-highlights)
14114 (org-remove-latex-fragment-image-overlays)
14115 (message "Temporary highlights/overlays removed from current buffer"))
14116 ((and (local-variable-p 'org-finish-function (current-buffer))
14117 (fboundp org-finish-function))
14118 (funcall org-finish-function))
14119 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14120 ((org-at-property-p)
14121 (call-interactively 'org-property-action))
14122 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14123 ((org-on-heading-p) (call-interactively 'org-set-tags))
14124 ((org-at-table.el-p)
14125 (require 'table)
14126 (beginning-of-line 1)
14127 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14128 (call-interactively 'table-recognize-table))
14129 ((org-at-table-p)
14130 (org-table-maybe-eval-formula)
14131 (if arg
14132 (call-interactively 'org-table-recalculate)
14133 (org-table-maybe-recalculate-line))
14134 (call-interactively 'org-table-align))
14135 ((or (org-footnote-at-reference-p)
14136 (org-footnote-at-definition-p))
14137 (call-interactively 'org-footnote-action))
14138 ((org-at-item-checkbox-p)
14139 (call-interactively 'org-toggle-checkbox))
14140 ((org-at-item-p)
14141 (if arg
14142 (call-interactively 'org-toggle-checkbox)
14143 (call-interactively 'org-maybe-renumber-ordered-list)))
14144 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14145 ;; Dynamic block
14146 (beginning-of-line 1)
14147 (save-excursion (org-update-dblock)))
14148 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14149 (cond
14150 ((equal (match-string 1) "TBLFM")
14151 ;; Recalculate the table before this line
14152 (save-excursion
14153 (beginning-of-line 1)
14154 (skip-chars-backward " \r\n\t")
14155 (if (org-at-table-p)
14156 (org-call-with-arg 'org-table-recalculate t))))
14158 ; (org-set-regexps-and-options)
14159 ; (org-restart-font-lock)
14160 (let ((org-inhibit-startup t)) (org-mode-restart))
14161 (message "Local setup has been refreshed"))))
14162 (t (error "C-c C-c can do nothing useful at this location.")))))
14164 (defun org-mode-restart ()
14165 "Restart Org-mode, to scan again for special lines.
14166 Also updates the keyword regular expressions."
14167 (interactive)
14168 (org-mode)
14169 (message "Org-mode restarted"))
14171 (defun org-kill-note-or-show-branches ()
14172 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14173 (interactive)
14174 (if (not org-finish-function)
14175 (call-interactively 'show-branches)
14176 (let ((org-note-abort t))
14177 (funcall org-finish-function))))
14179 (defun org-return (&optional indent)
14180 "Goto next table row or insert a newline.
14181 Calls `org-table-next-row' or `newline', depending on context.
14182 See the individual commands for more information."
14183 (interactive)
14184 (cond
14185 ((bobp) (if indent (newline-and-indent) (newline)))
14186 ((org-at-table-p)
14187 (org-table-justify-field-maybe)
14188 (call-interactively 'org-table-next-row))
14189 ((and org-return-follows-link
14190 (eq (get-text-property (point) 'face) 'org-link))
14191 (call-interactively 'org-open-at-point))
14192 ((and (org-at-heading-p)
14193 (looking-at
14194 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14195 (org-show-entry)
14196 (end-of-line 1)
14197 (newline))
14198 (t (if indent (newline-and-indent) (newline)))))
14200 (defun org-return-indent ()
14201 "Goto next table row or insert a newline and indent.
14202 Calls `org-table-next-row' or `newline-and-indent', depending on
14203 context. See the individual commands for more information."
14204 (interactive)
14205 (org-return t))
14207 (defun org-ctrl-c-star ()
14208 "Compute table, or change heading status of lines.
14209 Calls `org-table-recalculate' or `org-toggle-heading',
14210 depending on context."
14211 (interactive)
14212 (cond
14213 ((org-at-table-p)
14214 (call-interactively 'org-table-recalculate))
14216 ;; Convert all lines in region to list items
14217 (call-interactively 'org-toggle-heading))))
14219 (defun org-ctrl-c-minus ()
14220 "Insert separator line in table or modify bullet status of line.
14221 Also turns a plain line or a region of lines into list items.
14222 Calls `org-table-insert-hline', `org-toggle-item', or
14223 `org-cycle-list-bullet', depending on context."
14224 (interactive)
14225 (cond
14226 ((org-at-table-p)
14227 (call-interactively 'org-table-insert-hline))
14228 ((org-region-active-p)
14229 (call-interactively 'org-toggle-item))
14230 ((org-in-item-p)
14231 (call-interactively 'org-cycle-list-bullet))
14233 (call-interactively 'org-toggle-item))))
14235 (defun org-toggle-item ()
14236 "Convert headings or normal lines to items, items to normal lines.
14237 If there is no active region, only the current line is considered.
14239 If the first line in the region is a headline, convert all headlines to items.
14241 If the first line in the region is an item, convert all items to normal lines.
14243 If the first line is normal text, add an item bullet to each line."
14244 (interactive)
14245 (let (l2 l beg end)
14246 (if (org-region-active-p)
14247 (setq beg (region-beginning) end (region-end))
14248 (setq beg (point-at-bol)
14249 end (min (1+ (point-at-eol)) (point-max))))
14250 (save-excursion
14251 (goto-char end)
14252 (setq l2 (org-current-line))
14253 (goto-char beg)
14254 (beginning-of-line 1)
14255 (setq l (1- (org-current-line)))
14256 (if (org-at-item-p)
14257 ;; We already have items, de-itemize
14258 (while (< (setq l (1+ l)) l2)
14259 (when (org-at-item-p)
14260 (goto-char (match-beginning 2))
14261 (delete-region (match-beginning 2) (match-end 2))
14262 (and (looking-at "[ \t]+") (replace-match "")))
14263 (beginning-of-line 2))
14264 (if (org-on-heading-p)
14265 ;; Headings, convert to items
14266 (while (< (setq l (1+ l)) l2)
14267 (if (looking-at org-outline-regexp)
14268 (replace-match "- " t t))
14269 (beginning-of-line 2))
14270 ;; normal lines, turn them into items
14271 (while (< (setq l (1+ l)) l2)
14272 (unless (org-at-item-p)
14273 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14274 (replace-match "\\1- \\2")))
14275 (beginning-of-line 2)))))))
14277 (defun org-toggle-heading (&optional nstars)
14278 "Convert headings to normal text, or items or text to headings.
14279 If there is no active region, only the current line is considered.
14281 If the first line is a heading, remove the stars from all headlines
14282 in the region.
14284 If the first line is a plain list item, turn all plain list items into
14285 headings.
14287 If the first line is a normal line, turn each and every line in the region
14288 into a heading.
14290 When converting a line into a heading, the number of stars is chosen
14291 such that the lines become children of the current entry. However, when
14292 a prefix argument is given, its value determines the number of stars to add."
14293 (interactive "P")
14294 (let (l2 l itemp beg end)
14295 (if (org-region-active-p)
14296 (setq beg (region-beginning) end (region-end))
14297 (setq beg (point-at-bol)
14298 end (min (1+ (point-at-eol)) (point-max))))
14299 (save-excursion
14300 (goto-char end)
14301 (setq l2 (org-current-line))
14302 (goto-char beg)
14303 (beginning-of-line 1)
14304 (setq l (1- (org-current-line)))
14305 (if (org-on-heading-p)
14306 ;; We already have headlines, de-star them
14307 (while (< (setq l (1+ l)) l2)
14308 (when (org-on-heading-p t)
14309 (and (looking-at outline-regexp) (replace-match "")))
14310 (beginning-of-line 2))
14311 (setq itemp (org-at-item-p))
14312 (let* ((stars
14313 (if nstars
14314 (make-string (prefix-numeric-value current-prefix-arg)
14316 (save-excursion
14317 (re-search-backward org-complex-heading-regexp nil t)
14318 (or (match-string 1) ""))))
14319 (add-stars (cond (nstars "")
14320 ((equal stars "") "*")
14321 (org-odd-levels-only "**")
14322 (t "*")))
14323 (rpl (concat stars add-stars " ")))
14324 (while (< (setq l (1+ l)) l2)
14325 (if itemp
14326 (and (org-at-item-p) (replace-match rpl t t))
14327 (unless (org-on-heading-p)
14328 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14329 (replace-match (concat rpl (match-string 2))))))
14330 (beginning-of-line 2)))))))
14332 (defun org-meta-return (&optional arg)
14333 "Insert a new heading or wrap a region in a table.
14334 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14335 See the individual commands for more information."
14336 (interactive "P")
14337 (cond
14338 ((run-hook-with-args-until-success 'org-metareturn-hook))
14339 ((org-at-table-p)
14340 (call-interactively 'org-table-wrap-region))
14341 (t (call-interactively 'org-insert-heading))))
14343 ;;; Menu entries
14345 ;; Define the Org-mode menus
14346 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14347 '("Tbl"
14348 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14349 ["Next Field" org-cycle (org-at-table-p)]
14350 ["Previous Field" org-shifttab (org-at-table-p)]
14351 ["Next Row" org-return (org-at-table-p)]
14352 "--"
14353 ["Blank Field" org-table-blank-field (org-at-table-p)]
14354 ["Edit Field" org-table-edit-field (org-at-table-p)]
14355 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14356 "--"
14357 ("Column"
14358 ["Move Column Left" org-metaleft (org-at-table-p)]
14359 ["Move Column Right" org-metaright (org-at-table-p)]
14360 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14361 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14362 ("Row"
14363 ["Move Row Up" org-metaup (org-at-table-p)]
14364 ["Move Row Down" org-metadown (org-at-table-p)]
14365 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14366 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14367 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14368 "--"
14369 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14370 ("Rectangle"
14371 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14372 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14373 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14374 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14375 "--"
14376 ("Calculate"
14377 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14378 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14379 ["Edit Formulas" org-edit-special (org-at-table-p)]
14380 "--"
14381 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14382 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14383 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14384 "--"
14385 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14386 "--"
14387 ["Sum Column/Rectangle" org-table-sum
14388 (or (org-at-table-p) (org-region-active-p))]
14389 ["Which Column?" org-table-current-column (org-at-table-p)])
14390 ["Debug Formulas"
14391 org-table-toggle-formula-debugger
14392 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14393 ["Show Col/Row Numbers"
14394 org-table-toggle-coordinate-overlays
14395 :style toggle
14396 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14397 "--"
14398 ["Create" org-table-create (and (not (org-at-table-p))
14399 org-enable-table-editor)]
14400 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14401 ["Import from File" org-table-import (not (org-at-table-p))]
14402 ["Export to File" org-table-export (org-at-table-p)]
14403 "--"
14404 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14406 (easy-menu-define org-org-menu org-mode-map "Org menu"
14407 '("Org"
14408 ("Show/Hide"
14409 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14410 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14411 ["Sparse Tree..." org-sparse-tree t]
14412 ["Reveal Context" org-reveal t]
14413 ["Show All" show-all t]
14414 "--"
14415 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14416 "--"
14417 ["New Heading" org-insert-heading t]
14418 ("Navigate Headings"
14419 ["Up" outline-up-heading t]
14420 ["Next" outline-next-visible-heading t]
14421 ["Previous" outline-previous-visible-heading t]
14422 ["Next Same Level" outline-forward-same-level t]
14423 ["Previous Same Level" outline-backward-same-level t]
14424 "--"
14425 ["Jump" org-goto t])
14426 ("Edit Structure"
14427 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14428 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14429 "--"
14430 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14431 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14432 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14433 "--"
14434 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14435 "--"
14436 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14437 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14438 ["Demote Heading" org-metaright (not (org-at-table-p))]
14439 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14440 "--"
14441 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14442 "--"
14443 ["Convert to odd levels" org-convert-to-odd-levels t]
14444 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14445 ("Editing"
14446 ["Emphasis..." org-emphasize t]
14447 ["Edit Source Example" org-edit-special t]
14448 "--"
14449 ["Footnote new/jump" org-footnote-action t]
14450 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14451 ("Archive"
14452 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14453 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14454 ; :active t :keys "C-u C-c C-x C-a"]
14455 ["Sparse trees open ARCHIVE trees"
14456 (setq org-sparse-tree-open-archived-trees
14457 (not org-sparse-tree-open-archived-trees))
14458 :style toggle :selected org-sparse-tree-open-archived-trees]
14459 ["Cycling opens ARCHIVE trees"
14460 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14461 :style toggle :selected org-cycle-open-archived-trees]
14462 "--"
14463 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14464 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14465 ; ["Check and Move Children" (org-archive-subtree '(4))
14466 ; :active t :keys "C-u C-c C-x C-s"]
14468 "--"
14469 ("TODO Lists"
14470 ["TODO/DONE/-" org-todo t]
14471 ("Select keyword"
14472 ["Next keyword" org-shiftright (org-on-heading-p)]
14473 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14474 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14475 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14476 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14477 ["Show TODO Tree" org-show-todo-tree t]
14478 ["Global TODO list" org-todo-list t]
14479 "--"
14480 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14481 :selected org-enforce-todo-dependencies :style toggle :active t]
14482 "Settings for tree at point"
14483 ["Do Children sequentially" org-toggle-ordered-property :style radio
14484 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14485 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14486 ["Do Children parallel" org-toggle-ordered-property :style radio
14487 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14488 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14489 "--"
14490 ["Set Priority" org-priority t]
14491 ["Priority Up" org-shiftup t]
14492 ["Priority Down" org-shiftdown t]
14493 "--"
14494 ["Get news from all feeds" org-feed-update-all t]
14495 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
14496 ["Customize feeds" (customize-variable 'org-feed-alist) t])
14497 ("TAGS and Properties"
14498 ["Set Tags" org-set-tags-command t]
14499 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14500 "--"
14501 ["Set property" org-set-property t]
14502 ["Column view of properties" org-columns t]
14503 ["Insert Column View DBlock" org-insert-columns-dblock t])
14504 ("Dates and Scheduling"
14505 ["Timestamp" org-time-stamp t]
14506 ["Timestamp (inactive)" org-time-stamp-inactive t]
14507 ("Change Date"
14508 ["1 Day Later" org-shiftright t]
14509 ["1 Day Earlier" org-shiftleft t]
14510 ["1 ... Later" org-shiftup t]
14511 ["1 ... Earlier" org-shiftdown t])
14512 ["Compute Time Range" org-evaluate-time-range t]
14513 ["Schedule Item" org-schedule t]
14514 ["Deadline" org-deadline t]
14515 "--"
14516 ["Custom time format" org-toggle-time-stamp-overlays
14517 :style radio :selected org-display-custom-times]
14518 "--"
14519 ["Goto Calendar" org-goto-calendar t]
14520 ["Date from Calendar" org-date-from-calendar t]
14521 "--"
14522 ["Start/Restart Timer" org-timer-start t]
14523 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14524 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14525 ["Insert Timer String" org-timer t]
14526 ["Insert Timer Item" org-timer-item t])
14527 ("Logging work"
14528 ["Clock in" org-clock-in t]
14529 ["Clock out" org-clock-out t]
14530 ["Clock cancel" org-clock-cancel t]
14531 ["Goto running clock" org-clock-goto t]
14532 ["Display times" org-clock-display t]
14533 ["Create clock table" org-clock-report t]
14534 "--"
14535 ["Record DONE time"
14536 (progn (setq org-log-done (not org-log-done))
14537 (message "Switching to %s will %s record a timestamp"
14538 (car org-done-keywords)
14539 (if org-log-done "automatically" "not")))
14540 :style toggle :selected org-log-done])
14541 "--"
14542 ["Agenda Command..." org-agenda t]
14543 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14544 ("File List for Agenda")
14545 ("Special views current file"
14546 ["TODO Tree" org-show-todo-tree t]
14547 ["Check Deadlines" org-check-deadlines t]
14548 ["Timeline" org-timeline t]
14549 ["Tags/Property tree" org-match-sparse-tree t])
14550 "--"
14551 ("Hyperlinks"
14552 ["Store Link (Global)" org-store-link t]
14553 ["Insert Link" org-insert-link t]
14554 ["Follow Link" org-open-at-point t]
14555 "--"
14556 ["Next link" org-next-link t]
14557 ["Previous link" org-previous-link t]
14558 "--"
14559 ["Descriptive Links"
14560 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14561 :style radio
14562 :selected (member '(org-link) buffer-invisibility-spec)]
14563 ["Literal Links"
14564 (progn
14565 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14566 :style radio
14567 :selected (not (member '(org-link) buffer-invisibility-spec))])
14568 "--"
14569 ["Export/Publish..." org-export t]
14570 ("LaTeX"
14571 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14572 :selected org-cdlatex-mode]
14573 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14574 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14575 ["Modify math symbol" org-cdlatex-math-modify
14576 (org-inside-LaTeX-fragment-p)]
14577 ["Export LaTeX fragments as images"
14578 (if (featurep 'org-exp)
14579 (setq org-export-with-LaTeX-fragments
14580 (not org-export-with-LaTeX-fragments))
14581 (require 'org-exp))
14582 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14583 org-export-with-LaTeX-fragments)])
14584 "--"
14585 ("Documentation"
14586 ["Show Version" org-version t]
14587 ["Info Documentation" org-info t])
14588 ("Customize"
14589 ["Browse Org Group" org-customize t]
14590 "--"
14591 ["Expand This Menu" org-create-customize-menu
14592 (fboundp 'customize-menu-create)])
14593 "--"
14594 ("Refresh/Reload"
14595 ["Refresh setup current buffer" org-mode-restart t]
14596 ["Reload Org (after update)" org-reload t]
14597 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14600 (defun org-info (&optional node)
14601 "Read documentation for Org-mode in the info system.
14602 With optional NODE, go directly to that node."
14603 (interactive)
14604 (info (format "(org)%s" (or node ""))))
14606 (defun org-install-agenda-files-menu ()
14607 (let ((bl (buffer-list)))
14608 (save-excursion
14609 (while bl
14610 (set-buffer (pop bl))
14611 (if (org-mode-p) (setq bl nil)))
14612 (when (org-mode-p)
14613 (easy-menu-change
14614 '("Org") "File List for Agenda"
14615 (append
14616 (list
14617 ["Edit File List" (org-edit-agenda-file-list) t]
14618 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14619 ["Remove Current File from List" org-remove-file t]
14620 ["Cycle through agenda files" org-cycle-agenda-files t]
14621 ["Occur in all agenda files" org-occur-in-agenda-files t]
14622 "--")
14623 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14625 ;;;; Documentation
14627 ;;;###autoload
14628 (defun org-require-autoloaded-modules ()
14629 (interactive)
14630 (mapc 'require
14631 '(org-agenda org-archive org-attach org-clock org-colview
14632 org-exp org-id org-export-latex org-docbook.el
14633 org-publish org-remember org-table org-timer)))
14635 ;;;###autoload
14636 (defun org-reload (&optional uncompiled)
14637 "Reload all org lisp files.
14638 With prefix arg UNCOMPILED, load the uncompiled versions."
14639 (interactive "P")
14640 (require 'find-func)
14641 (let* ((dir (file-name-directory (find-library-name "org")))
14642 (files (directory-files dir t "\\.el\\'"))
14643 (remove-re (concat (if (featurep 'xemacs)
14644 "org-colview" "org-colview-xemacs")
14645 "\\'")))
14646 (setq files (mapcar 'file-name-sans-extension files))
14647 (setq files (mapcar
14648 (lambda (x) (if (string-match remove-re x) nil x))
14649 files))
14650 (setq files (delq nil files))
14651 (mapc
14652 (lambda (f)
14653 (if (and (not uncompiled)
14654 (file-exists-p (concat f ".elc")))
14655 (load (concat f ".elc") nil nil t)
14656 (load (concat f ".el") nil nil t)))
14657 files)))
14659 ;;;###autoload
14660 (defun org-customize ()
14661 "Call the customize function with org as argument."
14662 (interactive)
14663 (org-load-modules-maybe)
14664 (org-require-autoloaded-modules)
14665 (customize-browse 'org))
14667 (defun org-create-customize-menu ()
14668 "Create a full customization menu for Org-mode, insert it into the menu."
14669 (interactive)
14670 (org-load-modules-maybe)
14671 (org-require-autoloaded-modules)
14672 (if (fboundp 'customize-menu-create)
14673 (progn
14674 (easy-menu-change
14675 '("Org") "Customize"
14676 `(["Browse Org group" org-customize t]
14677 "--"
14678 ,(customize-menu-create 'org)
14679 ["Set" Custom-set t]
14680 ["Save" Custom-save t]
14681 ["Reset to Current" Custom-reset-current t]
14682 ["Reset to Saved" Custom-reset-saved t]
14683 ["Reset to Standard Settings" Custom-reset-standard t]))
14684 (message "\"Org\"-menu now contains full customization menu"))
14685 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14687 ;;;; Miscellaneous stuff
14689 ;;; Generally useful functions
14691 (defun org-find-text-property-in-string (prop s)
14692 "Return the first non-nil value of property PROP in string S."
14693 (or (get-text-property 0 prop s)
14694 (get-text-property (or (next-single-property-change 0 prop s) 0)
14695 prop s)))
14697 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14698 "Display the given MESSAGE as a warning."
14699 (if (fboundp 'display-warning)
14700 (display-warning 'org message
14701 (if (featurep 'xemacs)
14702 'warning
14703 :warning))
14704 (let ((buf (get-buffer-create "*Org warnings*")))
14705 (with-current-buffer buf
14706 (goto-char (point-max))
14707 (insert "Warning (Org): " message)
14708 (unless (bolp)
14709 (newline)))
14710 (display-buffer buf)
14711 (sit-for 0))))
14713 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14714 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14715 (if (and marker (marker-buffer marker)
14716 (buffer-live-p (marker-buffer marker)))
14717 (progn
14718 (switch-to-buffer (marker-buffer marker))
14719 (if (or (> marker (point-max)) (< marker (point-min)))
14720 (widen))
14721 (goto-char marker)
14722 (org-show-context 'org-goto))
14723 (if bookmark
14724 (bookmark-jump bookmark)
14725 (error "Cannot find location"))))
14727 (defun org-quote-csv-field (s)
14728 "Quote field for inclusion in CSV material."
14729 (if (string-match "[\",]" s)
14730 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14733 (defun org-plist-delete (plist property)
14734 "Delete PROPERTY from PLIST.
14735 This is in contrast to merely setting it to 0."
14736 (let (p)
14737 (while plist
14738 (if (not (eq property (car plist)))
14739 (setq p (plist-put p (car plist) (nth 1 plist))))
14740 (setq plist (cddr plist)))
14743 (defun org-force-self-insert (N)
14744 "Needed to enforce self-insert under remapping."
14745 (interactive "p")
14746 (self-insert-command N))
14748 (defun org-string-width (s)
14749 "Compute width of string, ignoring invisible characters.
14750 This ignores character with invisibility property `org-link', and also
14751 characters with property `org-cwidth', because these will become invisible
14752 upon the next fontification round."
14753 (let (b l)
14754 (when (or (eq t buffer-invisibility-spec)
14755 (assq 'org-link buffer-invisibility-spec))
14756 (while (setq b (text-property-any 0 (length s)
14757 'invisible 'org-link s))
14758 (setq s (concat (substring s 0 b)
14759 (substring s (or (next-single-property-change
14760 b 'invisible s) (length s)))))))
14761 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14762 (setq s (concat (substring s 0 b)
14763 (substring s (or (next-single-property-change
14764 b 'org-cwidth s) (length s))))))
14765 (setq l (string-width s) b -1)
14766 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14767 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14770 (defun org-get-indentation (&optional line)
14771 "Get the indentation of the current line, interpreting tabs.
14772 When LINE is given, assume it represents a line and compute its indentation."
14773 (if line
14774 (if (string-match "^ *" (org-remove-tabs line))
14775 (match-end 0))
14776 (save-excursion
14777 (beginning-of-line 1)
14778 (skip-chars-forward " \t")
14779 (current-column))))
14781 (defun org-remove-tabs (s &optional width)
14782 "Replace tabulators in S with spaces.
14783 Assumes that s is a single line, starting in column 0."
14784 (setq width (or width tab-width))
14785 (while (string-match "\t" s)
14786 (setq s (replace-match
14787 (make-string
14788 (- (* width (/ (+ (match-beginning 0) width) width))
14789 (match-beginning 0)) ?\ )
14790 t t s)))
14793 (defun org-fix-indentation (line ind)
14794 "Fix indentation in LINE.
14795 IND is a cons cell with target and minimum indentation.
14796 If the current indentation in LINE is smaller than the minimum,
14797 leave it alone. If it is larger than ind, set it to the target."
14798 (let* ((l (org-remove-tabs line))
14799 (i (org-get-indentation l))
14800 (i1 (car ind)) (i2 (cdr ind)))
14801 (if (>= i i2) (setq l (substring line i2)))
14802 (if (> i1 0)
14803 (concat (make-string i1 ?\ ) l)
14804 l)))
14806 (defun org-base-buffer (buffer)
14807 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14808 (if (not buffer)
14809 buffer
14810 (or (buffer-base-buffer buffer)
14811 buffer)))
14813 (defun org-trim (s)
14814 "Remove whitespace at beginning and end of string."
14815 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14816 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14819 (defun org-wrap (string &optional width lines)
14820 "Wrap string to either a number of lines, or a width in characters.
14821 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14822 that costs. If there is a word longer than WIDTH, the text is actually
14823 wrapped to the length of that word.
14824 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14825 many lines, whatever width that takes.
14826 The return value is a list of lines, without newlines at the end."
14827 (let* ((words (org-split-string string "[ \t\n]+"))
14828 (maxword (apply 'max (mapcar 'org-string-width words)))
14829 w ll)
14830 (cond (width
14831 (org-do-wrap words (max maxword width)))
14832 (lines
14833 (setq w maxword)
14834 (setq ll (org-do-wrap words maxword))
14835 (if (<= (length ll) lines)
14837 (setq ll words)
14838 (while (> (length ll) lines)
14839 (setq w (1+ w))
14840 (setq ll (org-do-wrap words w)))
14841 ll))
14842 (t (error "Cannot wrap this")))))
14844 (defun org-do-wrap (words width)
14845 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14846 (let (lines line)
14847 (while words
14848 (setq line (pop words))
14849 (while (and words (< (+ (length line) (length (car words))) width))
14850 (setq line (concat line " " (pop words))))
14851 (setq lines (push line lines)))
14852 (nreverse lines)))
14854 (defun org-split-string (string &optional separators)
14855 "Splits STRING into substrings at SEPARATORS.
14856 No empty strings are returned if there are matches at the beginning
14857 and end of string."
14858 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14859 (start 0)
14860 notfirst
14861 (list nil))
14862 (while (and (string-match rexp string
14863 (if (and notfirst
14864 (= start (match-beginning 0))
14865 (< start (length string)))
14866 (1+ start) start))
14867 (< (match-beginning 0) (length string)))
14868 (setq notfirst t)
14869 (or (eq (match-beginning 0) 0)
14870 (and (eq (match-beginning 0) (match-end 0))
14871 (eq (match-beginning 0) start))
14872 (setq list
14873 (cons (substring string start (match-beginning 0))
14874 list)))
14875 (setq start (match-end 0)))
14876 (or (eq start (length string))
14877 (setq list
14878 (cons (substring string start)
14879 list)))
14880 (nreverse list)))
14882 (defun org-uuidgen-p (s)
14883 "Is S an ID created by UUIDGEN?"
14884 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
14886 (defun org-context ()
14887 "Return a list of contexts of the current cursor position.
14888 If several contexts apply, all are returned.
14889 Each context entry is a list with a symbol naming the context, and
14890 two positions indicating start and end of the context. Possible
14891 contexts are:
14893 :headline anywhere in a headline
14894 :headline-stars on the leading stars in a headline
14895 :todo-keyword on a TODO keyword (including DONE) in a headline
14896 :tags on the TAGS in a headline
14897 :priority on the priority cookie in a headline
14898 :item on the first line of a plain list item
14899 :item-bullet on the bullet/number of a plain list item
14900 :checkbox on the checkbox in a plain list item
14901 :table in an org-mode table
14902 :table-special on a special filed in a table
14903 :table-table in a table.el table
14904 :link on a hyperlink
14905 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14906 :target on a <<target>>
14907 :radio-target on a <<<radio-target>>>
14908 :latex-fragment on a LaTeX fragment
14909 :latex-preview on a LaTeX fragment with overlayed preview image
14911 This function expects the position to be visible because it uses font-lock
14912 faces as a help to recognize the following contexts: :table-special, :link,
14913 and :keyword."
14914 (let* ((f (get-text-property (point) 'face))
14915 (faces (if (listp f) f (list f)))
14916 (p (point)) clist o)
14917 ;; First the large context
14918 (cond
14919 ((org-on-heading-p t)
14920 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14921 (when (progn
14922 (beginning-of-line 1)
14923 (looking-at org-todo-line-tags-regexp))
14924 (push (org-point-in-group p 1 :headline-stars) clist)
14925 (push (org-point-in-group p 2 :todo-keyword) clist)
14926 (push (org-point-in-group p 4 :tags) clist))
14927 (goto-char p)
14928 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14929 (if (looking-at "\\[#[A-Z0-9]\\]")
14930 (push (org-point-in-group p 0 :priority) clist)))
14932 ((org-at-item-p)
14933 (push (org-point-in-group p 2 :item-bullet) clist)
14934 (push (list :item (point-at-bol)
14935 (save-excursion (org-end-of-item) (point)))
14936 clist)
14937 (and (org-at-item-checkbox-p)
14938 (push (org-point-in-group p 0 :checkbox) clist)))
14940 ((org-at-table-p)
14941 (push (list :table (org-table-begin) (org-table-end)) clist)
14942 (if (memq 'org-formula faces)
14943 (push (list :table-special
14944 (previous-single-property-change p 'face)
14945 (next-single-property-change p 'face)) clist)))
14946 ((org-at-table-p 'any)
14947 (push (list :table-table) clist)))
14948 (goto-char p)
14950 ;; Now the small context
14951 (cond
14952 ((org-at-timestamp-p)
14953 (push (org-point-in-group p 0 :timestamp) clist))
14954 ((memq 'org-link faces)
14955 (push (list :link
14956 (previous-single-property-change p 'face)
14957 (next-single-property-change p 'face)) clist))
14958 ((memq 'org-special-keyword faces)
14959 (push (list :keyword
14960 (previous-single-property-change p 'face)
14961 (next-single-property-change p 'face)) clist))
14962 ((org-on-target-p)
14963 (push (org-point-in-group p 0 :target) clist)
14964 (goto-char (1- (match-beginning 0)))
14965 (if (looking-at org-radio-target-regexp)
14966 (push (org-point-in-group p 0 :radio-target) clist))
14967 (goto-char p))
14968 ((setq o (car (delq nil
14969 (mapcar
14970 (lambda (x)
14971 (if (memq x org-latex-fragment-image-overlays) x))
14972 (org-overlays-at (point))))))
14973 (push (list :latex-fragment
14974 (org-overlay-start o) (org-overlay-end o)) clist)
14975 (push (list :latex-preview
14976 (org-overlay-start o) (org-overlay-end o)) clist))
14977 ((org-inside-LaTeX-fragment-p)
14978 ;; FIXME: positions wrong.
14979 (push (list :latex-fragment (point) (point)) clist)))
14981 (setq clist (nreverse (delq nil clist)))
14982 clist))
14984 ;; FIXME: Compare with at-regexp-p Do we need both?
14985 (defun org-in-regexp (re &optional nlines visually)
14986 "Check if point is inside a match of regexp.
14987 Normally only the current line is checked, but you can include NLINES extra
14988 lines both before and after point into the search.
14989 If VISUALLY is set, require that the cursor is not after the match but
14990 really on, so that the block visually is on the match."
14991 (catch 'exit
14992 (let ((pos (point))
14993 (eol (point-at-eol (+ 1 (or nlines 0))))
14994 (inc (if visually 1 0)))
14995 (save-excursion
14996 (beginning-of-line (- 1 (or nlines 0)))
14997 (while (re-search-forward re eol t)
14998 (if (and (<= (match-beginning 0) pos)
14999 (>= (+ inc (match-end 0)) pos))
15000 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15002 (defun org-at-regexp-p (regexp)
15003 "Is point inside a match of REGEXP in the current line?"
15004 (catch 'exit
15005 (save-excursion
15006 (let ((pos (point)) (end (point-at-eol)))
15007 (beginning-of-line 1)
15008 (while (re-search-forward regexp end t)
15009 (if (and (<= (match-beginning 0) pos)
15010 (>= (match-end 0) pos))
15011 (throw 'exit t)))
15012 nil))))
15014 (defun org-occur-in-agenda-files (regexp &optional nlines)
15015 "Call `multi-occur' with buffers for all agenda files."
15016 (interactive "sOrg-files matching: \np")
15017 (let* ((files (org-agenda-files))
15018 (tnames (mapcar 'file-truename files))
15019 (extra org-agenda-text-search-extra-files)
15021 (when (eq (car extra) 'agenda-archives)
15022 (setq extra (cdr extra))
15023 (setq files (org-add-archive-files files)))
15024 (while (setq f (pop extra))
15025 (unless (member (file-truename f) tnames)
15026 (add-to-list 'files f 'append)
15027 (add-to-list 'tnames (file-truename f) 'append)))
15028 (multi-occur
15029 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15030 regexp)))
15032 (if (boundp 'occur-mode-find-occurrence-hook)
15033 ;; Emacs 23
15034 (add-hook 'occur-mode-find-occurrence-hook
15035 (lambda ()
15036 (when (org-mode-p)
15037 (org-reveal))))
15038 ;; Emacs 22
15039 (defadvice occur-mode-goto-occurrence
15040 (after org-occur-reveal activate)
15041 (and (org-mode-p) (org-reveal)))
15042 (defadvice occur-mode-goto-occurrence-other-window
15043 (after org-occur-reveal activate)
15044 (and (org-mode-p) (org-reveal)))
15045 (defadvice occur-mode-display-occurrence
15046 (after org-occur-reveal activate)
15047 (when (org-mode-p)
15048 (let ((pos (occur-mode-find-occurrence)))
15049 (with-current-buffer (marker-buffer pos)
15050 (save-excursion
15051 (goto-char pos)
15052 (org-reveal)))))))
15054 (defun org-uniquify (list)
15055 "Remove duplicate elements from LIST."
15056 (let (res)
15057 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15058 res))
15060 (defun org-delete-all (elts list)
15061 "Remove all elements in ELTS from LIST."
15062 (while elts
15063 (setq list (delete (pop elts) list)))
15064 list)
15066 (defun org-back-over-empty-lines ()
15067 "Move backwards over whitespace, to the beginning of the first empty line.
15068 Returns the number of empty lines passed."
15069 (let ((pos (point)))
15070 (skip-chars-backward " \t\n\r")
15071 (beginning-of-line 2)
15072 (goto-char (min (point) pos))
15073 (count-lines (point) pos)))
15075 (defun org-skip-whitespace ()
15076 (skip-chars-forward " \t\n\r"))
15078 (defun org-point-in-group (point group &optional context)
15079 "Check if POINT is in match-group GROUP.
15080 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15081 match. If the match group does ot exist or point is not inside it,
15082 return nil."
15083 (and (match-beginning group)
15084 (>= point (match-beginning group))
15085 (<= point (match-end group))
15086 (if context
15087 (list context (match-beginning group) (match-end group))
15088 t)))
15090 (defun org-switch-to-buffer-other-window (&rest args)
15091 "Switch to buffer in a second window on the current frame.
15092 In particular, do not allow pop-up frames."
15093 (let (pop-up-frames special-display-buffer-names special-display-regexps
15094 special-display-function)
15095 (apply 'switch-to-buffer-other-window args)))
15097 (defun org-combine-plists (&rest plists)
15098 "Create a single property list from all plists in PLISTS.
15099 The process starts by copying the first list, and then setting properties
15100 from the other lists. Settings in the last list are the most significant
15101 ones and overrule settings in the other lists."
15102 (let ((rtn (copy-sequence (pop plists)))
15103 p v ls)
15104 (while plists
15105 (setq ls (pop plists))
15106 (while ls
15107 (setq p (pop ls) v (pop ls))
15108 (setq rtn (plist-put rtn p v))))
15109 rtn))
15111 (defun org-move-line-down (arg)
15112 "Move the current line down. With prefix argument, move it past ARG lines."
15113 (interactive "p")
15114 (let ((col (current-column))
15115 beg end pos)
15116 (beginning-of-line 1) (setq beg (point))
15117 (beginning-of-line 2) (setq end (point))
15118 (beginning-of-line (+ 1 arg))
15119 (setq pos (move-marker (make-marker) (point)))
15120 (insert (delete-and-extract-region beg end))
15121 (goto-char pos)
15122 (org-move-to-column col)))
15124 (defun org-move-line-up (arg)
15125 "Move the current line up. With prefix argument, move it past ARG lines."
15126 (interactive "p")
15127 (let ((col (current-column))
15128 beg end pos)
15129 (beginning-of-line 1) (setq beg (point))
15130 (beginning-of-line 2) (setq end (point))
15131 (beginning-of-line (- arg))
15132 (setq pos (move-marker (make-marker) (point)))
15133 (insert (delete-and-extract-region beg end))
15134 (goto-char pos)
15135 (org-move-to-column col)))
15137 (defun org-replace-escapes (string table)
15138 "Replace %-escapes in STRING with values in TABLE.
15139 TABLE is an association list with keys like \"%a\" and string values.
15140 The sequences in STRING may contain normal field width and padding information,
15141 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15142 so values can contain further %-escapes if they are define later in TABLE."
15143 (let ((case-fold-search nil)
15144 e re rpl)
15145 (while (setq e (pop table))
15146 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15147 (while (string-match re string)
15148 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15149 (cdr e)))
15150 (setq string (replace-match rpl t t string))))
15151 string))
15154 (defun org-sublist (list start end)
15155 "Return a section of LIST, from START to END.
15156 Counting starts at 1."
15157 (let (rtn (c start))
15158 (setq list (nthcdr (1- start) list))
15159 (while (and list (<= c end))
15160 (push (pop list) rtn)
15161 (setq c (1+ c)))
15162 (nreverse rtn)))
15164 (defun org-find-base-buffer-visiting (file)
15165 "Like `find-buffer-visiting' but alway return the base buffer and
15166 not an indirect buffer."
15167 (let ((buf (find-buffer-visiting file)))
15168 (if buf
15169 (or (buffer-base-buffer buf) buf)
15170 nil)))
15172 (defun org-image-file-name-regexp (&optional extensions)
15173 "Return regexp matching the file names of images.
15174 If EXTENSIONS is given, only match these."
15175 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15176 (image-file-name-regexp)
15177 (let ((image-file-name-extensions
15178 (or extensions
15179 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15180 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15181 (concat "\\."
15182 (regexp-opt (nconc (mapcar 'upcase
15183 image-file-name-extensions)
15184 image-file-name-extensions)
15186 "\\'"))))
15188 (defun org-file-image-p (file &optional extensions)
15189 "Return non-nil if FILE is an image."
15190 (save-match-data
15191 (string-match (org-image-file-name-regexp extensions) file)))
15193 (defun org-get-cursor-date ()
15194 "Return the date at cursor in as a time.
15195 This works in the calendar and in the agenda, anywhere else it just
15196 returns the current time."
15197 (let (date day defd)
15198 (cond
15199 ((eq major-mode 'calendar-mode)
15200 (setq date (calendar-cursor-to-date)
15201 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15202 ((eq major-mode 'org-agenda-mode)
15203 (setq day (get-text-property (point) 'day))
15204 (if day
15205 (setq date (calendar-gregorian-from-absolute day)
15206 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15207 (nth 2 date))))))
15208 (or defd (current-time))))
15210 (defvar org-agenda-action-marker (make-marker)
15211 "Marker pointing to the entry for the next agenda action.")
15213 (defun org-mark-entry-for-agenda-action ()
15214 "Mark the current entry as target of an agenda action.
15215 Agenda actions are actions executed from the agenda with the key `k',
15216 which make use of the date at the cursor."
15217 (interactive)
15218 (move-marker org-agenda-action-marker
15219 (save-excursion (org-back-to-heading t) (point))
15220 (current-buffer))
15221 (message
15222 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15224 ;;; Paragraph filling stuff.
15225 ;; We want this to be just right, so use the full arsenal.
15227 (defun org-indent-line-function ()
15228 "Indent line like previous, but further if previous was headline or item."
15229 (interactive)
15230 (let* ((pos (point))
15231 (itemp (org-at-item-p))
15232 (org-drawer-regexp (or org-drawer-regexp "\000"))
15233 column bpos bcol tpos tcol bullet btype bullet-type)
15234 ;; Find the previous relevant line
15235 (beginning-of-line 1)
15236 (cond
15237 ((looking-at "#") (setq column 0))
15238 ((looking-at "\\*+ ") (setq column 0))
15239 ((and (looking-at "[ \t]*:END:")
15240 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15241 (save-excursion
15242 (goto-char (1- (match-beginning 1)))
15243 (setq column (current-column))))
15245 (beginning-of-line 0)
15246 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15247 (not (looking-at "[ \t]*:END:"))
15248 (not (looking-at org-drawer-regexp)))
15249 (beginning-of-line 0))
15250 (cond
15251 ((looking-at "\\*+[ \t]+")
15252 (if (not org-adapt-indentation)
15253 (setq column 0)
15254 (goto-char (match-end 0))
15255 (setq column (current-column))))
15256 ((looking-at org-drawer-regexp)
15257 (goto-char (1- (match-beginning 1)))
15258 (setq column (current-column)))
15259 ((looking-at "\\([ \t]*\\):END:")
15260 (goto-char (match-end 1))
15261 (setq column (current-column)))
15262 ((org-in-item-p)
15263 (org-beginning-of-item)
15264 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15265 (setq bpos (match-beginning 1) tpos (match-end 0)
15266 bcol (progn (goto-char bpos) (current-column))
15267 tcol (progn (goto-char tpos) (current-column))
15268 bullet (match-string 1)
15269 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15270 (if (> tcol (+ bcol org-description-max-indent))
15271 (setq tcol (+ bcol 5)))
15272 (if (not itemp)
15273 (setq column tcol)
15274 (goto-char pos)
15275 (beginning-of-line 1)
15276 (if (looking-at "\\S-")
15277 (progn
15278 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15279 (setq bullet (match-string 1)
15280 btype (if (string-match "[0-9]" bullet) "n" bullet))
15281 (setq column (if (equal btype bullet-type) bcol tcol)))
15282 (setq column (org-get-indentation)))))
15283 (t (setq column (org-get-indentation))))))
15284 (goto-char pos)
15285 (if (<= (current-column) (current-indentation))
15286 (org-indent-line-to column)
15287 (save-excursion (org-indent-line-to column)))
15288 (setq column (current-column))
15289 (beginning-of-line 1)
15290 (if (looking-at
15291 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15292 (replace-match (concat "\\1" (format org-property-format
15293 (match-string 2) (match-string 3)))
15294 t nil))
15295 (org-move-to-column column)))
15297 (defun org-set-autofill-regexps ()
15298 (interactive)
15299 ;; In the paragraph separator we include headlines, because filling
15300 ;; text in a line directly attached to a headline would otherwise
15301 ;; fill the headline as well.
15302 (org-set-local 'comment-start-skip "^#+[ \t]*")
15303 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15304 ;; The paragraph starter includes hand-formatted lists.
15305 (org-set-local 'paragraph-start
15306 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15307 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15308 ;; But only if the user has not turned off tables or fixed-width regions
15309 (org-set-local
15310 'auto-fill-inhibit-regexp
15311 (concat "\\*+ \\|#\\+"
15312 "\\|[ \t]*" org-keyword-time-regexp
15313 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15314 (concat
15315 "\\|[ \t]*["
15316 (if org-enable-table-editor "|" "")
15317 (if org-enable-fixed-width-editor ":" "")
15318 "]"))))
15319 ;; We use our own fill-paragraph function, to make sure that tables
15320 ;; and fixed-width regions are not wrapped. That function will pass
15321 ;; through to `fill-paragraph' when appropriate.
15322 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15323 ; Adaptive filling: To get full control, first make sure that
15324 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15325 (org-set-local 'adaptive-fill-regexp "\000")
15326 (org-set-local 'adaptive-fill-function
15327 'org-adaptive-fill-function)
15328 (org-set-local
15329 'align-mode-rules-list
15330 '((org-in-buffer-settings
15331 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15332 (modes . '(org-mode))))))
15334 (defun org-fill-paragraph (&optional justify)
15335 "Re-align a table, pass through to fill-paragraph if no table."
15336 (let ((table-p (org-at-table-p))
15337 (table.el-p (org-at-table.el-p)))
15338 (cond ((and (equal (char-after (point-at-bol)) ?*)
15339 (save-excursion (goto-char (point-at-bol))
15340 (looking-at outline-regexp)))
15341 t) ; skip headlines
15342 (table.el-p t) ; skip table.el tables
15343 (table-p (org-table-align) t) ; align org-mode tables
15344 (t nil)))) ; call paragraph-fill
15346 ;; For reference, this is the default value of adaptive-fill-regexp
15347 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15349 (defun org-adaptive-fill-function ()
15350 "Return a fill prefix for org-mode files.
15351 In particular, this makes sure hanging paragraphs for hand-formatted lists
15352 work correctly."
15353 (cond ((looking-at "#[ \t]+")
15354 (match-string 0))
15355 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15356 (save-excursion
15357 (if (> (match-end 1) (+ (match-beginning 1)
15358 org-description-max-indent))
15359 (goto-char (+ (match-beginning 1) 5))
15360 (goto-char (match-end 0)))
15361 (make-string (current-column) ?\ )))
15362 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15363 (save-excursion
15364 (goto-char (match-end 0))
15365 (make-string (current-column) ?\ )))
15366 (t nil)))
15368 ;;; Other stuff.
15370 (defun org-toggle-fixed-width-section (arg)
15371 "Toggle the fixed-width export.
15372 If there is no active region, the QUOTE keyword at the current headline is
15373 inserted or removed. When present, it causes the text between this headline
15374 and the next to be exported as fixed-width text, and unmodified.
15375 If there is an active region, this command adds or removes a colon as the
15376 first character of this line. If the first character of a line is a colon,
15377 this line is also exported in fixed-width font."
15378 (interactive "P")
15379 (let* ((cc 0)
15380 (regionp (org-region-active-p))
15381 (beg (if regionp (region-beginning) (point)))
15382 (end (if regionp (region-end)))
15383 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15384 (case-fold-search nil)
15385 (re "[ \t]*\\(: \\)")
15386 off)
15387 (if regionp
15388 (save-excursion
15389 (goto-char beg)
15390 (setq cc (current-column))
15391 (beginning-of-line 1)
15392 (setq off (looking-at re))
15393 (while (> nlines 0)
15394 (setq nlines (1- nlines))
15395 (beginning-of-line 1)
15396 (cond
15397 (arg
15398 (org-move-to-column cc t)
15399 (insert ": \n")
15400 (forward-line -1))
15401 ((and off (looking-at re))
15402 (replace-match "" t t nil 1))
15403 ((not off) (org-move-to-column cc t) (insert ": ")))
15404 (forward-line 1)))
15405 (save-excursion
15406 (org-back-to-heading)
15407 (if (looking-at (concat outline-regexp
15408 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15409 (replace-match "" t t nil 1)
15410 (if (looking-at outline-regexp)
15411 (progn
15412 (goto-char (match-end 0))
15413 (insert org-quote-string " "))))))))
15415 (defun org-reftex-citation ()
15416 "Use reftex-citation to insert a citation into the buffer.
15417 This looks for a line like
15419 #+BIBLIOGRAPHY: foo plain option:-d
15421 and derives from it that foo.bib is the bbliography file relevant
15422 for this document. It then installs the necessary environment for RefTeX
15423 to work in this buffer and calls `reftex-citation' to insert a citation
15424 into the buffer.
15426 Export of such citations to both LaTeX and HTML is handled by the contributed
15427 package org-exp-bibtex by Taru Karttunen."
15428 (interactive)
15429 (let ((reftex-docstruct-symbol 'rds)
15430 (reftex-cite-format "\\cite{%l}")
15431 rds bib)
15432 (save-excursion
15433 (save-restriction
15434 (widen)
15435 (let ((case-fold-search t)
15436 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15437 (if (not (save-excursion
15438 (or (re-search-forward re nil t)
15439 (re-search-backward re nil t))))
15440 (error "No bibliography defined in file")
15441 (setq bib (concat (match-string 1) ".bib")
15442 rds (list (list 'bib bib)))))))
15443 (call-interactively 'reftex-citation)))
15445 ;;;; Functions extending outline functionality
15447 (defun org-beginning-of-line (&optional arg)
15448 "Go to the beginning of the current line. If that is invisible, continue
15449 to a visible line beginning. This makes the function of C-a more intuitive.
15450 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15451 first attempt, and only move to after the tags when the cursor is already
15452 beyond the end of the headline."
15453 (interactive "P")
15454 (let ((pos (point))
15455 (special (if (consp org-special-ctrl-a/e)
15456 (car org-special-ctrl-a/e)
15457 org-special-ctrl-a/e))
15458 refpos)
15459 (beginning-of-line 1)
15460 (if (and arg (fboundp 'move-beginning-of-line))
15461 (call-interactively 'move-beginning-of-line)
15462 (if (bobp)
15464 (backward-char 1)
15465 (if (org-invisible-p)
15466 (while (and (not (bobp)) (org-invisible-p))
15467 (backward-char 1)
15468 (beginning-of-line 1))
15469 (forward-char 1))))
15470 (when special
15471 (cond
15472 ((and (looking-at org-complex-heading-regexp)
15473 (= (char-after (match-end 1)) ?\ ))
15474 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15475 (point-at-eol)))
15476 (goto-char
15477 (if (eq special t)
15478 (cond ((> pos refpos) refpos)
15479 ((= pos (point)) refpos)
15480 (t (point)))
15481 (cond ((> pos (point)) (point))
15482 ((not (eq last-command this-command)) (point))
15483 (t refpos)))))
15484 ((org-at-item-p)
15485 (goto-char
15486 (if (eq special t)
15487 (cond ((> pos (match-end 4)) (match-end 4))
15488 ((= pos (point)) (match-end 4))
15489 (t (point)))
15490 (cond ((> pos (point)) (point))
15491 ((not (eq last-command this-command)) (point))
15492 (t (match-end 4))))))))
15493 (org-no-warnings
15494 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15496 (defun org-end-of-line (&optional arg)
15497 "Go to the end of the line.
15498 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15499 first attempt, and only move to after the tags when the cursor is already
15500 beyond the end of the headline."
15501 (interactive "P")
15502 (let ((special (if (consp org-special-ctrl-a/e)
15503 (cdr org-special-ctrl-a/e)
15504 org-special-ctrl-a/e)))
15505 (if (or (not special)
15506 (not (org-on-heading-p))
15507 arg)
15508 (call-interactively (if (fboundp 'move-end-of-line)
15509 'move-end-of-line
15510 'end-of-line))
15511 (let ((pos (point)))
15512 (beginning-of-line 1)
15513 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15514 (if (eq special t)
15515 (if (or (< pos (match-beginning 1))
15516 (= pos (match-end 0)))
15517 (goto-char (match-beginning 1))
15518 (goto-char (match-end 0)))
15519 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15520 (goto-char (match-end 0))
15521 (goto-char (match-beginning 1))))
15522 (call-interactively (if (fboundp 'move-end-of-line)
15523 'move-end-of-line
15524 'end-of-line)))))
15525 (org-no-warnings
15526 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15528 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15529 (define-key org-mode-map "\C-e" 'org-end-of-line)
15531 (defun org-backward-sentence (&optional arg)
15532 "Go to beginning of sentence, or beginning of table field.
15533 This will call `backward-sentence' or `org-table-beginning-of-field',
15534 depending on context."
15535 (interactive "P")
15536 (cond
15537 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
15538 (t (call-interactively 'backward-sentence))))
15540 (defun org-forward-sentence (&optional arg)
15541 "Go to end of sentence, or end of table field.
15542 This will call `forward-sentence' or `org-table-end-of-field',
15543 depending on context."
15544 (interactive "P")
15545 (cond
15546 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
15547 (t (call-interactively 'forward-sentence))))
15549 (define-key org-mode-map "\M-a" 'org-backward-sentence)
15550 (define-key org-mode-map "\M-e" 'org-forward-sentence)
15552 (defun org-kill-line (&optional arg)
15553 "Kill line, to tags or end of line."
15554 (interactive "P")
15555 (cond
15556 ((or (not org-special-ctrl-k)
15557 (bolp)
15558 (not (org-on-heading-p)))
15559 (call-interactively 'kill-line))
15560 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15561 (kill-region (point) (match-beginning 1))
15562 (org-set-tags nil t))
15563 (t (kill-region (point) (point-at-eol)))))
15565 (define-key org-mode-map "\C-k" 'org-kill-line)
15567 (defun org-yank (&optional arg)
15568 "Yank. If the kill is a subtree, treat it specially.
15569 This command will look at the current kill and check if is a single
15570 subtree, or a series of subtrees[1]. If it passes the test, and if the
15571 cursor is at the beginning of a line or after the stars of a currently
15572 empty headline, then the yank is handled specially. How exactly depends
15573 on the value of the following variables, both set by default.
15575 org-yank-folded-subtrees
15576 When set, the subtree(s) will be folded after insertion, but only
15577 if doing so would now swallow text after the yanked text.
15579 org-yank-adjusted-subtrees
15580 When set, the subtree will be promoted or demoted in order to
15581 fit into the local outline tree structure, which means that the level
15582 will be adjusted so that it becomes the smaller one of the two
15583 *visible* surrounding headings.
15585 Any prefix to this command will cause `yank' to be called directly with
15586 no special treatment. In particular, a simple `C-u' prefix will just
15587 plainly yank the text as it is.
15589 \[1] Basically, the test checks if the first non-white line is a heading
15590 and if there are no other headings with fewer stars."
15591 (interactive "P")
15592 (setq this-command 'yank)
15593 (if arg
15594 (call-interactively 'yank)
15595 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15596 (and (org-kill-is-subtree-p)
15597 (or (bolp)
15598 (and (looking-at "[ \t]*$")
15599 (string-match
15600 "\\`\\*+\\'"
15601 (buffer-substring (point-at-bol) (point)))))))
15602 swallowp)
15603 (cond
15604 ((and subtreep org-yank-folded-subtrees)
15605 (let ((beg (point))
15606 end)
15607 (if (and subtreep org-yank-adjusted-subtrees)
15608 (org-paste-subtree nil nil 'for-yank)
15609 (call-interactively 'yank))
15610 (setq end (point))
15611 (goto-char beg)
15612 (when (and (bolp) subtreep
15613 (not (setq swallowp
15614 (org-yank-folding-would-swallow-text beg end))))
15615 (or (looking-at outline-regexp)
15616 (re-search-forward (concat "^" outline-regexp) end t))
15617 (while (and (< (point) end) (looking-at outline-regexp))
15618 (hide-subtree)
15619 (org-cycle-show-empty-lines 'folded)
15620 (condition-case nil
15621 (outline-forward-same-level 1)
15622 (error (goto-char end)))))
15623 (when swallowp
15624 (message
15625 "Yanked text not folded because that would swallow text"))
15626 (goto-char end)
15627 (skip-chars-forward " \t\n\r")
15628 (beginning-of-line 1)
15629 (push-mark beg 'nomsg)))
15630 ((and subtreep org-yank-adjusted-subtrees)
15631 (let ((beg (point-at-bol)))
15632 (org-paste-subtree nil nil 'for-yank)
15633 (push-mark beg 'nomsg)))
15635 (call-interactively 'yank))))))
15637 (defun org-yank-folding-would-swallow-text (beg end)
15638 "Would hide-subtree at BEG swallow any text after END?"
15639 (let (level)
15640 (save-excursion
15641 (goto-char beg)
15642 (when (or (looking-at outline-regexp)
15643 (re-search-forward (concat "^" outline-regexp) end t))
15644 (setq level (org-outline-level)))
15645 (goto-char end)
15646 (skip-chars-forward " \t\r\n\v\f")
15647 (if (or (eobp)
15648 (and (bolp) (looking-at org-outline-regexp)
15649 (<= (org-outline-level) level)))
15650 nil ; Nothing would be swallowed
15651 t)))) ; something would swallow
15653 (define-key org-mode-map "\C-y" 'org-yank)
15655 (defun org-invisible-p ()
15656 "Check if point is at a character currently not visible."
15657 ;; Early versions of noutline don't have `outline-invisible-p'.
15658 (if (fboundp 'outline-invisible-p)
15659 (outline-invisible-p)
15660 (get-char-property (point) 'invisible)))
15662 (defun org-invisible-p2 ()
15663 "Check if point is at a character currently not visible."
15664 (save-excursion
15665 (if (and (eolp) (not (bobp))) (backward-char 1))
15666 ;; Early versions of noutline don't have `outline-invisible-p'.
15667 (if (fboundp 'outline-invisible-p)
15668 (outline-invisible-p)
15669 (get-char-property (point) 'invisible))))
15671 (defun org-back-to-heading (&optional invisible-ok)
15672 "Call `outline-back-to-heading', but provide a better error message."
15673 (condition-case nil
15674 (outline-back-to-heading invisible-ok)
15675 (error (error "Before first headline at position %d in buffer %s"
15676 (point) (current-buffer)))))
15678 (defun org-before-first-heading-p ()
15679 "Before first heading?"
15680 (save-excursion
15681 (null (re-search-backward "^\\*+ " nil t))))
15683 (defalias 'org-on-heading-p 'outline-on-heading-p)
15684 (defalias 'org-at-heading-p 'outline-on-heading-p)
15685 (defun org-at-heading-or-item-p ()
15686 (or (org-on-heading-p) (org-at-item-p)))
15688 (defun org-on-target-p ()
15689 (or (org-in-regexp org-radio-target-regexp)
15690 (org-in-regexp org-target-regexp)))
15692 (defun org-up-heading-all (arg)
15693 "Move to the heading line of which the present line is a subheading.
15694 This function considers both visible and invisible heading lines.
15695 With argument, move up ARG levels."
15696 (if (fboundp 'outline-up-heading-all)
15697 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15698 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15700 (defun org-up-heading-safe ()
15701 "Move to the heading line of which the present line is a subheading.
15702 This version will not throw an error. It will return the level of the
15703 headline found, or nil if no higher level is found."
15704 (let (start-level re)
15705 (org-back-to-heading t)
15706 (setq start-level (funcall outline-level))
15707 (if (equal start-level 1)
15709 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15710 (if (re-search-backward re nil t)
15711 (funcall outline-level)))))
15713 (defun org-first-sibling-p ()
15714 "Is this heading the first child of its parents?"
15715 (interactive)
15716 (let ((re (concat "^" outline-regexp))
15717 level l)
15718 (unless (org-at-heading-p t)
15719 (error "Not at a heading"))
15720 (setq level (funcall outline-level))
15721 (save-excursion
15722 (if (not (re-search-backward re nil t))
15724 (setq l (funcall outline-level))
15725 (< l level)))))
15727 (defun org-goto-sibling (&optional previous)
15728 "Goto the next sibling, even if it is invisible.
15729 When PREVIOUS is set, go to the previous sibling instead. Returns t
15730 when a sibling was found. When none is found, return nil and don't
15731 move point."
15732 (let ((fun (if previous 're-search-backward 're-search-forward))
15733 (pos (point))
15734 (re (concat "^" outline-regexp))
15735 level l)
15736 (when (condition-case nil (org-back-to-heading t) (error nil))
15737 (setq level (funcall outline-level))
15738 (catch 'exit
15739 (or previous (forward-char 1))
15740 (while (funcall fun re nil t)
15741 (setq l (funcall outline-level))
15742 (when (< l level) (goto-char pos) (throw 'exit nil))
15743 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15744 (goto-char pos)
15745 nil))))
15747 (defun org-show-siblings ()
15748 "Show all siblings of the current headline."
15749 (save-excursion
15750 (while (org-goto-sibling) (org-flag-heading nil)))
15751 (save-excursion
15752 (while (org-goto-sibling 'previous)
15753 (org-flag-heading nil))))
15755 (defun org-show-hidden-entry ()
15756 "Show an entry where even the heading is hidden."
15757 (save-excursion
15758 (org-show-entry)))
15760 (defun org-flag-heading (flag &optional entry)
15761 "Flag the current heading. FLAG non-nil means make invisible.
15762 When ENTRY is non-nil, show the entire entry."
15763 (save-excursion
15764 (org-back-to-heading t)
15765 ;; Check if we should show the entire entry
15766 (if entry
15767 (progn
15768 (org-show-entry)
15769 (save-excursion
15770 (and (outline-next-heading)
15771 (org-flag-heading nil))))
15772 (outline-flag-region (max (point-min) (1- (point)))
15773 (save-excursion (outline-end-of-heading) (point))
15774 flag))))
15776 (defun org-forward-same-level (arg)
15777 "Move forward to the ARG'th subheading at same level as this one.
15778 Stop at the first and last subheadings of a superior heading.
15779 This is like outline-forward-same-level, but invisible headings are ok."
15780 (interactive "p")
15781 (org-back-to-heading t)
15782 (while (> arg 0)
15783 (let ((point-to-move-to (save-excursion
15784 (org-get-next-sibling))))
15785 (if point-to-move-to
15786 (progn
15787 (goto-char point-to-move-to)
15788 (setq arg (1- arg)))
15789 (progn
15790 (setq arg 0)
15791 (error "No following same-level heading"))))))
15793 (defun org-get-next-sibling ()
15794 "Move to next heading of the same level, and return point.
15795 If there is no such heading, return nil.
15796 This is like outline-next-sibling, but invisible headings are ok."
15797 (let ((level (funcall outline-level)))
15798 (outline-next-heading)
15799 (while (and (not (eobp)) (> (funcall outline-level) level))
15800 (outline-next-heading))
15801 (if (or (eobp) (< (funcall outline-level) level))
15803 (point))))
15805 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15806 ;; This is an exact copy of the original function, but it uses
15807 ;; `org-back-to-heading', to make it work also in invisible
15808 ;; trees. And is uses an invisible-OK argument.
15809 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15810 (org-back-to-heading invisible-OK)
15811 (let ((first t)
15812 (level (funcall outline-level)))
15813 (while (and (not (eobp))
15814 (or first (> (funcall outline-level) level)))
15815 (setq first nil)
15816 (outline-next-heading))
15817 (unless to-heading
15818 (if (memq (preceding-char) '(?\n ?\^M))
15819 (progn
15820 ;; Go to end of line before heading
15821 (forward-char -1)
15822 (if (memq (preceding-char) '(?\n ?\^M))
15823 ;; leave blank line before heading
15824 (forward-char -1))))))
15825 (point))
15827 (defun org-show-subtree ()
15828 "Show everything after this heading at deeper levels."
15829 (outline-flag-region
15830 (point)
15831 (save-excursion
15832 (outline-end-of-subtree) (outline-next-heading) (point))
15833 nil))
15835 (defun org-show-entry ()
15836 "Show the body directly following this heading.
15837 Show the heading too, if it is currently invisible."
15838 (interactive)
15839 (save-excursion
15840 (condition-case nil
15841 (progn
15842 (org-back-to-heading t)
15843 (outline-flag-region
15844 (max (point-min) (1- (point)))
15845 (save-excursion
15846 (if (re-search-forward
15847 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15848 (match-beginning 1)
15849 (point-max)))
15850 nil))
15851 (error nil))))
15853 (defun org-make-options-regexp (kwds &optional extra)
15854 "Make a regular expression for keyword lines."
15855 (concat
15857 "#?[ \t]*\\+\\("
15858 (mapconcat 'regexp-quote kwds "\\|")
15859 (if extra (concat "\\|" extra))
15860 "\\):[ \t]*"
15861 "\\(.+\\)"))
15863 ;; Make isearch reveal the necessary context
15864 (defun org-isearch-end ()
15865 "Reveal context after isearch exits."
15866 (when isearch-success ; only if search was successful
15867 (if (featurep 'xemacs)
15868 ;; Under XEmacs, the hook is run in the correct place,
15869 ;; we directly show the context.
15870 (org-show-context 'isearch)
15871 ;; In Emacs the hook runs *before* restoring the overlays.
15872 ;; So we have to use a one-time post-command-hook to do this.
15873 ;; (Emacs 22 has a special variable, see function `org-mode')
15874 (unless (and (boundp 'isearch-mode-end-hook-quit)
15875 isearch-mode-end-hook-quit)
15876 ;; Only when the isearch was not quitted.
15877 (org-add-hook 'post-command-hook 'org-isearch-post-command
15878 'append 'local)))))
15880 (defun org-isearch-post-command ()
15881 "Remove self from hook, and show context."
15882 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15883 (org-show-context 'isearch))
15886 ;;;; Integration with and fixes for other packages
15888 ;;; Imenu support
15890 (defvar org-imenu-markers nil
15891 "All markers currently used by Imenu.")
15892 (make-variable-buffer-local 'org-imenu-markers)
15894 (defun org-imenu-new-marker (&optional pos)
15895 "Return a new marker for use by Imenu, and remember the marker."
15896 (let ((m (make-marker)))
15897 (move-marker m (or pos (point)))
15898 (push m org-imenu-markers)
15901 (defun org-imenu-get-tree ()
15902 "Produce the index for Imenu."
15903 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15904 (setq org-imenu-markers nil)
15905 (let* ((n org-imenu-depth)
15906 (re (concat "^" outline-regexp))
15907 (subs (make-vector (1+ n) nil))
15908 (last-level 0)
15909 m level head)
15910 (save-excursion
15911 (save-restriction
15912 (widen)
15913 (goto-char (point-max))
15914 (while (re-search-backward re nil t)
15915 (setq level (org-reduced-level (funcall outline-level)))
15916 (when (<= level n)
15917 (looking-at org-complex-heading-regexp)
15918 (setq head (org-link-display-format
15919 (org-match-string-no-properties 4))
15920 m (org-imenu-new-marker))
15921 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15922 (if (>= level last-level)
15923 (push (cons head m) (aref subs level))
15924 (push (cons head (aref subs (1+ level))) (aref subs level))
15925 (loop for i from (1+ level) to n do (aset subs i nil)))
15926 (setq last-level level)))))
15927 (aref subs 1)))
15929 (eval-after-load "imenu"
15930 '(progn
15931 (add-hook 'imenu-after-jump-hook
15932 (lambda ()
15933 (if (eq major-mode 'org-mode)
15934 (org-show-context 'org-goto))))))
15936 (defun org-link-display-format (link)
15937 "Replace a link with either the description, or the link target
15938 if no description is present"
15939 (save-match-data
15940 (if (string-match org-bracket-link-analytic-regexp link)
15941 (replace-match (or (match-string 5 link)
15942 (concat (match-string 1 link)
15943 (match-string 3 link)))
15944 nil nil link)
15945 link)))
15947 ;; Speedbar support
15949 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15950 "Overlay marking the agenda restriction line in speedbar.")
15951 (org-overlay-put org-speedbar-restriction-lock-overlay
15952 'face 'org-agenda-restriction-lock)
15953 (org-overlay-put org-speedbar-restriction-lock-overlay
15954 'help-echo "Agendas are currently limited to this item.")
15955 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15957 (defun org-speedbar-set-agenda-restriction ()
15958 "Restrict future agenda commands to the location at point in speedbar.
15959 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15960 (interactive)
15961 (require 'org-agenda)
15962 (let (p m tp np dir txt)
15963 (cond
15964 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15965 'org-imenu t))
15966 (setq m (get-text-property p 'org-imenu-marker))
15967 (save-excursion
15968 (save-restriction
15969 (set-buffer (marker-buffer m))
15970 (goto-char m)
15971 (org-agenda-set-restriction-lock 'subtree))))
15972 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15973 'speedbar-function 'speedbar-find-file))
15974 (setq tp (previous-single-property-change
15975 (1+ p) 'speedbar-function)
15976 np (next-single-property-change
15977 tp 'speedbar-function)
15978 dir (speedbar-line-directory)
15979 txt (buffer-substring-no-properties (or tp (point-min))
15980 (or np (point-max))))
15981 (save-excursion
15982 (save-restriction
15983 (set-buffer (find-file-noselect
15984 (let ((default-directory dir))
15985 (expand-file-name txt))))
15986 (unless (org-mode-p)
15987 (error "Cannot restrict to non-Org-mode file"))
15988 (org-agenda-set-restriction-lock 'file))))
15989 (t (error "Don't know how to restrict Org-mode's agenda")))
15990 (org-move-overlay org-speedbar-restriction-lock-overlay
15991 (point-at-bol) (point-at-eol))
15992 (setq current-prefix-arg nil)
15993 (org-agenda-maybe-redo)))
15995 (eval-after-load "speedbar"
15996 '(progn
15997 (speedbar-add-supported-extension ".org")
15998 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15999 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16000 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16001 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16002 (add-hook 'speedbar-visiting-tag-hook
16003 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16006 ;;; Fixes and Hacks for problems with other packages
16008 ;; Make flyspell not check words in links, to not mess up our keymap
16009 (defun org-mode-flyspell-verify ()
16010 "Don't let flyspell put overlays at active buttons."
16011 (not (get-text-property (point) 'keymap)))
16013 ;; Make `bookmark-jump' show the jump location if it was hidden.
16014 (eval-after-load "bookmark"
16015 '(if (boundp 'bookmark-after-jump-hook)
16016 ;; We can use the hook
16017 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16018 ;; Hook not available, use advice
16019 (defadvice bookmark-jump (after org-make-visible activate)
16020 "Make the position visible."
16021 (org-bookmark-jump-unhide))))
16023 ;; Make sure saveplace show the location if it was hidden
16024 (eval-after-load "saveplace"
16025 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16026 "Make the position visible."
16027 (org-bookmark-jump-unhide)))
16029 (defun org-bookmark-jump-unhide ()
16030 "Unhide the current position, to show the bookmark location."
16031 (and (org-mode-p)
16032 (or (org-invisible-p)
16033 (save-excursion (goto-char (max (point-min) (1- (point))))
16034 (org-invisible-p)))
16035 (org-show-context 'bookmark-jump)))
16037 ;; Make session.el ignore our circular variable
16038 (eval-after-load "session"
16039 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16041 ;;;; Experimental code
16043 (defun org-closed-in-range ()
16044 "Sparse tree of items closed in a certain time range.
16045 Still experimental, may disappear in the future."
16046 (interactive)
16047 ;; Get the time interval from the user.
16048 (let* ((time1 (time-to-seconds
16049 (org-read-date nil 'to-time nil "Starting date: ")))
16050 (time2 (time-to-seconds
16051 (org-read-date nil 'to-time nil "End date:")))
16052 ;; callback function
16053 (callback (lambda ()
16054 (let ((time
16055 (time-to-seconds
16056 (apply 'encode-time
16057 (org-parse-time-string
16058 (match-string 1))))))
16059 ;; check if time in interval
16060 (and (>= time time1) (<= time time2))))))
16061 ;; make tree, check each match with the callback
16062 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16064 ;;;; Finish up
16066 (provide 'org)
16068 (run-hooks 'org-load-hook)
16070 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16072 ;;; org.el ends here